Compare commits
43 Commits
9828d2b0a1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| b97d79e13a | |||
| a6449a7d70 | |||
| 9b67ace944 | |||
| 3a3e481750 | |||
| 1af2a70406 | |||
| e7abc7c86c | |||
| a8be9db476 | |||
| 2b309b007c | |||
| bd64bb6307 | |||
| 79c7d4f335 | |||
| bc69e52174 | |||
| 39adbf32e2 | |||
| 8fbcbf6899 | |||
| a2a01e24e6 | |||
| 3c8bbe8b4b | |||
| 5222cb2b3c | |||
| 8302250325 | |||
| bc0e04a482 | |||
| c1be111e1a | |||
| 1917bc6513 | |||
| e66bce0d25 | |||
| cddde114fe | |||
| adc92e3460 | |||
| 11758a33e9 | |||
| 9f7031232e | |||
| 1b5bad0baf | |||
| 2821208c65 | |||
| fac2816622 | |||
| b5fa601e93 | |||
| 84c2a2e512 | |||
| ea183854f8 | |||
| 94571f9684 | |||
| 79d802d536 | |||
| 9992a435b2 | |||
| 80b7d4732e | |||
| b3741ca106 | |||
| d8e92386d9 | |||
| 6e365ac434 | |||
| 34fb98e69c | |||
| 9cfb341774 | |||
| 6c608a8779 | |||
| 1f5eed2064 | |||
| aa7f1d8f59 |
@@ -46,3 +46,7 @@ secrets.*
|
|||||||
*~
|
*~
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
_tmp_*.py
|
||||||
|
output/
|
||||||
|
storage/
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(python *)",
|
||||||
|
"Bash(cd *)",
|
||||||
|
"Bash(git diff *)",
|
||||||
|
"Bash(git status)",
|
||||||
|
"Bash(find *)",
|
||||||
|
"Bash(type *)",
|
||||||
|
"Bash(findstr *)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"$version": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
## Назначение
|
||||||
|
|
||||||
|
Этот файл содержит постоянные правила работы AI-агентов с проектом.
|
||||||
|
|
||||||
|
Конкретная задача всегда задаётся отдельным файлом в каталоге `docs/tasks/`.
|
||||||
|
|
||||||
|
Task-файл является контрактом конкретной работы.
|
||||||
|
|
||||||
|
Рабочий процесс проекта:
|
||||||
|
|
||||||
|
Task → Implementation → Implementation Report → Review → Commit
|
||||||
|
|
||||||
|
Агент обязан соблюдать одновременно:
|
||||||
|
1. правила этого AGENTS.md;
|
||||||
|
2. требования конкретного task-файла.
|
||||||
|
|
||||||
|
Если task-файл содержит более конкретное требование, оно имеет приоритет в рамках своей задачи.
|
||||||
|
|
||||||
|
Не расширяй scope задачи самостоятельно.
|
||||||
|
|
||||||
|
## Рабочая среда
|
||||||
|
|
||||||
|
Проект разрабатывается и тестируется на Windows.
|
||||||
|
|
||||||
|
По умолчанию считай текущей средой Windows и работай в текущем проектном каталоге.
|
||||||
|
|
||||||
|
Используй PowerShell и Windows-совместимые команды.
|
||||||
|
|
||||||
|
Не переходи на Linux, WSL, Bash, Docker, SSH или другую среду без прямого требования конкретной задачи.
|
||||||
|
|
||||||
|
Не пытайся решать локальную задачу через Linux или удалённый сервер.
|
||||||
|
|
||||||
|
Не используй без необходимости Linux-специфичные команды:
|
||||||
|
- apt
|
||||||
|
- apt-get
|
||||||
|
- systemctl
|
||||||
|
- service
|
||||||
|
- sudo
|
||||||
|
- grep
|
||||||
|
- sed
|
||||||
|
- awk
|
||||||
|
- chmod
|
||||||
|
- chown
|
||||||
|
|
||||||
|
Не используй Linux-пути, если они не указаны непосредственно в задаче и действительно не относятся к её выполнению:
|
||||||
|
- /app
|
||||||
|
- /home/...
|
||||||
|
- /opt/...
|
||||||
|
- /etc/...
|
||||||
|
|
||||||
|
Не предполагай существование Linux-среды.
|
||||||
|
|
||||||
|
Если команда или тест завершились ошибкой, сначала разбери фактическую ошибку. Не пытайся решить её сменой операционной системы.
|
||||||
|
|
||||||
|
## Стек проекта
|
||||||
|
|
||||||
|
Проект представляет собой локальное web-приложение для учёта объёмов выполненных и оставшихся работ.
|
||||||
|
|
||||||
|
Основной стек:
|
||||||
|
- Python 3.13+
|
||||||
|
- FastAPI
|
||||||
|
- SQLAlchemy 2.x
|
||||||
|
- SQLite
|
||||||
|
- Jinja2
|
||||||
|
- Bootstrap 5
|
||||||
|
- Vanilla JavaScript
|
||||||
|
- openpyxl
|
||||||
|
|
||||||
|
Не вводи React, Vue, SPA, PostgreSQL, Docker или другие крупные технологические изменения, если конкретная задача явно этого не требует.
|
||||||
|
|
||||||
|
## Работа с task-файлами
|
||||||
|
|
||||||
|
Перед началом работы обязательно прочитай назначенный task-файл полностью.
|
||||||
|
|
||||||
|
Task-файл определяет:
|
||||||
|
- цель;
|
||||||
|
- scope;
|
||||||
|
- конкретные требования;
|
||||||
|
- ограничения;
|
||||||
|
- необходимые проверки;
|
||||||
|
- требования к implementation report.
|
||||||
|
|
||||||
|
Task является контрактом.
|
||||||
|
|
||||||
|
Если во время работы обнаружена проблема, не относящаяся к текущей задаче, не исправляй её автоматически.
|
||||||
|
|
||||||
|
Запиши её в разделе Follow-up / Open Questions implementation report.
|
||||||
|
|
||||||
|
Не превращай небольшую задачу в рефакторинг проекта.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Работай только в рамках явно указанного scope.
|
||||||
|
|
||||||
|
Запрещено самостоятельно добавлять:
|
||||||
|
- новые функции;
|
||||||
|
- новые API;
|
||||||
|
- новые модели;
|
||||||
|
- новые зависимости;
|
||||||
|
- архитектурные изменения;
|
||||||
|
- рефакторинг несвязанного кода;
|
||||||
|
- изменения UI, если они не требуются;
|
||||||
|
- изменения бизнес-логики, если они не требуются;
|
||||||
|
- исправления технического долга, не относящегося к задаче.
|
||||||
|
|
||||||
|
Не делай работу по принципу «заодно можно улучшить».
|
||||||
|
|
||||||
|
Если что-то можно было бы улучшить, но этого нет в task-файле, оставь это для отдельной задачи.
|
||||||
|
|
||||||
|
## Перед изменением кода
|
||||||
|
|
||||||
|
Сначала:
|
||||||
|
1. прочитай task-файл;
|
||||||
|
2. прочитай файлы, которые task требует изучить;
|
||||||
|
3. изучи существующую реализацию;
|
||||||
|
4. найди существующие fixtures и helper-функции;
|
||||||
|
5. следуй существующему стилю проекта;
|
||||||
|
6. только после этого вноси изменения.
|
||||||
|
|
||||||
|
Не создавай дублирующую инфраструктуру без необходимости.
|
||||||
|
|
||||||
|
Не переписывай существующий код целиком, если достаточно небольшого изменения.
|
||||||
|
|
||||||
|
## Минимальность изменений
|
||||||
|
|
||||||
|
Делай минимальное изменение, которое полностью выполняет задачу.
|
||||||
|
|
||||||
|
Не переписывай большие файлы ради небольшого изменения.
|
||||||
|
|
||||||
|
Не меняй форматирование несвязанных участков.
|
||||||
|
|
||||||
|
Не меняй рабочую архитектуру без прямого требования.
|
||||||
|
|
||||||
|
После изменений обязательно проверь git diff и убедись, что изменены только необходимые файлы.
|
||||||
|
|
||||||
|
## Production-код
|
||||||
|
|
||||||
|
Если task явно требует только тесты, документацию или другой ограниченный тип изменений, production-код менять нельзя.
|
||||||
|
|
||||||
|
В частности, для test-only задачи не изменяй:
|
||||||
|
- модели;
|
||||||
|
- сервисы;
|
||||||
|
- роутеры;
|
||||||
|
- шаблоны;
|
||||||
|
- бизнес-логику;
|
||||||
|
- миграции;
|
||||||
|
|
||||||
|
если это прямо не разрешено task-файлом.
|
||||||
|
|
||||||
|
Если выполнение задачи невозможно без изменения production-кода, не делай такое изменение молча.
|
||||||
|
|
||||||
|
Зафиксируй проблему в implementation report.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
При добавлении тестов:
|
||||||
|
- используй существующий стиль проекта;
|
||||||
|
- используй существующие fixtures;
|
||||||
|
- используй существующие helper-функции;
|
||||||
|
- не дублируй существующую инфраструктуру без необходимости;
|
||||||
|
- каждый тест должен проверять конкретное поведение;
|
||||||
|
- названия тестов должны быть понятными;
|
||||||
|
- не изменяй существующие тесты без необходимости;
|
||||||
|
- не ослабляй проверки ради прохождения тестов.
|
||||||
|
|
||||||
|
Если task требует запустить pytest, обязательно выполни его.
|
||||||
|
|
||||||
|
Не утверждай, что тесты прошли, если они фактически не запускались.
|
||||||
|
|
||||||
|
Не изменяй production-код только для того, чтобы тесты начали проходить, если это выходит за scope текущей задачи.
|
||||||
|
|
||||||
|
## Бизнес-правила проекта
|
||||||
|
|
||||||
|
Не смешивай следующие понятия:
|
||||||
|
1. плановое/согласованное количество;
|
||||||
|
2. фактически выполненное количество;
|
||||||
|
3. количество, закрытое КС-2;
|
||||||
|
4. оплаченная сумма.
|
||||||
|
|
||||||
|
Daily Reports являются источником факта выполнения.
|
||||||
|
|
||||||
|
План не является жёстким ограничением фактического выполнения.
|
||||||
|
|
||||||
|
Если план = 10, а факт = 15, то факт 15 должен быть допустимым.
|
||||||
|
|
||||||
|
Превышение плана может приводить к предупреждению, но само по себе не должно блокировать регистрацию фактического выполнения.
|
||||||
|
|
||||||
|
## Дополнительные соглашения
|
||||||
|
|
||||||
|
Дополнительные соглашения изменяют согласованный план.
|
||||||
|
|
||||||
|
Они не являются фактом выполнения.
|
||||||
|
|
||||||
|
Факт выполнения фиксируется через Daily Reports.
|
||||||
|
|
||||||
|
Не смешивай:
|
||||||
|
- базовый план;
|
||||||
|
- утверждённые дополнительные соглашения;
|
||||||
|
- фактическое выполнение;
|
||||||
|
- закрытые КС-2;
|
||||||
|
- оплаты.
|
||||||
|
|
||||||
|
## KS-2
|
||||||
|
|
||||||
|
КС-2 является документом выборочного закрытия накопленного фактического выполнения.
|
||||||
|
|
||||||
|
Основные правила:
|
||||||
|
- Daily Reports являются первичным источником факта;
|
||||||
|
- КС-2 не изменяет Daily Reports;
|
||||||
|
- один DailyReportItem может быть частично закрыт несколькими КС-2;
|
||||||
|
- один KS2Item может иметь несколько источников DailyReportItem;
|
||||||
|
- доступный объём = фактически выполнено - уже закрыто;
|
||||||
|
- нельзя закрыть больше доступного фактического объёма;
|
||||||
|
- частичное закрытие разрешено;
|
||||||
|
- превышение планового количества само по себе не является ошибкой.
|
||||||
|
|
||||||
|
Не изменяй эти правила без прямого требования.
|
||||||
|
|
||||||
|
## KS-3 и платежи
|
||||||
|
|
||||||
|
КС-3 является финансовым сводным документом на основании одного или нескольких КС-2.
|
||||||
|
|
||||||
|
Платежи являются отдельными финансовыми фактами.
|
||||||
|
|
||||||
|
Не добавляй логику КС-3 или платежей в задачи по КС-2, если это явно не указано в task-файле.
|
||||||
|
|
||||||
|
## Целостность данных
|
||||||
|
|
||||||
|
Для операций с количествами и документами:
|
||||||
|
- сохраняй транзакционность;
|
||||||
|
- не допускай частичного сохранения некорректной операции;
|
||||||
|
- серверная валидация обязательна;
|
||||||
|
- UI-валидация не заменяет серверную;
|
||||||
|
- для денежных значений используй Decimal там, где это предусмотрено существующей архитектурой;
|
||||||
|
- не вводи float для денежных расчётов.
|
||||||
|
|
||||||
|
Не ослабляй существующие проверки ради прохождения тестов.
|
||||||
|
|
||||||
|
## Пути и файлы
|
||||||
|
|
||||||
|
Работай относительно текущего каталога проекта.
|
||||||
|
|
||||||
|
Не придумывай пути.
|
||||||
|
|
||||||
|
Перед использованием файла убедись, что он действительно существует.
|
||||||
|
|
||||||
|
Не переноси логику или предположения из другого проекта, другой машины или другой операционной системы.
|
||||||
|
|
||||||
|
## Команды
|
||||||
|
|
||||||
|
Предпочитай простые и воспроизводимые команды.
|
||||||
|
|
||||||
|
Для Windows/PowerShell допустимы, например:
|
||||||
|
- Get-ChildItem
|
||||||
|
- Get-Content
|
||||||
|
- Select-String
|
||||||
|
- pytest -q
|
||||||
|
- git status
|
||||||
|
- git diff
|
||||||
|
- git diff --check
|
||||||
|
|
||||||
|
Используй Python напрямую, когда это уместно.
|
||||||
|
|
||||||
|
Не заменяй простую команду сложным shell-пайплайном.
|
||||||
|
|
||||||
|
## Ошибки
|
||||||
|
|
||||||
|
Если команда или тест завершились ошибкой:
|
||||||
|
1. прочитай фактическое сообщение об ошибке;
|
||||||
|
2. определи причину;
|
||||||
|
3. определи, относится ли ошибка к текущей задаче;
|
||||||
|
4. если относится — исправь её в рамках scope;
|
||||||
|
5. если не относится — зафиксируй её в implementation report.
|
||||||
|
|
||||||
|
Не скрывай ошибки.
|
||||||
|
|
||||||
|
Не помечай задачу как выполненную, если обязательные проверки не пройдены.
|
||||||
|
|
||||||
|
Не меняй среду выполнения только потому, что команда завершилась ошибкой.
|
||||||
|
|
||||||
|
## Implementation Report
|
||||||
|
|
||||||
|
После выполнения задачи обязательно создай implementation report в каталоге `docs/implementation/`.
|
||||||
|
|
||||||
|
Имя отчёта должно соответствовать номеру task.
|
||||||
|
|
||||||
|
Например, для task:
|
||||||
|
`docs/tasks/001-ks2-regression-tests.md`
|
||||||
|
|
||||||
|
отчёт:
|
||||||
|
`docs/implementation/001-ks2-regression-tests.md`
|
||||||
|
|
||||||
|
Отчёт должен содержать:
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
Один из статусов:
|
||||||
|
- DONE
|
||||||
|
- PARTIAL
|
||||||
|
- BLOCKED
|
||||||
|
|
||||||
|
### What was done
|
||||||
|
|
||||||
|
Кратко описать выполненную работу.
|
||||||
|
|
||||||
|
### Changed files
|
||||||
|
|
||||||
|
Перечислить изменённые и созданные файлы.
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
Указать:
|
||||||
|
- какие тесты добавлены или изменены;
|
||||||
|
- какие проверки выполнены;
|
||||||
|
- результат pytest -q, если он требуется task-файлом;
|
||||||
|
- результат git diff --check.
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
Указать отклонения от task-файла.
|
||||||
|
|
||||||
|
Если отклонений нет:
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Follow-up / Open Questions
|
||||||
|
|
||||||
|
Указать обнаруженные проблемы, идеи и технический долг, которые не относятся к текущему scope.
|
||||||
|
|
||||||
|
Не реализовывать эти пункты без отдельной задачи.
|
||||||
|
|
||||||
|
## Git
|
||||||
|
|
||||||
|
Не выполняй commit без прямого указания пользователя или task-файла.
|
||||||
|
|
||||||
|
Не выполняй push без прямого указания пользователя или task-файла.
|
||||||
|
|
||||||
|
Стандартный процесс:
|
||||||
|
|
||||||
|
Implementation → Implementation Report → Review → Commit
|
||||||
|
|
||||||
|
Даже если задача полностью выполнена, это не означает автоматическое разрешение на commit или push.
|
||||||
|
|
||||||
|
## Финальная проверка
|
||||||
|
|
||||||
|
Перед завершением задачи:
|
||||||
|
1. проверь git status;
|
||||||
|
2. проверь git diff;
|
||||||
|
3. убедись, что нет неожиданных изменений;
|
||||||
|
4. выполни обязательные тесты;
|
||||||
|
5. выполни git diff --check;
|
||||||
|
6. создай implementation report;
|
||||||
|
7. не делай commit/push без разрешения.
|
||||||
|
|
||||||
|
## Ответ после выполнения
|
||||||
|
|
||||||
|
В финальном сообщении кратко укажи:
|
||||||
|
- Status;
|
||||||
|
- что сделано;
|
||||||
|
- изменённые файлы;
|
||||||
|
- результаты тестов;
|
||||||
|
- результат git diff --check;
|
||||||
|
- Deviations;
|
||||||
|
- Follow-up / Open Questions.
|
||||||
|
|
||||||
|
Подробности должны находиться в implementation report.
|
||||||
|
|
||||||
|
Не утверждай то, чего фактически не проверял.
|
||||||
|
|
||||||
|
## Приоритет правил
|
||||||
|
|
||||||
|
При конфликте используй следующий порядок:
|
||||||
|
1. прямое указание пользователя;
|
||||||
|
2. конкретный task-файл;
|
||||||
|
3. этот AGENTS.md;
|
||||||
|
4. существующие соглашения проекта;
|
||||||
|
5. собственные предпочтения агента.
|
||||||
|
|
||||||
|
Собственные предпочтения агента не являются основанием для расширения scope, изменения архитектуры или смены среды выполнения.
|
||||||
|
|
||||||
|
## Главная цель
|
||||||
|
|
||||||
|
Точно выполнить поставленную задачу, минимально изменить проект, проверить результат и оставить понятный implementation report.
|
||||||
|
|
||||||
|
Не нужно самостоятельно проектировать проект заново.
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
# Work Volume Tracker — Product Roadmap
|
||||||
|
|
||||||
|
## Назначение
|
||||||
|
|
||||||
|
Документ фиксирует текущее состояние Work Volume Tracker и направления дальнейшего развития. Roadmap не означает, что все будущие функции должны быть реализованы в ближайшем релизе.
|
||||||
|
|
||||||
|
## Принципы продукта
|
||||||
|
|
||||||
|
- **Local-first:** текущая версия должна полноценно работать локально на ноутбуке без обязательного сервера, Docker или PostgreSQL.
|
||||||
|
- **Простота ежедневной работы:** внесение фактических объёмов после смены должно занимать около 2–5 минут.
|
||||||
|
- **Сохранность данных:** база SQLite, фотографии, ведомости и документы проекта являются пользовательскими данными и не должны теряться при установке, обновлении или переустановке.
|
||||||
|
- **Постепенное развитие:** не усложнять архитектуру ради гипотетических будущих требований.
|
||||||
|
- **Регрессионная безопасность:** новые функции не должны ломать ведомость, ежедневные отчёты, КС-2, КС-3, платежи и экспорт/импорт проекта.
|
||||||
|
|
||||||
|
## Текущее состояние
|
||||||
|
|
||||||
|
Локальная MVP-версия считается готовой к практическому использованию в предстоящей командировке. Основные области:
|
||||||
|
|
||||||
|
- проекты и реквизиты;
|
||||||
|
- импорт ведомости работ из Excel;
|
||||||
|
- системы, разделы и позиции работ;
|
||||||
|
- дополнительные соглашения и изменения согласованного плана;
|
||||||
|
- ежедневные отчёты с фактическими объёмами и фотографиями;
|
||||||
|
- сравнение плана, факта и остатка;
|
||||||
|
- формирование КС-2 и КС-3;
|
||||||
|
- учёт платежей и распределения оплат;
|
||||||
|
- экспорт и импорт проекта;
|
||||||
|
- сокрытие финансовых сумм по умолчанию.
|
||||||
|
|
||||||
|
Ближайшая цель — подготовить надёжную установку на рабочем Windows-ноутбуке. До командировки не расширять продукт крупными новыми функциями без необходимости.
|
||||||
|
|
||||||
|
## Этап 0 — подготовка к командировке
|
||||||
|
|
||||||
|
**Приоритет: сейчас.**
|
||||||
|
|
||||||
|
- Установка и запуск без ручной настройки Python-окружения пользователем.
|
||||||
|
- Понятные действия для запуска и остановки приложения.
|
||||||
|
- Открытие локального интерфейса в браузере.
|
||||||
|
- Хранение базы и пользовательских файлов вне каталога приложения.
|
||||||
|
- Сохранение данных при обновлении и переустановке.
|
||||||
|
- Документированное резервное копирование и восстановление базы и файлов.
|
||||||
|
- Понятная диагностика ошибок запуска и миграций.
|
||||||
|
- Проверка повторного запуска после перезагрузки Windows.
|
||||||
|
- Проверка на целевом ноутбуке или чистой Windows-системе.
|
||||||
|
|
||||||
|
**Критерий готовности:** приложение запускается по инструкции; данные сохраняются после остановки и повторного запуска; резервную копию можно создать и восстановить по инструкции.
|
||||||
|
|
||||||
|
## Этап 1 — стабилизация
|
||||||
|
|
||||||
|
**Приоритет: после подготовки к командировке.**
|
||||||
|
|
||||||
|
- Проверить сквозной процесс: ведомость → Daily Report → КС-2 → КС-3 → платежи.
|
||||||
|
- Проверить экспорт/импорт проекта, включая фотографии и сформированные документы.
|
||||||
|
- Исправлять подтверждённые дефекты отдельными задачами.
|
||||||
|
- Сделать тесты независимыми от реальной пользовательской БД и фиксированных идентификаторов.
|
||||||
|
- Поддерживать инструкции по эксплуатации и резервному копированию.
|
||||||
|
|
||||||
|
## Этап 2 — календарное планирование и диаграмма Ганта
|
||||||
|
|
||||||
|
**Статус: будущее развитие, не входит в текущую MVP.**
|
||||||
|
|
||||||
|
Предполагаемый первый вариант:
|
||||||
|
|
||||||
|
- плановые даты начала и окончания работ;
|
||||||
|
- график по проекту с группировкой по системам и разделам;
|
||||||
|
- отображение фактического прогресса на основании Daily Reports;
|
||||||
|
- наглядное отображение просрочек и отклонений от плана;
|
||||||
|
- масштаб временной шкалы по дням, неделям и месяцам;
|
||||||
|
- отметка текущей даты.
|
||||||
|
|
||||||
|
До реализации требуется решить, на каком уровне задаются сроки: система, раздел или отдельная позиция; как рассчитывается прогресс; как отображаются работы без календарных дат.
|
||||||
|
|
||||||
|
Возможное последующее развитие: зависимости между работами, базовый утверждённый график, история переноса сроков и критический путь — только если это оправдано практическими сценариями.
|
||||||
|
|
||||||
|
## Этап 3 — управленческая аналитика
|
||||||
|
|
||||||
|
**Статус: будущее развитие.**
|
||||||
|
|
||||||
|
- плановые и фактические объёмы и стоимость;
|
||||||
|
- отклонения по срокам и объёмам;
|
||||||
|
- состояние закрытия КС-2 и КС-3;
|
||||||
|
- полученные, распределённые и нераспределённые платежи;
|
||||||
|
- сводная картина по проекту и системам;
|
||||||
|
- в перспективе — аналитика по нескольким проектам.
|
||||||
|
|
||||||
|
Показатели должны чётко различать план, факт, закрытые объёмы и оплаты.
|
||||||
|
|
||||||
|
## Этап 4 — серверная многопользовательская версия
|
||||||
|
|
||||||
|
**Статус: отдельный будущий этап; не требуется локальной версии.**
|
||||||
|
|
||||||
|
Возможные направления:
|
||||||
|
|
||||||
|
- серверное размещение;
|
||||||
|
- несколько пользователей и одновременная работа;
|
||||||
|
- аутентификация и разграничение прав;
|
||||||
|
- журналирование значимых действий;
|
||||||
|
- централизованное резервное копирование и восстановление;
|
||||||
|
- перенос или синхронизация данных локальных экземпляров;
|
||||||
|
- управление несколькими проектами и организациями.
|
||||||
|
|
||||||
|
Перед началом требуется отдельное архитектурное решение. Не внедрять серверную инфраструктуру в локальную версию только ради потенциальной будущей продажи.
|
||||||
|
|
||||||
|
## Этап 5 — коммерциализация
|
||||||
|
|
||||||
|
**Статус: исследовательский этап после подтверждения практической ценности.**
|
||||||
|
|
||||||
|
- определить целевую аудиторию и типовые сценарии;
|
||||||
|
- предусмотреть настраиваемые реквизиты организации и оформление документов;
|
||||||
|
- обеспечить безопасные обновления и совместимость данных;
|
||||||
|
- улучшить диагностику ошибок и пользовательскую документацию;
|
||||||
|
- определить модель распространения, лицензирования и поддержки;
|
||||||
|
- проверить требования к безопасности и защите данных.
|
||||||
|
|
||||||
|
Наличие установщика само по себе не означает готовность коммерческой версии: нужны отдельные критерии поддержки, обновления, восстановления и защиты данных.
|
||||||
|
|
||||||
|
## Что не входит в ближайший этап
|
||||||
|
|
||||||
|
- полноценная диаграмма Ганта;
|
||||||
|
- сервер, PostgreSQL и многопользовательский режим;
|
||||||
|
- сложная система ролей и прав;
|
||||||
|
- переписывание приложения или замена текущего стека;
|
||||||
|
- масштабная переработка интерфейса без конкретной эксплуатационной необходимости.
|
||||||
|
|
||||||
|
## Управление roadmap
|
||||||
|
|
||||||
|
Каждый этап оформляется отдельной задачей с критериями приёмки. Не смешивать продуктовые улучшения с подготовкой установщика. Перед изменением файлов проверять состояние Git и сохранять посторонние незакоммиченные задачи. Коммиты и push выполнять только по явному разрешению пользователя.
|
||||||
|
|
||||||
|
Связанные документы:
|
||||||
|
|
||||||
|
- `docs/tasks/REQ-windows-installer.md` — задание на Windows-установщик и первый проход анализа.
|
||||||
+235
@@ -0,0 +1,235 @@
|
|||||||
|
"""Application configuration: code vs persistent user data.
|
||||||
|
|
||||||
|
Layout (portable-friendly)::
|
||||||
|
|
||||||
|
<project_root>/app/ application code, templates, template_docs
|
||||||
|
<project_root>/data/ persistent user data (never shipped in the app package)
|
||||||
|
work_tracker.db SQLite database
|
||||||
|
uploads/ Excel imports and project-import archives
|
||||||
|
storage/ document artifacts and Daily Report photos
|
||||||
|
<project_root>/backups/ pre-migration and manual backup archives
|
||||||
|
|
||||||
|
Overrides (environment):
|
||||||
|
|
||||||
|
WORK_TRACKER_DATA_DIR data root (default <project_root>/data)
|
||||||
|
DOCUMENT_STORAGE_ROOT storage root (default <data_root>/storage)
|
||||||
|
WORK_TRACKER_BACKUPS_DIR backups root (default <project_root>/backups)
|
||||||
|
|
||||||
|
Legacy locations (pre-portable tree) are copied into the new layout once by
|
||||||
|
:meth:`migrate_legacy_data`. Sources are never deleted.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
APP_DIR = Path(__file__).resolve().parent
|
||||||
|
PROJECT_ROOT = APP_DIR.parent
|
||||||
|
|
||||||
|
ENV_DATA_DIR = "WORK_TRACKER_DATA_DIR"
|
||||||
|
ENV_DOCUMENT_STORAGE_ROOT = "DOCUMENT_STORAGE_ROOT"
|
||||||
|
ENV_BACKUPS_DIR = "WORK_TRACKER_BACKUPS_DIR"
|
||||||
|
|
||||||
|
# Legacy locations kept only as migration sources.
|
||||||
|
_LEGACY_DATABASE_PATH = APP_DIR / "database" / "work_tracker.db"
|
||||||
|
_LEGACY_UPLOADS_DIR = APP_DIR / "uploads"
|
||||||
|
_LEGACY_STORAGE_DIR = PROJECT_ROOT / "storage"
|
||||||
|
|
||||||
|
|
||||||
|
def data_root() -> Path:
|
||||||
|
"""Persistent user-data root (DB, uploads, storage)."""
|
||||||
|
override = os.environ.get(ENV_DATA_DIR, "").strip()
|
||||||
|
if override:
|
||||||
|
return Path(override).expanduser().resolve()
|
||||||
|
return (PROJECT_ROOT / "data").resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def database_path() -> Path:
|
||||||
|
return data_root() / "work_tracker.db"
|
||||||
|
|
||||||
|
|
||||||
|
def uploads_dir() -> Path:
|
||||||
|
return data_root() / "uploads"
|
||||||
|
|
||||||
|
|
||||||
|
def import_uploads_dir() -> Path:
|
||||||
|
return uploads_dir() / "project_import"
|
||||||
|
|
||||||
|
|
||||||
|
def document_storage_root() -> Path:
|
||||||
|
"""Document/photo storage root without creating it.
|
||||||
|
|
||||||
|
DOCUMENT_STORAGE_ROOT keeps its historical meaning and wins over the
|
||||||
|
default data-root layout so existing tests and deployments keep working.
|
||||||
|
"""
|
||||||
|
override = os.environ.get(ENV_DOCUMENT_STORAGE_ROOT, "").strip()
|
||||||
|
if override:
|
||||||
|
return Path(override).expanduser().resolve()
|
||||||
|
return (data_root() / "storage").resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def backups_dir() -> Path:
|
||||||
|
override = os.environ.get(ENV_BACKUPS_DIR, "").strip()
|
||||||
|
if override:
|
||||||
|
return Path(override).expanduser().resolve()
|
||||||
|
return (PROJECT_ROOT / "backups").resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_data_layout() -> None:
|
||||||
|
"""Create the persistent data directories. Idempotent."""
|
||||||
|
data_root().mkdir(parents=True, exist_ok=True)
|
||||||
|
uploads_dir().mkdir(parents=True, exist_ok=True)
|
||||||
|
import_uploads_dir().mkdir(parents=True, exist_ok=True)
|
||||||
|
document_storage_root().mkdir(parents=True, exist_ok=True)
|
||||||
|
backups_dir().mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MigrationReport:
|
||||||
|
"""Outcome of one idempotent legacy → data/ migration pass."""
|
||||||
|
|
||||||
|
db_copied: bool = False
|
||||||
|
uploads_copied: int = 0
|
||||||
|
storage_copied: int = 0
|
||||||
|
backup_path: str | None = None
|
||||||
|
skipped: bool = False
|
||||||
|
notes: list[str] = field(default_factory=list)
|
||||||
|
errors: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ok(self) -> bool:
|
||||||
|
return not self.errors
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_file_safe(src: Path, dest: Path, report: MigrationReport) -> bool:
|
||||||
|
"""Copy one file without overwriting an existing destination."""
|
||||||
|
if dest.exists():
|
||||||
|
report.notes.append(f"skip existing {dest}")
|
||||||
|
return False
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(src, dest)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_tree_safe(src: Path, dest: Path, report: MigrationReport) -> int:
|
||||||
|
"""Copy files from src to dest without overwriting existing files."""
|
||||||
|
if not src.is_dir():
|
||||||
|
return 0
|
||||||
|
copied = 0
|
||||||
|
for path in src.rglob("*"):
|
||||||
|
if path.is_dir():
|
||||||
|
continue
|
||||||
|
rel = path.relative_to(src)
|
||||||
|
target = dest / rel
|
||||||
|
if target.exists():
|
||||||
|
continue
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(path, target)
|
||||||
|
copied += 1
|
||||||
|
return copied
|
||||||
|
|
||||||
|
|
||||||
|
def _sqlite_integrity_ok(db_file: Path) -> tuple[bool, str]:
|
||||||
|
"""Open a SQLite file read-only and run integrity_check."""
|
||||||
|
try:
|
||||||
|
uri = db_file.resolve().as_uri() + "?mode=ro"
|
||||||
|
conn = sqlite3.connect(uri, uri=True)
|
||||||
|
try:
|
||||||
|
row = conn.execute("PRAGMA integrity_check").fetchone()
|
||||||
|
ok = bool(row) and str(row[0]).lower() == "ok"
|
||||||
|
return ok, str(row[0]) if row else "empty result"
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as exc:
|
||||||
|
return False, f"{type(exc).__name__}: {exc}"
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_legacy_sources(legacy_db: Path, report: MigrationReport) -> Path | None:
|
||||||
|
"""Snapshot legacy DB (+WAL/SHM) into backups/ before copying."""
|
||||||
|
if not legacy_db.is_file():
|
||||||
|
return None
|
||||||
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
dest = backups_dir() / f"pre-migrate-{stamp}"
|
||||||
|
dest.mkdir(parents=True, exist_ok=True)
|
||||||
|
for name in (legacy_db.name, legacy_db.name + "-wal", legacy_db.name + "-shm"):
|
||||||
|
src = legacy_db.parent / name
|
||||||
|
if src.is_file():
|
||||||
|
shutil.copy2(src, dest / name)
|
||||||
|
report.backup_path = str(dest)
|
||||||
|
return dest
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_legacy_data() -> MigrationReport:
|
||||||
|
"""Copy legacy DB/uploads/storage into the new data layout. Idempotent.
|
||||||
|
|
||||||
|
Safety rules:
|
||||||
|
- never delete or overwrite sources;
|
||||||
|
- never overwrite an existing file in the destination;
|
||||||
|
- snapshot the legacy database into backups/ before copying;
|
||||||
|
- verify the copied database with PRAGMA integrity_check;
|
||||||
|
- on verification failure the destination copy is removed and the source
|
||||||
|
is left untouched.
|
||||||
|
"""
|
||||||
|
report = MigrationReport()
|
||||||
|
ensure_data_layout()
|
||||||
|
dest_db = database_path()
|
||||||
|
|
||||||
|
# --- database ---
|
||||||
|
if dest_db.is_file():
|
||||||
|
report.skipped = True
|
||||||
|
report.notes.append(f"destination DB already present: {dest_db}")
|
||||||
|
elif _LEGACY_DATABASE_PATH.is_file():
|
||||||
|
_backup_legacy_sources(_LEGACY_DATABASE_PATH, report)
|
||||||
|
sidecars = [
|
||||||
|
_LEGACY_DATABASE_PATH,
|
||||||
|
Path(str(_LEGACY_DATABASE_PATH) + "-wal"),
|
||||||
|
Path(str(_LEGACY_DATABASE_PATH) + "-shm"),
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
for src in sidecars:
|
||||||
|
if src.is_file():
|
||||||
|
target = dest_db.parent / src.name
|
||||||
|
if _copy_file_safe(src, target, report):
|
||||||
|
if src.name == _LEGACY_DATABASE_PATH.name:
|
||||||
|
report.db_copied = True
|
||||||
|
if report.db_copied:
|
||||||
|
ok, detail = _sqlite_integrity_ok(dest_db)
|
||||||
|
if not ok:
|
||||||
|
# Roll back only the copy we just made; source stays.
|
||||||
|
for name in (
|
||||||
|
dest_db.name,
|
||||||
|
dest_db.name + "-wal",
|
||||||
|
dest_db.name + "-shm",
|
||||||
|
):
|
||||||
|
p = dest_db.parent / name
|
||||||
|
if p.is_file():
|
||||||
|
p.unlink()
|
||||||
|
report.db_copied = False
|
||||||
|
report.errors.append(f"integrity_check failed for copied DB: {detail}")
|
||||||
|
else:
|
||||||
|
report.notes.append(f"integrity_check ok: {dest_db}")
|
||||||
|
except OSError as exc:
|
||||||
|
report.errors.append(f"database copy failed: {type(exc).__name__}: {exc}")
|
||||||
|
else:
|
||||||
|
report.notes.append("no legacy database; fresh data directory")
|
||||||
|
|
||||||
|
# --- uploads ---
|
||||||
|
try:
|
||||||
|
report.uploads_copied = _copy_tree_safe(_LEGACY_UPLOADS_DIR, uploads_dir(), report)
|
||||||
|
except OSError as exc:
|
||||||
|
report.errors.append(f"uploads copy failed: {type(exc).__name__}: {exc}")
|
||||||
|
|
||||||
|
# --- storage ---
|
||||||
|
# Prefer the configured storage root as destination; if the user pointed
|
||||||
|
# DOCUMENT_STORAGE_ROOT outside data/, still copy into that root.
|
||||||
|
try:
|
||||||
|
dest_storage = document_storage_root()
|
||||||
|
report.storage_copied = _copy_tree_safe(_LEGACY_STORAGE_DIR, dest_storage, report)
|
||||||
|
except OSError as exc:
|
||||||
|
report.errors.append(f"storage copy failed: {type(exc).__name__}: {exc}")
|
||||||
|
|
||||||
|
return report
|
||||||
@@ -3,8 +3,15 @@ from sqlalchemy.ext.declarative import declarative_base
|
|||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Keep SQLite anchored to the project, independent of the process working directory.
|
from app.config import database_path, ensure_data_layout, migrate_legacy_data
|
||||||
DATABASE_PATH = Path(__file__).resolve().with_name("work_tracker.db")
|
|
||||||
|
# Persistent user database lives under data/ (see app.config). Resolve paths
|
||||||
|
# and migrate any legacy app/database/work_tracker.db before opening SQLite.
|
||||||
|
ensure_data_layout()
|
||||||
|
migrate_legacy_data()
|
||||||
|
|
||||||
|
# Keep SQLite anchored to the configured data root, independent of CWD.
|
||||||
|
DATABASE_PATH: Path = database_path()
|
||||||
DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
# SQLAlchemy accepts an absolute SQLite URL in this form on Windows and Unix.
|
# SQLAlchemy accepts an absolute SQLite URL in this form on Windows and Unix.
|
||||||
|
|||||||
@@ -7,6 +7,14 @@ SCOPE_MIGRATION = "20260925_agreement_scope_boq"
|
|||||||
ITEM_WORK_ITEM_MIGRATION = "20260925_agreement_item_work_item_required"
|
ITEM_WORK_ITEM_MIGRATION = "20260925_agreement_item_work_item_required"
|
||||||
WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq"
|
WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq"
|
||||||
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
|
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
|
||||||
|
KS2_REPORTING_PERIOD_MIGRATION = "20260925_ks2_reporting_period"
|
||||||
|
PAYMENT_STATUS_MIGRATION = "20260926_payment_status"
|
||||||
|
KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique"
|
||||||
|
BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites"
|
||||||
|
DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts"
|
||||||
|
AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled"
|
||||||
|
PROJECT_REQUISITES_MIGRATION = "20260930_project_requisites"
|
||||||
|
DAILY_REPORT_PHOTOS_MIGRATION = "20261015_daily_report_photos"
|
||||||
|
|
||||||
|
|
||||||
def run_migrations(engine):
|
def run_migrations(engine):
|
||||||
@@ -169,6 +177,164 @@ def run_migrations(engine):
|
|||||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_report_date ON daily_reports (report_date)")
|
connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_report_date ON daily_reports (report_date)")
|
||||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
(DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
(DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if KS2_REPORTING_PERIOD_MIGRATION not in applied:
|
||||||
|
ks2_cols = {row[1] for row in connection.execute("PRAGMA table_info(ks2_documents)")}
|
||||||
|
if "reporting_period_from" not in ks2_cols:
|
||||||
|
connection.execute("ALTER TABLE ks2_documents ADD COLUMN reporting_period_from DATE")
|
||||||
|
if "reporting_period_to" not in ks2_cols:
|
||||||
|
connection.execute("ALTER TABLE ks2_documents ADD COLUMN reporting_period_to DATE")
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(KS2_REPORTING_PERIOD_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if PAYMENT_STATUS_MIGRATION not in applied:
|
||||||
|
payment_cols = {row[1] for row in connection.execute("PRAGMA table_info(payments)")}
|
||||||
|
if "status" not in payment_cols:
|
||||||
|
connection.execute("ALTER TABLE payments ADD COLUMN status VARCHAR NOT NULL DEFAULT 'active'")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS ix_payments_status ON payments (status)")
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(PAYMENT_STATUS_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if KS3_NUMBER_UNIQUE_MIGRATION not in applied:
|
||||||
|
duplicates = connection.execute(
|
||||||
|
"SELECT project_id, number FROM ks3_documents GROUP BY project_id, number HAVING COUNT(*) > 1"
|
||||||
|
).fetchall()
|
||||||
|
if duplicates:
|
||||||
|
raise RuntimeError(f"Cannot add unique KS3 numbers: duplicates found {duplicates[:10]}")
|
||||||
|
connection.execute(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS uq_ks3_project_number ON ks3_documents (project_id, number)"
|
||||||
|
)
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(KS3_NUMBER_UNIQUE_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if BOQ_DOCUMENT_REQUISITES_MIGRATION not in applied:
|
||||||
|
doc_cols = {row[1] for row in connection.execute("PRAGMA table_info(boq_documents)")}
|
||||||
|
if "document_number" not in doc_cols:
|
||||||
|
connection.execute("ALTER TABLE boq_documents ADD COLUMN document_number VARCHAR")
|
||||||
|
if "document_date" not in doc_cols:
|
||||||
|
connection.execute("ALTER TABLE boq_documents ADD COLUMN document_date DATE")
|
||||||
|
if "contract" not in doc_cols:
|
||||||
|
connection.execute("ALTER TABLE boq_documents ADD COLUMN contract VARCHAR")
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(BOQ_DOCUMENT_REQUISITES_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if DOCUMENT_ARTIFACTS_MIGRATION not in applied:
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS document_artifacts (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||||
|
document_type VARCHAR NOT NULL,
|
||||||
|
document_id INTEGER NOT NULL,
|
||||||
|
format VARCHAR NOT NULL,
|
||||||
|
storage_key VARCHAR NOT NULL,
|
||||||
|
template_type VARCHAR NOT NULL,
|
||||||
|
template_version INTEGER NOT NULL,
|
||||||
|
content_hash VARCHAR(64) NOT NULL,
|
||||||
|
input_hash VARCHAR(64) NOT NULL,
|
||||||
|
is_current BOOLEAN NOT NULL DEFAULT 1,
|
||||||
|
generated_at DATETIME NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)""")
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_document_artifacts_id ON document_artifacts (id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_document_artifacts_project_id ON document_artifacts (project_id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_document_artifacts_type_doc "
|
||||||
|
"ON document_artifacts (document_type, document_id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_document_artifacts_current "
|
||||||
|
"ON document_artifacts (document_type, document_id, is_current)"
|
||||||
|
)
|
||||||
|
# Partial unique index: one current artifact per (type, id, format).
|
||||||
|
connection.execute(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS uq_document_artifact_current "
|
||||||
|
"ON document_artifacts (document_type, document_id, format) WHERE is_current = 1"
|
||||||
|
)
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(DOCUMENT_ARTIFACTS_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if AGREEMENT_STATUS_CANCELLED_MIGRATION not in applied:
|
||||||
|
tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
||||||
|
if "agreements" in tables:
|
||||||
|
# SQLite CHECK constraints are baked into table definition.
|
||||||
|
# Recreate agreements with the expanded status set.
|
||||||
|
connection.execute("""CREATE TABLE agreements_new (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||||
|
boq_document_id INTEGER REFERENCES boq_documents(id),
|
||||||
|
number VARCHAR NOT NULL,
|
||||||
|
date DATE NOT NULL,
|
||||||
|
title VARCHAR NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
status VARCHAR NOT NULL DEFAULT 'draft',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT ck_agreements_status CHECK (status IN ('draft', 'approved', 'cancelled')),
|
||||||
|
CONSTRAINT uq_agreements_project_number UNIQUE (project_id, number)
|
||||||
|
)""")
|
||||||
|
connection.execute("""INSERT INTO agreements_new
|
||||||
|
(id, project_id, boq_document_id, number, date, title, description, status, created_at, updated_at)
|
||||||
|
SELECT id, project_id, boq_document_id, number, date, title, description, status, created_at, updated_at
|
||||||
|
FROM agreements""")
|
||||||
|
connection.execute("DROP TABLE agreements")
|
||||||
|
connection.execute("ALTER TABLE agreements_new RENAME TO agreements")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_id ON agreements (id)")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_project_id ON agreements (project_id)")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)")
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(AGREEMENT_STATUS_CANCELLED_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if PROJECT_REQUISITES_MIGRATION not in applied:
|
||||||
|
proj_cols = {row[1] for row in connection.execute("PRAGMA table_info(projects)")}
|
||||||
|
if "investor_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN investor_name VARCHAR")
|
||||||
|
if "customer_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN customer_name VARCHAR")
|
||||||
|
if "contractor_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN contractor_name VARCHAR")
|
||||||
|
if "construction_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN construction_name VARCHAR")
|
||||||
|
if "object_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN object_name VARCHAR")
|
||||||
|
if "contract_amount" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN contract_amount NUMERIC(18,2)")
|
||||||
|
if "contractor_signer_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN contractor_signer_name VARCHAR")
|
||||||
|
if "contractor_signer_position" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN contractor_signer_position VARCHAR")
|
||||||
|
if "customer_signer_name" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN customer_signer_name VARCHAR")
|
||||||
|
if "customer_signer_position" not in proj_cols:
|
||||||
|
connection.execute("ALTER TABLE projects ADD COLUMN customer_signer_position VARCHAR")
|
||||||
|
# Normalize legacy customer → customer_name for new domain field
|
||||||
|
connection.execute(
|
||||||
|
"UPDATE projects SET customer_name = customer WHERE customer_name IS NULL AND customer IS NOT NULL"
|
||||||
|
)
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(PROJECT_REQUISITES_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if DAILY_REPORT_PHOTOS_MIGRATION not in applied:
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS daily_report_photos (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||||
|
daily_report_id INTEGER NOT NULL REFERENCES daily_reports(id),
|
||||||
|
storage_key VARCHAR NOT NULL,
|
||||||
|
original_name VARCHAR,
|
||||||
|
content_type VARCHAR(100) NOT NULL,
|
||||||
|
file_size INTEGER NOT NULL,
|
||||||
|
content_hash VARCHAR(64) NOT NULL,
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)""")
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_id ON daily_report_photos (id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_project_id "
|
||||||
|
"ON daily_report_photos (project_id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_report_id "
|
||||||
|
"ON daily_report_photos (daily_report_id)"
|
||||||
|
)
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(DAILY_REPORT_PHOTOS_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
||||||
if violations:
|
if violations:
|
||||||
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Export layer: shared DTOs, helpers, and format-specific renderers."""
|
||||||
|
import re
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_export_name(raw: str) -> str:
|
||||||
|
return re.sub(r'[<>:"/\\|?*]', "_", raw)
|
||||||
|
|
||||||
|
|
||||||
|
def safe_export_filename(prefix: str, number: str, dt, extension: str) -> str:
|
||||||
|
raw = f"{prefix} №{number} от {dt.strftime('%d.%m.%Y')}"
|
||||||
|
return f"{_clean_export_name(raw)}.{extension}"
|
||||||
|
|
||||||
|
|
||||||
|
def safe_export_filename_period(prefix: str, date_from, date_to, extension: str, suffix: str = "") -> str:
|
||||||
|
raw = f"{prefix}_{date_from.strftime('%d.%m.%Y')}-{date_to.strftime('%d.%m.%Y')}"
|
||||||
|
if suffix:
|
||||||
|
raw = f"{raw}_{suffix}"
|
||||||
|
return f"{_clean_export_name(raw)}.{extension}"
|
||||||
|
|
||||||
|
|
||||||
|
def content_disposition(filename: str) -> str:
|
||||||
|
return f"attachment; filename*=UTF-8''{quote(filename)}"
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Shared export formatting helpers for Excel/Word renderers."""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
DATE_FMT = "%d.%m.%Y"
|
||||||
|
MONEY_FMT = "#,##0.00"
|
||||||
|
QTY_FMT = "#,##0.00"
|
||||||
|
MONEY_TEXT = "{:.2f}"
|
||||||
|
QTY_TEXT = "{:.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def format_date(value: date | None) -> str:
|
||||||
|
return value.strftime(DATE_FMT) if value else ""
|
||||||
|
|
||||||
|
|
||||||
|
def format_period(date_from: date | None, date_to: date | None) -> str:
|
||||||
|
if date_from and date_to:
|
||||||
|
return f"{format_date(date_from)} — {format_date(date_to)}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def project_requisite_lines(
|
||||||
|
project_name: str = "",
|
||||||
|
customer: str = "",
|
||||||
|
contract_number: str = "",
|
||||||
|
contract_date: date | None = None,
|
||||||
|
currency: str = "",
|
||||||
|
period_text: str = "",
|
||||||
|
extra: list[tuple[str, str]] | None = None,
|
||||||
|
) -> list[tuple[str, str]]:
|
||||||
|
"""Unified header block: project, customer, contract, currency, period, extras."""
|
||||||
|
lines: list[tuple[str, str]] = []
|
||||||
|
if project_name:
|
||||||
|
lines.append(("Проект:", project_name))
|
||||||
|
if customer:
|
||||||
|
lines.append(("Заказчик:", customer))
|
||||||
|
if contract_number:
|
||||||
|
lines.append(("Договор:", contract_number))
|
||||||
|
if contract_date:
|
||||||
|
lines.append(("Дата договора:", format_date(contract_date)))
|
||||||
|
if currency:
|
||||||
|
lines.append(("Валюта:", currency))
|
||||||
|
if period_text:
|
||||||
|
lines.append(("Период:", period_text))
|
||||||
|
for label, value in extra or []:
|
||||||
|
if value:
|
||||||
|
lines.append((label, value))
|
||||||
|
return lines
|
||||||
@@ -0,0 +1,596 @@
|
|||||||
|
"""Template-based Excel renderer for KS-2 (official form v2).
|
||||||
|
|
||||||
|
DB -> KS2ExportDocument (DTO) -> Official Template v2 -> xlsx bytes
|
||||||
|
|
||||||
|
Column mapping (7 data columns in the template):
|
||||||
|
A = row_number (№ пп)
|
||||||
|
B = source_number (№ поз. Ведомости)
|
||||||
|
C = name (Наименование работ и затрат)
|
||||||
|
E = unit (Ед. изм.)
|
||||||
|
G = quantity (Количество)
|
||||||
|
I = unit_price (Цена за единицу)
|
||||||
|
K = amount (Стоимость)
|
||||||
|
|
||||||
|
Merge policy:
|
||||||
|
- Header merges (rows above the group marker) are never unmerged.
|
||||||
|
- Data-area merges are recreated per output row (group = A:M, item = C:D..K:M).
|
||||||
|
- Merges below the data area are shifted by the inserted row count.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from copy import copy
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
|
from openpyxl.worksheet.cell_range import CellRange
|
||||||
|
|
||||||
|
from app.exporters.common import format_date
|
||||||
|
from app.exporters.ks2_dto import KS2ExportDocument
|
||||||
|
|
||||||
|
TEMPLATE_TYPE = "ks2"
|
||||||
|
TEMPLATE_VERSION = 2
|
||||||
|
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
|
||||||
|
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_v2.xlsx"
|
||||||
|
MANIFEST_FILE = TEMPLATE_DIR / "manifest.json"
|
||||||
|
|
||||||
|
_ROWS_MARKER = "##KS2_ROWS##"
|
||||||
|
_GROUP_MARKER = "##KS2_GROUP##"
|
||||||
|
_TOTALS_MARKER = "##KS2_TOTALS##"
|
||||||
|
_STORNO_MARKER = "##KS2_STORNO##"
|
||||||
|
|
||||||
|
_COL_NUM = 1
|
||||||
|
_COL_SOURCE = 2
|
||||||
|
_COL_NAME = 3
|
||||||
|
_COL_UNIT = 5
|
||||||
|
_COL_QTY = 7
|
||||||
|
_COL_PRICE = 9
|
||||||
|
_COL_AMOUNT = 11
|
||||||
|
MAX_COL = 13
|
||||||
|
|
||||||
|
# Excel numeric format for money/qty: invariant "0.00" renders as 0,00 in ru locale.
|
||||||
|
_NUM_FMT = "0.00"
|
||||||
|
|
||||||
|
# Per-item column pairs from the official template (C:D, E:F, G:H, I:J, K:M)
|
||||||
|
_ITEM_MERGES = ((3, 4), (5, 6), (7, 8), (9, 10), (11, 13))
|
||||||
|
# Group divider spans the full table width
|
||||||
|
_GROUP_MERGE = (1, 13)
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNotFoundError(FileNotFoundError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def load_template_manifest() -> dict:
|
||||||
|
if not MANIFEST_FILE.is_file():
|
||||||
|
raise TemplateNotFoundError(f"Template manifest not found: {MANIFEST_FILE}")
|
||||||
|
with MANIFEST_FILE.open("r", encoding="utf-8") as handle:
|
||||||
|
return json.load(handle)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_excel_number(value) -> int | float:
|
||||||
|
"""Convert Decimal/int/float/None to an Excel numeric (int or float)."""
|
||||||
|
if value is None:
|
||||||
|
return 0
|
||||||
|
if not isinstance(value, Decimal):
|
||||||
|
value = Decimal(str(value))
|
||||||
|
if value == value.to_integral_value():
|
||||||
|
return int(value)
|
||||||
|
return float(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_marker_row(ws, marker: str) -> int:
|
||||||
|
for row in range(1, ws.max_row + 1):
|
||||||
|
cell = ws.cell(row=row, column=1)
|
||||||
|
if cell.value is not None and marker in str(cell.value):
|
||||||
|
return row
|
||||||
|
raise TemplateNotFoundError(f"Marker {marker!r} not found in template")
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_placeholders(ws, mapping: dict[str, str]) -> None:
|
||||||
|
for row in ws.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if not isinstance(cell.value, str):
|
||||||
|
continue
|
||||||
|
text = cell.value
|
||||||
|
for key, value in mapping.items():
|
||||||
|
text = text.replace("{{" + key + "}}", value if value is not None else "")
|
||||||
|
if text != cell.value:
|
||||||
|
cell.value = text
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_row_style(ws, src_row: int, max_col: int) -> list[dict]:
|
||||||
|
captured = []
|
||||||
|
for col in range(1, max_col + 1):
|
||||||
|
src = ws.cell(row=src_row, column=col)
|
||||||
|
captured.append({
|
||||||
|
"font": copy(src.font) if src.has_style else None,
|
||||||
|
"border": copy(src.border) if src.has_style else None,
|
||||||
|
"fill": copy(src.fill) if src.has_style else None,
|
||||||
|
"number_format": src.number_format,
|
||||||
|
"protection": copy(src.protection) if src.has_style else None,
|
||||||
|
"alignment": copy(src.alignment) if src.has_style else None,
|
||||||
|
})
|
||||||
|
return captured
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_row_style(ws, captured: list[dict], dest_row: int, max_col: int) -> None:
|
||||||
|
for col in range(1, max_col + 1):
|
||||||
|
if col - 1 >= len(captured):
|
||||||
|
break
|
||||||
|
st = captured[col - 1]
|
||||||
|
dest = ws.cell(row=dest_row, column=col)
|
||||||
|
if st["font"] is not None:
|
||||||
|
dest.font = copy(st["font"])
|
||||||
|
if st["border"] is not None:
|
||||||
|
dest.border = copy(st["border"])
|
||||||
|
if st["fill"] is not None:
|
||||||
|
dest.fill = copy(st["fill"])
|
||||||
|
dest.number_format = st["number_format"]
|
||||||
|
if st["protection"] is not None:
|
||||||
|
dest.protection = copy(st["protection"])
|
||||||
|
if st["alignment"] is not None:
|
||||||
|
dest.alignment = copy(st["alignment"])
|
||||||
|
|
||||||
|
|
||||||
|
def _row_is_empty(ws, row: int, max_col: int = MAX_COL) -> bool:
|
||||||
|
for col in range(1, max_col + 1):
|
||||||
|
val = ws.cell(row=row, column=col).value
|
||||||
|
if val is not None and str(val).strip() != "":
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _remap_row_after_delete(row: int, deleted: int) -> int | None:
|
||||||
|
"""Map row index after deleting `deleted` (None = that row is gone)."""
|
||||||
|
if row < deleted:
|
||||||
|
return row
|
||||||
|
if row == deleted:
|
||||||
|
return None
|
||||||
|
return row - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot_row_heights(ws) -> dict[int, float]:
|
||||||
|
heights: dict[int, float] = {}
|
||||||
|
for r in range(1, ws.max_row + 1):
|
||||||
|
dim = ws.row_dimensions[r]
|
||||||
|
if dim.height is not None:
|
||||||
|
heights[r] = float(dim.height)
|
||||||
|
return heights
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_row_heights(ws, heights: dict[int, float]) -> None:
|
||||||
|
for r in range(1, ws.max_row + 1):
|
||||||
|
if r in heights:
|
||||||
|
ws.row_dimensions[r].height = heights[r]
|
||||||
|
else:
|
||||||
|
# drop stale dimension left behind by insert/delete
|
||||||
|
if r in ws.row_dimensions:
|
||||||
|
ws.row_dimensions[r].height = None
|
||||||
|
|
||||||
|
|
||||||
|
def _shift_heights_after_insert(heights: dict[int, float], at: int, amount: int) -> dict[int, float]:
|
||||||
|
"""openpyxl insert_rows does not move row_dimensions — remap manually."""
|
||||||
|
out: dict[int, float] = {}
|
||||||
|
for r, h in heights.items():
|
||||||
|
out[r + amount if r >= at else r] = h
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_rows_with_merges(ws, rows_to_delete: list[int]) -> None:
|
||||||
|
"""Delete rows bottom-up, remapping merges AND row heights.
|
||||||
|
|
||||||
|
Header merges (entirely above the first deleted row) are left untouched —
|
||||||
|
they must never be unmerged or recreated.
|
||||||
|
"""
|
||||||
|
targets = sorted({r for r in rows_to_delete if r >= 1}, reverse=True)
|
||||||
|
if not targets:
|
||||||
|
return
|
||||||
|
first = min(targets)
|
||||||
|
|
||||||
|
heights = _snapshot_row_heights(ws)
|
||||||
|
merges: list[list[int]] = []
|
||||||
|
for rng in list(ws.merged_cells.ranges):
|
||||||
|
cr = CellRange(str(rng))
|
||||||
|
if cr.max_row < first:
|
||||||
|
continue # header / earlier merges: do not touch
|
||||||
|
merges.append([cr.min_row, cr.min_col, cr.max_row, cr.max_col])
|
||||||
|
ws.unmerge_cells(str(rng))
|
||||||
|
|
||||||
|
for deleted in targets:
|
||||||
|
ws.delete_rows(deleted)
|
||||||
|
|
||||||
|
new_heights: dict[int, float] = {}
|
||||||
|
for r, h in heights.items():
|
||||||
|
nr = _remap_row_after_delete(r, deleted)
|
||||||
|
if nr is not None:
|
||||||
|
new_heights[nr] = h
|
||||||
|
heights = new_heights
|
||||||
|
|
||||||
|
kept: list[list[int]] = []
|
||||||
|
for min_r, min_c, max_r, max_c in merges:
|
||||||
|
new_min = _remap_row_after_delete(min_r, deleted)
|
||||||
|
new_max = _remap_row_after_delete(max_r, deleted)
|
||||||
|
if new_min is None and new_max is None:
|
||||||
|
continue
|
||||||
|
if new_min is None:
|
||||||
|
new_min = new_max
|
||||||
|
if new_max is None:
|
||||||
|
new_max = new_min
|
||||||
|
kept.append([new_min, min_c, new_max, max_c])
|
||||||
|
merges = kept
|
||||||
|
|
||||||
|
_apply_row_heights(ws, heights)
|
||||||
|
for min_r, min_c, max_r, max_c in merges:
|
||||||
|
if min_r < 1 or max_r < min_r:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ws.merge_cells(
|
||||||
|
start_row=min_r, start_column=min_c,
|
||||||
|
end_row=max_r, end_column=max_c,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _set_num(cell, value) -> None:
|
||||||
|
"""Write a numeric Excel value with 0.00 format (no currency)."""
|
||||||
|
cell.value = _to_excel_number(value)
|
||||||
|
cell.number_format = _NUM_FMT
|
||||||
|
|
||||||
|
|
||||||
|
# Signature block: values sit on the row above the labels row.
|
||||||
|
# Column E is the position/value column in the signature block.
|
||||||
|
_SIG_COL_POS = 5
|
||||||
|
_SIG_COL_NAME = 10 # column J (name / расшифровка)
|
||||||
|
|
||||||
|
|
||||||
|
def _write_into_merge_top_left(ws, row: int, col: int, value: str) -> None:
|
||||||
|
"""Write to the top-left cell of a merge covering (row, col) if any; else the cell."""
|
||||||
|
target_row, target_col = row, col
|
||||||
|
for rng in ws.merged_cells.ranges:
|
||||||
|
cr = CellRange(str(rng))
|
||||||
|
if cr.min_row <= row <= cr.max_row and cr.min_col <= col <= cr.max_col:
|
||||||
|
target_row, target_col = cr.min_row, cr.min_col
|
||||||
|
break
|
||||||
|
ws.cell(row=target_row, column=target_col).value = value
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_signature_placeholders(ws) -> None:
|
||||||
|
"""Remove leftover {{...}} signer markers so they never render as text."""
|
||||||
|
for row in ws.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if isinstance(cell.value, str) and "{{" in cell.value and "signer" in cell.value:
|
||||||
|
cell.value = None
|
||||||
|
|
||||||
|
|
||||||
|
def _place_signatures(ws, h) -> None:
|
||||||
|
"""Place signer names/positions on the value row (above the signature line).
|
||||||
|
|
||||||
|
Template quirk: ks2_ru_v2 has {{customer_signer_position}} on the label row
|
||||||
|
(next to «(подпись)») and leaves the intended value-row merge empty.
|
||||||
|
Renderer must write values strictly into the form's value-row cells and
|
||||||
|
restore the «(должность)» label below the line — without touching header
|
||||||
|
merges and without editing the template file.
|
||||||
|
"""
|
||||||
|
_clear_signature_placeholders(ws)
|
||||||
|
|
||||||
|
pairs = (
|
||||||
|
("Сдал", h.contractor_signer_position or "", h.contractor_signer_name or ""),
|
||||||
|
("Принял", h.customer_signer_position or "", h.customer_signer_name or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
for row in range(1, ws.max_row + 1):
|
||||||
|
c3 = ws.cell(row=row, column=3).value
|
||||||
|
if c3 is None:
|
||||||
|
continue
|
||||||
|
text = str(c3).strip()
|
||||||
|
for label, position, name in pairs:
|
||||||
|
if text != label:
|
||||||
|
continue
|
||||||
|
# Value row is the «Сдал»/«Принял» row itself: position in E:I, name in J:K.
|
||||||
|
_write_into_merge_top_left(ws, row, _SIG_COL_POS, position)
|
||||||
|
_write_into_merge_top_left(ws, row, _SIG_COL_NAME, name)
|
||||||
|
# Label row below the signature line must show «(должность)» under the position.
|
||||||
|
label_row = row + 1
|
||||||
|
if label_row <= ws.max_row:
|
||||||
|
cell = ws.cell(row=label_row, column=_SIG_COL_POS)
|
||||||
|
val = "" if cell.value is None else str(cell.value).strip()
|
||||||
|
if "(должность)" not in val:
|
||||||
|
cell.value = "(должность)"
|
||||||
|
|
||||||
|
|
||||||
|
def _polish_header_doc_block(ws) -> None:
|
||||||
|
"""Polish «Номер документа / Дата составления / Отчётный период» block.
|
||||||
|
|
||||||
|
Values are already written into the template-designated cells (G22..J22)
|
||||||
|
by placeholder substitution. Only alignment is adjusted — merged cells
|
||||||
|
are never created, destroyed or re-created here.
|
||||||
|
|
||||||
|
Labels use shrink-to-fit so «Дата составления» does not break mid-word
|
||||||
|
in the narrow template column.
|
||||||
|
"""
|
||||||
|
for row in range(1, min(ws.max_row, 28) + 1):
|
||||||
|
val = ws.cell(row=row, column=7).value # column G
|
||||||
|
if val is not None and "Номер документа" in str(val):
|
||||||
|
label_row = row
|
||||||
|
value_row = row + 2 # labels occupy 2 rows (G20:G21 / H20:H21); values on next
|
||||||
|
for col in range(7, 11): # G..J
|
||||||
|
label = ws.cell(row=label_row, column=col)
|
||||||
|
if label.value is not None:
|
||||||
|
text = str(label.value).replace("\n", " ")
|
||||||
|
label.value = text
|
||||||
|
words = text.split()
|
||||||
|
longest = max((len(w) for w in words), default=0)
|
||||||
|
if longest >= 10:
|
||||||
|
# Narrow column: Excel would split the word mid-syllable.
|
||||||
|
# shrink_to_fit keeps one clean line without touching the template.
|
||||||
|
label.alignment = Alignment(
|
||||||
|
horizontal="center", vertical="center",
|
||||||
|
wrap_text=False, shrink_to_fit=True,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
label.alignment = Alignment(
|
||||||
|
horizontal="center", vertical="center",
|
||||||
|
wrap_text=True, shrink_to_fit=False,
|
||||||
|
)
|
||||||
|
# «с» / «по» sub-labels sit on the second label row
|
||||||
|
sub = ws.cell(row=label_row + 1, column=col)
|
||||||
|
if sub.value is not None:
|
||||||
|
sub.alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
cell = ws.cell(row=value_row, column=col)
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=False)
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_table_alignment(ws, row: int, *, numeric_cols: tuple[int, ...]) -> None:
|
||||||
|
"""Neat cell padding: text = vcenter+wrap+small left indent; numbers = vcenter, no indent."""
|
||||||
|
for col in range(1, MAX_COL + 1):
|
||||||
|
cell = ws.cell(row=row, column=col)
|
||||||
|
if col in numeric_cols:
|
||||||
|
# numbers: vertical center, no indent (centered so they don't stick to borders)
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=False, indent=0)
|
||||||
|
else:
|
||||||
|
cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True, indent=1)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_storno(ws, storno_row: int, cancelled: bool) -> None:
|
||||||
|
"""Fill ##KS2_STORNO## without breaking existing merges.
|
||||||
|
|
||||||
|
For cancelled: full-width merge A:M + bold red centered label.
|
||||||
|
The merge is only created when the row is not already inside another merge,
|
||||||
|
so surrounding template merges stay intact.
|
||||||
|
"""
|
||||||
|
if cancelled:
|
||||||
|
already = False
|
||||||
|
for rng in ws.merged_cells.ranges:
|
||||||
|
cr = CellRange(str(rng))
|
||||||
|
if cr.min_row <= storno_row <= cr.max_row and cr.max_col >= MAX_COL:
|
||||||
|
already = True
|
||||||
|
storno_merge = str(rng)
|
||||||
|
break
|
||||||
|
if not already:
|
||||||
|
# Row must be free of other merges; if occupied, write into the
|
||||||
|
# top-left of the existing range instead of destroying it.
|
||||||
|
occupied = None
|
||||||
|
for rng in ws.merged_cells.ranges:
|
||||||
|
cr = CellRange(str(rng))
|
||||||
|
if cr.min_row <= storno_row <= cr.max_row:
|
||||||
|
occupied = cr
|
||||||
|
break
|
||||||
|
if occupied is not None:
|
||||||
|
ws.cell(row=occupied.min_row, column=occupied.min_col).value = "СТОРНИРОВАН"
|
||||||
|
ws.cell(row=occupied.min_row, column=occupied.min_col).font = Font(
|
||||||
|
name="Arial", size=12, bold=True, color="FF0000"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
ws.merge_cells(
|
||||||
|
start_row=storno_row, start_column=1,
|
||||||
|
end_row=storno_row, end_column=MAX_COL,
|
||||||
|
)
|
||||||
|
cell = ws.cell(row=storno_row, column=1)
|
||||||
|
cell.value = "СТОРНИРОВАН"
|
||||||
|
cell.font = Font(name="Arial", size=12, bold=True, color="FF0000")
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
dim = ws.row_dimensions[storno_row]
|
||||||
|
if not dim.height or dim.height < 18:
|
||||||
|
dim.height = 18
|
||||||
|
else:
|
||||||
|
# Clear marker only; leave merges untouched.
|
||||||
|
cell = ws.cell(row=storno_row, column=1)
|
||||||
|
cell.value = None
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
|
||||||
|
if not TEMPLATE_FILE.is_file():
|
||||||
|
raise TemplateNotFoundError(f"KS-2 template not found: {TEMPLATE_FILE}.")
|
||||||
|
|
||||||
|
wb = load_workbook(TEMPLATE_FILE)
|
||||||
|
ws = wb["КС-2"] if "КС-2" in wb.sheetnames else wb.active
|
||||||
|
|
||||||
|
# --- Header placeholders (never unmerge this area) ---
|
||||||
|
h = doc.header
|
||||||
|
mapping = {
|
||||||
|
"customer": h.customer or h.customer_name or "",
|
||||||
|
"contractor_name": h.contractor_name or "",
|
||||||
|
"object_name": h.object_name or "",
|
||||||
|
"contract_number": h.contract_number or "",
|
||||||
|
"contract_date": format_date(h.contract_date),
|
||||||
|
"ks2_number": h.ks2_number or "",
|
||||||
|
"ks2_date": format_date(h.ks2_date),
|
||||||
|
"period_from": format_date(h.period_from),
|
||||||
|
"period_to": format_date(h.period_to),
|
||||||
|
"project_name": h.project_name or "",
|
||||||
|
}
|
||||||
|
# Signer fields are placed by _place_signatures into the correct value-row
|
||||||
|
# cells (the template has {{customer_signer_position}} on the wrong row).
|
||||||
|
_replace_placeholders(ws, mapping)
|
||||||
|
_polish_header_doc_block(ws)
|
||||||
|
|
||||||
|
# --- STORNO (header zone; must not destroy merges) ---
|
||||||
|
storno_row = _find_marker_row(ws, _STORNO_MARKER)
|
||||||
|
_apply_storno(ws, storno_row, h.status == "cancelled")
|
||||||
|
|
||||||
|
# --- Locate template rows ---
|
||||||
|
group_marker = _find_marker_row(ws, _GROUP_MARKER)
|
||||||
|
rows_marker = _find_marker_row(ws, _ROWS_MARKER)
|
||||||
|
totals_marker = _find_marker_row(ws, _TOTALS_MARKER)
|
||||||
|
|
||||||
|
items = list(doc.items)
|
||||||
|
sequence: list[tuple[str, object]] = []
|
||||||
|
for item in items:
|
||||||
|
gh = getattr(item, "group_header", None)
|
||||||
|
if gh:
|
||||||
|
sequence.append(("group", gh))
|
||||||
|
sequence.append(("item", item))
|
||||||
|
if not sequence:
|
||||||
|
sequence = [("item", None)]
|
||||||
|
|
||||||
|
total_rows = len(sequence)
|
||||||
|
# Template data block occupies group_marker..rows_marker (2 rows)
|
||||||
|
template_data_rows = rows_marker - group_marker + 1
|
||||||
|
extra = total_rows - template_data_rows
|
||||||
|
|
||||||
|
# --- Capture styles for group/item rows before any insert ---
|
||||||
|
group_styles = _capture_row_style(ws, group_marker, MAX_COL)
|
||||||
|
item_styles = _capture_row_style(ws, rows_marker, MAX_COL)
|
||||||
|
group_height = ws.row_dimensions[group_marker].height
|
||||||
|
item_height = ws.row_dimensions[rows_marker].height
|
||||||
|
|
||||||
|
# --- Snapshot merges at/after data area; leave header merges alone ---
|
||||||
|
shifting_merges: list[tuple[int, int, int, int]] = []
|
||||||
|
for rng in list(ws.merged_cells.ranges):
|
||||||
|
cr = CellRange(str(rng))
|
||||||
|
if cr.min_row >= group_marker:
|
||||||
|
shifting_merges.append((cr.min_row, cr.min_col, cr.max_row, cr.max_col))
|
||||||
|
ws.unmerge_cells(str(rng))
|
||||||
|
|
||||||
|
row_heights = _snapshot_row_heights(ws)
|
||||||
|
|
||||||
|
# --- Insert extra data rows just below the group template row ---
|
||||||
|
if extra > 0:
|
||||||
|
ws.insert_rows(rows_marker + 1, amount=extra)
|
||||||
|
row_heights = _shift_heights_after_insert(row_heights, rows_marker + 1, extra)
|
||||||
|
_apply_row_heights(ws, row_heights)
|
||||||
|
|
||||||
|
# --- Fill data area ---
|
||||||
|
data_start = group_marker
|
||||||
|
for idx, (kind, payload) in enumerate(sequence):
|
||||||
|
r = data_start + idx
|
||||||
|
if kind == "group":
|
||||||
|
_apply_row_style(ws, group_styles, r, MAX_COL)
|
||||||
|
ws.cell(row=r, column=1).value = str(payload)
|
||||||
|
for col in range(2, MAX_COL + 1):
|
||||||
|
ws.cell(row=r, column=col).value = None
|
||||||
|
ws.merge_cells(
|
||||||
|
start_row=r, start_column=_GROUP_MERGE[0],
|
||||||
|
end_row=r, end_column=_GROUP_MERGE[1],
|
||||||
|
)
|
||||||
|
# group divider text: neat padding like table text
|
||||||
|
ws.cell(row=r, column=1).alignment = Alignment(
|
||||||
|
horizontal="left", vertical="center", wrap_text=True, indent=1,
|
||||||
|
)
|
||||||
|
if group_height:
|
||||||
|
ws.row_dimensions[r].height = group_height
|
||||||
|
else:
|
||||||
|
_apply_row_style(ws, item_styles, r, MAX_COL)
|
||||||
|
if payload is None:
|
||||||
|
for col in (_COL_NUM, _COL_SOURCE, _COL_NAME, _COL_UNIT):
|
||||||
|
ws.cell(row=r, column=col).value = "—"
|
||||||
|
for col in (_COL_QTY, _COL_PRICE, _COL_AMOUNT):
|
||||||
|
_set_num(ws.cell(row=r, column=col), 0)
|
||||||
|
else:
|
||||||
|
item = payload
|
||||||
|
ws.cell(row=r, column=_COL_NUM).value = item.row_number
|
||||||
|
ws.cell(row=r, column=_COL_SOURCE).value = item.source_number or ""
|
||||||
|
ws.cell(row=r, column=_COL_NAME).value = item.name or ""
|
||||||
|
ws.cell(row=r, column=_COL_UNIT).value = item.unit or ""
|
||||||
|
_set_num(ws.cell(row=r, column=_COL_QTY), item.quantity)
|
||||||
|
_set_num(ws.cell(row=r, column=_COL_PRICE), item.unit_price)
|
||||||
|
_set_num(ws.cell(row=r, column=_COL_AMOUNT), item.amount)
|
||||||
|
for c1, c2 in _ITEM_MERGES:
|
||||||
|
ws.merge_cells(start_row=r, start_column=c1, end_row=r, end_column=c2)
|
||||||
|
# neat padding: text vcenter+wrap+left indent; numbers vcenter, no indent
|
||||||
|
_apply_table_alignment(ws, r, numeric_cols=(_COL_NUM, _COL_QTY, _COL_PRICE, _COL_AMOUNT))
|
||||||
|
if item_height:
|
||||||
|
ws.row_dimensions[r].height = item_height
|
||||||
|
|
||||||
|
data_end = data_start + total_rows - 1
|
||||||
|
shift = max(extra, 0)
|
||||||
|
|
||||||
|
# --- Restore merges that lived at/after the original data area ---
|
||||||
|
orig_lo, orig_hi = group_marker, rows_marker
|
||||||
|
for (min_r, min_c, max_r, max_c) in shifting_merges:
|
||||||
|
# Recreated per data row — skip originals inside the template data block
|
||||||
|
if orig_lo <= min_r and max_r <= orig_hi:
|
||||||
|
continue
|
||||||
|
if min_r > orig_hi:
|
||||||
|
new_min, new_max = min_r + shift, max_r + shift
|
||||||
|
elif max_r < orig_lo:
|
||||||
|
new_min, new_max = min_r, max_r
|
||||||
|
else:
|
||||||
|
# Spans across the data block — skip (template has none of these)
|
||||||
|
continue
|
||||||
|
if new_min <= new_max:
|
||||||
|
try:
|
||||||
|
ws.merge_cells(
|
||||||
|
start_row=new_min, start_column=min_c,
|
||||||
|
end_row=new_max, end_column=max_c,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# --- Totals ---
|
||||||
|
totals_row = _find_marker_row(ws, _TOTALS_MARKER)
|
||||||
|
ws.cell(row=totals_row, column=1).value = None
|
||||||
|
|
||||||
|
vsyo_row = None
|
||||||
|
for row in range(totals_row, ws.max_row + 1):
|
||||||
|
val = ws.cell(row=row, column=1).value
|
||||||
|
if val and "ВСЕГО" in str(val):
|
||||||
|
vsyo_row = row
|
||||||
|
_set_num(ws.cell(row=row, column=_COL_AMOUNT), doc.total)
|
||||||
|
# Do not stretch the totals row with reserved template height
|
||||||
|
ws.row_dimensions[row].height = 22.5
|
||||||
|
break
|
||||||
|
|
||||||
|
# --- Compact layout: drop unused data slots and empty reserved rows ---
|
||||||
|
# 1) leftover template data rows between last item and the ВСЕГО block
|
||||||
|
delete_rows: list[int] = []
|
||||||
|
block_end = vsyo_row if vsyo_row is not None else totals_row
|
||||||
|
for r in range(data_end + 1, block_end):
|
||||||
|
# Clear leftover markers/placeholders from the template data slot
|
||||||
|
for col in range(1, MAX_COL + 1):
|
||||||
|
ws.cell(row=r, column=col).value = None
|
||||||
|
if _row_is_empty(ws, r):
|
||||||
|
delete_rows.append(r)
|
||||||
|
|
||||||
|
# 2) empty spacer rows between ВСЕГО and the signature block ("Сдал")
|
||||||
|
sdal_row = None
|
||||||
|
for r in range(block_end + 1, ws.max_row + 1):
|
||||||
|
val = ws.cell(row=r, column=3).value # "Сдал" lives in col C
|
||||||
|
if val is not None and "Сдал" in str(val):
|
||||||
|
sdal_row = r
|
||||||
|
break
|
||||||
|
if sdal_row is not None:
|
||||||
|
for r in range(block_end + 1, sdal_row):
|
||||||
|
if _row_is_empty(ws, r):
|
||||||
|
delete_rows.append(r)
|
||||||
|
|
||||||
|
if delete_rows:
|
||||||
|
_delete_rows_with_merges(ws, delete_rows)
|
||||||
|
|
||||||
|
# --- Signatures: values on the value row (above the line), labels below ---
|
||||||
|
_place_signatures(ws, h)
|
||||||
|
|
||||||
|
# --- Print: one page wide, repeat table header on page breaks ---
|
||||||
|
ws.print_area = f"A1:M{ws.max_row}"
|
||||||
|
ws.print_title_rows = f"{group_marker - 2}:{group_marker - 1}" # 27:28
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Excel renderer for KS-3 export using openpyxl."""
|
||||||
|
import io
|
||||||
|
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from openpyxl.styles import Alignment, Border, Font, Side
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
from app.exporters.common import (
|
||||||
|
MONEY_FMT,
|
||||||
|
format_date,
|
||||||
|
format_period,
|
||||||
|
project_requisite_lines,
|
||||||
|
)
|
||||||
|
from app.exporters.ks3_dto import KS3ExportDocument
|
||||||
|
|
||||||
|
THIN = Side(style="thin")
|
||||||
|
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||||
|
HEADER_FONT = Font(bold=True, size=11)
|
||||||
|
TITLE_FONT = Font(bold=True, size=14)
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks3_excel(doc: KS3ExportDocument) -> bytes:
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "КС-3"
|
||||||
|
|
||||||
|
h = doc.header
|
||||||
|
row = 1
|
||||||
|
col_count = 5
|
||||||
|
|
||||||
|
# Title
|
||||||
|
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
|
||||||
|
c = ws.cell(row=row, column=1, value=f"Акт КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
|
||||||
|
c.font = TITLE_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center")
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
if h.status == "cancelled":
|
||||||
|
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
|
||||||
|
c = ws.cell(row=row, column=1, value="СТОРНИРОВАН")
|
||||||
|
c.font = Font(bold=True, size=12, color="C00000")
|
||||||
|
c.alignment = Alignment(horizontal="center")
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
header_lines = project_requisite_lines(
|
||||||
|
project_name=h.project_name,
|
||||||
|
customer=h.customer,
|
||||||
|
contract_number=h.contract_number,
|
||||||
|
contract_date=h.contract_date,
|
||||||
|
currency=h.currency,
|
||||||
|
period_text=format_period(h.period_from, h.period_to),
|
||||||
|
extra=[("Комментарий:", h.comment)],
|
||||||
|
)
|
||||||
|
for label, value in header_lines:
|
||||||
|
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
|
||||||
|
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count)
|
||||||
|
ws.cell(row=row, column=2, value=value)
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
row += 1 # blank row
|
||||||
|
|
||||||
|
# Table header
|
||||||
|
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
|
||||||
|
for col_idx, col_name in enumerate(columns, start=1):
|
||||||
|
c = ws.cell(row=row, column=col_idx, value=col_name)
|
||||||
|
c.font = HEADER_FONT
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
header_row = row
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
# Items
|
||||||
|
for item in doc.items:
|
||||||
|
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
|
||||||
|
ws.cell(row=row, column=2, value=f"№{item.ks2_number}").border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=3, value=format_date(item.ks2_date))
|
||||||
|
c.border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=4, value=format_period(item.period_from, item.period_to))
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(wrap_text=True, vertical="top")
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=5, value=float(item.amount))
|
||||||
|
c.border = BORDER
|
||||||
|
c.number_format = MONEY_FMT
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
# Total row
|
||||||
|
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=4)
|
||||||
|
c = ws.cell(row=row, column=1, value="Итого:")
|
||||||
|
c.font = HEADER_FONT
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(horizontal="right")
|
||||||
|
for col in range(2, 5):
|
||||||
|
ws.cell(row=row, column=col).border = BORDER
|
||||||
|
c = ws.cell(row=row, column=5, value=float(doc.total))
|
||||||
|
c.font = HEADER_FONT
|
||||||
|
c.border = BORDER
|
||||||
|
c.number_format = MONEY_FMT
|
||||||
|
|
||||||
|
# Column widths
|
||||||
|
widths = {1: 5, 2: 12, 3: 14, 4: 24, 5: 16}
|
||||||
|
for col, width in widths.items():
|
||||||
|
ws.column_dimensions[get_column_letter(col)].width = width
|
||||||
|
|
||||||
|
ws.freeze_panes = ws.cell(row=header_row + 1, column=1)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Excel renderer for KS-6a export using openpyxl."""
|
||||||
|
import io
|
||||||
|
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from openpyxl.styles import Alignment, Border, Font, Side
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
from app.exporters.common import (
|
||||||
|
QTY_FMT,
|
||||||
|
format_date,
|
||||||
|
format_period,
|
||||||
|
project_requisite_lines,
|
||||||
|
)
|
||||||
|
from app.exporters.ks6a_dto import KS6aExportDocument
|
||||||
|
|
||||||
|
THIN = Side(style="thin")
|
||||||
|
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||||
|
HEADER_FONT = Font(bold=True, size=11)
|
||||||
|
TITLE_FONT = Font(bold=True, size=14)
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks6a_excel(doc: KS6aExportDocument) -> bytes:
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "КС-6а"
|
||||||
|
|
||||||
|
h = doc.header
|
||||||
|
row = 1
|
||||||
|
col_count = 8
|
||||||
|
|
||||||
|
# Title
|
||||||
|
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
|
||||||
|
c = ws.cell(row=row, column=1, value="КС-6а — Журнал учёта выполненных работ")
|
||||||
|
c.font = TITLE_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center")
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
extra = []
|
||||||
|
if h.contractor:
|
||||||
|
extra.append(("Подрядчик:", h.contractor))
|
||||||
|
if h.system_name:
|
||||||
|
extra.append(("Система:", h.system_name))
|
||||||
|
|
||||||
|
header_lines = project_requisite_lines(
|
||||||
|
project_name=h.project_name,
|
||||||
|
customer=h.customer,
|
||||||
|
contract_number=h.contract_number,
|
||||||
|
contract_date=h.contract_date,
|
||||||
|
currency=h.currency,
|
||||||
|
period_text=format_period(h.period_from, h.period_to),
|
||||||
|
extra=extra,
|
||||||
|
)
|
||||||
|
for label, value in header_lines:
|
||||||
|
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
|
||||||
|
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count)
|
||||||
|
ws.cell(row=row, column=2, value=value)
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
row += 1 # blank row
|
||||||
|
|
||||||
|
# Table header
|
||||||
|
columns = [
|
||||||
|
"№", "Дата", "Система", "Раздел", "№ позиции",
|
||||||
|
"Наименование работ", "Ед. изм.", "Количество",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(columns, start=1):
|
||||||
|
c = ws.cell(row=row, column=col_idx, value=col_name)
|
||||||
|
c.font = HEADER_FONT
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
header_row = row
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
# Items — one row per DailyReportItem
|
||||||
|
for item in doc.items:
|
||||||
|
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=2, value=format_date(item.report_date))
|
||||||
|
c.border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=3, value=item.system_name)
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(wrap_text=True, vertical="top")
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=4, value=item.section_name)
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(wrap_text=True, vertical="top")
|
||||||
|
|
||||||
|
ws.cell(row=row, column=5, value=item.source_number).border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=6, value=item.name)
|
||||||
|
c.border = BORDER
|
||||||
|
c.alignment = Alignment(wrap_text=True, vertical="top")
|
||||||
|
|
||||||
|
ws.cell(row=row, column=7, value=item.unit).border = BORDER
|
||||||
|
|
||||||
|
c = ws.cell(row=row, column=8, value=float(item.quantity))
|
||||||
|
c.border = BORDER
|
||||||
|
c.number_format = QTY_FMT
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
# Column widths
|
||||||
|
widths = {1: 5, 2: 12, 3: 16, 4: 16, 5: 12, 6: 40, 7: 10, 8: 12}
|
||||||
|
for col, width in widths.items():
|
||||||
|
ws.column_dimensions[get_column_letter(col)].width = width
|
||||||
|
|
||||||
|
ws.freeze_panes = ws.cell(row=header_row + 1, column=1)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""Shared document DTOs for export renderers. One source of truth for Excel and Word."""
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS2ExportItem:
|
||||||
|
row_number: int
|
||||||
|
source_number: str
|
||||||
|
name: str
|
||||||
|
unit: str
|
||||||
|
quantity: Decimal
|
||||||
|
unit_price: Decimal
|
||||||
|
amount: Decimal
|
||||||
|
group_header: str | None = None
|
||||||
|
group_code: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS2ExportHeader:
|
||||||
|
project_name: str
|
||||||
|
customer: str
|
||||||
|
contract_number: str
|
||||||
|
contract_date: date | None
|
||||||
|
currency: str
|
||||||
|
ks2_number: str
|
||||||
|
ks2_date: date
|
||||||
|
period_from: date | None
|
||||||
|
period_to: date | None
|
||||||
|
comment: str
|
||||||
|
status: str
|
||||||
|
# Official requisites (DOC-B10)
|
||||||
|
investor_name: str = ""
|
||||||
|
customer_name: str = ""
|
||||||
|
contractor_name: str = ""
|
||||||
|
construction_name: str = ""
|
||||||
|
object_name: str = ""
|
||||||
|
contract_amount: str = ""
|
||||||
|
contractor_signer_name: str = ""
|
||||||
|
contractor_signer_position: str = ""
|
||||||
|
customer_signer_name: str = ""
|
||||||
|
customer_signer_position: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS2ExportDocument:
|
||||||
|
header: KS2ExportHeader
|
||||||
|
items: list[KS2ExportItem]
|
||||||
|
total: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
|
||||||
|
"""Build the export DTO from a KS2 document. Read-only: does not modify any data."""
|
||||||
|
from decimal import Decimal as D
|
||||||
|
|
||||||
|
project = ks2_document.project
|
||||||
|
items = []
|
||||||
|
total = D("0")
|
||||||
|
current_group = None
|
||||||
|
for idx, line in enumerate(ks2_document.items, start=1):
|
||||||
|
wi = line.work_item
|
||||||
|
amount = D(str(line.amount or 0))
|
||||||
|
total += amount
|
||||||
|
# Determine group header from System → Section hierarchy
|
||||||
|
group_header = None
|
||||||
|
group_code = None
|
||||||
|
if wi is not None:
|
||||||
|
system_name = wi.system.name if wi.system else None
|
||||||
|
system_code = wi.system.code if wi.system else None
|
||||||
|
section_name = wi.section.name if wi.section else None
|
||||||
|
if system_name and system_name != current_group:
|
||||||
|
group_header = system_name
|
||||||
|
group_code = system_code
|
||||||
|
current_group = system_name
|
||||||
|
elif section_name and system_name is None and section_name != current_group:
|
||||||
|
group_header = section_name
|
||||||
|
current_group = section_name
|
||||||
|
items.append(KS2ExportItem(
|
||||||
|
row_number=idx,
|
||||||
|
source_number=wi.source_number or "",
|
||||||
|
name=wi.name or "",
|
||||||
|
unit=wi.unit or "",
|
||||||
|
quantity=D(str(line.quantity or 0)),
|
||||||
|
unit_price=D(str(line.unit_price or 0)),
|
||||||
|
amount=amount,
|
||||||
|
group_header=group_header,
|
||||||
|
group_code=group_code,
|
||||||
|
))
|
||||||
|
|
||||||
|
header = KS2ExportHeader(
|
||||||
|
project_name=project.name if project else "",
|
||||||
|
customer=project.effective_customer_name if project else "",
|
||||||
|
contract_number=project.contract_number if project and project.contract_number else "",
|
||||||
|
contract_date=project.contract_date if project else None,
|
||||||
|
currency=project.currency if project and project.currency else "",
|
||||||
|
ks2_number=ks2_document.number,
|
||||||
|
ks2_date=ks2_document.date,
|
||||||
|
period_from=ks2_document.reporting_period_from,
|
||||||
|
period_to=ks2_document.reporting_period_to,
|
||||||
|
comment=ks2_document.comment or "",
|
||||||
|
status=ks2_document.status or "",
|
||||||
|
investor_name=project.investor_name if project and project.investor_name else "",
|
||||||
|
customer_name=project.effective_customer_name if project else "",
|
||||||
|
contractor_name=project.contractor_name if project and project.contractor_name else "",
|
||||||
|
construction_name=project.construction_name if project and project.construction_name else "",
|
||||||
|
object_name=project.object_name if project and project.object_name else "",
|
||||||
|
contract_amount=str(project.contract_amount) if project and project.contract_amount is not None else "",
|
||||||
|
contractor_signer_name=project.contractor_signer_name if project and project.contractor_signer_name else "",
|
||||||
|
contractor_signer_position=project.contractor_signer_position if project and project.contractor_signer_position else "",
|
||||||
|
customer_signer_name=project.customer_signer_name if project and project.customer_signer_name else "",
|
||||||
|
customer_signer_position=project.customer_signer_position if project and project.customer_signer_position else "",
|
||||||
|
)
|
||||||
|
return KS2ExportDocument(header=header, items=items, total=total)
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""KS-3 export DTO. One source of truth for Excel and Word renderers."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS3ExportItem:
|
||||||
|
row_number: int
|
||||||
|
ks2_number: str
|
||||||
|
ks2_date: date | None
|
||||||
|
period_from: date | None
|
||||||
|
period_to: date | None
|
||||||
|
amount: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS3ExportHeader:
|
||||||
|
project_name: str
|
||||||
|
customer: str
|
||||||
|
contract_number: str
|
||||||
|
contract_date: date | None
|
||||||
|
currency: str
|
||||||
|
ks3_number: str
|
||||||
|
ks3_date: date
|
||||||
|
period_from: date | None
|
||||||
|
period_to: date | None
|
||||||
|
comment: str
|
||||||
|
status: str
|
||||||
|
# Official requisites (DOC-B10)
|
||||||
|
investor_name: str = ""
|
||||||
|
customer_name: str = ""
|
||||||
|
contractor_name: str = ""
|
||||||
|
construction_name: str = ""
|
||||||
|
object_name: str = ""
|
||||||
|
contract_amount: str = ""
|
||||||
|
contractor_signer_name: str = ""
|
||||||
|
contractor_signer_position: str = ""
|
||||||
|
customer_signer_name: str = ""
|
||||||
|
customer_signer_position: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS3ExportDocument:
|
||||||
|
header: KS3ExportHeader
|
||||||
|
items: list[KS3ExportItem]
|
||||||
|
total: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
def build_ks3_export_dto(db, ks3_document) -> KS3ExportDocument:
|
||||||
|
"""Build the export DTO from a KS3 document. Read-only: does not modify any data."""
|
||||||
|
from decimal import Decimal as D
|
||||||
|
|
||||||
|
project = ks3_document.project
|
||||||
|
items = []
|
||||||
|
total = D("0")
|
||||||
|
for idx, link in enumerate(ks3_document.links, start=1):
|
||||||
|
ks2 = link.ks2
|
||||||
|
if ks2 is None:
|
||||||
|
continue
|
||||||
|
amount = sum((D(str(line.amount or 0)) for line in ks2.items), D("0"))
|
||||||
|
total += amount
|
||||||
|
items.append(KS3ExportItem(
|
||||||
|
row_number=idx,
|
||||||
|
ks2_number=ks2.number,
|
||||||
|
ks2_date=ks2.date,
|
||||||
|
period_from=ks2.reporting_period_from,
|
||||||
|
period_to=ks2.reporting_period_to,
|
||||||
|
amount=amount,
|
||||||
|
))
|
||||||
|
|
||||||
|
header = KS3ExportHeader(
|
||||||
|
project_name=project.name if project else "",
|
||||||
|
customer=project.effective_customer_name if project else "",
|
||||||
|
contract_number=project.contract_number if project and project.contract_number else "",
|
||||||
|
contract_date=project.contract_date if project else None,
|
||||||
|
currency=project.currency if project and project.currency else "",
|
||||||
|
ks3_number=ks3_document.number,
|
||||||
|
ks3_date=ks3_document.date,
|
||||||
|
period_from=ks3_document.reporting_period_from,
|
||||||
|
period_to=ks3_document.reporting_period_to,
|
||||||
|
comment=ks3_document.comment or "",
|
||||||
|
status=ks3_document.status or "",
|
||||||
|
investor_name=project.investor_name if project and project.investor_name else "",
|
||||||
|
customer_name=project.effective_customer_name if project else "",
|
||||||
|
contractor_name=project.contractor_name if project and project.contractor_name else "",
|
||||||
|
construction_name=project.construction_name if project and project.construction_name else "",
|
||||||
|
object_name=project.object_name if project and project.object_name else "",
|
||||||
|
contract_amount=str(project.contract_amount) if project and project.contract_amount is not None else "",
|
||||||
|
contractor_signer_name=project.contractor_signer_name if project and project.contractor_signer_name else "",
|
||||||
|
contractor_signer_position=project.contractor_signer_position if project and project.contractor_signer_position else "",
|
||||||
|
customer_signer_name=project.customer_signer_name if project and project.customer_signer_name else "",
|
||||||
|
customer_signer_position=project.customer_signer_position if project and project.customer_signer_position else "",
|
||||||
|
)
|
||||||
|
return KS3ExportDocument(header=header, items=items, total=total)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""KS-6a export DTO. One source of truth for Excel and Word renderers.
|
||||||
|
|
||||||
|
KS-6a is a reporting view of actual completed work from Daily Reports.
|
||||||
|
One row = one DailyReportItem. No financial data (price/amount/plan/KS-2 balance).
|
||||||
|
"""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS6aExportItem:
|
||||||
|
row_number: int
|
||||||
|
report_date: date
|
||||||
|
system_name: str
|
||||||
|
section_name: str
|
||||||
|
source_number: str
|
||||||
|
name: str
|
||||||
|
unit: str
|
||||||
|
quantity: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS6aExportHeader:
|
||||||
|
project_name: str
|
||||||
|
customer: str
|
||||||
|
contractor: str
|
||||||
|
contract_number: str
|
||||||
|
contract_date: date | None
|
||||||
|
currency: str
|
||||||
|
period_from: date
|
||||||
|
period_to: date
|
||||||
|
system_name: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KS6aExportDocument:
|
||||||
|
header: KS6aExportHeader
|
||||||
|
items: list[KS6aExportItem]
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_ks6a_rows(db, project_id: int, date_from: date, date_to: date, system_id: int | None = None):
|
||||||
|
"""One KS-6a row = one DailyReportItem. No aggregation across Daily Reports."""
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app.models.boq import WorkItem
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
|
||||||
|
query = db.query(DailyReportItem).join(
|
||||||
|
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||||
|
).join(
|
||||||
|
WorkItem, WorkItem.id == DailyReportItem.work_item_id
|
||||||
|
).options(
|
||||||
|
joinedload(DailyReportItem.work_item),
|
||||||
|
joinedload(DailyReportItem.report),
|
||||||
|
).filter(
|
||||||
|
DailyReport.project_id == project_id,
|
||||||
|
DailyReport.report_date >= date_from,
|
||||||
|
DailyReport.report_date <= date_to,
|
||||||
|
)
|
||||||
|
|
||||||
|
if system_id is not None:
|
||||||
|
query = query.filter(WorkItem.system_id == system_id)
|
||||||
|
|
||||||
|
return query.order_by(
|
||||||
|
DailyReport.report_date,
|
||||||
|
DailyReport.id,
|
||||||
|
DailyReportItem.id,
|
||||||
|
).all()
|
||||||
|
|
||||||
|
|
||||||
|
def build_ks6a_export_dto(project, rows, date_from: date, date_to: date, system_name: str = "") -> KS6aExportDocument:
|
||||||
|
"""Build the export DTO from KS-6a reporting rows. Read-only: does not modify any data."""
|
||||||
|
from decimal import Decimal as D
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for idx, row in enumerate(rows, start=1):
|
||||||
|
wi = row.work_item
|
||||||
|
items.append(KS6aExportItem(
|
||||||
|
row_number=idx,
|
||||||
|
report_date=row.report.report_date,
|
||||||
|
system_name=wi.system.name if wi.system else "",
|
||||||
|
section_name=wi.section.name if wi.section else "",
|
||||||
|
source_number=wi.source_number or "",
|
||||||
|
name=wi.name or "",
|
||||||
|
unit=wi.unit or "",
|
||||||
|
quantity=D(str(row.completed_quantity or 0)),
|
||||||
|
))
|
||||||
|
|
||||||
|
header = KS6aExportHeader(
|
||||||
|
project_name=project.name if project else "",
|
||||||
|
customer=project.customer if project and project.customer else "",
|
||||||
|
contractor="",
|
||||||
|
contract_number=project.contract_number if project and project.contract_number else "",
|
||||||
|
contract_date=project.contract_date if project else None,
|
||||||
|
currency=project.currency if project and project.currency else "",
|
||||||
|
period_from=date_from,
|
||||||
|
period_to=date_to,
|
||||||
|
system_name=system_name or "",
|
||||||
|
)
|
||||||
|
return KS6aExportDocument(header=header, items=items)
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"""Build a ZIP package of project documents for a selected period.
|
||||||
|
|
||||||
|
Uses existing export DTO/renderers. Does not duplicate generation logic.
|
||||||
|
Only issued KS-2/KS-3 with a fully set reporting period that falls into
|
||||||
|
the selected range are included. KS-6a is a reporting view of Daily Reports.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from app.exporters import _clean_export_name
|
||||||
|
|
||||||
|
|
||||||
|
class PackageEmptyError(Exception):
|
||||||
|
"""No documents match the selected package composition."""
|
||||||
|
|
||||||
|
|
||||||
|
class PackageValidationError(Exception):
|
||||||
|
"""Invalid package request parameters."""
|
||||||
|
|
||||||
|
|
||||||
|
VALID_DOCS = ("ks6a", "ks2", "ks3")
|
||||||
|
VALID_FORMATS = ("excel", "word", "both")
|
||||||
|
|
||||||
|
|
||||||
|
def _period_formats(export_format: str) -> list[str]:
|
||||||
|
if export_format == "excel":
|
||||||
|
return ["xlsx"]
|
||||||
|
if export_format == "word":
|
||||||
|
return ["docx"]
|
||||||
|
return ["xlsx", "docx"]
|
||||||
|
|
||||||
|
|
||||||
|
def _period_text(date_from: date, date_to: date) -> str:
|
||||||
|
return f"{date_from.strftime('%d.%m.%Y')}-{date_to.strftime('%d.%m.%Y')}"
|
||||||
|
|
||||||
|
|
||||||
|
def package_filename(project_name: str, date_from: date, date_to: date) -> str:
|
||||||
|
raw = f"Комплект_{project_name}_{_period_text(date_from, date_to)}"
|
||||||
|
raw = re.sub(r"\s+", "_", raw.strip())
|
||||||
|
return f"{_clean_export_name(raw)}.zip"
|
||||||
|
|
||||||
|
|
||||||
|
def _member_filename(prefix: str, number: str, dt) -> str:
|
||||||
|
raw = f"{prefix}_№{number}_{dt.strftime('%d.%m.%Y')}"
|
||||||
|
return _clean_export_name(raw)
|
||||||
|
|
||||||
|
|
||||||
|
def _period_fits(doc_from: date | None, doc_to: date | None, date_from: date, date_to: date) -> bool:
|
||||||
|
if doc_from is None or doc_to is None:
|
||||||
|
return False
|
||||||
|
return doc_from <= date_to and doc_to >= date_from
|
||||||
|
|
||||||
|
|
||||||
|
def _ks2_in_period(db, project_id: int, date_from: date, date_to: date):
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
|
||||||
|
return db.query(KS2).options(
|
||||||
|
joinedload(KS2.items)
|
||||||
|
).filter(
|
||||||
|
KS2.project_id == project_id,
|
||||||
|
KS2.status == "issued",
|
||||||
|
KS2.reporting_period_from.isnot(None),
|
||||||
|
KS2.reporting_period_to.isnot(None),
|
||||||
|
KS2.reporting_period_from <= date_to,
|
||||||
|
KS2.reporting_period_to >= date_from,
|
||||||
|
).order_by(KS2.date, KS2.id).all()
|
||||||
|
|
||||||
|
|
||||||
|
def _ks3_in_period(db, project_id: int, date_from: date, date_to: date):
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
|
||||||
|
return db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(
|
||||||
|
KS3.project_id == project_id,
|
||||||
|
KS3.status == "issued",
|
||||||
|
KS3.reporting_period_from.isnot(None),
|
||||||
|
KS3.reporting_period_to.isnot(None),
|
||||||
|
KS3.reporting_period_from <= date_to,
|
||||||
|
KS3.reporting_period_to >= date_from,
|
||||||
|
).order_by(KS3.date, KS3.id).all()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_package_params(date_from: str, date_to: str, include, export_format: str):
|
||||||
|
if not date_from or not date_to:
|
||||||
|
raise PackageValidationError("Необходимо указать период (date_from и date_to)")
|
||||||
|
try:
|
||||||
|
parsed_from = date.fromisoformat(date_from)
|
||||||
|
parsed_to = date.fromisoformat(date_to)
|
||||||
|
except ValueError:
|
||||||
|
raise PackageValidationError("Неверный формат даты")
|
||||||
|
if parsed_to < parsed_from:
|
||||||
|
raise PackageValidationError("Дата окончания не может быть раньше даты начала")
|
||||||
|
|
||||||
|
selected = []
|
||||||
|
for item in include or []:
|
||||||
|
if item in VALID_DOCS and item not in selected:
|
||||||
|
selected.append(item)
|
||||||
|
if not selected:
|
||||||
|
raise PackageValidationError("Выберите хотя бы один тип документов (КС-6а, КС-2, КС-3)")
|
||||||
|
|
||||||
|
if export_format not in VALID_FORMATS:
|
||||||
|
raise PackageValidationError("Неверный формат экспорта")
|
||||||
|
|
||||||
|
return parsed_from, parsed_to, selected, export_format
|
||||||
|
|
||||||
|
|
||||||
|
def build_document_package(db, project, date_from: date, date_to: date,
|
||||||
|
include: list[str], export_format: str) -> tuple[bytes, str]:
|
||||||
|
"""Return (zip_bytes, filename). Raises PackageEmptyError when nothing to pack."""
|
||||||
|
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||||
|
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||||
|
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
|
||||||
|
|
||||||
|
formats = _period_formats(export_format)
|
||||||
|
members: list[tuple[str, bytes]] = [] # (zip arcname, data)
|
||||||
|
|
||||||
|
if "ks6a" in include:
|
||||||
|
from app.exporters.excel.ks6a_renderer import render_ks6a_excel
|
||||||
|
from app.exporters.word.ks6a_renderer import render_ks6a_word
|
||||||
|
|
||||||
|
rows = fetch_ks6a_rows(db, project.id, date_from, date_to, None)
|
||||||
|
dto = build_ks6a_export_dto(project, rows, date_from, date_to, "")
|
||||||
|
base = f"КС-6а_{_period_text(date_from, date_to)}"
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-6а/{base}.xlsx", render_ks6a_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-6а/{base}.docx", render_ks6a_word(dto)))
|
||||||
|
|
||||||
|
if "ks2" in include:
|
||||||
|
from app.exporters.excel.ks2_renderer import render_ks2_excel
|
||||||
|
from app.exporters.word.ks2_renderer import render_ks2_word
|
||||||
|
|
||||||
|
for doc in _ks2_in_period(db, project.id, date_from, date_to):
|
||||||
|
dto = build_ks2_export_dto(db, doc)
|
||||||
|
base = _member_filename("КС-2", doc.number, doc.date)
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-2/{base}.xlsx", render_ks2_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-2/{base}.docx", render_ks2_word(dto)))
|
||||||
|
|
||||||
|
if "ks3" in include:
|
||||||
|
from app.exporters.excel.ks3_renderer import render_ks3_excel
|
||||||
|
from app.exporters.word.ks3_renderer import render_ks3_word
|
||||||
|
|
||||||
|
for doc in _ks3_in_period(db, project.id, date_from, date_to):
|
||||||
|
dto = build_ks3_export_dto(db, doc)
|
||||||
|
base = _member_filename("КС-3", doc.number, doc.date)
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-3/{base}.xlsx", render_ks3_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-3/{base}.docx", render_ks3_word(dto)))
|
||||||
|
|
||||||
|
if not members:
|
||||||
|
raise PackageEmptyError(
|
||||||
|
"За выбранный период нет документов для включения в комплект"
|
||||||
|
)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for arcname, data in members:
|
||||||
|
zf.writestr(arcname, data)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read(), package_filename(project.name or "проект", date_from, date_to)
|
||||||
@@ -0,0 +1,845 @@
|
|||||||
|
"""Machine-readable project export as a portable ZIP archive."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Any, Callable, Iterable
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.daily_report_photo import DailyReportPhoto
|
||||||
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.work_journal import WorkJournalEntry
|
||||||
|
from app.models.document_artifact import DocumentArtifact
|
||||||
|
|
||||||
|
FORMAT_NAME = "work_volume_tracker"
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
|
||||||
|
REQUIRED_FILES = (
|
||||||
|
"manifest.json",
|
||||||
|
"project.json",
|
||||||
|
"boq_documents.json",
|
||||||
|
"systems.json",
|
||||||
|
"sections.json",
|
||||||
|
"work_items.json",
|
||||||
|
"agreements.json",
|
||||||
|
"agreement_items.json",
|
||||||
|
"daily_reports.json",
|
||||||
|
"daily_report_items.json",
|
||||||
|
"ks2.json",
|
||||||
|
"ks2_items.json",
|
||||||
|
"ks2_item_sources.json",
|
||||||
|
"ks3.json",
|
||||||
|
"ks3_ks2.json",
|
||||||
|
"payments.json",
|
||||||
|
"payment_allocations.json",
|
||||||
|
"checksums.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Old Task 025 archives may lack these files; import treats them as empty.
|
||||||
|
OPTIONAL_FILES = (
|
||||||
|
"work_journal_entries.json",
|
||||||
|
"document_artifacts.json",
|
||||||
|
"daily_report_photos.json",
|
||||||
|
)
|
||||||
|
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectExportError(RuntimeError):
|
||||||
|
"""Raised when the project cannot be exported safely."""
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(value: Any) -> Any:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.isoformat()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value.isoformat()
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _dec(value: Any) -> Any:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = format(Decimal(str(value)), "f")
|
||||||
|
if "." in text:
|
||||||
|
text = text.rstrip("0").rstrip(".")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _export_key(kind: str, index: int) -> str:
|
||||||
|
return f"{kind}:{index:08d}"
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_archive_filename(project_name: str, when: date | datetime | None = None) -> str:
|
||||||
|
name = (project_name or "проект").strip() or "проект"
|
||||||
|
name = re.sub(r'[<>:"/\\|?*\r\n\t]', "_", name)
|
||||||
|
name = re.sub(r"\s+", "_", name).strip("._") or "проект"
|
||||||
|
day = (when or datetime.now()).strftime("%Y-%m-%d")
|
||||||
|
return f"Проект_{name}_{day}.wvt.zip"
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(data: bytes) -> str:
|
||||||
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _dumps(payload: Any) -> bytes:
|
||||||
|
return json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=False).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def collect_project(db: Session, project_id: int) -> dict[str, Any]:
|
||||||
|
"""Load the full logical project graph and return JSON-ready records."""
|
||||||
|
project = db.query(Project).filter(Project.id == project_id).first()
|
||||||
|
if project is None:
|
||||||
|
raise ProjectExportError("Проект не найден")
|
||||||
|
|
||||||
|
boq_docs = (
|
||||||
|
db.query(BoqDocument)
|
||||||
|
.filter(BoqDocument.project_id == project_id)
|
||||||
|
.order_by(BoqDocument.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
systems = (
|
||||||
|
db.query(System).filter(System.project_id == project_id).order_by(System.id).all()
|
||||||
|
)
|
||||||
|
system_ids = [s.id for s in systems]
|
||||||
|
sections = (
|
||||||
|
db.query(Section)
|
||||||
|
.filter(Section.system_id.in_(system_ids) if system_ids else False)
|
||||||
|
.order_by(Section.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
work_items = (
|
||||||
|
db.query(WorkItem).filter(WorkItem.project_id == project_id).order_by(WorkItem.id).all()
|
||||||
|
)
|
||||||
|
agreements = (
|
||||||
|
db.query(Agreement).filter(Agreement.project_id == project_id).order_by(Agreement.id).all()
|
||||||
|
)
|
||||||
|
agreement_ids = [a.id for a in agreements]
|
||||||
|
agreement_items = (
|
||||||
|
db.query(AgreementItem)
|
||||||
|
.filter(AgreementItem.agreement_id.in_(agreement_ids) if agreement_ids else False)
|
||||||
|
.order_by(AgreementItem.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
daily_reports = (
|
||||||
|
db.query(DailyReport)
|
||||||
|
.filter(DailyReport.project_id == project_id)
|
||||||
|
.order_by(DailyReport.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
daily_report_ids = [d.id for d in daily_reports]
|
||||||
|
daily_report_items = (
|
||||||
|
db.query(DailyReportItem)
|
||||||
|
.filter(
|
||||||
|
DailyReportItem.daily_report_id.in_(daily_report_ids)
|
||||||
|
if daily_report_ids
|
||||||
|
else False
|
||||||
|
)
|
||||||
|
.order_by(DailyReportItem.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
ks2_docs = db.query(KS2).filter(KS2.project_id == project_id).order_by(KS2.id).all()
|
||||||
|
ks2_ids = [k.id for k in ks2_docs]
|
||||||
|
ks2_items = (
|
||||||
|
db.query(KS2Item)
|
||||||
|
.filter(KS2Item.ks2_id.in_(ks2_ids) if ks2_ids else False)
|
||||||
|
.order_by(KS2Item.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
ks2_item_ids = [i.id for i in ks2_items]
|
||||||
|
ks2_item_sources = (
|
||||||
|
db.query(KS2ItemSource)
|
||||||
|
.filter(KS2ItemSource.ks2_item_id.in_(ks2_item_ids) if ks2_item_ids else False)
|
||||||
|
.order_by(KS2ItemSource.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
ks3_docs = db.query(KS3).filter(KS3.project_id == project_id).order_by(KS3.id).all()
|
||||||
|
ks3_ids = [k.id for k in ks3_docs]
|
||||||
|
ks3_ks2 = (
|
||||||
|
db.query(KS3KS2)
|
||||||
|
.filter(KS3KS2.ks3_id.in_(ks3_ids) if ks3_ids else False)
|
||||||
|
.order_by(KS3KS2.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
payments = (
|
||||||
|
db.query(Payment).filter(Payment.project_id == project_id).order_by(Payment.id).all()
|
||||||
|
)
|
||||||
|
payment_ids = [p.id for p in payments]
|
||||||
|
payment_allocations = (
|
||||||
|
db.query(PaymentAllocation)
|
||||||
|
.filter(PaymentAllocation.payment_id.in_(payment_ids) if payment_ids else False)
|
||||||
|
.order_by(PaymentAllocation.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
work_journal_entries = (
|
||||||
|
db.query(WorkJournalEntry)
|
||||||
|
.filter(WorkJournalEntry.project_id == project_id)
|
||||||
|
.order_by(WorkJournalEntry.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
# Official artifacts for issued/cancelled KS-2 and KS-3 only.
|
||||||
|
ks2_statuses = {k.id: k.status for k in ks2_docs}
|
||||||
|
ks3_statuses = {k.id: k.status for k in ks3_docs}
|
||||||
|
eligible_doc_ids = {
|
||||||
|
"KS2": {kid for kid, st in ks2_statuses.items() if st in ("issued", "cancelled")},
|
||||||
|
"KS3": {kid for kid, st in ks3_statuses.items() if st in ("issued", "cancelled")},
|
||||||
|
}
|
||||||
|
document_artifacts = (
|
||||||
|
db.query(DocumentArtifact)
|
||||||
|
.filter(DocumentArtifact.project_id == project_id)
|
||||||
|
.order_by(DocumentArtifact.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
# Daily Report photos belong to the primary report and travel with it.
|
||||||
|
daily_report_photos = (
|
||||||
|
db.query(DailyReportPhoto)
|
||||||
|
.filter(DailyReportPhoto.project_id == project_id)
|
||||||
|
.order_by(DailyReportPhoto.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"project": project,
|
||||||
|
"boq_documents": boq_docs,
|
||||||
|
"systems": systems,
|
||||||
|
"sections": sections,
|
||||||
|
"work_items": work_items,
|
||||||
|
"agreements": agreements,
|
||||||
|
"agreement_items": agreement_items,
|
||||||
|
"daily_reports": daily_reports,
|
||||||
|
"daily_report_items": daily_report_items,
|
||||||
|
"daily_report_photos": daily_report_photos,
|
||||||
|
"ks2": ks2_docs,
|
||||||
|
"ks2_items": ks2_items,
|
||||||
|
"ks2_item_sources": ks2_item_sources,
|
||||||
|
"ks3": ks3_docs,
|
||||||
|
"ks3_ks2": ks3_ks2,
|
||||||
|
"payments": payments,
|
||||||
|
"payment_allocations": payment_allocations,
|
||||||
|
"work_journal_entries": work_journal_entries,
|
||||||
|
"document_artifacts": document_artifacts,
|
||||||
|
"eligible_doc_ids": eligible_doc_ids,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_graph(graph: dict[str, Any]) -> None:
|
||||||
|
"""Refuse to export a project with broken internal references."""
|
||||||
|
project = graph["project"]
|
||||||
|
pid = project.id
|
||||||
|
|
||||||
|
doc_ids = {d.id for d in graph["boq_documents"]}
|
||||||
|
system_ids = {s.id for s in graph["systems"]}
|
||||||
|
section_ids = {s.id for s in graph["sections"]}
|
||||||
|
work_item_ids = {w.id for w in graph["work_items"]}
|
||||||
|
agreement_ids = {a.id for a in graph["agreements"]}
|
||||||
|
report_ids = {r.id for r in graph["daily_reports"]}
|
||||||
|
report_item_ids = {i.id for i in graph["daily_report_items"]}
|
||||||
|
ks2_ids = {k.id for k in graph["ks2"]}
|
||||||
|
ks2_item_ids = {i.id for i in graph["ks2_items"]}
|
||||||
|
ks3_ids = {k.id for k in graph["ks3"]}
|
||||||
|
payment_ids = {p.id for p in graph["payments"]}
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
|
||||||
|
for d in graph["boq_documents"]:
|
||||||
|
if d.project_id != pid:
|
||||||
|
errors.append(f"boq_document:{d.id} belongs to another project")
|
||||||
|
if d.agreement_id is not None and d.agreement_id not in agreement_ids:
|
||||||
|
errors.append(f"boq_document:{d.id} references missing agreement")
|
||||||
|
for s in graph["systems"]:
|
||||||
|
if s.project_id != pid:
|
||||||
|
errors.append(f"system:{s.id} belongs to another project")
|
||||||
|
for sec in graph["sections"]:
|
||||||
|
if sec.system_id not in system_ids:
|
||||||
|
errors.append(f"section:{sec.id} references missing system")
|
||||||
|
for w in graph["work_items"]:
|
||||||
|
if w.project_id != pid:
|
||||||
|
errors.append(f"work_item:{w.id} belongs to another project")
|
||||||
|
if w.boq_document_id is not None and w.boq_document_id not in doc_ids:
|
||||||
|
errors.append(f"work_item:{w.id} references missing boq_document")
|
||||||
|
if w.system_id is not None and w.system_id not in system_ids:
|
||||||
|
errors.append(f"work_item:{w.id} references missing system")
|
||||||
|
if w.section_id is not None and w.section_id not in section_ids:
|
||||||
|
errors.append(f"work_item:{w.id} references missing section")
|
||||||
|
for a in graph["agreements"]:
|
||||||
|
if a.project_id != pid:
|
||||||
|
errors.append(f"agreement:{a.id} belongs to another project")
|
||||||
|
if a.boq_document_id is not None and a.boq_document_id not in doc_ids:
|
||||||
|
errors.append(f"agreement:{a.id} references missing boq_document")
|
||||||
|
for i in graph["agreement_items"]:
|
||||||
|
if i.agreement_id not in agreement_ids:
|
||||||
|
errors.append(f"agreement_item:{i.id} references missing agreement")
|
||||||
|
if i.work_item_id not in work_item_ids:
|
||||||
|
errors.append(f"agreement_item:{i.id} references missing work_item")
|
||||||
|
for label, value in (
|
||||||
|
("source_boq_document_id", i.source_boq_document_id),
|
||||||
|
("source_system_id", i.source_system_id),
|
||||||
|
("source_section_id", i.source_section_id),
|
||||||
|
):
|
||||||
|
if value is None:
|
||||||
|
continue
|
||||||
|
pool = {"source_boq_document_id": doc_ids, "source_system_id": system_ids, "source_section_id": section_ids}[label]
|
||||||
|
if value not in pool:
|
||||||
|
errors.append(f"agreement_item:{i.id} references missing {label}")
|
||||||
|
for r in graph["daily_reports"]:
|
||||||
|
if r.project_id != pid:
|
||||||
|
errors.append(f"daily_report:{r.id} belongs to another project")
|
||||||
|
if r.system_id is not None and r.system_id not in system_ids:
|
||||||
|
errors.append(f"daily_report:{r.id} references missing system")
|
||||||
|
for i in graph["daily_report_items"]:
|
||||||
|
if i.daily_report_id not in report_ids:
|
||||||
|
errors.append(f"daily_report_item:{i.id} references missing daily_report")
|
||||||
|
if i.work_item_id not in work_item_ids:
|
||||||
|
errors.append(f"daily_report_item:{i.id} references missing work_item")
|
||||||
|
for p in graph.get("daily_report_photos", []):
|
||||||
|
if p.daily_report_id not in report_ids:
|
||||||
|
errors.append(f"daily_report_photo:{p.id} references missing daily_report")
|
||||||
|
if p.project_id != pid:
|
||||||
|
errors.append(f"daily_report_photo:{p.id} belongs to another project")
|
||||||
|
for k in graph["ks2"]:
|
||||||
|
if k.project_id != pid:
|
||||||
|
errors.append(f"ks2:{k.id} belongs to another project")
|
||||||
|
for i in graph["ks2_items"]:
|
||||||
|
if i.ks2_id not in ks2_ids:
|
||||||
|
errors.append(f"ks2_item:{i.id} references missing ks2")
|
||||||
|
if i.work_item_id not in work_item_ids:
|
||||||
|
errors.append(f"ks2_item:{i.id} references missing work_item")
|
||||||
|
for s in graph["ks2_item_sources"]:
|
||||||
|
if s.ks2_item_id not in ks2_item_ids:
|
||||||
|
errors.append(f"ks2_item_source:{s.id} references missing ks2_item")
|
||||||
|
if s.daily_report_item_id not in report_item_ids:
|
||||||
|
errors.append(f"ks2_item_source:{s.id} references missing daily_report_item")
|
||||||
|
for k in graph["ks3"]:
|
||||||
|
if k.project_id != pid:
|
||||||
|
errors.append(f"ks3:{k.id} belongs to another project")
|
||||||
|
for link in graph["ks3_ks2"]:
|
||||||
|
if link.ks3_id not in ks3_ids:
|
||||||
|
errors.append(f"ks3_ks2:{link.id} references missing ks3")
|
||||||
|
if link.ks2_id not in ks2_ids:
|
||||||
|
errors.append(f"ks3_ks2:{link.id} references missing ks2")
|
||||||
|
for p in graph["payments"]:
|
||||||
|
if p.project_id != pid:
|
||||||
|
errors.append(f"payment:{p.id} belongs to another project")
|
||||||
|
for a in graph["payment_allocations"]:
|
||||||
|
if a.payment_id not in payment_ids:
|
||||||
|
errors.append(f"payment_allocation:{a.id} references missing payment")
|
||||||
|
if a.ks3_id not in ks3_ids:
|
||||||
|
errors.append(f"payment_allocation:{a.id} references missing ks3")
|
||||||
|
for entry in graph.get("work_journal_entries", []):
|
||||||
|
if entry.project_id != pid:
|
||||||
|
errors.append(f"work_journal_entry:{entry.id} belongs to another project")
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
raise ProjectExportError(
|
||||||
|
"Экспорт остановлен: нарушена ссылочная целостность проекта — "
|
||||||
|
+ "; ".join(errors[:10])
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _key_map(entities: Iterable[Any], kind: str) -> dict[int, str]:
|
||||||
|
return {e.id: _export_key(kind, idx) for idx, e in enumerate(entities, start=1)}
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||||
|
"""Convert ORM objects into JSON-ready records with export_id keys."""
|
||||||
|
project = graph["project"]
|
||||||
|
keys = {
|
||||||
|
"boq_document": _key_map(graph["boq_documents"], "boq_document"),
|
||||||
|
"system": _key_map(graph["systems"], "system"),
|
||||||
|
"section": _key_map(graph["sections"], "section"),
|
||||||
|
"work_item": _key_map(graph["work_items"], "work_item"),
|
||||||
|
"agreement": _key_map(graph["agreements"], "agreement"),
|
||||||
|
"agreement_item": _key_map(graph["agreement_items"], "agreement_item"),
|
||||||
|
"daily_report": _key_map(graph["daily_reports"], "daily_report"),
|
||||||
|
"daily_report_item": _key_map(graph["daily_report_items"], "daily_report_item"),
|
||||||
|
"daily_report_photo": _key_map(graph.get("daily_report_photos", []), "daily_report_photo"),
|
||||||
|
"ks2": _key_map(graph["ks2"], "ks2"),
|
||||||
|
"ks2_item": _key_map(graph["ks2_items"], "ks2_item"),
|
||||||
|
"ks2_item_source": _key_map(graph["ks2_item_sources"], "ks2_item_source"),
|
||||||
|
"ks3": _key_map(graph["ks3"], "ks3"),
|
||||||
|
"ks3_ks2": _key_map(graph["ks3_ks2"], "ks3_ks2"),
|
||||||
|
"payment": _key_map(graph["payments"], "payment"),
|
||||||
|
"payment_allocation": _key_map(graph["payment_allocations"], "payment_allocation"),
|
||||||
|
"work_journal_entry": _key_map(graph.get("work_journal_entries", []), "work_journal_entry"),
|
||||||
|
}
|
||||||
|
|
||||||
|
def ref(kind: str, value: int | None) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return keys[kind].get(value)
|
||||||
|
|
||||||
|
project_record = {
|
||||||
|
"export_id": "project:00000001",
|
||||||
|
"source_id": project.id,
|
||||||
|
"name": project.name,
|
||||||
|
"contract_number": project.contract_number,
|
||||||
|
"contract_date": _iso(project.contract_date),
|
||||||
|
"customer": project.customer,
|
||||||
|
"currency": project.currency,
|
||||||
|
"start_date": _iso(project.start_date),
|
||||||
|
"end_date": _iso(project.end_date),
|
||||||
|
"status": project.status,
|
||||||
|
"created_at": _iso(project.created_at),
|
||||||
|
"updated_at": _iso(project.updated_at),
|
||||||
|
"investor_name": project.investor_name,
|
||||||
|
"customer_name": project.customer_name or project.customer,
|
||||||
|
"contractor_name": project.contractor_name,
|
||||||
|
"construction_name": project.construction_name,
|
||||||
|
"object_name": project.object_name,
|
||||||
|
"contract_amount": _dec(project.contract_amount),
|
||||||
|
"contractor_signer_name": project.contractor_signer_name,
|
||||||
|
"contractor_signer_position": project.contractor_signer_position,
|
||||||
|
"customer_signer_name": project.customer_signer_name,
|
||||||
|
"customer_signer_position": project.customer_signer_position,
|
||||||
|
}
|
||||||
|
|
||||||
|
def record(kind: str, obj: Any, fields: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out = {"export_id": keys[kind][obj.id], "source_id": obj.id}
|
||||||
|
out.update(fields)
|
||||||
|
return out
|
||||||
|
|
||||||
|
boq_documents = [
|
||||||
|
record(
|
||||||
|
"boq_document",
|
||||||
|
d,
|
||||||
|
{
|
||||||
|
"agreement_export_id": ref("agreement", d.agreement_id),
|
||||||
|
"name": d.name,
|
||||||
|
"version": d.version,
|
||||||
|
"source_file": d.source_file,
|
||||||
|
"document_number": d.document_number,
|
||||||
|
"document_date": _iso(d.document_date),
|
||||||
|
"contract": d.contract,
|
||||||
|
"created_at": _iso(d.created_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for d in graph["boq_documents"]
|
||||||
|
]
|
||||||
|
systems = [
|
||||||
|
record(
|
||||||
|
"system",
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"code": s.code,
|
||||||
|
"name": s.name,
|
||||||
|
"sort_order": s.sort_order,
|
||||||
|
"created_at": _iso(s.created_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for s in graph["systems"]
|
||||||
|
]
|
||||||
|
sections = [
|
||||||
|
record(
|
||||||
|
"section",
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"system_export_id": ref("system", s.system_id),
|
||||||
|
"name": s.name,
|
||||||
|
"sort_order": s.sort_order,
|
||||||
|
"created_at": _iso(s.created_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for s in graph["sections"]
|
||||||
|
]
|
||||||
|
work_items = [
|
||||||
|
record(
|
||||||
|
"work_item",
|
||||||
|
w,
|
||||||
|
{
|
||||||
|
"boq_document_export_id": ref("boq_document", w.boq_document_id),
|
||||||
|
"system_export_id": ref("system", w.system_id),
|
||||||
|
"section_export_id": ref("section", w.section_id),
|
||||||
|
"source_number": w.source_number,
|
||||||
|
"name": w.name,
|
||||||
|
"model": w.model,
|
||||||
|
"manufacturer": w.manufacturer,
|
||||||
|
"unit": w.unit,
|
||||||
|
"quantity": _dec(w.quantity),
|
||||||
|
"unit_price": _dec(w.unit_price),
|
||||||
|
"amount": _dec(w.amount),
|
||||||
|
"created_at": _iso(w.created_at),
|
||||||
|
"updated_at": _iso(w.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for w in graph["work_items"]
|
||||||
|
]
|
||||||
|
agreements = [
|
||||||
|
record(
|
||||||
|
"agreement",
|
||||||
|
a,
|
||||||
|
{
|
||||||
|
"boq_document_export_id": ref("boq_document", a.boq_document_id),
|
||||||
|
"number": a.number,
|
||||||
|
"date": _iso(a.date),
|
||||||
|
"title": a.title,
|
||||||
|
"description": a.description,
|
||||||
|
"status": a.status,
|
||||||
|
"created_at": _iso(a.created_at),
|
||||||
|
"updated_at": _iso(a.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for a in graph["agreements"]
|
||||||
|
]
|
||||||
|
agreement_items = [
|
||||||
|
record(
|
||||||
|
"agreement_item",
|
||||||
|
i,
|
||||||
|
{
|
||||||
|
"agreement_export_id": ref("agreement", i.agreement_id),
|
||||||
|
"work_item_export_id": ref("work_item", i.work_item_id),
|
||||||
|
"change_type": i.change_type,
|
||||||
|
"quantity_delta": _dec(i.quantity_delta),
|
||||||
|
"amount_delta": _dec(i.amount_delta),
|
||||||
|
"source_row": i.source_row,
|
||||||
|
"source_number": i.source_number,
|
||||||
|
"source_name": i.source_name,
|
||||||
|
"source_model": i.source_model,
|
||||||
|
"source_manufacturer": i.source_manufacturer,
|
||||||
|
"source_unit": i.source_unit,
|
||||||
|
"source_unit_price": _dec(i.source_unit_price),
|
||||||
|
"source_boq_document_export_id": ref("boq_document", i.source_boq_document_id),
|
||||||
|
"source_system_export_id": ref("system", i.source_system_id),
|
||||||
|
"source_section_export_id": ref("section", i.source_section_id),
|
||||||
|
"created_at": _iso(i.created_at),
|
||||||
|
"updated_at": _iso(i.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for i in graph["agreement_items"]
|
||||||
|
]
|
||||||
|
daily_reports = [
|
||||||
|
record(
|
||||||
|
"daily_report",
|
||||||
|
r,
|
||||||
|
{
|
||||||
|
"system_export_id": ref("system", r.system_id),
|
||||||
|
"report_date": _iso(r.report_date),
|
||||||
|
"notes": r.notes,
|
||||||
|
"created_at": _iso(r.created_at),
|
||||||
|
"updated_at": _iso(r.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for r in graph["daily_reports"]
|
||||||
|
]
|
||||||
|
daily_report_items = [
|
||||||
|
record(
|
||||||
|
"daily_report_item",
|
||||||
|
i,
|
||||||
|
{
|
||||||
|
"daily_report_export_id": ref("daily_report", i.daily_report_id),
|
||||||
|
"work_item_export_id": ref("work_item", i.work_item_id),
|
||||||
|
"completed_quantity": _dec(i.completed_quantity),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for i in graph["daily_report_items"]
|
||||||
|
]
|
||||||
|
daily_report_photo_records = []
|
||||||
|
photo_blobs: dict[str, bytes] = {}
|
||||||
|
for photo in graph.get("daily_report_photos", []):
|
||||||
|
photo_export_id = ref("daily_report", photo.daily_report_id)
|
||||||
|
if photo_export_id is None:
|
||||||
|
raise ProjectExportError(
|
||||||
|
f"Photo {photo.id} references unknown DailyReport {photo.daily_report_id}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
photo_file_bytes,
|
||||||
|
)
|
||||||
|
file_bytes = photo_file_bytes(photo)
|
||||||
|
except Exception as exc:
|
||||||
|
raise ProjectExportError(
|
||||||
|
f"Photo file missing for daily_report_photo:{photo.id} "
|
||||||
|
f"({photo.storage_key})"
|
||||||
|
) from exc
|
||||||
|
archive_path = f"photos/{photo_export_id.replace(':', '_')}/{photo.id:08d}.bin"
|
||||||
|
photo_blobs[archive_path] = file_bytes
|
||||||
|
daily_report_photo_records.append({
|
||||||
|
"export_id": f"daily_report_photo:{photo.id:08d}",
|
||||||
|
"source_id": photo.id,
|
||||||
|
"daily_report_export_id": photo_export_id,
|
||||||
|
"original_name": photo.original_name,
|
||||||
|
"content_type": photo.content_type,
|
||||||
|
"file_size": photo.file_size,
|
||||||
|
"content_hash": photo.content_hash,
|
||||||
|
"sort_order": photo.sort_order,
|
||||||
|
"created_at": _iso(photo.created_at),
|
||||||
|
"archive_path": archive_path,
|
||||||
|
})
|
||||||
|
ks2 = [
|
||||||
|
record(
|
||||||
|
"ks2",
|
||||||
|
k,
|
||||||
|
{
|
||||||
|
"number": k.number,
|
||||||
|
"date": _iso(k.date),
|
||||||
|
"reporting_period_from": _iso(k.reporting_period_from),
|
||||||
|
"reporting_period_to": _iso(k.reporting_period_to),
|
||||||
|
"comment": k.comment,
|
||||||
|
"status": k.status,
|
||||||
|
"created_at": _iso(k.created_at),
|
||||||
|
"updated_at": _iso(k.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for k in graph["ks2"]
|
||||||
|
]
|
||||||
|
ks2_items = [
|
||||||
|
record(
|
||||||
|
"ks2_item",
|
||||||
|
i,
|
||||||
|
{
|
||||||
|
"ks2_export_id": ref("ks2", i.ks2_id),
|
||||||
|
"work_item_export_id": ref("work_item", i.work_item_id),
|
||||||
|
"quantity": _dec(i.quantity),
|
||||||
|
"unit_price": _dec(i.unit_price),
|
||||||
|
"amount": _dec(i.amount),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for i in graph["ks2_items"]
|
||||||
|
]
|
||||||
|
ks2_item_sources = [
|
||||||
|
record(
|
||||||
|
"ks2_item_source",
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"ks2_item_export_id": ref("ks2_item", s.ks2_item_id),
|
||||||
|
"daily_report_item_export_id": ref("daily_report_item", s.daily_report_item_id),
|
||||||
|
"quantity": _dec(s.quantity),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for s in graph["ks2_item_sources"]
|
||||||
|
]
|
||||||
|
ks3 = [
|
||||||
|
record(
|
||||||
|
"ks3",
|
||||||
|
k,
|
||||||
|
{
|
||||||
|
"number": k.number,
|
||||||
|
"date": _iso(k.date),
|
||||||
|
"reporting_period_from": _iso(k.reporting_period_from),
|
||||||
|
"reporting_period_to": _iso(k.reporting_period_to),
|
||||||
|
"comment": k.comment,
|
||||||
|
"status": k.status,
|
||||||
|
"created_at": _iso(k.created_at),
|
||||||
|
"updated_at": _iso(k.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for k in graph["ks3"]
|
||||||
|
]
|
||||||
|
ks3_ks2 = [
|
||||||
|
record(
|
||||||
|
"ks3_ks2",
|
||||||
|
link,
|
||||||
|
{
|
||||||
|
"ks3_export_id": ref("ks3", link.ks3_id),
|
||||||
|
"ks2_export_id": ref("ks2", link.ks2_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for link in graph["ks3_ks2"]
|
||||||
|
]
|
||||||
|
payments = [
|
||||||
|
record(
|
||||||
|
"payment",
|
||||||
|
p,
|
||||||
|
{
|
||||||
|
"date": _iso(p.date),
|
||||||
|
"document_number": p.document_number,
|
||||||
|
"amount": _dec(p.amount),
|
||||||
|
"currency": p.currency,
|
||||||
|
"comment": p.comment,
|
||||||
|
"status": p.status,
|
||||||
|
"created_at": _iso(p.created_at),
|
||||||
|
"updated_at": _iso(p.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for p in graph["payments"]
|
||||||
|
]
|
||||||
|
payment_allocations = [
|
||||||
|
record(
|
||||||
|
"payment_allocation",
|
||||||
|
a,
|
||||||
|
{
|
||||||
|
"payment_export_id": ref("payment", a.payment_id),
|
||||||
|
"ks3_export_id": ref("ks3", a.ks3_id),
|
||||||
|
"amount": _dec(a.amount),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for a in graph["payment_allocations"]
|
||||||
|
]
|
||||||
|
work_journal_entries = [
|
||||||
|
record(
|
||||||
|
"work_journal_entry",
|
||||||
|
e,
|
||||||
|
{
|
||||||
|
"type": e.type,
|
||||||
|
"text": e.text,
|
||||||
|
"status": e.status,
|
||||||
|
"due_date": _iso(e.due_date),
|
||||||
|
"created_at": _iso(e.created_at),
|
||||||
|
"updated_at": _iso(e.updated_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for e in graph.get("work_journal_entries", [])
|
||||||
|
]
|
||||||
|
|
||||||
|
# Official artifacts (issued/cancelled KS-2/KS-3 only)
|
||||||
|
from app.services.document_artifact_service import compute_content_hash
|
||||||
|
from app.config import document_storage_root
|
||||||
|
|
||||||
|
eligible = graph.get("eligible_doc_ids", {})
|
||||||
|
ks2_map = keys["ks2"]
|
||||||
|
ks3_map = keys["ks3"]
|
||||||
|
document_artifacts_records = []
|
||||||
|
artifact_blobs: dict[str, bytes] = {}
|
||||||
|
storage_root = document_storage_root()
|
||||||
|
|
||||||
|
for art in graph.get("document_artifacts", []):
|
||||||
|
if art.document_type == "KS2":
|
||||||
|
eligible_ids = eligible.get("KS2", set())
|
||||||
|
doc_export_id = ks2_map.get(art.document_id)
|
||||||
|
elif art.document_type == "KS3":
|
||||||
|
eligible_ids = eligible.get("KS3", set())
|
||||||
|
doc_export_id = ks3_map.get(art.document_id)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
# Only issued/cancelled documents
|
||||||
|
if art.document_id not in eligible_ids:
|
||||||
|
continue
|
||||||
|
if doc_export_id is None:
|
||||||
|
raise ProjectExportError(
|
||||||
|
f"Artifact {art.id} references unknown document {art.document_type}:{art.document_id}"
|
||||||
|
)
|
||||||
|
# Physical file must exist and match content_hash
|
||||||
|
from app.services.document_artifact_service import resolve_storage_path
|
||||||
|
|
||||||
|
file_path = resolve_storage_path(art.storage_key)
|
||||||
|
if not file_path.is_file():
|
||||||
|
raise ProjectExportError(
|
||||||
|
f"Artifact file not found for {art.document_type}:{art.document_id} ({art.format})"
|
||||||
|
)
|
||||||
|
file_bytes = file_path.read_bytes()
|
||||||
|
actual_hash = compute_content_hash(file_bytes)
|
||||||
|
if actual_hash != art.content_hash:
|
||||||
|
raise ProjectExportError(
|
||||||
|
f"Artifact file hash mismatch for {art.document_type}:{art.document_id}"
|
||||||
|
)
|
||||||
|
ext = "xlsx" if art.format == "xlsx" else "docx" if art.format == "docx" else art.format
|
||||||
|
archive_path = f"artifacts/{art.document_type.lower()}/{art.id}.{ext}"
|
||||||
|
artifact_blobs[archive_path] = file_bytes
|
||||||
|
document_artifacts_records.append({
|
||||||
|
"export_id": f"document_artifact:{art.id:08d}",
|
||||||
|
"source_id": art.id,
|
||||||
|
"document_type": art.document_type,
|
||||||
|
"document_export_id": doc_export_id,
|
||||||
|
"format": art.format,
|
||||||
|
"template_type": art.template_type,
|
||||||
|
"template_version": art.template_version,
|
||||||
|
"content_hash": art.content_hash,
|
||||||
|
"input_hash": art.input_hash,
|
||||||
|
"is_current": bool(art.is_current),
|
||||||
|
"generated_at": _iso(art.generated_at),
|
||||||
|
"archive_path": archive_path,
|
||||||
|
})
|
||||||
|
|
||||||
|
counts = {
|
||||||
|
"boq_documents": len(boq_documents),
|
||||||
|
"systems": len(systems),
|
||||||
|
"sections": len(sections),
|
||||||
|
"work_items": len(work_items),
|
||||||
|
"agreements": len(agreements),
|
||||||
|
"agreement_items": len(agreement_items),
|
||||||
|
"daily_reports": len(daily_reports),
|
||||||
|
"daily_report_items": len(daily_report_items),
|
||||||
|
"daily_report_photos": len(daily_report_photo_records),
|
||||||
|
"ks2": len(ks2),
|
||||||
|
"ks2_items": len(ks2_items),
|
||||||
|
"ks2_item_sources": len(ks2_item_sources),
|
||||||
|
"ks3": len(ks3),
|
||||||
|
"ks3_ks2": len(ks3_ks2),
|
||||||
|
"payments": len(payments),
|
||||||
|
"payment_allocations": len(payment_allocations),
|
||||||
|
"work_journal_entries": len(work_journal_entries),
|
||||||
|
"document_artifacts": len(document_artifacts_records),
|
||||||
|
}
|
||||||
|
manifest = {
|
||||||
|
"format": FORMAT_NAME,
|
||||||
|
"format_version": FORMAT_VERSION,
|
||||||
|
"exported_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"source_project_id": project.id,
|
||||||
|
"project_name": project.name,
|
||||||
|
"counts": counts,
|
||||||
|
}
|
||||||
|
|
||||||
|
files = {
|
||||||
|
"manifest.json": manifest,
|
||||||
|
"project.json": project_record,
|
||||||
|
"boq_documents.json": boq_documents,
|
||||||
|
"systems.json": systems,
|
||||||
|
"sections.json": sections,
|
||||||
|
"work_items.json": work_items,
|
||||||
|
"agreements.json": agreements,
|
||||||
|
"agreement_items.json": agreement_items,
|
||||||
|
"daily_reports.json": daily_reports,
|
||||||
|
"daily_report_items.json": daily_report_items,
|
||||||
|
"daily_report_photos.json": daily_report_photo_records,
|
||||||
|
"ks2.json": ks2,
|
||||||
|
"ks2_items.json": ks2_items,
|
||||||
|
"ks2_item_sources.json": ks2_item_sources,
|
||||||
|
"ks3.json": ks3,
|
||||||
|
"ks3_ks2.json": ks3_ks2,
|
||||||
|
"payments.json": payments,
|
||||||
|
"payment_allocations.json": payment_allocations,
|
||||||
|
"work_journal_entries.json": work_journal_entries,
|
||||||
|
"document_artifacts.json": document_artifacts_records,
|
||||||
|
}
|
||||||
|
artifact_blobs.update(photo_blobs)
|
||||||
|
return {**files, "__artifact_blobs__": artifact_blobs}
|
||||||
|
|
||||||
|
|
||||||
|
def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
|
||||||
|
"""Serialize payload dict to a ZIP with checksums. Returns (zip_bytes, filename)."""
|
||||||
|
artifact_blobs = files.pop("__artifact_blobs__", {}) if "__artifact_blobs__" in files else {}
|
||||||
|
parts: dict[str, bytes] = {}
|
||||||
|
for name, payload in files.items():
|
||||||
|
if name == "__artifact_blobs__":
|
||||||
|
continue
|
||||||
|
if isinstance(payload, bytes):
|
||||||
|
parts[name] = payload
|
||||||
|
else:
|
||||||
|
parts[name] = _dumps(payload)
|
||||||
|
# Physical artifact files
|
||||||
|
for path, data in artifact_blobs.items():
|
||||||
|
parts[path] = data
|
||||||
|
checksums = {name: _sha256(data) for name, data in parts.items()}
|
||||||
|
parts["checksums.json"] = _dumps(checksums)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for name in EXPORT_FILES:
|
||||||
|
if name not in parts:
|
||||||
|
raise ProjectExportError(f"В архиве отсутствует обязательный файл {name}")
|
||||||
|
zf.writestr(name, parts[name])
|
||||||
|
# Physical artifacts (always present if collected)
|
||||||
|
for path in sorted(artifact_blobs.keys()):
|
||||||
|
zf.writestr(path, artifact_blobs[path])
|
||||||
|
project_name = files.get("manifest.json", {}).get("project_name", "проект")
|
||||||
|
return buf.getvalue(), _safe_archive_filename(project_name)
|
||||||
|
|
||||||
|
|
||||||
|
def export_project(db: Session, project_id: int) -> tuple[bytes, str]:
|
||||||
|
"""Full export pipeline. Returns (zip_bytes, filename)."""
|
||||||
|
graph = collect_project(db, project_id)
|
||||||
|
_validate_graph(graph)
|
||||||
|
files = serialize_project(graph)
|
||||||
|
return build_archive(files)
|
||||||
@@ -0,0 +1,929 @@
|
|||||||
|
"""Validate and import a project archive produced by project_export."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import zipfile
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.work_journal import WorkJournalEntry
|
||||||
|
from app.models.document_artifact import DocumentArtifact
|
||||||
|
from app.exporters.project_export import (
|
||||||
|
FORMAT_NAME,
|
||||||
|
FORMAT_VERSION,
|
||||||
|
OPTIONAL_FILES,
|
||||||
|
REQUIRED_FILES,
|
||||||
|
ProjectExportError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectImportError(ValueError):
|
||||||
|
"""Archive failed validation and was not imported."""
|
||||||
|
|
||||||
|
|
||||||
|
_LIST_FILES = (
|
||||||
|
"boq_documents.json",
|
||||||
|
"systems.json",
|
||||||
|
"sections.json",
|
||||||
|
"work_items.json",
|
||||||
|
"agreements.json",
|
||||||
|
"agreement_items.json",
|
||||||
|
"daily_reports.json",
|
||||||
|
"daily_report_items.json",
|
||||||
|
"ks2.json",
|
||||||
|
"ks2_items.json",
|
||||||
|
"ks2_item_sources.json",
|
||||||
|
"ks3.json",
|
||||||
|
"ks3_ks2.json",
|
||||||
|
"payments.json",
|
||||||
|
"payment_allocations.json",
|
||||||
|
"work_journal_entries.json",
|
||||||
|
"document_artifacts.json",
|
||||||
|
"daily_report_photos.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"}
|
||||||
|
_ALLOWED_AGREEMENT_CHANGE = {"increase", "decrease", "new_position"}
|
||||||
|
_ALLOWED_KS2_STATUS = {"draft", "issued", "cancelled"}
|
||||||
|
_ALLOWED_KS3_STATUS = {"draft", "issued", "cancelled"}
|
||||||
|
_ALLOWED_PAYMENT_STATUS = {"active", "cancelled"}
|
||||||
|
|
||||||
|
_REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
|
||||||
|
"project.json": ("export_id", "name", "status"),
|
||||||
|
"boq_documents.json": ("export_id", "name"),
|
||||||
|
"systems.json": ("export_id", "name"),
|
||||||
|
"sections.json": ("export_id", "system_export_id", "name"),
|
||||||
|
"work_items.json": ("export_id", "name"),
|
||||||
|
"agreements.json": ("export_id", "number", "date", "title", "status"),
|
||||||
|
"agreement_items.json": ("export_id", "agreement_export_id", "work_item_export_id", "change_type", "quantity_delta", "amount_delta"),
|
||||||
|
"daily_reports.json": ("export_id", "report_date"),
|
||||||
|
"daily_report_items.json": ("export_id", "daily_report_export_id", "work_item_export_id", "completed_quantity"),
|
||||||
|
"ks2.json": ("export_id", "number", "date", "status"),
|
||||||
|
"ks2_items.json": ("export_id", "ks2_export_id", "work_item_export_id", "quantity", "unit_price", "amount"),
|
||||||
|
"ks2_item_sources.json": ("export_id", "ks2_item_export_id", "daily_report_item_export_id", "quantity"),
|
||||||
|
"ks3.json": ("export_id", "number", "date", "status"),
|
||||||
|
"ks3_ks2.json": ("export_id", "ks3_export_id", "ks2_export_id"),
|
||||||
|
"payments.json": ("export_id", "date", "amount", "currency", "status"),
|
||||||
|
"payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"),
|
||||||
|
"work_journal_entries.json": ("export_id", "type", "text"),
|
||||||
|
"document_artifacts.json": ("export_id", "document_type", "document_export_id", "format", "content_hash", "archive_path"),
|
||||||
|
"daily_report_photos.json": ("export_id", "daily_report_export_id", "content_type", "file_size", "content_hash", "archive_path"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(data: bytes) -> str:
|
||||||
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(value: Any, field: str) -> date | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(str(value)[:10])
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise ProjectImportError(f"Поле {field}: некорректная дата {value!r}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_datetime(value: Any, field: str) -> datetime | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(str(value))
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise ProjectImportError(f"Поле {field}: некорректное время {value!r}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_decimal(value: Any, field: str, *, required: bool = False) -> Decimal | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
if required:
|
||||||
|
raise ProjectImportError(f"Поле {field}: значение обязательно")
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return Decimal(str(value))
|
||||||
|
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||||
|
raise ProjectImportError(f"Поле {field}: некорректное число {value!r}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _require_mapping(ref: str | None, mapping: dict[str, int], field: str) -> int:
|
||||||
|
if not ref:
|
||||||
|
raise ProjectImportError(f"Поле {field}: ссылка export_id отсутствует")
|
||||||
|
if ref not in mapping:
|
||||||
|
raise ProjectImportError(f"Поле {field}: неизвестная ссылка {ref!r}")
|
||||||
|
return mapping[ref]
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_mapping(ref: str | None, mapping: dict[str, int], field: str) -> int | None:
|
||||||
|
if ref is None or ref == "":
|
||||||
|
return None
|
||||||
|
return _require_mapping(ref, mapping, field)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_archive(data: bytes) -> dict[str, Any]:
|
||||||
|
"""Read + checksum + JSON-validate the archive without touching the DB."""
|
||||||
|
try:
|
||||||
|
zf = zipfile.ZipFile(io.BytesIO(data), "r")
|
||||||
|
except zipfile.BadZipFile as exc:
|
||||||
|
raise ProjectImportError("Файл не является корректным ZIP-архивом") from exc
|
||||||
|
|
||||||
|
with zf:
|
||||||
|
names = set(zf.namelist())
|
||||||
|
missing = [n for n in REQUIRED_FILES if n not in names]
|
||||||
|
if missing:
|
||||||
|
raise ProjectImportError(f"В архиве отсутствуют файлы: {', '.join(missing)}")
|
||||||
|
|
||||||
|
wanted = [n for n in REQUIRED_FILES] + [n for n in OPTIONAL_FILES if n in names]
|
||||||
|
raw: dict[str, bytes] = {n: zf.read(n) for n in wanted}
|
||||||
|
# Physical artifact files (any path under artifacts/)
|
||||||
|
artifact_files: dict[str, bytes] = {}
|
||||||
|
for name in names:
|
||||||
|
if name.startswith("artifacts/") and not name.endswith("/"):
|
||||||
|
artifact_files[name] = zf.read(name)
|
||||||
|
# Daily Report photo files (any path under photos/)
|
||||||
|
photo_files: dict[str, bytes] = {}
|
||||||
|
for name in names:
|
||||||
|
if name.startswith("photos/") and not name.endswith("/"):
|
||||||
|
photo_files[name] = zf.read(name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||||
|
raise ProjectImportError("checksums.json повреждён") from exc
|
||||||
|
if not isinstance(checksums, dict):
|
||||||
|
raise ProjectImportError("checksums.json: ожидается объект")
|
||||||
|
|
||||||
|
for name, body in raw.items():
|
||||||
|
if name == "checksums.json":
|
||||||
|
continue
|
||||||
|
expected = checksums.get(name)
|
||||||
|
actual = _sha256(body)
|
||||||
|
if expected != actual:
|
||||||
|
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||||
|
|
||||||
|
# Validate artifact file checksums too
|
||||||
|
for name, body in artifact_files.items():
|
||||||
|
expected = checksums.get(name)
|
||||||
|
actual = _sha256(body)
|
||||||
|
if expected != actual:
|
||||||
|
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||||
|
|
||||||
|
# Validate photo file checksums too
|
||||||
|
for name, body in photo_files.items():
|
||||||
|
expected = checksums.get(name)
|
||||||
|
actual = _sha256(body)
|
||||||
|
if expected != actual:
|
||||||
|
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||||
|
|
||||||
|
payload: dict[str, Any] = {}
|
||||||
|
for name, body in raw.items():
|
||||||
|
if name == "checksums.json":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
payload[name] = json.loads(body.decode("utf-8"))
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||||
|
raise ProjectImportError(f"{name}: некорректный JSON") from exc
|
||||||
|
|
||||||
|
# Backward compatibility: old Task 025 archives have no work journal file.
|
||||||
|
missing_optional = set()
|
||||||
|
if "work_journal_entries.json" not in payload:
|
||||||
|
payload["work_journal_entries.json"] = []
|
||||||
|
missing_optional.add("work_journal_entries.json")
|
||||||
|
|
||||||
|
# Backward compatibility: old archives have no document artifacts.
|
||||||
|
if "document_artifacts.json" not in payload:
|
||||||
|
payload["document_artifacts.json"] = []
|
||||||
|
missing_optional.add("document_artifacts.json")
|
||||||
|
|
||||||
|
# Backward compatibility: old archives have no Daily Report photos.
|
||||||
|
if "daily_report_photos.json" not in payload:
|
||||||
|
payload["daily_report_photos.json"] = []
|
||||||
|
missing_optional.add("daily_report_photos.json")
|
||||||
|
|
||||||
|
manifest = payload.get("manifest.json")
|
||||||
|
if not isinstance(manifest, dict):
|
||||||
|
raise ProjectImportError("manifest.json: ожидается объект")
|
||||||
|
if manifest.get("format") != FORMAT_NAME:
|
||||||
|
raise ProjectImportError(f"Неизвестный format: {manifest.get('format')!r}")
|
||||||
|
if manifest.get("format_version") != FORMAT_VERSION:
|
||||||
|
raise ProjectImportError(
|
||||||
|
f"Неподдерживаемая format_version: {manifest.get('format_version')!r}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not isinstance(payload.get("project.json"), dict):
|
||||||
|
raise ProjectImportError("project.json: ожидается объект")
|
||||||
|
for name in _LIST_FILES:
|
||||||
|
if not isinstance(payload.get(name), list):
|
||||||
|
raise ProjectImportError(f"{name}: ожидается массив")
|
||||||
|
|
||||||
|
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional,
|
||||||
|
"artifact_files": artifact_files, "photo_files": photo_files}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_records(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
manifest: dict[str, Any],
|
||||||
|
missing_optional: set[str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Validate required fields, types, statuses, and internal export_id links."""
|
||||||
|
missing_optional = missing_optional or set()
|
||||||
|
project = payload["project.json"]
|
||||||
|
for field in _REQUIRED_FIELDS["project.json"]:
|
||||||
|
if field not in project:
|
||||||
|
raise ProjectImportError(f"project.json: нет поля {field}")
|
||||||
|
|
||||||
|
export_ids: dict[str, set[str]] = {}
|
||||||
|
for name in _LIST_FILES:
|
||||||
|
required = _REQUIRED_FIELDS[name]
|
||||||
|
ids: set[str] = set()
|
||||||
|
for idx, row in enumerate(payload[name], start=1):
|
||||||
|
if not isinstance(row, dict):
|
||||||
|
raise ProjectImportError(f"{name}[{idx}]: ожидается объект")
|
||||||
|
for field in required:
|
||||||
|
if field not in row:
|
||||||
|
raise ProjectImportError(f"{name}[{idx}]: нет поля {field}")
|
||||||
|
eid = row["export_id"]
|
||||||
|
if not isinstance(eid, str) or not eid:
|
||||||
|
raise ProjectImportError(f"{name}[{idx}]: некорректный export_id")
|
||||||
|
if eid in ids:
|
||||||
|
raise ProjectImportError(f"{name}: дублирующийся export_id {eid!r}")
|
||||||
|
ids.add(eid)
|
||||||
|
export_ids[name] = ids
|
||||||
|
|
||||||
|
# Counts vs manifest
|
||||||
|
counts = manifest.get("counts")
|
||||||
|
if isinstance(counts, dict):
|
||||||
|
name_to_key = {
|
||||||
|
"boq_documents.json": "boq_documents",
|
||||||
|
"systems.json": "systems",
|
||||||
|
"sections.json": "sections",
|
||||||
|
"work_items.json": "work_items",
|
||||||
|
"agreements.json": "agreements",
|
||||||
|
"agreement_items.json": "agreement_items",
|
||||||
|
"daily_reports.json": "daily_reports",
|
||||||
|
"daily_report_items.json": "daily_report_items",
|
||||||
|
"ks2.json": "ks2",
|
||||||
|
"ks2_items.json": "ks2_items",
|
||||||
|
"ks2_item_sources.json": "ks2_item_sources",
|
||||||
|
"ks3.json": "ks3",
|
||||||
|
"ks3_ks2.json": "ks3_ks2",
|
||||||
|
"payments.json": "payments",
|
||||||
|
"payment_allocations.json": "payment_allocations",
|
||||||
|
"work_journal_entries.json": "work_journal_entries",
|
||||||
|
}
|
||||||
|
for name, key in name_to_key.items():
|
||||||
|
# Old manifests may omit work_journal_entries — treat as 0.
|
||||||
|
if key == "work_journal_entries":
|
||||||
|
if name in missing_optional:
|
||||||
|
continue
|
||||||
|
expected = counts.get(key, 0)
|
||||||
|
actual = len(payload.get(name, []))
|
||||||
|
if expected != actual:
|
||||||
|
raise ProjectImportError(
|
||||||
|
f"Количество записей {key} не совпадает с manifest: "
|
||||||
|
f"{expected} != {actual}"
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
if key not in counts:
|
||||||
|
continue
|
||||||
|
if counts[key] != len(payload[name]):
|
||||||
|
raise ProjectImportError(
|
||||||
|
f"Количество записей {key} не совпадает с manifest: "
|
||||||
|
f"{counts[key]} != {len(payload[name])}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Statuses and value ranges
|
||||||
|
for row in payload["agreements.json"]:
|
||||||
|
if row["status"] not in _ALLOWED_AGREEMENT_STATUS:
|
||||||
|
raise ProjectImportError(f"agreements: недопустимый status {row['status']!r}")
|
||||||
|
for row in payload["agreement_items.json"]:
|
||||||
|
if row["change_type"] not in _ALLOWED_AGREEMENT_CHANGE:
|
||||||
|
raise ProjectImportError(f"agreement_items: недопустимый change_type {row['change_type']!r}")
|
||||||
|
qd = _parse_decimal(row.get("quantity_delta"), "quantity_delta", required=True)
|
||||||
|
if row["change_type"] == "decrease" and qd >= 0:
|
||||||
|
raise ProjectImportError("agreement_items: для decrease quantity_delta должен быть < 0")
|
||||||
|
if row["change_type"] in ("increase", "new_position") and qd <= 0:
|
||||||
|
raise ProjectImportError("agreement_items: quantity_delta должен быть > 0")
|
||||||
|
for row in payload["daily_report_items.json"]:
|
||||||
|
q = _parse_decimal(row.get("completed_quantity"), "completed_quantity", required=True)
|
||||||
|
if q < 0:
|
||||||
|
raise ProjectImportError("daily_report_items: completed_quantity не может быть отрицательным")
|
||||||
|
for row in payload["ks2.json"]:
|
||||||
|
if row["status"] not in _ALLOWED_KS2_STATUS:
|
||||||
|
raise ProjectImportError(f"ks2: недопустимый status {row['status']!r}")
|
||||||
|
for row in payload["ks2_items.json"]:
|
||||||
|
if _parse_decimal(row.get("quantity"), "quantity", required=True) <= 0:
|
||||||
|
raise ProjectImportError("ks2_items: quantity должен быть > 0")
|
||||||
|
for row in payload["ks2_item_sources.json"]:
|
||||||
|
if _parse_decimal(row.get("quantity"), "quantity", required=True) <= 0:
|
||||||
|
raise ProjectImportError("ks2_item_sources: quantity должен быть > 0")
|
||||||
|
for row in payload["ks3.json"]:
|
||||||
|
if row["status"] not in _ALLOWED_KS3_STATUS:
|
||||||
|
raise ProjectImportError(f"ks3: недопустимый status {row['status']!r}")
|
||||||
|
for row in payload["payments.json"]:
|
||||||
|
if row["status"] not in _ALLOWED_PAYMENT_STATUS:
|
||||||
|
raise ProjectImportError(f"payments: недопустимый status {row['status']!r}")
|
||||||
|
if _parse_decimal(row.get("amount"), "amount", required=True) <= 0:
|
||||||
|
raise ProjectImportError("payments: amount должен быть > 0")
|
||||||
|
for row in payload["payment_allocations.json"]:
|
||||||
|
if _parse_decimal(row.get("amount"), "amount", required=True) <= 0:
|
||||||
|
raise ProjectImportError("payment_allocations: amount должен быть > 0")
|
||||||
|
|
||||||
|
# Validate document_artifacts.json
|
||||||
|
ks2_ids = {r["export_id"] for r in payload["ks2.json"]}
|
||||||
|
ks3_ids = {r["export_id"] for r in payload["ks3.json"]}
|
||||||
|
ks2_status = {r["export_id"]: r["status"] for r in payload["ks2.json"]}
|
||||||
|
ks3_status = {r["export_id"]: r["status"] for r in payload["ks3.json"]}
|
||||||
|
allowed_doc_ids = ks2_ids | ks3_ids
|
||||||
|
allowed_statuses = {"issued", "cancelled"}
|
||||||
|
art_required = ("export_id", "document_type", "document_export_id", "format",
|
||||||
|
"template_type", "template_version", "content_hash", "input_hash",
|
||||||
|
"archive_path")
|
||||||
|
for idx, row in enumerate(payload.get("document_artifacts.json", []), start=1):
|
||||||
|
for field in art_required:
|
||||||
|
if field not in row:
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: нет поля {field}")
|
||||||
|
if row["document_type"] not in ("KS2", "KS3"):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый document_type")
|
||||||
|
if row["format"] not in ("xlsx", "docx"):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый format")
|
||||||
|
if not isinstance(row["template_version"], int):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: template_version должен быть числом")
|
||||||
|
for hf in ("content_hash", "input_hash"):
|
||||||
|
h = row[hf]
|
||||||
|
if not isinstance(h, str) or len(h) != 64:
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: {hf} должен быть SHA-256 (64 символа)")
|
||||||
|
# document_export_id must reference issued/cancelled KS-2/KS-3
|
||||||
|
deid = row["document_export_id"]
|
||||||
|
if deid not in allowed_doc_ids:
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: неизвестный document_export_id {deid!r}")
|
||||||
|
status = ks2_status.get(deid) or ks3_status.get(deid)
|
||||||
|
if status not in allowed_statuses:
|
||||||
|
raise ProjectImportError(
|
||||||
|
f"document_artifacts[{idx}]: artifact может относиться только к issued/cancelled документу"
|
||||||
|
)
|
||||||
|
# archive_path must be safe and under artifacts/
|
||||||
|
ap = row["archive_path"].replace("\\", "/")
|
||||||
|
if not ap.startswith("artifacts/") or ".." in ap.split("/") or ap.startswith("/"):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: небезопасный archive_path")
|
||||||
|
if row["format"] == "xlsx" and not ap.endswith(".xlsx"):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
|
||||||
|
if row["format"] == "docx" and not ap.endswith(".docx"):
|
||||||
|
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
|
||||||
|
|
||||||
|
# Internal export_id references
|
||||||
|
def has(name: str, eid: str) -> bool:
|
||||||
|
return eid in export_ids.get(name, set())
|
||||||
|
|
||||||
|
for row in payload["boq_documents.json"]:
|
||||||
|
if row.get("agreement_export_id") and not has("agreements.json", row["agreement_export_id"]):
|
||||||
|
raise ProjectImportError(f"boq_documents: битая ссылка {row['agreement_export_id']!r}")
|
||||||
|
for row in payload["sections.json"]:
|
||||||
|
if not has("systems.json", row["system_export_id"]):
|
||||||
|
raise ProjectImportError(f"sections: битая ссылка на system {row['system_export_id']!r}")
|
||||||
|
for row in payload["work_items.json"]:
|
||||||
|
for field, name in (
|
||||||
|
("boq_document_export_id", "boq_documents.json"),
|
||||||
|
("system_export_id", "systems.json"),
|
||||||
|
("section_export_id", "sections.json"),
|
||||||
|
):
|
||||||
|
ref = row.get(field)
|
||||||
|
if ref and not has(name, ref):
|
||||||
|
raise ProjectImportError(f"work_items: битая ссылка {field}={ref!r}")
|
||||||
|
for row in payload["agreements.json"]:
|
||||||
|
if row.get("boq_document_export_id") and not has("boq_documents.json", row["boq_document_export_id"]):
|
||||||
|
raise ProjectImportError(f"agreements: битая ссылка {row['boq_document_export_id']!r}")
|
||||||
|
for row in payload["agreement_items.json"]:
|
||||||
|
if not has("agreements.json", row["agreement_export_id"]):
|
||||||
|
raise ProjectImportError(f"agreement_items: битая ссылка на agreement")
|
||||||
|
if not has("work_items.json", row["work_item_export_id"]):
|
||||||
|
raise ProjectImportError(f"agreement_items: битая ссылка на work_item")
|
||||||
|
for row in payload["daily_reports.json"]:
|
||||||
|
if row.get("system_export_id") and not has("systems.json", row["system_export_id"]):
|
||||||
|
raise ProjectImportError(f"daily_reports: битая ссылка на system")
|
||||||
|
for row in payload["daily_report_items.json"]:
|
||||||
|
if not has("daily_reports.json", row["daily_report_export_id"]):
|
||||||
|
raise ProjectImportError("daily_report_items: битая ссылка на daily_report")
|
||||||
|
if not has("work_items.json", row["work_item_export_id"]):
|
||||||
|
raise ProjectImportError("daily_report_items: битая ссылка на work_item")
|
||||||
|
for idx, row in enumerate(payload.get("daily_report_photos.json", []), 1):
|
||||||
|
for field in _REQUIRED_FIELDS["daily_report_photos.json"]:
|
||||||
|
if field not in row:
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: нет поля {field}")
|
||||||
|
if not has("daily_reports.json", row["daily_report_export_id"]):
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: битая ссылка на daily_report")
|
||||||
|
if not isinstance(row["file_size"], int) or row["file_size"] <= 0:
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size должен быть положительным числом")
|
||||||
|
h = row["content_hash"]
|
||||||
|
if not isinstance(h, str) or len(h) != 64:
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: content_hash должен быть SHA-256 (64 символа)")
|
||||||
|
for row in payload["ks2_items.json"]:
|
||||||
|
if not has("ks2.json", row["ks2_export_id"]):
|
||||||
|
raise ProjectImportError("ks2_items: битая ссылка на ks2")
|
||||||
|
if not has("work_items.json", row["work_item_export_id"]):
|
||||||
|
raise ProjectImportError("ks2_items: битая ссылка на work_item")
|
||||||
|
for row in payload["ks2_item_sources.json"]:
|
||||||
|
if not has("ks2_items.json", row["ks2_item_export_id"]):
|
||||||
|
raise ProjectImportError("ks2_item_sources: битая ссылка на ks2_item")
|
||||||
|
if not has("daily_report_items.json", row["daily_report_item_export_id"]):
|
||||||
|
raise ProjectImportError("ks2_item_sources: битая ссылка на daily_report_item")
|
||||||
|
for row in payload["ks3_ks2.json"]:
|
||||||
|
if not has("ks3.json", row["ks3_export_id"]):
|
||||||
|
raise ProjectImportError("ks3_ks2: битая ссылка на ks3")
|
||||||
|
if not has("ks2.json", row["ks2_export_id"]):
|
||||||
|
raise ProjectImportError("ks3_ks2: битая ссылка на ks2")
|
||||||
|
for row in payload["payment_allocations.json"]:
|
||||||
|
if not has("payments.json", row["payment_export_id"]):
|
||||||
|
raise ProjectImportError("payment_allocations: битая ссылка на payment")
|
||||||
|
if not has("ks3.json", row["ks3_export_id"]):
|
||||||
|
raise ProjectImportError("payment_allocations: битая ссылка на ks3")
|
||||||
|
|
||||||
|
# Unique numbers inside the imported project
|
||||||
|
for label, rows, field in (
|
||||||
|
("agreements", payload["agreements.json"], "number"),
|
||||||
|
("ks2", payload["ks2.json"], "number"),
|
||||||
|
("ks3", payload["ks3.json"], "number"),
|
||||||
|
):
|
||||||
|
seen: set[str] = set()
|
||||||
|
for row in rows:
|
||||||
|
num = row.get(field)
|
||||||
|
if num is None:
|
||||||
|
continue
|
||||||
|
if num in seen:
|
||||||
|
raise ProjectImportError(f"{label}: дублирующийся номер {num!r}")
|
||||||
|
seen.add(num)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_archive(data: bytes) -> dict[str, Any]:
|
||||||
|
"""Full archive validation. Returns parsed payload for UI preview."""
|
||||||
|
result = _read_archive(data)
|
||||||
|
payload = result["payload"]
|
||||||
|
manifest = result["manifest"]
|
||||||
|
artifact_files = result.get("artifact_files", {})
|
||||||
|
_validate_records(payload, manifest, result.get("missing_optional"))
|
||||||
|
|
||||||
|
# Validate artifact files against document_artifacts.json
|
||||||
|
art_rows = payload.get("document_artifacts.json", [])
|
||||||
|
art_paths = {r["archive_path"] for r in art_rows}
|
||||||
|
for row in art_rows:
|
||||||
|
ap = row["archive_path"]
|
||||||
|
if ap not in artifact_files:
|
||||||
|
raise ProjectImportError(f"Artifact file missing in archive: {ap}")
|
||||||
|
from app.services.document_artifact_service import compute_content_hash
|
||||||
|
actual = compute_content_hash(artifact_files[ap])
|
||||||
|
if actual != row["content_hash"]:
|
||||||
|
raise ProjectImportError(f"Artifact hash mismatch for {ap}")
|
||||||
|
# No orphan artifact references
|
||||||
|
for ap in artifact_files:
|
||||||
|
if ap not in art_paths:
|
||||||
|
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
|
||||||
|
|
||||||
|
# Validate photo files against daily_report_photos.json
|
||||||
|
photo_files = result.get("photo_files", {})
|
||||||
|
photo_rows = payload.get("daily_report_photos.json", [])
|
||||||
|
photo_paths = {r["archive_path"] for r in photo_rows}
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
ALLOWED_CONTENT_TYPES,
|
||||||
|
MAX_PHOTO_BYTES,
|
||||||
|
compute_content_hash as photo_hash,
|
||||||
|
)
|
||||||
|
for idx, row in enumerate(photo_rows, 1):
|
||||||
|
ap = row["archive_path"]
|
||||||
|
if not isinstance(ap, str) or not ap.startswith("photos/") or ".." in ap.split("/") or ap.startswith("/"):
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: небезопасный archive_path")
|
||||||
|
if ap not in photo_files:
|
||||||
|
raise ProjectImportError(f"Photo file missing in archive: {ap}")
|
||||||
|
body = photo_files[ap]
|
||||||
|
if len(body) > MAX_PHOTO_BYTES:
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: файл превышает лимит размера")
|
||||||
|
if photo_hash(body) != row["content_hash"]:
|
||||||
|
raise ProjectImportError(f"Photo hash mismatch for {ap}")
|
||||||
|
if int(row.get("file_size") or 0) != len(body):
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size не совпадает с содержимым")
|
||||||
|
if row["content_type"] not in ALLOWED_CONTENT_TYPES:
|
||||||
|
raise ProjectImportError(f"daily_report_photos[{idx}]: недопустимый content_type")
|
||||||
|
# No orphan photo files
|
||||||
|
for ap in photo_files:
|
||||||
|
if ap not in photo_paths:
|
||||||
|
raise ProjectImportError(f"Orphan photo file in archive: {ap}")
|
||||||
|
|
||||||
|
counts = dict(manifest.get("counts") or {})
|
||||||
|
if "work_journal_entries.json" in result.get("missing_optional", set()):
|
||||||
|
counts["work_journal_entries"] = 0
|
||||||
|
else:
|
||||||
|
counts.setdefault("work_journal_entries", len(payload.get("work_journal_entries.json", [])))
|
||||||
|
if "document_artifacts.json" in result.get("missing_optional", set()):
|
||||||
|
counts["document_artifacts"] = 0
|
||||||
|
else:
|
||||||
|
counts.setdefault("document_artifacts", len(art_rows))
|
||||||
|
if "daily_report_photos.json" in result.get("missing_optional", set()):
|
||||||
|
counts["daily_report_photos"] = 0
|
||||||
|
else:
|
||||||
|
counts.setdefault("daily_report_photos", len(photo_rows))
|
||||||
|
return {
|
||||||
|
"manifest": manifest,
|
||||||
|
"project_name": payload["project.json"].get("name"),
|
||||||
|
"project": payload["project.json"],
|
||||||
|
"counts": counts,
|
||||||
|
"payload": payload,
|
||||||
|
"artifact_files": artifact_files,
|
||||||
|
"photo_files": photo_files,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
|
||||||
|
"""Insert the whole graph in one transaction. Raises on any error."""
|
||||||
|
src = payload["project.json"]
|
||||||
|
project = Project(
|
||||||
|
name=src["name"],
|
||||||
|
contract_number=src.get("contract_number"),
|
||||||
|
contract_date=_parse_date(src.get("contract_date"), "contract_date"),
|
||||||
|
customer=src.get("customer"),
|
||||||
|
currency=src.get("currency") or "RUB",
|
||||||
|
start_date=_parse_date(src.get("start_date"), "start_date"),
|
||||||
|
end_date=_parse_date(src.get("end_date"), "end_date"),
|
||||||
|
status=src.get("status") or "active",
|
||||||
|
investor_name=src.get("investor_name"),
|
||||||
|
customer_name=src.get("customer_name") or src.get("customer"),
|
||||||
|
contractor_name=src.get("contractor_name"),
|
||||||
|
construction_name=src.get("construction_name"),
|
||||||
|
object_name=src.get("object_name"),
|
||||||
|
contract_amount=_parse_decimal(src.get("contract_amount"), "contract_amount"),
|
||||||
|
contractor_signer_name=src.get("contractor_signer_name"),
|
||||||
|
contractor_signer_position=src.get("contractor_signer_position"),
|
||||||
|
customer_signer_name=src.get("customer_signer_name"),
|
||||||
|
customer_signer_position=src.get("customer_signer_position"),
|
||||||
|
)
|
||||||
|
db.add(project)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
ids: dict[str, int] = {src["export_id"]: project.id}
|
||||||
|
|
||||||
|
# BOQ documents (agreement FK filled after agreements)
|
||||||
|
boq_agreement_refs: dict[int, str | None] = {}
|
||||||
|
for row in payload["boq_documents.json"]:
|
||||||
|
obj = BoqDocument(
|
||||||
|
project_id=project.id,
|
||||||
|
name=row["name"],
|
||||||
|
version=row.get("version"),
|
||||||
|
source_file=row.get("source_file"),
|
||||||
|
document_number=row.get("document_number"),
|
||||||
|
document_date=_parse_date(row.get("document_date"), "document_date"),
|
||||||
|
contract=row.get("contract"),
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
boq_agreement_refs[obj.id] = row.get("agreement_export_id")
|
||||||
|
|
||||||
|
for row in payload["systems.json"]:
|
||||||
|
obj = System(
|
||||||
|
project_id=project.id,
|
||||||
|
code=row.get("code"),
|
||||||
|
name=row["name"],
|
||||||
|
sort_order=row.get("sort_order") or 0,
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["sections.json"]:
|
||||||
|
obj = Section(
|
||||||
|
system_id=_require_mapping(row["system_export_id"], ids, "system_export_id"),
|
||||||
|
name=row["name"],
|
||||||
|
sort_order=row.get("sort_order") or 0,
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["work_items.json"]:
|
||||||
|
obj = WorkItem(
|
||||||
|
project_id=project.id,
|
||||||
|
boq_document_id=_optional_mapping(row.get("boq_document_export_id"), ids, "boq_document_export_id"),
|
||||||
|
system_id=_optional_mapping(row.get("system_export_id"), ids, "system_export_id"),
|
||||||
|
section_id=_optional_mapping(row.get("section_export_id"), ids, "section_export_id"),
|
||||||
|
source_number=row.get("source_number"),
|
||||||
|
name=row["name"],
|
||||||
|
model=row.get("model"),
|
||||||
|
manufacturer=row.get("manufacturer"),
|
||||||
|
unit=row.get("unit"),
|
||||||
|
quantity=_parse_decimal(row.get("quantity"), "quantity"),
|
||||||
|
unit_price=_parse_decimal(row.get("unit_price"), "unit_price"),
|
||||||
|
amount=_parse_decimal(row.get("amount"), "amount"),
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["agreements.json"]:
|
||||||
|
obj = Agreement(
|
||||||
|
project_id=project.id,
|
||||||
|
boq_document_id=_optional_mapping(row.get("boq_document_export_id"), ids, "boq_document_export_id"),
|
||||||
|
number=row["number"],
|
||||||
|
date=_parse_date(row["date"], "date"),
|
||||||
|
title=row["title"],
|
||||||
|
description=row.get("description"),
|
||||||
|
status=row["status"],
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
# Back-fill BoqDocument.agreement_id now that agreements exist
|
||||||
|
for doc_db_id, agr_ref in boq_agreement_refs.items():
|
||||||
|
if agr_ref:
|
||||||
|
db.query(BoqDocument).filter(BoqDocument.id == doc_db_id).update(
|
||||||
|
{"agreement_id": ids[agr_ref]}
|
||||||
|
)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
for row in payload["agreement_items.json"]:
|
||||||
|
obj = AgreementItem(
|
||||||
|
agreement_id=_require_mapping(row["agreement_export_id"], ids, "agreement_export_id"),
|
||||||
|
work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"),
|
||||||
|
change_type=row["change_type"],
|
||||||
|
quantity_delta=_parse_decimal(row.get("quantity_delta"), "quantity_delta", required=True),
|
||||||
|
amount_delta=_parse_decimal(row.get("amount_delta"), "amount_delta", required=True),
|
||||||
|
source_row=row.get("source_row"),
|
||||||
|
source_number=row.get("source_number"),
|
||||||
|
source_name=row.get("source_name"),
|
||||||
|
source_model=row.get("source_model"),
|
||||||
|
source_manufacturer=row.get("source_manufacturer"),
|
||||||
|
source_unit=row.get("source_unit"),
|
||||||
|
source_unit_price=_parse_decimal(row.get("source_unit_price"), "source_unit_price"),
|
||||||
|
source_boq_document_id=_optional_mapping(row.get("source_boq_document_export_id"), ids, "source_boq_document_export_id"),
|
||||||
|
source_system_id=_optional_mapping(row.get("source_system_export_id"), ids, "source_system_export_id"),
|
||||||
|
source_section_id=_optional_mapping(row.get("source_section_export_id"), ids, "source_section_export_id"),
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["daily_reports.json"]:
|
||||||
|
obj = DailyReport(
|
||||||
|
project_id=project.id,
|
||||||
|
system_id=_optional_mapping(row.get("system_export_id"), ids, "system_export_id"),
|
||||||
|
report_date=_parse_date(row["report_date"], "report_date"),
|
||||||
|
notes=row.get("notes"),
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["daily_report_items.json"]:
|
||||||
|
obj = DailyReportItem(
|
||||||
|
daily_report_id=_require_mapping(row["daily_report_export_id"], ids, "daily_report_export_id"),
|
||||||
|
work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"),
|
||||||
|
completed_quantity=_parse_decimal(row.get("completed_quantity"), "completed_quantity", required=True),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["ks2.json"]:
|
||||||
|
obj = KS2(
|
||||||
|
project_id=project.id,
|
||||||
|
number=row["number"],
|
||||||
|
date=_parse_date(row["date"], "date"),
|
||||||
|
reporting_period_from=_parse_date(row.get("reporting_period_from"), "reporting_period_from"),
|
||||||
|
reporting_period_to=_parse_date(row.get("reporting_period_to"), "reporting_period_to"),
|
||||||
|
comment=row.get("comment"),
|
||||||
|
status=row["status"],
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["ks2_items.json"]:
|
||||||
|
obj = KS2Item(
|
||||||
|
ks2_id=_require_mapping(row["ks2_export_id"], ids, "ks2_export_id"),
|
||||||
|
work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"),
|
||||||
|
quantity=_parse_decimal(row.get("quantity"), "quantity", required=True),
|
||||||
|
unit_price=_parse_decimal(row.get("unit_price"), "unit_price") or Decimal("0"),
|
||||||
|
amount=_parse_decimal(row.get("amount"), "amount") or Decimal("0"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["ks2_item_sources.json"]:
|
||||||
|
obj = KS2ItemSource(
|
||||||
|
ks2_item_id=_require_mapping(row["ks2_item_export_id"], ids, "ks2_item_export_id"),
|
||||||
|
daily_report_item_id=_require_mapping(row["daily_report_item_export_id"], ids, "daily_report_item_export_id"),
|
||||||
|
quantity=_parse_decimal(row.get("quantity"), "quantity", required=True),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["ks3.json"]:
|
||||||
|
obj = KS3(
|
||||||
|
project_id=project.id,
|
||||||
|
number=row["number"],
|
||||||
|
date=_parse_date(row["date"], "date"),
|
||||||
|
reporting_period_from=_parse_date(row.get("reporting_period_from"), "reporting_period_from"),
|
||||||
|
reporting_period_to=_parse_date(row.get("reporting_period_to"), "reporting_period_to"),
|
||||||
|
comment=row.get("comment"),
|
||||||
|
status=row["status"],
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["ks3_ks2.json"]:
|
||||||
|
obj = KS3KS2(
|
||||||
|
ks3_id=_require_mapping(row["ks3_export_id"], ids, "ks3_export_id"),
|
||||||
|
ks2_id=_require_mapping(row["ks2_export_id"], ids, "ks2_export_id"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["payments.json"]:
|
||||||
|
obj = Payment(
|
||||||
|
project_id=project.id,
|
||||||
|
date=_parse_date(row["date"], "date"),
|
||||||
|
document_number=row.get("document_number"),
|
||||||
|
amount=_parse_decimal(row.get("amount"), "amount", required=True),
|
||||||
|
currency=row.get("currency") or "RUB",
|
||||||
|
comment=row.get("comment"),
|
||||||
|
status=row["status"],
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload["payment_allocations.json"]:
|
||||||
|
obj = PaymentAllocation(
|
||||||
|
payment_id=_require_mapping(row["payment_export_id"], ids, "payment_export_id"),
|
||||||
|
ks3_id=_require_mapping(row["ks3_export_id"], ids, "ks3_export_id"),
|
||||||
|
amount=_parse_decimal(row.get("amount"), "amount", required=True),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
for row in payload.get("work_journal_entries.json", []):
|
||||||
|
obj = WorkJournalEntry(
|
||||||
|
project_id=project.id,
|
||||||
|
type=row["type"],
|
||||||
|
text=row["text"],
|
||||||
|
status=row.get("status"),
|
||||||
|
due_date=_parse_date(row.get("due_date"), "due_date"),
|
||||||
|
created_at=_parse_datetime(row.get("created_at"), "created_at"),
|
||||||
|
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
|
||||||
|
)
|
||||||
|
db.add(obj)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = obj.id
|
||||||
|
|
||||||
|
# Restore document artifacts (official issued/cancelled files)
|
||||||
|
created_artifact_paths: list = []
|
||||||
|
try:
|
||||||
|
from app.services.document_artifact_service import build_storage_key, resolve_storage_path
|
||||||
|
from app.config import document_storage_root
|
||||||
|
|
||||||
|
artifact_files = payload.get("__artifact_files__", {})
|
||||||
|
for row in payload.get("document_artifacts.json", []):
|
||||||
|
doc_type = row["document_type"]
|
||||||
|
new_doc_id = _require_mapping(row["document_export_id"], ids, "document_export_id")
|
||||||
|
ext = row["format"]
|
||||||
|
storage_key = build_storage_key(
|
||||||
|
project.id, doc_type, new_doc_id,
|
||||||
|
row["template_type"], row["template_version"], ext,
|
||||||
|
)
|
||||||
|
file_bytes = artifact_files.get(row["archive_path"])
|
||||||
|
if file_bytes is None:
|
||||||
|
raise ProjectImportError(f"Artifact file missing in archive: {row['archive_path']}")
|
||||||
|
dest = resolve_storage_path(storage_key)
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
dest.write_bytes(file_bytes)
|
||||||
|
created_artifact_paths.append(dest)
|
||||||
|
|
||||||
|
art = DocumentArtifact(
|
||||||
|
project_id=project.id,
|
||||||
|
document_type=doc_type,
|
||||||
|
document_id=new_doc_id,
|
||||||
|
format=ext,
|
||||||
|
storage_key=storage_key,
|
||||||
|
template_type=row["template_type"],
|
||||||
|
template_version=int(row["template_version"]),
|
||||||
|
content_hash=row["content_hash"],
|
||||||
|
input_hash=row["input_hash"],
|
||||||
|
is_current=bool(row.get("is_current", True)),
|
||||||
|
generated_at=_parse_datetime(row.get("generated_at"), "generated_at"),
|
||||||
|
)
|
||||||
|
db.add(art)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = art.id
|
||||||
|
except Exception:
|
||||||
|
# Compensating cleanup: remove files created by this attempt
|
||||||
|
for p in created_artifact_paths:
|
||||||
|
try:
|
||||||
|
if p.is_file():
|
||||||
|
p.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
# Restore Daily Report photos (primary report attachments)
|
||||||
|
created_photo_paths: list = []
|
||||||
|
try:
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
build_photo_storage_key,
|
||||||
|
resolve_photo_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
photo_files = payload.get("__photo_files__", {})
|
||||||
|
for row in payload.get("daily_report_photos.json", []):
|
||||||
|
new_report_id = _require_mapping(
|
||||||
|
row["daily_report_export_id"], ids, "daily_report_export_id"
|
||||||
|
)
|
||||||
|
# Extension comes from validated content_type, never from the archive name.
|
||||||
|
ext_by_type = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||||||
|
ext = ext_by_type[row["content_type"]]
|
||||||
|
storage_key = build_photo_storage_key(
|
||||||
|
project.id, new_report_id, ext,
|
||||||
|
)
|
||||||
|
file_bytes = photo_files.get(row["archive_path"])
|
||||||
|
if file_bytes is None:
|
||||||
|
raise ProjectImportError(
|
||||||
|
f"Photo file missing in archive: {row['archive_path']}"
|
||||||
|
)
|
||||||
|
dest = resolve_photo_path(storage_key)
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
dest.write_bytes(file_bytes)
|
||||||
|
created_photo_paths.append(dest)
|
||||||
|
|
||||||
|
from app.models.daily_report_photo import DailyReportPhoto
|
||||||
|
photo = DailyReportPhoto(
|
||||||
|
project_id=project.id,
|
||||||
|
daily_report_id=new_report_id,
|
||||||
|
storage_key=storage_key,
|
||||||
|
original_name=row.get("original_name"),
|
||||||
|
content_type=row["content_type"],
|
||||||
|
file_size=int(row["file_size"]),
|
||||||
|
content_hash=row["content_hash"],
|
||||||
|
sort_order=int(row.get("sort_order") or 0),
|
||||||
|
)
|
||||||
|
db.add(photo)
|
||||||
|
db.flush()
|
||||||
|
ids[row["export_id"]] = photo.id
|
||||||
|
except Exception:
|
||||||
|
for p in created_photo_paths:
|
||||||
|
try:
|
||||||
|
if p.is_file():
|
||||||
|
p.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
def import_project(db: Session, data: bytes) -> Project:
|
||||||
|
"""Validate archive then create a new project atomically."""
|
||||||
|
preview = validate_archive(data)
|
||||||
|
payload = preview["payload"]
|
||||||
|
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
||||||
|
payload["__photo_files__"] = preview.get("photo_files", {})
|
||||||
|
try:
|
||||||
|
project = _import_entities(db, payload)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(project)
|
||||||
|
return project
|
||||||
|
except ProjectImportError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise ProjectImportError(f"Импорт прерван, изменения отменены: {exc}") from exc
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
"""Official-form KS-2 Word renderer.
|
||||||
|
|
||||||
|
KS2ExportDocument -> official DOCX template -> generated DOCX
|
||||||
|
|
||||||
|
Working template: app/templates_docs/ks2/ks2_ru_markers.docx
|
||||||
|
(copied from docs/templates/official/КС-2.docx via ks2_ru_v2.docx;
|
||||||
|
the original is never modified).
|
||||||
|
|
||||||
|
Static header fields (DOC-C4) are named template markers `{{name}}`:
|
||||||
|
the template owns the layout, Python only supplies data
|
||||||
|
(build_ks2_template_fields + fill_template_markers). The dynamic works
|
||||||
|
table is still filled by the code below.
|
||||||
|
|
||||||
|
Template layout (python-docx tables):
|
||||||
|
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/Объект/ОКДП/Договор)
|
||||||
|
t1 Номер документа / Дата составления / Отчетный период + АКТ
|
||||||
|
t2 Сметная (договорная) стоимость
|
||||||
|
t3 one dynamic works table (3-row header + system/item rows);
|
||||||
|
header rows repeat on page breaks via w:tblHeader
|
||||||
|
t4 closing totals block only («Итого» + «Всего по акту») after the items
|
||||||
|
t5 «Сдал» signatures
|
||||||
|
t6 «Принял» signatures
|
||||||
|
|
||||||
|
Data columns (8): № по порядку | № поз. по смете | Наименование |
|
||||||
|
Номер ед. расценки (always empty) | Ед. изм. | Количество | Цена | Стоимость.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
from docx.shared import RGBColor
|
||||||
|
|
||||||
|
from app.exporters.ks2_dto import KS2ExportDocument
|
||||||
|
from app.exporters.word.template_markers import fill_template_markers
|
||||||
|
|
||||||
|
TEMPLATE_TYPE = "ks2_word"
|
||||||
|
TEMPLATE_VERSION = 1
|
||||||
|
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
|
||||||
|
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_markers.docx"
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNotFoundError(FileNotFoundError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Column indices inside the 8-column data tables.
|
||||||
|
_COL_NUM = 0
|
||||||
|
_COL_SOURCE = 1
|
||||||
|
_COL_NAME = 2
|
||||||
|
_COL_RATE = 3 # always empty
|
||||||
|
_COL_UNIT = 4
|
||||||
|
_COL_QTY = 5
|
||||||
|
_COL_PRICE = 6
|
||||||
|
_COL_AMOUNT = 7
|
||||||
|
|
||||||
|
_DATA_COLS = 8
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Formatters (Word-only; Excel keeps its own numeric formats)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def format_money(value) -> str:
|
||||||
|
"""Money: thousands = space, decimal = comma, exactly 2 digits, no currency.
|
||||||
|
|
||||||
|
Examples: 31 293,36 / 18 600 000,00 / 1 005,00
|
||||||
|
"""
|
||||||
|
if value is None or value == "":
|
||||||
|
return ""
|
||||||
|
d = Decimal(str(value)).quantize(Decimal("0.01"))
|
||||||
|
sign = "-" if d < 0 else ""
|
||||||
|
d = abs(d)
|
||||||
|
int_part, frac = f"{d:.2f}".split(".")
|
||||||
|
groups = []
|
||||||
|
while len(int_part) > 3:
|
||||||
|
groups.append(int_part[-3:])
|
||||||
|
int_part = int_part[:-3]
|
||||||
|
groups.append(int_part)
|
||||||
|
int_part = " ".join(reversed(groups))
|
||||||
|
return f"{sign}{int_part},{frac}"
|
||||||
|
|
||||||
|
|
||||||
|
def format_qty(value) -> str:
|
||||||
|
"""Quantity: ordinary number with comma decimal and exactly 2 digits (17,00)."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return ""
|
||||||
|
d = Decimal(str(value)).quantize(Decimal("0.01"))
|
||||||
|
return f"{d:.2f}".replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
def _tr(tbl, row_idx):
|
||||||
|
return tbl.rows[row_idx]._tr
|
||||||
|
|
||||||
|
|
||||||
|
def _tcs(tbl, row_idx):
|
||||||
|
"""Raw w:tc elements of a row (merged cells appear once)."""
|
||||||
|
return _tr(tbl, row_idx).findall(qn("w:tc"))
|
||||||
|
|
||||||
|
|
||||||
|
def _set_tc_text(tc, text: str, *, bold: bool = False, size_pt: float | None = None,
|
||||||
|
color: RGBColor | None = None, align=None, no_wrap: bool = False) -> None:
|
||||||
|
"""Replace all runs of a w:tc with a single run carrying `text`.
|
||||||
|
|
||||||
|
Newlines become real OOXML line breaks (w:br).
|
||||||
|
"""
|
||||||
|
for p in tc.findall(qn("w:p")):
|
||||||
|
tc.remove(p)
|
||||||
|
p = tc.makeelement(qn("w:p"), {})
|
||||||
|
tc.append(p)
|
||||||
|
pPr = p.makeelement(qn("w:pPr"), {})
|
||||||
|
p.append(pPr)
|
||||||
|
if align is not None:
|
||||||
|
jc = pPr.makeelement(qn("w:jc"), {qn("w:val"): align})
|
||||||
|
pPr.append(jc)
|
||||||
|
if no_wrap:
|
||||||
|
tcPr = tc.find(qn("w:tcPr"))
|
||||||
|
if tcPr is None:
|
||||||
|
tcPr = tc.makeelement(qn("w:tcPr"), {})
|
||||||
|
tc.insert(0, tcPr)
|
||||||
|
if tcPr.find(qn("w:noWrap")) is None:
|
||||||
|
tcPr.append(tcPr.makeelement(qn("w:noWrap"), {}))
|
||||||
|
run = p.makeelement(qn("w:r"), {})
|
||||||
|
p.append(run)
|
||||||
|
rPr = run.makeelement(qn("w:rPr"), {})
|
||||||
|
run.append(rPr)
|
||||||
|
if bold:
|
||||||
|
rPr.append(rPr.makeelement(qn("w:b"), {}))
|
||||||
|
if size_pt is not None:
|
||||||
|
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): str(int(size_pt * 2))}))
|
||||||
|
if color is not None:
|
||||||
|
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): str(color)}))
|
||||||
|
parts = text.split("\n")
|
||||||
|
for i, part in enumerate(parts):
|
||||||
|
if i > 0:
|
||||||
|
run.append(run.makeelement(qn("w:br"), {}))
|
||||||
|
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
|
||||||
|
t.text = part
|
||||||
|
run.append(t)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_row_by_text(tbl, needle: str, tc_index: int = 0) -> int | None:
|
||||||
|
for ri in range(len(tbl.rows)):
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if tc_index < len(tcs):
|
||||||
|
texts = [t.text or "" for t in tcs[tc_index].iter(qn("w:t"))]
|
||||||
|
if needle in "".join(texts):
|
||||||
|
return ri
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _split_date(value: date | None) -> tuple[str, str, str]:
|
||||||
|
"""Return (day, month, year) as zero-padded strings; empty when no date."""
|
||||||
|
if value is None:
|
||||||
|
return "", "", ""
|
||||||
|
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_date(value: date | None) -> str:
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
return f"{value.day:02d}.{value.month:02d}.{value.year}"
|
||||||
|
|
||||||
|
|
||||||
|
def build_ks2_template_fields(doc: KS2ExportDocument) -> dict[str, str]:
|
||||||
|
"""Named marker values for the static KS-2 header (DOC-C4).
|
||||||
|
|
||||||
|
Values only — layout stays in the template (ks2_ru_markers.docx).
|
||||||
|
"""
|
||||||
|
h = doc.header
|
||||||
|
day, month, year = _split_date(h.contract_date)
|
||||||
|
raw_amount = (h.contract_amount or "").strip()
|
||||||
|
if raw_amount:
|
||||||
|
try:
|
||||||
|
amount = format_money(Decimal(raw_amount))
|
||||||
|
except Exception:
|
||||||
|
amount = raw_amount
|
||||||
|
else:
|
||||||
|
amount = ""
|
||||||
|
return {
|
||||||
|
"ks2_number": h.ks2_number or "",
|
||||||
|
"ks2_date": _fmt_date(h.ks2_date),
|
||||||
|
"contract_number": h.contract_number or "",
|
||||||
|
"contract_date_day": day,
|
||||||
|
"contract_date_month": month,
|
||||||
|
"contract_date_year": year,
|
||||||
|
"report_from": _fmt_date(h.period_from),
|
||||||
|
"report_to": _fmt_date(h.period_to),
|
||||||
|
"investor": h.investor_name or "",
|
||||||
|
"customer": h.customer or h.customer_name or "",
|
||||||
|
"contractor": h.contractor_name or "",
|
||||||
|
"construction": h.construction_name or "",
|
||||||
|
"object": h.object_name or "",
|
||||||
|
"contract_amount": amount,
|
||||||
|
"contractor_signer_name": h.contractor_signer_name or "",
|
||||||
|
"contractor_signer_position": h.contractor_signer_position or "",
|
||||||
|
"customer_signer_name": h.customer_signer_name or "",
|
||||||
|
"customer_signer_position": h.customer_signer_position or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _data_row_index(tbl) -> int | None:
|
||||||
|
"""First empty data row (after the 3-row header block, before «Итого»)."""
|
||||||
|
total_ri = _find_row_by_text(tbl, "Итого", 0)
|
||||||
|
if total_ri is None:
|
||||||
|
return None
|
||||||
|
for ri in range(3, total_ri):
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if len(tcs) == 8:
|
||||||
|
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||||
|
if not "".join(texts).strip():
|
||||||
|
return ri
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _totals_row_index(tbl) -> int | None:
|
||||||
|
return _find_row_by_text(tbl, "Итого", 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _grand_total_row_index(tbl) -> int | None:
|
||||||
|
return _find_row_by_text(tbl, "Всего по акту", 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_row(tbl, row_idx: int) -> None:
|
||||||
|
tr = _tr(tbl, row_idx)
|
||||||
|
tr.getparent().remove(tr)
|
||||||
|
|
||||||
|
|
||||||
|
def _clone_row_before(tbl, template_tr, before_tr):
|
||||||
|
new_tr = deepcopy(template_tr)
|
||||||
|
before_tr.addprevious(new_tr)
|
||||||
|
return new_tr
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_data_row_tr(tr, item) -> None:
|
||||||
|
tcs = tr.findall(qn("w:tc"))
|
||||||
|
if len(tcs) < 8:
|
||||||
|
return
|
||||||
|
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
|
||||||
|
_set_tc_text(tcs[_COL_SOURCE], item.source_number or "", size_pt=9, align="center")
|
||||||
|
_set_tc_text(tcs[_COL_NAME], item.name or "", size_pt=9)
|
||||||
|
_set_tc_text(tcs[_COL_RATE], "", size_pt=9) # always empty
|
||||||
|
_set_tc_text(tcs[_COL_UNIT], item.unit or "", size_pt=9, align="center")
|
||||||
|
_set_tc_text(tcs[_COL_QTY], format_qty(item.quantity), size_pt=9, align="right")
|
||||||
|
_set_tc_text(tcs[_COL_PRICE], format_money(item.unit_price), size_pt=9, align="right")
|
||||||
|
_set_tc_text(tcs[_COL_AMOUNT], format_money(item.amount), size_pt=9, align="right")
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_tr_cells(tr) -> object:
|
||||||
|
"""Merge every w:tc of a row into a single cell spanning all columns."""
|
||||||
|
tcs = tr.findall(qn("w:tc"))
|
||||||
|
if len(tcs) <= 1:
|
||||||
|
return tcs[0] if tcs else None
|
||||||
|
first = tcs[0]
|
||||||
|
tcPr = first.find(qn("w:tcPr"))
|
||||||
|
if tcPr is None:
|
||||||
|
tcPr = first.makeelement(qn("w:tcPr"), {})
|
||||||
|
first.insert(0, tcPr)
|
||||||
|
for gs in tcPr.findall(qn("w:gridSpan")):
|
||||||
|
tcPr.remove(gs)
|
||||||
|
gs = tcPr.makeelement(qn("w:gridSpan"), {qn("w:val"): str(len(tcs))})
|
||||||
|
tcPr.append(gs)
|
||||||
|
for tc in tcs[1:]:
|
||||||
|
tr.remove(tc)
|
||||||
|
return first
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_group_row_tr(tr, title: str) -> None:
|
||||||
|
"""System/section divider: one merged cell across all 8 columns, bold title.
|
||||||
|
|
||||||
|
No row number — text never lands in the № column.
|
||||||
|
"""
|
||||||
|
tc = _merge_tr_cells(tr)
|
||||||
|
if tc is None:
|
||||||
|
return
|
||||||
|
_set_tc_text(tc, title, bold=True, size_pt=9, align="left")
|
||||||
|
|
||||||
|
|
||||||
|
def _group_title(code: str | None, name: str) -> str:
|
||||||
|
code = (code or "").strip()
|
||||||
|
name = name or ""
|
||||||
|
return f"{code} — {name}" if code else name
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_totals(tbl, total) -> None:
|
||||||
|
ri = _totals_row_index(tbl)
|
||||||
|
if ri is None:
|
||||||
|
return
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
# [5]'Итого' [1]'' [1]'Х' [1]'' → amount in the last tc
|
||||||
|
if tcs:
|
||||||
|
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_grand_total(tbl, total) -> None:
|
||||||
|
ri = _grand_total_row_index(tbl)
|
||||||
|
if ri is None:
|
||||||
|
return
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if tcs:
|
||||||
|
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_intermediate_totals(tbl) -> None:
|
||||||
|
"""Remove the intermediate «Итого» row (page subtotal) from a data table.
|
||||||
|
|
||||||
|
Only the final «Итого» / «Всего по акту» at the very end of the document
|
||||||
|
may show money totals (DOC-C6).
|
||||||
|
"""
|
||||||
|
ri = _totals_row_index(tbl)
|
||||||
|
if ri is not None:
|
||||||
|
_delete_row(tbl, ri)
|
||||||
|
|
||||||
|
|
||||||
|
def _set_header_repeat(tbl, n_header_rows: int) -> None:
|
||||||
|
"""Mark the first rows as a repeating Word header (w:tblHeader).
|
||||||
|
|
||||||
|
Word then repeats them automatically when the single works table
|
||||||
|
flows onto the next page (DOC-C7).
|
||||||
|
"""
|
||||||
|
for ri in range(min(n_header_rows, len(tbl.rows))):
|
||||||
|
tr = _tr(tbl, ri)
|
||||||
|
trPr = tr.find(qn("w:trPr"))
|
||||||
|
if trPr is None:
|
||||||
|
trPr = tr.makeelement(qn("w:trPr"), {})
|
||||||
|
tr.insert(0, trPr)
|
||||||
|
if trPr.find(qn("w:tblHeader")) is None:
|
||||||
|
trPr.append(trPr.makeelement(qn("w:tblHeader"), {}))
|
||||||
|
|
||||||
|
|
||||||
|
def _to_totals_block(tbl, total) -> None:
|
||||||
|
"""Turn a second data table into a standalone totals block (DOC-C7).
|
||||||
|
|
||||||
|
Keeps only the «Итого» and «Всего по акту» rows (already formatted like
|
||||||
|
the works table) and drops the copied header/data rows — this is not a
|
||||||
|
continuation table, just the closing money block after the last item.
|
||||||
|
"""
|
||||||
|
keep: set[int] = set()
|
||||||
|
ri_itogo = _totals_row_index(tbl)
|
||||||
|
ri_vsyo = _grand_total_row_index(tbl)
|
||||||
|
if ri_itogo is not None:
|
||||||
|
keep.add(ri_itogo)
|
||||||
|
if ri_vsyo is not None:
|
||||||
|
keep.add(ri_vsyo)
|
||||||
|
# delete every row except the totals rows (bottom-up so indices stay valid)
|
||||||
|
for ri in range(len(tbl.rows) - 1, -1, -1):
|
||||||
|
if ri not in keep:
|
||||||
|
_delete_row(tbl, ri)
|
||||||
|
_fill_totals(tbl, total)
|
||||||
|
_fill_grand_total(tbl, total)
|
||||||
|
|
||||||
|
|
||||||
|
def _place_storno(doc, h) -> None:
|
||||||
|
"""Bold red СТОРНИРОВАН as a body paragraph right before the АКТ title table.
|
||||||
|
|
||||||
|
Does not touch any table structure.
|
||||||
|
"""
|
||||||
|
if h.status != "cancelled":
|
||||||
|
return
|
||||||
|
body = doc.element.body
|
||||||
|
for child in body:
|
||||||
|
if child.tag != qn("w:tbl"):
|
||||||
|
continue
|
||||||
|
texts = [t.text or "" for t in child.iter(qn("w:t"))]
|
||||||
|
if any("О ПРИЕМКЕ" in t for t in texts):
|
||||||
|
p = body.makeelement(qn("w:p"), {})
|
||||||
|
child.addprevious(p)
|
||||||
|
pPr = p.makeelement(qn("w:pPr"), {})
|
||||||
|
p.append(pPr)
|
||||||
|
pPr.append(pPr.makeelement(qn("w:jc"), {qn("w:val"): "center"}))
|
||||||
|
run = p.makeelement(qn("w:r"), {})
|
||||||
|
p.append(run)
|
||||||
|
rPr = run.makeelement(qn("w:rPr"), {})
|
||||||
|
run.append(rPr)
|
||||||
|
rPr.append(rPr.makeelement(qn("w:b"), {}))
|
||||||
|
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): "FF0000"}))
|
||||||
|
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): "28"}))
|
||||||
|
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
|
||||||
|
t.text = "СТОРНИРОВАН"
|
||||||
|
run.append(t)
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def _expand_data_table(tbl, items, group_headers=None):
|
||||||
|
"""Fill data rows of a table; clone/delete template rows as needed.
|
||||||
|
|
||||||
|
`group_headers` maps id(item) -> (code, name) or a plain string.
|
||||||
|
Returns the number of item rows written.
|
||||||
|
"""
|
||||||
|
first_data = _data_row_index(tbl)
|
||||||
|
total_ri = _totals_row_index(tbl)
|
||||||
|
if first_data is None or total_ri is None:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# Build the sequence: optional group header rows + item rows.
|
||||||
|
sequence = []
|
||||||
|
for item in items:
|
||||||
|
gh = group_headers.get(id(item)) if group_headers else None
|
||||||
|
if gh:
|
||||||
|
sequence.append(("group", gh))
|
||||||
|
sequence.append(("item", item))
|
||||||
|
if not sequence:
|
||||||
|
sequence = []
|
||||||
|
|
||||||
|
template_tr = _tr(tbl, first_data)
|
||||||
|
# current number of data slots
|
||||||
|
slots = total_ri - first_data
|
||||||
|
needed = len(sequence)
|
||||||
|
|
||||||
|
# Delete unused slots (bottom-up).
|
||||||
|
for ri in range(total_ri - 1, first_data + needed - 1, -1):
|
||||||
|
if ri >= first_data:
|
||||||
|
_delete_row(tbl, ri)
|
||||||
|
|
||||||
|
# Insert extra clones before the totals row.
|
||||||
|
totals_tr = _tr(tbl, _totals_row_index(tbl))
|
||||||
|
for _ in range(max(0, needed - slots)):
|
||||||
|
_clone_row_before(tbl, template_tr, totals_tr)
|
||||||
|
|
||||||
|
# Fill.
|
||||||
|
data_start = _data_row_index(tbl)
|
||||||
|
for idx, (kind, payload) in enumerate(sequence):
|
||||||
|
tr = _tr(tbl, data_start + idx)
|
||||||
|
if kind == "group":
|
||||||
|
if isinstance(payload, tuple):
|
||||||
|
title = _group_title(payload[0], payload[1])
|
||||||
|
else:
|
||||||
|
title = str(payload)
|
||||||
|
_fill_group_row_tr(tr, title)
|
||||||
|
else:
|
||||||
|
_fill_data_row_tr(tr, payload)
|
||||||
|
return sum(1 for k, _ in sequence if k == "item")
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks2_word(doc: KS2ExportDocument) -> bytes:
|
||||||
|
if not TEMPLATE_FILE.is_file():
|
||||||
|
raise TemplateNotFoundError(f"KS-2 Word template not found: {TEMPLATE_FILE}")
|
||||||
|
|
||||||
|
document = Document(str(TEMPLATE_FILE))
|
||||||
|
h = doc.header
|
||||||
|
|
||||||
|
tables = document.tables
|
||||||
|
if len(tables) < 7:
|
||||||
|
raise TemplateNotFoundError(
|
||||||
|
f"KS-2 Word template must contain 7 tables, found {len(tables)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Static header fields: named template markers own the layout (DOC-C4).
|
||||||
|
fields = build_ks2_template_fields(doc)
|
||||||
|
fill_template_markers(document, fields)
|
||||||
|
|
||||||
|
# Group headers keyed by item identity (from DTO): (code, name).
|
||||||
|
group_headers: dict[int, tuple] = {}
|
||||||
|
for item in doc.items:
|
||||||
|
gh = getattr(item, "group_header", None)
|
||||||
|
if gh:
|
||||||
|
group_headers[id(item)] = (
|
||||||
|
getattr(item, "group_code", None) or "",
|
||||||
|
gh,
|
||||||
|
)
|
||||||
|
|
||||||
|
items = list(doc.items)
|
||||||
|
# DOC-C7: one dynamic works table for every item and system row. Word
|
||||||
|
# flows it across pages on its own; the header repeats via w:tblHeader.
|
||||||
|
# No t3/t4 split, no per-page row limits.
|
||||||
|
_expand_data_table(tables[3], items, group_headers)
|
||||||
|
_set_header_repeat(tables[3], 3)
|
||||||
|
# The «Итого» template row of the works table is a page-subtotal slot —
|
||||||
|
# money totals live only in the separate closing block (DOC-C6).
|
||||||
|
_delete_intermediate_totals(tables[3])
|
||||||
|
|
||||||
|
# t4 used to be a second data table (page 2). It is now only the closing
|
||||||
|
# totals block: «Итого» + «Всего по акту» after the last position.
|
||||||
|
_to_totals_block(tables[4], doc.total)
|
||||||
|
|
||||||
|
_place_storno(document, h)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
document.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
"""Official-form KS-3 Word renderer (DOC-C8, marker-template architecture).
|
||||||
|
|
||||||
|
KS3ExportDocument -> ks3_ru_markers.docx -> generated DOCX
|
||||||
|
|
||||||
|
Architecture follows DOC-C4–DOC-C7:
|
||||||
|
- the template owns the geometry (requisites, block titles, signatures);
|
||||||
|
- static fields are named markers filled by fill_template_markers;
|
||||||
|
- one dynamic works table flows across pages (w:tblHeader repeats the
|
||||||
|
column header); no t_left/t_right split and no row-count limits;
|
||||||
|
- money totals sit once at the end (Итого / Сумма НДС / Всего с НДС) —
|
||||||
|
never as a page subtotal.
|
||||||
|
|
||||||
|
Template layout (python-docx tables):
|
||||||
|
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/ОКДП/Договор)
|
||||||
|
t1 Номер документа / Дата составления / Отчетный период + СПРАВКА
|
||||||
|
t2 works table: 3-row header, form rows, data rows, «Итого» block
|
||||||
|
t3 «Заказчик (Генподрядчик)» signatures
|
||||||
|
t4 «Подрядчик (Субподрядчик)» signatures
|
||||||
|
|
||||||
|
Data columns (6): № по порядку | Наименование | Код |
|
||||||
|
с начала проведения работ | с начала года | за отчетный период.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
|
||||||
|
from app.exporters.ks3_dto import KS3ExportDocument
|
||||||
|
from app.exporters.word.template_markers import fill_template_markers
|
||||||
|
from app.exporters.word.ks2_renderer import (
|
||||||
|
_clone_row_before,
|
||||||
|
_delete_row,
|
||||||
|
_set_header_repeat,
|
||||||
|
_set_tc_text,
|
||||||
|
format_money,
|
||||||
|
)
|
||||||
|
|
||||||
|
TEMPLATE_TYPE = "ks3"
|
||||||
|
TEMPLATE_VERSION = 1
|
||||||
|
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks3"
|
||||||
|
TEMPLATE_FILE = TEMPLATE_DIR / "ks3_ru_markers.docx"
|
||||||
|
|
||||||
|
_ROW_MARKER = "##KS3_ROW##"
|
||||||
|
|
||||||
|
# Column indices inside the 6-column works table.
|
||||||
|
_COL_NUM = 0
|
||||||
|
_COL_NAME = 1
|
||||||
|
_COL_CODE = 2 # always empty
|
||||||
|
_COL_FROM_START = 3 # unsupported by KS3ExportItem
|
||||||
|
_COL_FROM_YEAR = 4 # unsupported by KS3ExportItem
|
||||||
|
_COL_PERIOD = 5 # amount for the reporting period
|
||||||
|
|
||||||
|
# Header rows of the works table that repeat on page breaks.
|
||||||
|
_HEADER_ROWS = 3
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNotFoundError(FileNotFoundError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _tr(tbl, row_idx):
|
||||||
|
return tbl.rows[row_idx]._tr
|
||||||
|
|
||||||
|
|
||||||
|
def _tcs(tbl, row_idx):
|
||||||
|
"""Raw w:tc elements of a row (merged cells appear once)."""
|
||||||
|
return _tr(tbl, row_idx).findall(qn("w:tc"))
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_date(value: date | None) -> str:
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
return f"{value.day:02d}.{value.month:02d}.{value.year}"
|
||||||
|
|
||||||
|
|
||||||
|
def _split_date(value: date | None) -> tuple[str, str, str]:
|
||||||
|
if value is None:
|
||||||
|
return "", "", ""
|
||||||
|
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
|
||||||
|
|
||||||
|
|
||||||
|
def build_ks3_template_fields(doc: KS3ExportDocument) -> dict[str, str]:
|
||||||
|
"""Named marker values for the static KS-3 header (DOC-C4 contract).
|
||||||
|
|
||||||
|
Values only — layout stays in the template (ks3_ru_markers.docx).
|
||||||
|
Fields that the official blank does not contain (e.g. `object`) are
|
||||||
|
simply absent here and never rendered.
|
||||||
|
"""
|
||||||
|
h = doc.header
|
||||||
|
day, month, year = _split_date(h.contract_date)
|
||||||
|
raw_amount = (h.contract_amount or "").strip()
|
||||||
|
if raw_amount:
|
||||||
|
try:
|
||||||
|
amount = format_money(Decimal(raw_amount))
|
||||||
|
except Exception:
|
||||||
|
amount = raw_amount
|
||||||
|
else:
|
||||||
|
amount = ""
|
||||||
|
return {
|
||||||
|
"ks3_number": h.ks3_number or "",
|
||||||
|
"ks3_date": _fmt_date(h.ks3_date),
|
||||||
|
"contract_number": h.contract_number or "",
|
||||||
|
"contract_date_day": day,
|
||||||
|
"contract_date_month": month,
|
||||||
|
"contract_date_year": year,
|
||||||
|
"report_from": _fmt_date(h.period_from),
|
||||||
|
"report_to": _fmt_date(h.period_to),
|
||||||
|
"investor": h.investor_name or "",
|
||||||
|
"customer": h.customer or h.customer_name or "",
|
||||||
|
"contractor": h.contractor_name or "",
|
||||||
|
"construction": h.construction_name or "",
|
||||||
|
"contract_amount": amount,
|
||||||
|
"contractor_signer_name": h.contractor_signer_name or "",
|
||||||
|
"contractor_signer_position": h.contractor_signer_position or "",
|
||||||
|
"customer_signer_name": h.customer_signer_name or "",
|
||||||
|
"customer_signer_position": h.customer_signer_position or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _find_row_marker(tbl, marker: str) -> int | None:
|
||||||
|
for ri in range(len(tbl.rows)):
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if not tcs:
|
||||||
|
continue
|
||||||
|
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||||
|
if marker in "".join(texts):
|
||||||
|
return ri
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _find_text_row(tbl, needle: str) -> int | None:
|
||||||
|
for ri in range(len(tbl.rows)):
|
||||||
|
for tc in _tcs(tbl, ri):
|
||||||
|
texts = [t.text or "" for t in tc.iter(qn("w:t"))]
|
||||||
|
if needle in "".join(texts):
|
||||||
|
return ri
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_item_row_tr(tr, item) -> None:
|
||||||
|
"""One KS2 line: number, factual KS2 reference, empty code/cumulative
|
||||||
|
columns (not supported by the DTO), amount in «за отчетный период».
|
||||||
|
"""
|
||||||
|
tcs = tr.findall(qn("w:tc"))
|
||||||
|
if len(tcs) < 6:
|
||||||
|
return
|
||||||
|
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
|
||||||
|
ref = f"КС-2 №{item.ks2_number}" if item.ks2_number else ""
|
||||||
|
if item.ks2_date:
|
||||||
|
ref = f"{ref} от {_fmt_date(item.ks2_date)}" if ref else _fmt_date(item.ks2_date)
|
||||||
|
_set_tc_text(tcs[_COL_NAME], ref, size_pt=9)
|
||||||
|
_set_tc_text(tcs[_COL_CODE], "", size_pt=9)
|
||||||
|
_set_tc_text(tcs[_COL_FROM_START], "", size_pt=9)
|
||||||
|
_set_tc_text(tcs[_COL_FROM_YEAR], "", size_pt=9)
|
||||||
|
_set_tc_text(tcs[_COL_PERIOD], format_money(item.amount), size_pt=9, align="right")
|
||||||
|
|
||||||
|
|
||||||
|
def _expand_works_table(tbl, items) -> None:
|
||||||
|
"""Fill the single dynamic works table; clone/delete template rows as needed.
|
||||||
|
|
||||||
|
No page limits and no second continuation table — Word paginates the one
|
||||||
|
table and repeats the header via w:tblHeader.
|
||||||
|
"""
|
||||||
|
first_data = _find_row_marker(tbl, _ROW_MARKER)
|
||||||
|
if first_data is None:
|
||||||
|
# fall back: first empty 6-cell row after the 3-row header
|
||||||
|
for ri in range(_HEADER_ROWS, len(tbl.rows)):
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if len(tcs) == 6:
|
||||||
|
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||||
|
if not "".join(texts).strip():
|
||||||
|
first_data = ri
|
||||||
|
break
|
||||||
|
if first_data is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
itogo_ri = _find_text_row(tbl, "Итого")
|
||||||
|
if itogo_ri is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
needed = len(items)
|
||||||
|
slots = itogo_ri - first_data
|
||||||
|
template_tr = _tr(tbl, first_data)
|
||||||
|
|
||||||
|
# Drop unused data slots (bottom-up).
|
||||||
|
for ri in range(itogo_ri - 1, first_data + needed - 1, -1):
|
||||||
|
if ri >= first_data:
|
||||||
|
_delete_row(tbl, ri)
|
||||||
|
|
||||||
|
# Clone extra rows before the totals block.
|
||||||
|
totals_tr = _tr(tbl, _find_text_row(tbl, "Итого"))
|
||||||
|
for _ in range(max(0, needed - slots)):
|
||||||
|
_clone_row_before(tbl, template_tr, totals_tr)
|
||||||
|
|
||||||
|
start = _find_row_marker(tbl, _ROW_MARKER)
|
||||||
|
if start is None:
|
||||||
|
start = first_data
|
||||||
|
for idx, item in enumerate(items):
|
||||||
|
_fill_item_row_tr(_tr(tbl, start + idx), item)
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_totals(tbl, total) -> None:
|
||||||
|
"""Final money totals at the very end — once, never a page subtotal."""
|
||||||
|
ri = _find_text_row(tbl, "Итого")
|
||||||
|
if ri is None:
|
||||||
|
return
|
||||||
|
tcs = _tcs(tbl, ri)
|
||||||
|
if tcs:
|
||||||
|
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
|
||||||
|
# «Сумма НДС» / «Всего с учетом НДС» stay empty: VAT is not supported
|
||||||
|
# by KS3ExportItem and must not be invented (DOC-C8 §3).
|
||||||
|
|
||||||
|
|
||||||
|
def _place_storno(doc, h) -> None:
|
||||||
|
"""Bold red СТОРНИРОВАН before the СПРАВКА title table (like KS-2)."""
|
||||||
|
if h.status != "cancelled":
|
||||||
|
return
|
||||||
|
body = doc.element.body
|
||||||
|
for child in body:
|
||||||
|
if child.tag != qn("w:tbl"):
|
||||||
|
continue
|
||||||
|
texts = [t.text or "" for t in child.iter(qn("w:t"))]
|
||||||
|
if any("СПРАВКА" in t for t in texts):
|
||||||
|
p = body.makeelement(qn("w:p"), {})
|
||||||
|
child.addprevious(p)
|
||||||
|
pPr = p.makeelement(qn("w:pPr"), {})
|
||||||
|
p.append(pPr)
|
||||||
|
pPr.append(pPr.makeelement(qn("w:jc"), {qn("w:val"): "center"}))
|
||||||
|
run = p.makeelement(qn("w:r"), {})
|
||||||
|
p.append(run)
|
||||||
|
rPr = run.makeelement(qn("w:rPr"), {})
|
||||||
|
run.append(rPr)
|
||||||
|
rPr.append(rPr.makeelement(qn("w:b"), {}))
|
||||||
|
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): "FF0000"}))
|
||||||
|
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): "28"}))
|
||||||
|
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
|
||||||
|
t.text = "СТОРНИРОВАН"
|
||||||
|
run.append(t)
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
||||||
|
"""Render official-form KS-3. Returns docx bytes. No DB / no artifact writes."""
|
||||||
|
if not TEMPLATE_FILE.is_file():
|
||||||
|
raise TemplateNotFoundError(f"KS-3 Word template not found: {TEMPLATE_FILE}")
|
||||||
|
|
||||||
|
document = Document(str(TEMPLATE_FILE))
|
||||||
|
h = doc.header
|
||||||
|
|
||||||
|
tables = document.tables
|
||||||
|
if len(tables) < 5:
|
||||||
|
raise TemplateNotFoundError(
|
||||||
|
f"KS-3 Word template must contain 5 tables, found {len(tables)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Static header fields: named template markers own the layout (DOC-C4).
|
||||||
|
fields = build_ks3_template_fields(doc)
|
||||||
|
fill_template_markers(document, fields)
|
||||||
|
|
||||||
|
# One dynamic works table (t2); Word paginates it naturally.
|
||||||
|
works = tables[2]
|
||||||
|
_expand_works_table(works, list(doc.items))
|
||||||
|
_set_header_repeat(works, _HEADER_ROWS)
|
||||||
|
_fill_totals(works, doc.total)
|
||||||
|
|
||||||
|
_place_storno(document, h)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
document.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Word renderer for KS-6a export using python-docx."""
|
||||||
|
import io
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.enum.section import WD_ORIENT
|
||||||
|
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.shared import Pt
|
||||||
|
|
||||||
|
from app.exporters.common import QTY_TEXT, format_date, format_period, project_requisite_lines
|
||||||
|
from app.exporters.ks6a_dto import KS6aExportDocument
|
||||||
|
|
||||||
|
|
||||||
|
def render_ks6a_word(doc: KS6aExportDocument) -> bytes:
|
||||||
|
d = Document()
|
||||||
|
h = doc.header
|
||||||
|
|
||||||
|
# Landscape page for the wide table
|
||||||
|
section = d.sections[0]
|
||||||
|
section.orientation = WD_ORIENT.LANDSCAPE
|
||||||
|
section.page_width, section.page_height = section.page_height, section.page_width
|
||||||
|
|
||||||
|
# Title
|
||||||
|
title = d.add_paragraph()
|
||||||
|
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
run = title.add_run("КС-6а — Журнал учёта выполненных работ")
|
||||||
|
run.bold = True
|
||||||
|
run.font.size = Pt(14)
|
||||||
|
|
||||||
|
d.add_paragraph()
|
||||||
|
|
||||||
|
extra = []
|
||||||
|
if h.contractor:
|
||||||
|
extra.append(("Подрядчик:", h.contractor))
|
||||||
|
if h.system_name:
|
||||||
|
extra.append(("Система:", h.system_name))
|
||||||
|
|
||||||
|
header_lines = project_requisite_lines(
|
||||||
|
project_name=h.project_name,
|
||||||
|
customer=h.customer,
|
||||||
|
contract_number=h.contract_number,
|
||||||
|
contract_date=h.contract_date,
|
||||||
|
currency=h.currency,
|
||||||
|
period_text=format_period(h.period_from, h.period_to),
|
||||||
|
extra=extra,
|
||||||
|
)
|
||||||
|
for label, value in header_lines:
|
||||||
|
p = d.add_paragraph()
|
||||||
|
run = p.add_run(label + " ")
|
||||||
|
run.bold = True
|
||||||
|
p.add_run(value)
|
||||||
|
|
||||||
|
d.add_paragraph()
|
||||||
|
|
||||||
|
# Table — one row per DailyReportItem
|
||||||
|
table = d.add_table(rows=1, cols=8)
|
||||||
|
table.style = "Table Grid"
|
||||||
|
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
|
||||||
|
columns = [
|
||||||
|
"№", "Дата", "Система", "Раздел", "№ поз.",
|
||||||
|
"Наименование работ", "Ед. изм.", "Количество",
|
||||||
|
]
|
||||||
|
for idx, col_name in enumerate(columns):
|
||||||
|
cell = table.rows[0].cells[idx]
|
||||||
|
cell.text = col_name
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
for run in paragraph.runs:
|
||||||
|
run.bold = True
|
||||||
|
run.font.size = Pt(9)
|
||||||
|
|
||||||
|
for item in doc.items:
|
||||||
|
row = table.add_row()
|
||||||
|
row.cells[0].text = str(item.row_number)
|
||||||
|
row.cells[1].text = format_date(item.report_date)
|
||||||
|
row.cells[2].text = item.system_name
|
||||||
|
row.cells[3].text = item.section_name
|
||||||
|
row.cells[4].text = item.source_number
|
||||||
|
row.cells[5].text = item.name
|
||||||
|
row.cells[6].text = item.unit
|
||||||
|
row.cells[7].text = QTY_TEXT.format(item.quantity)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
d.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read()
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Named text markers for official-form DOCX templates (DOC-C4 prototype).
|
||||||
|
|
||||||
|
A working template carries named markers like ``{{ks2_number}}`` directly in
|
||||||
|
the cells where the renderer used to write static values. The template owns the
|
||||||
|
layout (geometry, merges, run formatting); Python owns the data.
|
||||||
|
|
||||||
|
``fill_template_markers(document, fields)`` replaces every ``{{name}}`` with
|
||||||
|
``fields[name]``. Only ``w:t`` text nodes are touched, so runs, line breaks and
|
||||||
|
cell geometry stay exactly as the template defines them.
|
||||||
|
|
||||||
|
Prototype limits (by design, see docs/tasks/DOC-C4-ks2-template-markers.md):
|
||||||
|
- a marker must sit inside a single run/w:t (true for ks2_ru_markers.docx);
|
||||||
|
- no VBA, no search by Russian labels, no cell coordinate math;
|
||||||
|
- a marker without a value in `fields` becomes an empty string — a missing
|
||||||
|
optional field never breaks the export.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
|
||||||
|
MARKER_RE = re.compile(r"\{\{([a-z0-9_]+)\}\}")
|
||||||
|
|
||||||
|
# Named fields of the static KS-2 header (the marker contract of the template).
|
||||||
|
REQUIRED_KS2_MARKERS = (
|
||||||
|
"ks2_number",
|
||||||
|
"ks2_date",
|
||||||
|
"contract_number",
|
||||||
|
"contract_date_day",
|
||||||
|
"contract_date_month",
|
||||||
|
"contract_date_year",
|
||||||
|
"report_from",
|
||||||
|
"report_to",
|
||||||
|
"investor",
|
||||||
|
"customer",
|
||||||
|
"contractor",
|
||||||
|
"construction",
|
||||||
|
"object",
|
||||||
|
"contract_amount",
|
||||||
|
"contractor_signer_name",
|
||||||
|
"contractor_signer_position",
|
||||||
|
"customer_signer_name",
|
||||||
|
"customer_signer_position",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fill_template_markers(document, fields) -> int:
|
||||||
|
"""Replace ``{{name}}`` markers in the document body with `fields` values.
|
||||||
|
|
||||||
|
`document` is a python-docx Document. `fields` maps marker name -> str.
|
||||||
|
Markers missing from `fields` are replaced with "" (never raises).
|
||||||
|
Returns the number of replacements made.
|
||||||
|
"""
|
||||||
|
fields = fields or {}
|
||||||
|
replaced = 0
|
||||||
|
|
||||||
|
def _sub(match):
|
||||||
|
nonlocal replaced
|
||||||
|
replaced += 1
|
||||||
|
return str(fields.get(match.group(1), ""))
|
||||||
|
|
||||||
|
for t in document.element.iter(qn("w:t")):
|
||||||
|
text = t.text
|
||||||
|
if not text or "{{" not in text:
|
||||||
|
continue
|
||||||
|
new_text = MARKER_RE.sub(_sub, text)
|
||||||
|
if new_text != text:
|
||||||
|
t.text = new_text
|
||||||
|
return replaced
|
||||||
@@ -161,13 +161,32 @@ def preview_excel_data(file_path: str, sheet_name: str, header_row: int, start_r
|
|||||||
return parsed
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
def import_excel_data(db: Session, file_path: str, sheet_name: str, header_row: int, start_row: int, project_id: int) -> Dict[str, Any]:
|
def import_excel_data(
|
||||||
|
db: Session,
|
||||||
|
file_path: str,
|
||||||
|
sheet_name: str,
|
||||||
|
header_row: int,
|
||||||
|
start_row: int,
|
||||||
|
project_id: int,
|
||||||
|
document_name: Optional[str] = None,
|
||||||
|
document_number: Optional[str] = None,
|
||||||
|
document_date: Optional[Any] = None,
|
||||||
|
contract: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
parsed = parse_excel_data(file_path, sheet_name, header_row, start_row)
|
parsed = parse_excel_data(file_path, sheet_name, header_row, start_row)
|
||||||
if parsed["errors"]:
|
if parsed["errors"]:
|
||||||
raise ValueError("\n".join(parsed["errors"]))
|
raise ValueError("\n".join(parsed["errors"]))
|
||||||
|
name = (document_name or "").strip() or f"Импорт ведомости — {sheet_name}"
|
||||||
try:
|
try:
|
||||||
doc = boq.BoqDocument(project_id=project_id, name=f"Импорт ведомости — {sheet_name}",
|
doc = boq.BoqDocument(
|
||||||
source_file=Path(file_path).name, version="1.0")
|
project_id=project_id,
|
||||||
|
name=name,
|
||||||
|
source_file=Path(file_path).name,
|
||||||
|
version="1.0",
|
||||||
|
document_number=(document_number or "").strip() or None,
|
||||||
|
document_date=document_date,
|
||||||
|
contract=(contract or "").strip() or None,
|
||||||
|
)
|
||||||
db.add(doc)
|
db.add(doc)
|
||||||
db.flush()
|
db.flush()
|
||||||
systems: Dict[str, boq.System] = {}
|
systems: Dict[str, boq.System] = {}
|
||||||
@@ -202,7 +221,8 @@ def import_excel_data(db: Session, file_path: str, sheet_name: str, header_row:
|
|||||||
).scalar()
|
).scalar()
|
||||||
db_total_display = Decimal(str(db_total or 0)).quantize(Decimal("0.01"))
|
db_total_display = Decimal(str(db_total or 0)).quantize(Decimal("0.01"))
|
||||||
excel_total_display = parsed["excel_total"].quantize(Decimal("0.01"))
|
excel_total_display = parsed["excel_total"].quantize(Decimal("0.01"))
|
||||||
return {"status": "success", "document_id": doc.id, "systems": len(systems), "sections": len(sections),
|
return {"status": "success", "document_id": doc.id, "document_name": doc.display_name,
|
||||||
|
"systems": len(systems), "sections": len(sections),
|
||||||
"work_items": parsed["work_items_count"], "total_amount": db_total_display,
|
"work_items": parsed["work_items_count"], "total_amount": db_total_display,
|
||||||
"db_total": db_total_display, "excel_total": excel_total_display,
|
"db_total": db_total_display, "excel_total": excel_total_display,
|
||||||
"difference": db_total_display - excel_total_display}
|
"difference": db_total_display - excel_total_display}
|
||||||
|
|||||||
+9
-2
@@ -1,18 +1,22 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from fastapi.templating import Jinja2Templates
|
from fastapi.templating import Jinja2Templates
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Import routers
|
# Import routers
|
||||||
from app.routers import projects, boq as boq_router, daily_reports, agreements, ks2
|
from app.routers import projects, boq as boq_router, daily_reports, agreements, ks2, ks3, ks6a, payments
|
||||||
|
|
||||||
# Import models to ensure they're registered
|
# Import models to ensure they're registered
|
||||||
from app.models import project as project_models, boq as boq_models
|
from app.models import project as project_models, boq as boq_models
|
||||||
from app.models import daily_report as daily_report_models
|
from app.models import daily_report as daily_report_models
|
||||||
|
from app.models import daily_report_photo as daily_report_photo_models
|
||||||
from app.models import work_journal as work_journal_models
|
from app.models import work_journal as work_journal_models
|
||||||
from app.models import agreement as agreement_models
|
from app.models import agreement as agreement_models
|
||||||
from app.models import ks2 as ks2_models
|
from app.models import ks2 as ks2_models
|
||||||
|
from app.models import ks3 as ks3_models
|
||||||
|
from app.models import payment as payment_models
|
||||||
|
from app.models import document_artifact as document_artifact_models
|
||||||
|
|
||||||
# Initialize database
|
# Initialize database
|
||||||
from app.database.database import engine
|
from app.database.database import engine
|
||||||
@@ -43,6 +47,9 @@ app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
|
|||||||
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
||||||
app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
|
app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
|
||||||
app.include_router(ks2.router, prefix="/projects", tags=["ks2"])
|
app.include_router(ks2.router, prefix="/projects", tags=["ks2"])
|
||||||
|
app.include_router(ks3.router, prefix="/projects", tags=["ks3"])
|
||||||
|
app.include_router(ks6a.router, prefix="/projects", tags=["ks6a"])
|
||||||
|
app.include_router(payments.router, prefix="/projects", tags=["payments"])
|
||||||
|
|
||||||
@app.get("/", include_in_schema=False)
|
@app.get("/", include_in_schema=False)
|
||||||
async def read_root():
|
async def read_root():
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from app.database.database import Base
|
|||||||
class Agreement(Base):
|
class Agreement(Base):
|
||||||
__tablename__ = "agreements"
|
__tablename__ = "agreements"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
CheckConstraint("status IN ('draft', 'approved')", name="ck_agreements_status"),
|
CheckConstraint("status IN ('draft', 'approved', 'cancelled')", name="ck_agreements_status"),
|
||||||
UniqueConstraint("project_id", "number", name="uq_agreements_project_number"),
|
UniqueConstraint("project_id", "number", name="uq_agreements_project_number"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -14,12 +14,35 @@ class BoqDocument(Base):
|
|||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
version = Column(String)
|
version = Column(String)
|
||||||
source_file = Column(String)
|
source_file = Column(String)
|
||||||
|
document_number = Column(String)
|
||||||
|
document_date = Column(Date)
|
||||||
|
contract = Column(String)
|
||||||
created_at = Column(DateTime, default=func.now())
|
created_at = Column(DateTime, default=func.now())
|
||||||
|
|
||||||
# Relationship to project
|
# Relationship to project
|
||||||
project = relationship("Project", back_populates="boq_documents")
|
project = relationship("Project", back_populates="boq_documents")
|
||||||
agreement = relationship("Agreement", back_populates="boq_documents", foreign_keys=[agreement_id])
|
agreement = relationship("Agreement", back_populates="boq_documents", foreign_keys=[agreement_id])
|
||||||
|
|
||||||
|
_TECHNICAL_PREFIXES = (
|
||||||
|
"BOQ Import - ",
|
||||||
|
"BOQ Import — ",
|
||||||
|
"BOQ Import —",
|
||||||
|
"BOQ Import -",
|
||||||
|
"Импорт ведомости — ",
|
||||||
|
"Импорт ведомости - ",
|
||||||
|
"Импорт ведомости —",
|
||||||
|
"Импорт ведомости -",
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display_name(self) -> str:
|
||||||
|
name = (self.name or "").strip()
|
||||||
|
for prefix in self._TECHNICAL_PREFIXES:
|
||||||
|
if name.startswith(prefix):
|
||||||
|
name = name[len(prefix):].strip(" —-–")
|
||||||
|
break
|
||||||
|
return name or f"Ведомость #{self.id}"
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<BoqDocument(id={self.id}, name='{self.name}')>"
|
return f"<BoqDocument(id={self.id}, name='{self.name}')>"
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class DailyReport(Base):
|
|||||||
project = relationship("Project")
|
project = relationship("Project")
|
||||||
system = relationship("System")
|
system = relationship("System")
|
||||||
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
||||||
|
photos = relationship("DailyReportPhoto", back_populates="report", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
class DailyReportItem(Base):
|
class DailyReportItem(Base):
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Daily Report photo metadata.
|
||||||
|
|
||||||
|
Photo files live in the managed application storage, never in SQLite. This
|
||||||
|
table keeps metadata and the link to the owning Daily Report. Binary content
|
||||||
|
is not stored here.
|
||||||
|
|
||||||
|
Photos are attached to the Daily Report as a whole (REQ), not to individual
|
||||||
|
work positions.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import (
|
||||||
|
Column,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Integer,
|
||||||
|
String,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DailyReportPhoto(Base):
|
||||||
|
__tablename__ = "daily_report_photos"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
|
daily_report_id = Column(
|
||||||
|
Integer, ForeignKey("daily_reports.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
# Relative path under DOCUMENT_STORAGE_ROOT. Never an absolute path or URL.
|
||||||
|
storage_key = Column(String, nullable=False)
|
||||||
|
# Display-only label from the uploader. Never used to build a path.
|
||||||
|
original_name = Column(String, nullable=True)
|
||||||
|
content_type = Column(String(100), nullable=False)
|
||||||
|
file_size = Column(Integer, nullable=False)
|
||||||
|
content_hash = Column(String(64), nullable=False)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0, server_default="0")
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
|
||||||
|
report = relationship("DailyReport", back_populates="photos")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return (
|
||||||
|
f"<DailyReportPhoto(id={self.id}, report={self.daily_report_id}, "
|
||||||
|
f"size={self.file_size}, type={self.content_type!r})>"
|
||||||
|
)
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Document artifact metadata.
|
||||||
|
|
||||||
|
Printed document files are stored outside SQLite. This table keeps metadata
|
||||||
|
about generated artifacts (type, storage key, template version, hashes,
|
||||||
|
currency flag). Binary content is never stored here.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import (
|
||||||
|
Boolean,
|
||||||
|
Column,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Integer,
|
||||||
|
String,
|
||||||
|
Index,
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentArtifact(Base):
|
||||||
|
__tablename__ = "document_artifacts"
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_document_artifacts_type_doc", "document_type", "document_id"),
|
||||||
|
Index("ix_document_artifacts_project_id", "project_id"),
|
||||||
|
Index(
|
||||||
|
"ix_document_artifacts_current",
|
||||||
|
"document_type",
|
||||||
|
"document_id",
|
||||||
|
"is_current",
|
||||||
|
),
|
||||||
|
# At most one current artifact per (document_type, document_id, format).
|
||||||
|
# Partial unique index: history rows (is_current = 0) may repeat freely.
|
||||||
|
Index(
|
||||||
|
"uq_document_artifact_current",
|
||||||
|
"document_type",
|
||||||
|
"document_id",
|
||||||
|
"format",
|
||||||
|
unique=True,
|
||||||
|
sqlite_where=text("is_current = 1"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
||||||
|
# Polymorphic link to the source document (ks2 / ks3 / ...).
|
||||||
|
document_type = Column(String, nullable=False)
|
||||||
|
document_id = Column(Integer, nullable=False)
|
||||||
|
format = Column(String, nullable=False)
|
||||||
|
# Relative path under DOCUMENT_STORAGE_ROOT. Never an absolute path or URL.
|
||||||
|
storage_key = Column(String, nullable=False)
|
||||||
|
template_type = Column(String, nullable=False)
|
||||||
|
template_version = Column(Integer, nullable=False)
|
||||||
|
content_hash = Column(String(64), nullable=False)
|
||||||
|
input_hash = Column(String(64), nullable=False)
|
||||||
|
is_current = Column(Boolean, nullable=False, default=True, server_default="1")
|
||||||
|
generated_at = Column(DateTime, nullable=False)
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
updated_at = Column(
|
||||||
|
DateTime, nullable=False, server_default=func.now(), onupdate=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
project = relationship("Project")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return (
|
||||||
|
f"<DocumentArtifact(id={self.id}, type={self.document_type!r}, "
|
||||||
|
f"doc={self.document_id}, format={self.format!r}, current={self.is_current})>"
|
||||||
|
)
|
||||||
+3
-1
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from sqlalchemy.sql import func
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
@@ -13,6 +13,8 @@ class KS2(Base):
|
|||||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
number = Column(String, nullable=False)
|
number = Column(String, nullable=False)
|
||||||
date = Column(Date, nullable=False, index=True)
|
date = Column(Date, nullable=False, index=True)
|
||||||
|
reporting_period_from = Column(Date, nullable=True)
|
||||||
|
reporting_period_to = Column(Date, nullable=True)
|
||||||
comment = Column(Text)
|
comment = Column(Text)
|
||||||
status = Column(String, nullable=False, default="draft", index=True)
|
status = Column(String, nullable=False, default="draft", index=True)
|
||||||
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class KS3(Base):
|
||||||
|
__tablename__ = "ks3_documents"
|
||||||
|
__table_args__ = (UniqueConstraint("project_id", "number", name="uq_ks3_project_number"),)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
|
number = Column(String, nullable=False)
|
||||||
|
date = Column(Date, nullable=False, index=True)
|
||||||
|
reporting_period_from = Column(Date, nullable=True)
|
||||||
|
reporting_period_to = Column(Date, nullable=True)
|
||||||
|
comment = Column(Text)
|
||||||
|
status = Column(String, nullable=False, default="draft", index=True)
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
project = relationship("Project")
|
||||||
|
links = relationship("KS3KS2", back_populates="ks3", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class KS3KS2(Base):
|
||||||
|
__tablename__ = "ks3_ks2_links"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("ks3_id", "ks2_id", name="uq_ks3_ks2_link"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
ks3_id = Column(Integer, ForeignKey("ks3_documents.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
ks2_id = Column(Integer, ForeignKey("ks2_documents.id"), nullable=False, index=True)
|
||||||
|
|
||||||
|
ks3 = relationship("KS3", back_populates="links")
|
||||||
|
ks2 = relationship("KS2")
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Payment(Base):
|
||||||
|
__tablename__ = "payments"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
|
date = Column(Date, nullable=False, index=True)
|
||||||
|
document_number = Column(String, nullable=True)
|
||||||
|
amount = Column(Numeric(18, 2), nullable=False)
|
||||||
|
currency = Column(String, nullable=False, default="RUB")
|
||||||
|
comment = Column(Text)
|
||||||
|
status = Column(String, nullable=False, default="active", index=True)
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
project = relationship("Project")
|
||||||
|
allocations = relationship("PaymentAllocation", back_populates="payment", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentAllocation(Base):
|
||||||
|
__tablename__ = "payment_allocations"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("payment_id", "ks3_id", name="uq_payment_ks3"),
|
||||||
|
CheckConstraint("amount > 0", name="ck_payment_alloc_positive"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
payment_id = Column(Integer, ForeignKey("payments.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
ks3_id = Column(Integer, ForeignKey("ks3_documents.id"), nullable=False, index=True)
|
||||||
|
amount = Column(Numeric(18, 2), nullable=False)
|
||||||
|
|
||||||
|
payment = relationship("Payment", back_populates="allocations")
|
||||||
|
ks3 = relationship("KS3")
|
||||||
+19
-2
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Date, DateTime, Text, Enum
|
from sqlalchemy import Column, Integer, String, Date, DateTime, Text, Numeric
|
||||||
from sqlalchemy.sql import func
|
from sqlalchemy.sql import func
|
||||||
from app.database.database import Base
|
from app.database.database import Base
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -12,7 +12,7 @@ class Project(Base):
|
|||||||
name = Column(String, index=True, nullable=False)
|
name = Column(String, index=True, nullable=False)
|
||||||
contract_number = Column(String)
|
contract_number = Column(String)
|
||||||
contract_date = Column(Date)
|
contract_date = Column(Date)
|
||||||
customer = Column(String)
|
customer = Column(String) # domain: customer_name
|
||||||
currency = Column(String, default="RUB")
|
currency = Column(String, default="RUB")
|
||||||
start_date = Column(Date)
|
start_date = Column(Date)
|
||||||
end_date = Column(Date)
|
end_date = Column(Date)
|
||||||
@@ -20,10 +20,27 @@ class Project(Base):
|
|||||||
created_at = Column(DateTime, default=func.now())
|
created_at = Column(DateTime, default=func.now())
|
||||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
# Official document requisites (DOC-B10)
|
||||||
|
investor_name = Column(String)
|
||||||
|
customer_name = Column(String) # preferred domain name for customer
|
||||||
|
contractor_name = Column(String)
|
||||||
|
construction_name = Column(String)
|
||||||
|
object_name = Column(String)
|
||||||
|
contract_amount = Column(Numeric(18, 2))
|
||||||
|
contractor_signer_name = Column(String)
|
||||||
|
contractor_signer_position = Column(String)
|
||||||
|
customer_signer_name = Column(String)
|
||||||
|
customer_signer_position = Column(String)
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
boq_documents = relationship("BoqDocument", back_populates="project")
|
boq_documents = relationship("BoqDocument", back_populates="project")
|
||||||
systems = relationship("System", back_populates="project")
|
systems = relationship("System", back_populates="project")
|
||||||
agreements = relationship("Agreement", back_populates="project", cascade="all, delete-orphan")
|
agreements = relationship("Agreement", back_populates="project", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def effective_customer_name(self) -> str:
|
||||||
|
"""Return customer_name if set, else fall back to legacy customer field."""
|
||||||
|
return self.customer_name or self.customer or ""
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<Project(id={self.id}, name='{self.name}')>"
|
return f"<Project(id={self.id}, name='{self.name}')>"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from app.services.agreement_items import (
|
|||||||
add_existing_item,
|
add_existing_item,
|
||||||
add_new_item,
|
add_new_item,
|
||||||
available_work_items,
|
available_work_items,
|
||||||
|
delete_draft_agreement,
|
||||||
delete_draft_item,
|
delete_draft_item,
|
||||||
update_draft_item,
|
update_draft_item,
|
||||||
)
|
)
|
||||||
@@ -61,7 +62,7 @@ def _scope_label(agreement, docs):
|
|||||||
if agreement.boq_document_id is None:
|
if agreement.boq_document_id is None:
|
||||||
return "Весь проект"
|
return "Весь проект"
|
||||||
doc = next((doc for doc in docs if doc.id == agreement.boq_document_id), None)
|
doc = next((doc for doc in docs if doc.id == agreement.boq_document_id), None)
|
||||||
return doc.name if doc else f"Ведомость #{agreement.boq_document_id}"
|
return doc.display_name if doc else f"Ведомость #{agreement.boq_document_id}"
|
||||||
|
|
||||||
|
|
||||||
def _parse_scope(db, project_id, scope):
|
def _parse_scope(db, project_id, scope):
|
||||||
@@ -379,6 +380,19 @@ async def remove_item(project_id: int, agreement_id: int, line_id: int,
|
|||||||
return _detail_response(request, db, project_obj, agreement, str(exc), 409)
|
return _detail_response(request, db, project_obj, agreement, str(exc), 409)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/agreements/{agreement_id}/delete")
|
||||||
|
async def delete_agreement(project_id: int, agreement_id: int, db: Session = Depends(get_db)):
|
||||||
|
_project(db, project_id)
|
||||||
|
agreement = _agreement(db, project_id, agreement_id)
|
||||||
|
try:
|
||||||
|
delete_draft_agreement(db, agreement)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(
|
||||||
|
f"/projects/{project_id}/agreements?deleted=1", status_code=303
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/agreements/{agreement_id}/approve")
|
@router.post("/{project_id}/agreements/{agreement_id}/approve")
|
||||||
async def confirm_approval(project_id: int, agreement_id: int, request: Request,
|
async def confirm_approval(project_id: int, agreement_id: int, request: Request,
|
||||||
db: Session = Depends(get_db)):
|
db: Session = Depends(get_db)):
|
||||||
@@ -390,3 +404,18 @@ async def confirm_approval(project_id: int, agreement_id: int, request: Request,
|
|||||||
db.rollback()
|
db.rollback()
|
||||||
return _detail_response(request, db, _project(db, project_id),
|
return _detail_response(request, db, _project(db, project_id),
|
||||||
_agreement(db, project_id, agreement_id), str(exc), 400)
|
_agreement(db, project_id, agreement_id), str(exc), 400)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/agreements/{agreement_id}/cancel")
|
||||||
|
async def cancel_agreement_route(project_id: int, agreement_id: int, request: Request,
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
|
from app.services.agreement_items import cancel_agreement, agreement_cancel_block_reason
|
||||||
|
|
||||||
|
agreement = _agreement(db, project_id, agreement_id)
|
||||||
|
try:
|
||||||
|
cancel_agreement(db, agreement)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||||
|
except ValueError as exc:
|
||||||
|
db.rollback()
|
||||||
|
return _detail_response(request, db, _project(db, project_id),
|
||||||
|
_agreement(db, project_id, agreement_id), str(exc), 400)
|
||||||
|
|||||||
+109
-8
@@ -1,15 +1,31 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File
|
from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
from app.config import uploads_dir
|
||||||
from app.database import database
|
from app.database import database
|
||||||
from app.models import project, boq
|
from app.models import project, boq
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
from app.importer import excel_importer
|
from app.importer import excel_importer
|
||||||
from typing import List
|
|
||||||
import os
|
import os
|
||||||
|
from datetime import date
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
UPLOAD_DIR = Path(__file__).resolve().parents[1] / "uploads"
|
UPLOAD_DIR = uploads_dir()
|
||||||
|
|
||||||
|
|
||||||
|
def _completed_quantities(db, project_id, items):
|
||||||
|
item_ids = [item.id for item in items]
|
||||||
|
if not item_ids:
|
||||||
|
return {}
|
||||||
|
rows = db.query(DailyReportItem.work_item_id, DailyReportItem.completed_quantity).join(
|
||||||
|
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||||
|
).filter(DailyReport.project_id == project_id, DailyReportItem.work_item_id.in_(item_ids)).all()
|
||||||
|
totals = {}
|
||||||
|
for wid, qty in rows:
|
||||||
|
totals[wid] = totals.get(wid, Decimal("0")) + Decimal(str(qty or 0))
|
||||||
|
return totals
|
||||||
|
|
||||||
# Dependency
|
# Dependency
|
||||||
def get_db():
|
def get_db():
|
||||||
@@ -45,9 +61,7 @@ async def view_boq_document(request: Request, project_id: int, document_id: int,
|
|||||||
).first()
|
).first()
|
||||||
if document is None:
|
if document is None:
|
||||||
raise HTTPException(status_code=404, detail="BOQ document not found")
|
raise HTTPException(status_code=404, detail="BOQ document not found")
|
||||||
document_title = document.name.replace("BOQ Import - ", "Импорт ведомости — ").replace(
|
document_title = document.display_name
|
||||||
"BOQ Import — ", "Импорт ведомости — "
|
|
||||||
)
|
|
||||||
|
|
||||||
items = db.query(boq.WorkItem).filter(
|
items = db.query(boq.WorkItem).filter(
|
||||||
boq.WorkItem.boq_document_id == document_id,
|
boq.WorkItem.boq_document_id == document_id,
|
||||||
@@ -79,13 +93,67 @@ async def view_boq_document(request: Request, project_id: int, document_id: int,
|
|||||||
"document_title": document_title,
|
"document_title": document_title,
|
||||||
"systems": tree, "total": total,
|
"systems": tree, "total": total,
|
||||||
"unassigned_items": [item for item in items if item.system_id is None or item.section_id is None],
|
"unassigned_items": [item for item in items if item.system_id is None or item.section_id is None],
|
||||||
|
"completed_by_item": _completed_quantities(db, project_id, items),
|
||||||
|
"has_history": _has_history(db, items),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _has_history(db, items):
|
||||||
|
"""Check if BOQ items participate in DailyReports / KS2 / KS3 / Payments."""
|
||||||
|
item_ids = [i.id for i in items]
|
||||||
|
if not item_ids:
|
||||||
|
return False
|
||||||
|
if db.query(DailyReportItem).filter(DailyReportItem.work_item_id.in_(item_ids)).first():
|
||||||
|
return True
|
||||||
|
from app.models.ks2 import KS2Item
|
||||||
|
if db.query(KS2Item).filter(KS2Item.work_item_id.in_(item_ids)).first():
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/documents/{document_id}/delete")
|
||||||
|
async def delete_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = db.query(boq.BoqDocument).filter(
|
||||||
|
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if document is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
items = db.query(boq.WorkItem).filter(boq.WorkItem.boq_document_id == document_id).all()
|
||||||
|
if _has_history(db, items):
|
||||||
|
raise HTTPException(status_code=400, detail="Cannot delete document with history. Archive it instead.")
|
||||||
|
try:
|
||||||
|
for item in items:
|
||||||
|
db.delete(item)
|
||||||
|
db.delete(document)
|
||||||
|
db.commit()
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=400, detail="Cannot delete document with related data")
|
||||||
|
return RedirectResponse(f"/boq/{project_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/documents/{document_id}/archive")
|
||||||
|
async def archive_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = db.query(boq.BoqDocument).filter(
|
||||||
|
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if document is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
if document.version == "archived":
|
||||||
|
raise HTTPException(status_code=400, detail="Already archived")
|
||||||
|
document.version = "archived"
|
||||||
|
db.commit()
|
||||||
|
return RedirectResponse(f"/boq/{project_id}/documents/{document_id}", status_code=303)
|
||||||
|
|
||||||
@router.post("/{project_id}/import/upload")
|
@router.post("/{project_id}/import/upload")
|
||||||
async def upload_excel_file(
|
async def upload_excel_file(
|
||||||
request: Request,
|
request: Request,
|
||||||
project_id: int,
|
project_id: int,
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
|
document_name: str = Form(""),
|
||||||
|
document_number: str = Form(""),
|
||||||
|
document_date: str = Form(""),
|
||||||
|
contract: str = Form(""),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
@@ -107,7 +175,11 @@ async def upload_excel_file(
|
|||||||
"project": db_project,
|
"project": db_project,
|
||||||
"project_id": project_id,
|
"project_id": project_id,
|
||||||
"filename": filename,
|
"filename": filename,
|
||||||
"sheets": sheets
|
"sheets": sheets,
|
||||||
|
"document_name": document_name,
|
||||||
|
"document_number": document_number,
|
||||||
|
"document_date": document_date,
|
||||||
|
"contract": contract,
|
||||||
})
|
})
|
||||||
|
|
||||||
@router.post("/{project_id}/import/preview")
|
@router.post("/{project_id}/import/preview")
|
||||||
@@ -118,6 +190,10 @@ async def preview_import(
|
|||||||
sheet_name: str = Form(...),
|
sheet_name: str = Form(...),
|
||||||
header_row: int = Form(...),
|
header_row: int = Form(...),
|
||||||
start_row: int = Form(...),
|
start_row: int = Form(...),
|
||||||
|
document_name: str = Form(""),
|
||||||
|
document_number: str = Form(""),
|
||||||
|
document_date: str = Form(""),
|
||||||
|
contract: str = Form(""),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
# Get the file path
|
# Get the file path
|
||||||
@@ -141,9 +217,20 @@ async def preview_import(
|
|||||||
"filename": filename,
|
"filename": filename,
|
||||||
"sheet_name": sheet_name,
|
"sheet_name": sheet_name,
|
||||||
"header_row": header_row,
|
"header_row": header_row,
|
||||||
"start_row": start_row
|
"start_row": start_row,
|
||||||
|
"document_name": document_name or sheet_name,
|
||||||
|
"document_number": document_number,
|
||||||
|
"document_date": document_date,
|
||||||
|
"contract": contract or (db_project.contract_number or ""),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
def _parse_optional_date(value: str):
|
||||||
|
value = (value or "").strip()
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
return date.fromisoformat(value)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/import/confirm")
|
@router.post("/{project_id}/import/confirm")
|
||||||
async def confirm_import(
|
async def confirm_import(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -152,6 +239,10 @@ async def confirm_import(
|
|||||||
sheet_name: str = Form(...),
|
sheet_name: str = Form(...),
|
||||||
header_row: int = Form(...),
|
header_row: int = Form(...),
|
||||||
start_row: int = Form(...),
|
start_row: int = Form(...),
|
||||||
|
document_name: str = Form(""),
|
||||||
|
document_number: str = Form(""),
|
||||||
|
document_date: str = Form(""),
|
||||||
|
contract: str = Form(""),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
# Get the file path
|
# Get the file path
|
||||||
@@ -162,7 +253,17 @@ async def confirm_import(
|
|||||||
if db_project is None:
|
if db_project is None:
|
||||||
raise HTTPException(status_code=404, detail="Project not found")
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
try:
|
try:
|
||||||
result = excel_importer.import_excel_data(db, file_path, sheet_name, header_row, start_row, project_id)
|
parsed_date = _parse_optional_date(document_date)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail="Дата ведомости должна быть в формате ГГГГ-ММ-ДД") from exc
|
||||||
|
try:
|
||||||
|
result = excel_importer.import_excel_data(
|
||||||
|
db, file_path, sheet_name, header_row, start_row, project_id,
|
||||||
|
document_name=document_name,
|
||||||
|
document_number=document_number,
|
||||||
|
document_date=parsed_date,
|
||||||
|
contract=contract,
|
||||||
|
)
|
||||||
except (ValueError, OSError) as exc:
|
except (ValueError, OSError) as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|||||||
+297
-32
@@ -1,14 +1,36 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app.database.database import SessionLocal
|
from app.database.database import SessionLocal
|
||||||
from app.models import boq, project
|
from app.models import boq, project
|
||||||
from app.models.daily_report import DailyReport, DailyReportItem
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.ks2 import KS2ItemSource
|
||||||
|
from app.services.daily_report_service import (
|
||||||
|
DailyReportError,
|
||||||
|
apply_quantities,
|
||||||
|
can_delete_item,
|
||||||
|
can_delete_report,
|
||||||
|
delete_item,
|
||||||
|
delete_report,
|
||||||
|
has_closed_volume,
|
||||||
|
report_close_infos,
|
||||||
|
)
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
DailyReportPhotoError,
|
||||||
|
PhotoNotFoundError,
|
||||||
|
PhotoValidationError,
|
||||||
|
MAX_PHOTOS_PER_REPORT,
|
||||||
|
MAX_PHOTO_BYTES,
|
||||||
|
ALLOWED_IMAGE_TYPES,
|
||||||
|
delete_photo,
|
||||||
|
persist_photos,
|
||||||
|
photo_file_bytes,
|
||||||
|
)
|
||||||
from app.services.effective_plan import build_effective_plan
|
from app.services.effective_plan import build_effective_plan
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -38,7 +60,8 @@ def _report_or_404(db: Session, project_id: int, report_id: int):
|
|||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_report_id=None):
|
def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_report_id=None,
|
||||||
|
all_systems: bool = False):
|
||||||
totals = db.query(
|
totals = db.query(
|
||||||
DailyReportItem.work_item_id.label("work_item_id"),
|
DailyReportItem.work_item_id.label("work_item_id"),
|
||||||
func.sum(DailyReportItem.completed_quantity).label("completed"),
|
func.sum(DailyReportItem.completed_quantity).label("completed"),
|
||||||
@@ -53,14 +76,15 @@ def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_re
|
|||||||
rows = []
|
rows = []
|
||||||
for planned in plan["items"]:
|
for planned in plan["items"]:
|
||||||
item = planned.item
|
item = planned.item
|
||||||
if item.system_id == system_id:
|
if all_systems or item.system_id == system_id:
|
||||||
rows.append({"item": item, "planned_quantity": planned.quantity,
|
rows.append({"item": item, "planned_quantity": planned.quantity,
|
||||||
"accumulated": totals.get(item.id, Decimal("0"))})
|
"accumulated": totals.get(item.id, Decimal("0"))})
|
||||||
rows.sort(key=lambda row: (row["item"].section_id or 0, row["item"].id))
|
rows.sort(key=lambda row: (row["item"].section_id or 0, row["item"].id))
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None):
|
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None,
|
||||||
|
form_values=None, status_code=200):
|
||||||
effective = build_effective_plan(db, project_obj.id)["items"]
|
effective = build_effective_plan(db, project_obj.id)["items"]
|
||||||
token = "unclassified" if system_id == "unclassified" else (str(system_id) if system_id not in (None, "") else None)
|
token = "unclassified" if system_id == "unclassified" else (str(system_id) if system_id not in (None, "") else None)
|
||||||
unclassified = [row for row in effective if row.item.system_id is None]
|
unclassified = [row for row in effective if row.item.system_id is None]
|
||||||
@@ -73,7 +97,7 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
|
|||||||
).order_by(boq.System.sort_order, boq.System.id).all()
|
).order_by(boq.System.sort_order, boq.System.id).all()
|
||||||
unclassified_selected = token == "unclassified" or (report is not None and report.system_id is None and token is None)
|
unclassified_selected = token == "unclassified" or (report is not None and report.system_id is None and token is None)
|
||||||
selected_system = None
|
selected_system = None
|
||||||
rows = []
|
selected_id = None
|
||||||
if token is not None:
|
if token is not None:
|
||||||
if token == "unclassified":
|
if token == "unclassified":
|
||||||
if not unclassified:
|
if not unclassified:
|
||||||
@@ -87,16 +111,49 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
|
|||||||
selected_system = next((row for row in systems if row.id == selected_id), None)
|
selected_system = next((row for row in systems if row.id == selected_id), None)
|
||||||
if selected_system is None:
|
if selected_system is None:
|
||||||
raise HTTPException(status_code=400, detail="System does not belong to this project effective plan")
|
raise HTTPException(status_code=400, detail="System does not belong to this project effective plan")
|
||||||
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None)
|
# DOC-C10: always render every effective position — the picker filters by
|
||||||
current = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
|
# system client-side and switching systems must not drop already-added rows.
|
||||||
|
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None,
|
||||||
|
all_systems=True)
|
||||||
|
form_values = form_values or {}
|
||||||
|
if report is not None:
|
||||||
|
current = {line.work_item_id: line.completed_quantity for line in report.items}
|
||||||
|
else:
|
||||||
|
# Error recovery: re-show the quantities the user already submitted so a
|
||||||
|
# photo/quantity problem never wipes their in-progress report.
|
||||||
|
current = {}
|
||||||
|
for key, value in form_values.items():
|
||||||
|
if not key.startswith("quantity_"):
|
||||||
|
continue
|
||||||
|
raw = (value or "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
item_id = int(key.removeprefix("quantity_"))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
qty = Decimal(raw.replace(",", "."))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
continue
|
||||||
|
if qty.is_finite() and qty > 0:
|
||||||
|
current[item_id] = qty
|
||||||
for row in rows:
|
for row in rows:
|
||||||
row["current_quantity"] = current.get(row["item"].id)
|
row["current_quantity"] = current.get(row["item"].id)
|
||||||
row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
|
row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
|
||||||
|
row["in_selection"] = token is not None and row["item"].system_id == selected_id
|
||||||
|
existing_photos = list(report.photos) if report is not None else []
|
||||||
|
existing_photos.sort(key=lambda p: (p.sort_order, p.id))
|
||||||
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
||||||
"request": request, "project": project_obj, "systems": systems,
|
"request": request, "project": project_obj, "systems": systems,
|
||||||
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
|
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
|
||||||
"selected_system": selected_system, "rows": rows, "report": report, "errors": errors or [],
|
"selected_system": selected_system, "rows": rows, "report": report, "errors": errors or [],
|
||||||
})
|
"form_values": form_values,
|
||||||
|
"existing_photos": existing_photos,
|
||||||
|
"photo_limit": MAX_PHOTOS_PER_REPORT,
|
||||||
|
"photo_max_bytes": MAX_PHOTO_BYTES,
|
||||||
|
"photo_formats": ", ".join(sorted({ext for ext in ALLOWED_IMAGE_TYPES})),
|
||||||
|
}, status_code=status_code)
|
||||||
|
|
||||||
|
|
||||||
def _parse_system_selection(db, project_id, token):
|
def _parse_system_selection(db, project_id, token):
|
||||||
@@ -130,10 +187,69 @@ async def new_daily_report(request: Request, project_id: int, system_id: str = N
|
|||||||
return _render_form(request, db, _project_or_404(db, project_id), system_id)
|
return _render_form(request, db, _project_or_404(db, project_id), system_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_uploads(files) -> list[tuple[bytes, str | None, str | None]]:
|
||||||
|
"""Read upload payloads into memory (content, original_name, content_type)."""
|
||||||
|
uploads: list[tuple[bytes, str | None, str | None]] = []
|
||||||
|
for upload in files or []:
|
||||||
|
filename = getattr(upload, "filename", "") or ""
|
||||||
|
if not filename.strip():
|
||||||
|
continue
|
||||||
|
content = upload.file.read()
|
||||||
|
uploads.append((content, filename, getattr(upload, "content_type", None)))
|
||||||
|
return uploads
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_uploads(uploads) -> list[str]:
|
||||||
|
"""Pure validation of upload payloads. No filesystem, no DB writes."""
|
||||||
|
from app.services.daily_report_photo_service import validate_upload
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
for content, name, ctype in uploads:
|
||||||
|
try:
|
||||||
|
validate_upload(content, name, ctype)
|
||||||
|
except PhotoValidationError as exc:
|
||||||
|
errors.append(f"{name or 'файл'}: {exc}")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_photo_ids_from_form(form) -> list[int]:
|
||||||
|
ids: list[int] = []
|
||||||
|
for key, value in form.multi_items():
|
||||||
|
if not key.startswith("delete_photo_"):
|
||||||
|
continue
|
||||||
|
if value not in ("1", "on", "true"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ids.append(int(key.removeprefix("delete_photo_")))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _save_report_photos(db, project_obj, report, uploads):
|
||||||
|
"""Persist pre-validated photos; return error list (empty on success)."""
|
||||||
|
if not uploads:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
persist_photos(
|
||||||
|
db,
|
||||||
|
project_id=project_obj.id,
|
||||||
|
daily_report_id=report.id,
|
||||||
|
uploads=uploads,
|
||||||
|
)
|
||||||
|
except PhotoValidationError as exc:
|
||||||
|
return [str(exc)]
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
return [f"Не удалось сохранить фото: {exc}"]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/daily-reports")
|
@router.post("/{project_id}/daily-reports")
|
||||||
async def create_daily_report(request: Request, project_id: int,
|
async def create_daily_report(request: Request, project_id: int,
|
||||||
report_date: str = Form(...), system_id: str = Form(...),
|
report_date: str = Form(...), system_id: str = Form(...),
|
||||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
notes: str = Form(""),
|
||||||
|
files: list[UploadFile] = File(default=[]),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
try:
|
try:
|
||||||
parsed_date = date.fromisoformat(report_date)
|
parsed_date = date.fromisoformat(report_date)
|
||||||
@@ -141,17 +257,32 @@ async def create_daily_report(request: Request, project_id: int,
|
|||||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||||
system_id = _parse_system_selection(db, project_id, system_id)
|
system_id = _parse_system_selection(db, project_id, system_id)
|
||||||
form = await request.form()
|
form = await request.form()
|
||||||
|
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||||
quantities, errors = _quantities_from_form(form)
|
quantities, errors = _quantities_from_form(form)
|
||||||
|
uploads = _collect_uploads(files)
|
||||||
|
errors.extend(_validate_uploads(uploads))
|
||||||
|
selection = "unclassified" if system_id is None else system_id
|
||||||
|
# Nothing is written yet: the user keeps every already-entered field.
|
||||||
if errors:
|
if errors:
|
||||||
selection = "unclassified" if system_id is None else system_id
|
return _render_form(request, db, project_obj, selection, errors=errors,
|
||||||
return _render_form(request, db, project_obj, selection, errors=errors)
|
form_values=form_values, status_code=400)
|
||||||
_validate_work_items(db, project_id, system_id, quantities)
|
_validate_work_items(db, project_id, system_id, quantities)
|
||||||
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
||||||
notes=notes.strip() or None)
|
notes=notes.strip() or None)
|
||||||
for item_id, quantity in quantities.items():
|
for item_id, quantity in quantities.items():
|
||||||
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
||||||
db.add(report)
|
db.add(report)
|
||||||
db.commit()
|
db.flush()
|
||||||
|
photo_errors = _save_report_photos(db, project_obj, report, uploads)
|
||||||
|
if photo_errors:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, errors=photo_errors,
|
||||||
|
form_values=form_values, status_code=400)
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=500, detail=f"Не удалось создать отчёт: {exc}") from exc
|
||||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -160,7 +291,7 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
db: Session = Depends(get_db)):
|
db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
report = _report_or_404(db, project_id, report_id)
|
report = _report_or_404(db, project_id, report_id)
|
||||||
rows = _report_rows(db, project_id, report.system_id, report.id)
|
rows = _report_rows(db, project_id, report.system_id, report.id, all_systems=True)
|
||||||
lines = {line.work_item_id: line for line in report.items}
|
lines = {line.work_item_id: line for line in report.items}
|
||||||
displayed = []
|
displayed = []
|
||||||
warnings = []
|
warnings = []
|
||||||
@@ -175,44 +306,89 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
if row["over_plan"]:
|
if row["over_plan"]:
|
||||||
warnings.append(row)
|
warnings.append(row)
|
||||||
displayed.append(row)
|
displayed.append(row)
|
||||||
|
infos = report_close_infos(db, report)
|
||||||
|
info_by_work = {info.work_item_id: info for info in infos}
|
||||||
|
for row in displayed:
|
||||||
|
info = info_by_work.get(row["item"].id)
|
||||||
|
row["closed_quantity"] = info.closed_quantity if info else Decimal("0")
|
||||||
|
row["available_quantity"] = info.available_quantity if info else row["current_quantity"]
|
||||||
|
can_del, del_reason = can_delete_report(db, report)
|
||||||
|
system_names = sorted({row["item"].system.name for row in displayed if row["item"].system})
|
||||||
|
photos = sorted(report.photos, key=lambda p: (p.sort_order, p.id))
|
||||||
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
|
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
|
||||||
"request": request, "project": project_obj, "report": report,
|
"request": request, "project": project_obj, "report": report,
|
||||||
"rows": displayed, "warnings": warnings,
|
"rows": displayed, "warnings": warnings, "system_names": system_names,
|
||||||
|
"can_delete_report": can_del, "delete_blocked_reason": del_reason,
|
||||||
|
"photos": photos,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{project_id}/daily-reports/{report_id}/edit")
|
@router.get("/{project_id}/daily-reports/{report_id}/edit")
|
||||||
async def edit_daily_report(request: Request, project_id: int, report_id: int,
|
async def edit_daily_report(request: Request, project_id: int, report_id: int,
|
||||||
db: Session = Depends(get_db)):
|
system_id: str = None, db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
report = _report_or_404(db, project_id, report_id)
|
report = _report_or_404(db, project_id, report_id)
|
||||||
return _render_form(request, db, project_obj,
|
selection = system_id if system_id not in (None, "") else (
|
||||||
report.system_id if report.system_id is not None else "unclassified", report)
|
report.system_id if report.system_id is not None else "unclassified")
|
||||||
|
return _render_form(request, db, project_obj, selection, report)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/daily-reports/{report_id}/edit")
|
@router.post("/{project_id}/daily-reports/{report_id}/edit")
|
||||||
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
||||||
report_date: str = Form(...), system_id: str = Form(...),
|
report_date: str = Form(...), system_id: str = Form(...),
|
||||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
notes: str = Form(""),
|
||||||
|
files: list[UploadFile] = File(default=[]),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
report = _report_or_404(db, project_id, report_id)
|
report = _report_or_404(db, project_id, report_id)
|
||||||
try:
|
try:
|
||||||
report.report_date = date.fromisoformat(report_date)
|
parsed_date = date.fromisoformat(report_date)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||||
system_id = _parse_system_selection(db, project_id, system_id)
|
system_id = _parse_system_selection(db, project_id, system_id)
|
||||||
form = await request.form()
|
form = await request.form()
|
||||||
|
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||||
quantities, errors = _quantities_from_form(form)
|
quantities, errors = _quantities_from_form(form)
|
||||||
|
uploads = _collect_uploads(files)
|
||||||
|
errors.extend(_validate_uploads(uploads))
|
||||||
|
delete_ids = _delete_photo_ids_from_form(form)
|
||||||
|
selection = "unclassified" if system_id is None else system_id
|
||||||
|
# Nothing is written yet: the user keeps every already-entered field.
|
||||||
if errors:
|
if errors:
|
||||||
selection = "unclassified" if system_id is None else system_id
|
return _render_form(request, db, project_obj, selection, report, errors,
|
||||||
return _render_form(request, db, project_obj, selection, report, errors)
|
form_values=form_values, status_code=400)
|
||||||
_validate_work_items(db, project_id, system_id, quantities)
|
_validate_work_items(db, project_id, system_id, quantities)
|
||||||
report.system_id = system_id
|
try:
|
||||||
report.notes = notes.strip() or None
|
apply_quantities(
|
||||||
db.query(DailyReportItem).filter(DailyReportItem.daily_report_id == report.id).delete()
|
db, report, quantities,
|
||||||
report.items = [DailyReportItem(work_item_id=item_id, completed_quantity=quantity)
|
new_date=parsed_date, system_id=system_id, notes=notes.strip() or None,
|
||||||
for item_id, quantity in quantities.items()]
|
)
|
||||||
db.commit()
|
except DailyReportError as exc:
|
||||||
|
return _render_form(request, db, project_obj, selection, report, [str(exc)],
|
||||||
|
form_values=form_values, status_code=400)
|
||||||
|
# Photo changes are explicit and separate from the volume lifecycle.
|
||||||
|
try:
|
||||||
|
if delete_ids:
|
||||||
|
owned = {p.id: p for p in report.photos}
|
||||||
|
for photo_id in delete_ids:
|
||||||
|
photo = owned.get(photo_id)
|
||||||
|
if photo is not None:
|
||||||
|
delete_photo(db, photo)
|
||||||
|
if uploads:
|
||||||
|
photo_errors = _save_report_photos(db, project_obj, report, uploads)
|
||||||
|
if photo_errors:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
photo_errors, form_values=form_values, status_code=400)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
[f"Не удалось обновить фотографии: {exc}"], form_values=form_values, status_code=400)
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
[f"Не удалось сохранить фотографии: {exc}"], form_values=form_values, status_code=400)
|
||||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -238,7 +414,96 @@ def _quantities_from_form(form):
|
|||||||
|
|
||||||
|
|
||||||
def _validate_work_items(db, project_id, system_id, quantities):
|
def _validate_work_items(db, project_id, system_id, quantities):
|
||||||
effective_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]
|
"""Quantities must reference effective-plan items of the project.
|
||||||
if row.item.system_id == system_id}
|
|
||||||
if effective_ids.intersection(quantities) != set(quantities):
|
Items may come from several systems at once: one Daily Report can hold
|
||||||
raise HTTPException(status_code=400, detail="One or more work items are not part of the selected system effective plan")
|
positions of multiple systems, so only project membership is enforced.
|
||||||
|
"""
|
||||||
|
effective_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]}
|
||||||
|
if not set(quantities).issubset(effective_ids):
|
||||||
|
raise HTTPException(status_code=400, detail="One or more work items are not part of the project effective plan")
|
||||||
|
|
||||||
|
|
||||||
|
def _ks2_closed_item_ids(db, report_id):
|
||||||
|
"""Return DailyReportItem ids already closed via KS-2 for this report."""
|
||||||
|
rows = db.query(KS2ItemSource.daily_report_item_id).join(
|
||||||
|
DailyReportItem, DailyReportItem.id == KS2ItemSource.daily_report_item_id
|
||||||
|
).filter(DailyReportItem.daily_report_id == report_id).distinct().all()
|
||||||
|
return {r[0] for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/daily-reports/{report_id}/delete")
|
||||||
|
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
# Photo files live outside SQLite — collect keys before the cascade drops rows.
|
||||||
|
photo_keys = [p.storage_key for p in report.photos]
|
||||||
|
try:
|
||||||
|
delete_report(db, report)
|
||||||
|
except DailyReportError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
from app.services.daily_report_photo_service import remove_photo_file
|
||||||
|
for key in photo_keys:
|
||||||
|
remove_photo_file(key)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/daily-reports/{report_id}/photos/{photo_id}/delete")
|
||||||
|
async def delete_daily_report_photo(
|
||||||
|
project_id: int, report_id: int, photo_id: int, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""Explicit photo removal. Never implied by editing volumes or systems."""
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
photo = next((p for p in report.photos if p.id == photo_id), None)
|
||||||
|
if photo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Photo not found")
|
||||||
|
try:
|
||||||
|
delete_photo(db, photo)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=500, detail=f"Не удалось удалить фото: {exc}") from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/daily-reports/{report_id}/photos/{photo_id}")
|
||||||
|
async def view_daily_report_photo(
|
||||||
|
project_id: int, report_id: int, photo_id: int, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""Serve the stored photo bytes. Read-only; no regeneration."""
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
photo = next((p for p in report.photos if p.id == photo_id), None)
|
||||||
|
if photo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Photo not found")
|
||||||
|
try:
|
||||||
|
content = photo_file_bytes(photo)
|
||||||
|
except PhotoNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
filename = photo.original_name or f"photo_{photo.id}"
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return Response(
|
||||||
|
content=content,
|
||||||
|
media_type=photo.content_type,
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/daily-reports/{report_id}/items/{item_id}/delete")
|
||||||
|
async def delete_daily_report_item(
|
||||||
|
project_id: int, report_id: int, item_id: int, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
item = next((i for i in report.items if i.id == item_id), None)
|
||||||
|
if item is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Daily report item not found")
|
||||||
|
try:
|
||||||
|
delete_item(db, item)
|
||||||
|
except DailyReportError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|||||||
+140
-15
@@ -1,9 +1,10 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from fastapi.templating import Jinja2Templates
|
from fastapi.templating import Jinja2Templates
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -15,9 +16,18 @@ from app.services.ks2_service import (
|
|||||||
)
|
)
|
||||||
from app.utils.formatters import format_money
|
from app.utils.formatters import format_money
|
||||||
|
|
||||||
|
|
||||||
|
def _quantity2(value):
|
||||||
|
try:
|
||||||
|
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||||
|
except Exception:
|
||||||
|
return "0.00"
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||||
templates.env.filters["money"] = format_money
|
templates.env.filters["money"] = format_money
|
||||||
|
templates.env.filters["quantity2"] = _quantity2
|
||||||
|
|
||||||
|
|
||||||
def _project(db, project_id):
|
def _project(db, project_id):
|
||||||
@@ -45,13 +55,28 @@ def _entries_from_form(form):
|
|||||||
return entries
|
return entries
|
||||||
|
|
||||||
|
|
||||||
def _render_selection(request, db, project, document=None, error=None, status_code=200):
|
def _render_selection(request, db, project, document=None, error=None, status_code=200,
|
||||||
|
suggested_number=None, form_values=None):
|
||||||
balances = build_work_item_balances(db, project.id)
|
balances = build_work_item_balances(db, project.id)
|
||||||
selected = {line.work_item_id: line.quantity for line in document.items} if document else {}
|
if document is not None:
|
||||||
|
selected = {line.work_item_id: line.quantity for line in document.items}
|
||||||
|
elif form_values:
|
||||||
|
selected = {}
|
||||||
|
for key, value in form_values.items():
|
||||||
|
if key.startswith("include_") and value in ("1", "on", "true"):
|
||||||
|
try:
|
||||||
|
item_id = int(key.removeprefix("include_"))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
selected[item_id] = form_values.get(f"quantity_{item_id}", "")
|
||||||
|
else:
|
||||||
|
selected = {}
|
||||||
visible = [row for row in balances if row.available_quantity > 0 or row.item.id in selected]
|
visible = [row for row in balances if row.available_quantity > 0 or row.item.id in selected]
|
||||||
return templates.TemplateResponse(request=request, name="ks2/form.html", context={
|
return templates.TemplateResponse(name="ks2/form.html", context={
|
||||||
"project": project, "document": document, "balances": visible,
|
"request": request, "project": project, "document": document, "balances": visible,
|
||||||
"selected": selected, "error": error,
|
"selected": selected, "error": error,
|
||||||
|
"suggested_number": suggested_number or "",
|
||||||
|
"form_values": form_values or {},
|
||||||
}, status_code=status_code)
|
}, status_code=status_code)
|
||||||
|
|
||||||
|
|
||||||
@@ -59,29 +84,41 @@ def _render_selection(request, db, project, document=None, error=None, status_co
|
|||||||
async def ks2_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
async def ks2_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
project = _project(db, project_id)
|
project = _project(db, project_id)
|
||||||
rows = project_ks2_totals(db, project_id)
|
rows = project_ks2_totals(db, project_id)
|
||||||
return templates.TemplateResponse(request=request, name="ks2/list.html", context={
|
return templates.TemplateResponse(name="ks2/list.html", context={
|
||||||
"project": project, "rows": rows,
|
"request": request, "project": project, "rows": rows,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{project_id}/ks2/new")
|
@router.get("/{project_id}/ks2/new")
|
||||||
async def ks2_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
async def ks2_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
project = _project(db, project_id)
|
project = _project(db, project_id)
|
||||||
return _render_selection(request, db, project)
|
from app.models.ks2 import KS2
|
||||||
|
from app.services.document_numbering import next_document_number
|
||||||
|
suggested = next_document_number(db, KS2, project_id)
|
||||||
|
return _render_selection(request, db, project, suggested_number=suggested)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/ks2")
|
@router.post("/{project_id}/ks2")
|
||||||
async def ks2_create(request: Request, project_id: int, number: str = Form(...),
|
async def ks2_create(request: Request, project_id: int, number: str = Form(...),
|
||||||
document_date: str = Form(...), comment: str = Form(""),
|
document_date: str = Form(...), comment: str = Form(""),
|
||||||
|
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||||
db: Session = Depends(get_db)):
|
db: Session = Depends(get_db)):
|
||||||
project = _project(db, project_id)
|
project = _project(db, project_id)
|
||||||
form = await request.form()
|
form = await request.form()
|
||||||
entries = _entries_from_form(form)
|
entries = _entries_from_form(form)
|
||||||
|
form_values = {key: value for key, value in form.multi_items() if not key.startswith("include_") and not key.startswith("quantity_")}
|
||||||
|
form_values.update({key: value for key, value in form.multi_items()})
|
||||||
try:
|
try:
|
||||||
parsed_date = date.fromisoformat(document_date)
|
parsed_date = date.fromisoformat(document_date)
|
||||||
document = save_draft(db, project_id, number, parsed_date, comment, entries)
|
document = save_draft(db, project_id, number, parsed_date, comment, entries,
|
||||||
|
reporting_period_from=reporting_period_from or None,
|
||||||
|
reporting_period_to=reporting_period_to or None)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return _render_selection(request, db, project, error=str(exc), status_code=400)
|
from app.models.ks2 import KS2
|
||||||
|
from app.services.document_numbering import next_document_number
|
||||||
|
suggested = next_document_number(db, KS2, project_id)
|
||||||
|
return _render_selection(request, db, project, error=str(exc), status_code=400,
|
||||||
|
suggested_number=suggested, form_values=form_values)
|
||||||
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -94,8 +131,11 @@ async def ks2_view(request: Request, project_id: int, ks2_id: int, db: Session =
|
|||||||
line.sources.sort(key=lambda source: (source.daily_report_item.report.report_date,
|
line.sources.sort(key=lambda source: (source.daily_report_item.report.report_date,
|
||||||
source.daily_report_item.report.id,
|
source.daily_report_item.report.id,
|
||||||
source.daily_report_item.id))
|
source.daily_report_item.id))
|
||||||
return templates.TemplateResponse(request=request, name="ks2/view.html", context={
|
from app.services.ks2_service import ks2_cancel_block_reason
|
||||||
"project": project, "document": document, "total": total,
|
cancel_reason = ks2_cancel_block_reason(db, project_id, ks2_id) if document.status != "cancelled" else None
|
||||||
|
return templates.TemplateResponse(name="ks2/view.html", context={
|
||||||
|
"request": request, "project": project, "document": document, "total": total,
|
||||||
|
"cancel_blocked_reason": cancel_reason,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -111,6 +151,7 @@ async def ks2_edit(request: Request, project_id: int, ks2_id: int, db: Session =
|
|||||||
@router.post("/{project_id}/ks2/{ks2_id}/edit")
|
@router.post("/{project_id}/ks2/{ks2_id}/edit")
|
||||||
async def ks2_update(request: Request, project_id: int, ks2_id: int,
|
async def ks2_update(request: Request, project_id: int, ks2_id: int,
|
||||||
number: str = Form(...), document_date: str = Form(...), comment: str = Form(""),
|
number: str = Form(...), document_date: str = Form(...), comment: str = Form(""),
|
||||||
|
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||||
db: Session = Depends(get_db)):
|
db: Session = Depends(get_db)):
|
||||||
project = _project(db, project_id)
|
project = _project(db, project_id)
|
||||||
document = _document(db, project_id, ks2_id)
|
document = _document(db, project_id, ks2_id)
|
||||||
@@ -118,11 +159,15 @@ async def ks2_update(request: Request, project_id: int, ks2_id: int,
|
|||||||
try:
|
try:
|
||||||
parsed_date = date.fromisoformat(document_date)
|
parsed_date = date.fromisoformat(document_date)
|
||||||
document = save_draft(db, project_id, number, parsed_date, comment,
|
document = save_draft(db, project_id, number, parsed_date, comment,
|
||||||
_entries_from_form(form), ks2_id=ks2_id)
|
_entries_from_form(form), ks2_id=ks2_id,
|
||||||
|
reporting_period_from=reporting_period_from or None,
|
||||||
|
reporting_period_to=reporting_period_to or None)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
db.expire_all()
|
db.expire_all()
|
||||||
document = _document(db, project_id, ks2_id)
|
document = _document(db, project_id, ks2_id)
|
||||||
return _render_selection(request, db, project, document=document, error=str(exc), status_code=400)
|
form_values = {key: value for key, value in form.multi_items()}
|
||||||
|
return _render_selection(request, db, project, document=document, error=str(exc),
|
||||||
|
status_code=400, form_values=form_values)
|
||||||
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -133,3 +178,83 @@ async def ks2_issue(project_id: int, ks2_id: int, db: Session = Depends(get_db))
|
|||||||
except KS2ValidationError as exc:
|
except KS2ValidationError as exc:
|
||||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/ks2/{ks2_id}/cancel")
|
||||||
|
async def ks2_cancel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||||
|
from app.services.ks2_service import KS2ValidationError, cancel_ks2
|
||||||
|
try:
|
||||||
|
cancel_ks2(db, project_id, ks2_id)
|
||||||
|
except KS2ValidationError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
def _content_disposition(filename: str) -> str:
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return content_disposition(filename)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks2/{ks2_id}/artifact")
|
||||||
|
async def ks2_download_artifact(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""Download the official issued artifact (stored file, no re-render)."""
|
||||||
|
from app.exporters import content_disposition, safe_export_filename
|
||||||
|
from app.services.document_artifact_service import (
|
||||||
|
ArtifactHashMismatchError,
|
||||||
|
ArtifactNotFoundError,
|
||||||
|
resolve_artifact,
|
||||||
|
)
|
||||||
|
|
||||||
|
document = _document(db, project_id, ks2_id)
|
||||||
|
if document.status == "draft":
|
||||||
|
raise HTTPException(status_code=409, detail="Официальная форма доступна только после проведения КС-2")
|
||||||
|
try:
|
||||||
|
artifact, content = resolve_artifact(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS2",
|
||||||
|
document_id=ks2_id,
|
||||||
|
format="xlsx",
|
||||||
|
)
|
||||||
|
except ArtifactNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail="Официальная форма недоступна: файл документа не найден.") from exc
|
||||||
|
except ArtifactHashMismatchError as exc:
|
||||||
|
raise HTTPException(status_code=500, detail="Файл документа повреждён и не может быть выдан.") from exc
|
||||||
|
filename = safe_export_filename("КС-2", document.number, document.date, "xlsx")
|
||||||
|
return Response(
|
||||||
|
content=content,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks2/{ks2_id}/export/excel")
|
||||||
|
async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = _document(db, project_id, ks2_id)
|
||||||
|
from app.exporters import safe_export_filename
|
||||||
|
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||||
|
from app.exporters.excel.ks2_renderer import render_ks2_excel
|
||||||
|
dto = build_ks2_export_dto(db, document)
|
||||||
|
data = render_ks2_excel(dto)
|
||||||
|
filename = safe_export_filename("КС-2", document.number, document.date, "xlsx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": _content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks2/{ks2_id}/export/word")
|
||||||
|
async def ks2_export_word(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = _document(db, project_id, ks2_id)
|
||||||
|
from app.exporters import safe_export_filename
|
||||||
|
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||||
|
from app.exporters.word.ks2_renderer import render_ks2_word
|
||||||
|
dto = build_ks2_export_dto(db, document)
|
||||||
|
data = render_ks2_word(dto)
|
||||||
|
filename = safe_export_filename("КС-2", document.number, document.date, "docx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
headers={"Content-Disposition": _content_disposition(filename)},
|
||||||
|
)
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||||
|
from fastapi.responses import RedirectResponse, Response
|
||||||
|
from fastapi.templating import Jinja2Templates
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from app.database.database import get_db
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
from app.services.ks3_service import (
|
||||||
|
KS3ValidationError, available_ks2, issue_ks3, project_ks3_totals, save_draft,
|
||||||
|
)
|
||||||
|
from app.utils.formatters import format_money
|
||||||
|
|
||||||
|
|
||||||
|
def _quantity2(value):
|
||||||
|
try:
|
||||||
|
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||||
|
except Exception:
|
||||||
|
return "0.00"
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||||
|
templates.env.filters["money"] = format_money
|
||||||
|
templates.env.filters["quantity2"] = _quantity2
|
||||||
|
|
||||||
|
|
||||||
|
def _project(db, project_id):
|
||||||
|
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||||
|
if obj is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
def _document(db, project_id, ks3_id):
|
||||||
|
doc = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||||
|
if doc is None:
|
||||||
|
raise HTTPException(status_code=404, detail="КС-3 не найден")
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def _ks2_total(ks2):
|
||||||
|
return sum(Decimal(str(item.amount or 0)) for item in ks2.items)
|
||||||
|
|
||||||
|
|
||||||
|
def _render_form(request, db, project, document=None, error=None, status_code=200,
|
||||||
|
suggested_number=None, form_values=None):
|
||||||
|
available = available_ks2(
|
||||||
|
db, project.id,
|
||||||
|
exclude_ks3_id=document.id if document is not None else None,
|
||||||
|
)
|
||||||
|
if document is not None:
|
||||||
|
selected_ids = {link.ks2_id for link in document.links}
|
||||||
|
elif form_values:
|
||||||
|
selected_ids = set()
|
||||||
|
for key, value in form_values.items():
|
||||||
|
if key == "ks2_ids":
|
||||||
|
try:
|
||||||
|
selected_ids.add(int(value))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
selected_ids = set()
|
||||||
|
return templates.TemplateResponse(name="ks3/form.html", context={
|
||||||
|
"request": request, "project": project, "document": document,
|
||||||
|
"available_ks2": available, "selected_ids": selected_ids, "error": error,
|
||||||
|
"suggested_number": suggested_number or "",
|
||||||
|
"form_values": form_values or {},
|
||||||
|
}, status_code=status_code)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3")
|
||||||
|
async def ks3_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
rows = project_ks3_totals(db, project_id)
|
||||||
|
return templates.TemplateResponse(name="ks3/list.html", context={
|
||||||
|
"request": request, "project": project, "rows": rows,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/new")
|
||||||
|
async def ks3_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
from app.models.ks3 import KS3
|
||||||
|
from app.services.document_numbering import next_document_number
|
||||||
|
suggested = next_document_number(db, KS3, project_id)
|
||||||
|
return _render_form(request, db, project, suggested_number=suggested)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/ks3")
|
||||||
|
async def ks3_create(request: Request, project_id: int,
|
||||||
|
number: str = Form(...), document_date: str = Form(...),
|
||||||
|
comment: str = Form(""),
|
||||||
|
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
form = await request.form()
|
||||||
|
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
|
||||||
|
form_values = {key: value for key, value in form.multi_items()}
|
||||||
|
try:
|
||||||
|
parsed_date = date.fromisoformat(document_date)
|
||||||
|
document = save_draft(
|
||||||
|
db, project_id, number, parsed_date, comment, ks2_ids,
|
||||||
|
reporting_period_from=reporting_period_from or None,
|
||||||
|
reporting_period_to=reporting_period_to or None,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
from app.models.ks3 import KS3
|
||||||
|
from app.services.document_numbering import next_document_number
|
||||||
|
suggested = next_document_number(db, KS3, project_id)
|
||||||
|
return _render_form(request, db, project, error=str(exc), status_code=400,
|
||||||
|
suggested_number=suggested, form_values=form_values)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/{ks3_id}")
|
||||||
|
async def ks3_view(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
total = Decimal("0")
|
||||||
|
ks2_rows = []
|
||||||
|
for link in document.links:
|
||||||
|
if link.ks2:
|
||||||
|
ks2_total = _ks2_total(link.ks2)
|
||||||
|
total += ks2_total
|
||||||
|
ks2_rows.append({"ks2": link.ks2, "total": ks2_total})
|
||||||
|
from app.services.ks3_service import ks3_cancel_block_reason
|
||||||
|
cancel_reason = ks3_cancel_block_reason(db, project_id, ks3_id) if document.status != "cancelled" else None
|
||||||
|
return templates.TemplateResponse(name="ks3/view.html", context={
|
||||||
|
"request": request, "project": project, "document": document,
|
||||||
|
"ks2_rows": ks2_rows, "total": total,
|
||||||
|
"cancel_blocked_reason": cancel_reason,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/{ks3_id}/edit")
|
||||||
|
async def ks3_edit(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
if document.status != "draft":
|
||||||
|
raise HTTPException(status_code=409, detail="Проведённый КС-3 нельзя редактировать")
|
||||||
|
return _render_form(request, db, project, document)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/ks3/{ks3_id}/edit")
|
||||||
|
async def ks3_update(request: Request, project_id: int, ks3_id: int,
|
||||||
|
number: str = Form(...), document_date: str = Form(...),
|
||||||
|
comment: str = Form(""),
|
||||||
|
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
form = await request.form()
|
||||||
|
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
|
||||||
|
try:
|
||||||
|
parsed_date = date.fromisoformat(document_date)
|
||||||
|
document = save_draft(
|
||||||
|
db, project_id, number, parsed_date, comment, ks2_ids,
|
||||||
|
reporting_period_from=reporting_period_from or None,
|
||||||
|
reporting_period_to=reporting_period_to or None,
|
||||||
|
ks3_id=ks3_id,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
db.expire_all()
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
form_values = {key: value for key, value in form.multi_items()}
|
||||||
|
return _render_form(request, db, project, document=document, error=str(exc),
|
||||||
|
status_code=400, form_values=form_values)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/ks3/{ks3_id}/issue")
|
||||||
|
async def ks3_issue(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
try:
|
||||||
|
issue_ks3(db, project_id, ks3_id)
|
||||||
|
except KS3ValidationError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/ks3/{ks3_id}/cancel")
|
||||||
|
async def ks3_cancel(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
from app.services.ks3_service import KS3ValidationError, cancel_ks3
|
||||||
|
try:
|
||||||
|
cancel_ks3(db, project_id, ks3_id)
|
||||||
|
except KS3ValidationError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/{ks3_id}/artifact")
|
||||||
|
async def ks3_download_artifact(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""Download the official issued artifact (stored file, no re-render)."""
|
||||||
|
from app.exporters import content_disposition, safe_export_filename
|
||||||
|
from app.services.document_artifact_service import (
|
||||||
|
ArtifactHashMismatchError,
|
||||||
|
ArtifactNotFoundError,
|
||||||
|
resolve_artifact,
|
||||||
|
)
|
||||||
|
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
if document.status == "draft":
|
||||||
|
raise HTTPException(status_code=409, detail="Официальная форма доступна только после проведения КС-3")
|
||||||
|
try:
|
||||||
|
artifact, content = resolve_artifact(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS3",
|
||||||
|
document_id=ks3_id,
|
||||||
|
format="docx",
|
||||||
|
)
|
||||||
|
except ArtifactNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail="Официальная форма недоступна: файл документа не найден.") from exc
|
||||||
|
except ArtifactHashMismatchError as exc:
|
||||||
|
raise HTTPException(status_code=500, detail="Файл документа повреждён и не может быть выдан.") from exc
|
||||||
|
filename = safe_export_filename("КС-3", document.number, document.date, "docx")
|
||||||
|
return Response(
|
||||||
|
content=content,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/{ks3_id}/export/excel")
|
||||||
|
async def ks3_export_excel(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
from app.exporters import safe_export_filename, content_disposition
|
||||||
|
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||||
|
from app.exporters.excel.ks3_renderer import render_ks3_excel
|
||||||
|
dto = build_ks3_export_dto(db, document)
|
||||||
|
data = render_ks3_excel(dto)
|
||||||
|
filename = safe_export_filename("КС-3", document.number, document.date, "xlsx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks3/{ks3_id}/export/word")
|
||||||
|
async def ks3_export_word(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||||
|
document = _document(db, project_id, ks3_id)
|
||||||
|
from app.exporters import safe_export_filename, content_disposition
|
||||||
|
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||||
|
from app.exporters.word.ks3_renderer import render_ks3_word
|
||||||
|
dto = build_ks3_export_dto(db, document)
|
||||||
|
data = render_ks3_word(dto)
|
||||||
|
filename = safe_export_filename("КС-3", document.number, document.date, "docx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
|
from fastapi.responses import Response
|
||||||
|
from fastapi.templating import Jinja2Templates
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.database.database import get_db
|
||||||
|
from app.models.boq import System
|
||||||
|
from app.models.project import Project
|
||||||
|
|
||||||
|
|
||||||
|
def _quantity2(value):
|
||||||
|
try:
|
||||||
|
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||||
|
except Exception:
|
||||||
|
return "0.00"
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||||
|
templates.env.filters["quantity2"] = _quantity2
|
||||||
|
|
||||||
|
|
||||||
|
def _project(db, project_id):
|
||||||
|
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||||
|
if obj is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks6a")
|
||||||
|
async def ks6a_journal(
|
||||||
|
request: Request,
|
||||||
|
project_id: int,
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
system_id: str = "",
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
systems = db.query(System).filter(
|
||||||
|
System.project_id == project_id
|
||||||
|
).order_by(System.sort_order, System.id).all()
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
total_count = 0
|
||||||
|
parsed_from = None
|
||||||
|
parsed_to = None
|
||||||
|
error = None
|
||||||
|
|
||||||
|
if date_from and date_to:
|
||||||
|
try:
|
||||||
|
parsed_from = date.fromisoformat(date_from)
|
||||||
|
parsed_to = date.fromisoformat(date_to)
|
||||||
|
except ValueError:
|
||||||
|
error = "Неверный формат даты"
|
||||||
|
else:
|
||||||
|
if parsed_to < parsed_from:
|
||||||
|
error = "Дата окончания не может быть раньше даты начала"
|
||||||
|
|
||||||
|
if parsed_from and parsed_to and not error:
|
||||||
|
sid = None
|
||||||
|
if system_id and system_id != "all":
|
||||||
|
try:
|
||||||
|
sid = int(system_id)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
error = "Некорректный идентификатор системы"
|
||||||
|
|
||||||
|
if not error:
|
||||||
|
from app.exporters.ks6a_dto import fetch_ks6a_rows
|
||||||
|
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
|
||||||
|
total_count = len(rows)
|
||||||
|
|
||||||
|
return templates.TemplateResponse(name="ks6a/journal.html", context={
|
||||||
|
"request": request,
|
||||||
|
"project": project,
|
||||||
|
"systems": systems,
|
||||||
|
"rows": rows,
|
||||||
|
"total_count": total_count,
|
||||||
|
"date_from": date_from,
|
||||||
|
"date_to": date_to,
|
||||||
|
"system_id": system_id,
|
||||||
|
"error": error,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _export_filters(db, project_id: int, date_from: str, date_to: str, system_id: str):
|
||||||
|
if not date_from or not date_to:
|
||||||
|
raise HTTPException(status_code=400, detail="Необходимо указать период (date_from и date_to)")
|
||||||
|
try:
|
||||||
|
parsed_from = date.fromisoformat(date_from)
|
||||||
|
parsed_to = date.fromisoformat(date_to)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail="Неверный формат даты")
|
||||||
|
if parsed_to < parsed_from:
|
||||||
|
raise HTTPException(status_code=400, detail="Дата окончания не может быть раньше даты начала")
|
||||||
|
|
||||||
|
sid = None
|
||||||
|
system_name = ""
|
||||||
|
if system_id and system_id != "all":
|
||||||
|
try:
|
||||||
|
sid = int(system_id)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise HTTPException(status_code=400, detail="Некорректный идентификатор системы")
|
||||||
|
system = db.query(System).filter(
|
||||||
|
System.id == sid, System.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if system is None:
|
||||||
|
raise HTTPException(status_code=400, detail="Система не найдена")
|
||||||
|
system_name = system.name
|
||||||
|
|
||||||
|
return parsed_from, parsed_to, sid, system_name
|
||||||
|
|
||||||
|
|
||||||
|
def _export_filename(date_from, date_to, system_name: str, extension: str) -> str:
|
||||||
|
from app.exporters import safe_export_filename_period
|
||||||
|
return safe_export_filename_period("КС-6а", date_from, date_to, extension, suffix=system_name)
|
||||||
|
|
||||||
|
|
||||||
|
def _content_disposition(filename: str) -> str:
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return content_disposition(filename)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks6a/export/excel")
|
||||||
|
async def ks6a_export_excel(
|
||||||
|
project_id: int,
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
system_id: str = "",
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
parsed_from, parsed_to, sid, system_name = _export_filters(db, project_id, date_from, date_to, system_id)
|
||||||
|
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
|
||||||
|
from app.exporters.excel.ks6a_renderer import render_ks6a_excel
|
||||||
|
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
|
||||||
|
dto = build_ks6a_export_dto(project, rows, parsed_from, parsed_to, system_name)
|
||||||
|
data = render_ks6a_excel(dto)
|
||||||
|
filename = _export_filename(parsed_from, parsed_to, system_name, "xlsx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": _content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/ks6a/export/word")
|
||||||
|
async def ks6a_export_word(
|
||||||
|
project_id: int,
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
system_id: str = "",
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
parsed_from, parsed_to, sid, system_name = _export_filters(db, project_id, date_from, date_to, system_id)
|
||||||
|
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
|
||||||
|
from app.exporters.word.ks6a_renderer import render_ks6a_word
|
||||||
|
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
|
||||||
|
dto = build_ks6a_export_dto(project, rows, parsed_from, parsed_to, system_name)
|
||||||
|
data = render_ks6a_word(dto)
|
||||||
|
filename = _export_filename(parsed_from, parsed_to, system_name, "docx")
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
headers={"Content-Disposition": _content_disposition(filename)},
|
||||||
|
)
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
from fastapi.templating import Jinja2Templates
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from app.database.database import get_db
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
from app.services.payment_service import (
|
||||||
|
PaymentValidationError, _parse_money, available_ks3_for_payment, cancel_payment,
|
||||||
|
delete_payment, project_payments, save_payment,
|
||||||
|
)
|
||||||
|
from app.utils.formatters import format_money
|
||||||
|
|
||||||
|
|
||||||
|
def _quantity2(value):
|
||||||
|
try:
|
||||||
|
return f"{Decimal(str(value if value is not None else 0)):.2f}"
|
||||||
|
except Exception:
|
||||||
|
return "0.00"
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||||
|
templates.env.filters["money"] = format_money
|
||||||
|
templates.env.filters["quantity2"] = _quantity2
|
||||||
|
|
||||||
|
|
||||||
|
def _project(db, project_id):
|
||||||
|
obj = db.query(Project).filter(Project.id == project_id).first()
|
||||||
|
if obj is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Проект не найден")
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
def _payment(db, project_id, payment_id):
|
||||||
|
p = db.query(Payment).options(
|
||||||
|
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
|
||||||
|
).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
|
||||||
|
if p is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Платёж не найден")
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _render_form(request, db, project, payment=None, error=None, status_code=200):
|
||||||
|
available = available_ks3_for_payment(db, project.id, exclude_payment_id=payment.id if payment else None)
|
||||||
|
current_allocs = {a.ks3_id: Decimal(str(a.amount)) for a in payment.allocations} if payment else {}
|
||||||
|
return templates.TemplateResponse(name="payments/form.html", context={
|
||||||
|
"request": request, "project": project, "payment": payment,
|
||||||
|
"available_ks3": available, "current_allocs": current_allocs, "error": error,
|
||||||
|
}, status_code=status_code)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/payments")
|
||||||
|
async def payment_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
rows = project_payments(db, project_id)
|
||||||
|
return templates.TemplateResponse(name="payments/list.html", context={
|
||||||
|
"request": request, "project": project, "rows": rows,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/payments/new")
|
||||||
|
async def payment_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
return _render_form(request, db, project)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/payments")
|
||||||
|
async def payment_create(request: Request, project_id: int,
|
||||||
|
payment_date: str = Form(...),
|
||||||
|
document_number: str = Form(""),
|
||||||
|
amount: str = Form(...), currency: str = Form("RUB"),
|
||||||
|
comment: str = Form(""),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
form = await request.form()
|
||||||
|
allocations = []
|
||||||
|
for k, v in form.multi_items():
|
||||||
|
if k.startswith("alloc_") and v.strip():
|
||||||
|
try:
|
||||||
|
ks3_id = int(k.removeprefix("alloc_"))
|
||||||
|
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
|
||||||
|
if alloc_amount > 0:
|
||||||
|
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||||
|
except PaymentValidationError:
|
||||||
|
raise
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
parsed_date = date.fromisoformat(payment_date)
|
||||||
|
parsed_amount = _parse_money(amount, "Сумма платежа")
|
||||||
|
payment = save_payment(
|
||||||
|
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||||
|
allocations, document_number=document_number or None,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _render_form(request, db, project, error=str(exc), status_code=400)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/payments/{payment_id}")
|
||||||
|
async def payment_view(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
payment = _payment(db, project_id, payment_id)
|
||||||
|
allocated = sum(Decimal(str(a.amount)) for a in payment.allocations)
|
||||||
|
unallocated = max(Decimal(str(payment.amount)) - allocated, Decimal("0"))
|
||||||
|
return templates.TemplateResponse(name="payments/view.html", context={
|
||||||
|
"request": request, "project": project, "payment": payment,
|
||||||
|
"allocated": allocated, "unallocated": unallocated,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/payments/{payment_id}/edit")
|
||||||
|
async def payment_edit(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
payment = _payment(db, project_id, payment_id)
|
||||||
|
if payment.status == "cancelled":
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
|
||||||
|
return _render_form(request, db, project, payment)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/payments/{payment_id}/edit")
|
||||||
|
async def payment_update(request: Request, project_id: int, payment_id: int,
|
||||||
|
payment_date: str = Form(...),
|
||||||
|
document_number: str = Form(""),
|
||||||
|
amount: str = Form(...), currency: str = Form("RUB"),
|
||||||
|
comment: str = Form(""),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
|
project = _project(db, project_id)
|
||||||
|
form = await request.form()
|
||||||
|
allocations = []
|
||||||
|
for k, v in form.multi_items():
|
||||||
|
if k.startswith("alloc_") and v.strip():
|
||||||
|
try:
|
||||||
|
ks3_id = int(k.removeprefix("alloc_"))
|
||||||
|
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
|
||||||
|
if alloc_amount > 0:
|
||||||
|
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||||
|
except PaymentValidationError:
|
||||||
|
raise
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
parsed_date = date.fromisoformat(payment_date)
|
||||||
|
parsed_amount = _parse_money(amount, "Сумма платежа")
|
||||||
|
payment = save_payment(
|
||||||
|
db, project_id, parsed_date, parsed_amount, currency, comment,
|
||||||
|
allocations, document_number=document_number or None,
|
||||||
|
payment_id=payment_id,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
db.expire_all()
|
||||||
|
payment = _payment(db, project_id, payment_id)
|
||||||
|
return _render_form(request, db, project, payment=payment, error=str(exc), status_code=400)
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/payments/{payment_id}/delete")
|
||||||
|
async def payment_delete(project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||||
|
try:
|
||||||
|
delete_payment(db, project_id, payment_id)
|
||||||
|
except PaymentValidationError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/payments", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/payments/{payment_id}/cancel")
|
||||||
|
async def payment_cancel(project_id: int, payment_id: int, db: Session = Depends(get_db)):
|
||||||
|
try:
|
||||||
|
cancel_payment(db, project_id, payment_id)
|
||||||
|
except PaymentValidationError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
|
||||||
+271
-3
@@ -1,17 +1,24 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form, UploadFile, File
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
from app.config import import_uploads_dir
|
||||||
from app.database import database
|
from app.database import database
|
||||||
from app.models import project
|
from app.models import project
|
||||||
from app.models import boq
|
from app.models import boq
|
||||||
from app.services.project_dashboard import build_project_dashboard
|
from app.services.project_dashboard import build_project_dashboard
|
||||||
from app.services.effective_plan import BaseBoqConfigurationError
|
from app.services.effective_plan import BaseBoqConfigurationError
|
||||||
from app.models.daily_report import DailyReport
|
from app.models.daily_report import DailyReport
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
from app.models.ks3 import KS3
|
||||||
|
from app.models.payment import Payment
|
||||||
from app.models.work_journal import WorkJournalEntry
|
from app.models.work_journal import WorkJournalEntry
|
||||||
from typing import List
|
from typing import List
|
||||||
import os
|
import os
|
||||||
|
import secrets
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
IMPORT_UPLOAD_DIR = import_uploads_dir()
|
||||||
|
|
||||||
|
|
||||||
def _journal_entry_or_404(db: Session, project_id: int, entry_id: int):
|
def _journal_entry_or_404(db: Session, project_id: int, entry_id: int):
|
||||||
@@ -61,6 +68,114 @@ async def read_projects(request: Request, db: Session = Depends(get_db)):
|
|||||||
async def new_project(request: Request):
|
async def new_project(request: Request):
|
||||||
return request.app.templates.TemplateResponse("projects/new.html", {"request": request})
|
return request.app.templates.TemplateResponse("projects/new.html", {"request": request})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import")
|
||||||
|
async def project_import_form(request: Request):
|
||||||
|
return request.app.templates.TemplateResponse("projects/import_project.html", {
|
||||||
|
"request": request,
|
||||||
|
"error": None,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/settings/database-reset")
|
||||||
|
async def database_reset_form(request: Request, db: Session = Depends(get_db)):
|
||||||
|
from app.services.database_reset import count_project_data
|
||||||
|
counts = count_project_data(db)
|
||||||
|
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||||
|
"request": request,
|
||||||
|
"counts": counts,
|
||||||
|
"error": None,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/database-reset")
|
||||||
|
async def database_reset_submit(request: Request, db: Session = Depends(get_db)):
|
||||||
|
from app.services.database_reset import DatabaseResetError, count_project_data, reset_database
|
||||||
|
|
||||||
|
form = await request.form()
|
||||||
|
confirmation = (form.get("confirmation") or "").strip()
|
||||||
|
if confirmation != "УДАЛИТЬ ВСЕ ДАННЫЕ":
|
||||||
|
counts = count_project_data(db)
|
||||||
|
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||||
|
"request": request,
|
||||||
|
"counts": counts,
|
||||||
|
"error": "Ввод не совпадает с подтверждением. Данные не удалены.",
|
||||||
|
}, status_code=400)
|
||||||
|
try:
|
||||||
|
result = reset_database(db)
|
||||||
|
except DatabaseResetError as exc:
|
||||||
|
counts = count_project_data(db)
|
||||||
|
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||||
|
"request": request,
|
||||||
|
"counts": counts,
|
||||||
|
"error": str(exc),
|
||||||
|
}, status_code=500)
|
||||||
|
if result.storage_error:
|
||||||
|
# DB is clean but FS cleanup failed — still a partial success
|
||||||
|
return RedirectResponse(
|
||||||
|
url=f"/projects/?reset=1&storage_error=1", status_code=303
|
||||||
|
)
|
||||||
|
return RedirectResponse(url="/projects/?reset=1", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/import/upload")
|
||||||
|
async def project_import_upload(
|
||||||
|
request: Request,
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
from app.exporters.project_import import ProjectImportError, validate_archive
|
||||||
|
|
||||||
|
data = (file.file.read() or b"")
|
||||||
|
try:
|
||||||
|
preview = validate_archive(data)
|
||||||
|
except ProjectImportError as exc:
|
||||||
|
return request.app.templates.TemplateResponse("projects/import_project.html", {
|
||||||
|
"request": request,
|
||||||
|
"error": str(exc),
|
||||||
|
}, status_code=400)
|
||||||
|
|
||||||
|
token = secrets.token_hex(16)
|
||||||
|
IMPORT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
stored = IMPORT_UPLOAD_DIR / f"{token}.wvt.zip"
|
||||||
|
stored.write_bytes(data)
|
||||||
|
|
||||||
|
counts = preview["counts"]
|
||||||
|
return request.app.templates.TemplateResponse("projects/import_project_preview.html", {
|
||||||
|
"request": request,
|
||||||
|
"token": token,
|
||||||
|
"project_name": preview["project_name"],
|
||||||
|
"project": preview["project"],
|
||||||
|
"manifest": preview["manifest"],
|
||||||
|
"counts": counts,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/import/confirm")
|
||||||
|
async def project_import_confirm(
|
||||||
|
request: Request,
|
||||||
|
token: str = Form(...),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
from app.exporters.project_import import ProjectImportError, import_project
|
||||||
|
|
||||||
|
safe_token = Path(token).name
|
||||||
|
stored = IMPORT_UPLOAD_DIR / f"{safe_token}.wvt.zip"
|
||||||
|
if not stored.exists():
|
||||||
|
raise HTTPException(status_code=400, detail="Файл импорта не найден. Загрузите архив заново.")
|
||||||
|
data = stored.read_bytes()
|
||||||
|
try:
|
||||||
|
imported = import_project(db, data)
|
||||||
|
except ProjectImportError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
stored.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return RedirectResponse(url=f"/projects/{imported.id}?imported=1", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/create")
|
@router.post("/create")
|
||||||
async def create_project(
|
async def create_project(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -112,6 +227,25 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
|
|||||||
except BaseBoqConfigurationError as exc:
|
except BaseBoqConfigurationError as exc:
|
||||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
|
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
|
||||||
|
ks2_count = db.query(KS2).filter(KS2.project_id == project_id).count()
|
||||||
|
ks3_count = db.query(KS3).filter(KS3.project_id == project_id).count()
|
||||||
|
payments_count = db.query(Payment).filter(Payment.project_id == project_id).count()
|
||||||
|
from app.models.agreement import Agreement
|
||||||
|
agreements_count = db.query(Agreement).filter(Agreement.project_id == project_id).count()
|
||||||
|
from app.services.payment_service import ks3_payment_summary
|
||||||
|
payment_summary = ks3_payment_summary(db, project_id)
|
||||||
|
|
||||||
|
# Build document tree: base BOQ docs with scoped agreements + project-wide agreements
|
||||||
|
all_agreements = db.query(Agreement).filter(
|
||||||
|
Agreement.project_id == project_id
|
||||||
|
).order_by(Agreement.id).all()
|
||||||
|
base_docs = [d for d in boq_docs if d.agreement_id is None]
|
||||||
|
doc_tree = []
|
||||||
|
for doc in base_docs:
|
||||||
|
scoped = [a for a in all_agreements if a.boq_document_id == doc.id]
|
||||||
|
doc_tree.append({"doc": doc, "agreements": scoped})
|
||||||
|
project_wide = [a for a in all_agreements if a.boq_document_id is None]
|
||||||
|
|
||||||
journal_tasks = db.query(WorkJournalEntry).filter(
|
journal_tasks = db.query(WorkJournalEntry).filter(
|
||||||
WorkJournalEntry.project_id == project_id,
|
WorkJournalEntry.project_id == project_id,
|
||||||
WorkJournalEntry.type == "task",
|
WorkJournalEntry.type == "task",
|
||||||
@@ -128,8 +262,15 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
|
|||||||
"project": db_project,
|
"project": db_project,
|
||||||
"boq_docs": boq_docs,
|
"boq_docs": boq_docs,
|
||||||
"daily_reports_count": daily_reports,
|
"daily_reports_count": daily_reports,
|
||||||
|
"ks2_count": ks2_count,
|
||||||
|
"ks3_count": ks3_count,
|
||||||
|
"payments_count": payments_count,
|
||||||
|
"agreements_count": agreements_count,
|
||||||
|
"payment_summary": payment_summary,
|
||||||
"journal_tasks": journal_tasks,
|
"journal_tasks": journal_tasks,
|
||||||
"journal_notes": journal_notes,
|
"journal_notes": journal_notes,
|
||||||
|
"doc_tree": doc_tree,
|
||||||
|
"project_wide_agreements": project_wide,
|
||||||
**dashboard,
|
**dashboard,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -208,12 +349,23 @@ async def update_project(
|
|||||||
start_date: str = Form(None),
|
start_date: str = Form(None),
|
||||||
end_date: str = Form(None),
|
end_date: str = Form(None),
|
||||||
status: str = Form("active"),
|
status: str = Form("active"),
|
||||||
|
investor_name: str = Form(None),
|
||||||
|
customer_name: str = Form(None),
|
||||||
|
contractor_name: str = Form(None),
|
||||||
|
construction_name: str = Form(None),
|
||||||
|
object_name: str = Form(None),
|
||||||
|
contract_amount: str = Form(None),
|
||||||
|
contractor_signer_name: str = Form(None),
|
||||||
|
contractor_signer_position: str = Form(None),
|
||||||
|
customer_signer_name: str = Form(None),
|
||||||
|
customer_signer_position: str = Form(None),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
):
|
):
|
||||||
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
if db_project is None:
|
if db_project is None:
|
||||||
raise HTTPException(status_code=404, detail="Project not found")
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
try:
|
try:
|
||||||
db_project.contract_date = datetime.strptime(contract_date, "%Y-%m-%d").date() if contract_date else None
|
db_project.contract_date = datetime.strptime(contract_date, "%Y-%m-%d").date() if contract_date else None
|
||||||
db_project.start_date = datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else None
|
db_project.start_date = datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else None
|
||||||
@@ -222,9 +374,27 @@ async def update_project(
|
|||||||
raise HTTPException(status_code=400, detail="Dates must use YYYY-MM-DD format") from exc
|
raise HTTPException(status_code=400, detail="Dates must use YYYY-MM-DD format") from exc
|
||||||
db_project.name = name.strip()
|
db_project.name = name.strip()
|
||||||
db_project.contract_number = contract_number.strip() if contract_number else None
|
db_project.contract_number = contract_number.strip() if contract_number else None
|
||||||
db_project.customer = customer.strip() if customer else None
|
# customer_name is the domain field; customer is kept in sync for compatibility
|
||||||
|
resolved_customer = (customer_name or customer or "").strip() or None
|
||||||
|
db_project.customer_name = resolved_customer
|
||||||
|
db_project.customer = resolved_customer
|
||||||
db_project.currency = currency.strip() if currency else "RUB"
|
db_project.currency = currency.strip() if currency else "RUB"
|
||||||
db_project.status = status
|
db_project.status = status
|
||||||
|
db_project.investor_name = investor_name.strip() if investor_name else None
|
||||||
|
db_project.contractor_name = contractor_name.strip() if contractor_name else None
|
||||||
|
db_project.construction_name = construction_name.strip() if construction_name else None
|
||||||
|
db_project.object_name = object_name.strip() if object_name else None
|
||||||
|
db_project.contractor_signer_name = contractor_signer_name.strip() if contractor_signer_name else None
|
||||||
|
db_project.contractor_signer_position = contractor_signer_position.strip() if contractor_signer_position else None
|
||||||
|
db_project.customer_signer_name = customer_signer_name.strip() if customer_signer_name else None
|
||||||
|
db_project.customer_signer_position = customer_signer_position.strip() if customer_signer_position else None
|
||||||
|
if contract_amount:
|
||||||
|
try:
|
||||||
|
db_project.contract_amount = Decimal(contract_amount.strip().replace(",", "."))
|
||||||
|
except InvalidOperation:
|
||||||
|
raise HTTPException(status_code=400, detail="Сумма договора должна быть числом")
|
||||||
|
else:
|
||||||
|
db_project.contract_amount = None
|
||||||
db.commit()
|
db.commit()
|
||||||
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
||||||
|
|
||||||
@@ -239,3 +409,101 @@ async def import_boq(request: Request, project_id: int, db: Session = Depends(ge
|
|||||||
"request": request,
|
"request": request,
|
||||||
"project": db_project
|
"project": db_project
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _has_financial_history(db, project_id):
|
||||||
|
"""Check if project has issued KS-2/KS-3 or payments."""
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
from app.models.ks3 import KS3
|
||||||
|
from app.models.payment import Payment
|
||||||
|
if db.query(KS2).filter(KS2.project_id == project_id, KS2.status == "issued").first():
|
||||||
|
return True
|
||||||
|
if db.query(KS3).filter(KS3.project_id == project_id, KS3.status == "issued").first():
|
||||||
|
return True
|
||||||
|
if db.query(Payment).filter(Payment.project_id == project_id).first():
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/delete")
|
||||||
|
async def delete_project(project_id: int, db: Session = Depends(get_db)):
|
||||||
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
|
if db_project is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
if _has_financial_history(db, project_id):
|
||||||
|
raise HTTPException(status_code=400, detail="Cannot delete project with financial history. Archive it instead.")
|
||||||
|
try:
|
||||||
|
db.delete(db_project)
|
||||||
|
db.commit()
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=400, detail="Cannot delete project with related data")
|
||||||
|
return RedirectResponse(url="/projects/", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/archive")
|
||||||
|
async def archive_project(project_id: int, db: Session = Depends(get_db)):
|
||||||
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
|
if db_project is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
db_project.status = "archived"
|
||||||
|
db.commit()
|
||||||
|
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/export/package")
|
||||||
|
async def export_document_package(
|
||||||
|
project_id: int,
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
include: list[str] = Query(default=[]),
|
||||||
|
export_format: str = Query("both", alias="format"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
|
if db_project is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
|
||||||
|
from app.exporters.package_service import (
|
||||||
|
PackageEmptyError,
|
||||||
|
PackageValidationError,
|
||||||
|
build_document_package,
|
||||||
|
parse_package_params,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
parsed_from, parsed_to, selected, export_format = parse_package_params(
|
||||||
|
date_from, date_to, include, export_format
|
||||||
|
)
|
||||||
|
except PackageValidationError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
data, filename = build_document_package(
|
||||||
|
db, db_project, parsed_from, parsed_to, selected, export_format
|
||||||
|
)
|
||||||
|
except PackageEmptyError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/zip",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/export/project")
|
||||||
|
async def export_project_archive(project_id: int, db: Session = Depends(get_db)):
|
||||||
|
from app.exporters.project_export import ProjectExportError, export_project
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
|
||||||
|
try:
|
||||||
|
data, filename = export_project(db, project_id)
|
||||||
|
except ProjectExportError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/zip",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
from app.models import boq
|
from app.models import boq
|
||||||
from app.models.agreement import Agreement, AgreementItem
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
@@ -8,6 +10,8 @@ from app.services.effective_plan import (
|
|||||||
work_item_scope_document_id,
|
work_item_scope_document_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
def decimal_value(value, label):
|
def decimal_value(value, label):
|
||||||
try:
|
try:
|
||||||
@@ -239,3 +243,171 @@ def delete_draft_item(db, agreement, line):
|
|||||||
).first():
|
).first():
|
||||||
db.delete(document)
|
db.delete(document)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def _work_item_is_orphan_for_draft(db, item, agreement) -> bool:
|
||||||
|
"""True when this WorkItem exists only because of the given draft agreement."""
|
||||||
|
if item is None:
|
||||||
|
return False
|
||||||
|
if item.boq_document_id is not None:
|
||||||
|
return False
|
||||||
|
other_lines = db.query(AgreementItem.id).filter(
|
||||||
|
AgreementItem.work_item_id == item.id,
|
||||||
|
AgreementItem.agreement_id != agreement.id,
|
||||||
|
).first()
|
||||||
|
if other_lines is not None:
|
||||||
|
return False
|
||||||
|
from app.models.daily_report import DailyReportItem
|
||||||
|
from app.models.ks2 import KS2Item, KS2ItemSource
|
||||||
|
|
||||||
|
if db.query(DailyReportItem.id).filter(DailyReportItem.work_item_id == item.id).first():
|
||||||
|
return False
|
||||||
|
if db.query(KS2Item.id).filter(KS2Item.work_item_id == item.id).first():
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def delete_draft_agreement(db, agreement):
|
||||||
|
"""
|
||||||
|
Delete a draft Agreement and its items atomically.
|
||||||
|
|
||||||
|
Orphan WorkItems created solely for this draft (new_position) are removed.
|
||||||
|
Base WorkItems are never deleted. Approved agreements are rejected.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if agreement is None:
|
||||||
|
raise ValueError("Agreement not found")
|
||||||
|
_require_draft(agreement)
|
||||||
|
lines = list(agreement.items)
|
||||||
|
orphan_items = []
|
||||||
|
for line in lines:
|
||||||
|
if line.change_type == "new_position" and _work_item_is_orphan_for_draft(
|
||||||
|
db, line.work_item, agreement
|
||||||
|
):
|
||||||
|
orphan_items.append(line.work_item)
|
||||||
|
|
||||||
|
for item in orphan_items:
|
||||||
|
db.delete(item)
|
||||||
|
db.flush()
|
||||||
|
document = item.boq_document
|
||||||
|
if (
|
||||||
|
document is not None
|
||||||
|
and document.agreement_id == agreement.id
|
||||||
|
and not db.query(boq.WorkItem.id)
|
||||||
|
.filter(boq.WorkItem.boq_document_id == document.id)
|
||||||
|
.first()
|
||||||
|
):
|
||||||
|
db.delete(document)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
# ORM cascade on Agreement.items removes AgreementItem rows.
|
||||||
|
db.delete(agreement)
|
||||||
|
db.commit()
|
||||||
|
except ValueError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise ValueError(f"Failed to delete agreement: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _closed_quantity_for_work_item(db, work_item_id: int) -> Decimal:
|
||||||
|
"""Sum of KS2ItemSource quantities for a work item, excluding cancelled KS-2."""
|
||||||
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
|
|
||||||
|
total = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).join(
|
||||||
|
KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id
|
||||||
|
).join(
|
||||||
|
KS2, KS2.id == KS2Item.ks2_id
|
||||||
|
).filter(
|
||||||
|
KS2Item.work_item_id == work_item_id,
|
||||||
|
KS2.status != "cancelled",
|
||||||
|
).scalar()
|
||||||
|
return Decimal(str(total or 0))
|
||||||
|
|
||||||
|
|
||||||
|
def _agreement_item_used_volume(db, agreement, line: AgreementItem) -> Decimal:
|
||||||
|
"""
|
||||||
|
Return how much of *this* AgreementItem's positive delta is consumed by
|
||||||
|
non-cancelled KS-2 closings, using FIFO layering.
|
||||||
|
|
||||||
|
Layers are stacked bottom-up: base BOQ quantity first, then each approved
|
||||||
|
AgreementItem's quantity_delta in (Agreement.id, AgreementItem.id) order.
|
||||||
|
Closed volume fills from the bottom. For an increase / new_position line
|
||||||
|
the "used" part is the portion of closed volume that falls inside *that*
|
||||||
|
line's positive delta window.
|
||||||
|
|
||||||
|
For ``decrease`` lines the semantics of "used" are ambiguous (a decrease
|
||||||
|
only shrinks the plan), so we keep the pre-existing conservative rule:
|
||||||
|
any closed volume on the WorkItem blocks cancellation.
|
||||||
|
"""
|
||||||
|
if line.change_type == "decrease":
|
||||||
|
closed = _closed_quantity_for_work_item(db, line.work_item_id)
|
||||||
|
return closed if closed > ZERO else ZERO
|
||||||
|
|
||||||
|
item = db.query(boq.WorkItem).filter(boq.WorkItem.id == line.work_item_id).first()
|
||||||
|
base_qty = ZERO if line.change_type == "new_position" else (
|
||||||
|
Decimal(str(item.quantity)) if item and item.quantity is not None else ZERO
|
||||||
|
)
|
||||||
|
|
||||||
|
# All approved AgreementItems on this WorkItem, FIFO order.
|
||||||
|
all_lines = (
|
||||||
|
db.query(AgreementItem)
|
||||||
|
.join(Agreement, Agreement.id == AgreementItem.agreement_id)
|
||||||
|
.filter(
|
||||||
|
AgreementItem.work_item_id == line.work_item_id,
|
||||||
|
Agreement.status == "approved",
|
||||||
|
)
|
||||||
|
.order_by(Agreement.id, AgreementItem.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
prior_delta = ZERO
|
||||||
|
for aline in all_lines:
|
||||||
|
if aline.id == line.id:
|
||||||
|
break
|
||||||
|
prior_delta += Decimal(str(aline.quantity_delta))
|
||||||
|
|
||||||
|
floor = base_qty + prior_delta
|
||||||
|
closed = _closed_quantity_for_work_item(db, line.work_item_id)
|
||||||
|
delta = Decimal(str(line.quantity_delta))
|
||||||
|
return max(ZERO, min(closed - floor, delta))
|
||||||
|
|
||||||
|
|
||||||
|
def agreement_cancel_block_reason(db, agreement) -> str | None:
|
||||||
|
"""Return why an approved agreement cannot be cancelled, or None."""
|
||||||
|
if agreement.status == "draft":
|
||||||
|
return "Черновик нельзя отменить. Сначала утвердите ДС."
|
||||||
|
if agreement.status == "cancelled":
|
||||||
|
return "ДС уже отменено."
|
||||||
|
for line in agreement.items:
|
||||||
|
used = _agreement_item_used_volume(db, agreement, line)
|
||||||
|
if used > ZERO:
|
||||||
|
return "Нельзя отменить ДС: его объём уже использован в закрытых КС-2."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_agreement(db, agreement):
|
||||||
|
"""
|
||||||
|
Cancel an approved agreement atomically.
|
||||||
|
|
||||||
|
The agreement becomes cancelled and drops out of the effective plan.
|
||||||
|
AgreementItems, WorkItems and history are preserved.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
reason = agreement_cancel_block_reason(db, agreement)
|
||||||
|
if reason is not None:
|
||||||
|
raise ValueError(reason)
|
||||||
|
# Re-check status inside the transaction
|
||||||
|
if agreement.status != "approved":
|
||||||
|
raise ValueError("Отменить можно только утверждённое ДС")
|
||||||
|
agreement.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(agreement)
|
||||||
|
return agreement
|
||||||
|
except ValueError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise ValueError(f"Не удалось отменить ДС: {exc}") from exc
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
"""Daily Report photo service: validate, persist, resolve, delete.
|
||||||
|
|
||||||
|
Photos are attached to the whole Daily Report (REQ). Files live under the
|
||||||
|
managed document storage root; only metadata is stored in SQLite.
|
||||||
|
|
||||||
|
Storage key layout (server-generated only, never derived from user input):
|
||||||
|
|
||||||
|
projects/{project_id}/daily_reports/{daily_report_id}/photos/{uuid}.{ext}
|
||||||
|
|
||||||
|
Transaction ownership: the service does NOT commit. The caller manages the
|
||||||
|
database transaction. Filesystem writes use compensating cleanup on failure.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.config import document_storage_root
|
||||||
|
from app.models.daily_report_photo import DailyReportPhoto
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Limits and supported formats
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Accepted raster formats. Extension is only a hint — content is validated
|
||||||
|
# against magic bytes so a renamed non-image cannot be stored as a photo.
|
||||||
|
ALLOWED_IMAGE_TYPES: dict[str, str] = {
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".png": "image/png",
|
||||||
|
".webp": "image/webp",
|
||||||
|
}
|
||||||
|
ALLOWED_CONTENT_TYPES = frozenset(ALLOWED_IMAGE_TYPES.values())
|
||||||
|
|
||||||
|
# Hard limit per file. Larger uploads are rejected with a clear message.
|
||||||
|
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 10 MB
|
||||||
|
# Hard limit per Daily Report so a report cannot be flooded with uploads.
|
||||||
|
MAX_PHOTOS_PER_REPORT = 20
|
||||||
|
|
||||||
|
_SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9._-]+$")
|
||||||
|
|
||||||
|
|
||||||
|
class DailyReportPhotoError(ValueError):
|
||||||
|
"""Domain error raised by the photo service."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoNotFoundError(DailyReportPhotoError):
|
||||||
|
"""Photo row or physical file is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoPathError(DailyReportPhotoError):
|
||||||
|
"""storage_key is unsafe or escapes the storage root."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoValidationError(DailyReportPhotoError):
|
||||||
|
"""Uploaded file is not an accepted image or exceeds the limits."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Content validation
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def compute_content_hash(content: bytes) -> str:
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
return hashlib.sha256(content).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _sniff_extension(content: bytes) -> str | None:
|
||||||
|
"""Return the image extension implied by magic bytes, or None."""
|
||||||
|
if content.startswith(b"\xff\xd8\xff"):
|
||||||
|
return ".jpg"
|
||||||
|
if content.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return ".png"
|
||||||
|
if len(content) >= 12 and content[:4] == b"RIFF" and content[8:12] == b"WEBP":
|
||||||
|
return ".webp"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extension_for_name(filename: str | None) -> str:
|
||||||
|
if not filename:
|
||||||
|
return ""
|
||||||
|
return Path(str(filename)).suffix.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_upload(content: bytes, original_name: str | None, content_type: str | None) -> tuple[str, str]:
|
||||||
|
"""Validate an uploaded photo. Returns (extension, content_type).
|
||||||
|
|
||||||
|
The original file name is never used as a path — only its extension is
|
||||||
|
consulted as a hint and then cross-checked against the magic bytes.
|
||||||
|
"""
|
||||||
|
if not isinstance(content, (bytes, bytearray)):
|
||||||
|
raise PhotoValidationError("Файл фотографии повреждён")
|
||||||
|
content = bytes(content)
|
||||||
|
if not content:
|
||||||
|
raise PhotoValidationError("Файл фотографии пуст")
|
||||||
|
if len(content) > MAX_PHOTO_BYTES:
|
||||||
|
limit_mb = MAX_PHOTO_BYTES // (1024 * 1024)
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Файл слишком большой: {len(content) / (1024 * 1024):.1f} МБ "
|
||||||
|
f"при лимите {limit_mb} МБ"
|
||||||
|
)
|
||||||
|
|
||||||
|
sniffed = _sniff_extension(content)
|
||||||
|
if sniffed is None:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
"Неподдерживаемый формат файла: допускаются JPEG, PNG и WebP"
|
||||||
|
)
|
||||||
|
|
||||||
|
name_ext = _extension_for_name(original_name)
|
||||||
|
# Declared extension is only a hint; the content decides the real type.
|
||||||
|
if name_ext and name_ext in ALLOWED_IMAGE_TYPES and name_ext != sniffed and not (
|
||||||
|
sniffed == ".jpg" and name_ext == ".jpeg"
|
||||||
|
):
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Содержимое файла не соответствует расширению {name_ext}: "
|
||||||
|
f"ожидается {ALLOWED_IMAGE_TYPES[sniffed]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
declared_type = (content_type or "").split(";")[0].strip().lower()
|
||||||
|
real_type = ALLOWED_IMAGE_TYPES[sniffed]
|
||||||
|
if declared_type and declared_type in ALLOWED_CONTENT_TYPES and declared_type != real_type:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Тип содержимого не соответствует формату файла: {declared_type} ≠ {real_type}"
|
||||||
|
)
|
||||||
|
return sniffed, real_type
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Storage paths
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def build_photo_storage_key(
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
extension: str,
|
||||||
|
token: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Server-generated relative storage key. Never uses the original file name."""
|
||||||
|
project_id = int(project_id)
|
||||||
|
daily_report_id = int(daily_report_id)
|
||||||
|
if project_id <= 0 or daily_report_id <= 0:
|
||||||
|
raise PhotoPathError("project_id and daily_report_id must be positive")
|
||||||
|
ext = extension.lstrip(".").lower()
|
||||||
|
if not _SAFE_SEGMENT.match(ext):
|
||||||
|
raise PhotoPathError(f"Invalid extension: {extension!r}")
|
||||||
|
if f".{ext}" not in ALLOWED_IMAGE_TYPES:
|
||||||
|
raise PhotoPathError(f"Unsupported extension: {extension!r}")
|
||||||
|
name = f"{token or uuid.uuid4().hex}.{ext}"
|
||||||
|
return (
|
||||||
|
f"projects/{project_id}/daily_reports/{daily_report_id}/photos/{name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_photo_path(storage_key: str) -> Path:
|
||||||
|
"""Map a relative storage key to an absolute path inside the storage root."""
|
||||||
|
if not storage_key or not str(storage_key).strip():
|
||||||
|
raise PhotoPathError("storage_key is required")
|
||||||
|
key = str(storage_key).replace("\\", "/").strip()
|
||||||
|
if key.startswith("/") or re.match(r"^[A-Za-z]:", key):
|
||||||
|
raise PhotoPathError("storage_key must be relative")
|
||||||
|
if ".." in Path(key).parts:
|
||||||
|
raise PhotoPathError("storage_key must not contain '..'")
|
||||||
|
root = document_storage_root().resolve()
|
||||||
|
candidate = (root / key).resolve()
|
||||||
|
try:
|
||||||
|
candidate.relative_to(root)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise PhotoPathError("storage_key escapes storage root") from exc
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Persist / delete
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def count_photos(db: Session, daily_report_id: int) -> int:
|
||||||
|
return int(
|
||||||
|
db.execute(
|
||||||
|
select(func.count()).select_from(DailyReportPhoto).where(
|
||||||
|
DailyReportPhoto.daily_report_id == int(daily_report_id)
|
||||||
|
)
|
||||||
|
).scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def persist_photo(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
content: bytes,
|
||||||
|
original_name: str | None = None,
|
||||||
|
content_type: str | None = None,
|
||||||
|
sort_order: int = 0,
|
||||||
|
) -> DailyReportPhoto:
|
||||||
|
"""Validate, store photo bytes on disk and stage a DailyReportPhoto row.
|
||||||
|
|
||||||
|
Does NOT commit. The caller owns the transaction. On failure the file
|
||||||
|
created by this call is removed (compensating cleanup); existing photos
|
||||||
|
are never touched.
|
||||||
|
"""
|
||||||
|
content = bytes(content)
|
||||||
|
extension, real_type = validate_upload(content, original_name, content_type)
|
||||||
|
|
||||||
|
existing = count_photos(db, daily_report_id)
|
||||||
|
if existing >= MAX_PHOTOS_PER_REPORT:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"К отчёту уже прикреплено максимальное количество фото "
|
||||||
|
f"({MAX_PHOTOS_PER_REPORT})"
|
||||||
|
)
|
||||||
|
|
||||||
|
storage_key = build_photo_storage_key(project_id, daily_report_id, extension)
|
||||||
|
path = resolve_photo_path(storage_key)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
tmp_fd, tmp_name = tempfile.mkstemp(
|
||||||
|
dir=str(path.parent), prefix=".tmp-photo-", suffix=extension
|
||||||
|
)
|
||||||
|
tmp_path = Path(tmp_name)
|
||||||
|
try:
|
||||||
|
with os.fdopen(tmp_fd, "wb") as handle:
|
||||||
|
handle.write(content)
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
os.replace(tmp_path, path)
|
||||||
|
except Exception:
|
||||||
|
if tmp_path.exists():
|
||||||
|
try:
|
||||||
|
tmp_path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
photo = DailyReportPhoto(
|
||||||
|
project_id=int(project_id),
|
||||||
|
daily_report_id=int(daily_report_id),
|
||||||
|
storage_key=storage_key,
|
||||||
|
# Display only. Never used to build a path.
|
||||||
|
original_name=(str(original_name).strip()[:255] or None) if original_name else None,
|
||||||
|
content_type=real_type,
|
||||||
|
file_size=len(content),
|
||||||
|
content_hash=compute_content_hash(content),
|
||||||
|
sort_order=int(sort_order),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
db.add(photo)
|
||||||
|
db.flush()
|
||||||
|
except Exception:
|
||||||
|
# Compensating cleanup: the file must not outlive a failed row insert.
|
||||||
|
remove_photo_file(storage_key)
|
||||||
|
raise
|
||||||
|
return photo
|
||||||
|
|
||||||
|
|
||||||
|
def persist_photos(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
uploads: list[tuple[bytes, str | None, str | None]],
|
||||||
|
) -> list[DailyReportPhoto]:
|
||||||
|
"""Persist a batch of uploads. Rolls back all files of the batch on failure.
|
||||||
|
|
||||||
|
`uploads` is a list of (content, original_name, content_type).
|
||||||
|
"""
|
||||||
|
created: list[DailyReportPhoto] = []
|
||||||
|
keys: list[str] = []
|
||||||
|
try:
|
||||||
|
for index, (content, name, ctype) in enumerate(uploads):
|
||||||
|
photo = persist_photo(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
daily_report_id=daily_report_id,
|
||||||
|
content=content,
|
||||||
|
original_name=name,
|
||||||
|
content_type=ctype,
|
||||||
|
sort_order=index,
|
||||||
|
)
|
||||||
|
created.append(photo)
|
||||||
|
keys.append(photo.storage_key)
|
||||||
|
except Exception:
|
||||||
|
for key in keys:
|
||||||
|
remove_photo_file(key)
|
||||||
|
raise
|
||||||
|
return created
|
||||||
|
|
||||||
|
|
||||||
|
def remove_photo_file(storage_key: str) -> None:
|
||||||
|
"""Best-effort delete of a photo file. Never raises."""
|
||||||
|
try:
|
||||||
|
path = resolve_photo_path(storage_key)
|
||||||
|
except PhotoPathError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if path.is_file():
|
||||||
|
path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def delete_photo(db: Session, photo: DailyReportPhoto) -> None:
|
||||||
|
"""Delete the photo row and its physical file.
|
||||||
|
|
||||||
|
Row removal is the caller's transaction; the file is removed after the
|
||||||
|
row is gone so a rollback keeps the file reachable.
|
||||||
|
"""
|
||||||
|
storage_key = photo.storage_key
|
||||||
|
db.delete(photo)
|
||||||
|
db.flush()
|
||||||
|
remove_photo_file(storage_key)
|
||||||
|
|
||||||
|
|
||||||
|
def photo_file_bytes(photo: DailyReportPhoto) -> bytes:
|
||||||
|
"""Read the photo file. Raises PhotoNotFoundError when missing."""
|
||||||
|
try:
|
||||||
|
path = resolve_photo_path(photo.storage_key)
|
||||||
|
except PhotoPathError as exc:
|
||||||
|
raise PhotoNotFoundError(f"Файл фотографии недоступен: {exc}") from exc
|
||||||
|
if not path.is_file():
|
||||||
|
raise PhotoNotFoundError("Файл фотографии не найден в хранилище")
|
||||||
|
return path.read_bytes()
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""Daily Report lifecycle rules tied to KS-2 closing via KS2ItemSource."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.ks2 import KS2ItemSource
|
||||||
|
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
_UNSET = object()
|
||||||
|
|
||||||
|
|
||||||
|
class DailyReportError(ValueError):
|
||||||
|
"""Business rule violation in Daily Report lifecycle."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ItemCloseInfo:
|
||||||
|
item_id: int
|
||||||
|
work_item_id: int
|
||||||
|
actual_quantity: Decimal
|
||||||
|
closed_quantity: Decimal
|
||||||
|
|
||||||
|
@property
|
||||||
|
def available_quantity(self) -> Decimal:
|
||||||
|
return self.actual_quantity - self.closed_quantity
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_closed(self) -> bool:
|
||||||
|
return self.closed_quantity >= self.actual_quantity and self.actual_quantity > 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_partially_closed(self) -> bool:
|
||||||
|
return ZERO < self.closed_quantity < self.actual_quantity
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_open(self) -> bool:
|
||||||
|
return self.closed_quantity == ZERO
|
||||||
|
|
||||||
|
|
||||||
|
def closed_quantity(db: Session, daily_report_item_id: int) -> Decimal:
|
||||||
|
value = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).filter(
|
||||||
|
KS2ItemSource.daily_report_item_id == daily_report_item_id,
|
||||||
|
).scalar()
|
||||||
|
return Decimal(str(value or 0))
|
||||||
|
|
||||||
|
|
||||||
|
def item_close_info(db: Session, item: DailyReportItem) -> ItemCloseInfo:
|
||||||
|
return ItemCloseInfo(
|
||||||
|
item_id=item.id,
|
||||||
|
work_item_id=item.work_item_id,
|
||||||
|
actual_quantity=Decimal(str(item.completed_quantity)),
|
||||||
|
closed_quantity=closed_quantity(db, item.id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def report_close_infos(db: Session, report: DailyReport) -> list[ItemCloseInfo]:
|
||||||
|
return [item_close_info(db, item) for item in report.items]
|
||||||
|
|
||||||
|
|
||||||
|
def has_closed_volume(db: Session, report: DailyReport) -> bool:
|
||||||
|
"""True when any item of the report has any KS-2 closed volume."""
|
||||||
|
for info in report_close_infos(db, report):
|
||||||
|
if info.closed_quantity > ZERO:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def can_delete_report(db: Session, report: DailyReport) -> tuple[bool, str]:
|
||||||
|
if has_closed_volume(db, report):
|
||||||
|
return False, "Отчёт нельзя удалить: его объём уже использован в КС-2."
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def delete_report(db: Session, report: DailyReport) -> None:
|
||||||
|
"""Delete report + items atomically. Blocked when any item is closed in KS-2."""
|
||||||
|
try:
|
||||||
|
ok, reason = can_delete_report(db, report)
|
||||||
|
if not ok:
|
||||||
|
raise DailyReportError(reason)
|
||||||
|
# ORM cascade on DailyReport.items removes DailyReportItem rows.
|
||||||
|
db.delete(report)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise DailyReportError(f"Не удалось удалить отчёт: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def can_delete_item(db: Session, item: DailyReportItem) -> tuple[bool, str]:
|
||||||
|
closed = closed_quantity(db, item.id)
|
||||||
|
if closed > ZERO:
|
||||||
|
return False, (
|
||||||
|
f"Позицию нельзя удалить: в КС-2 уже закрыто {closed}. "
|
||||||
|
f"Изменение закрытого объёма недопустимо."
|
||||||
|
)
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def delete_item(db: Session, item: DailyReportItem) -> None:
|
||||||
|
try:
|
||||||
|
ok, reason = can_delete_item(db, item)
|
||||||
|
if not ok:
|
||||||
|
raise DailyReportError(reason)
|
||||||
|
db.delete(item)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise DailyReportError(f"Не удалось удалить позицию: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def can_change_quantity(info: ItemCloseInfo, new_quantity: Decimal) -> tuple[bool, str]:
|
||||||
|
if new_quantity < ZERO:
|
||||||
|
return False, "Количество не может быть отрицательным."
|
||||||
|
if info.closed_quantity == ZERO:
|
||||||
|
return True, ""
|
||||||
|
if new_quantity < info.closed_quantity:
|
||||||
|
return False, (
|
||||||
|
f"Количество нельзя уменьшить ниже закрытого в КС-2 объёма "
|
||||||
|
f"({info.closed_quantity}). Доступно к изменению от {info.closed_quantity}."
|
||||||
|
)
|
||||||
|
if info.closed_quantity >= info.actual_quantity and new_quantity != info.actual_quantity:
|
||||||
|
return False, (
|
||||||
|
f"Позиция полностью закрыта в КС-2 ({info.closed_quantity}). "
|
||||||
|
f"Количество изменить нельзя."
|
||||||
|
)
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def can_change_date(db: Session, report: DailyReport) -> tuple[bool, str]:
|
||||||
|
if has_closed_volume(db, report):
|
||||||
|
return False, "Дату отчёта нельзя изменить: его объём уже использован в КС-2."
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def apply_quantities(
|
||||||
|
db: Session,
|
||||||
|
report: DailyReport,
|
||||||
|
quantities: dict[int, Decimal],
|
||||||
|
*,
|
||||||
|
new_date: date | None = None,
|
||||||
|
system_id: int | None | object = _UNSET,
|
||||||
|
notes: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Update report items in place, preserving KS2ItemSource links.
|
||||||
|
|
||||||
|
- open items: quantity may change freely; item may be removed;
|
||||||
|
- partially closed: quantity may only stay or increase (>= closed);
|
||||||
|
- fully closed: quantity is frozen; item cannot be removed;
|
||||||
|
- date: changeable only when nothing is closed.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if new_date is not None and new_date != report.report_date:
|
||||||
|
ok, reason = can_change_date(db, report)
|
||||||
|
if not ok:
|
||||||
|
raise DailyReportError(reason)
|
||||||
|
report.report_date = new_date
|
||||||
|
|
||||||
|
if system_id is not _UNSET:
|
||||||
|
report.system_id = system_id
|
||||||
|
|
||||||
|
infos = {info.work_item_id: info for info in report_close_infos(db, report)}
|
||||||
|
existing_by_work = {item.work_item_id: item for item in report.items}
|
||||||
|
|
||||||
|
seen_work_ids = set(quantities)
|
||||||
|
for work_item_id, item in list(existing_by_work.items()):
|
||||||
|
info = infos[work_item_id]
|
||||||
|
if work_item_id not in seen_work_ids:
|
||||||
|
if info.closed_quantity > ZERO:
|
||||||
|
raise DailyReportError(
|
||||||
|
f"Позицию нельзя удалить: в КС-2 уже закрыто {info.closed_quantity}."
|
||||||
|
)
|
||||||
|
db.delete(item)
|
||||||
|
continue
|
||||||
|
new_qty = Decimal(str(quantities[work_item_id]))
|
||||||
|
ok, reason = can_change_quantity(info, new_qty)
|
||||||
|
if not ok:
|
||||||
|
raise DailyReportError(reason)
|
||||||
|
if new_qty != info.actual_quantity:
|
||||||
|
item.completed_quantity = new_qty
|
||||||
|
|
||||||
|
for work_item_id, new_qty in quantities.items():
|
||||||
|
if work_item_id not in existing_by_work:
|
||||||
|
if new_qty < ZERO:
|
||||||
|
raise DailyReportError("Количество не может быть отрицательным.")
|
||||||
|
report.items.append(DailyReportItem(
|
||||||
|
work_item_id=work_item_id, completed_quantity=new_qty,
|
||||||
|
))
|
||||||
|
|
||||||
|
if notes is not None:
|
||||||
|
report.notes = notes.strip() or None
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
except DailyReportError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise DailyReportError(f"Не удалось обновить отчёт: {exc}") from exc
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""Full wipe of all project-dependent data, keeping schema and migrations."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.config import document_storage_root
|
||||||
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.daily_report_photo import DailyReportPhoto
|
||||||
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.work_journal import WorkJournalEntry
|
||||||
|
from app.models.document_artifact import DocumentArtifact
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseResetError(RuntimeError):
|
||||||
|
"""Reset failed and was rolled back."""
|
||||||
|
|
||||||
|
|
||||||
|
# Order matters: dependents first. BoqDocument ↔ Agreement is circular
|
||||||
|
# (boq_documents.agreement_id and agreements.boq_document_id), so
|
||||||
|
# boq_documents.agreement_id is cleared before deleting Agreements.
|
||||||
|
DELETE_ORDER = (
|
||||||
|
("payment_allocations", PaymentAllocation),
|
||||||
|
("payments", Payment),
|
||||||
|
("ks3_ks2_links", KS3KS2),
|
||||||
|
("ks3_documents", KS3),
|
||||||
|
("ks2_item_sources", KS2ItemSource),
|
||||||
|
("ks2_items", KS2Item),
|
||||||
|
("ks2_documents", KS2),
|
||||||
|
("daily_report_photos", DailyReportPhoto),
|
||||||
|
("daily_report_items", DailyReportItem),
|
||||||
|
("daily_reports", DailyReport),
|
||||||
|
("agreement_items", AgreementItem),
|
||||||
|
("agreements", Agreement),
|
||||||
|
("work_items", WorkItem),
|
||||||
|
("sections", Section),
|
||||||
|
("systems", System),
|
||||||
|
("boq_documents", BoqDocument),
|
||||||
|
("work_journal_entries", WorkJournalEntry),
|
||||||
|
("document_artifacts", DocumentArtifact),
|
||||||
|
("projects", Project),
|
||||||
|
)
|
||||||
|
|
||||||
|
PROJECT_DEPENDENT_TABLES = tuple(name for name, _ in DELETE_ORDER)
|
||||||
|
|
||||||
|
|
||||||
|
def project_storage_path(project_id: int) -> Path:
|
||||||
|
"""
|
||||||
|
Return the storage directory for a project. Server-side construction only.
|
||||||
|
|
||||||
|
The result is always strictly inside document_storage_root()/projects/.
|
||||||
|
Does NOT create the directory.
|
||||||
|
"""
|
||||||
|
pid = int(project_id)
|
||||||
|
if pid <= 0:
|
||||||
|
raise ValueError("project_id must be a positive integer")
|
||||||
|
root = document_storage_root()
|
||||||
|
projects_root = (root / "projects").resolve()
|
||||||
|
candidate = (projects_root / str(pid)).resolve()
|
||||||
|
# Safety: must be a direct child of projects_root
|
||||||
|
if candidate.parent != projects_root:
|
||||||
|
raise ValueError("project storage path escapes projects root")
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ResetResult:
|
||||||
|
deleted: dict[str, int]
|
||||||
|
verified: dict[str, int]
|
||||||
|
storage_removed: bool = False
|
||||||
|
storage_error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def count_project_data(db: Session) -> dict[str, int]:
|
||||||
|
"""Row counts for every project-dependent table."""
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for name, model in DELETE_ORDER:
|
||||||
|
counts[name] = int(db.execute(select(func.count()).select_from(model)).scalar() or 0)
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_project_storage(project_ids: list[int]) -> tuple[bool, str | None]:
|
||||||
|
"""
|
||||||
|
Remove physical storage for the given project IDs.
|
||||||
|
|
||||||
|
Only called AFTER a successful DB commit. Never rolls back DB.
|
||||||
|
Returns (all_removed, error_message_or_None).
|
||||||
|
"""
|
||||||
|
errors = []
|
||||||
|
for pid in project_ids:
|
||||||
|
try:
|
||||||
|
storage_dir = project_storage_path(pid)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(f"project {pid}: {exc}")
|
||||||
|
continue
|
||||||
|
if not storage_dir.exists():
|
||||||
|
continue # missing storage is not an error
|
||||||
|
try:
|
||||||
|
# Guard: resolved path must still be inside projects root
|
||||||
|
projects_root = (document_storage_root() / "projects").resolve()
|
||||||
|
if storage_dir.parent != projects_root:
|
||||||
|
errors.append(f"project {pid}: storage path escapes projects root")
|
||||||
|
continue
|
||||||
|
# Refuse to follow symlinks out of the tree
|
||||||
|
if storage_dir.is_symlink():
|
||||||
|
errors.append(f"project {pid}: storage directory is a symlink, refused to delete")
|
||||||
|
continue
|
||||||
|
shutil.rmtree(storage_dir)
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"FS cleanup failed for project %s: %s: %s",
|
||||||
|
pid, type(exc).__name__, exc,
|
||||||
|
)
|
||||||
|
errors.append(f"project {pid}: {type(exc).__name__}: {exc}")
|
||||||
|
return (not errors, "; ".join(errors) if errors else None)
|
||||||
|
|
||||||
|
|
||||||
|
def reset_database(db: Session) -> ResetResult:
|
||||||
|
"""
|
||||||
|
Delete all project-dependent rows in one transaction, then clean FS.
|
||||||
|
|
||||||
|
Schema, indexes and schema_migrations are left untouched. On any DB error
|
||||||
|
the transaction is rolled back and physical storage is NOT touched.
|
||||||
|
FS deletion happens only after a successful DB commit.
|
||||||
|
"""
|
||||||
|
project_ids: list[int] = []
|
||||||
|
try:
|
||||||
|
# Collect project IDs before deletion
|
||||||
|
project_ids = [row[0] for row in db.execute(select(Project.id)).all()]
|
||||||
|
|
||||||
|
deleted: dict[str, int] = {}
|
||||||
|
# Break the circular BoqDocument ↔ Agreement FK before deleting either side.
|
||||||
|
db.execute(
|
||||||
|
BoqDocument.__table__.update().values(agreement_id=None)
|
||||||
|
)
|
||||||
|
for name, model in DELETE_ORDER:
|
||||||
|
result = db.execute(
|
||||||
|
model.__table__.delete()
|
||||||
|
)
|
||||||
|
deleted[name] = int(result.rowcount or 0)
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
verified = count_project_data(db)
|
||||||
|
leftovers = {k: v for k, v in verified.items() if v != 0}
|
||||||
|
if leftovers:
|
||||||
|
raise DatabaseResetError(
|
||||||
|
"Контроль очистки обнаружил остаточные данные: "
|
||||||
|
+ ", ".join(f"{k}={v}" for k, v in leftovers.items())
|
||||||
|
)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
except DatabaseResetError:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise DatabaseResetError(f"Сброс прерван, изменения отменены: {exc}") from exc
|
||||||
|
|
||||||
|
# DB commit succeeded — now clean physical storage.
|
||||||
|
storage_removed, storage_error = _delete_project_storage(project_ids)
|
||||||
|
return ResetResult(
|
||||||
|
deleted=deleted,
|
||||||
|
verified=verified,
|
||||||
|
storage_removed=storage_removed,
|
||||||
|
storage_error=storage_error,
|
||||||
|
)
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
"""Document artifact service: hash, persist, resolve, invalidate.
|
||||||
|
|
||||||
|
Implements the service layer for DocumentArtifact (DOC-B1):
|
||||||
|
|
||||||
|
DTO / bytes -> Artifact Service -> hash / persist / resolve / invalidate
|
||||||
|
|
||||||
|
Transaction ownership: the service does NOT commit. The caller manages the
|
||||||
|
database transaction. Filesystem writes use compensating cleanup on failure.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
from dataclasses import asdict, is_dataclass
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select, update
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.config import document_storage_root
|
||||||
|
from app.models.document_artifact import DocumentArtifact
|
||||||
|
|
||||||
|
_ZERO_DECIMAL = Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentArtifactError(ValueError):
|
||||||
|
"""Domain error raised by the artifact service."""
|
||||||
|
|
||||||
|
|
||||||
|
class ArtifactNotFoundError(DocumentArtifactError):
|
||||||
|
"""Artifact row or physical file is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
class ArtifactPathError(DocumentArtifactError):
|
||||||
|
"""storage_key is unsafe or escapes the storage root."""
|
||||||
|
|
||||||
|
|
||||||
|
class ArtifactHashMismatchError(DocumentArtifactError):
|
||||||
|
"""Physical file content does not match the recorded content_hash."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Hashing
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def compute_content_hash(content: bytes) -> str:
|
||||||
|
"""SHA-256 of raw bytes as a 64-char lowercase hex string."""
|
||||||
|
return hashlib.sha256(content).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _canonicalize(value: Any) -> Any:
|
||||||
|
"""Convert a value into a deterministic JSON-safe structure."""
|
||||||
|
if is_dataclass(value) and not isinstance(value, type):
|
||||||
|
return _canonicalize(asdict(value))
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {str(k): _canonicalize(v) for k, v in value.items()}
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
return [_canonicalize(v) for v in value]
|
||||||
|
if isinstance(value, Decimal):
|
||||||
|
# Normalize to a plain decimal string without exponent noise.
|
||||||
|
text = format(value, "f")
|
||||||
|
if "." in text:
|
||||||
|
text = text.rstrip("0").rstrip(".")
|
||||||
|
return text
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.isoformat()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value.isoformat()
|
||||||
|
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||||
|
return value
|
||||||
|
raise DocumentArtifactError(
|
||||||
|
f"Unsupported type for canonical input hash: {type(value)!r}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_json(dto: Any) -> str:
|
||||||
|
"""Deterministic JSON: sorted keys, Decimal/date as strings, UTF-8."""
|
||||||
|
return json.dumps(
|
||||||
|
_canonicalize(dto),
|
||||||
|
ensure_ascii=False,
|
||||||
|
sort_keys=True,
|
||||||
|
separators=(",", ":"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_input_hash(dto: Any, template_type: str, template_version: int) -> str:
|
||||||
|
"""SHA-256(canonical_json(dto) + template_type + template_version)."""
|
||||||
|
payload = (
|
||||||
|
canonical_json(dto)
|
||||||
|
+ "|"
|
||||||
|
+ str(template_type)
|
||||||
|
+ "|"
|
||||||
|
+ str(int(template_version))
|
||||||
|
)
|
||||||
|
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Storage paths
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9._-]+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_segment(value: Any, label: str) -> str:
|
||||||
|
text = str(value)
|
||||||
|
if not _SAFE_SEGMENT.match(text):
|
||||||
|
raise ArtifactPathError(f"Invalid {label}: {text!r}")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def build_storage_key(
|
||||||
|
project_id: int,
|
||||||
|
document_type: str,
|
||||||
|
document_id: int,
|
||||||
|
template_type: str,
|
||||||
|
template_version: int,
|
||||||
|
extension: str,
|
||||||
|
when: datetime | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Server-generated relative storage key. Never uses user input."""
|
||||||
|
project_id = int(project_id)
|
||||||
|
document_id = int(document_id)
|
||||||
|
if project_id <= 0 or document_id <= 0:
|
||||||
|
raise ArtifactPathError("project_id and document_id must be positive")
|
||||||
|
doc_type = _validate_segment(document_type, "document_type")
|
||||||
|
template = _validate_segment(template_type, "template_type")
|
||||||
|
ext = _validate_segment(extension.lstrip("."), "extension")
|
||||||
|
stamp = (when or datetime.now()).strftime("%Y-%m-%d_%H%M%S_%f")
|
||||||
|
name = f"{template}_v{int(template_version)}_{stamp}.{ext}"
|
||||||
|
return (
|
||||||
|
f"projects/{project_id}/documents/{doc_type}/{document_id}/{name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_storage_path(storage_key: str) -> Path:
|
||||||
|
"""Map a relative storage key to an absolute path inside the storage root."""
|
||||||
|
if not storage_key or not str(storage_key).strip():
|
||||||
|
raise ArtifactPathError("storage_key is required")
|
||||||
|
key = str(storage_key).replace("\\", "/").strip()
|
||||||
|
if key.startswith("/") or re.match(r"^[A-Za-z]:", key):
|
||||||
|
raise ArtifactPathError("storage_key must be relative")
|
||||||
|
if ".." in Path(key).parts:
|
||||||
|
raise ArtifactPathError("storage_key must not contain '..'")
|
||||||
|
root = document_storage_root().resolve()
|
||||||
|
candidate = (root / key).resolve()
|
||||||
|
try:
|
||||||
|
candidate.relative_to(root)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ArtifactPathError("storage_key escapes storage root") from exc
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Persist
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def persist_artifact(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
document_type: str,
|
||||||
|
document_id: int,
|
||||||
|
format: str,
|
||||||
|
template_type: str,
|
||||||
|
template_version: int,
|
||||||
|
content: bytes,
|
||||||
|
input_hash: str | None = None,
|
||||||
|
dto: Any = None,
|
||||||
|
generated_at: datetime | None = None,
|
||||||
|
) -> DocumentArtifact:
|
||||||
|
"""
|
||||||
|
Store artifact bytes on disk and stage a DocumentArtifact row.
|
||||||
|
|
||||||
|
Does NOT commit. The caller owns the transaction. On failure the file
|
||||||
|
created by this call is removed (compensating cleanup); existing artifacts
|
||||||
|
are never touched.
|
||||||
|
"""
|
||||||
|
if input_hash is None and dto is None:
|
||||||
|
raise DocumentArtifactError("Either input_hash or dto is required")
|
||||||
|
if not isinstance(content, (bytes, bytearray)):
|
||||||
|
raise DocumentArtifactError("content must be bytes")
|
||||||
|
content = bytes(content)
|
||||||
|
fmt = _validate_segment(format, "format")
|
||||||
|
|
||||||
|
content_hash = compute_content_hash(content)
|
||||||
|
if input_hash is None:
|
||||||
|
input_hash = compute_input_hash(dto, template_type, template_version)
|
||||||
|
|
||||||
|
storage_key = build_storage_key(
|
||||||
|
project_id,
|
||||||
|
document_type,
|
||||||
|
document_id,
|
||||||
|
template_type,
|
||||||
|
template_version,
|
||||||
|
fmt,
|
||||||
|
when=generated_at,
|
||||||
|
)
|
||||||
|
path = resolve_storage_path(storage_key)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
tmp_fd, tmp_name = tempfile.mkstemp(
|
||||||
|
dir=str(path.parent), prefix=".tmp-artifact-", suffix=f".{fmt}"
|
||||||
|
)
|
||||||
|
tmp_path = Path(tmp_name)
|
||||||
|
try:
|
||||||
|
with os.fdopen(tmp_fd, "wb") as handle:
|
||||||
|
handle.write(content)
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
os.replace(tmp_path, path)
|
||||||
|
|
||||||
|
# Demote any previous current rows for this (type, id, format).
|
||||||
|
db.execute(
|
||||||
|
update(DocumentArtifact)
|
||||||
|
.where(
|
||||||
|
DocumentArtifact.document_type == document_type,
|
||||||
|
DocumentArtifact.document_id == document_id,
|
||||||
|
DocumentArtifact.format == fmt,
|
||||||
|
DocumentArtifact.is_current.is_(True),
|
||||||
|
)
|
||||||
|
.values(is_current=False)
|
||||||
|
)
|
||||||
|
|
||||||
|
artifact = DocumentArtifact(
|
||||||
|
project_id=project_id,
|
||||||
|
document_type=document_type,
|
||||||
|
document_id=document_id,
|
||||||
|
format=fmt,
|
||||||
|
storage_key=storage_key,
|
||||||
|
template_type=template_type,
|
||||||
|
template_version=int(template_version),
|
||||||
|
content_hash=content_hash,
|
||||||
|
input_hash=input_hash,
|
||||||
|
is_current=True,
|
||||||
|
generated_at=generated_at or datetime.now(),
|
||||||
|
)
|
||||||
|
db.add(artifact)
|
||||||
|
db.flush()
|
||||||
|
return artifact
|
||||||
|
except Exception:
|
||||||
|
# Compensating cleanup: remove only the file created by this attempt.
|
||||||
|
try:
|
||||||
|
if tmp_path.exists():
|
||||||
|
tmp_path.unlink()
|
||||||
|
if path.exists():
|
||||||
|
path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Resolve
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _artifact_to_path(artifact: DocumentArtifact) -> Path:
|
||||||
|
path = resolve_storage_path(artifact.storage_key)
|
||||||
|
if not path.is_file():
|
||||||
|
raise ArtifactNotFoundError(
|
||||||
|
f"Artifact file not found: {artifact.storage_key!r}"
|
||||||
|
)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _check_content_hash(path: Path, expected: str) -> bytes:
|
||||||
|
content = path.read_bytes()
|
||||||
|
actual = compute_content_hash(content)
|
||||||
|
if actual != expected:
|
||||||
|
raise ArtifactHashMismatchError(
|
||||||
|
"Artifact file content does not match recorded hash"
|
||||||
|
)
|
||||||
|
return content
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_artifact(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
document_type: str,
|
||||||
|
document_id: int,
|
||||||
|
format: str,
|
||||||
|
verify_hash: bool = True,
|
||||||
|
) -> tuple[DocumentArtifact, bytes]:
|
||||||
|
"""Resolve the current artifact and return (row, bytes)."""
|
||||||
|
fmt = _validate_segment(format, "format")
|
||||||
|
artifact = db.execute(
|
||||||
|
select(DocumentArtifact)
|
||||||
|
.where(
|
||||||
|
DocumentArtifact.project_id == project_id,
|
||||||
|
DocumentArtifact.document_type == document_type,
|
||||||
|
DocumentArtifact.document_id == document_id,
|
||||||
|
DocumentArtifact.format == fmt,
|
||||||
|
DocumentArtifact.is_current.is_(True),
|
||||||
|
)
|
||||||
|
.order_by(DocumentArtifact.id.desc())
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if artifact is None:
|
||||||
|
raise ArtifactNotFoundError(
|
||||||
|
f"No current artifact for {document_type}:{document_id} ({fmt})"
|
||||||
|
)
|
||||||
|
path = _artifact_to_path(artifact)
|
||||||
|
content = _check_content_hash(path, artifact.content_hash) if verify_hash else path.read_bytes()
|
||||||
|
return artifact, content
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_artifact_by_id(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
artifact_id: int,
|
||||||
|
project_id: int,
|
||||||
|
verify_hash: bool = True,
|
||||||
|
) -> tuple[DocumentArtifact, bytes]:
|
||||||
|
"""Resolve a historical artifact by id, always scoped to a project."""
|
||||||
|
artifact = db.get(DocumentArtifact, artifact_id)
|
||||||
|
if artifact is None:
|
||||||
|
raise ArtifactNotFoundError(f"Artifact {artifact_id} not found")
|
||||||
|
if artifact.project_id != project_id:
|
||||||
|
raise DocumentArtifactError(
|
||||||
|
f"Artifact {artifact_id} does not belong to project {project_id}"
|
||||||
|
)
|
||||||
|
path = _artifact_to_path(artifact)
|
||||||
|
content = _check_content_hash(path, artifact.content_hash) if verify_hash else path.read_bytes()
|
||||||
|
return artifact, content
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Invalidate
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def invalidate_artifacts(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
document_type: str,
|
||||||
|
document_id: int,
|
||||||
|
format: str | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""
|
||||||
|
Mark current artifacts as historical. Idempotent.
|
||||||
|
|
||||||
|
Files and rows are not deleted. Returns the number of rows updated.
|
||||||
|
"""
|
||||||
|
stmt = (
|
||||||
|
update(DocumentArtifact)
|
||||||
|
.where(
|
||||||
|
DocumentArtifact.project_id == project_id,
|
||||||
|
DocumentArtifact.document_type == document_type,
|
||||||
|
DocumentArtifact.document_id == document_id,
|
||||||
|
DocumentArtifact.is_current.is_(True),
|
||||||
|
)
|
||||||
|
.values(is_current=False)
|
||||||
|
)
|
||||||
|
if format is not None:
|
||||||
|
stmt = stmt.where(DocumentArtifact.format == _validate_segment(format, "format"))
|
||||||
|
result = db.execute(stmt)
|
||||||
|
return int(result.rowcount or 0)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Cleanup helper (for failed transactions)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def remove_artifact_file(artifact: DocumentArtifact) -> bool:
|
||||||
|
"""
|
||||||
|
Delete the physical file of a single artifact row.
|
||||||
|
|
||||||
|
Narrowly scoped cleanup for a failed transaction that created an artifact
|
||||||
|
file but could not commit. Accepts only a DocumentArtifact row (never an
|
||||||
|
arbitrary path). Resolves through the safe path resolver. Never touches
|
||||||
|
other artifacts. Returns True if a file was removed.
|
||||||
|
"""
|
||||||
|
if artifact is None or not artifact.storage_key:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
path = resolve_storage_path(artifact.storage_key)
|
||||||
|
except ArtifactPathError:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
if path.is_file():
|
||||||
|
path.unlink()
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
return False
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Next document number suggestions for KS-2 / KS-3.
|
||||||
|
|
||||||
|
Separate sequences per document type. Cancelled documents keep their numbers.
|
||||||
|
Numbers stay strings in the model; suggestion is numeric max + 1.
|
||||||
|
"""
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
|
||||||
|
def next_document_number(db: Session, model, project_id: int) -> str:
|
||||||
|
"""Return the next free number for the given document model in a project."""
|
||||||
|
rows = db.query(model.number).filter(model.project_id == project_id).all()
|
||||||
|
max_number = 0
|
||||||
|
for (raw,) in rows:
|
||||||
|
text = str(raw or "").strip()
|
||||||
|
try:
|
||||||
|
value = int(text)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if value > max_number:
|
||||||
|
max_number = value
|
||||||
|
return str(max_number + 1)
|
||||||
+126
-2
@@ -1,4 +1,4 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
@@ -37,6 +37,17 @@ def _decimal(value):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(value, label):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(str(value).strip())
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise KS2ValidationError(f"{label}: неверный формат даты") from exc
|
||||||
|
|
||||||
|
|
||||||
def build_work_item_balances(db: Session, project_id: int):
|
def build_work_item_balances(db: Session, project_id: int):
|
||||||
"""Return effective plan, accumulated Daily Report fact and issued KS-2 closure."""
|
"""Return effective plan, accumulated Daily Report fact and issued KS-2 closure."""
|
||||||
plan = build_effective_plan(db, project_id)
|
plan = build_effective_plan(db, project_id)
|
||||||
@@ -91,7 +102,8 @@ def _validated_entries(db, project_id, entries, excluded_ks2_id=None):
|
|||||||
|
|
||||||
|
|
||||||
def save_draft(db: Session, project_id: int, number: str, document_date: date, comment: str | None,
|
def save_draft(db: Session, project_id: int, number: str, document_date: date, comment: str | None,
|
||||||
entries, ks2_id: int | None = None):
|
entries, ks2_id: int | None = None,
|
||||||
|
reporting_period_from=None, reporting_period_to=None):
|
||||||
"""Create/update a draft and its selected lines in one transaction."""
|
"""Create/update a draft and its selected lines in one transaction."""
|
||||||
try:
|
try:
|
||||||
number = (number or "").strip()
|
number = (number or "").strip()
|
||||||
@@ -103,6 +115,17 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c
|
|||||||
if conflict.first():
|
if conflict.first():
|
||||||
raise KS2ValidationError("КС-2 с таким номером уже существует в проекте")
|
raise KS2ValidationError("КС-2 с таким номером уже существует в проекте")
|
||||||
normalized, _ = _validated_entries(db, project_id, entries)
|
normalized, _ = _validated_entries(db, project_id, entries)
|
||||||
|
|
||||||
|
period_from = _parse_date(reporting_period_from, "Период с")
|
||||||
|
period_to = _parse_date(reporting_period_to, "Период по")
|
||||||
|
if ks2_id is None:
|
||||||
|
if period_from is None:
|
||||||
|
raise KS2ValidationError("Укажите дату начала периода")
|
||||||
|
if period_to is None:
|
||||||
|
raise KS2ValidationError("Укажите дату окончания периода")
|
||||||
|
if period_from is not None and period_to is not None and period_to < period_from:
|
||||||
|
raise KS2ValidationError("Дата окончания периода не может быть раньше даты начала")
|
||||||
|
|
||||||
document = None
|
document = None
|
||||||
if ks2_id is not None:
|
if ks2_id is not None:
|
||||||
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
||||||
@@ -115,6 +138,8 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c
|
|||||||
db.add(document)
|
db.add(document)
|
||||||
document.number = number
|
document.number = number
|
||||||
document.date = document_date
|
document.date = document_date
|
||||||
|
document.reporting_period_from = period_from
|
||||||
|
document.reporting_period_to = period_to
|
||||||
document.comment = comment.strip() or None if comment else None
|
document.comment = comment.strip() or None if comment else None
|
||||||
document.items.clear()
|
document.items.clear()
|
||||||
for item_id, quantity in normalized.items():
|
for item_id, quantity in normalized.items():
|
||||||
@@ -122,6 +147,15 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c
|
|||||||
price = _decimal(item.unit_price)
|
price = _decimal(item.unit_price)
|
||||||
document.items.append(KS2Item(work_item_id=item_id, quantity=quantity,
|
document.items.append(KS2Item(work_item_id=item_id, quantity=quantity,
|
||||||
unit_price=price, amount=price * quantity))
|
unit_price=price, amount=price * quantity))
|
||||||
|
# Successful draft change invalidates existing draft artifacts (same tx).
|
||||||
|
if ks2_id is not None:
|
||||||
|
from app.services.document_artifact_service import invalidate_artifacts
|
||||||
|
invalidate_artifacts(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS2",
|
||||||
|
document_id=document.id,
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(document)
|
db.refresh(document)
|
||||||
return document
|
return document
|
||||||
@@ -132,6 +166,8 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c
|
|||||||
|
|
||||||
def issue_ks2(db: Session, project_id: int, ks2_id: int):
|
def issue_ks2(db: Session, project_id: int, ks2_id: int):
|
||||||
"""Revalidate current balances, attribute quantity to DR lines oldest-first, and issue atomically."""
|
"""Revalidate current balances, attribute quantity to DR lines oldest-first, and issue atomically."""
|
||||||
|
artifact = None
|
||||||
|
word_artifact = None
|
||||||
try:
|
try:
|
||||||
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
||||||
if document is None:
|
if document is None:
|
||||||
@@ -181,11 +217,56 @@ def issue_ks2(db: Session, project_id: int, ks2_id: int):
|
|||||||
f"Не удалось распределить весь объём по источникам Daily Reports для позиции {line.work_item.name}"
|
f"Не удалось распределить весь объём по источникам Daily Reports для позиции {line.work_item.name}"
|
||||||
)
|
)
|
||||||
document.status = "issued"
|
document.status = "issued"
|
||||||
|
|
||||||
|
# Generate and persist the official artifacts inside this transaction.
|
||||||
|
from app.exporters.excel.ks2_renderer import (
|
||||||
|
TEMPLATE_TYPE as KS2_TEMPLATE_TYPE,
|
||||||
|
TEMPLATE_VERSION as KS2_TEMPLATE_VERSION,
|
||||||
|
render_ks2_excel,
|
||||||
|
)
|
||||||
|
from app.exporters.word.ks2_renderer import (
|
||||||
|
TEMPLATE_TYPE as KS2_WORD_TEMPLATE_TYPE,
|
||||||
|
TEMPLATE_VERSION as KS2_WORD_TEMPLATE_VERSION,
|
||||||
|
render_ks2_word,
|
||||||
|
)
|
||||||
|
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||||
|
from app.services.document_artifact_service import persist_artifact, remove_artifact_file
|
||||||
|
|
||||||
|
dto = build_ks2_export_dto(db, document)
|
||||||
|
content = render_ks2_excel(dto)
|
||||||
|
artifact = persist_artifact(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS2",
|
||||||
|
document_id=document.id,
|
||||||
|
format="xlsx",
|
||||||
|
template_type=KS2_TEMPLATE_TYPE,
|
||||||
|
template_version=KS2_TEMPLATE_VERSION,
|
||||||
|
content=content,
|
||||||
|
dto=dto,
|
||||||
|
)
|
||||||
|
word_content = render_ks2_word(dto)
|
||||||
|
word_artifact = persist_artifact(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS2",
|
||||||
|
document_id=document.id,
|
||||||
|
format="docx",
|
||||||
|
template_type=KS2_WORD_TEMPLATE_TYPE,
|
||||||
|
template_version=KS2_WORD_TEMPLATE_VERSION,
|
||||||
|
content=word_content,
|
||||||
|
dto=dto,
|
||||||
|
)
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(document)
|
db.refresh(document)
|
||||||
return document
|
return document
|
||||||
except Exception:
|
except Exception:
|
||||||
db.rollback()
|
db.rollback()
|
||||||
|
if artifact is not None:
|
||||||
|
remove_artifact_file(artifact)
|
||||||
|
if word_artifact is not None:
|
||||||
|
remove_artifact_file(word_artifact)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
@@ -196,3 +277,46 @@ def project_ks2_totals(db: Session, project_id: int):
|
|||||||
rows.append({"document": document, "item_count": len(document.items),
|
rows.append({"document": document, "item_count": len(document.items),
|
||||||
"amount": sum((_decimal(line.amount) for line in document.items), ZERO)})
|
"amount": sum((_decimal(line.amount) for line in document.items), ZERO)})
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def ks2_cancel_block_reason(db: Session, project_id: int, ks2_id: int) -> str | None:
|
||||||
|
"""Return why KS-2 cannot be cancelled, or None if cancellation is allowed."""
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
|
||||||
|
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
|
||||||
|
if document is None:
|
||||||
|
return "КС-2 не найден"
|
||||||
|
if document.status == "cancelled":
|
||||||
|
return "КС-2 уже сторнирован"
|
||||||
|
active_link = db.query(KS3KS2).join(KS3, KS3.id == KS3KS2.ks3_id).filter(
|
||||||
|
KS3KS2.ks2_id == ks2_id,
|
||||||
|
KS3.project_id == project_id,
|
||||||
|
KS3.status == "issued",
|
||||||
|
).first()
|
||||||
|
if active_link is not None:
|
||||||
|
ks3_doc = db.query(KS3).filter(KS3.id == active_link.ks3_id).first()
|
||||||
|
number = ks3_doc.number if ks3_doc else active_link.ks3_id
|
||||||
|
return f"КС-2 включён в действующий КС-3 №{number}. Сначала сторнируйте КС-3."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_ks2(db: Session, project_id: int, ks2_id: int):
|
||||||
|
"""Cancel a KS-2 atomically. Blocked when linked to an issued KS-3."""
|
||||||
|
try:
|
||||||
|
reason = ks2_cancel_block_reason(db, project_id, ks2_id)
|
||||||
|
if reason is not None:
|
||||||
|
raise KS2ValidationError(reason)
|
||||||
|
document = db.query(KS2).filter(
|
||||||
|
KS2.id == ks2_id, KS2.project_id == project_id
|
||||||
|
).with_for_update().first()
|
||||||
|
if document is None:
|
||||||
|
raise KS2ValidationError("КС-2 не найден")
|
||||||
|
if document.status == "cancelled":
|
||||||
|
raise KS2ValidationError("КС-2 уже сторнирован")
|
||||||
|
document.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from app.models.ks2 import KS2, KS2Item
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
|
class KS3ValidationError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _decimal(value):
|
||||||
|
try:
|
||||||
|
return Decimal(str(value)) if value is not None else ZERO
|
||||||
|
except (InvalidOperation, ValueError, TypeError):
|
||||||
|
return ZERO
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(value, label):
|
||||||
|
if value is None or (isinstance(value, str) and not value.strip()):
|
||||||
|
return None
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(str(value).strip())
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise KS3ValidationError(f"{label}: неверный формат даты") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _ks2_total(ks2):
|
||||||
|
return sum(_decimal(item.amount) for item in ks2.items)
|
||||||
|
|
||||||
|
|
||||||
|
def _taken_ks2_ids(db: Session, project_id: int, exclude_ks3_id: int | None = None) -> set[int]:
|
||||||
|
"""KS-2 ids already linked to an issued KS-3 of this project.
|
||||||
|
|
||||||
|
Draft and cancelled KS-3 do not claim KS-2. exclude_ks3_id keeps the
|
||||||
|
current document's own selection available while editing.
|
||||||
|
"""
|
||||||
|
query = (
|
||||||
|
db.query(KS3KS2.ks2_id)
|
||||||
|
.join(KS3, KS3.id == KS3KS2.ks3_id)
|
||||||
|
.filter(KS3.project_id == project_id, KS3.status == "issued")
|
||||||
|
)
|
||||||
|
if exclude_ks3_id is not None:
|
||||||
|
query = query.filter(KS3.id != exclude_ks3_id)
|
||||||
|
return {row[0] for row in query.all()}
|
||||||
|
|
||||||
|
|
||||||
|
def _reject_if_taken_by_other_issued_ks3(db: Session, project_id: int, ks2_id: int,
|
||||||
|
ks2_number: str, exclude_ks3_id: int | None = None) -> None:
|
||||||
|
query = (
|
||||||
|
db.query(KS3KS2, KS3)
|
||||||
|
.join(KS3, KS3.id == KS3KS2.ks3_id)
|
||||||
|
.filter(
|
||||||
|
KS3KS2.ks2_id == ks2_id,
|
||||||
|
KS3.project_id == project_id,
|
||||||
|
KS3.status == "issued",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if exclude_ks3_id is not None:
|
||||||
|
query = query.filter(KS3.id != exclude_ks3_id)
|
||||||
|
taken = query.first()
|
||||||
|
if taken is not None:
|
||||||
|
_, other = taken
|
||||||
|
raise KS3ValidationError(
|
||||||
|
f"КС-2 №{ks2_number} уже включён в проведённый КС-3 №{other.number}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def available_ks2(db: Session, project_id: int, exclude_ks3_id: int | None = None):
|
||||||
|
"""Return issued KS-2 documents available for inclusion in a KS-3.
|
||||||
|
|
||||||
|
KS-2 already linked to another issued KS-3 is excluded. Draft/cancelled
|
||||||
|
KS-3 do not block. exclude_ks3_id keeps the document's own KS-2 visible.
|
||||||
|
"""
|
||||||
|
taken = _taken_ks2_ids(db, project_id, exclude_ks3_id=exclude_ks3_id)
|
||||||
|
docs = db.query(KS2).options(joinedload(KS2.items)).filter(
|
||||||
|
KS2.project_id == project_id,
|
||||||
|
KS2.status == "issued",
|
||||||
|
).order_by(KS2.date, KS2.id).all()
|
||||||
|
result = []
|
||||||
|
for doc in docs:
|
||||||
|
if doc.id in taken:
|
||||||
|
continue
|
||||||
|
result.append({
|
||||||
|
"id": doc.id,
|
||||||
|
"number": doc.number,
|
||||||
|
"date": doc.date,
|
||||||
|
"period_from": doc.reporting_period_from,
|
||||||
|
"period_to": doc.reporting_period_to,
|
||||||
|
"total": _ks2_total(doc),
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def save_draft(db: Session, project_id: int, number: str, document_date: date,
|
||||||
|
comment: str | None, ks2_ids: list[int],
|
||||||
|
reporting_period_from=None, reporting_period_to=None,
|
||||||
|
ks3_id: int | None = None):
|
||||||
|
"""Create or update a KS-3 draft."""
|
||||||
|
try:
|
||||||
|
number = (number or "").strip()
|
||||||
|
if not number:
|
||||||
|
raise KS3ValidationError("Укажите номер КС-3")
|
||||||
|
conflict = db.query(KS3).filter(KS3.project_id == project_id, KS3.number == number)
|
||||||
|
if ks3_id is not None:
|
||||||
|
conflict = conflict.filter(KS3.id != ks3_id)
|
||||||
|
if conflict.first():
|
||||||
|
raise KS3ValidationError("КС-3 с таким номером уже существует в проекте")
|
||||||
|
|
||||||
|
period_from = _parse_date(reporting_period_from, "Период с")
|
||||||
|
period_to = _parse_date(reporting_period_to, "Период по")
|
||||||
|
if ks3_id is None:
|
||||||
|
if period_from is None:
|
||||||
|
raise KS3ValidationError("Укажите дату начала периода")
|
||||||
|
if period_to is None:
|
||||||
|
raise KS3ValidationError("Укажите дату окончания периода")
|
||||||
|
if period_from is not None and period_to is not None and period_to < period_from:
|
||||||
|
raise KS3ValidationError("Дата окончания периода не может быть раньше даты начала")
|
||||||
|
|
||||||
|
if not ks2_ids:
|
||||||
|
raise KS3ValidationError("Выберите хотя бы один КС-2")
|
||||||
|
if len(ks2_ids) != len(set(ks2_ids)):
|
||||||
|
raise KS3ValidationError("Один и тот же КС-2 не может быть выбран дважды")
|
||||||
|
|
||||||
|
document = None
|
||||||
|
if ks3_id is not None:
|
||||||
|
document = db.query(KS3).filter(
|
||||||
|
KS3.id == ks3_id, KS3.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if document is None:
|
||||||
|
raise KS3ValidationError("КС-3 не найден")
|
||||||
|
if document.status != "draft":
|
||||||
|
raise KS3ValidationError("Проведённый КС-3 нельзя редактировать")
|
||||||
|
else:
|
||||||
|
document = KS3(project_id=project_id, status="draft")
|
||||||
|
db.add(document)
|
||||||
|
|
||||||
|
document.number = number
|
||||||
|
document.date = document_date
|
||||||
|
document.reporting_period_from = period_from
|
||||||
|
document.reporting_period_to = period_to
|
||||||
|
document.comment = comment.strip() or None if comment else None
|
||||||
|
|
||||||
|
# Validate all selected KS-2
|
||||||
|
seen_ks2 = set()
|
||||||
|
for ks2_id in ks2_ids:
|
||||||
|
if ks2_id in seen_ks2:
|
||||||
|
raise KS3ValidationError(f"КС-2 с id={ks2_id} выбран несколько раз")
|
||||||
|
seen_ks2.add(ks2_id)
|
||||||
|
ks2 = db.query(KS2).filter(KS2.id == ks2_id).first()
|
||||||
|
if ks2 is None:
|
||||||
|
raise KS3ValidationError(f"КС-2 с id={ks2_id} не найден")
|
||||||
|
if ks2.project_id != project_id:
|
||||||
|
raise KS3ValidationError(f"КС-2 №{ks2.number} не принадлежит этому проекту")
|
||||||
|
if ks2.status != "issued":
|
||||||
|
raise KS3ValidationError(f"КС-2 №{ks2.number} не проведён")
|
||||||
|
# Server-side guard: a KS-2 can belong to only one issued KS-3.
|
||||||
|
_reject_if_taken_by_other_issued_ks3(
|
||||||
|
db, project_id, ks2_id, ks2.number, exclude_ks3_id=ks3_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Replace links: delete old rows first so re-selecting the same KS-2
|
||||||
|
# does not hit the unique constraint during the autoflush below.
|
||||||
|
document.links.clear()
|
||||||
|
db.flush()
|
||||||
|
for ks2_id in seen_ks2:
|
||||||
|
document.links.append(KS3KS2(ks2_id=ks2_id))
|
||||||
|
|
||||||
|
# Successful draft change invalidates existing draft artifacts (same tx).
|
||||||
|
if ks3_id is not None:
|
||||||
|
from app.services.document_artifact_service import invalidate_artifacts
|
||||||
|
invalidate_artifacts(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS3",
|
||||||
|
document_id=document.id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def issue_ks3(db: Session, project_id: int, ks3_id: int):
|
||||||
|
"""Issue a KS-3 draft atomically."""
|
||||||
|
artifact = None
|
||||||
|
try:
|
||||||
|
document = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||||
|
if document is None:
|
||||||
|
raise KS3ValidationError("КС-3 не найден")
|
||||||
|
if document.status != "draft":
|
||||||
|
raise KS3ValidationError("Можно провести только черновик КС-3")
|
||||||
|
if not document.links:
|
||||||
|
raise KS3ValidationError("В КС-3 нет выбранных КС-2")
|
||||||
|
|
||||||
|
# Re-validate all linked KS-2
|
||||||
|
for link in document.links:
|
||||||
|
ks2 = link.ks2
|
||||||
|
if ks2 is None or ks2.project_id != project_id:
|
||||||
|
raise KS3ValidationError("Один из выбранных КС-2 не найден в проекте")
|
||||||
|
if ks2.status != "issued":
|
||||||
|
raise KS3ValidationError(f"КС-2 №{ks2.number} не проведён")
|
||||||
|
_reject_if_taken_by_other_issued_ks3(
|
||||||
|
db, project_id, ks2.id, ks2.number, exclude_ks3_id=document.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
document.status = "issued"
|
||||||
|
|
||||||
|
# Generate and persist the official artifact inside this transaction.
|
||||||
|
# KS-3 issue must NOT touch KS-2 artifacts.
|
||||||
|
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||||
|
from app.exporters.word.ks3_renderer import (
|
||||||
|
TEMPLATE_TYPE as KS3_TEMPLATE_TYPE,
|
||||||
|
TEMPLATE_VERSION as KS3_TEMPLATE_VERSION,
|
||||||
|
render_ks3_word,
|
||||||
|
)
|
||||||
|
from app.services.document_artifact_service import persist_artifact, remove_artifact_file
|
||||||
|
|
||||||
|
dto = build_ks3_export_dto(db, document)
|
||||||
|
content = render_ks3_word(dto)
|
||||||
|
artifact = persist_artifact(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
document_type="KS3",
|
||||||
|
document_id=document.id,
|
||||||
|
format="docx",
|
||||||
|
template_type=KS3_TEMPLATE_TYPE,
|
||||||
|
template_version=KS3_TEMPLATE_VERSION,
|
||||||
|
content=content,
|
||||||
|
dto=dto,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
if artifact is not None:
|
||||||
|
remove_artifact_file(artifact)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def project_ks3_totals(db: Session, project_id: int):
|
||||||
|
"""Return all KS-3 documents for a project with amounts."""
|
||||||
|
documents = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.project_id == project_id).order_by(KS3.date.desc(), KS3.id.desc()).all()
|
||||||
|
rows = []
|
||||||
|
for doc in documents:
|
||||||
|
total = ZERO
|
||||||
|
for link in doc.links:
|
||||||
|
if link.ks2:
|
||||||
|
total += _ks2_total(link.ks2)
|
||||||
|
rows.append({
|
||||||
|
"document": doc,
|
||||||
|
"ks2_count": len(doc.links),
|
||||||
|
"amount": total,
|
||||||
|
})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def ks3_cancel_block_reason(db: Session, project_id: int, ks3_id: int) -> str | None:
|
||||||
|
"""Return why KS-3 cannot be cancelled, or None if cancellation is allowed."""
|
||||||
|
from decimal import Decimal as D
|
||||||
|
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
|
||||||
|
document = db.query(KS3).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
|
||||||
|
if document is None:
|
||||||
|
return "КС-3 не найден"
|
||||||
|
if document.status == "cancelled":
|
||||||
|
return "КС-3 уже сторнирован"
|
||||||
|
paid = db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO)).join(
|
||||||
|
Payment, Payment.id == PaymentAllocation.payment_id
|
||||||
|
).filter(
|
||||||
|
PaymentAllocation.ks3_id == ks3_id,
|
||||||
|
Payment.status != "cancelled",
|
||||||
|
PaymentAllocation.amount > 0,
|
||||||
|
).scalar()
|
||||||
|
if D(str(paid or 0)) > 0:
|
||||||
|
return "На КС-3 распределены платежи. Сначала отмените распределения платежей."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_ks3(db: Session, project_id: int, ks3_id: int):
|
||||||
|
"""Cancel a KS-3 atomically. Blocked when payment allocations exist."""
|
||||||
|
try:
|
||||||
|
reason = ks3_cancel_block_reason(db, project_id, ks3_id)
|
||||||
|
if reason is not None:
|
||||||
|
raise KS3ValidationError(reason)
|
||||||
|
document = db.query(KS3).filter(
|
||||||
|
KS3.id == ks3_id, KS3.project_id == project_id
|
||||||
|
).with_for_update().first()
|
||||||
|
if document is None:
|
||||||
|
raise KS3ValidationError("КС-3 не найден")
|
||||||
|
if document.status == "cancelled":
|
||||||
|
raise KS3ValidationError("КС-3 уже сторнирован")
|
||||||
|
document.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
from app.models.ks2 import KS2, KS2Item
|
||||||
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
|
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentValidationError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _decimal(value):
|
||||||
|
try:
|
||||||
|
return Decimal(str(value)) if value is not None else ZERO
|
||||||
|
except (InvalidOperation, ValueError, TypeError):
|
||||||
|
return ZERO
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_money(value, label):
|
||||||
|
"""Parse a user-supplied money value; reject NaN/Infinity and bad input."""
|
||||||
|
try:
|
||||||
|
amount = Decimal(str(value).strip().replace(",", ".")) if value is not None else None
|
||||||
|
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||||
|
raise PaymentValidationError(f"{label}: неверное число") from exc
|
||||||
|
if amount is None or not amount.is_finite():
|
||||||
|
raise PaymentValidationError(f"{label}: неверное число")
|
||||||
|
return amount
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(value, label):
|
||||||
|
if value is None or (isinstance(value, str) and not value.strip()):
|
||||||
|
return None
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(str(value).strip())
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise PaymentValidationError(f"{label}: неверный формат даты") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _ks3_total(ks3_doc):
|
||||||
|
total = ZERO
|
||||||
|
for link in ks3_doc.links:
|
||||||
|
if link.ks2:
|
||||||
|
total += sum(_decimal(item.amount) for item in link.ks2.items)
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def _ks3_paid(db, ks3_id, exclude_payment_id=None):
|
||||||
|
"""Total paid amount for a KS-3, optionally excluding one payment."""
|
||||||
|
q = db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO)).join(
|
||||||
|
Payment, Payment.id == PaymentAllocation.payment_id
|
||||||
|
).filter(
|
||||||
|
PaymentAllocation.ks3_id == ks3_id,
|
||||||
|
Payment.status != "cancelled",
|
||||||
|
)
|
||||||
|
if exclude_payment_id is not None:
|
||||||
|
q = q.filter(PaymentAllocation.payment_id != exclude_payment_id)
|
||||||
|
return Decimal(str(q.scalar()))
|
||||||
|
|
||||||
|
|
||||||
|
def ks3_payment_summary(db: Session, project_id: int):
|
||||||
|
"""Return summary of KS-3 payments for a project."""
|
||||||
|
ks3_docs = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.project_id == project_id, KS3.status == "issued").all()
|
||||||
|
|
||||||
|
total_ks3 = ZERO
|
||||||
|
for doc in ks3_docs:
|
||||||
|
total_ks3 += _ks3_total(doc)
|
||||||
|
|
||||||
|
received = Decimal(str(
|
||||||
|
db.query(func.coalesce(func.sum(Payment.amount), ZERO))
|
||||||
|
.filter(Payment.project_id == project_id, Payment.status != "cancelled")
|
||||||
|
.scalar()
|
||||||
|
))
|
||||||
|
distributed = Decimal(str(
|
||||||
|
db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO))
|
||||||
|
.join(Payment, Payment.id == PaymentAllocation.payment_id)
|
||||||
|
.filter(Payment.project_id == project_id, Payment.status != "cancelled")
|
||||||
|
.scalar()
|
||||||
|
))
|
||||||
|
unallocated = max(received - distributed, ZERO)
|
||||||
|
outstanding = total_ks3 - distributed
|
||||||
|
return {
|
||||||
|
"ks3_count": len(ks3_docs),
|
||||||
|
"ks3_total": total_ks3,
|
||||||
|
"received": received,
|
||||||
|
"paid": distributed,
|
||||||
|
"distributed": distributed,
|
||||||
|
"unallocated": unallocated,
|
||||||
|
"outstanding": outstanding,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def available_ks3_for_payment(db: Session, project_id: int, exclude_payment_id=None):
|
||||||
|
"""Return issued KS-3 with paid/outstanding info."""
|
||||||
|
docs = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.project_id == project_id, KS3.status == "issued").order_by(KS3.date, KS3.id).all()
|
||||||
|
result = []
|
||||||
|
for doc in docs:
|
||||||
|
total = _ks3_total(doc)
|
||||||
|
paid = _ks3_paid(db, doc.id, exclude_payment_id)
|
||||||
|
outstanding = max(total - paid, ZERO)
|
||||||
|
result.append({
|
||||||
|
"id": doc.id,
|
||||||
|
"number": doc.number,
|
||||||
|
"date": doc.date,
|
||||||
|
"period_from": doc.reporting_period_from,
|
||||||
|
"period_to": doc.reporting_period_to,
|
||||||
|
"total": total,
|
||||||
|
"paid": paid,
|
||||||
|
"outstanding": outstanding,
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def save_payment(db: Session, project_id: int, payment_date: date,
|
||||||
|
amount: Decimal, currency: str, comment: str | None,
|
||||||
|
allocations: list[dict], document_number: str | None = None,
|
||||||
|
payment_id: int | None = None):
|
||||||
|
"""Create or update a payment with allocations."""
|
||||||
|
try:
|
||||||
|
amount = _decimal(amount) if not isinstance(amount, Decimal) else amount
|
||||||
|
# Decimal('NaN')/('Infinity') make comparisons raise or pass silently —
|
||||||
|
# reject them explicitly so the form gets 400, not 500 / a bad row.
|
||||||
|
if not amount.is_finite():
|
||||||
|
raise PaymentValidationError("Сумма платежа должна быть конечным числом")
|
||||||
|
if amount <= ZERO:
|
||||||
|
raise PaymentValidationError("Сумма платежа должна быть больше нуля")
|
||||||
|
currency = (currency or "").strip()
|
||||||
|
if not currency:
|
||||||
|
raise PaymentValidationError("Укажите валюту")
|
||||||
|
|
||||||
|
# Validate allocations
|
||||||
|
alloc_map = {}
|
||||||
|
total_allocated = ZERO
|
||||||
|
for alloc in allocations:
|
||||||
|
ks3_id = alloc["ks3_id"]
|
||||||
|
alloc_amount = _decimal(alloc["amount"])
|
||||||
|
if not alloc_amount.is_finite():
|
||||||
|
raise PaymentValidationError("Сумма распределения должна быть конечным числом")
|
||||||
|
if alloc_amount <= ZERO:
|
||||||
|
raise PaymentValidationError("Сумма распределения должна быть больше нуля")
|
||||||
|
if ks3_id in alloc_map:
|
||||||
|
raise PaymentValidationError(f"КС-3 с id={ks3_id} указан несколько раз")
|
||||||
|
alloc_map[ks3_id] = alloc_amount
|
||||||
|
total_allocated += alloc_amount
|
||||||
|
|
||||||
|
if total_allocated > amount:
|
||||||
|
raise PaymentValidationError("Сумма распределения превышает сумму платежа")
|
||||||
|
|
||||||
|
# Validate each KS-3
|
||||||
|
for ks3_id, alloc_amount in alloc_map.items():
|
||||||
|
ks3 = db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(KS3.id == ks3_id).first()
|
||||||
|
if ks3 is None:
|
||||||
|
raise PaymentValidationError(f"КС-3 с id={ks3_id} не найден")
|
||||||
|
if ks3.project_id != project_id:
|
||||||
|
raise PaymentValidationError(f"КС-3 №{ks3.number} не принадлежит этому проекту")
|
||||||
|
if ks3.status != "issued":
|
||||||
|
raise PaymentValidationError(f"КС-3 №{ks3.number} не проведён")
|
||||||
|
total = _ks3_total(ks3)
|
||||||
|
paid = _ks3_paid(db, ks3_id, exclude_payment_id=payment_id)
|
||||||
|
outstanding = max(total - paid, ZERO)
|
||||||
|
if alloc_amount > outstanding:
|
||||||
|
raise PaymentValidationError(
|
||||||
|
f"КС-3 №{ks3.number}: остаток к оплате {outstanding}, запрошено {alloc_amount}"
|
||||||
|
)
|
||||||
|
|
||||||
|
payment = None
|
||||||
|
if payment_id is not None:
|
||||||
|
payment = db.query(Payment).filter(
|
||||||
|
Payment.id == payment_id, Payment.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if payment is None:
|
||||||
|
raise PaymentValidationError("Платёж не найден")
|
||||||
|
if payment.status == "cancelled":
|
||||||
|
raise PaymentValidationError("Сторнированный платёж нельзя изменить")
|
||||||
|
else:
|
||||||
|
payment = Payment(project_id=project_id)
|
||||||
|
db.add(payment)
|
||||||
|
|
||||||
|
payment.date = payment_date
|
||||||
|
payment.document_number = (document_number or "").strip() or None
|
||||||
|
payment.amount = amount
|
||||||
|
payment.currency = currency
|
||||||
|
payment.comment = (comment or "").strip() or None
|
||||||
|
|
||||||
|
# Update allocations in place: clearing + re-adding the same KS-3 would
|
||||||
|
# INSERT before the deferred DELETE and hit uq_payment_ks3.
|
||||||
|
existing = {a.ks3_id: a for a in payment.allocations}
|
||||||
|
for ks3_id, alloc_amount in alloc_map.items():
|
||||||
|
if ks3_id in existing:
|
||||||
|
existing[ks3_id].amount = alloc_amount
|
||||||
|
else:
|
||||||
|
payment.allocations.append(
|
||||||
|
PaymentAllocation(ks3_id=ks3_id, amount=alloc_amount)
|
||||||
|
)
|
||||||
|
for ks3_id, alloc in existing.items():
|
||||||
|
if ks3_id not in alloc_map:
|
||||||
|
payment.allocations.remove(alloc)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(payment)
|
||||||
|
return payment
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def delete_payment(db: Session, project_id: int, payment_id: int):
|
||||||
|
"""Delete a payment and its allocations atomically. Blocked for cancelled payments."""
|
||||||
|
try:
|
||||||
|
payment = db.query(Payment).filter(
|
||||||
|
Payment.id == payment_id, Payment.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if payment is None:
|
||||||
|
raise PaymentValidationError("Платёж не найден")
|
||||||
|
if payment.status == "cancelled":
|
||||||
|
raise PaymentValidationError("Сторнированный платёж нельзя удалить")
|
||||||
|
db.delete(payment)
|
||||||
|
db.commit()
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_payment(db: Session, project_id: int, payment_id: int):
|
||||||
|
"""
|
||||||
|
Storno a payment atomically.
|
||||||
|
|
||||||
|
The payment is kept in history with status=cancelled. Its allocations are
|
||||||
|
preserved as historical records but excluded from active payment aggregates
|
||||||
|
(received / distributed / unallocated / outstanding) via status filters.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
payment = db.query(Payment).filter(
|
||||||
|
Payment.id == payment_id, Payment.project_id == project_id
|
||||||
|
).first()
|
||||||
|
if payment is None:
|
||||||
|
raise PaymentValidationError("Платёж не найден")
|
||||||
|
if payment.status == "cancelled":
|
||||||
|
raise PaymentValidationError("Платёж уже сторнирован")
|
||||||
|
payment.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(payment)
|
||||||
|
return payment
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def project_payments(db: Session, project_id: int):
|
||||||
|
"""Return all payments for a project with summary."""
|
||||||
|
payments = db.query(Payment).options(
|
||||||
|
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
|
||||||
|
).filter(Payment.project_id == project_id).order_by(Payment.date.desc(), Payment.id.desc()).all()
|
||||||
|
result = []
|
||||||
|
for p in payments:
|
||||||
|
allocated = sum(_decimal(a.amount) for a in p.allocations)
|
||||||
|
unallocated = max(_decimal(p.amount) - allocated, ZERO)
|
||||||
|
result.append({
|
||||||
|
"payment": p,
|
||||||
|
"allocated": allocated,
|
||||||
|
"unallocated": unallocated,
|
||||||
|
"ks3_count": len(p.allocations),
|
||||||
|
})
|
||||||
|
return result
|
||||||
@@ -1,21 +1,22 @@
|
|||||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
|
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
|
||||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">№{{ agreement.number }}</li></ol></nav>
|
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">№{{ agreement.number }}</li></ol></nav>
|
||||||
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
||||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">ДС №{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">К списку</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">Утверждено</span>{% else %}<span class="badge text-bg-secondary align-self-center">Черновик</span>{% endif %}</div></header>
|
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">ДС №{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">К списку</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">Утверждено</span><button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#cancelAgreementModal">Отменить ДС</button>{% elif agreement.status == 'cancelled' %}<span class="badge text-bg-danger align-self-center">ОТМЕНЕНО</span>{% else %}<span class="badge text-bg-secondary align-self-center">Черновик</span><button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteAgreementModal">Удалить ДС</button>{% endif %}</div></header>
|
||||||
{% if agreement.status == 'draft' %}
|
{% if agreement.status == 'draft' %}
|
||||||
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">Реквизиты ДС</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3">
|
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">Реквизиты ДС</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3">
|
||||||
<div class="col-md-3"><label class="form-label">Номер</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">Дата</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">Описание</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div>
|
<div class="col-md-3"><label class="form-label">Номер</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">Дата</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">Описание</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div>
|
||||||
<div class="col-md-7"><label class="form-label">Область применения</label><select class="form-select" name="scope" required><option value="project" {% if agreement.boq_document_id is none %}selected{% endif %}>Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary" type="submit">Сохранить реквизиты</button></div></form></section>
|
<div class="col-md-7"><label class="form-label">Область применения</label><select class="form-select" name="scope" required><option value="project" {% if agreement.boq_document_id is none %}selected{% endif %}>Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary" type="submit">Сохранить реквизиты</button></div></form></section>
|
||||||
{% else %}<section class="card border-0 shadow-sm mb-4"><div class="card-body row g-3"><div class="col-md-3"><span class="text-muted">Номер:</span> <strong>{{ agreement.number }}</strong></div><div class="col-md-3"><span class="text-muted">Дата:</span> {{ agreement.date.strftime('%d.%m.%Y') }}</div><div class="col-md-6"><span class="text-muted">Область:</span> {{ scope_label }}</div><div class="col-12"><span class="text-muted">Описание:</span> {{ agreement.description or '—' }}</div></div></section>{% endif %}
|
{% else %}<section class="card border-0 shadow-sm mb-4"><div class="card-body row g-3"><div class="col-md-3"><span class="text-muted">Номер:</span> <strong>{{ agreement.number }}</strong></div><div class="col-md-3"><span class="text-muted">Дата:</span> {{ agreement.date.strftime('%d.%m.%Y') }}</div><div class="col-md-6"><span class="text-muted">Область:</span> {{ scope_label }}</div><div class="col-12"><span class="text-muted">Описание:</span> {{ agreement.description or '—' }}</div></div></section>{% endif %}
|
||||||
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white d-flex justify-content-between"><h2 class="h5 mb-0">Позиции ДС</h2><span>{{ line_rows|length }} поз.</span></div><div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>Тип</th><th>№ / Позиция</th><th>Ед.</th><th class="text-end">Базовое / текущее</th><th class="text-end">Изменение</th><th class="text-end">После ДС</th><th class="text-end">Сумма изменения</th><th></th></tr></thead><tbody>
|
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white d-flex justify-content-between"><h2 class="h5 mb-0">Позиции ДС</h2><span>{{ line_rows|length }} поз.</span></div><div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>Тип</th><th>№ / Позиция</th><th>Ед.</th><th class="text-end">Базовое / текущее</th><th class="text-end">Изменение</th><th class="text-end">После ДС</th><th class="text-end">Сумма изменения</th><th></th></tr></thead><tbody>
|
||||||
{% for row in line_rows %}<tr><td>{% if row.line.change_type == 'new_position' %}<span class="badge text-bg-info">Новая</span>{% elif row.line.change_type == 'decrease' %}<span class="badge text-bg-warning">Уменьшение</span>{% else %}<span class="badge text-bg-primary">Увеличение</span>{% endif %}</td><td class="item-name"><div class="fw-semibold">{{ row.item.source_number or '' }} {{ row.item.name }}</div><small class="text-muted">{{ row.item.model or '' }}{% if row.item.manufacturer %} · {{ row.item.manufacturer }}{% endif %}</small></td><td>{{ row.item.unit or '—' }}</td><td class="text-end numeric">{{ row.before_quantity }}</td><td class="text-end numeric">{{ row.line.quantity_delta }}</td><td class="text-end numeric">{{ row.after_quantity }}</td><td class="text-end numeric">{{ row.amount_delta|money(project.currency) }}</td><td class="text-end">{% if agreement.status == 'draft' %}<button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#edit-line-{{ row.line.id }}">Править</button><form class="d-inline" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/delete" onsubmit="return confirm('Удалить позицию из черновика?')"><button class="btn btn-sm btn-outline-danger">×</button></form>{% endif %}</td></tr>
|
{% for row in line_rows %}<tr><td>{% if row.line.change_type == 'new_position' %}<span class="badge text-bg-info">Новая</span>{% elif row.line.change_type == 'decrease' %}<span class="badge text-bg-warning">Уменьшение</span>{% else %}<span class="badge text-bg-primary">Увеличение</span>{% endif %}</td><td class="item-name"><div class="fw-semibold">{{ row.item.source_number or '' }} {{ row.item.name }}</div><small class="text-muted">{{ row.item.model or '' }}{% if row.item.manufacturer %} · {{ row.item.manufacturer }}{% endif %}</small></td><td>{{ row.item.unit or '—' }}</td><td class="text-end numeric">{{ row.before_quantity }}</td><td class="text-end numeric">{{ row.line.quantity_delta }}</td><td class="text-end numeric">{{ row.after_quantity }}</td><td class="text-end numeric">{{ row.amount_delta|money(project.currency) }}</td><td class="text-end">{% if agreement.status == 'draft' %}<button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#edit-line-{{ row.line.id }}">Править</button><form class="d-inline" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/delete" onsubmit="return confirm('Удалить позицию из черновика?')"><button class="btn btn-sm btn-outline-danger">×</button></form>{% endif %}</td></tr>
|
||||||
{% if agreement.status == 'draft' %}<tr class="collapse" id="edit-line-{{ row.line.id }}"><td colspan="8"><form class="row g-2" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/edit"><div class="col-md-2"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" value="{{ row.line.quantity_delta }}" required></div>{% if row.line.change_type == 'new_position' %}<div class="col-md-2"><label class="form-label">Имя</label><input class="form-control" name="name" value="{{ row.item.name }}" required></div><div class="col-md-2"><label class="form-label">Модель</label><input class="form-control" name="model" value="{{ row.item.model or '' }}"></div><div class="col-md-2"><label class="form-label">Произв.</label><input class="form-control" name="manufacturer" value="{{ row.item.manufacturer or '' }}"></div><div class="col-md-2"><label class="form-label">Ед.</label><input class="form-control" name="unit" value="{{ row.item.unit or '' }}"></div><div class="col-md-2"><label class="form-label">Цена</label><input class="form-control" type="number" step="0.000000000001" name="unit_price" value="{{ row.item.unit_price }}" required></div><div class="col-md-3"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" required>{% for system in systems %}<option value="{{ system.id }}" {% if row.item.system_id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}</select></div><div class="col-md-3"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" required>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}" {% if row.item.section_id == section.id %}selected{% endif %}>{{ section.name }}</option>{% endfor %}</select></div>{% endif %}<div class="col-md-2 align-self-end"><button class="btn btn-primary">Сохранить</button></div></form></td></tr>{% endif %}
|
{% if agreement.status == 'draft' %}<tr class="collapse" id="edit-line-{{ row.line.id }}"><td colspan="8"><form class="row g-2" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/edit"><div class="col-md-2"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" value="{{ row.line.quantity_delta }}" required></div>{% if row.line.change_type == 'new_position' %}<div class="col-md-2"><label class="form-label">Имя</label><input class="form-control" name="name" value="{{ row.item.name }}" required></div><div class="col-md-2"><label class="form-label">Модель</label><input class="form-control" name="model" value="{{ row.item.model or '' }}"></div><div class="col-md-2"><label class="form-label">Произв.</label><input class="form-control" name="manufacturer" value="{{ row.item.manufacturer or '' }}"></div><div class="col-md-2"><label class="form-label">Ед.</label><input class="form-control" name="unit" value="{{ row.item.unit or '' }}"></div><div class="col-md-2"><label class="form-label">Цена</label><input class="form-control" type="number" step="0.000000000001" name="unit_price" value="{{ row.item.unit_price }}" required></div><div class="col-md-3"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" required>{% for system in systems %}<option value="{{ system.id }}" {% if row.item.system_id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}</select></div><div class="col-md-3"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" required>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}" {% if row.item.section_id == section.id %}selected{% endif %}>{{ section.name }}</option>{% endfor %}</select></div>{% endif %}<div class="col-md-2 align-self-end"><button class="btn btn-primary">Сохранить</button></div></form></td></tr>{% endif %}
|
||||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">Позиции ещё не добавлены.</td></tr>{% endfor %}</tbody></table></div><div class="card-footer bg-white d-flex justify-content-between"><span class="text-muted">Сумма изменения плана</span><strong>{{ change_amount|money(project.currency) }}</strong></div></section>
|
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">Позиции ещё не добавлены.</td></tr>{% endfor %}</tbody></table></div><div class="card-footer bg-white d-flex justify-content-between"><span class="text-muted">Сумма изменения плана</span><strong>{{ change_amount|money(project.currency) }}</strong></div></section>
|
||||||
{% if agreement.status == 'draft' %}<div class="row g-4"><div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить существующую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/existing"><div class="card-body"><div class="mb-3 position-relative" data-position-picker><label class="form-label" for="existing-position-search">Позиция проекта</label><div class="input-group"><input id="existing-position-search" class="form-control" type="search" autocomplete="off" placeholder="Поиск по номеру, наименованию, модели, системе..." aria-expanded="false" aria-controls="existing-position-results" required><button class="btn btn-outline-secondary" type="button" data-clear-position>Очистить</button></div><input type="hidden" name="work_item_id" data-work-item-id><div class="form-text" data-selected-position aria-live="polite">Позиция не выбрана</div><div id="existing-position-results" class="list-group position-absolute shadow bg-white" role="listbox" style="z-index:1050;max-height:18rem;overflow-y:auto;min-width:min(100%,40rem);display:none">{% for row in selectable_items %}<button type="button" class="list-group-item list-group-item-action autocomplete-position" role="option" data-id="{{ row.item.id }}" data-search="{{ row.item.source_number or '' }} {{ row.item.name }} {{ row.item.model or '' }} {{ row.item.manufacturer or '' }} {{ row.item.system.name if row.item.system else '' }} {{ row.item.section.name if row.item.section else '' }}" data-label="{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '' }} ? {{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %} ? {{ row.quantity }} {{ row.item.unit or '' }}"><span class="fw-semibold">{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '?' }}</span><br>{{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %}<small class="d-block text-muted">{{ row.item.manufacturer or '' }}{% if row.item.manufacturer %} ? {% endif %}{{ row.quantity }} {{ row.item.unit or '' }}</small></button>{% endfor %}<div class="list-group-item text-muted d-none" data-no-results>Ничего не найдено.</div><div class="list-group-item text-muted d-none" data-more-results>Показаны первые 20 результатов. Уточните поиск.</div></div></div><div class="mb-3"><label class="form-label">Δ количество (+ / −)</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" required><div class="form-text">Для уменьшения укажите отрицательное число. Сумма рассчитается по цене позиции.</div></div>{% if not selectable_items %}<div class="text-muted small mb-3">В этой области нет недобавленных позиц.</div>{% endif %}</div><div class="card-footer bg-white"><button class="btn btn-outline-primary" {% if not selectable_items %}disabled{% endif %}>Добавить позицию</button></div></form></section></div>
|
{% if agreement.status == 'draft' %}<div class="row g-4"><div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить существующую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/existing"><div class="card-body"><div class="mb-3 position-relative" data-position-picker><label class="form-label" for="existing-position-search">Позиция проекта</label><div class="input-group"><input id="existing-position-search" class="form-control" type="search" autocomplete="off" placeholder="Поиск по номеру, наименованию, модели, системе..." aria-expanded="false" aria-controls="existing-position-results" required><button class="btn btn-outline-secondary" type="button" data-clear-position>Очистить</button></div><input type="hidden" name="work_item_id" data-work-item-id><div class="form-text" data-selected-position aria-live="polite">Позиция не выбрана</div><div id="existing-position-results" class="list-group position-absolute shadow bg-white" role="listbox" style="z-index:1050;max-height:18rem;overflow-y:auto;min-width:min(100%,40rem);display:none">{% for row in selectable_items %}<button type="button" class="list-group-item list-group-item-action autocomplete-position" role="option" data-id="{{ row.item.id }}" data-search="{{ row.item.source_number or '' }} {{ row.item.name }} {{ row.item.model or '' }} {{ row.item.manufacturer or '' }} {{ row.item.system.name if row.item.system else '' }} {{ row.item.section.name if row.item.section else '' }}" data-label="{{ row.item.system.name if row.item.system else '' }} · {{ row.item.section.name if row.item.section else '' }} · {{ row.item.source_number or '' }} · {{ row.item.name }}{% if row.item.model %} · {{ row.item.model }}{% endif %} · {{ row.quantity }} {{ row.item.unit or '' }}"><span class="fw-semibold">{{ row.item.system.name if row.item.system else '' }} · {{ row.item.section.name if row.item.section else '' }} · {{ row.item.source_number or '?' }}</span><br>{{ row.item.name }}{% if row.item.model %} · {{ row.item.model }}{% endif %}<small class="d-block text-muted">{{ row.item.manufacturer or '' }}{% if row.item.manufacturer %} · {% endif %}{{ row.quantity }} {{ row.item.unit or '' }}</small></button>{% endfor %}<div class="list-group-item text-muted d-none" data-no-results>Ничего не найдено.</div><div class="list-group-item text-muted d-none" data-more-results>Показаны первые 20 результатов. Уточните поиск.</div></div></div><div class="mb-3"><label class="form-label">Δ количество (+ / −)</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" required><div class="form-text">Для уменьшения укажите отрицательное число. Сумма рассчитается по цене позиции.</div></div>{% if not selectable_items %}<div class="text-muted small mb-3">В этой области нет недобавленных позиц.</div>{% endif %}</div><div class="card-footer bg-white"><button class="btn btn-outline-primary" {% if not selectable_items %}disabled{% endif %}>Добавить позицию</button></div></form></section></div>
|
||||||
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить новую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">Ведомость (необязательно)</label><select class="form-select" name="source_boq_document_id"><option value="">Без ведомости</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">Модель / артикул</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">Производитель</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">Единица</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">Цена за единицу</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" data-system-select><option value="">Без системы</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ Новая система...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="Название системы"><button type="button" class="btn btn-outline-primary" data-create-system>Создать</button></div></div><div class="col-md-6"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" data-section-select><option value="">Без раздела</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ Новый раздел...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="Название раздела"><button type="button" class="btn btn-outline-primary" data-create-section>Создать</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">Добавить новую позицию</button></div></form></section></div></div>
|
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">Добавить новую позицию</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">Ведомость (необязательно)</label><select class="form-select" name="source_boq_document_id"><option value="">Без ведомости</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">Наименование</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">Модель / артикул</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">Производитель</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">Единица</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">Δ кол-во</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">Цена за единицу</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">Система</label><select class="form-select system-select" name="system_id" data-system-select><option value="">Без системы</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ Новая система...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="Название системы"><button type="button" class="btn btn-outline-primary" data-create-system>Создать</button></div></div><div class="col-md-6"><label class="form-label">Раздел</label><select class="form-select section-select" name="section_id" data-section-select><option value="">Без раздела</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ Новый раздел...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="Название раздела"><button type="button" class="btn btn-outline-primary" data-create-section>Создать</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">Добавить новую позицию</button></div></form></section></div></div>
|
||||||
<section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>Утвердить</button></section>
|
<section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>Утвердить</button></section>
|
||||||
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Подтвердите утверждение</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>ДС №{{ agreement.number }}</strong></div><div>Область: {{ scope_label }}</div><div>Количество позиций: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">После утверждения изменения нельзя редактировать.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">Утвердить ДС</button></form></div></div></div></div>
|
|
||||||
{% else %}<div class="alert alert-info">ДС утверждено. Изменения недоступны.</div>{% endif %}
|
{% else %}<div class="alert alert-info">ДС утверждено. Изменения недоступны.</div>{% endif %}
|
||||||
|
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Подтвердите утверждение</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>ДС №{{ agreement.number }}</strong></div><div>Область: {{ scope_label }}</div><div>Количество позиций: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">После утверждения изменения нельзя редактировать.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">Утвердить ДС</button></form></div></div></div></div><div class="modal fade" id="deleteAgreementModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Удалить черновик ДС</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Будет удалён весь документ <strong>ДС №{{ agreement.number }}</strong> и все его позиции ({{ line_rows|length }} шт.).</p><p class="text-danger mb-0">Действие необратимо.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/delete"><button class="btn btn-danger">Удалить ДС</button></form></div></div></div></div><div class="modal fade" id="cancelAgreementModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Отменить ДС</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>После отмены ДС перестанет участвовать в согласованном плане. История ДС сохранится.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Назад</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/cancel"><button class="btn btn-warning">Отменить ДС</button></form></div></div></div></div>
|
||||||
|
|
||||||
</main><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script>
|
</main><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script>
|
||||||
document.querySelectorAll('.system-select').forEach(systemSelect=>{const form=systemSelect.closest('form');const section=form.querySelector('.section-select');if(!section)return;const filter=()=>{const value=systemSelect.value;[...section.options].forEach(option=>{if(!option.dataset.system)return;option.hidden=!!value&&value!=='__new__'&&option.dataset.system!==value;});const selected=section.selectedOptions[0];if(selected&&selected.dataset.system&&selected.hidden)section.value='';};systemSelect.addEventListener('change',filter);filter();});
|
document.querySelectorAll('.system-select').forEach(systemSelect=>{const form=systemSelect.closest('form');const section=form.querySelector('.section-select');if(!section)return;const filter=()=>{const value=systemSelect.value;[...section.options].forEach(option=>{if(!option.dataset.system)return;option.hidden=!!value&&value!=='__new__'&&option.dataset.system!==value;});const selected=section.selectedOptions[0];if(selected&&selected.dataset.system&&selected.hidden)section.value='';};systemSelect.addEventListener('change',filter);filter();});
|
||||||
const makeOption=(select,id,name,attributes={})=>{const option=document.createElement('option');option.value=id;option.textContent=name;Object.entries(attributes).forEach(([key,value])=>option.dataset[key]=value);const createOption=[...select.options].find(item=>item.value==='__new__');select.insertBefore(option,createOption||null);select.value=String(id);};
|
const makeOption=(select,id,name,attributes={})=>{const option=document.createElement('option');option.value=id;option.textContent=name;Object.entries(attributes).forEach(([key,value])=>option.dataset[key]=value);const createOption=[...select.options].find(item=>item.value==='__new__');select.insertBefore(option,createOption||null);select.value=String(id);};
|
||||||
|
|||||||
@@ -1,5 +1,59 @@
|
|||||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Дополнительные соглашения — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
<!doctype html>
|
||||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item active">Дополнительные соглашения</li></ol></nav>
|
<html lang="ru">
|
||||||
<header class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4"><div><h1 class="h2 mb-1">Дополнительные соглашения</h1><div class="text-muted">{{ project.name }}</div></div><a class="btn btn-primary" href="/projects/{{ project.id }}/agreements/new">+ Создать ДС</a></header>
|
<head>
|
||||||
<section class="card border-0 shadow-sm"><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Номер</th><th>Дата</th><th>Наименование</th><th>Область</th><th>Статус</th><th class="text-end">Позиций</th><th></th></tr></thead><tbody>
|
<meta charset="utf-8">
|
||||||
{% for row in rows %}<tr><td class="fw-semibold">{{ row.agreement.number }}</td><td>{{ row.agreement.date.strftime('%d.%m.%Y') }}</td><td>{{ row.agreement.title }}</td><td>{{ row.scope_label }}</td><td>{% if row.agreement.status == 'approved' %}<span class="badge text-bg-success">Утверждено</span>{% else %}<span class="badge text-bg-secondary">Черновик</span>{% endif %}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">Открыть</a></td></tr>{% else %}<tr><td colspan="7" class="text-center text-muted py-5">ДС пока нет.</td></tr>{% endfor %}</tbody></table></div></section></main></body></html>
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Дополнительные соглашения — {{ project.name }}</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
.clickable-row { cursor: pointer; }
|
||||||
|
.clickable-row:hover { background-color: rgba(0,0,0,0.04); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<main class="container py-4">
|
||||||
|
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item active">Дополнительные соглашения</li></ol></nav>
|
||||||
|
<header class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
|
||||||
|
<div><h1 class="h2 mb-1">Дополнительные соглашения</h1><div class="text-muted">{{ project.name }}</div></div>
|
||||||
|
<a class="btn btn-primary" href="/projects/{{ project.id }}/agreements/new">+ Создать ДС</a>
|
||||||
|
</header>
|
||||||
|
{% if request.query_params.get('deleted') %}
|
||||||
|
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||||
|
Черновик ДС удалён.
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<section class="card border-0 shadow-sm">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table align-middle mb-0">
|
||||||
|
<thead><tr><th>Номер</th><th>Дата</th><th>Наименование</th><th>Область</th><th>Статус</th><th class="text-end">Позиций</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr class="clickable-row" data-url="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">
|
||||||
|
<td class="fw-semibold">{{ row.agreement.number }}</td>
|
||||||
|
<td>{{ row.agreement.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{{ row.agreement.title }}</td>
|
||||||
|
<td>{{ row.scope_label }}</td>
|
||||||
|
<td>{% if row.agreement.status == 'approved' %}<span class="badge text-bg-success">Утверждено</span>{% elif row.agreement.status == 'cancelled' %}<span class="badge text-bg-danger">Отменено</span>{% else %}<span class="badge text-bg-secondary">Черновик</span>{% endif %}</td>
|
||||||
|
<td class="text-end">{{ row.item_count }}</td>
|
||||||
|
<td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">Открыть</a></td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="7" class="text-center text-muted py-5">ДС пока нет.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
document.querySelectorAll('.clickable-row').forEach(function(row) {
|
||||||
|
row.addEventListener('click', function(e) {
|
||||||
|
if (e.target.closest('a, button, form, input, select, textarea')) return;
|
||||||
|
var url = row.dataset.url;
|
||||||
|
if (url) window.location.href = url;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Новое ДС — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Новое ДС — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
|
||||||
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">Создать</li></ol></nav><h1 class="h2 mb-4">Создать ДС</h1>
|
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">ДС</a></li><li class="breadcrumb-item active">Создать</li></ol></nav><h1 class="h2 mb-4">Создать ДС</h1>
|
||||||
{% if error %}<div class="alert alert-danger">{{ error }}</div>{% endif %}<form class="card border-0 shadow-sm" method="post" action="/projects/{{ project.id }}/agreements"><div class="card-body row g-3">
|
{% if error %}<div class="alert alert-danger">{{ error }}</div>{% endif %}<form class="card border-0 shadow-sm" method="post" action="/projects/{{ project.id }}/agreements"><div class="card-body row g-3">
|
||||||
<div class="col-md-4"><label class="form-label" for="number">Номер</label><input class="form-control" id="number" name="number" required maxlength="100"></div><div class="col-md-4"><label class="form-label" for="agreement_date">Дата</label><input class="form-control" type="date" id="agreement_date" name="agreement_date" value="{{ today }}" required></div><div class="col-md-4"><label class="form-label" for="title">Наименование</label><input class="form-control" id="title" name="title" required maxlength="255"></div>
|
<div class="col-md-4"><label class="form-label" for="number">Номер</label><input class="form-control" id="number" name="number" required maxlength="100"></div><div class="col-md-4"><label class="form-label" for="agreement_date">Дата</label><input class="form-control" type="date" id="agreement_date" name="agreement_date" value="{{ today }}" required></div><div class="col-md-4"><label class="form-label" for="title">Наименование</label><input class="form-control" id="title" name="title" required maxlength="255"></div>
|
||||||
<div class="col-12"><label class="form-label" for="description">Описание</label><textarea class="form-control" id="description" name="description" rows="3"></textarea></div><div class="col-md-7"><label class="form-label" for="scope">Область применения</label><select class="form-select" id="scope" name="scope" required><option value="project">Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}">{{ doc.name }}</option>{% endfor %}</select></div>
|
<div class="col-12"><label class="form-label" for="description">Описание</label><textarea class="form-control" id="description" name="description" rows="3"></textarea></div><div class="col-md-7"><label class="form-label" for="scope">Область применения</label><select class="form-select" id="scope" name="scope" required><option value="project">Весь проект</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}">{{ doc.display_name }}</option>{% endfor %}</select></div>
|
||||||
{% if not boq_documents %}<div class="col-12"><div class="alert alert-warning mb-0">В проекте нет Ведомостей. Можно выбрать область «Весь проект».</div></div>{% endif %}</div><div class="card-footer bg-white d-flex gap-2"><button class="btn btn-primary" type="submit">Создать черновик</button><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">Отмена</a></div></form></main></body></html>
|
{% if not boq_documents %}<div class="col-12"><div class="alert alert-warning mb-0">В проекте нет Ведомостей. Можно выбрать область «Весь проект».</div></div>{% endif %}</div><div class="card-footer bg-white d-flex gap-2"><button class="btn btn-primary" type="submit">Создать черновик</button><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">Отмена</a></div></form></main></body></html>
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>{% block title %}Work Volume Tracker{% endblock %}</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
.money-value { transition: filter 0.15s; }
|
||||||
|
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||||
|
.clickable-row { cursor: pointer; }
|
||||||
|
.clickable-row:hover { background-color: rgba(0,0,0,0.04); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="bg-light money-hidden">
|
||||||
|
<main class="container py-4">
|
||||||
|
<div class="d-flex justify-content-end align-items-center gap-2 mb-2">
|
||||||
|
<span class="text-muted small">Финансовые суммы</span>
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||||
|
</div>
|
||||||
|
{% block content %}{% endblock %}
|
||||||
|
</main>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var btn = document.getElementById('toggleMoney');
|
||||||
|
if (btn) btn.addEventListener('click', function() {
|
||||||
|
document.body.classList.toggle('money-hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('.clickable-row').forEach(function(row) {
|
||||||
|
row.addEventListener('click', function(e) {
|
||||||
|
if (e.target.closest('a, button, form, input, select, textarea')) return;
|
||||||
|
var url = row.dataset.url;
|
||||||
|
if (url) window.location.href = url;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ 'Редактирование' if document else 'Создание' }} КС-2{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>{{ 'Редактирование КС-2' if document else 'Создание КС-2' }}</h2>
|
||||||
|
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
{{ error }}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks2{% if document %}/{{ document.id }}/edit{% endif %}" id="ks2-form">
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="number" class="form-label">Номер КС-2</label>
|
||||||
|
<input type="text" class="form-control" id="number" name="number" required
|
||||||
|
value="{{ form_values.get('number', document.number if document else suggested_number) }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="document_date" class="form-label">Дата</label>
|
||||||
|
<input type="date" class="form-control" id="document_date" name="document_date" required
|
||||||
|
value="{{ form_values.get('document_date', document.date.isoformat() if document else '') }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="reporting_period_from" class="form-label">Период с</label>
|
||||||
|
<input type="date" class="form-control" id="reporting_period_from" name="reporting_period_from" required
|
||||||
|
value="{{ form_values.get('reporting_period_from', document.reporting_period_from.isoformat() if document and document.reporting_period_from else '') }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="reporting_period_to" class="form-label">Период по</label>
|
||||||
|
<input type="date" class="form-control" id="reporting_period_to" name="reporting_period_to" required
|
||||||
|
value="{{ form_values.get('reporting_period_to', document.reporting_period_to.isoformat() if document and document.reporting_period_to else '') }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<label for="comment" class="form-label">Комментарий</label>
|
||||||
|
<input type="text" class="form-control" id="comment" name="comment"
|
||||||
|
value="{{ form_values.get('comment', document.comment if document and document.comment else '') }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4>Объёмы к закрытию</h4>
|
||||||
|
|
||||||
|
<div class="d-flex flex-wrap gap-2 align-items-center mb-2">
|
||||||
|
<button type="button" class="btn btn-outline-success btn-sm" id="fill-available">Учесть весь объём</button>
|
||||||
|
<span class="form-text mb-0">Подставляет доступный остаток по всем позициям. Количество можно править вручную в любой момент.</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-sm" style="table-layout: fixed;">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: 50px">
|
||||||
|
<col>
|
||||||
|
<col style="width: 40px">
|
||||||
|
<col style="width: 72px">
|
||||||
|
<col style="width: 72px">
|
||||||
|
<col style="width: 72px">
|
||||||
|
<col style="width: 72px">
|
||||||
|
<col style="width: 72px">
|
||||||
|
<col style="width: 96px">
|
||||||
|
<col style="width: 88px">
|
||||||
|
<col style="width: 100px">
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>№ поз.</th>
|
||||||
|
<th>Наименование</th>
|
||||||
|
<th>Ед.</th>
|
||||||
|
<th class="text-end text-nowrap">План</th>
|
||||||
|
<th class="text-end text-nowrap">Факт</th>
|
||||||
|
<th class="text-end text-nowrap">Закрыто</th>
|
||||||
|
<th class="text-end text-nowrap">Доступно</th>
|
||||||
|
<th class="text-end text-nowrap">Цена</th>
|
||||||
|
<th class="text-nowrap">Кол-во</th>
|
||||||
|
<th></th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for balance in balances %}
|
||||||
|
{% set item_id = balance.item.id %}
|
||||||
|
{% set available = balance.available_quantity %}
|
||||||
|
{% set qty_value = form_values.get('quantity_' ~ item_id, selected.get(item_id, '')) %}
|
||||||
|
<tr data-available="{{ available }}" data-item-id="{{ item_id }}"{% if available <= 0 %} class="table-secondary"{% endif %}>
|
||||||
|
<td>{{ balance.item.source_number or '' }}</td>
|
||||||
|
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ balance.item.name }}</td>
|
||||||
|
<td>{{ balance.item.unit or '' }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ balance.planned_quantity|quantity2 }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ balance.actual_quantity|quantity2 }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ balance.closed_quantity|quantity2 }}</td>
|
||||||
|
<td class="text-end text-nowrap">
|
||||||
|
{{ available|quantity2 }}
|
||||||
|
{% if available <= 0 %}
|
||||||
|
<span class="badge text-bg-secondary">нет остатка</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="text-end text-nowrap" data-price="{{ balance.item.unit_price or 0 }}">{{ balance.item.unit_price|money }}</td>
|
||||||
|
<td>
|
||||||
|
<input type="number" class="form-control form-control-sm"
|
||||||
|
name="quantity_{{ item_id }}"
|
||||||
|
value="{{ qty_value }}"
|
||||||
|
min="0" step="0.01"
|
||||||
|
placeholder="0.00"
|
||||||
|
style="width: 100%; box-sizing: border-box;"
|
||||||
|
data-item-id="{{ item_id }}">
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button type="button" class="btn btn-outline-success btn-sm fill-row"
|
||||||
|
data-item-id="{{ item_id }}"
|
||||||
|
{% if available <= 0 %}disabled{% endif %}
|
||||||
|
title="Подставить доступный остаток этой позиции"
|
||||||
|
aria-label="Весь объём позиции {{ balance.item.source_number or item_id }}">Весь объём</button>
|
||||||
|
</td>
|
||||||
|
<td class="text-end text-nowrap" id="amount_{{ item_id }}">—</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary">{{ 'Сохранить' if document else 'Создать' }}</button>
|
||||||
|
<a href="/projects/{{ project.id }}/ks2{% if document %}/{{ document.id }}{% endif %}" class="btn btn-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const form = document.getElementById('ks2-form');
|
||||||
|
|
||||||
|
function availableOf(row) {
|
||||||
|
return parseFloat(row.dataset.available) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rows() {
|
||||||
|
return Array.from(document.querySelectorAll('tr[data-item-id]'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function quantityOf(row) {
|
||||||
|
return row.querySelector('input[type="number"][data-item-id]');
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAmount(itemId, quantityInput) {
|
||||||
|
const amountCell = document.getElementById('amount_' + itemId);
|
||||||
|
const priceCell = quantityInput.closest('tr').querySelector('[data-price]');
|
||||||
|
const price = parseFloat(priceCell.dataset.price) || 0;
|
||||||
|
const qty = parseFloat(quantityInput.value) || 0;
|
||||||
|
const amount = price * qty;
|
||||||
|
amountCell.textContent = amount > 0
|
||||||
|
? amount.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' \u20BD'
|
||||||
|
: '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillRow(row) {
|
||||||
|
const available = availableOf(row);
|
||||||
|
if (available <= 0) return;
|
||||||
|
const input = quantityOf(row);
|
||||||
|
if (!input) return;
|
||||||
|
input.value = available.toFixed(2);
|
||||||
|
updateAmount(input.dataset.itemId, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Кнопка строки: подставить доступный остаток только этой позиции.
|
||||||
|
document.querySelectorAll('.fill-row').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() {
|
||||||
|
const row = this.closest('tr[data-item-id]');
|
||||||
|
if (row) fillRow(row);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Глобальная кнопка: доступный остаток по всем позициям формы.
|
||||||
|
const fillAllBtn = document.getElementById('fill-available');
|
||||||
|
if (fillAllBtn) {
|
||||||
|
fillAllBtn.addEventListener('click', function() {
|
||||||
|
rows().forEach(fillRow);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ручной ввод количества всегда доступен и не зависит от кнопок.
|
||||||
|
document.querySelectorAll('input[type="number"][data-item-id]').forEach(function(input) {
|
||||||
|
input.addEventListener('input', function() {
|
||||||
|
updateAmount(this.dataset.itemId, this);
|
||||||
|
});
|
||||||
|
if (input.value) {
|
||||||
|
updateAmount(input.dataset.itemId, input);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Серверный контракт _entries_from_form ждёт include_<id>=1.
|
||||||
|
// Чекбоксов нет: поля include_* создаются на submit только для строк
|
||||||
|
// с количеством > 0. Это не «выбор», а протокол передачи закрываемых позиций.
|
||||||
|
if (form) {
|
||||||
|
form.addEventListener('submit', function() {
|
||||||
|
form.querySelectorAll('input[name^="include_"]').forEach(function(el) {
|
||||||
|
el.remove();
|
||||||
|
});
|
||||||
|
rows().forEach(function(row) {
|
||||||
|
const input = quantityOf(row);
|
||||||
|
if (!input) return;
|
||||||
|
const qty = parseFloat(input.value);
|
||||||
|
if (!(qty > 0)) return;
|
||||||
|
const hidden = document.createElement('input');
|
||||||
|
hidden.type = 'hidden';
|
||||||
|
hidden.name = 'include_' + input.dataset.itemId;
|
||||||
|
hidden.value = '1';
|
||||||
|
form.appendChild(hidden);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}КС-2 проекта {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>КС-2 проекта {{ project.name }}</h2>
|
||||||
|
<a href="/projects/{{ project.id }}/ks2/new" class="btn btn-primary mb-3">Создать новый КС-2</a>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Номер</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
<th>Количество позиций</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
<th>Действия</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr class="clickable-row" data-url="/projects/{{ project.id }}/ks2/{{ row.document.id }}">
|
||||||
|
<td>{{ row.document.number }}</td>
|
||||||
|
<td>{{ row.document.date.strftime('%d.%m.%Y') }}{% if row.document.reporting_period_from and row.document.reporting_period_to %}<br><small class="text-muted">{{ row.document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.document.reporting_period_to.strftime('%d.%m.%Y') }}</small>{% endif %}</td>
|
||||||
|
<td>
|
||||||
|
{% if row.document.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% elif row.document.status == 'issued' %}
|
||||||
|
<span class="badge bg-success">Проведён</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-secondary">Черновик</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>{{ row.item_count }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||||
|
<td>
|
||||||
|
<a href="/projects/{{ project.id }}/ks2/{{ row.document.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}КС-2 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>КС-2 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}</h2>
|
||||||
|
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<p><strong>Статус:</strong>
|
||||||
|
{% if document.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% elif document.status == 'issued' %}
|
||||||
|
<span class="badge bg-success">Проведён</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-secondary">Черновик</span>
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
{% if document.reporting_period_from and document.reporting_period_to %}
|
||||||
|
<p><strong>Период:</strong> {{ document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ document.reporting_period_to.strftime('%d.%m.%Y') }}</p>
|
||||||
|
{% endif %}
|
||||||
|
{% if document.comment %}
|
||||||
|
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||||
|
{% endif %}
|
||||||
|
<div class="mt-2">
|
||||||
|
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">КС-2 (Word)</a>
|
||||||
|
{% if document.status == 'cancelled' %}<span class="badge bg-danger ms-1">СТОРНИРОВАН</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if document.status == 'cancelled' %}
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
КС-2 сторнирован. Документ неизменяем, исключён из финансовых агрегатов. История сохранена.
|
||||||
|
</div>
|
||||||
|
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
{% else %}
|
||||||
|
|
||||||
|
{% if document.status == 'issued' %}
|
||||||
|
<div class="alert alert-success" role="alert">
|
||||||
|
КС-2 проведено. Документ не может быть изменён.
|
||||||
|
</div>
|
||||||
|
{% if cancel_blocked_reason %}
|
||||||
|
<div class="alert alert-warning" role="alert">
|
||||||
|
Сторнирование недоступно: {{ cancel_blocked_reason }}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks2/{{ document.id }}/cancel" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-danger"
|
||||||
|
onclick="return confirm('ВНИМАНИЕ: Сторнировать КС-2? Документ будет исключён из финансовых агрегатов. Действие необратимо.')">Сторнировать</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<h4>Позиции</h4>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Наименование</th>
|
||||||
|
<th>Ед.</th>
|
||||||
|
<th class="text-end text-nowrap">Количество</th>
|
||||||
|
<th class="text-end text-nowrap">Цена</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for line in document.items %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ line.work_item.name }}</td>
|
||||||
|
<td>{{ line.work_item.unit or '' }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ line.quantity|quantity2 }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ line.unit_price | money }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ line.amount | money }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<th colspan="4" class="text-end">Итого</th>
|
||||||
|
<th class="text-end text-nowrap money-value">{{ total | money }}</th>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if document.status == 'draft' %}
|
||||||
|
<div class="d-flex gap-2 align-items-center">
|
||||||
|
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/edit" class="btn btn-primary">Редактировать</a>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks2/{{ document.id }}/issue" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-success"
|
||||||
|
onclick="return confirm('После проведения КС-2 изменить его будет нельзя. Продолжить?')">Провести КС-2</button>
|
||||||
|
</form>
|
||||||
|
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
|
||||||
|
<h4>Источники факта</h4>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Наименование</th>
|
||||||
|
<th>Дата отчёта</th>
|
||||||
|
<th>Количество</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for line in document.items %}
|
||||||
|
<tr>
|
||||||
|
<td colspan="3"><strong>{{ line.work_item.name }}</strong></td>
|
||||||
|
</tr>
|
||||||
|
{% for source in line.sources %}
|
||||||
|
<tr>
|
||||||
|
<td></td>
|
||||||
|
<td>{{ source.daily_report_item.report.report_date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{{ source.quantity|quantity2 }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/projects/{{ project.id }}/ks2" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ 'Редактирование' if document else 'Создание' }} КС-3{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>{{ 'Редактирование КС-3' if document else 'Создание КС-3' }}</h2>
|
||||||
|
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks3{% if document %}/{{ document.id }}/edit{% endif %}">
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="number" class="form-label">Номер КС-3</label>
|
||||||
|
<input type="text" class="form-control" id="number" name="number" required
|
||||||
|
value="{{ form_values.get('number', document.number if document else suggested_number) }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="document_date" class="form-label">Дата</label>
|
||||||
|
<input type="date" class="form-control" id="document_date" name="document_date" required
|
||||||
|
value="{{ form_values.get('document_date', document.date.isoformat() if document else '') }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="reporting_period_from" class="form-label">Период с</label>
|
||||||
|
<input type="date" class="form-control" id="reporting_period_from" name="reporting_period_from" required
|
||||||
|
value="{{ form_values.get('reporting_period_from', document.reporting_period_from.isoformat() if document and document.reporting_period_from else '') }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="reporting_period_to" class="form-label">Период по</label>
|
||||||
|
<input type="date" class="form-control" id="reporting_period_to" name="reporting_period_to" required
|
||||||
|
value="{{ form_values.get('reporting_period_to', document.reporting_period_to.isoformat() if document and document.reporting_period_to else '') }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<label for="comment" class="form-label">Комментарий</label>
|
||||||
|
<input type="text" class="form-control" id="comment" name="comment"
|
||||||
|
value="{{ form_values.get('comment', document.comment if document and document.comment else '') }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4>Выберите проведённые КС-2</h4>
|
||||||
|
|
||||||
|
{% if available_ks2 %}
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-sm" style="table-layout: fixed;">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: 40px">
|
||||||
|
<col style="width: 100px">
|
||||||
|
<col style="width: 90px">
|
||||||
|
<col>
|
||||||
|
<col style="width: 120px">
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th></th>
|
||||||
|
<th>№ КС-2</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Период</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for item in available_ks2 %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<input type="checkbox" class="form-check-input" name="ks2_ids"
|
||||||
|
value="{{ item.id }}"
|
||||||
|
{% if item.id in selected_ids %}checked{% endif %}>
|
||||||
|
</td>
|
||||||
|
<td>{{ item.number }}</td>
|
||||||
|
<td>{{ item.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{% if item.period_from and item.period_to %}{{ item.period_from.strftime('%d.%m.%Y') }} — {{ item.period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ item.total | money }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-info">Нет проведённых КС-2 для выбора.</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary">{{ 'Сохранить' if document else 'Создать' }}</button>
|
||||||
|
<a href="/projects/{{ project.id }}/ks3{% if document %}/{{ document.id }}{% endif %}" class="btn btn-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}КС-3 проекта {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>КС-3 проекта {{ project.name }}</h2>
|
||||||
|
<a href="/projects/{{ project.id }}/ks3/new" class="btn btn-primary mb-3">Создать КС-3</a>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Номер</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Период</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
<th>КС-2</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
<th>Действия</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr class="clickable-row" data-url="/projects/{{ project.id }}/ks3/{{ row.document.id }}">
|
||||||
|
<td>{{ row.document.number }}</td>
|
||||||
|
<td>{{ row.document.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{% if row.document.reporting_period_from and row.document.reporting_period_to %}{{ row.document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.document.reporting_period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||||
|
<td>
|
||||||
|
{% if row.document.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% elif row.document.status == 'issued' %}
|
||||||
|
<span class="badge bg-success">Проведён</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-secondary">Черновик</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>{{ row.ks2_count }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.amount | money }}</td>
|
||||||
|
<td>
|
||||||
|
<a href="/projects/{{ project.id }}/ks3/{{ row.document.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="7" class="text-center text-muted py-4">КС-3 пока нет.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}КС-3 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>КС-3 №{{ document.number }} от {{ document.date.strftime('%d.%m.%Y') }}</h2>
|
||||||
|
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<p><strong>Статус:</strong>
|
||||||
|
{% if document.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% elif document.status == 'issued' %}
|
||||||
|
<span class="badge bg-success">Проведён</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-secondary">Черновик</span>
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
{% if document.reporting_period_from and document.reporting_period_to %}
|
||||||
|
<p><strong>Период:</strong> {{ document.reporting_period_from.strftime('%d.%m.%Y') }} — {{ document.reporting_period_to.strftime('%d.%m.%Y') }}</p>
|
||||||
|
{% endif %}
|
||||||
|
{% if document.comment %}
|
||||||
|
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||||
|
{% endif %}
|
||||||
|
<div class="mt-2">
|
||||||
|
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">КС-3 (Word)</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if document.status == 'cancelled' %}
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
КС-3 сторнировано. Документ неизменяем, исключён из финансовых агрегатов. Связанные КС-2 сохранены.
|
||||||
|
</div>
|
||||||
|
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
{% else %}
|
||||||
|
|
||||||
|
<h4>Включённые КС-2</h4>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>№ КС-2</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Период</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in ks2_rows %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ row.ks2.number }}</td>
|
||||||
|
<td>{{ row.ks2.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{% if row.ks2.reporting_period_from and row.ks2.reporting_period_to %}{{ row.ks2.reporting_period_from.strftime('%d.%m.%Y') }} — {{ row.ks2.reporting_period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.total | money }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="4" class="text-center text-muted">Нет включённых КС-2.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<th colspan="3" class="text-end">Итого</th>
|
||||||
|
<th class="text-end text-nowrap money-value">{{ total | money }}</th>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if document.status == 'draft' %}
|
||||||
|
<div class="d-flex gap-2 align-items-center">
|
||||||
|
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/edit" class="btn btn-primary">Редактировать</a>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks3/{{ document.id }}/issue" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-success"
|
||||||
|
onclick="return confirm('После проведения КС-3 изменить его будет нельзя. Продолжить?')">Провести КС-3</button>
|
||||||
|
</form>
|
||||||
|
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-success" role="alert">
|
||||||
|
КС-3 проведено. Документ не может быть изменён.
|
||||||
|
</div>
|
||||||
|
{% if cancel_blocked_reason %}
|
||||||
|
<div class="alert alert-warning" role="alert">
|
||||||
|
Сторнирование недоступно: {{ cancel_blocked_reason }}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/ks3/{{ document.id }}/cancel" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-danger"
|
||||||
|
onclick="return confirm('ВНИМАНИЕ: Сторнировать КС-3? Документ будет исключён из финансовых агрегатов. Действие необратимо.')">Сторнировать</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<a href="/projects/{{ project.id }}/ks3" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}КС-6а — {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<h2>КС-6а — Журнал выполненных работ</h2>
|
||||||
|
<p class="text-muted">{{ project.name }}</p>
|
||||||
|
|
||||||
|
<form method="get" action="/projects/{{ project.id }}/ks6a" class="card card-body mb-3">
|
||||||
|
<div class="row g-3 align-items-end">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="date_from" class="form-label">Дата с</label>
|
||||||
|
<input type="date" class="form-control" id="date_from" name="date_from" required
|
||||||
|
value="{{ date_from }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="date_to" class="form-label">Дата по</label>
|
||||||
|
<input type="date" class="form-control" id="date_to" name="date_to" required
|
||||||
|
value="{{ date_to }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4">
|
||||||
|
<label for="system_id" class="form-label">Система</label>
|
||||||
|
<select class="form-select" id="system_id" name="system_id">
|
||||||
|
<option value="all" {% if not system_id or system_id == 'all' %}selected{% endif %}>Все системы</option>
|
||||||
|
{% for system in systems %}
|
||||||
|
<option value="{{ system.id }}" {% if system_id|string == system.id|string %}selected{% endif %}>{{ system.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Сформировать</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if date_from and date_to and not error %}
|
||||||
|
<div class="mb-2 d-flex flex-wrap align-items-center gap-2">
|
||||||
|
<div class="text-muted">
|
||||||
|
Период: {{ date_from }} — {{ date_to }}
|
||||||
|
{% if system_id and system_id != 'all' %}
|
||||||
|
{% for system in systems %}{% if system_id|string == system.id|string %} · Система: {{ system.name }}{% endif %}{% endfor %}
|
||||||
|
{% else %} · Все системы{% endif %}
|
||||||
|
· Строк: {{ total_count }}
|
||||||
|
</div>
|
||||||
|
<a href="/projects/{{ project.id }}/ks6a/export/excel?date_from={{ date_from }}&date_to={{ date_to }}&system_id={{ system_id or 'all' }}"
|
||||||
|
class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||||
|
<a href="/projects/{{ project.id }}/ks6a/export/word?date_from={{ date_from }}&date_to={{ date_to }}&system_id={{ system_id or 'all' }}"
|
||||||
|
class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if rows %}
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-sm" style="table-layout: fixed;">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: 88px">
|
||||||
|
<col style="width: 120px">
|
||||||
|
<col style="width: 120px">
|
||||||
|
<col style="width: 70px">
|
||||||
|
<col>
|
||||||
|
<col style="width: 50px">
|
||||||
|
<col style="width: 80px">
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Система</th>
|
||||||
|
<th>Раздел</th>
|
||||||
|
<th>№ поз.</th>
|
||||||
|
<th>Наименование</th>
|
||||||
|
<th>Ед.</th>
|
||||||
|
<th class="text-end text-nowrap">Кол-во</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr>
|
||||||
|
<td class="text-nowrap">{{ row.report.report_date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.system.name if row.work_item.system else '—' }}</td>
|
||||||
|
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.section.name if row.work_item.section else '—' }}</td>
|
||||||
|
<td>{{ row.work_item.source_number or '' }}</td>
|
||||||
|
<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ row.work_item.name }}</td>
|
||||||
|
<td>{{ row.work_item.unit or '' }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ row.completed_quantity|quantity2 }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-info">За выбранный период работ не найдено.</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ 'Редактирование' if payment else 'Новый' }} платёж — {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<h2>{{ 'Редактирование платежа' if payment else 'Новый платёж' }}</h2>
|
||||||
|
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/payments{% if payment %}/{{ payment.id }}/edit{% endif %}">
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="payment_date" class="form-label">Дата</label>
|
||||||
|
<input type="date" class="form-control" id="payment_date" name="payment_date" required
|
||||||
|
value="{{ payment.date.isoformat() if payment else '' }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="document_number" class="form-label">Номер документа</label>
|
||||||
|
<input type="text" class="form-control" id="document_number" name="document_number"
|
||||||
|
value="{{ payment.document_number if payment and payment.document_number else '' }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="amount" class="form-label">Сумма</label>
|
||||||
|
<input type="number" class="form-control" id="amount" name="amount" required min="0.01" step="0.01"
|
||||||
|
value="{{ payment.amount if payment else '' }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="currency" class="form-label">Валюта</label>
|
||||||
|
<input type="text" class="form-control" id="currency" name="currency" required
|
||||||
|
value="{{ payment.currency if payment else 'RUB' }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<label for="comment" class="form-label">Комментарий</label>
|
||||||
|
<input type="text" class="form-control" id="comment" name="comment"
|
||||||
|
value="{{ payment.comment if payment and payment.comment else '' }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4>Распределение по КС-3</h4>
|
||||||
|
<p class="text-muted">Укажите суммы распределения. Можно оставить пустым.</p>
|
||||||
|
|
||||||
|
{% if available_ks3 %}
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-sm">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>№ КС-3</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Период</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма КС-3</th>
|
||||||
|
<th class="text-end text-nowrap">Оплачено</th>
|
||||||
|
<th class="text-end text-nowrap">Остаток</th>
|
||||||
|
<th>Распределить</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for item in available_ks3 %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ item.number }}</td>
|
||||||
|
<td>{{ item.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{% if item.period_from and item.period_to %}{{ item.period_from.strftime('%d.%m.%Y') }} — {{ item.period_to.strftime('%d.%m.%Y') }}{% endif %}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ item.total | money }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ item.paid | money }}</td>
|
||||||
|
<td class="text-end text-nowrap">{{ item.outstanding | money }}</td>
|
||||||
|
<td style="min-width: 120px">
|
||||||
|
<input type="number" class="form-control form-control-sm" name="alloc_{{ item.id }}"
|
||||||
|
min="0" step="0.01" placeholder="0.00"
|
||||||
|
value="{{ current_allocs.get(item.id, '') if current_allocs else '' }}">
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-info">Нет проведённых КС-3 для распределения.</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary">{{ 'Сохранить' if payment else 'Создать' }}</button>
|
||||||
|
<a href="/projects/{{ project.id }}/payments{% if payment %}/{{ payment.id }}{% endif %}" class="btn btn-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Платежи — {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container mt-4">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
<h2>Платежи проекта {{ project.name }}</h2>
|
||||||
|
<a href="/projects/{{ project.id }}/payments/new" class="btn btn-primary mb-3">Новый платёж</a>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped align-middle">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: 6.5rem">
|
||||||
|
<col style="width: 8rem">
|
||||||
|
<col style="width: 7.5rem">
|
||||||
|
<col style="width: 8rem">
|
||||||
|
<col style="width: 4.5rem">
|
||||||
|
<col style="width: 8rem">
|
||||||
|
<col style="width: 8.5rem">
|
||||||
|
<col style="width: 4.5rem">
|
||||||
|
<col>
|
||||||
|
<col style="width: 17rem">
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Номер документа</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
<th>Валюта</th>
|
||||||
|
<th class="text-end text-nowrap">Распределено</th>
|
||||||
|
<th class="text-end text-nowrap">Не распределено</th>
|
||||||
|
<th>КС-3</th>
|
||||||
|
<th>Комментарий</th>
|
||||||
|
<th class="text-nowrap">Действия</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr class="clickable-row" data-url="/projects/{{ project.id }}/payments/{{ row.payment.id }}">
|
||||||
|
<td class="text-nowrap">{{ row.payment.date.strftime('%d.%m.%Y') }}</td>
|
||||||
|
<td>{{ row.payment.document_number or '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{% if row.payment.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-success">Активный</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.payment.amount | money(row.payment.currency) }}</td>
|
||||||
|
<td>{{ row.payment.currency }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.allocated | money(row.payment.currency) }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ row.unallocated | money(row.payment.currency) }}</td>
|
||||||
|
<td>{{ row.ks3_count }}</td>
|
||||||
|
<td>{{ row.payment.comment or '' }}</td>
|
||||||
|
<td class="text-nowrap payments-actions">
|
||||||
|
<span class="d-inline-flex gap-1 align-items-center">
|
||||||
|
<a href="/projects/{{ project.id }}/payments/{{ row.payment.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a>
|
||||||
|
{% if row.payment.status != 'cancelled' %}
|
||||||
|
<a href="/projects/{{ project.id }}/payments/{{ row.payment.id }}/edit" class="btn btn-sm btn-outline-secondary">Редактировать</a>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/payments/{{ row.payment.id }}/delete" class="d-inline m-0">
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Удалить платёж?')">Удалить</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<span class="text-muted small">Действия недоступны</span>
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="10" class="text-center text-muted py-4">Платежей пока нет.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Платёж — {{ project.name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<style>
|
||||||
|
/*
|
||||||
|
* Payment card layout only.
|
||||||
|
* Alert must stay inside the container and wrap long text (incl. 480px).
|
||||||
|
* min-width:0 lets flex/grid children shrink instead of overflowing.
|
||||||
|
*/
|
||||||
|
.payment-view {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.payment-storno-alert {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
white-space: normal;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
word-wrap: break-word;
|
||||||
|
word-break: normal;
|
||||||
|
}
|
||||||
|
.payment-storno-alert p {
|
||||||
|
margin: 0 0 .5rem;
|
||||||
|
}
|
||||||
|
.payment-storno-alert p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
.payment-view .money-value,
|
||||||
|
.payment-view .card-body {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
.payment-view .card {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.payment-view .row {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.payment-view .row > [class*="col"] {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.payment-actions {
|
||||||
|
justify-content: flex-start;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.payment-actions .btn {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<div class="payment-view">
|
||||||
|
<nav class="mb-3">
|
||||||
|
<a href="/projects/{{ project.id }}" class="btn btn-outline-secondary btn-sm">← К проекту</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<h2 class="h4 text-break">Платёж{% if payment.document_number %} №{{ payment.document_number }}{% endif %} от {{ payment.date.strftime('%d.%m.%Y') }}</h2>
|
||||||
|
|
||||||
|
{% if payment.status == 'cancelled' %}
|
||||||
|
<div class="alert alert-danger payment-storno-alert" role="alert">
|
||||||
|
<p>Платёж сторнирован. Сумма не считается полученными деньгами, распределения исключены из агрегатов.</p>
|
||||||
|
<p>Исторические распределения сохранены ниже.</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="mb-3"><strong>Статус:</strong>
|
||||||
|
{% if payment.status == 'cancelled' %}
|
||||||
|
<span class="badge bg-danger">Сторнирован</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-success">Активен</span>
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-12 col-sm-6 col-lg-4">
|
||||||
|
<div class="text-muted small mb-1">Сумма</div>
|
||||||
|
<div class="fw-semibold money-value text-break">{{ payment.amount | money(payment.currency) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-6 col-lg-4">
|
||||||
|
<div class="text-muted small mb-1">Распределено</div>
|
||||||
|
<div class="fw-semibold money-value text-break">{{ allocated | money(payment.currency) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-6 col-lg-4">
|
||||||
|
<div class="text-muted small mb-1">Не распределено</div>
|
||||||
|
<div class="fw-semibold money-value text-break">{{ unallocated | money(payment.currency) }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% if payment.comment %}
|
||||||
|
<p class="mb-0 mt-3 text-break"><strong>Комментарий:</strong> {{ payment.comment }}</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 class="h5 text-break">{% if payment.status == 'cancelled' %}Исторические распределения по КС-3{% else %}Распределение по КС-3{% endif %}</h4>
|
||||||
|
|
||||||
|
<div class="table-responsive mb-3">
|
||||||
|
<table class="table table-striped align-middle">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>№ КС-3</th>
|
||||||
|
<th>Дата КС-3</th>
|
||||||
|
<th class="text-end text-nowrap">Сумма</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for alloc in payment.allocations %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ alloc.ks3.number if alloc.ks3 else alloc.ks3_id }}</td>
|
||||||
|
<td class="text-nowrap">{{ alloc.ks3.date.strftime('%d.%m.%Y') if alloc.ks3 and alloc.ks3.date else '—' }}</td>
|
||||||
|
<td class="text-end text-nowrap money-value">{{ alloc.amount | money(payment.currency) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="3" class="text-center text-muted">Платёж не распределён.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex flex-wrap gap-2 payment-actions">
|
||||||
|
<a href="/projects/{{ project.id }}/payments" class="btn btn-secondary">Назад к списку</a>
|
||||||
|
{% if payment.status != 'cancelled' %}
|
||||||
|
<a href="/projects/{{ project.id }}/payments/{{ payment.id }}/edit" class="btn btn-primary">Редактировать</a>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/payments/{{ payment.id }}/cancel" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-danger"
|
||||||
|
onclick="return confirm('ВНИМАНИЕ: Сторнировать платёж? Сумма перестанет считаться полученной. Действие необратимо.')">Сторнировать платёж</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/payments/{{ payment.id }}/delete" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-danger"
|
||||||
|
onclick="return confirm('Удалить платёж?')">Удалить</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<span class="text-muted small align-self-center">Редактирование, удаление и повторное сторнирование недоступны.</span>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -5,8 +5,44 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>{{ document_title }} — {{ project.name }}</title>
|
<title>{{ document_title }} — {{ project.name }}</title>
|
||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
.money-value { transition: filter 0.15s; white-space: nowrap; }
|
||||||
|
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||||
|
.microstat-bar { min-width: 6rem; height: 0.5rem; }
|
||||||
|
.microstat-label { font-size: 0.75rem; }
|
||||||
|
.boq-table { table-layout: fixed; width: 100%; }
|
||||||
|
.boq-table td, .boq-table th { overflow-wrap: anywhere; }
|
||||||
|
.boq-table .money-value { overflow-wrap: normal; }
|
||||||
|
.boq-table-wrap {
|
||||||
|
max-height: calc(100vh - 12rem);
|
||||||
|
overflow: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
.boq-table thead th {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 10;
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
box-shadow: inset 0 -1px 0 #dee2e6;
|
||||||
|
}
|
||||||
|
.toggle-row { cursor: pointer; user-select: none; }
|
||||||
|
.toggle-row .toggle-icon { display: inline-block; width: 1.2em; transition: transform 0.15s; }
|
||||||
|
.toggle-row.collapsed .toggle-icon { transform: rotate(-90deg); }
|
||||||
|
|
||||||
|
.progress-legend { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; }
|
||||||
|
.progress-legend .dot { display: inline-block; width: 0.75rem; height: 0.75rem; border-radius: 50%; }
|
||||||
|
.progress-legend .dot-not-started { background: #6c757d; }
|
||||||
|
.progress-legend .dot-in-progress { background: #0d6efd; }
|
||||||
|
.progress-legend .dot-completed { background: #198754; }
|
||||||
|
.progress-legend .dot-overspend { background: #dc3545; }
|
||||||
|
|
||||||
|
.filter-bar { display: flex; flex-wrap: wrap; gap: 0.375rem; }
|
||||||
|
.filter-btn { cursor: pointer; }
|
||||||
|
.filtered-out { display: none !important; }
|
||||||
|
.group-hidden { display: none !important; }
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body class="money-hidden">
|
||||||
<main class="container my-4">
|
<main class="container my-4">
|
||||||
<nav aria-label="Навигация" class="mb-3">
|
<nav aria-label="Навигация" class="mb-3">
|
||||||
<ol class="breadcrumb">
|
<ol class="breadcrumb">
|
||||||
@@ -16,52 +52,127 @@
|
|||||||
<li class="breadcrumb-item active" aria-current="page">Ведомость</li>
|
<li class="breadcrumb-item active" aria-current="page">Ведомость</li>
|
||||||
</ol>
|
</ol>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="d-flex justify-content-between align-items-start mb-4">
|
<div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-2">
|
||||||
<div>
|
<div>
|
||||||
<h1>{{ document_title }}</h1>
|
<h1>{{ document_title }}</h1>
|
||||||
<p class="text-muted mb-0">{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}</p>
|
<p class="text-muted mb-0">
|
||||||
|
{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}
|
||||||
|
</p>
|
||||||
|
{% if document.document_number or document.document_date or document.contract %}
|
||||||
|
<p class="text-muted small mb-0">
|
||||||
|
{% if document.document_number %}<span>№ {{ document.document_number }}</span>{% endif %}
|
||||||
|
{% if document.document_date %}<span class="ms-2">от {{ document.document_date.strftime('%d.%m.%Y') }}</span>{% endif %}
|
||||||
|
{% if document.contract %}<span class="ms-2">Договор: {{ document.contract }}</span>{% endif %}
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
<div class="d-flex flex-wrap gap-2">
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" id="expandAll">Развернуть всё</button>
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" id="collapseAll">Свернуть всё</button>
|
||||||
|
{% if not has_history %}
|
||||||
|
<form method="post" action="/boq/{{ project.id }}/documents/{{ document.id }}/delete" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-danger" onclick="return confirm('Удалить ведомость и все её позиции? Это действие необратимо.')">Удалить ведомость</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<form method="post" action="/boq/{{ project.id }}/documents/{{ document.id }}/archive" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-warning" onclick="return confirm('Архивировать ведомость? Данные будут сохранены.')">Архивировать</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-end align-items-center gap-2 mb-3">
|
||||||
|
<span class="text-muted small">Финансовые суммы</span>
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="table-responsive">
|
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||||
<table class="table table-bordered table-sm align-middle">
|
<div class="progress-legend">
|
||||||
|
<span class="text-muted small">Выполнение:</span>
|
||||||
|
<span class="small"><span class="dot dot-not-started"></span> Не начато</span>
|
||||||
|
<span class="small"><span class="dot dot-in-progress"></span> В работе</span>
|
||||||
|
<span class="small"><span class="dot dot-completed"></span> Выполнено</span>
|
||||||
|
<span class="small"><span class="dot dot-overspend"></span> Перерасход</span>
|
||||||
|
</div>
|
||||||
|
<div class="filter-bar" id="progressFilter">
|
||||||
|
<button type="button" class="btn btn-sm btn-primary filter-btn active" data-filter="all">Все</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="not-started">Не начато</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="in-progress">В работе</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="completed">Выполнено</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="overspend">Перерасход</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="boq-table-wrap">
|
||||||
|
<table class="table table-bordered table-sm align-middle boq-table">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: 3.5rem">
|
||||||
|
<col>
|
||||||
|
<col style="width: 9rem">
|
||||||
|
<col style="width: 9rem">
|
||||||
|
<col style="width: 4.5rem">
|
||||||
|
<col style="width: 5.5rem">
|
||||||
|
<col style="width: 7.5rem">
|
||||||
|
<col style="width: 8.5rem">
|
||||||
|
<col style="width: 11rem">
|
||||||
|
</colgroup>
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
<tr>
|
<tr>
|
||||||
<th>№</th><th>Наименование</th><th>Модель / артикул</th><th>Производитель</th>
|
<th>№</th><th>Наименование</th><th>Модель / артикул</th><th>Производитель</th>
|
||||||
<th>Ед. изм.</th><th class="text-end">Кол-во</th><th class="text-end">Цена за ед.</th><th class="text-end">Сумма</th>
|
<th>Ед. изм.</th><th class="text-end">Кол-во</th><th class="text-end">Цена за ед.</th><th class="text-end">Сумма</th>
|
||||||
|
<th>Выполнение</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for system_node in systems %}
|
{% for system_node in systems %}
|
||||||
<tr class="table-primary">
|
<tr class="table-primary toggle-row" data-toggle="system-{{ system_node.system.id }}">
|
||||||
<th colspan="7">Система: {{ system_node.system.name }}</th>
|
<th colspan="8"><span class="toggle-icon">▼</span> Система: {{ system_node.system.name }}</th>
|
||||||
<th class="text-end">{{ system_node.total|money(project.currency) }}</th>
|
<th class="text-end money-value">{{ system_node.total|money(project.currency) }}</th>
|
||||||
</tr>
|
</tr>
|
||||||
{% for section_node in system_node.sections %}
|
{% for section_node in system_node.sections %}
|
||||||
<tr class="table-success">
|
<tr class="table-success toggle-row" data-toggle="section-{{ section_node.section.id }}" data-parent="system-{{ system_node.system.id }}">
|
||||||
<th colspan="7">Раздел: {{ section_node.section.name }}</th>
|
<th colspan="8"><span class="toggle-icon">▼</span> Раздел: {{ section_node.section.name }}</th>
|
||||||
<th class="text-end">{{ section_node.total|money(project.currency) }}</th>
|
<th class="text-end money-value">{{ section_node.total|money(project.currency) }}</th>
|
||||||
</tr>
|
</tr>
|
||||||
{% for item in section_node["items"] %}
|
{% for item in section_node["items"] %}
|
||||||
<tr>
|
{% set done = completed_by_item.get(item.id, 0) %}
|
||||||
|
{% set planned = item.quantity if item.quantity is not none else 0 %}
|
||||||
|
{% set pct = (done / planned * 100) if planned else 0 %}
|
||||||
|
{% if pct == 0 %}{% set state = 'not-started' %}{% elif pct < 100 %}{% set state = 'in-progress' %}{% elif pct == 100 %}{% set state = 'completed' %}{% else %}{% set state = 'overspend' %}{% endif %}
|
||||||
|
<tr data-parent="section-{{ section_node.section.id }}" data-progress-state="{{ state }}">
|
||||||
<td>{{ item.source_number or '' }}</td>
|
<td>{{ item.source_number or '' }}</td>
|
||||||
<td>{{ item.name }}</td>
|
<td>{{ item.name }}</td>
|
||||||
<td>{{ item.model or '' }}</td>
|
<td>{{ item.model or '' }}</td>
|
||||||
<td>{{ item.manufacturer or '' }}</td>
|
<td>{{ item.manufacturer or '' }}</td>
|
||||||
<td>{{ item.unit or '' }}</td>
|
<td>{{ item.unit or '' }}</td>
|
||||||
<td class="text-end">{{ item.quantity if item.quantity is not none else '' }}</td>
|
<td class="text-end">{{ item.quantity if item.quantity is not none else '' }}</td>
|
||||||
<td class="text-end">{{ item.unit_price|money(project.currency) if item.unit_price is not none else '' }}</td>
|
<td class="text-end money-value">{{ item.unit_price|money(project.currency) if item.unit_price is not none else '' }}</td>
|
||||||
<td class="text-end">{{ item.amount|money(project.currency) if item.amount is not none else '' }}</td>
|
<td class="text-end money-value">{{ item.amount|money(project.currency) if item.amount is not none else '' }}</td>
|
||||||
|
<td>
|
||||||
|
{% if planned %}
|
||||||
|
<div class="microstat-label text-muted mb-1">Выполнено: {{ done|round(2) }} / {{ planned }}</div>
|
||||||
|
<div class="progress microstat-bar">
|
||||||
|
{% if state == 'not-started' %}
|
||||||
|
<div class="progress-bar bg-secondary" style="width: 100%"></div>
|
||||||
|
{% elif state == 'in-progress' %}
|
||||||
|
<div class="progress-bar bg-primary" style="width: {{ pct }}%"></div>
|
||||||
|
{% elif state == 'completed' %}
|
||||||
|
<div class="progress-bar bg-success" style="width: 100%"></div>
|
||||||
|
{% else %}
|
||||||
|
<div class="progress-bar bg-danger" style="width: 100%"></div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan="8" class="text-center text-muted py-4">В документе нет рабочих позиций.</td></tr>
|
<tr><td colspan="9" class="text-center text-muted py-4">В документе нет рабочих позиций.</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<tr class="table-dark fw-bold">
|
<tr class="table-dark fw-bold">
|
||||||
<td colspan="7">Итого по ведомости</td>
|
<td colspan="8">Итого по ведомости</td>
|
||||||
<td class="text-end">{{ total|money(project.currency) }}</td>
|
<td class="text-end money-value">{{ total|money(project.currency) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -71,5 +182,78 @@
|
|||||||
<div class="alert alert-warning mt-3">В документе есть {{ unassigned_items|length }} позиций без полной привязки к системе и разделу.</div>
|
<div class="alert alert-warning mt-3">В документе есть {{ unassigned_items|length }} позиций без полной привязки к системе и разделу.</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</main>
|
</main>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var moneyBtn = document.getElementById('toggleMoney');
|
||||||
|
if (moneyBtn) moneyBtn.addEventListener('click', function() {
|
||||||
|
document.body.classList.toggle('money-hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
function toggleGroup(id, collapsed) {
|
||||||
|
document.querySelectorAll('[data-parent="' + id + '"]').forEach(function(el) {
|
||||||
|
el.style.display = collapsed ? 'none' : '';
|
||||||
|
if (el.dataset.toggle) toggleGroup(el.dataset.toggle, collapsed);
|
||||||
|
});
|
||||||
|
var header = document.querySelector('[data-toggle="' + id + '"]');
|
||||||
|
if (header) header.classList.toggle('collapsed', collapsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||||
|
row.addEventListener('click', function() {
|
||||||
|
var id = row.dataset.toggle;
|
||||||
|
if (!id) return;
|
||||||
|
var isCollapsed = row.classList.contains('collapsed');
|
||||||
|
toggleGroup(id, !isCollapsed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('expandAll').addEventListener('click', function() {
|
||||||
|
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||||
|
if (row.dataset.toggle) toggleGroup(row.dataset.toggle, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
document.getElementById('collapseAll').addEventListener('click', function() {
|
||||||
|
document.querySelectorAll('.toggle-row').forEach(function(row) {
|
||||||
|
if (row.dataset.toggle) toggleGroup(row.dataset.toggle, true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Progress filter (CSS classes, independent of collapse inline display) ---
|
||||||
|
function applyFilter(state) {
|
||||||
|
// 1. Tag items
|
||||||
|
document.querySelectorAll('tr[data-progress-state]').forEach(function(row) {
|
||||||
|
row.classList.toggle('filtered-out', state !== 'all' && row.dataset.progressState !== state);
|
||||||
|
});
|
||||||
|
// 2. Hide sections with no matching items
|
||||||
|
document.querySelectorAll('[data-toggle^="section-"]').forEach(function(secHeader) {
|
||||||
|
var secId = secHeader.dataset.toggle;
|
||||||
|
var items = document.querySelectorAll('tr[data-parent="' + secId + '"][data-progress-state]');
|
||||||
|
var hasMatch = false;
|
||||||
|
items.forEach(function(el) { if (!el.classList.contains('filtered-out')) hasMatch = true; });
|
||||||
|
secHeader.classList.toggle('group-hidden', !hasMatch);
|
||||||
|
});
|
||||||
|
// 3. Hide systems with no visible sections
|
||||||
|
document.querySelectorAll('[data-toggle^="system-"]').forEach(function(sysHeader) {
|
||||||
|
var sysId = sysHeader.dataset.toggle;
|
||||||
|
var sections = document.querySelectorAll('tr[data-parent="' + sysId + '"][data-toggle^="section-"]');
|
||||||
|
var hasVisible = false;
|
||||||
|
sections.forEach(function(el) { if (!el.classList.contains('group-hidden')) hasVisible = true; });
|
||||||
|
sysHeader.classList.toggle('group-hidden', !hasVisible);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('#progressFilter .filter-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() {
|
||||||
|
document.querySelectorAll('#progressFilter .filter-btn').forEach(function(b) {
|
||||||
|
b.classList.remove('active', 'btn-primary');
|
||||||
|
b.classList.add('btn-outline-secondary');
|
||||||
|
});
|
||||||
|
btn.classList.add('active', 'btn-primary');
|
||||||
|
btn.classList.remove('btn-outline-secondary');
|
||||||
|
applyFilter(btn.dataset.filter);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
<div class="list-group shadow-sm">
|
<div class="list-group shadow-sm">
|
||||||
{% for document in documents %}
|
{% for document in documents %}
|
||||||
<a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center gap-3" href="/boq/{{ project.id }}/documents/{{ document.id }}">
|
<a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center gap-3" href="/boq/{{ project.id }}/documents/{{ document.id }}">
|
||||||
<span><strong>{{ document.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</strong><br><small class="text-muted">{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}</small></span>
|
<span><strong>{{ document.display_name }}</strong><br><small class="text-muted">{{ document.source_file or 'Источник не указан' }} · {{ document.created_at.strftime('%d.%m.%Y %H:%M') if document.created_at else 'Дата не указана' }}</small></span>
|
||||||
<span class="btn btn-sm btn-outline-primary">Открыть</span>
|
<span class="btn btn-sm btn-outline-primary">Открыть</span>
|
||||||
</a>
|
</a>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|||||||
@@ -4,6 +4,13 @@
|
|||||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>{{ 'Редактирование' if report else 'Новый' }} Daily Report — {{ project.name }}</title>
|
<title>{{ 'Редактирование' if report else 'Новый' }} Daily Report — {{ project.name }}</title>
|
||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
#picker-scroll { max-height: 420px; overflow-x: auto; overflow-y: auto; }
|
||||||
|
.item-action { white-space: nowrap; }
|
||||||
|
.table-compact { width: 100%; table-layout: fixed; }
|
||||||
|
.table-compact th, .table-compact td { padding-left: .35rem; padding-right: .35rem; overflow-wrap: anywhere; }
|
||||||
|
.sel-group td { background: #f8f9fa; }
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-light">
|
<body class="bg-light">
|
||||||
<main class="container py-4">
|
<main class="container py-4">
|
||||||
@@ -11,68 +18,293 @@
|
|||||||
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
||||||
{% for error in errors %}<div class="alert alert-danger">{{ error }}</div>{% endfor %}
|
{% for error in errors %}<div class="alert alert-danger">{{ error }}</div>{% endfor %}
|
||||||
|
|
||||||
<form method="get" action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports/new{% endif %}" class="card card-body mb-3">
|
<form method="post" enctype="multipart/form-data"
|
||||||
<label for="system-picker" class="form-label">Система</label>
|
action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports{% endif %}">
|
||||||
<div class="d-flex gap-2"><select id="system-picker" name="system_id" class="form-select" required>
|
<input type="hidden" name="system_id" id="hidden-system-id" value="{{ selected_system.id if selected_system else ('unclassified' if unclassified_selected else '') }}">
|
||||||
<option value="">Выберите систему</option>
|
|
||||||
{% for system in systems %}<option value="{{ system.id }}" {% if selected_system and selected_system.id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}
|
|
||||||
{% if has_unclassified_items %}<option value="unclassified" {% if unclassified_selected %}selected{% endif %}>Проектные позиции без системы</option>{% endif %}
|
|
||||||
</select><button class="btn btn-outline-primary" type="submit">Показать позиции</button></div>
|
|
||||||
{% if report %}<div class="form-text">При смене системы сначала нажмите «Показать позиции»; несохранённые изменения формы будут сброшены.</div>{% endif %}
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{% if selected_system or unclassified_selected %}
|
|
||||||
<form method="post" action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports{% endif %}">
|
|
||||||
<input type="hidden" name="system_id" value="{{ selected_system.id if selected_system else 'unclassified' }}">
|
|
||||||
<div class="card card-body mb-3">
|
<div class="card card-body mb-3">
|
||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<div class="col-md-4"><label for="report-date" class="form-label">Дата отчёта</label><input id="report-date" class="form-control" type="date" name="report_date" required value="{{ report.report_date.isoformat() if report else '' }}"></div>
|
<div class="col-md-4"><label for="report-date" class="form-label">Дата отчёта</label><input id="report-date" class="form-control" type="date" name="report_date" required value="{{ form_values.get('report_date', report.report_date.isoformat() if report else '') }}"></div>
|
||||||
<div class="col-md-8"><label for="notes" class="form-label">Комментарий</label><input id="notes" class="form-control" name="notes" value="{{ report.notes if report and report.notes else '' }}"></div>
|
<div class="col-md-8"><label for="notes" class="form-label">Комментарий</label><input id="notes" class="form-control" name="notes" value="{{ form_values.get('notes', report.notes if report and report.notes else '') }}"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
|
||||||
<div class="card-header"><strong>{{ selected_system.name if selected_system else 'Проектные позиции без системы' }}</strong> — укажите фактическое количество хотя бы для одной позиции</div>
|
<!-- ============ Зона 1: подбор позиций ============ -->
|
||||||
<div class="p-3 border-bottom">
|
<div class="card mb-3" id="picker-zone">
|
||||||
<label class="form-label" for="position-search">Поиск позиций</label>
|
<div class="card-header"><strong>Подбор позиций</strong></div>
|
||||||
<input id="position-search" class="form-control" type="search" autocomplete="off" placeholder="Номер, наименование, модель или производитель">
|
<div class="card-body py-2">
|
||||||
<div id="position-search-empty" class="form-text text-muted" hidden>Совпадений нет.</div>
|
<div class="row g-2">
|
||||||
|
<div class="col-12 col-md-4">
|
||||||
|
<label for="system-picker" class="form-label">Система</label>
|
||||||
|
<select id="system-picker" class="form-select">
|
||||||
|
<option value="">Выберите систему</option>
|
||||||
|
{% for system in systems %}<option value="{{ system.id }}" {% if selected_system and selected_system.id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}
|
||||||
|
{% if has_unclassified_items %}<option value="unclassified" {% if unclassified_selected %}selected{% endif %}>Проектные позиции без системы</option>{% endif %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-md-8">
|
||||||
|
<label for="position-search" class="form-label">Поиск</label>
|
||||||
|
<input id="position-search" class="form-control" type="search" autocomplete="off" placeholder="Номер, наименование, модель или производитель">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-text">Выберите систему, при необходимости введите количество и нажмите «Добавить». Позиции разных систем можно добавлять в один отчёт — уже добавленные при смене системы сохраняются.</div>
|
||||||
|
</div>
|
||||||
|
<div id="picker-scroll" class="table-responsive">
|
||||||
|
<table class="table table-sm table-hover align-middle mb-0 table-compact">
|
||||||
|
<thead class="table-light"><tr><th class="d-none d-md-table-cell">Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th style="width: 118px">Количество</th><th class="text-end" style="width: 104px" aria-label="Действие"></th></tr></thead>
|
||||||
|
<tbody id="picker-body">
|
||||||
|
{% for row in rows %}{% if row.current_quantity is none %}
|
||||||
|
<tr class="position-row" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}" data-system="{{ row.item.system_id if row.item.system_id is not none else 'unclassified' }}" data-system-name="{{ row.item.system.name if row.item.system else 'Без системы' }}" data-section="{{ row.item.section.name if row.item.section else '—' }}" {% if not row.in_selection %}hidden{% endif %}>
|
||||||
|
<td class="d-none d-md-table-cell">{{ row.item.section.name if row.item.section else '—' }}</td>
|
||||||
|
<td>{{ row.item.source_number or '' }}</td>
|
||||||
|
<td>{{ row.item.name }}<div class="small text-muted">План: {{ row.planned_quantity if row.planned_quantity is not none else '—' }} · Накоплено: {{ row.accumulated }}</div></td>
|
||||||
|
<td>{{ row.item.unit or '' }}</td>
|
||||||
|
<td><input class="form-control form-control-sm picker-qty" type="number" min="0" step="0.0001" name="quantity_{{ row.item.id }}" value="" data-item-id="{{ row.item.id }}" aria-label="Выполнено: {{ row.item.name }}"></td>
|
||||||
|
<td class="text-end"><button type="button" class="btn btn-sm btn-outline-success item-action" data-action="add">Добавить</button></td>
|
||||||
|
</tr>
|
||||||
|
{% endif %}{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div id="picker-empty" class="card-footer text-muted" hidden>Совпадений нет.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ============ Зона 2: добавленные позиции ============ -->
|
||||||
|
<div class="card mb-3" id="selected-zone">
|
||||||
|
<div class="card-header"><strong>Добавленные позиции</strong> — укажите фактическое количество хотя бы для одной</div>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm align-middle mb-0">
|
||||||
|
<thead class="table-light"><tr><th class="d-none d-md-table-cell">Раздел</th><th>№</th><th>Наименование</th><th>Ед.</th><th style="width: 118px">Количество</th><th class="text-end" style="width: 96px" aria-label="Действие"></th></tr></thead>
|
||||||
|
<tbody id="selected-body">
|
||||||
|
{% for row in rows %}{% if row.current_quantity is not none %}
|
||||||
|
<tr class="position-row" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}" data-system="{{ row.item.system_id if row.item.system_id is not none else 'unclassified' }}" data-system-name="{{ row.item.system.name if row.item.system else 'Без системы' }}" data-section="{{ row.item.section.name if row.item.section else '—' }}">
|
||||||
|
<td class="d-none d-md-table-cell">{{ row.item.section.name if row.item.section else '—' }}</td>
|
||||||
|
<td>{{ row.item.source_number or '' }}</td>
|
||||||
|
<td>{{ row.item.name }}</td>
|
||||||
|
<td>{{ row.item.unit or '' }}</td>
|
||||||
|
<td><input class="form-control form-control-sm" type="number" min="0" step="0.0001" name="quantity_{{ row.item.id }}" value="{{ row.current_quantity }}" aria-label="Выполнено: {{ row.item.name }}"></td>
|
||||||
|
<td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger item-action" data-action="remove">Удалить</button></td>
|
||||||
|
</tr>
|
||||||
|
{% endif %}{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div id="selected-empty" class="card-footer text-muted" hidden>Пока ничего не добавлено.</div>
|
||||||
|
|
||||||
|
<!-- ============ Фотоотчёт ============ -->
|
||||||
|
<div class="card-footer border-top" id="photo-zone">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||||
|
<strong>Фотоотчёт</strong>
|
||||||
|
<span class="text-muted small">до {{ photo_limit }} фото · до {{ (photo_max_bytes / 1024 / 1024)|round(0)|int }} МБ · {{ photo_formats }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-text mb-2">Фото привязываются к отчёту целиком. Можно выбрать файлы на компьютере или телефоне — из галереи или камерой, если это поддерживает устройство.</div>
|
||||||
|
|
||||||
|
{% if existing_photos %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<div class="form-label">Сохранённые фотографии</div>
|
||||||
|
<div class="row g-2" id="existing-photos">
|
||||||
|
{% for photo in existing_photos %}
|
||||||
|
<div class="col-4 col-md-2">
|
||||||
|
<div class="border rounded p-1">
|
||||||
|
<img class="img-fluid rounded w-100"
|
||||||
|
style="aspect-ratio: 4 / 3; object-fit: cover;"
|
||||||
|
src="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
alt="{{ photo.original_name or ('Фото ' ~ photo.id) }}">
|
||||||
|
<div class="form-check mt-1">
|
||||||
|
<input class="form-check-input" type="checkbox"
|
||||||
|
name="delete_photo_{{ photo.id }}" value="1"
|
||||||
|
id="delete_photo_{{ photo.id }}">
|
||||||
|
<label class="form-check-label small text-danger"
|
||||||
|
for="delete_photo_{{ photo.id }}">Удалить</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<div class="form-text">Существующие фото удаляются только по явной отметке «Удалить» и сохранению формы.</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="mb-2">
|
||||||
|
<label for="photo-input" class="form-label">Добавить фотографии</label>
|
||||||
|
<input class="form-control" type="file" id="photo-input" name="files"
|
||||||
|
accept="image/jpeg,image/png,image/webp,image/*" multiple>
|
||||||
|
</div>
|
||||||
|
<div class="row g-2" id="photo-preview"></div>
|
||||||
|
<div id="photo-empty" class="form-text">Новые файлы будут показаны миниатюрами здесь.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card-footer d-flex justify-content-between">
|
||||||
|
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a>
|
||||||
|
<button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="table-responsive"><table class="table table-sm table-hover align-middle mb-0">
|
|
||||||
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">Накоплено до отчёта</th><th style="width: 180px">Выполнено за дату</th></tr></thead>
|
|
||||||
<tbody>
|
|
||||||
{% for row in rows %}
|
|
||||||
<tr class="position-row {% if row.over_plan %}table-warning{% endif %}" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}">
|
|
||||||
<td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td>
|
|
||||||
<td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td>
|
|
||||||
<td><input class="form-control form-control-sm" type="number" min="0" step="0.0001" name="quantity_{{ row.item.id }}" value="{{ row.current_quantity if row.current_quantity is not none else '' }}" aria-label="Выполнено: {{ row.item.name }}"></td>
|
|
||||||
</tr>
|
|
||||||
{% else %}<tr><td colspan="7" class="text-center text-muted py-4">В этой системе нет рабочих позиций ведомости.</td></tr>{% endfor %}
|
|
||||||
</tbody>
|
|
||||||
</table></div>
|
|
||||||
<div class="card-footer d-flex justify-content-between"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a><button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button></div>
|
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(() => {
|
(() => {
|
||||||
|
const pickerBody = document.getElementById('picker-body');
|
||||||
|
const selectedBody = document.getElementById('selected-body');
|
||||||
|
const systemPicker = document.getElementById('system-picker');
|
||||||
const search = document.getElementById('position-search');
|
const search = document.getElementById('position-search');
|
||||||
if (!search) return;
|
const pickerEmpty = document.getElementById('picker-empty');
|
||||||
const rows = [...document.querySelectorAll('.position-row')];
|
const selectedEmpty = document.getElementById('selected-empty');
|
||||||
const empty = document.getElementById('position-search-empty');
|
const hiddenSystem = document.getElementById('hidden-system-id');
|
||||||
|
if (!pickerBody || !selectedBody) return;
|
||||||
|
|
||||||
const normalize = value => (value || '').toLocaleLowerCase('ru-RU').trim();
|
const normalize = value => (value || '').toLocaleLowerCase('ru-RU').trim();
|
||||||
search.addEventListener('input', () => {
|
|
||||||
const query = normalize(search.value);
|
const applyPickerFilter = () => {
|
||||||
|
const selected = systemPicker ? systemPicker.value : '';
|
||||||
|
const query = normalize(search ? search.value : '');
|
||||||
let visible = 0;
|
let visible = 0;
|
||||||
for (const row of rows) {
|
for (const row of pickerBody.querySelectorAll('tr.position-row')) {
|
||||||
|
const inSystem = selected !== '' && row.dataset.system === selected;
|
||||||
const haystack = normalize(['number', 'name', 'model', 'manufacturer']
|
const haystack = normalize(['number', 'name', 'model', 'manufacturer']
|
||||||
.map(key => row.dataset[key]).join(' '));
|
.map(key => row.dataset[key]).join(' '));
|
||||||
row.hidden = !haystack.includes(query);
|
const show = inSystem && haystack.includes(query);
|
||||||
if (!row.hidden) visible++;
|
row.hidden = !show;
|
||||||
|
if (show) visible++;
|
||||||
}
|
}
|
||||||
empty.hidden = visible !== 0;
|
if (pickerEmpty) pickerEmpty.hidden = visible !== 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setAddedState = (row, added) => {
|
||||||
|
const input = row.querySelector('input[name^="quantity_"]');
|
||||||
|
const btn = row.querySelector('.item-action');
|
||||||
|
if (input) {
|
||||||
|
// DOC-C11: the same input travels with the row, so the typed
|
||||||
|
// quantity survives add / remove / filter / system switch.
|
||||||
|
input.disabled = false;
|
||||||
|
}
|
||||||
|
if (btn) {
|
||||||
|
btn.dataset.action = added ? 'remove' : 'add';
|
||||||
|
btn.textContent = added ? 'Удалить' : 'Добавить';
|
||||||
|
btn.classList.toggle('btn-outline-success', !added);
|
||||||
|
btn.classList.toggle('btn-outline-danger', added);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rebuildSelected = () => {
|
||||||
|
const rows = [...selectedBody.querySelectorAll('tr.position-row')];
|
||||||
|
rows.sort((a, b) => {
|
||||||
|
const bySystem = (a.dataset.systemName || '').localeCompare(b.dataset.systemName || '', 'ru');
|
||||||
|
if (bySystem !== 0) return bySystem;
|
||||||
|
return (a.dataset.number || '').localeCompare(b.dataset.number || '', 'ru', { numeric: true });
|
||||||
|
});
|
||||||
|
selectedBody.textContent = '';
|
||||||
|
let lastSystem = null;
|
||||||
|
for (const row of rows) {
|
||||||
|
const systemName = row.dataset.systemName || 'Без системы';
|
||||||
|
if (systemName !== lastSystem) {
|
||||||
|
const group = document.createElement('tr');
|
||||||
|
group.className = 'sel-group';
|
||||||
|
const cell = document.createElement('td');
|
||||||
|
cell.colSpan = 6;
|
||||||
|
const strong = document.createElement('strong');
|
||||||
|
strong.textContent = systemName;
|
||||||
|
cell.appendChild(strong);
|
||||||
|
group.appendChild(cell);
|
||||||
|
selectedBody.appendChild(group);
|
||||||
|
lastSystem = systemName;
|
||||||
|
}
|
||||||
|
row.hidden = false;
|
||||||
|
selectedBody.appendChild(row);
|
||||||
|
}
|
||||||
|
if (selectedEmpty) selectedEmpty.hidden = rows.length !== 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveToSelected = row => {
|
||||||
|
setAddedState(row, true);
|
||||||
|
selectedBody.appendChild(row);
|
||||||
|
rebuildSelected();
|
||||||
|
applyPickerFilter();
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveToPicker = row => {
|
||||||
|
setAddedState(row, false);
|
||||||
|
pickerBody.appendChild(row);
|
||||||
|
rebuildSelected();
|
||||||
|
applyPickerFilter();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('click', event => {
|
||||||
|
const btn = event.target.closest('.item-action');
|
||||||
|
if (!btn) return;
|
||||||
|
const row = btn.closest('tr.position-row');
|
||||||
|
if (!row) return;
|
||||||
|
if (btn.dataset.action === 'add') moveToSelected(row);
|
||||||
|
else moveToPicker(row);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// DOC-C11: quantities typed in the picker but never submitted with
|
||||||
|
// "Добавить" must not reach POST / become Daily Report facts.
|
||||||
|
const form = pickerBody.closest('form');
|
||||||
|
if (form) {
|
||||||
|
form.addEventListener('submit', () => {
|
||||||
|
for (const row of pickerBody.querySelectorAll('tr.position-row')) {
|
||||||
|
const input = row.querySelector('input[name^="quantity_"]');
|
||||||
|
if (input) input.disabled = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (systemPicker) {
|
||||||
|
systemPicker.addEventListener('change', () => {
|
||||||
|
if (hiddenSystem) hiddenSystem.value = systemPicker.value;
|
||||||
|
applyPickerFilter();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (search) search.addEventListener('input', applyPickerFilter);
|
||||||
|
|
||||||
|
rebuildSelected();
|
||||||
|
applyPickerFilter();
|
||||||
|
|
||||||
|
// ---------- Фотоотчёт: миниатюры до сохранения ----------
|
||||||
|
const photoInput = document.getElementById('photo-input');
|
||||||
|
const photoPreview = document.getElementById('photo-preview');
|
||||||
|
const photoEmpty = document.getElementById('photo-empty');
|
||||||
|
if (photoInput && photoPreview) {
|
||||||
|
const renderPhotoPreview = () => {
|
||||||
|
photoPreview.textContent = '';
|
||||||
|
const files = [...photoInput.files];
|
||||||
|
if (photoEmpty) photoEmpty.hidden = files.length !== 0;
|
||||||
|
files.forEach((file, index) => {
|
||||||
|
const col = document.createElement('div');
|
||||||
|
col.className = 'col-4 col-md-2';
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.className = 'border rounded p-1';
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.className = 'img-fluid rounded w-100';
|
||||||
|
img.style.aspectRatio = '4 / 3';
|
||||||
|
img.style.objectFit = 'cover';
|
||||||
|
img.alt = file.name;
|
||||||
|
try {
|
||||||
|
img.src = URL.createObjectURL(file);
|
||||||
|
img.onload = () => URL.revokeObjectURL(img.src);
|
||||||
|
} catch { /* preview is best-effort */ }
|
||||||
|
const name = document.createElement('div');
|
||||||
|
name.className = 'small text-muted text-truncate';
|
||||||
|
name.textContent = file.name;
|
||||||
|
name.title = file.name;
|
||||||
|
const remove = document.createElement('button');
|
||||||
|
remove.type = 'button';
|
||||||
|
remove.className = 'btn btn-sm btn-outline-danger w-100 mt-1';
|
||||||
|
remove.textContent = 'Убрать';
|
||||||
|
remove.addEventListener('click', () => {
|
||||||
|
const dt = new DataTransfer();
|
||||||
|
[...photoInput.files].forEach((f, i) => { if (i !== index) dt.items.add(f); });
|
||||||
|
photoInput.files = dt.files;
|
||||||
|
renderPhotoPreview();
|
||||||
|
});
|
||||||
|
box.append(img, name, remove);
|
||||||
|
col.appendChild(box);
|
||||||
|
photoPreview.appendChild(col);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
photoInput.addEventListener('change', renderPhotoPreview);
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
{% endif %}
|
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -8,14 +8,75 @@
|
|||||||
<body class="bg-light">
|
<body class="bg-light">
|
||||||
<main class="container py-4">
|
<main class="container py-4">
|
||||||
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/daily-reports">Daily Reports</a></li><li class="breadcrumb-item active">{{ report.report_date.strftime('%d.%m.%Y') }}</li></ol></nav>
|
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/daily-reports">Daily Reports</a></li><li class="breadcrumb-item active">{{ report.report_date.strftime('%d.%m.%Y') }}</li></ol></nav>
|
||||||
<div class="d-flex justify-content-between align-items-start mb-4"><div><h1>Daily Report</h1><div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name if report.system else 'Проектные позиции без системы' }}</div>{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}</div><a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a></div>
|
<div class="d-flex justify-content-between align-items-start mb-4 gap-3 flex-wrap">
|
||||||
|
<div>
|
||||||
|
<h1>Daily Report</h1>
|
||||||
|
<div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ system_names|join(', ') if system_names else 'Проектные позиции без системы' }}</div>
|
||||||
|
{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="d-flex gap-2">
|
||||||
|
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a>
|
||||||
|
{% if can_delete_report %}
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/daily-reports/{{ report.id }}/delete" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-danger"
|
||||||
|
onclick="return confirm('Удалить Daily Report? Действие необратимо.')">Удалить отчёт</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<button type="button" class="btn btn-outline-danger" disabled
|
||||||
|
title="{{ delete_blocked_reason }}">Удалить отчёт</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% if not can_delete_report %}
|
||||||
|
<div class="alert alert-warning" role="alert">{{ delete_blocked_reason }}</div>
|
||||||
|
{% endif %}
|
||||||
{% if warnings %}<div class="alert alert-warning"><strong>Превышен план по {{ warnings|length }} позициям.</strong> Фактическое выполнение сохранено.</div>{% endif %}
|
{% if warnings %}<div class="alert alert-warning"><strong>Превышен план по {{ warnings|length }} позициям.</strong> Фактическое выполнение сохранено.</div>{% endif %}
|
||||||
<div class="card"><div class="table-responsive"><table class="table table-hover align-middle mb-0">
|
<div class="card"><div class="table-responsive"><table class="table table-hover align-middle mb-0">
|
||||||
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">Накоплено до отчёта</th><th class="text-end">В этом отчёте</th><th class="text-end">Накоплено</th></tr></thead>
|
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">В этом отчёте</th><th class="text-end">Закрыто КС-2</th><th class="text-end">Доступно</th></tr></thead>
|
||||||
<tbody>{% for row in rows %}
|
<tbody>{% for row in rows %}
|
||||||
<tr class="{% if row.over_plan %}table-warning{% endif %}"><td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td><td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td><td class="text-end">{{ row.current_quantity }}</td><td class="text-end">{{ row.accumulated + row.current_quantity }}</td></tr>
|
<tr class="{% if row.over_plan %}table-warning{% endif %}">
|
||||||
|
<td>{{ row.item.section.name if row.item.section else '—' }}<div class="small text-muted">{{ row.item.system.name if row.item.system else 'Без системы' }}</div></td>
|
||||||
|
<td>{{ row.item.source_number or '' }}</td>
|
||||||
|
<td>{{ row.item.name }}</td>
|
||||||
|
<td>{{ row.item.unit or '' }}</td>
|
||||||
|
<td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td>
|
||||||
|
<td class="text-end">{{ row.current_quantity }}</td>
|
||||||
|
<td class="text-end">{{ row.closed_quantity }}</td>
|
||||||
|
<td class="text-end">{{ row.available_quantity }}</td>
|
||||||
|
</tr>
|
||||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
||||||
</table></div></div>
|
</table></div></div>
|
||||||
|
|
||||||
|
<section class="card mt-4" id="photo-section">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<strong>Фотоотчёт</strong>
|
||||||
|
<span class="text-muted small">{{ photos|length }} фото</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if photos %}
|
||||||
|
<div class="row g-2">
|
||||||
|
{% for photo in photos %}
|
||||||
|
<div class="col-6 col-md-3 col-lg-2">
|
||||||
|
<a href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
target="_blank" rel="noopener" class="d-block">
|
||||||
|
<img class="img-fluid rounded border w-100"
|
||||||
|
style="aspect-ratio: 4 / 3; object-fit: cover;"
|
||||||
|
src="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
alt="{{ photo.original_name or ('Фото ' ~ photo.id) }}"
|
||||||
|
loading="lazy">
|
||||||
|
</a>
|
||||||
|
<div class="small text-muted text-truncate" title="{{ photo.original_name or '' }}">
|
||||||
|
{{ photo.original_name or ('Фото ' ~ photo.id) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="text-muted">Фотографии не прикреплены. Их можно добавить при редактировании отчёта.</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Сброс базы данных — Work Volume Tracker</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<main class="container py-4">
|
||||||
|
<nav class="mb-3"><ol class="breadcrumb">
|
||||||
|
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||||
|
<li class="breadcrumb-item active">Сброс базы данных</li>
|
||||||
|
</ol></nav>
|
||||||
|
|
||||||
|
<h1 class="h2 mb-3">Сброс базы данных</h1>
|
||||||
|
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
<strong>ВНИМАНИЕ!</strong>
|
||||||
|
Будут удалены ВСЕ проекты, ведомости, ДС, Daily Reports, КС-2, КС-3, платежи и связанная история.
|
||||||
|
Действие необратимо. Схема базы данных и история миграций сохранятся.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if error %}<div class="alert alert-warning" role="alert">{{ error }}</div>{% endif %}
|
||||||
|
|
||||||
|
<div class="card border-0 shadow-sm mb-3">
|
||||||
|
<div class="card-header bg-white"><h2 class="h5 mb-0">Текущие данные (preview)</h2></div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted small">GET ничего не удаляет. Эти данные будут удалены после подтверждения.</p>
|
||||||
|
<dl class="row mb-0">
|
||||||
|
<dt class="col-sm-6">Проектов</dt><dd class="col-sm-6">{{ counts.get('projects', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Ведомостей</dt><dd class="col-sm-6">{{ counts.get('boq_documents', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Систем</dt><dd class="col-sm-6">{{ counts.get('systems', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Разделов</dt><dd class="col-sm-6">{{ counts.get('sections', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Позиций</dt><dd class="col-sm-6">{{ counts.get('work_items', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">ДС</dt><dd class="col-sm-6">{{ counts.get('agreements', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Позиций ДС</dt><dd class="col-sm-6">{{ counts.get('agreement_items', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Daily Reports</dt><dd class="col-sm-6">{{ counts.get('daily_reports', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Позиций Daily Reports</dt><dd class="col-sm-6">{{ counts.get('daily_report_items', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">КС-2</dt><dd class="col-sm-6">{{ counts.get('ks2_documents', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">КС-3</dt><dd class="col-sm-6">{{ counts.get('ks3_documents', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Платежей</dt><dd class="col-sm-6">{{ counts.get('payments', 0) }}</dd>
|
||||||
|
<dt class="col-sm-6">Записей рабочего журнала</dt><dd class="col-sm-6">{{ counts.get('work_journal_entries', 0) }}</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card border-0 shadow-sm">
|
||||||
|
<div class="card-body">
|
||||||
|
<form method="post" action="/projects/settings/database-reset">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="confirmation">
|
||||||
|
Для подтверждения введите:<br>
|
||||||
|
<code>УДАЛИТЬ ВСЕ ДАННЫЕ</code>
|
||||||
|
</label>
|
||||||
|
<input class="form-control" type="text" id="confirmation" name="confirmation"
|
||||||
|
autocomplete="off" spellcheck="false" required>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-danger">Удалить все данные</button>
|
||||||
|
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -11,49 +11,175 @@
|
|||||||
.system-progress-table .progress-cell { min-width: 14rem; }
|
.system-progress-table .progress-cell { min-width: 14rem; }
|
||||||
.system-progress-table .progress-summary { flex-wrap: nowrap; gap: .5rem; }
|
.system-progress-table .progress-summary { flex-wrap: nowrap; gap: .5rem; }
|
||||||
.system-progress-table .progress-summary > * { white-space: nowrap; }
|
.system-progress-table .progress-summary > * { white-space: nowrap; }
|
||||||
|
.money-value { transition: filter 0.15s; white-space: nowrap; }
|
||||||
|
.money-hidden .money-value { filter: blur(6px); user-select: none; pointer-events: none; }
|
||||||
|
/* KPI collapse */
|
||||||
|
.kpi-toggle { cursor: pointer; list-style: none; }
|
||||||
|
.kpi-toggle::-webkit-details-marker { display: none; }
|
||||||
|
.kpi-toggle::marker { content: none; }
|
||||||
|
.kpi-toggle .kpi-chevron { transition: transform 0.15s; display: inline-block; }
|
||||||
|
details[open] > .kpi-toggle .kpi-chevron { transform: rotate(180deg); }
|
||||||
|
.kpi-toggle:hover { background-color: rgba(0,0,0,0.03); }
|
||||||
|
/*
|
||||||
|
* Document navigation: one horizontal row, no horizontal scroll.
|
||||||
|
* Buttons never wrap to a second row; long labels wrap inside the button.
|
||||||
|
* Equal height via stretch + flex centering of button content.
|
||||||
|
*/
|
||||||
|
.doc-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: .5rem;
|
||||||
|
}
|
||||||
|
.doc-nav .btn {
|
||||||
|
flex: 1 1 0;
|
||||||
|
min-width: 0;
|
||||||
|
white-space: normal;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.25;
|
||||||
|
padding-left: .5rem;
|
||||||
|
padding-right: .5rem;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-light">
|
<body class="bg-light money-hidden">
|
||||||
<main class="container-fluid container-xxl py-4">
|
<main class="container-fluid container-xxl py-4">
|
||||||
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item active">{{ project.name }}</li></ol></nav>
|
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item active">{{ project.name }}</li></ol></nav>
|
||||||
|
|
||||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
|
{% if request.query_params.get('imported') %}
|
||||||
<div>
|
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||||
<h1 class="h2 mb-2">{{ project.name }}</h1>
|
Проект «{{ project.name }}» успешно импортирован как новый проект.
|
||||||
<div class="d-flex flex-wrap gap-3 text-secondary">
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
|
||||||
<span>Договор: <strong class="text-dark">{{ project.contract_number or 'не указан' }}</strong></span>
|
</div>
|
||||||
<span>Заказчик: <strong class="text-dark">{{ project.customer or 'не указан' }}</strong></span>
|
{% endif %}
|
||||||
<span>Валюта: <strong class="text-dark">{{ project.currency or 'RUB' }}</strong></span>
|
|
||||||
<span>Период: <strong class="text-dark">{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}</strong></span>
|
<header class="mb-4">
|
||||||
<span>Статус: <span class="badge text-bg-secondary">{{ project.status or 'не указан' }}</span></span>
|
<!-- Block 1: project title -->
|
||||||
</div>
|
<h1 class="h2 mb-2">{{ project.name }}</h1>
|
||||||
{% if base_boq_documents|length == 1 %}<div class="small text-muted mt-2">Ведомость проекта: {{ base_boq_documents[0].name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</div>{% elif base_boq_documents|length > 1 %}<div class="small text-muted mt-2">Ведомостей проекта: {{ base_boq_documents|length }}</div>{% endif %}
|
<!-- Block 2: project actions (under title) -->
|
||||||
</div>
|
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||||
<div class="d-flex flex-wrap gap-2">
|
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Дневной отчёт</a>
|
||||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
|
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
|
||||||
<a class="btn btn-outline-primary" href="/boq/{{ project.id }}">Ведомости</a>
|
|
||||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/agreements">Дополнительные соглашения</a>
|
|
||||||
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/daily-reports">Daily Reports{% if daily_reports_count %} ({{ daily_reports_count }}){% endif %}</a>
|
|
||||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Создать Daily Report</a>
|
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Requisites -->
|
||||||
|
<div class="row g-3 g-md-4 align-items-start mb-2">
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Договор</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.contract_number or '—' }}{% if project.contract_date %} от {{ project.contract_date.strftime('%d.%m.%Y') }}{% endif %}</div>
|
||||||
|
</div>
|
||||||
|
{% if project.contract_amount is not none %}
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Сумма</div>
|
||||||
|
<div class="fw-semibold text-dark money-value">{{ project.contract_amount|money(project.currency) }}</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Заказчик</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.effective_customer_name or '—' }}</div>
|
||||||
|
</div>
|
||||||
|
{% if project.contractor_name %}
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Подрядчик</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.contractor_name }}</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if project.object_name %}
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Объект</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.object_name }}</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Валюта</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.currency or 'RUB' }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Период</div>
|
||||||
|
<div class="fw-semibold text-dark">{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-6 col-sm-4 col-md-auto">
|
||||||
|
<div class="text-muted small mb-1">Статус</div>
|
||||||
|
{% set status = project.status or 'active' %}
|
||||||
|
{% set status_map = {
|
||||||
|
'active': ('Активный', 'success'),
|
||||||
|
'completed': ('Завершён', 'primary'),
|
||||||
|
'on_hold': ('Приостановлен', 'warning'),
|
||||||
|
'archived': ('Архивирован', 'secondary')
|
||||||
|
} %}
|
||||||
|
{% set status_pair = status_map.get(status, (status, 'secondary')) %}
|
||||||
|
<div><span class="badge text-bg-{{ status_pair[1] }}">{{ status_pair[0] }}</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- BOQ document -->
|
||||||
|
{% if base_boq_documents|length == 1 %}<div class="small text-muted mb-3">Ведомость проекта: {{ base_boq_documents[0].display_name }}</div>{% elif base_boq_documents|length > 1 %}<div class="small text-muted mb-3">Ведомостей проекта: {{ base_boq_documents|length }}</div>{% endif %}
|
||||||
|
<!-- Document navigation: single left-aligned row, no h-scroll -->
|
||||||
|
<nav class="doc-nav mb-3" aria-label="Документы проекта">
|
||||||
|
<a class="btn btn-outline-primary" href="/boq/{{ project.id }}">Ведомости{% if base_boq_documents %} ({{ base_boq_documents|length }}){% endif %}</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/agreements">Дополнительные соглашения{% if agreements_count %} ({{ agreements_count }}){% endif %}</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/daily-reports">Daily Reports{% if daily_reports_count %} ({{ daily_reports_count }}){% endif %}</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks2">КС-2{% if ks2_count %} ({{ ks2_count }}){% endif %}</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks3">КС-3{% if ks3_count %} ({{ ks3_count }}){% endif %}</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/ks6a">КС-6а</a>
|
||||||
|
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/payments">Платежи{% if payments_count %} ({{ payments_count }}){% endif %}</a>
|
||||||
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
{% if project.status != 'archived' %}
|
||||||
|
<div class="mb-3 d-flex flex-wrap gap-2">
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/archive" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-outline-warning btn-sm" onclick="return confirm('Архивировать проект? Данные будут сохранены.')">Архивировать</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/delete" class="d-inline" id="delete-project-form">
|
||||||
|
<button type="submit" class="btn btn-outline-danger btn-sm">Удалить проект</button>
|
||||||
|
</form>
|
||||||
|
<a class="btn btn-outline-primary btn-sm" href="/projects/{{ project.id }}/export/project">Экспорт проекта</a>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-warning mb-3 d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
|
<span>Проект архивирован. Данные сохранены, проект не считается активным.</span>
|
||||||
|
<a class="btn btn-outline-primary btn-sm" href="/projects/{{ project.id }}/export/project">Экспорт проекта</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<section class="mt-3" aria-live="polite">
|
<section class="mt-3" aria-live="polite">
|
||||||
{% if over_plan_count %}
|
{% if over_plan_count %}
|
||||||
<div class="alert alert-warning py-2 mb-0">⚠ Проверка плана: {{ over_plan_count }} позиции превышают план · <button type="button" class="btn btn-link p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#planWarningsModal">Подробнее</button></div>
|
<div class="alert alert-warning py-2 mb-0">⚠ Проверка плана: {{ over_plan_count }} позиции превышают план · <button type="button" class="btn btn-link p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#planWarningsModal">Подробнее</button></div>
|
||||||
{% else %}<div class="text-success small py-2">✓ Проверка плана: превышений нет</div>{% endif %}
|
{% else %}<div class="text-success small py-2">✓ Проверка плана: превышений нет</div>{% endif %}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="mb-4" aria-labelledby="kpi-heading">
|
<div class="d-flex justify-content-end align-items-center gap-2 mb-3">
|
||||||
<h2 id="kpi-heading" class="h5 mb-3">План и выполнение</h2>
|
<span class="text-muted small">Финансовые суммы</span>
|
||||||
<div class="row g-3">
|
<button type="button" class="btn btn-outline-secondary btn-sm" id="toggleMoney" title="Показать/скрыть финансовые суммы" aria-label="Показать или скрыть финансовые суммы">👁</button>
|
||||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">по ведомостям проекта</div></div></article></div>
|
</div>
|
||||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнено по Daily Reports</div><div class="fs-3 fw-semibold text-success">{{ performed_cost|money(project.currency) }}</div></div></article></div>
|
|
||||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Остаток</div><div class="fs-3 fw-semibold {% if remaining_cost < 0 %}text-danger{% endif %}">{{ remaining_cost|money(project.currency) }}</div></div></article></div>
|
<details class="mb-4">
|
||||||
|
<summary id="kpi-heading" class="kpi-toggle d-flex justify-content-between align-items-center h5 px-2 py-2 rounded border bg-light">
|
||||||
|
<span>План и выполнение</span>
|
||||||
|
<span class="kpi-chevron text-muted" aria-hidden="true">⌄</span>
|
||||||
|
</summary>
|
||||||
|
<div class="row g-3 mt-1">
|
||||||
|
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold money-value">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">по ведомостям проекта</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнено по Daily Reports</div><div class="fs-3 fw-semibold text-success money-value">{{ performed_cost|money(project.currency) }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Остаток</div><div class="fs-3 fw-semibold money-value {% if remaining_cost < 0 %}text-danger{% endif %}">{{ remaining_cost|money(project.currency) }}</div></div></article></div>
|
||||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнение</div><div class="fs-3 fw-semibold">{{ '%.4f'|format(completion_percent) }}%</div><div class="progress mt-2" role="progressbar" aria-valuenow="{{ '%.4f'|format(completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if completion_percent > 100 else completion_percent }}%"></div></div></div></article></div>
|
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнение</div><div class="fs-3 fw-semibold">{{ '%.4f'|format(completion_percent) }}%</div><div class="progress mt-2" role="progressbar" aria-valuenow="{{ '%.4f'|format(completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if completion_percent > 100 else completion_percent }}%"></div></div></div></article></div>
|
||||||
</div>
|
</div>
|
||||||
{% if not base_boq_documents %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
{% if not base_boq_documents %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
||||||
</section>
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<h2 class="h5 mb-3">Оплата по КС-3</h2>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Всего КС-3</div><div class="fs-3 fw-semibold">{{ payment_summary.ks3_count }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Сумма КС-3</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.ks3_total|money(project.currency) }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Получено</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.received|money(project.currency) }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Распределено</div><div class="fs-3 fw-semibold text-success money-value">{{ payment_summary.distributed|money(project.currency) }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Нераспределено</div><div class="fs-3 fw-semibold money-value">{{ payment_summary.unallocated|money(project.currency) }}</div></div></article></div>
|
||||||
|
<div class="col-6 col-xl-2"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Задолженность</div><div class="fs-3 fw-semibold money-value {% if payment_summary.outstanding > 0 %}text-danger{% endif %}">{{ payment_summary.outstanding|money(project.currency) }}</div></div></article></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
<div class="row g-4">
|
<div class="row g-4">
|
||||||
<div class="col-lg-8">
|
<div class="col-lg-8">
|
||||||
@@ -66,8 +192,8 @@
|
|||||||
<tbody>{% for row in system_progress %}
|
<tbody>{% for row in system_progress %}
|
||||||
<tr>
|
<tr>
|
||||||
<td class="system-name-cell">{{ row.system.name }}</td>
|
<td class="system-name-cell">{{ row.system.name }}</td>
|
||||||
<td class="text-end money-cell">{{ row.planned_cost|money(project.currency) }}</td>
|
<td class="text-end money-cell money-value">{{ row.planned_cost|money(project.currency) }}</td>
|
||||||
<td class="text-end money-cell">{{ row.performed_cost|money(project.currency) }}</td>
|
<td class="text-end money-cell money-value">{{ row.performed_cost|money(project.currency) }}</td>
|
||||||
<td class="progress-cell"><div class="d-flex justify-content-between small mb-1 progress-summary"><span>{{ '%.4f'|format(row.completion_percent) }}%</span>{% if not row.planned_cost %}<span class="text-muted">нет плана</span>{% endif %}</div><div class="progress" role="progressbar" aria-valuenow="{{ '%.4f'|format(row.completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if row.completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if row.completion_percent > 100 else row.completion_percent }}%"></div></div></td>
|
<td class="progress-cell"><div class="d-flex justify-content-between small mb-1 progress-summary"><span>{{ '%.4f'|format(row.completion_percent) }}%</span>{% if not row.planned_cost %}<span class="text-muted">нет плана</span>{% endif %}</div><div class="progress" role="progressbar" aria-valuenow="{{ '%.4f'|format(row.completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if row.completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if row.completion_percent > 100 else row.completion_percent }}%"></div></div></td>
|
||||||
</tr>{% endfor %}</tbody>
|
</tr>{% endfor %}</tbody>
|
||||||
</table></div>
|
</table></div>
|
||||||
@@ -114,19 +240,105 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<section class="card border-0 shadow-sm mt-4" aria-labelledby="package-heading">
|
||||||
|
<div class="card-header bg-white">
|
||||||
|
<h2 class="h5 mb-0" id="package-heading">Комплект документов</h2>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted small mb-3">Единый ZIP-архив документации за период (КС-6а, КС-2, КС-3) для отправки заказчику или коллеге.</p>
|
||||||
|
<form method="get" action="/projects/{{ project.id }}/export/package" class="row g-3 align-items-end">
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label class="form-label" for="package-date-from">Дата с</label>
|
||||||
|
<input type="date" class="form-control" id="package-date-from" name="date_from" required>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label class="form-label" for="package-date-to">Дата по</label>
|
||||||
|
<input type="date" class="form-control" id="package-date-to" name="date_to" required>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<span class="form-label d-block">Состав комплекта</span>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks6a" id="package-ks6a" checked>
|
||||||
|
<label class="form-check-label" for="package-ks6a">КС-6а</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks2" id="package-ks2" checked>
|
||||||
|
<label class="form-check-label" for="package-ks2">КС-2</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks3" id="package-ks3" checked>
|
||||||
|
<label class="form-check-label" for="package-ks3">КС-3</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="package-format">Формат</label>
|
||||||
|
<select class="form-select" id="package-format" name="format">
|
||||||
|
<option value="both" selected>Excel + Word</option>
|
||||||
|
<option value="excel">Excel</option>
|
||||||
|
<option value="word">Word</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2 d-flex align-items-end">
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Сформировать комплект</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div id="package-error" class="alert alert-danger mt-3 mb-0" role="alert" hidden></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="card border-0 shadow-sm mt-4">
|
<section class="card border-0 shadow-sm mt-4">
|
||||||
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Последние Daily Reports</h2><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-sm btn-outline-primary">Все отчёты</a></div>
|
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Последние Daily Reports</h2><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-sm btn-outline-primary">Все отчёты</a></div>
|
||||||
{% if recent_reports %}
|
{% if recent_reports %}
|
||||||
<div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>Дата</th><th>Система</th><th class="text-end">Позиций</th><th class="text-end">Объём отчёта</th><th></th></tr></thead>
|
<div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>Дата</th><th>Система</th><th class="text-end">Позиций</th><th class="text-end">Объём отчёта</th><th></th></tr></thead>
|
||||||
<tbody>{% for row in recent_reports %}<tr><td>{{ row.report.report_date.strftime('%d.%m.%Y') }}</td><td>{{ row.systems|join(', ') }}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end">{{ row.volume|money(project.currency) }}</td><td class="text-end"><a href="/projects/{{ project.id }}/daily-reports/{{ row.report.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a></td></tr>{% endfor %}</tbody>
|
<tbody>{% for row in recent_reports %}<tr><td>{{ row.report.report_date.strftime('%d.%m.%Y') }}</td><td>{{ row.systems|join(', ') }}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end money-value">{{ row.volume|money(project.currency) }}</td><td class="text-end"><a href="/projects/{{ project.id }}/daily-reports/{{ row.report.id }}" class="btn btn-sm btn-outline-primary">Просмотр</a></td></tr>{% endfor %}</tbody>
|
||||||
</table></div>
|
</table></div>
|
||||||
{% else %}<div class="card-body text-muted">Daily Reports ещё не создавались. Выполненные объёмы пока равны нулю.</div>{% endif %}
|
{% else %}<div class="card-body text-muted">Daily Reports ещё не создавались. Выполненные объёмы пока равны нулю.</div>{% endif %}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="card border-0 shadow-sm mt-4">
|
<section class="card border-0 shadow-sm mt-4">
|
||||||
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Документы ведомости</h2><a href="/boq/{{ project.id }}" class="btn btn-sm btn-outline-primary">Список ведомостей</a></div>
|
<div class="card-header bg-white d-flex justify-content-between align-items-center">
|
||||||
{% if boq_docs %}<ul class="list-group list-group-flush">{% for doc in boq_docs %}<li class="list-group-item d-flex justify-content-between align-items-center"><span>{{ doc.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }} <small class="text-muted">{{ doc.source_file or '' }}</small></span><a class="btn btn-sm btn-outline-primary" href="/boq/{{ project.id }}/documents/{{ doc.id }}">Открыть ведомость</a></li>{% endfor %}</ul>
|
<h2 class="h5 mb-0">Дерево документов</h2>
|
||||||
{% else %}<div class="card-body"><span class="text-muted">Ведомость не импортирована.</span> <a href="/projects/{{ project.id }}/import">Импортировать ведомость</a></div>{% endif %}
|
<div class="d-flex gap-2">
|
||||||
|
<a href="/boq/{{ project.id }}" class="btn btn-sm btn-outline-primary">Ведомости</a>
|
||||||
|
<a href="/projects/{{ project.id }}/agreements" class="btn btn-sm btn-outline-primary">Дополнительные соглашения</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="mb-2 fw-semibold">План и ведомости</div>
|
||||||
|
{% for node in doc_tree %}
|
||||||
|
<div class="ms-3 mb-2">
|
||||||
|
<a href="/boq/{{ project.id }}/documents/{{ node.doc.id }}" class="text-decoration-none">
|
||||||
|
📄 {{ node.doc.display_name }}
|
||||||
|
</a>
|
||||||
|
{% if node.agreements %}
|
||||||
|
<div class="ms-4 mt-1">
|
||||||
|
{% for agr in node.agreements %}
|
||||||
|
<div class="small">
|
||||||
|
<a href="/projects/{{ project.id }}/agreements/{{ agr.id }}" class="text-decoration-none">
|
||||||
|
📋 ДС №{{ agr.number or agr.id }} — {{ agr.name or '' }}
|
||||||
|
<span class="badge bg-{{ 'success' if agr.status == 'approved' else 'secondary' }} ms-1">{{ 'Утверждено' if agr.status == 'approved' else 'Черновик' }}</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% if project_wide_agreements %}
|
||||||
|
<div class="mt-3 mb-2 fw-semibold">Дополнительные работы проекта</div>
|
||||||
|
{% for agr in project_wide_agreements %}
|
||||||
|
<div class="ms-3 small">
|
||||||
|
<a href="/projects/{{ project.id }}/agreements/{{ agr.id }}" class="text-decoration-none">
|
||||||
|
📋 ДС №{{ agr.number or agr.id }} — {{ agr.name or '' }}
|
||||||
|
<span class="badge bg-{{ 'success' if agr.status == 'approved' else 'secondary' }} ms-1">{{ 'Утверждено' if agr.status == 'approved' else 'Черновик' }}</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
{% if not doc_tree and not project_wide_agreements %}
|
||||||
|
<div class="text-muted">Документы ещё не добавлены. <a href="/projects/{{ project.id }}/import">Импортировать ведомость</a></div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<div class="modal fade" id="journalModal" tabindex="-1" aria-labelledby="journalModalTitle" aria-hidden="true">
|
<div class="modal fade" id="journalModal" tabindex="-1" aria-labelledby="journalModalTitle" aria-hidden="true">
|
||||||
<div class="modal-dialog"><form class="modal-content" id="journal-form" method="post">
|
<div class="modal-dialog"><form class="modal-content" id="journal-form" method="post">
|
||||||
@@ -151,6 +363,26 @@
|
|||||||
</table></div></div>
|
</table></div></div>
|
||||||
</div></div>
|
</div></div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="modal fade" id="deleteBlockedModal" tabindex="-1" aria-labelledby="deleteBlockedTitle" aria-hidden="true">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h2 class="modal-title fs-5" id="deleteBlockedTitle">Проект нельзя удалить</h2>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<p>В проекте есть связанные данные: ведомости, отчёты или документы. Удаление невозможно, чтобы не нарушить историю проекта.</p>
|
||||||
|
<p class="mb-0"><strong>Рекомендуется архивировать проект.</strong></p>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||||
|
<form method="post" action="/projects/{{ project.id }}/archive" class="d-inline">
|
||||||
|
<button type="submit" class="btn btn-warning">Архивировать проект</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
@@ -231,6 +463,69 @@
|
|||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
document.getElementById('toggleMoney').addEventListener('click', () => {
|
||||||
|
document.body.classList.toggle('money-hidden');
|
||||||
|
});
|
||||||
|
const deleteForm = document.getElementById('delete-project-form');
|
||||||
|
if (deleteForm) {
|
||||||
|
deleteForm.addEventListener('submit', async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!window.confirm('ВНИМАНИЕ: Проект будет физически удалён вместе со связанными данными. Это действие необратимо. Продолжить?')) return;
|
||||||
|
try {
|
||||||
|
const response = await fetch(deleteForm.getAttribute('action'), {method: 'POST'});
|
||||||
|
if (response.ok) {
|
||||||
|
window.location.href = '/projects/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const modal = new bootstrap.Modal(document.getElementById('deleteBlockedModal'));
|
||||||
|
modal.show();
|
||||||
|
} catch {
|
||||||
|
const modal = new bootstrap.Modal(document.getElementById('deleteBlockedModal'));
|
||||||
|
modal.show();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const packageForm = document.querySelector('form[action*="/export/package"]');
|
||||||
|
const packageError = document.getElementById('package-error');
|
||||||
|
if (packageForm) {
|
||||||
|
packageForm.addEventListener('submit', async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
packageError.hidden = true;
|
||||||
|
const action = packageForm.getAttribute('action');
|
||||||
|
const params = new URLSearchParams(new FormData(packageForm));
|
||||||
|
if (!params.getAll('include').length) {
|
||||||
|
packageError.textContent = 'Выберите хотя бы один тип документов (КС-6а, КС-2, КС-3).';
|
||||||
|
packageError.hidden = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${action}?${params.toString()}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = 'Не удалось сформировать комплект.';
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
if (payload && payload.detail) message = payload.detail;
|
||||||
|
} catch { /* keep default */ }
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
const blob = await response.blob();
|
||||||
|
const disposition = response.headers.get('Content-Disposition') || '';
|
||||||
|
const utfMatch = disposition.match(/filename\*=UTF-8''([^;]+)/);
|
||||||
|
const plainMatch = disposition.match(/filename="?([^";]+)"?/);
|
||||||
|
const filename = utfMatch ? decodeURIComponent(utfMatch[1]) : (plainMatch ? plainMatch[1] : 'Комплект.zip');
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = URL.createObjectURL(blob);
|
||||||
|
link.download = filename;
|
||||||
|
document.body.append(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
URL.revokeObjectURL(link.href);
|
||||||
|
} catch (e) {
|
||||||
|
packageError.textContent = e.message;
|
||||||
|
packageError.hidden = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -11,12 +11,9 @@
|
|||||||
<h1 class="h2 mb-4">Редактировать проект</h1>
|
<h1 class="h2 mb-4">Редактировать проект</h1>
|
||||||
<form method="post" action="/projects/{{ project.id }}/edit" class="card border-0 shadow-sm">
|
<form method="post" action="/projects/{{ project.id }}/edit" class="card border-0 shadow-sm">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="row g-3">
|
<h2 class="h5 mb-3">Проект</h2>
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
<div class="col-md-6"><label class="form-label" for="name">Название проекта *</label><input class="form-control" id="name" name="name" value="{{ project.name }}" required></div>
|
<div class="col-md-6"><label class="form-label" for="name">Название проекта *</label><input class="form-control" id="name" name="name" value="{{ project.name }}" required></div>
|
||||||
<div class="col-md-6"><label class="form-label" for="contract_number">Номер договора</label><input class="form-control" id="contract_number" name="contract_number" value="{{ project.contract_number or '' }}"></div>
|
|
||||||
<div class="col-md-6"><label class="form-label" for="contract_date">Дата договора</label><input class="form-control" type="date" id="contract_date" name="contract_date" value="{{ project.contract_date.isoformat() if project.contract_date else '' }}"></div>
|
|
||||||
<div class="col-md-6"><label class="form-label" for="customer">Заказчик</label><input class="form-control" id="customer" name="customer" value="{{ project.customer or '' }}"></div>
|
|
||||||
<div class="col-md-6"><label class="form-label" for="currency">Валюта</label><input class="form-control" id="currency" name="currency" value="{{ project.currency or 'RUB' }}"></div>
|
|
||||||
<div class="col-md-6"><label class="form-label" for="status">Статус</label><select class="form-select" id="status" name="status">
|
<div class="col-md-6"><label class="form-label" for="status">Статус</label><select class="form-select" id="status" name="status">
|
||||||
{% for value, label in [('active','Активный'),('completed','Завершён'),('on_hold','Приостановлен')] %}<option value="{{ value }}" {% if project.status == value %}selected{% endif %}>{{ label }}</option>{% endfor %}
|
{% for value, label in [('active','Активный'),('completed','Завершён'),('on_hold','Приостановлен')] %}<option value="{{ value }}" {% if project.status == value %}selected{% endif %}>{{ label }}</option>{% endfor %}
|
||||||
{% if project.status and project.status not in ['active','completed','on_hold'] %}<option value="{{ project.status }}" selected>{{ project.status }}</option>{% endif %}
|
{% if project.status and project.status not in ['active','completed','on_hold'] %}<option value="{{ project.status }}" selected>{{ project.status }}</option>{% endif %}
|
||||||
@@ -24,6 +21,49 @@
|
|||||||
<div class="col-md-6"><label class="form-label" for="start_date">Дата начала</label><input class="form-control" type="date" id="start_date" name="start_date" value="{{ project.start_date.isoformat() if project.start_date else '' }}"></div>
|
<div class="col-md-6"><label class="form-label" for="start_date">Дата начала</label><input class="form-control" type="date" id="start_date" name="start_date" value="{{ project.start_date.isoformat() if project.start_date else '' }}"></div>
|
||||||
<div class="col-md-6"><label class="form-label" for="end_date">Дата окончания</label><input class="form-control" type="date" id="end_date" name="end_date" value="{{ project.end_date.isoformat() if project.end_date else '' }}"></div>
|
<div class="col-md-6"><label class="form-label" for="end_date">Дата окончания</label><input class="form-control" type="date" id="end_date" name="end_date" value="{{ project.end_date.isoformat() if project.end_date else '' }}"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<h2 class="h5 mb-3">Договор</h2>
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
|
<div class="col-md-6"><label class="form-label" for="contract_number">Номер</label><input class="form-control" id="contract_number" name="contract_number" value="{{ project.contract_number or '' }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label" for="contract_date">Дата</label><input class="form-control" type="date" id="contract_date" name="contract_date" value="{{ project.contract_date.isoformat() if project.contract_date else '' }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label" for="contract_amount">Сумма</label><input class="form-control" id="contract_amount" name="contract_amount" type="number" step="0.01" value="{{ project.contract_amount if project.contract_amount is not none else '' }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label" for="currency">Валюта</label><input class="form-control" id="currency" name="currency" value="{{ project.currency or 'RUB' }}"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 class="h5 mb-3">Участники</h2>
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
|
<div class="col-md-4"><label class="form-label" for="investor_name">Инвестор</label><input class="form-control" id="investor_name" name="investor_name" value="{{ project.investor_name or '' }}"></div>
|
||||||
|
<div class="col-md-4"><label class="form-label" for="customer_name">Заказчик</label><input class="form-control" id="customer_name" name="customer_name" value="{{ project.effective_customer_name }}"></div>
|
||||||
|
<div class="col-md-4"><label class="form-label" for="contractor_name">Подрядчик</label><input class="form-control" id="contractor_name" name="contractor_name" value="{{ project.contractor_name or '' }}"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 class="h5 mb-3">Объект</h2>
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
|
<div class="col-md-6"><label class="form-label" for="construction_name">Наименование строительства</label><input class="form-control" id="construction_name" name="construction_name" value="{{ project.construction_name or '' }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label" for="object_name">Наименование объекта</label><input class="form-control" id="object_name" name="object_name" value="{{ project.object_name or '' }}"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 class="h5 mb-3">Подписанты</h2>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<div class="card bg-light border-0"><div class="card-body">
|
||||||
|
<h3 class="h6 mb-3">Заказчик</h3>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-12"><label class="form-label" for="customer_signer_name">ФИО</label><input class="form-control" id="customer_signer_name" name="customer_signer_name" value="{{ project.customer_signer_name or '' }}"></div>
|
||||||
|
<div class="col-12"><label class="form-label" for="customer_signer_position">Должность</label><input class="form-control" id="customer_signer_position" name="customer_signer_position" value="{{ project.customer_signer_position or '' }}"></div>
|
||||||
|
</div>
|
||||||
|
</div></div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<div class="card bg-light border-0"><div class="card-body">
|
||||||
|
<h3 class="h6 mb-3">Подрядчик</h3>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-12"><label class="form-label" for="contractor_signer_name">ФИО</label><input class="form-control" id="contractor_signer_name" name="contractor_signer_name" value="{{ project.contractor_signer_name or '' }}"></div>
|
||||||
|
<div class="col-12"><label class="form-label" for="contractor_signer_position">Должность</label><input class="form-control" id="contractor_signer_position" name="contractor_signer_position" value="{{ project.contractor_signer_position or '' }}"></div>
|
||||||
|
</div>
|
||||||
|
</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-footer bg-white d-flex justify-content-end gap-2"><a href="/projects/{{ project.id }}" class="btn btn-outline-secondary">Отмена</a><button class="btn btn-primary" type="submit">Сохранить</button></div>
|
<div class="card-footer bg-white d-flex justify-content-end gap-2"><a href="/projects/{{ project.id }}" class="btn btn-outline-secondary">Отмена</a><button class="btn btn-primary" type="submit">Сохранить</button></div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -19,6 +19,25 @@
|
|||||||
<label for="file" class="form-label">Выберите Excel файл</label>
|
<label for="file" class="form-label">Выберите Excel файл</label>
|
||||||
<input class="form-control" type="file" id="file" name="file" accept=".xlsx,.xls" required>
|
<input class="form-control" type="file" id="file" name="file" accept=".xlsx,.xls" required>
|
||||||
</div>
|
</div>
|
||||||
|
<h6 class="card-subtitle mb-3">Реквизиты ведомости</h6>
|
||||||
|
<div class="row g-3 mb-3">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<label for="document_name" class="form-label">Название ведомости</label>
|
||||||
|
<input class="form-control" type="text" id="document_name" name="document_name" maxlength="255" placeholder="Например: Основная ведомость">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="document_number" class="form-label">Номер</label>
|
||||||
|
<input class="form-control" type="text" id="document_number" name="document_number" maxlength="100">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="document_date" class="form-label">Дата</label>
|
||||||
|
<input class="form-control" type="date" id="document_date" name="document_date">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<label for="contract" class="form-label">Договор</label>
|
||||||
|
<input class="form-control" type="text" id="contract" name="contract" maxlength="255" value="{{ project.contract_number or '' }}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<button type="submit" class="btn btn-primary">Загрузить</button>
|
<button type="submit" class="btn btn-primary">Загрузить</button>
|
||||||
<a href="/projects/{{ project.id }}" class="btn btn-secondary">Отмена</a>
|
<a href="/projects/{{ project.id }}" class="btn btn-secondary">Отмена</a>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||||
<p><strong>Файл:</strong> {{ filename }}</p>
|
<p><strong>Файл:</strong> {{ filename }}</p>
|
||||||
<p><strong>Лист:</strong> {{ sheet_name }}</p>
|
<p><strong>Лист:</strong> {{ sheet_name }}</p>
|
||||||
|
{% if import_result.document_name %}<p><strong>Ведомость:</strong> {{ import_result.document_name }}</p>{% endif %}
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
|
|||||||
@@ -95,7 +95,30 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-4">
|
<div class="mt-4">
|
||||||
<form method="post" action="/boq/{{ project.id }}/import/confirm">
|
<form method="post" action="/boq/{{ project.id }}/import/confirm" id="import-confirm-form">
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<h5 class="card-title">Реквизиты ведомости</h5>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<label class="form-label" for="document_name">Название ведомости</label>
|
||||||
|
<input class="form-control" type="text" id="document_name" name="document_name" value="{{ document_name or sheet_name }}" required maxlength="255">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="document_number">Номер</label>
|
||||||
|
<input class="form-control" type="text" id="document_number" name="document_number" value="{{ document_number or '' }}" maxlength="100">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="document_date">Дата</label>
|
||||||
|
<input class="form-control" type="date" id="document_date" name="document_date" value="{{ document_date or '' }}">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<label class="form-label" for="contract">Договор</label>
|
||||||
|
<input class="form-control" type="text" id="contract" name="contract" value="{{ contract or '' }}" maxlength="255">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<input type="hidden" name="filename" value="{{ filename }}">
|
<input type="hidden" name="filename" value="{{ filename }}">
|
||||||
<input type="hidden" name="sheet_name" value="{{ sheet_name }}">
|
<input type="hidden" name="sheet_name" value="{{ sheet_name }}">
|
||||||
<input type="hidden" name="header_row" value="{{ header_row }}">
|
<input type="hidden" name="header_row" value="{{ header_row }}">
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Импорт проекта — Work Volume Tracker</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<main class="container py-4">
|
||||||
|
<nav class="mb-3"><ol class="breadcrumb">
|
||||||
|
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||||
|
<li class="breadcrumb-item active">Импорт проекта</li>
|
||||||
|
</ol></nav>
|
||||||
|
<h1 class="h2 mb-3">Импорт проекта</h1>
|
||||||
|
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
||||||
|
<div class="card border-0 shadow-sm mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted">Выберите ZIP-архив проекта, созданный через «Экспорт проекта».
|
||||||
|
Файл будет полностью проверен до каких-либо изменений в базе данных.</p>
|
||||||
|
<form method="post" action="/projects/import/upload" enctype="multipart/form-data">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="file">Архив проекта (.wvt.zip)</label>
|
||||||
|
<input class="form-control" type="file" id="file" name="file" accept=".zip,application/zip" required>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">Проверить файл</button>
|
||||||
|
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Проверка архива — Импорт проекта</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<main class="container py-4">
|
||||||
|
<nav class="mb-3"><ol class="breadcrumb">
|
||||||
|
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||||
|
<li class="breadcrumb-item"><a href="/projects/import">Импорт проекта</a></li>
|
||||||
|
<li class="breadcrumb-item active">Проверка</li>
|
||||||
|
</ol></nav>
|
||||||
|
<h1 class="h2 mb-3">Файл проверен</h1>
|
||||||
|
<div class="alert alert-success" role="alert">Архив корректен. После подтверждения будет создан новый проект.</div>
|
||||||
|
|
||||||
|
<div class="card border-0 shadow-sm mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<dl class="row mb-0">
|
||||||
|
<dt class="col-sm-4">Проект</dt>
|
||||||
|
<dd class="col-sm-8">{{ project_name }}</dd>
|
||||||
|
<dt class="col-sm-4">Договор</dt>
|
||||||
|
<dd class="col-sm-8">{{ project.get('contract_number') or '—' }}</dd>
|
||||||
|
<dt class="col-sm-4">Заказчик</dt>
|
||||||
|
<dd class="col-sm-8">{{ project.get('customer') or '—' }}</dd>
|
||||||
|
<dt class="col-sm-4">Ведомостей</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('boq_documents', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Систем</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('systems', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Разделов</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('sections', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Позиций</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('work_items', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">ДС</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('agreements', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Daily Reports</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('daily_reports', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">КС-2</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('ks2', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">КС-3</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('ks3', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Платежей</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('payments', 0) }}</dd>
|
||||||
|
<dt class="col-sm-4">Записей рабочего журнала</dt>
|
||||||
|
<dd class="col-sm-8">{{ counts.get('work_journal_entries', 0) }}</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="post" action="/projects/import/confirm" class="d-flex gap-2">
|
||||||
|
<input type="hidden" name="token" value="{{ token }}">
|
||||||
|
<button type="submit" class="btn btn-primary">Импортировать проект</button>
|
||||||
|
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -35,6 +35,10 @@
|
|||||||
<input type="hidden" name="sheet_name" value="{{ sheet }}">
|
<input type="hidden" name="sheet_name" value="{{ sheet }}">
|
||||||
<input type="hidden" name="header_row" value="5">
|
<input type="hidden" name="header_row" value="5">
|
||||||
<input type="hidden" name="start_row" value="6">
|
<input type="hidden" name="start_row" value="6">
|
||||||
|
<input type="hidden" name="document_name" value="{{ document_name or '' }}">
|
||||||
|
<input type="hidden" name="document_number" value="{{ document_number or '' }}">
|
||||||
|
<input type="hidden" name="document_date" value="{{ document_date or '' }}">
|
||||||
|
<input type="hidden" name="contract" value="{{ contract or '' }}">
|
||||||
<button type="submit" class="btn btn-sm btn-primary">Выбрать</button>
|
<button type="submit" class="btn btn-sm btn-primary">Выбрать</button>
|
||||||
</form>
|
</form>
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -10,9 +10,24 @@
|
|||||||
<div class="container mt-5">
|
<div class="container mt-5">
|
||||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||||
<h1>Projects</h1>
|
<h1>Projects</h1>
|
||||||
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
<div class="d-flex gap-2">
|
||||||
|
<a href="/projects/settings/database-reset" class="btn btn-outline-danger">Сброс базы</a>
|
||||||
|
<a href="/projects/import" class="btn btn-outline-primary">Импорт проекта</a>
|
||||||
|
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if request.query_params.get('reset') %}
|
||||||
|
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||||
|
{% if request.query_params.get('storage_error') %}
|
||||||
|
Данные проекта удалены, но физическое хранилище не удалось очистить. Требуется ручная очистка.
|
||||||
|
{% else %}
|
||||||
|
Данные удалены.
|
||||||
|
{% endif %}
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-md-12">
|
<div class="col-md-12">
|
||||||
{% if projects %}
|
{% if projects %}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"template_type": "ks2",
|
||||||
|
"template_version": 2,
|
||||||
|
"file": "ks2_ru_v2.xlsx",
|
||||||
|
"format": "xlsx",
|
||||||
|
"language": "ru",
|
||||||
|
"description": "Акт КС-2, официальная унифицированная форма № КС-2 (DOC-C2)",
|
||||||
|
"table_marker": "##KS2_ROWS##",
|
||||||
|
"group_marker": "##KS2_GROUP##",
|
||||||
|
"totals_marker": "##KS2_TOTALS##",
|
||||||
|
"storno_marker": "##KS2_STORNO##",
|
||||||
|
"placeholders": [
|
||||||
|
"customer",
|
||||||
|
"contractor_name",
|
||||||
|
"object_name",
|
||||||
|
"contract_number",
|
||||||
|
"contract_date",
|
||||||
|
"ks2_number",
|
||||||
|
"ks2_date",
|
||||||
|
"period_from",
|
||||||
|
"period_to",
|
||||||
|
"contractor_signer_position",
|
||||||
|
"contractor_signer_name",
|
||||||
|
"customer_signer_position",
|
||||||
|
"customer_signer_name"
|
||||||
|
],
|
||||||
|
"row_placeholders": [
|
||||||
|
"source_number",
|
||||||
|
"name",
|
||||||
|
"unit",
|
||||||
|
"quantity",
|
||||||
|
"unit_price",
|
||||||
|
"amount"
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"template_type": "ks3",
|
||||||
|
"template_version": 1,
|
||||||
|
"file": "ks3_ru_v1.docx",
|
||||||
|
"format": "docx",
|
||||||
|
"language": "ru",
|
||||||
|
"description": "Акт КС-3, таблица выбранных КС-2 (DOC-B4)",
|
||||||
|
"table_marker": "##KS3_KS2_ROWS##",
|
||||||
|
"totals_marker": "##KS3_TOTALS##",
|
||||||
|
"storno_marker": "##KS3_STORNO##",
|
||||||
|
"placeholders": [
|
||||||
|
"project_name",
|
||||||
|
"customer",
|
||||||
|
"contract_number",
|
||||||
|
"contract_date",
|
||||||
|
"currency",
|
||||||
|
"period",
|
||||||
|
"comment",
|
||||||
|
"ks3_number",
|
||||||
|
"ks3_date"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Implementation Report: 001-ks2-regression-tests
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
„®Ў ў«Ґл ¤ў ॣаҐббЁ®ле вҐбв ¤«п Їа®ўҐаЄЁ а Ў®вл KS-2:
|
||||||
|
1. \`test_multiple_ks2_same_daily_report_item\` - Їа®ўҐапҐв, зв® ҐбЄ®«мЄ® KS-2 ¬®Јгв ббл« вмбп ®¤Ё Ё в®в ¦Ґ DailyReportItem
|
||||||
|
2. \`test_exceeding_plan_allowed\` - Їа®ўҐапҐв, зв® ЇаҐўл襨Ґ Ї« а §аҐиҐ®
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
- tests/test_ks2.py (¤®Ў ў«Ґл ¤ў ®ўле вҐбв )
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
- „®Ў ў«Ґл ¤ў вҐбв : \`test_multiple_ks2_same_daily_report_item\` Ё \`test_exceeding_plan_allowed\`
|
||||||
|
- ђҐ§г«мв в pytest -q: 12 passed, 1 warning
|
||||||
|
- ђҐ§г«мв в git diff --check: (empty)
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None
|
||||||
|
|
||||||
|
## Follow-up / Open Questions
|
||||||
|
None
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Implementation Report: 002-ks2-readonly-audit
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## Checked files
|
||||||
|
- AGENTS.md
|
||||||
|
- docs/tasks/001-ks2-regression-tests.md
|
||||||
|
- docs/implementation/001-ks2-regression-tests.md
|
||||||
|
- app/models/ks2.py
|
||||||
|
- app/services/ks2_service.py
|
||||||
|
- tests/test_ks2.py
|
||||||
|
- app/models/daily_report.py
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
|
||||||
|
| Rule | Status | Evidence |
|
||||||
|
|---|---|---|
|
||||||
|
| фактический объём берётся из Daily Reports | PASS | В `app/models/daily_report.py` определена модель `DailyReportItem` с полем `completed_quantity`. В `app/services/ks2_service.py` функция `build_work_item_balances` использует `DailyReportItem` для расчета фактических объемов. |
|
||||||
|
| КС-2 не изменяет Daily Reports | PASS | В `app/services/ks2_service.py` функция `issue_ks2` только читает данные из `DailyReportItem` и не изменяет их. Только создает `KS2ItemSource` связи. |
|
||||||
|
| частичное закрытие фактического объёма | PASS | В `tests/test_ks2.py` тест `test_multiple_ks2_same_daily_report_item` демонстрирует, что один `DailyReportItem` может быть частично закрыт в нескольких KS-2. |
|
||||||
|
| один DailyReportItem может быть источником нескольких КС-2 | PASS | В `tests/test_ks2.py` тест `test_multiple_ks2_same_daily_report_item` демонстрирует, что один `DailyReportItem` может быть использован в нескольких KS-2. |
|
||||||
|
| один КС-2 может получать объём из нескольких DailyReportItem | PASS | В `app/services/ks2_service.py` функция `issue_ks2` распределяет объемы по нескольким `DailyReportItem` по дате. Тест `test_multiple_daily_reports` проверяет это. |
|
||||||
|
| доступный объём рассчитывается как `actual - closed` | PASS | В `app/services/ks2_service.py` функция `build_work_item_balances` рассчитывает `available_quantity` как `actual_qty - closed_qty`. |
|
||||||
|
| превышение доступного к закрытию количества блокируется | PASS | В `app/services/ks2_service.py` функция `_validated_entries` проверяет, что `quantity <= available` и вызывает `KS2ValidationError` при превышении. |
|
||||||
|
| превышение планового количества фактом само по себе не блокирует закрытие | PASS | В `tests/test_ks2.py` тест `test_exceeding_plan_allowed` демонстрирует, что фактическое превышение плана не блокирует создание KS-2. |
|
||||||
|
| количество в КС-2 должно быть положительным | PASS | В `app/models/ks2.py` модели `KS2Item` и `KS2ItemSource` есть `CheckConstraint("quantity > 0", name="ck_ks2_items_quantity_positive")`. В `app/services/ks2_service.py` функция `_decimal` и проверка `if quantity <= ZERO` проверяют положительность количества. |
|
||||||
|
| одна WorkItem не может быть добавлена в один КС-2 дважды | PASS | В `app/services/ks2_service.py` функция `_validated_entries` проверяет, что `item_id` не указан дважды в одной заявке. |
|
||||||
|
| количество в КС-2 умножается на серверную цену WorkItem | PASS | В `app/services/ks2_service.py` функция `save_draft` вычисляет `amount = price * quantity` где `price = _decimal(item.unit_price)`. |
|
||||||
|
| операции с ошибкой не оставляют частично созданные данные | PASS | В `app/services/ks2_service.py` все функции используют транзакции и `db.rollback()` в случае ошибки, обеспечивая атомарность операций. |
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
- Запущен pytest -q для тестов в tests/test_ks2.py
|
||||||
|
- Результат pytest -q: 34 passed, 1 warning
|
||||||
|
- Результат git diff --check: (empty)
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None
|
||||||
|
|
||||||
|
## Follow-up / Open Questions
|
||||||
|
- Не обнаружено отклонений от задания
|
||||||
|
- Все бизнес-правила корректно реализованы в текущей версии кода
|
||||||
|
- Все тесты проходят успешно и подтверждают корректность реализации
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# Implementation Report: 003-ks2-regression-coverage
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Добавлены регрессионные тесты для KS-2 сервиса, покрывающие следующие бизнес-правила:
|
||||||
|
|
||||||
|
1. **Cross-project integrity** — KS-2 не может быть создан с WorkItem из другого проекта
|
||||||
|
2. **Positive quantity** — количество KS-2 должно быть строго больше нуля (0 и отрицательные)
|
||||||
|
3. **Duplicate WorkItem** — одна WorkItem не может быть указана дважды в одном KS-2
|
||||||
|
4. **Server-side amount** — amount рассчитывается на сервере как quantity × unit_price
|
||||||
|
5. **Atomic rollback on issue failure** — при ошибке проведения не остаётся частично созданных KS2ItemSource; черновик, позиции и DailyReportItem остаются без изменений
|
||||||
|
6. **Issued KS-2 is immutable** — проведённый KS-2 нельзя редактировать
|
||||||
|
7. **Repeated issue is rejected** — проведённый KS-2 нельзя провести повторно
|
||||||
|
|
||||||
|
### Исправление test_atomic_rollback_on_issue_failure
|
||||||
|
Предыдущая версия теста пыталась создать черновик с quantity=15 при доступном объёме=10, что вызывало ошибку уже на этапе `save_draft()` — до `issue_ks2()` никогда не доходило.
|
||||||
|
|
||||||
|
Исправленная версия:
|
||||||
|
- Создаёт валидный черновик с двумя позициями (5 из 10 и 6 из 8) — `save_draft()` проходит успешно
|
||||||
|
- Мокает `build_work_item_balances` так, что первая позиция проходит (5 ≤ 7), вторая нет (6 > 3)
|
||||||
|
- Проверяет `KS2ValidationError` именно от `issue_ks2()`
|
||||||
|
- Верифицирует атомарность: status=draft, обе позиции на месте, 0 KS2ItemSource в БД, DailyReportItem не изменены
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
- `tests/test_ks2.py` — исправлен `test_atomic_rollback_on_issue_failure`
|
||||||
|
|
||||||
|
## Tests added, by test name
|
||||||
|
- test_cross_project_integrity
|
||||||
|
- test_positive_quantity
|
||||||
|
- test_duplicate_workitem_in_ks2
|
||||||
|
- test_server_side_amount_calculation
|
||||||
|
- test_atomic_rollback_on_issue_failure *(исправлен)*
|
||||||
|
- test_issued_ks2_is_immutable
|
||||||
|
- test_repeated_issue_is_rejected
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2.py -v
|
||||||
|
```
|
||||||
|
19 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 38 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий тест — `test_project_work_journal_crud_and_dashboard_warnings` в `tests/test_work_journal.py`. Не связан с KS-2, пред-existing.
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Trailing whitespace обнаружен в ранее добавленных тестах (test_cross_project_integrity, test_positive_quantity, test_duplicate_workitem_in_ks2 и др.) — не в `test_atomic_rollback_on_issue_failure`. Эти тесты не менялись в текущей задаче.
|
||||||
|
|
||||||
|
### git diff --stat
|
||||||
|
```
|
||||||
|
tests/test_ks2.py | 196 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
1 file changed, 196 insertions(+)
|
||||||
|
```
|
||||||
|
Production-код не изменён.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Follow-up / Open Questions
|
||||||
|
- Trailing whitespace в ранее добавленных тестах (test_cross_project_integrity и др.) — можно убрать отдельной задачей или при ближайшем commit.
|
||||||
|
- `test_project_work_journal_crud_and_dashboard_warnings` в `tests/test_work_journal.py` падает (pre-existing) — не относится к текущей задаче.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Implementation Report: 004-ks2-ui
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Реализован полный UI-сценарий KS-2: список → создание → редактирование → проведение → просмотр.
|
||||||
|
|
||||||
|
## Changed files — production
|
||||||
|
|
||||||
|
### app/routers/ks2.py
|
||||||
|
Исправлены вызовы `TemplateResponse` для совместимости со Starlette 0.27.0 (`request` перенесён из keyword-аргумента в `context`). Без этого исправления KS-2 страницы не рендерились.
|
||||||
|
|
||||||
|
### app/routers/projects.py
|
||||||
|
Добавлен импорт `KS2`, передача `ks2_count` в контекст страницы проекта для отображения кнопки «КС-2 (N)».
|
||||||
|
|
||||||
|
### app/templates/base.html (new)
|
||||||
|
Создан базовый шаблон — KS-2 шаблоны наследовали `base.html`, но файл отсутствовал.
|
||||||
|
|
||||||
|
### app/templates/ks2/form.html
|
||||||
|
- динамический action URL (создание / редактирование);
|
||||||
|
- предзаполнение полей при редактировании (номер, дата, комментарий);
|
||||||
|
- расширенная таблица позиций: № поз., наименование, ед., план, факт, закрыто, доступно, цена, кол-во, сумма;
|
||||||
|
- сумма рассчитывается на клиенте через JS (quantity × unit_price);
|
||||||
|
- кнопка «Создать» / «Сохранить»;
|
||||||
|
- ссылка «Назад» ведёт на просмотр (редактирование) или список (создание).
|
||||||
|
|
||||||
|
### app/templates/ks2/view.html
|
||||||
|
- добавлена колонка «Ед.» в таблицу позиций;
|
||||||
|
- исправлена логика: источники факта показываются для `issued` (было `draft` — у draft нет источников);
|
||||||
|
- кнопки «Редактировать» / «Провести» только для `draft`;
|
||||||
|
- для `issued` — сообщение «КС-2 проведено. Документ не может быть изменён.» и таблица источников.
|
||||||
|
|
||||||
|
### app/templates/projects/detail.html
|
||||||
|
Добавлена кнопка «КС-2» в навигацию проекта (рядом с Daily Reports, Доп. соглашениями).
|
||||||
|
|
||||||
|
## Changed files — tests
|
||||||
|
|
||||||
|
### tests/test_ks2_ui.py (new)
|
||||||
|
Интеграционный тест `test_ks2_ui_full_workflow`, покрывающий 10 пунктов из задания:
|
||||||
|
|
||||||
|
1. Список KS-2 проекта открывается (200, заголовок, кнопка создания)
|
||||||
|
2. Создание draft через endpoint (POST → 303 → редирект)
|
||||||
|
3. Открытие draft (номер, статус «Черновик», кнопки)
|
||||||
|
4. Редактирование draft (форма предзаполнена, сохранение)
|
||||||
|
5. Проведение draft (статус «Проведён», «КС-2 проведено», источники)
|
||||||
|
6. Issued KS-2 нельзя редактировать (GET /edit → 409)
|
||||||
|
7. Повторное проведение невозможно (POST /issue → 409)
|
||||||
|
8. Ошибка при проведении оставляет draft (status=draft, 0 sources)
|
||||||
|
9. Доступные количества = факт минус закрытое (30 − 15 = 15)
|
||||||
|
10. Создание draft не изменяет DailyReportItem (completed_quantity = 30)
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2_ui.py -v
|
||||||
|
```
|
||||||
|
1 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 39 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Только CRLF-предупреждения (Windows line ending normalization). Ошибок форматирования нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
- `app/routers/ks2.py` — исправлены вызовы `TemplateResponse` (не бизнес-логика, а API шаблонизатора).
|
||||||
|
- `app/templates/base.html` — создан, т.к. KS-2 шаблоны его наследовали, но файл отсутствовал.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- Поля «период с» / «период по» не реализованы — модель KS-2 не содержит этих полей, добавление потребует миграции.
|
||||||
|
- Для monetary privacy (скрытие сумм) в проекте нет общего механизма — не в scope.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Implementation Report: 005-ks2-ui-fix
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Исправлены UI-проблемы KS-2 по результатам ручной проверки.
|
||||||
|
|
||||||
|
### 1. Навигация — кнопка «← К проекту»
|
||||||
|
Добавлена на все три страницы KS-2:
|
||||||
|
- `ks2/list.html` — навигация перед заголовком
|
||||||
|
- `ks2/form.html` — навигация перед заголовком
|
||||||
|
- `ks2/view.html` — навигация перед заголовком
|
||||||
|
|
||||||
|
### 2. Ширина финансовых колонок в форме
|
||||||
|
Все числовые и финансовые колонки таблицы формы (`form.html`) помечены `text-nowrap`:
|
||||||
|
- План, Факт, Закрыто, Доступно, Цена, Кол-во, Сумма
|
||||||
|
- Ячейки данных `<td>` также получили `text-nowrap`
|
||||||
|
- Символ ₽ и числовые значения не переносится
|
||||||
|
|
||||||
|
В `list.html` — колонка «Сумма» получила `text-nowrap`.
|
||||||
|
|
||||||
|
В `view.html` — колонки Количество, Цена, Сумма получили `text-nowrap`.
|
||||||
|
|
||||||
|
### 3. Кнопки на странице просмотра (draft)
|
||||||
|
Кнопки «Редактировать», «Провести КС-2», «Назад к списку» обёрнуты в `<div class="d-flex gap-2 align-items-center">` — располагаются на одном уровне с одинаковым вертикальным выравниванием.
|
||||||
|
|
||||||
|
### 4. Строка «Итого»
|
||||||
|
Исправлена структура `<tfoot>` в `view.html`:
|
||||||
|
- `<th colspan="4" class="text-end">Итого</th>` — метка занимает первые 4 колонки, выровнена вправо
|
||||||
|
- `<th class="text-end text-nowrap">{{ total | money }}</th>` — сумма в колонке «Сумма», без переноса
|
||||||
|
|
||||||
|
### 5. Не изменено
|
||||||
|
- Бизнес-логика KS-2
|
||||||
|
- Расчёт количества
|
||||||
|
- Расчёт сумм
|
||||||
|
- issue/rollback
|
||||||
|
- Daily Reports
|
||||||
|
- Модели БД
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
- `app/templates/ks2/list.html` (modified — навигация, text-nowrap)
|
||||||
|
- `app/templates/ks2/form.html` (modified — навигация, text-nowrap)
|
||||||
|
- `app/templates/ks2/view.html` (modified — навигация, кнопки d-flex, Итого colspan, text-nowrap)
|
||||||
|
|
||||||
|
Production-код (роутеры, сервисы, модели) не изменён.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2_ui.py -v
|
||||||
|
```
|
||||||
|
1 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 39 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing, не связан с KS-2).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Только CRLF-предупреждения (Windows). Ошибок форматирования нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Follow-up / Open Questions
|
||||||
|
None.
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# Implementation Report: 006-ks2-reporting-period
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Добавлены поля «Период с» и «Период по» в KS-2: модель, миграция, валидация, UI.
|
||||||
|
|
||||||
|
## Changed files — production
|
||||||
|
|
||||||
|
### app/models/ks2.py
|
||||||
|
Добавлены два поля в модель `KS2`:
|
||||||
|
- `reporting_period_from = Column(Date, nullable=True)`
|
||||||
|
- `reporting_period_to = Column(Date, nullable=True)`
|
||||||
|
|
||||||
|
Nullable — для обратной совместимости с существующими записями.
|
||||||
|
|
||||||
|
### app/database/migrations.py
|
||||||
|
Добавлена миграция `20260925_ks2_reporting_period`:
|
||||||
|
- `ALTER TABLE ks2_documents ADD COLUMN reporting_period_from DATE`
|
||||||
|
- `ALTER TABLE ks2_documents ADD COLUMN reporting_period_to DATE`
|
||||||
|
|
||||||
|
Существующие записи сохраняются (новые колонки = NULL). Миграция идемпотентна (проверяет наличие колонок через `PRAGMA table_info`).
|
||||||
|
|
||||||
|
### app/services/ks2_service.py
|
||||||
|
Расширена функция `save_draft()`:
|
||||||
|
- Новые параметры: `reporting_period_from`, `reporting_period_to` (опциональные, `None` по умолчанию)
|
||||||
|
- Добавлена функция `_parse_date()` для парсинга дат из строк/объектов date
|
||||||
|
- Валидация:
|
||||||
|
- Для новых документов (`ks2_id=None`): оба поля обязательны
|
||||||
|
- Если оба заполнены: `period_to` не может быть раньше `period_from`
|
||||||
|
- Значения сохраняются в `document.reporting_period_from` / `document.reporting_period_to`
|
||||||
|
|
||||||
|
### app/routers/ks2.py
|
||||||
|
Эндпоинты `ks2_create` и `ks2_update` принимают `reporting_period_from` и `reporting_period_to` как `Form("")` и передают в `save_draft()`.
|
||||||
|
|
||||||
|
### app/templates/ks2/form.html
|
||||||
|
Добавлены два поля ввода типа `date`:
|
||||||
|
- «Период с» (`reporting_period_from`)
|
||||||
|
- «Период по» (`reporting_period_to`)
|
||||||
|
|
||||||
|
Поля расположены в верхней части формы рядом с номером и датой документа. При редактировании предзаполнены.
|
||||||
|
|
||||||
|
### app/templates/ks2/view.html
|
||||||
|
Отображение периода в карточке документа:
|
||||||
|
```
|
||||||
|
Период: 01.06.2023 — 30.06.2023
|
||||||
|
```
|
||||||
|
|
||||||
|
Показывается для draft и issued одинаково. Только если оба поля заполнены.
|
||||||
|
|
||||||
|
### app/templates/ks2/list.html
|
||||||
|
Период отображается компактно под датой документа в колонке «Дата»:
|
||||||
|
```
|
||||||
|
15.06.2023
|
||||||
|
01.06.2023 — 30.06.2023
|
||||||
|
```
|
||||||
|
|
||||||
|
## Changed files — tests
|
||||||
|
|
||||||
|
### tests/test_ks2.py
|
||||||
|
- Добавлены константы `DEFAULT_PERIOD_FROM`, `DEFAULT_PERIOD_TO`
|
||||||
|
- Все существующие вызовы `save_draft()` (создание новых документов) дополнены аргументами периода
|
||||||
|
- Все 19 существующих тестов продолжают проходить
|
||||||
|
|
||||||
|
### tests/test_ks2_ui.py
|
||||||
|
- `test_ks2_ui_full_workflow`: обновлён — форма создания/редактирования передаёт период, проверяется отображение периода на страницах просмотра, редактирования, списка
|
||||||
|
- `test_ks2_period_validation` (новый): проверяет:
|
||||||
|
- создание без периода → 400
|
||||||
|
- `to < from` → 400
|
||||||
|
- валидный период → 303, сохранение в БД
|
||||||
|
|
||||||
|
## Migration approach
|
||||||
|
Колонки добавлены как `nullable=True`. Существующие KS-2 сохраняются с `NULL` в полях периода. Это безопасно:
|
||||||
|
- Валидация обязательности периода применяется только при создании нового KS-2
|
||||||
|
- Старые записи без периода отображаются без строки «Период» (условие `{% if document.reporting_period_from and document.reporting_period_to %}`)
|
||||||
|
- Редактирование старого draft позволяет заполнить период, но не требует его (т.к. `ks2_id` передаётся)
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2.py -v
|
||||||
|
```
|
||||||
|
19 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2_ui.py -v
|
||||||
|
```
|
||||||
|
2 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 40 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Только CRLF-предупреждения (Windows). Ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- Старые KS-2 без периода отображаются без строки «Период». При желании можно добавить пометку «не указан».
|
||||||
|
- Редактирование старого draft не требует заполнения периода (backward compatibility). Для строгой обязательности потребуется миграция данных.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Implementation Report: 007-ks2-table-fix
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Исправлена структура таблицы формы KS-2: фиксированная ширина колонок, формат количества 2 знака, стабильность при вводе.
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
|
||||||
|
### app/routers/ks2.py
|
||||||
|
Добавлен Jinja2-фильтр `quantity2` — форматирование числовых значений с 2 знаками после запятой (напр. `2.00`, `531.00`, `2100.00`). Не изменяет внутреннюю точность Decimal.
|
||||||
|
|
||||||
|
### app/templates/ks2/form.html
|
||||||
|
- Добавлен `<colgroup>` с фиксированной шириной колонок:
|
||||||
|
- № поз.: 50px
|
||||||
|
- Наименование: auto (всё оставшееся пространство)
|
||||||
|
- Ед.: 40px
|
||||||
|
- План, Факт, Закрыто, Доступно: 72px каждый
|
||||||
|
- Цена: 96px
|
||||||
|
- Кол-во: 90px
|
||||||
|
- Сумма: 100px
|
||||||
|
- `table-layout: fixed` для стабильной ширины независимо от содержимого
|
||||||
|
- План, Факт, Закрыто, Доступно — формат `quantity2` (2 знака: `2.00`, `531.00`)
|
||||||
|
- Цена, Сумма — формат `money` (существующий, с ₽, `text-nowrap`)
|
||||||
|
- Наименование — `overflow: hidden; text-overflow: ellipsis; white-space: nowrap`
|
||||||
|
- Поле ввода количества: `style="width: 100%; box-sizing: border-box;"` — не расширяет колонку
|
||||||
|
- `step="0.01"` для ввода с 2 знаками
|
||||||
|
|
||||||
|
## What was NOT changed
|
||||||
|
- Расчёт доступного количества
|
||||||
|
- Расчёт суммы
|
||||||
|
- issue/rollback
|
||||||
|
- Модели БД
|
||||||
|
- Daily Reports
|
||||||
|
- Бизнес-логика KS-2
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks2.py tests/test_ks2_ui.py -v
|
||||||
|
```
|
||||||
|
21 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 40 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Implementation Report: 008-ks6a-journal
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Добавлен рабочий журнал КС-6а — read-only представление фактически выполненных работ на основании Daily Reports.
|
||||||
|
|
||||||
|
## Отдельная модель/таблица
|
||||||
|
Не создавалась. КС-6а строится как read-only view над существующими `DailyReportItem` + `DailyReport` + `WorkItem` + `System` + `Section`. Каждая строка = один `DailyReportItem`.
|
||||||
|
|
||||||
|
## Changed files — production
|
||||||
|
|
||||||
|
### app/routers/ks6a.py (new)
|
||||||
|
- GET `/{project_id}/ks6a` — страница журнала
|
||||||
|
- Параметры: `date_from`, `date_to` (обязательные для формирования), `system_id` (опциональный)
|
||||||
|
- Валидация: `date_to >= date_from`
|
||||||
|
- Единый запрос с `joinedload(DailyReportItem.work_item)` и `joinedload(DailyReportItem.report)` — без N+1
|
||||||
|
- Фильтр по системе через `join(WorkItem).filter(WorkItem.system_id == sid)`
|
||||||
|
- Jinja2-фильтр `quantity2` для формата `X.XX`
|
||||||
|
|
||||||
|
### app/templates/ks6a/journal.html (new)
|
||||||
|
- Форма периода + фильтр системы
|
||||||
|
- Таблица: Дата, Система, Раздел, № поз., Наименование, Ед., Кол-во
|
||||||
|
- `<colgroup>` с фиксированной шириной, `table-layout: fixed`
|
||||||
|
- Количества — формат `quantity2` (2 знака)
|
||||||
|
- Навигация «← К проекту»
|
||||||
|
- Нет денег, цен, сумм
|
||||||
|
|
||||||
|
### app/main.py
|
||||||
|
Регистрация роутера `ks6a` с prefix `/projects`.
|
||||||
|
|
||||||
|
### app/templates/projects/detail.html
|
||||||
|
Кнопка «КС-6а» в навигации проекта.
|
||||||
|
|
||||||
|
## Источник данных
|
||||||
|
- `DailyReportItem` (факт)
|
||||||
|
- `DailyReport` (дата, проект)
|
||||||
|
- `WorkItem` (наименование, ед., система, раздел)
|
||||||
|
- `System` / `Section` (через WorkItem)
|
||||||
|
|
||||||
|
## Фильтры
|
||||||
|
- Период (date_from, date_to) — оба обязательны
|
||||||
|
- Система — «Все системы» или конкретная
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
### tests/test_ks6a.py (new)
|
||||||
|
`test_ks6a_full_workflow` — покрывает все 11 требований:
|
||||||
|
|
||||||
|
1. Страница КС-6а открывается (200, заголовок)
|
||||||
|
2. Отображается выбранный период
|
||||||
|
3. Все DailyReportItem попадают в журнал (5 строк)
|
||||||
|
4. Каждая DailyReportItem — отдельная строка (3× трубы + 2× кабеля)
|
||||||
|
5. Фильтр по системе работает (только Система A → 3 строки)
|
||||||
|
6. Фильтр по периоду работает (01–03.03 → 2 строки)
|
||||||
|
7. `date_to < date_from` отклоняется
|
||||||
|
8. KS-2 не влияет на КС-6а (после проведения всё те же 5 строк)
|
||||||
|
9. Цены и суммы не попадают (нет ₽, нет колонок Цена/Сумма)
|
||||||
|
10. Несколько DailyReportItem одного WorkItem не агрегируются (3 отдельные строки)
|
||||||
|
11. Количество с двумя знаками (10.00, 15.00, 5.00)
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks6a.py -v
|
||||||
|
```
|
||||||
|
1 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 41 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- КС-6а не содержит денежных значений (по заданию)
|
||||||
|
- Нет экспорта PDF/Excel (по заданию)
|
||||||
|
- Нет колонки «Закрыто KS-2» (по заданию)
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Implementation Report: 009-ks3
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Реализован полный цикл КС-3: модель, сервис, роутер, UI (создание/редактирование/просмотр/выпуск), тесты.
|
||||||
|
|
||||||
|
## Модели / миграция
|
||||||
|
|
||||||
|
### app/models/ks3.py (new)
|
||||||
|
- `KS3` — документ КС-3: id, project_id, number, date, reporting_period_from/to, comment, status (draft/issued), created_at, updated_at
|
||||||
|
- `KS3KS2` — связь many-to-many КС-3 ↔ КС-2: id, ks3_id (FK → ks3_documents), ks2_id (FK → ks2_documents), UNIQUE(ks3_id, ks2_id)
|
||||||
|
- Таблицы создаются через `Base.metadata.create_all` (аналогично KS2, KS2Item)
|
||||||
|
|
||||||
|
### app/main.py
|
||||||
|
- Импорт `ks3_models` для регистрации таблиц
|
||||||
|
- Регистрация роутера `ks3` с prefix `/projects`
|
||||||
|
|
||||||
|
### app/templates/projects/detail.html
|
||||||
|
- Кнопка «КС-3» в навигации проекта
|
||||||
|
|
||||||
|
## Сервис — app/services/ks3_service.py (new)
|
||||||
|
|
||||||
|
### Бизнес-правила
|
||||||
|
- КС-3 = финансовый свод issued КС-2
|
||||||
|
- Сумма = SUM(KS2Item.amount) выбранных КС-2
|
||||||
|
- Один КС-2 нельзя выбрать дважды в одном КС-3
|
||||||
|
- Нельзя выбрать draft КС-2 или КС-2 другого проекта
|
||||||
|
- Повторное проведение КС-3 в разных КС-3 НЕ запрещено (по заданию)
|
||||||
|
- КС-3 не изменяет КС-2 или Daily Reports
|
||||||
|
- При выпуске повторная валидация всех выбранных КС-2 + атомарность
|
||||||
|
|
||||||
|
### Функции
|
||||||
|
- `save_draft()` — создание/обновление draft с валидацией периода и КС-2
|
||||||
|
- `issue_ks3()` — выпуск с повторной проверкой, атомарный
|
||||||
|
- `available_ks2()` — список issued КС-2 проекта
|
||||||
|
- `project_ks3_totals()` — все КС-3 проекта с суммами
|
||||||
|
|
||||||
|
## Роутер — app/routers/ks3.py (new)
|
||||||
|
- GET `/{project_id}/ks3` — список
|
||||||
|
- GET `/{project_id}/ks3/new` — форма создания
|
||||||
|
- POST `/{project_id}/ks3` — создание
|
||||||
|
- GET `/{project_id}/ks3/{ks3_id}` — просмотр
|
||||||
|
- GET `/{project_id}/ks3/{ks3_id}/edit` — форма редактирования
|
||||||
|
- POST `/{project_id}/ks3/{ks3_id}/edit` — обновление
|
||||||
|
- POST `/{project_id}/ks3/{ks3_id}/issue` — выпуск
|
||||||
|
|
||||||
|
## Шаблоны
|
||||||
|
- `app/templates/ks3/list.html` — список: №, дата, период, статус, КС-2, сумма, действия
|
||||||
|
- `app/templates/ks3/form.html` — форма: номер, дата, период, комментарий, таблица выбора КС-2 (issued only)
|
||||||
|
- `app/templates/ks3/view.html` — просмотр: карточка, таблица КС-2 с суммами, итого, кнопки
|
||||||
|
|
||||||
|
## Tests — tests/test_ks3.py (new)
|
||||||
|
|
||||||
|
13 тестов, покрывающих все 13 требований:
|
||||||
|
|
||||||
|
1. `test_create_draft` — создание draft
|
||||||
|
2. `test_period_required` — обязательность периода
|
||||||
|
3. `test_period_validation` — date_to >= date_from
|
||||||
|
4. `test_select_single_ks2` — выбор одного КС-2
|
||||||
|
5. `test_select_multiple_ks2` — выбор нескольких КС-2
|
||||||
|
6. `test_cannot_select_draft_ks2` — нельзя выбрать draft КС-2
|
||||||
|
7. `test_cannot_select_other_project_ks2` — нельзя выбрать КС-2 другого проекта
|
||||||
|
8. `test_ks3_amount_equals_sum_of_issued_ks2` — сумма = SUM(issued КС-2)
|
||||||
|
9. `test_ks3_does_not_modify_ks2` — КС-3 не изменяет КС-2
|
||||||
|
10. `test_issue_ks3` — выпуск КС-3
|
||||||
|
11. `test_issued_ks3_cannot_be_edited` — issued нельзя редактировать
|
||||||
|
12. `test_duplicate_ks2_in_same_ks3_rejected` — дублирование КС-2 запрещено
|
||||||
|
13. `test_issue_atomicity` — выпуск атомарен при некорректном состоянии КС-2
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks3.py -v
|
||||||
|
```
|
||||||
|
13 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 54 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- Нет экспорта Excel/Word/PDF (по заданию)
|
||||||
|
- Нет платежей (по заданию)
|
||||||
|
- Один и тот же КС-2 можно использовать в разных КС-3 (бизнес-правило пока не определено — по заданию)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Implementation Report: 010-ks3-count
|
||||||
|
|
||||||
|
## Status
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
Добавлен счётчик КС-3 в кнопку навигации проекта: `КС-3 (N)`.
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
|
||||||
|
### app/routers/projects.py
|
||||||
|
- Импорт `KS3` из `app.models.ks3`
|
||||||
|
- Добавлен `ks3_count = db.query(KS3).filter(KS3.project_id == project_id).count()`
|
||||||
|
- Передаётся `ks3_count` в контекст шаблона
|
||||||
|
|
||||||
|
### app/templates/projects/detail.html
|
||||||
|
- Кнопка `КС-3` → `КС-3{% if ks3_count %} ({{ ks3_count }}){% endif %}`
|
||||||
|
|
||||||
|
### tests/test_ks3.py
|
||||||
|
- Добавлен `test_ks3_count_on_project_page` — проверяет:
|
||||||
|
- без КС-3 — кнопка без счётчика
|
||||||
|
- 1 КС-3 → `КС-3 (1)`
|
||||||
|
- 2 КС-3 → `КС-3 (2)`
|
||||||
|
|
||||||
|
## Verification results
|
||||||
|
|
||||||
|
### python -m pytest tests/test_ks3.py -v
|
||||||
|
```
|
||||||
|
14 passed, 1 warning
|
||||||
|
```
|
||||||
|
|
||||||
|
### python -m pytest -q
|
||||||
|
```
|
||||||
|
1 failed, 55 passed, 28 warnings
|
||||||
|
```
|
||||||
|
Единственный падающий — `test_project_work_journal_crud_and_dashboard_warnings` (pre-existing).
|
||||||
|
|
||||||
|
### git diff --check
|
||||||
|
Ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
None.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Implementation Report — Task 011: Платежи
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
## What was done
|
||||||
|
|
||||||
|
Реализован полный цикл работы с платежами (Payment):
|
||||||
|
|
||||||
|
1. **Модели** — `Payment` и `PaymentAllocation` с Numeric(18,2) для денег, UniqueConstraint(payment_id, ks3_id), CheckConstraint(amount > 0), cascade delete.
|
||||||
|
2. **Сервис** (`payment_service.py`) — бизнес-логика создания/редактирования/удаления платежей с распределением по КС-3. Валидация: сумма > 0, валюта обязательна, allocation > 0, сумма allocations ≤ сумма платежа, нельзя превысить outstanding КС-3, нельзя распределять на draft КС-3 или КС-3 другого проекта, один КС-3 не может быть дважды в одном платеже. Атомарность при rollback.
|
||||||
|
3. **Роутер** (`payments.py`) — CRUD: список, создание, просмотр, редактирование, удаление. Серверная валидация allocations из формы.
|
||||||
|
4. **Шаблоны**:
|
||||||
|
- `list.html` — таблица с датой, номером документа, суммой, валютой, распределено/не распределено, КС-3, действия (просмотр, редактировать, удалить);
|
||||||
|
- `form.html` — форма платежа + таблица распределения по issued КС-3 с показом суммы, оплачено, остаток;
|
||||||
|
- `view.html` — реквизиты, сумма, распределено/не распределено, таблица allocations, кнопки редактировать/удалить.
|
||||||
|
5. **Страница проекта** (`detail.html`) — кнопка «Платежи (N)» в навигации, секция «Оплата по КС-3» с карточками: всего КС-3, сумма КС-3, оплачено, задолженность.
|
||||||
|
6. **Регистрация** — роутер и модели добавлены в `main.py`, счётчики и `payment_summary` передаются в `projects.py`.
|
||||||
|
|
||||||
|
## Changed files
|
||||||
|
|
||||||
|
### Созданы
|
||||||
|
- `app/models/payment.py` — модели Payment, PaymentAllocation
|
||||||
|
- `app/services/payment_service.py` — бизнес-логика платежей
|
||||||
|
- `app/routers/payments.py` — роутер CRUD
|
||||||
|
- `app/templates/payments/list.html` — список платежей
|
||||||
|
- `app/templates/payments/form.html` — форма создания/редактирования
|
||||||
|
- `app/templates/payments/view.html` — просмотр платежа
|
||||||
|
- `tests/test_payments.py` — 26 тестов
|
||||||
|
- `docs/tasks/011-payments.md` — task-файл
|
||||||
|
|
||||||
|
### Изменены
|
||||||
|
- `app/main.py` — импорт моделей, регистрация роутера payments
|
||||||
|
- `app/routers/projects.py` — счётчики ks3_count, payments_count, payment_summary
|
||||||
|
- `app/templates/projects/detail.html` — кнопка «Платежи», секция «Оплата по КС-3»
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- Создан `tests/test_payments.py` с 26 тестами (21 обязательных по task + 5 дополнительных).
|
||||||
|
- Результат `python -m pytest tests/test_payments.py -q`: **26 passed**.
|
||||||
|
- Результат `python -m pytest -q` (все тесты): **81 passed, 1 failed**.
|
||||||
|
- Падающий тест `test_work_journal.py::test_project_work_journal_crud_and_dashboard_warnings` — **pre-existing**, падал до начала работы над 011 (не связан с платежами).
|
||||||
|
- Результат `git diff --check`: чисто, ошибок нет.
|
||||||
|
|
||||||
|
## Deviations
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Follow-up / Open Questions
|
||||||
|
|
||||||
|
- Тест `test_work_journal.py::test_project_work_journal_crud_and_dashboard_warnings` падает — это pre-existing проблема, не связанная с платежами. Требует отдельной задачи.
|
||||||
|
- Экспорт Excel/Word/PDF не реализован (по task-файлу — не требуется на этом этапе).
|
||||||
|
- Денежные значения в проекте используют Decimal через Numeric(18,2) в SQLAlchemy, float не используется.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Implementation Report — Task 012
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
### What was done
|
||||||
|
|
||||||
|
Закрыт технический долг перед экспортом в Excel/Word. Работа проводилась по разделам task-файла.
|
||||||
|
|
||||||
|
**1.6 Рабочий журнал — pre-existing failing test (КРИТИЧНО)**
|
||||||
|
|
||||||
|
`tests/test_work_journal.py::test_project_work_journal_crud_and_dashboard_warnings` падал из-за зависимости от конкретного состояния БД: тест проверял наличие over-plan предупреждений для проекта 2, но в БД не было данных с превышением плана. Исправлено: тест теперь сам создаёт over-plan данные (DailyReport + DailyReportItem с количеством выше плана) перед проверками. Все функции сохранены: CRUD журнала, task checkbox, отображение на dashboard, dashboard warnings.
|
||||||
|
|
||||||
|
**1.3 Счётчик ведомостей**
|
||||||
|
|
||||||
|
Добавлен счётчик `Ведомости (N)` в навигации проекта (N = количество base BOQ documents).
|
||||||
|
|
||||||
|
**1.4 Счётчик дополнительных соглашений**
|
||||||
|
|
||||||
|
Добавлен счётчик `Дополнительные соглашения (N)` в навигации проекта (N = количество всех ДС проекта).
|
||||||
|
|
||||||
|
**2. Навигация проекта**
|
||||||
|
|
||||||
|
Навигация приведена к единому виду:
|
||||||
|
- `Ведомости (N)` — добавлен счётчик
|
||||||
|
- `Дополнительные соглашения (N)` — добавлен счётчик
|
||||||
|
- `Daily Reports (N)` — был
|
||||||
|
- `КС-2 (N)` — был
|
||||||
|
- `КС-3 (N)` — был
|
||||||
|
- `КС-6а` — без счётчика (по task)
|
||||||
|
- `Платежи (N)` — был
|
||||||
|
|
||||||
|
**4. Финансовая приватность**
|
||||||
|
|
||||||
|
Реализован eye-механизм (`👁` кнопка) на всех финансовых страницах:
|
||||||
|
- Dashboard (`projects/detail.html`)
|
||||||
|
- Ведомость (`boq_document.html`)
|
||||||
|
- КС-2 (`base.html` через наследование)
|
||||||
|
- КС-3 (`base.html`)
|
||||||
|
- Платежи (`base.html`)
|
||||||
|
|
||||||
|
Механика: CSS-класс `money-value` + blur при `money-hidden`. Кнопка переключает видимость локально (не сохраняется глобально). Количества и проценты остаются видимыми. Не является access control — защита от случайного просмотра.
|
||||||
|
|
||||||
|
**5. Ведомость — microstats**
|
||||||
|
|
||||||
|
В строках WorkItem добавлены:
|
||||||
|
- Текст `Выполнено: X / Y`
|
||||||
|
- Progress bar с цветовой логикой:
|
||||||
|
- 0% — серый (нейтральный)
|
||||||
|
- 1–49% — жёлтый
|
||||||
|
- 50–99% — синий
|
||||||
|
- 100% — зелёный
|
||||||
|
- >100% — красный
|
||||||
|
|
||||||
|
**1.5 Daily Reports — защита закрытых в КС-2 позиций**
|
||||||
|
|
||||||
|
Добавлена критическая защита:
|
||||||
|
- При редактировании: нельзя изменить/удалить количество, закрытое в КС-2 (проверка на уровне позиции)
|
||||||
|
- При удалении: нельзя удалить отчёт, содержащий позиции закрытые в КС-2
|
||||||
|
- Добавлен endpoint `POST /{project_id}/daily-reports/{report_id}/delete`
|
||||||
|
|
||||||
|
**7. UI — количество в КС-2 с двумя знаками**
|
||||||
|
|
||||||
|
В `ks2/view.html` количество отображается через фильтр `quantity2` (два знака после запятой).
|
||||||
|
|
||||||
|
**8. Кодовая чистка**
|
||||||
|
|
||||||
|
- Удалён неиспользуемый импорт `List` из `app/routers/boq.py`
|
||||||
|
- Не обнаружено: debug-кода, TODO/FIXME, мёртвого кода
|
||||||
|
|
||||||
|
### Changed files
|
||||||
|
|
||||||
|
**Изменённые:**
|
||||||
|
- `app/routers/boq.py` — добавлен `_completed_quantities()`, удалён unused `List` import
|
||||||
|
- `app/routers/daily_reports.py` — добавлена защита KS-2 closed items, endpoint delete
|
||||||
|
- `app/routers/projects.py` — добавлен `agreements_count`
|
||||||
|
- `app/templates/base.html` — financial privacy (eye icon, CSS, JS)
|
||||||
|
- `app/templates/ks2/list.html` — `money-value` class
|
||||||
|
- `app/templates/ks2/view.html` — `money-value` class, `quantity2` filter
|
||||||
|
- `app/templates/projects/boq_document.html` — microstats, financial privacy
|
||||||
|
- `app/templates/projects/detail.html` — счётчики `Ведомости (N)`, `Дополнительные соглашения (N)`, financial privacy
|
||||||
|
- `tests/test_work_journal.py` — self-contained over-plan данные
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
**Изменённые тесты:**
|
||||||
|
- `tests/test_work_journal.py` — добавлено создание over-plan данных для детерминированности
|
||||||
|
|
||||||
|
**Проверки:**
|
||||||
|
- `python -m pytest -q` → `82 passed, 0 failed`
|
||||||
|
- `git diff --check` → чисто (только CRLF warnings, не ошибки)
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Follow-up / Open Questions
|
||||||
|
|
||||||
|
1. `app/database/database.py:20` — `declarative_base()` deprecated warning (SQLAlchemy 2.0). Не относится к scope 012.
|
||||||
|
2. `openpyxl` — `datetime.utcnow()` deprecation warnings в тестах. Не относится к scope 012.
|
||||||
|
3. КС-2/КС-3 regression testing (раздел 6 task) — бизнес-правила не изменялись, существующие тесты (82 passed) подтверждают корректность. Детальная ручная проверка UI-форм не выполнялась.
|
||||||
|
4. Проекты/ведомости: физическое удаление не реализовано → данные не могут быть разрушены (безопасное состояние).
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user