chore: baseline before agreements
This commit is contained in:
+48
@@ -0,0 +1,48 @@
|
||||
# Python bytecode and virtual environments
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# Test and tool caches
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Local databases and database sidecar files
|
||||
*.db
|
||||
*.db-*
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.sqlite-*
|
||||
|
||||
# Uploaded/project spreadsheets and Excel temporary files
|
||||
*.xlsx
|
||||
*.xls
|
||||
*.xlsm
|
||||
~$*
|
||||
app/uploads/
|
||||
uploads/
|
||||
|
||||
# Environment configuration and credentials
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
*.key
|
||||
secrets.*
|
||||
|
||||
# Temporary/editor/OS files
|
||||
*.tmp
|
||||
*.temp
|
||||
*.bak
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,49 @@
|
||||
# Work Volume Tracker
|
||||
|
||||
A simple local web application for tracking completed work volumes in projects.
|
||||
|
||||
## Features
|
||||
- Project management
|
||||
- Excel import for BOQ (Bill of Quantities)
|
||||
- Work item tracking with systems and sections
|
||||
- SQLite database storage
|
||||
|
||||
## Setup
|
||||
|
||||
1. Create virtual environment:
|
||||
```bash
|
||||
python -m venv .venv
|
||||
```
|
||||
|
||||
2. Activate virtual environment:
|
||||
- Linux/macOS:
|
||||
```bash
|
||||
source .venv/bin/activate
|
||||
```
|
||||
- Windows:
|
||||
```cmd
|
||||
.venv\Scripts\activate
|
||||
```
|
||||
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. Run the application:
|
||||
```bash
|
||||
uvicorn app.main:app --reload
|
||||
```
|
||||
|
||||
5. Access the application at http://localhost:8000
|
||||
|
||||
## Project Structure
|
||||
- `app/` - Main application directory
|
||||
- `main.py` - FastAPI application entry point
|
||||
- `models/` - Database models
|
||||
- `routers/` - API routers
|
||||
- `database/` - Database connection and initialization
|
||||
- `templates/` - HTML templates
|
||||
- `static/` - Static files (CSS, JS, images)
|
||||
- `utils/` - Utility functions
|
||||
- `importer/` - Excel import functionality
|
||||
@@ -0,0 +1,3 @@
|
||||
# Database initialization
|
||||
# This file is now just a placeholder to avoid circular imports
|
||||
# The actual initialization is done in main.py
|
||||
@@ -0,0 +1,28 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from pathlib import Path
|
||||
|
||||
# Keep SQLite anchored to the project, independent of the process working directory.
|
||||
DATABASE_PATH = Path(__file__).resolve().with_name("work_tracker.db")
|
||||
DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# SQLAlchemy accepts an absolute SQLite URL in this form on Windows and Unix.
|
||||
DATABASE_URL = f"sqlite:///{DATABASE_PATH.as_posix()}"
|
||||
|
||||
# Create engine
|
||||
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
||||
|
||||
# Create session
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Base class for models
|
||||
Base = declarative_base()
|
||||
|
||||
# Dependency to get database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,208 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import openpyxl
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import boq
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedRow:
|
||||
row_number: int
|
||||
kind: str
|
||||
values: Dict[str, Any]
|
||||
system: Optional[str] = None
|
||||
section: Optional[str] = None
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
def _is_number(value: Any) -> bool:
|
||||
if isinstance(value, bool) or value is None:
|
||||
return False
|
||||
if isinstance(value, (int, float, Decimal)):
|
||||
return True
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
Decimal(value.strip().replace(" ", "").replace(",", "."))
|
||||
return bool(value.strip())
|
||||
except InvalidOperation:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _decimal(value: Any, row_number: int, label: str, errors: List[str]) -> Optional[Decimal]:
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value).strip().replace(" ", "").replace(",", "."))
|
||||
except (InvalidOperation, ValueError):
|
||||
errors.append(f"Строка {row_number}: в поле «{label}» некорректное число: {value!r}")
|
||||
return None
|
||||
|
||||
|
||||
def _row_level(ws, row_number: int) -> int:
|
||||
# Excel outline/indent metadata, when present, distinguishes nested headings
|
||||
row_dim = ws.row_dimensions[row_number]
|
||||
return int(row_dim.outlineLevel or 0) * 100 + int(row_dim.thickTop or 0)
|
||||
|
||||
|
||||
def _heading_kind(cell) -> Optional[str]:
|
||||
"""Use style/format characteristics, with style ids as workbook-specific hints."""
|
||||
if cell.style_id == 21:
|
||||
return "system"
|
||||
if cell.style_id == 19:
|
||||
return "section"
|
||||
fill = cell.fill
|
||||
color = fill.fgColor.rgb if fill and fill.fgColor.type == "rgb" else None
|
||||
size = cell.font.sz
|
||||
indent = cell.alignment.indent or 0
|
||||
if color and color[-6:].upper() in {"B4C6E7", "4472C4", "5B9BD5"} and size == 11:
|
||||
return "system"
|
||||
if color and color[-6:].upper() in {"E2EFDA", "70AD47", "A9D18E"} and size == 10 and indent > 0:
|
||||
return "section"
|
||||
return None
|
||||
|
||||
|
||||
def parse_excel_data(file_path: str, sheet_name: str, header_row: int = 5, start_row: int = 6) -> Dict[str, Any]:
|
||||
"""Parse the A:H BOQ layout once for both preview and database import."""
|
||||
wb = openpyxl.load_workbook(file_path, read_only=False, data_only=True)
|
||||
try:
|
||||
if sheet_name not in wb.sheetnames:
|
||||
raise ValueError(f"Лист {sheet_name!r} не найден. Доступны: {', '.join(wb.sheetnames)}")
|
||||
ws = wb[sheet_name]
|
||||
headers = [ws.cell(header_row, col).value for col in range(1, 9)]
|
||||
rows: List[ParsedRow] = []
|
||||
errors: List[str] = []
|
||||
current_system: Optional[str] = None
|
||||
current_section: Optional[str] = None
|
||||
prior_heading_level: Optional[int] = None
|
||||
|
||||
for row_number in range(start_row, ws.max_row + 1):
|
||||
values = [ws.cell(row_number, col).value for col in range(1, 9)]
|
||||
first = values[0]
|
||||
if all(v is None or (isinstance(v, str) and not v.strip()) for v in values):
|
||||
continue
|
||||
first_text = str(first).strip() if first is not None else ""
|
||||
if re.search(r"итого\s+по\s+(разделу|ведомости)", first_text, re.IGNORECASE):
|
||||
rows.append(ParsedRow(row_number, "total", {"raw": values}))
|
||||
continue
|
||||
if _is_number(first):
|
||||
row_errors: List[str] = []
|
||||
quantity = _decimal(values[5], row_number, "Кол-во", row_errors)
|
||||
price = _decimal(values[6], row_number, "Цена за ед.", row_errors)
|
||||
amount = _decimal(values[7], row_number, "Сумма", row_errors)
|
||||
if not str(values[1] or "").strip():
|
||||
row_errors.append(f"Строка {row_number}: не заполнено обязательное поле «Наименование»")
|
||||
errors.extend(row_errors)
|
||||
rows.append(ParsedRow(row_number, "item", {
|
||||
"source_number": str(first_text), "name": str(values[1]).strip() if values[1] is not None else "",
|
||||
"model": str(values[2]).strip() if values[2] is not None else None,
|
||||
"manufacturer": str(values[3]).strip() if values[3] is not None else None,
|
||||
"unit": str(values[4]).strip() if values[4] is not None else None,
|
||||
"quantity": quantity, "unit_price": price, "amount": amount,
|
||||
}, current_system, current_section, "; ".join(row_errors) or None))
|
||||
continue
|
||||
|
||||
# A non-numeric label in column A is a hierarchy heading. Determine
|
||||
# nesting from Excel outline metadata when available; otherwise the
|
||||
# first heading establishes a system and later headings establish sections.
|
||||
if not first_text:
|
||||
continue
|
||||
level = _row_level(ws, row_number)
|
||||
merged_heading = any(r.min_row == row_number and r.max_row == row_number
|
||||
and r.min_col == 1 and r.max_col >= 8
|
||||
for r in ws.merged_cells.ranges)
|
||||
heading_kind = _heading_kind(ws.cell(row_number, 1)) if merged_heading else None
|
||||
if heading_kind == "system" or (heading_kind is None and
|
||||
(current_system is None or level < (prior_heading_level or 0))):
|
||||
current_system, current_section = first_text, None
|
||||
rows.append(ParsedRow(row_number, "system", {}, current_system, None))
|
||||
elif heading_kind == "section" or level > (prior_heading_level or 0):
|
||||
current_section = first_text
|
||||
rows.append(ParsedRow(row_number, "section", {}, current_system, current_section))
|
||||
elif current_section is None:
|
||||
current_section = first_text
|
||||
rows.append(ParsedRow(row_number, "section", {}, current_system, current_section))
|
||||
else:
|
||||
# Same-level sibling after a section is a new section in the current system.
|
||||
current_section = first_text
|
||||
rows.append(ParsedRow(row_number, "section", {}, current_system, current_section))
|
||||
prior_heading_level = level
|
||||
|
||||
return {"headers": headers, "rows": rows, "errors": errors,
|
||||
"systems_count": len({r.system for r in rows if r.kind == "system"}),
|
||||
"sections_count": len({(r.system, r.section) for r in rows if r.kind == "section"}),
|
||||
"work_items_count": sum(r.kind == "item" for r in rows),
|
||||
"total_amount": sum((r.values["amount"] or Decimal("0")) for r in rows if r.kind == "item").quantize(Decimal("0.01")),
|
||||
"excel_total": sum((Decimal(str(r.values["raw"][7])) for r in rows if r.kind == "total"
|
||||
and re.search(r"по\s+ведомости", str(r.values["raw"][0]), re.IGNORECASE)
|
||||
and isinstance(r.values["raw"][7], (int, float, Decimal))), Decimal("0"))}
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def get_excel_sheets(file_path: str) -> List[str]:
|
||||
wb = openpyxl.load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
return wb.sheetnames
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def preview_excel_data(file_path: str, sheet_name: str, header_row: int, start_row: int) -> Dict[str, Any]:
|
||||
parsed = parse_excel_data(file_path, sheet_name, header_row, start_row)
|
||||
parsed["data"] = [r.values.get("raw", list(r.values.values())) for r in parsed["rows"][:20]]
|
||||
parsed["difference"] = parsed["total_amount"] - parsed["excel_total"]
|
||||
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]:
|
||||
parsed = parse_excel_data(file_path, sheet_name, header_row, start_row)
|
||||
if parsed["errors"]:
|
||||
raise ValueError("\n".join(parsed["errors"]))
|
||||
try:
|
||||
doc = boq.BoqDocument(project_id=project_id, name=f"Импорт ведомости — {sheet_name}",
|
||||
source_file=Path(file_path).name, version="1.0")
|
||||
db.add(doc)
|
||||
db.flush()
|
||||
systems: Dict[str, boq.System] = {}
|
||||
sections: Dict[tuple, boq.Section] = {}
|
||||
for row in parsed["rows"]:
|
||||
if row.kind == "system":
|
||||
if row.system not in systems:
|
||||
systems[row.system] = boq.System(project_id=project_id, name=row.system, code=None)
|
||||
db.add(systems[row.system])
|
||||
db.flush()
|
||||
elif row.kind == "section":
|
||||
key = (row.system, row.section)
|
||||
if row.system not in systems:
|
||||
systems[row.system] = boq.System(project_id=project_id, name=row.system, code=None)
|
||||
db.add(systems[row.system]); db.flush()
|
||||
if key not in sections:
|
||||
sections[key] = boq.Section(system_id=systems[row.system].id, name=row.section)
|
||||
db.add(sections[key]); db.flush()
|
||||
elif row.kind == "item":
|
||||
item = boq.WorkItem(project_id=project_id, boq_document_id=doc.id,
|
||||
system_id=systems[row.system].id if row.system in systems else None,
|
||||
section_id=sections[(row.system, row.section)].id if (row.system, row.section) in sections else None,
|
||||
**row.values)
|
||||
db.add(item)
|
||||
db.flush()
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
db_total = db.query(func.coalesce(func.sum(boq.WorkItem.amount), 0)).filter(
|
||||
boq.WorkItem.boq_document_id == doc.id
|
||||
).scalar()
|
||||
db_total_display = Decimal(str(db_total or 0)).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),
|
||||
"work_items": parsed["work_items_count"], "total_amount": db_total_display,
|
||||
"db_total": db_total_display, "excel_total": excel_total_display,
|
||||
"difference": db_total_display - excel_total_display}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi.responses import RedirectResponse
|
||||
from pathlib import Path
|
||||
|
||||
# Import routers
|
||||
from app.routers import projects, boq as boq_router, daily_reports
|
||||
|
||||
# Import models to ensure they're registered
|
||||
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 work_journal as work_journal_models
|
||||
|
||||
# Initialize database
|
||||
from app.database.database import engine
|
||||
from app.database.database import Base
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="Work Volume Tracker",
|
||||
description="A simple local web application for tracking completed work volumes in projects",
|
||||
version="0.1.0"
|
||||
)
|
||||
|
||||
# Resolve app resources relative to this module, not to the process working directory.
|
||||
APP_DIR = Path(__file__).resolve().parent
|
||||
app.mount("/static", StaticFiles(directory=APP_DIR / "static"), name="static")
|
||||
|
||||
# Create templates
|
||||
templates = Jinja2Templates(directory=APP_DIR / "templates")
|
||||
from app.utils.formatters import format_money
|
||||
templates.env.filters["money"] = format_money
|
||||
app.templates = templates
|
||||
|
||||
# Include routers
|
||||
app.include_router(projects.router, prefix="/projects", tags=["projects"])
|
||||
app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
|
||||
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def read_root():
|
||||
return RedirectResponse(url="/projects/", status_code=307)
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy"}
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="127.0.0.1", port=8000)
|
||||
@@ -0,0 +1,84 @@
|
||||
from sqlalchemy import Column, Integer, String, Date, DateTime, Text, ForeignKey, Numeric, Boolean
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.database.database import Base
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
class BoqDocument(Base):
|
||||
__tablename__ = "boq_documents"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
||||
agreement_id = Column(Integer) # nullable
|
||||
name = Column(String, nullable=False)
|
||||
version = Column(String)
|
||||
source_file = Column(String)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationship to project
|
||||
project = relationship("Project", back_populates="boq_documents")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<BoqDocument(id={self.id}, name='{self.name}')>"
|
||||
|
||||
class System(Base):
|
||||
__tablename__ = "systems"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
||||
code = Column(String, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
sort_order = Column(Integer, default=0)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationship to project
|
||||
project = relationship("Project", back_populates="systems")
|
||||
sections = relationship("Section", back_populates="system")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<System(id={self.id}, name='{self.name}')>"
|
||||
|
||||
class Section(Base):
|
||||
__tablename__ = "sections"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
system_id = Column(Integer, ForeignKey("systems.id"), nullable=False)
|
||||
name = Column(String, nullable=False)
|
||||
sort_order = Column(Integer, default=0)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationship to system
|
||||
system = relationship("System", back_populates="sections")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Section(id={self.id}, name='{self.name}')>"
|
||||
|
||||
class WorkItem(Base):
|
||||
__tablename__ = "work_items"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
||||
boq_document_id = Column(Integer, ForeignKey("boq_documents.id"), nullable=False)
|
||||
system_id = Column(Integer, ForeignKey("systems.id"))
|
||||
section_id = Column(Integer, ForeignKey("sections.id"))
|
||||
source_number = Column(String)
|
||||
name = Column(String, nullable=False)
|
||||
model = Column(String)
|
||||
manufacturer = Column(String)
|
||||
unit = Column(String)
|
||||
quantity = Column(Numeric(15, 4))
|
||||
# Imported workbook values can contain fractional cents while displaying to 2 places.
|
||||
unit_price = Column(Numeric(18, 12))
|
||||
amount = Column(Numeric(18, 12))
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||
|
||||
# Relationships
|
||||
project = relationship("Project")
|
||||
boq_document = relationship("BoqDocument")
|
||||
system = relationship("System")
|
||||
section = relationship("Section")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<WorkItem(id={self.id}, name='{self.name}')>"
|
||||
@@ -0,0 +1,33 @@
|
||||
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.database.database import Base
|
||||
|
||||
|
||||
class DailyReport(Base):
|
||||
__tablename__ = "daily_reports"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
system_id = Column(Integer, ForeignKey("systems.id"), nullable=False, index=True)
|
||||
report_date = Column(Date, nullable=False, index=True)
|
||||
notes = Column(Text)
|
||||
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")
|
||||
system = relationship("System")
|
||||
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class DailyReportItem(Base):
|
||||
__tablename__ = "daily_report_items"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
daily_report_id = Column(Integer, ForeignKey("daily_reports.id"), nullable=False, index=True)
|
||||
work_item_id = Column(Integer, ForeignKey("work_items.id"), nullable=False, index=True)
|
||||
completed_quantity = Column(Numeric(15, 4), nullable=False)
|
||||
|
||||
report = relationship("DailyReport", back_populates="items")
|
||||
work_item = relationship("WorkItem")
|
||||
@@ -0,0 +1,28 @@
|
||||
from sqlalchemy import Column, Integer, String, Date, DateTime, Text, Enum
|
||||
from sqlalchemy.sql import func
|
||||
from app.database.database import Base
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
class Project(Base):
|
||||
__tablename__ = "projects"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, index=True, nullable=False)
|
||||
contract_number = Column(String)
|
||||
contract_date = Column(Date)
|
||||
customer = Column(String)
|
||||
currency = Column(String, default="RUB")
|
||||
start_date = Column(Date)
|
||||
end_date = Column(Date)
|
||||
status = Column(String, default="active")
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||
|
||||
# Relationships
|
||||
boq_documents = relationship("BoqDocument", back_populates="project")
|
||||
systems = relationship("System", back_populates="project")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Project(id={self.id}, name='{self.name}')>"
|
||||
@@ -0,0 +1,20 @@
|
||||
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.database.database import Base
|
||||
|
||||
|
||||
class WorkJournalEntry(Base):
|
||||
__tablename__ = "work_journal_entries"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
type = Column(String(16), nullable=False)
|
||||
text = Column(Text, nullable=False)
|
||||
status = Column(String(16), nullable=True, default=None)
|
||||
due_date = Column(Date)
|
||||
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")
|
||||
@@ -0,0 +1,176 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import database
|
||||
from app.models import project, boq
|
||||
from app.importer import excel_importer
|
||||
from typing import List
|
||||
import os
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
router = APIRouter()
|
||||
UPLOAD_DIR = Path(__file__).resolve().parents[1] / "uploads"
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = database.SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/{project_id}")
|
||||
async def list_project_boq(request: Request, 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")
|
||||
documents = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.project_id == project_id
|
||||
).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).all()
|
||||
return request.app.templates.TemplateResponse("projects/boq_list.html", {
|
||||
"request": request, "project": db_project, "documents": documents,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/documents/{document_id}")
|
||||
async def view_boq_document(request: Request, project_id: int, document_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")
|
||||
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="BOQ document not found")
|
||||
document_title = document.name.replace("BOQ Import - ", "Импорт ведомости — ").replace(
|
||||
"BOQ Import — ", "Импорт ведомости — "
|
||||
)
|
||||
|
||||
items = db.query(boq.WorkItem).filter(
|
||||
boq.WorkItem.boq_document_id == document_id,
|
||||
).order_by(boq.WorkItem.id).all()
|
||||
system_ids = {item.system_id for item in items if item.system_id is not None}
|
||||
systems = db.query(boq.System).filter(
|
||||
boq.System.project_id == project_id,
|
||||
boq.System.id.in_(system_ids) if system_ids else False,
|
||||
).order_by(boq.System.sort_order, boq.System.id).all()
|
||||
tree = []
|
||||
total = Decimal("0.00")
|
||||
for system in systems:
|
||||
system_sections = db.query(boq.Section).filter(
|
||||
boq.Section.system_id == system.id,
|
||||
).order_by(boq.Section.sort_order, boq.Section.id).all()
|
||||
section_nodes = []
|
||||
system_total = Decimal("0.00")
|
||||
for section in system_sections:
|
||||
section_items = [item for item in items if item.section_id == section.id]
|
||||
section_total = sum((item.amount or Decimal("0.00") for item in section_items), Decimal("0.00"))
|
||||
section_nodes.append({"section": section, "items": section_items, "total": section_total})
|
||||
system_total += section_total
|
||||
# Keep system rows represented even if currently empty.
|
||||
tree.append({"system": system, "sections": section_nodes, "total": system_total})
|
||||
total += system_total
|
||||
|
||||
return request.app.templates.TemplateResponse("projects/boq_document.html", {
|
||||
"request": request, "project": db_project, "document": document,
|
||||
"document_title": document_title,
|
||||
"systems": tree, "total": total,
|
||||
"unassigned_items": [item for item in items if item.system_id is None or item.section_id is None],
|
||||
})
|
||||
|
||||
@router.post("/{project_id}/import/upload")
|
||||
async def upload_excel_file(
|
||||
request: Request,
|
||||
project_id: int,
|
||||
file: UploadFile = File(...),
|
||||
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")
|
||||
# Save the uploaded file
|
||||
filename = Path(file.filename or "upload.xlsx").name
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
file_location = UPLOAD_DIR / filename
|
||||
|
||||
with open(file_location, "wb+") as file_object:
|
||||
file_object.write(file.file.read())
|
||||
|
||||
# Get the sheets from the Excel file
|
||||
sheets = excel_importer.get_excel_sheets(file_location)
|
||||
|
||||
return request.app.templates.TemplateResponse("projects/import_sheet_selection.html", {
|
||||
"request": request,
|
||||
"project": db_project,
|
||||
"project_id": project_id,
|
||||
"filename": filename,
|
||||
"sheets": sheets
|
||||
})
|
||||
|
||||
@router.post("/{project_id}/import/preview")
|
||||
async def preview_import(
|
||||
request: Request,
|
||||
project_id: int,
|
||||
filename: str = Form(...),
|
||||
sheet_name: str = Form(...),
|
||||
header_row: int = Form(...),
|
||||
start_row: int = Form(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Get the file path
|
||||
file_path = UPLOAD_DIR / Path(filename).name
|
||||
|
||||
# Import and preview data
|
||||
try:
|
||||
preview_data = excel_importer.preview_excel_data(file_path, sheet_name, header_row, start_row)
|
||||
except (ValueError, OSError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
# Get project
|
||||
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")
|
||||
|
||||
return request.app.templates.TemplateResponse("projects/import_preview.html", {
|
||||
"request": request,
|
||||
"project": db_project,
|
||||
"preview_data": preview_data,
|
||||
"filename": filename,
|
||||
"sheet_name": sheet_name,
|
||||
"header_row": header_row,
|
||||
"start_row": start_row
|
||||
})
|
||||
|
||||
@router.post("/{project_id}/import/confirm")
|
||||
async def confirm_import(
|
||||
request: Request,
|
||||
project_id: int,
|
||||
filename: str = Form(...),
|
||||
sheet_name: str = Form(...),
|
||||
header_row: int = Form(...),
|
||||
start_row: int = Form(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Get the file path
|
||||
file_path = UPLOAD_DIR / Path(filename).name
|
||||
|
||||
# Import data into database
|
||||
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")
|
||||
try:
|
||||
result = excel_importer.import_excel_data(db, file_path, sheet_name, header_row, start_row, project_id)
|
||||
except (ValueError, OSError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
# Get project
|
||||
return request.app.templates.TemplateResponse("projects/import_confirm.html", {
|
||||
"request": request,
|
||||
"project": db_project,
|
||||
"import_result": result,
|
||||
"filename": filename,
|
||||
"sheet_name": sheet_name
|
||||
})
|
||||
@@ -0,0 +1,224 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database.database import SessionLocal
|
||||
from app.models import boq, project
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _project_or_404(db: Session, project_id: int):
|
||||
obj = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return obj
|
||||
|
||||
|
||||
def _report_or_404(db: Session, project_id: int, report_id: int):
|
||||
report = db.query(DailyReport).filter(
|
||||
DailyReport.id == report_id, DailyReport.project_id == project_id
|
||||
).first()
|
||||
if report is None:
|
||||
raise HTTPException(status_code=404, detail="Daily report not found")
|
||||
return report
|
||||
|
||||
|
||||
def _report_rows(db: Session, project_id: int, system_id: int, exclude_report_id=None):
|
||||
totals = db.query(
|
||||
DailyReportItem.work_item_id.label("work_item_id"),
|
||||
func.sum(DailyReportItem.completed_quantity).label("completed"),
|
||||
).join(DailyReport, DailyReport.id == DailyReportItem.daily_report_id).filter(
|
||||
DailyReport.project_id == project_id,
|
||||
)
|
||||
if exclude_report_id is not None:
|
||||
totals = totals.filter(DailyReport.id != exclude_report_id)
|
||||
totals = totals.group_by(DailyReportItem.work_item_id).subquery()
|
||||
items = db.query(boq.WorkItem, func.coalesce(totals.c.completed, 0)).outerjoin(
|
||||
totals, totals.c.work_item_id == boq.WorkItem.id
|
||||
).filter(
|
||||
boq.WorkItem.project_id == project_id,
|
||||
boq.WorkItem.system_id == system_id,
|
||||
).order_by(boq.WorkItem.section_id, boq.WorkItem.id).all()
|
||||
return [{"item": item, "accumulated": Decimal(str(completed or 0))} for item, completed in items]
|
||||
|
||||
|
||||
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None):
|
||||
systems = db.query(boq.System).filter(
|
||||
boq.System.project_id == project_obj.id,
|
||||
boq.System.id.in_(db.query(boq.WorkItem.system_id).filter(
|
||||
boq.WorkItem.project_id == project_obj.id,
|
||||
boq.WorkItem.system_id.is_not(None),
|
||||
).distinct()),
|
||||
).order_by(boq.System.sort_order, boq.System.id).all()
|
||||
selected_system = None
|
||||
rows = []
|
||||
current_quantities = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
|
||||
exclude_id = report.id if report else None
|
||||
if system_id:
|
||||
selected_system = next((s for s in systems if s.id == system_id), None)
|
||||
if selected_system is None:
|
||||
raise HTTPException(status_code=400, detail="System does not belong to this project")
|
||||
rows = _report_rows(db, project_obj.id, system_id, exclude_id)
|
||||
for row in rows:
|
||||
row["current_quantity"] = current_quantities.get(row["item"].id)
|
||||
planned = row["item"].quantity
|
||||
current = Decimal(str(row["current_quantity"] or 0))
|
||||
row["over_plan"] = planned is not None and row["accumulated"] + current > Decimal(str(planned))
|
||||
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
||||
"request": request, "project": project_obj, "systems": systems,
|
||||
"selected_system": selected_system, "rows": rows, "report": report,
|
||||
"errors": errors or [],
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/daily-reports")
|
||||
async def list_daily_reports(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project_obj = _project_or_404(db, project_id)
|
||||
reports = db.query(DailyReport).filter(
|
||||
DailyReport.project_id == project_id
|
||||
).order_by(DailyReport.report_date.desc(), DailyReport.id.desc()).all()
|
||||
return request.app.templates.TemplateResponse("projects/daily_reports.html", {
|
||||
"request": request, "project": project_obj, "reports": reports,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/daily-reports/new")
|
||||
async def new_daily_report(request: Request, project_id: int, system_id: int = None,
|
||||
db: Session = Depends(get_db)):
|
||||
return _render_form(request, db, _project_or_404(db, project_id), system_id)
|
||||
|
||||
|
||||
@router.post("/{project_id}/daily-reports")
|
||||
async def create_daily_report(request: Request, project_id: int,
|
||||
report_date: str = Form(...), system_id: int = Form(...),
|
||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
||||
project_obj = _project_or_404(db, project_id)
|
||||
try:
|
||||
parsed_date = date.fromisoformat(report_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||
system = db.query(boq.System).filter(
|
||||
boq.System.id == system_id, boq.System.project_id == project_id
|
||||
).first()
|
||||
if system is None:
|
||||
raise HTTPException(status_code=400, detail="System does not belong to this project")
|
||||
form = await request.form()
|
||||
quantities, errors = _quantities_from_form(form)
|
||||
if errors:
|
||||
return _render_form(request, db, project_obj, system_id, errors=errors)
|
||||
_validate_work_items(db, project_id, system_id, quantities)
|
||||
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
||||
notes=notes.strip() or None)
|
||||
for item_id, quantity in quantities.items():
|
||||
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
||||
db.add(report)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/daily-reports/{report_id}")
|
||||
async def view_daily_report(request: Request, project_id: int, report_id: int,
|
||||
db: Session = Depends(get_db)):
|
||||
project_obj = _project_or_404(db, project_id)
|
||||
report = _report_or_404(db, project_id, report_id)
|
||||
rows = _report_rows(db, project_id, report.system_id, report.id)
|
||||
lines = {line.work_item_id: line for line in report.items}
|
||||
displayed = []
|
||||
warnings = []
|
||||
for row in rows:
|
||||
line = lines.get(row["item"].id)
|
||||
if line is None:
|
||||
continue
|
||||
quantity = Decimal(str(line.completed_quantity))
|
||||
planned = row["item"].quantity
|
||||
row.update(current_quantity=quantity,
|
||||
over_plan=planned is not None and row["accumulated"] + quantity > Decimal(str(planned)))
|
||||
if row["over_plan"]:
|
||||
warnings.append(row)
|
||||
displayed.append(row)
|
||||
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
|
||||
"request": request, "project": project_obj, "report": report,
|
||||
"rows": displayed, "warnings": warnings,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/daily-reports/{report_id}/edit")
|
||||
async def edit_daily_report(request: Request, project_id: int, report_id: int,
|
||||
db: Session = Depends(get_db)):
|
||||
project_obj = _project_or_404(db, project_id)
|
||||
report = _report_or_404(db, project_id, report_id)
|
||||
return _render_form(request, db, project_obj, report.system_id, report)
|
||||
|
||||
|
||||
@router.post("/{project_id}/daily-reports/{report_id}/edit")
|
||||
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
||||
report_date: str = Form(...), system_id: int = Form(...),
|
||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
||||
project_obj = _project_or_404(db, project_id)
|
||||
report = _report_or_404(db, project_id, report_id)
|
||||
try:
|
||||
report.report_date = date.fromisoformat(report_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||
system = db.query(boq.System).filter(
|
||||
boq.System.id == system_id, boq.System.project_id == project_id
|
||||
).first()
|
||||
if system is None:
|
||||
raise HTTPException(status_code=400, detail="System does not belong to this project")
|
||||
form = await request.form()
|
||||
quantities, errors = _quantities_from_form(form)
|
||||
if errors:
|
||||
return _render_form(request, db, project_obj, report.system_id, report, errors)
|
||||
_validate_work_items(db, project_id, system_id, quantities)
|
||||
report.system_id = system_id
|
||||
report.notes = notes.strip() or None
|
||||
db.query(DailyReportItem).filter(DailyReportItem.daily_report_id == report.id).delete()
|
||||
report.items = [DailyReportItem(work_item_id=item_id, completed_quantity=quantity)
|
||||
for item_id, quantity in quantities.items()]
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||
|
||||
|
||||
def _quantities_from_form(form):
|
||||
quantities = {}
|
||||
errors = []
|
||||
for key, value in form.multi_items():
|
||||
if not key.startswith("quantity_") or not value.strip():
|
||||
continue
|
||||
try:
|
||||
item_id = int(key.removeprefix("quantity_"))
|
||||
quantity = Decimal(value.strip().replace(",", "."))
|
||||
if not quantity.is_finite() or quantity < 0:
|
||||
raise InvalidOperation
|
||||
except (ValueError, InvalidOperation):
|
||||
errors.append(f"Поле {key}: укажите неотрицательное число")
|
||||
continue
|
||||
if quantity > 0:
|
||||
quantities[item_id] = quantity
|
||||
if not quantities and not errors:
|
||||
errors.append("Добавьте хотя бы одну позицию с фактическим количеством больше нуля")
|
||||
return quantities, errors
|
||||
|
||||
|
||||
def _validate_work_items(db, project_id, system_id, quantities):
|
||||
valid_ids = {row[0] for row in db.query(boq.WorkItem.id).filter(
|
||||
boq.WorkItem.project_id == project_id,
|
||||
boq.WorkItem.system_id == system_id,
|
||||
boq.WorkItem.id.in_(quantities.keys()),
|
||||
).all()}
|
||||
if valid_ids != set(quantities):
|
||||
raise HTTPException(status_code=400, detail="Одна или несколько позиций не принадлежат выбранной системе проекта")
|
||||
@@ -0,0 +1,237 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import database
|
||||
from app.models import project
|
||||
from app.models import boq
|
||||
from app.services.project_dashboard import build_project_dashboard
|
||||
from app.models.daily_report import DailyReport
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from typing import List
|
||||
import os
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _journal_entry_or_404(db: Session, project_id: int, entry_id: int):
|
||||
entry = db.query(WorkJournalEntry).filter(
|
||||
WorkJournalEntry.id == entry_id,
|
||||
WorkJournalEntry.project_id == project_id,
|
||||
).first()
|
||||
if entry is None:
|
||||
raise HTTPException(status_code=404, detail="Journal entry not found")
|
||||
return entry
|
||||
|
||||
|
||||
def _journal_values(entry_type: str, entry_text: str, due_date: str | None):
|
||||
from datetime import date
|
||||
|
||||
entry_type = entry_type.strip()
|
||||
entry_text = entry_text.strip()
|
||||
if entry_type not in {"task", "note"}:
|
||||
raise HTTPException(status_code=422, detail="Type must be task or note")
|
||||
if not entry_text:
|
||||
raise HTTPException(status_code=422, detail="Text is required")
|
||||
if entry_type == "note":
|
||||
return entry_type, entry_text, None, None
|
||||
try:
|
||||
parsed_due_date = date.fromisoformat(due_date) if due_date else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail="Due date must use YYYY-MM-DD format") from exc
|
||||
return entry_type, entry_text, "open", parsed_due_date
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = database.SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@router.get("/")
|
||||
async def read_projects(request: Request, db: Session = Depends(get_db)):
|
||||
projects = db.query(project.Project).order_by(project.Project.created_at.desc()).all()
|
||||
return request.app.templates.TemplateResponse("projects/index.html", {
|
||||
"request": request,
|
||||
"projects": projects
|
||||
})
|
||||
|
||||
@router.get("/new")
|
||||
async def new_project(request: Request):
|
||||
return request.app.templates.TemplateResponse("projects/new.html", {"request": request})
|
||||
|
||||
@router.post("/create")
|
||||
async def create_project(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
name: str = Form(...),
|
||||
contract_number: str = Form(None),
|
||||
contract_date: str = Form(None),
|
||||
customer: str = Form(None),
|
||||
currency: str = Form("RUB"),
|
||||
start_date: str = Form(None),
|
||||
end_date: str = Form(None),
|
||||
status: str = Form("active")
|
||||
):
|
||||
# Convert string dates to date objects if provided
|
||||
from datetime import datetime
|
||||
contract_date_obj = datetime.strptime(contract_date, "%Y-%m-%d").date() if contract_date else None
|
||||
start_date_obj = datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else None
|
||||
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else None
|
||||
|
||||
db_project = project.Project(
|
||||
name=name,
|
||||
contract_number=contract_number,
|
||||
contract_date=contract_date_obj,
|
||||
customer=customer,
|
||||
currency=currency,
|
||||
start_date=start_date_obj,
|
||||
end_date=end_date_obj,
|
||||
status=status
|
||||
)
|
||||
|
||||
db.add(db_project)
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
|
||||
return RedirectResponse(url=f"/projects/{db_project.id}", status_code=303)
|
||||
|
||||
@router.get("/{project_id}")
|
||||
async def read_project(request: Request, 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")
|
||||
|
||||
# Get BOQ documents for this project
|
||||
boq_docs = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.project_id == project_id
|
||||
).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).all()
|
||||
dashboard = build_project_dashboard(db, db_project)
|
||||
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
|
||||
journal_tasks = db.query(WorkJournalEntry).filter(
|
||||
WorkJournalEntry.project_id == project_id,
|
||||
WorkJournalEntry.type == "task",
|
||||
WorkJournalEntry.status != "done",
|
||||
).order_by(WorkJournalEntry.due_date.is_(None), WorkJournalEntry.due_date,
|
||||
WorkJournalEntry.created_at.desc()).all()
|
||||
journal_notes = db.query(WorkJournalEntry).filter(
|
||||
WorkJournalEntry.project_id == project_id,
|
||||
WorkJournalEntry.type == "note",
|
||||
).order_by(WorkJournalEntry.created_at.desc(), WorkJournalEntry.id.desc()).limit(5).all()
|
||||
|
||||
return request.app.templates.TemplateResponse("projects/detail.html", {
|
||||
"request": request,
|
||||
"project": db_project,
|
||||
"boq_docs": boq_docs,
|
||||
"daily_reports_count": daily_reports,
|
||||
"journal_tasks": journal_tasks,
|
||||
"journal_notes": journal_notes,
|
||||
**dashboard,
|
||||
})
|
||||
|
||||
|
||||
@router.post("/{project_id}/journal")
|
||||
async def create_journal_entry(
|
||||
project_id: int,
|
||||
entry_type: str = Form(..., alias="type"),
|
||||
entry_text: str = Form(..., alias="text"),
|
||||
due_date: str = Form(""),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if db.query(project.Project.id).filter(project.Project.id == project_id).first() is None:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
entry_type, entry_text, status, parsed_due_date = _journal_values(entry_type, entry_text, due_date)
|
||||
db.add(WorkJournalEntry(project_id=project_id, type=entry_type, text=entry_text,
|
||||
status=status, due_date=parsed_due_date))
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/{project_id}/journal/{entry_id}")
|
||||
async def update_journal_entry(
|
||||
project_id: int,
|
||||
entry_id: int,
|
||||
entry_type: str = Form(..., alias="type"),
|
||||
entry_text: str = Form(..., alias="text"),
|
||||
due_date: str = Form(""),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
entry = _journal_entry_or_404(db, project_id, entry_id)
|
||||
entry_type, entry_text, next_status, parsed_due_date = _journal_values(entry_type, entry_text, due_date)
|
||||
entry.type = entry_type
|
||||
entry.text = entry_text
|
||||
entry.due_date = parsed_due_date
|
||||
entry.status = next_status if entry_type == "task" else None
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/{project_id}/journal/{entry_id}/toggle")
|
||||
async def toggle_journal_task(project_id: int, entry_id: int, db: Session = Depends(get_db)):
|
||||
entry = _journal_entry_or_404(db, project_id, entry_id)
|
||||
if entry.type != "task":
|
||||
raise HTTPException(status_code=400, detail="Only tasks have a status")
|
||||
entry.status = "done" if entry.status != "done" else "open"
|
||||
db.commit()
|
||||
return {"ok": True, "status": entry.status}
|
||||
|
||||
|
||||
@router.post("/{project_id}/journal/{entry_id}/delete")
|
||||
async def delete_journal_entry(project_id: int, entry_id: int, db: Session = Depends(get_db)):
|
||||
entry = _journal_entry_or_404(db, project_id, entry_id)
|
||||
db.delete(entry)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@router.get("/{project_id}/edit")
|
||||
async def edit_project(request: Request, 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")
|
||||
return request.app.templates.TemplateResponse("projects/edit.html", {
|
||||
"request": request, "project": db_project,
|
||||
})
|
||||
|
||||
|
||||
@router.post("/{project_id}/edit")
|
||||
async def update_project(
|
||||
project_id: int,
|
||||
name: str = Form(...),
|
||||
contract_number: str = Form(None),
|
||||
contract_date: str = Form(None),
|
||||
customer: str = Form(None),
|
||||
currency: str = Form("RUB"),
|
||||
start_date: str = Form(None),
|
||||
end_date: str = Form(None),
|
||||
status: str = Form("active"),
|
||||
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 datetime import datetime
|
||||
try:
|
||||
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.end_date = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Dates must use YYYY-MM-DD format") from exc
|
||||
db_project.name = name.strip()
|
||||
db_project.contract_number = contract_number.strip() if contract_number else None
|
||||
db_project.customer = customer.strip() if customer else None
|
||||
db_project.currency = currency.strip() if currency else "RUB"
|
||||
db_project.status = status
|
||||
db.commit()
|
||||
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/import")
|
||||
async def import_boq(request: Request, 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")
|
||||
|
||||
return request.app.templates.TemplateResponse("projects/import.html", {
|
||||
"request": request,
|
||||
"project": db_project
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from app.models import boq
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
|
||||
ZERO = Decimal("0.00")
|
||||
|
||||
|
||||
def _money(value):
|
||||
return Decimal(str(value)) if value is not None else ZERO
|
||||
|
||||
|
||||
def _round_money(value):
|
||||
return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def _item_plan_cost(item):
|
||||
if item.amount is not None:
|
||||
return _money(item.amount)
|
||||
if item.unit_price is not None and item.quantity is not None:
|
||||
return _money(item.unit_price) * _money(item.quantity)
|
||||
return ZERO
|
||||
|
||||
|
||||
def _performed_cost(item, quantity):
|
||||
if item.unit_price is None:
|
||||
return ZERO
|
||||
return _money(item.unit_price) * _money(quantity)
|
||||
|
||||
|
||||
def build_project_dashboard(db, project_obj):
|
||||
"""Build project dashboard aggregates from persisted BOQ and daily report rows."""
|
||||
current_boq = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.project_id == project_obj.id
|
||||
).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).first()
|
||||
|
||||
systems = db.query(boq.System).filter(
|
||||
boq.System.project_id == project_obj.id
|
||||
).order_by(boq.System.sort_order, boq.System.id).all()
|
||||
|
||||
items = []
|
||||
if current_boq:
|
||||
items = db.query(boq.WorkItem).filter(
|
||||
boq.WorkItem.boq_document_id == current_boq.id
|
||||
).order_by(boq.WorkItem.id).all()
|
||||
item_by_id = {item.id: item for item in items}
|
||||
|
||||
completed_by_item = {}
|
||||
if item_by_id:
|
||||
lines = db.query(DailyReportItem, DailyReport).join(
|
||||
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||
).filter(
|
||||
DailyReport.project_id == project_obj.id,
|
||||
DailyReportItem.work_item_id.in_(item_by_id),
|
||||
).all()
|
||||
for line, _report in lines:
|
||||
completed_by_item[line.work_item_id] = (
|
||||
completed_by_item.get(line.work_item_id, ZERO) + _money(line.completed_quantity)
|
||||
)
|
||||
|
||||
planned_total = _round_money(sum((_item_plan_cost(item) for item in items), ZERO))
|
||||
performed_total = _round_money(sum((
|
||||
_performed_cost(item, completed_by_item.get(item.id, ZERO)) for item in items
|
||||
), ZERO))
|
||||
remaining_total = planned_total - performed_total
|
||||
completion_percent = (performed_total / planned_total * Decimal("100")) if planned_total else ZERO
|
||||
|
||||
system_progress = []
|
||||
for system in systems:
|
||||
system_items = [item for item in items if item.system_id == system.id]
|
||||
plan = sum((_item_plan_cost(item) for item in system_items), ZERO)
|
||||
actual = sum((_performed_cost(item, completed_by_item.get(item.id, ZERO))
|
||||
for item in system_items), ZERO)
|
||||
percent = actual / plan * Decimal("100") if plan else ZERO
|
||||
system_progress.append({
|
||||
"system": system, "planned_cost": plan, "performed_cost": actual,
|
||||
"completion_percent": percent,
|
||||
})
|
||||
|
||||
over_plan_items = []
|
||||
for item in items:
|
||||
actual_quantity = completed_by_item.get(item.id, ZERO)
|
||||
if item.quantity is not None and actual_quantity > _money(item.quantity):
|
||||
over_plan_items.append({
|
||||
"item": item,
|
||||
"system": item.system,
|
||||
"planned_quantity": _money(item.quantity),
|
||||
"actual_quantity": actual_quantity,
|
||||
"excess_quantity": actual_quantity - _money(item.quantity),
|
||||
})
|
||||
warning_count = len(over_plan_items)
|
||||
|
||||
recent_reports = db.query(DailyReport).filter(
|
||||
DailyReport.project_id == project_obj.id
|
||||
).order_by(DailyReport.report_date.desc(), DailyReport.id.desc()).limit(5).all()
|
||||
recent_report_rows = []
|
||||
for report in recent_reports:
|
||||
report_lines = db.query(DailyReportItem, boq.WorkItem).join(
|
||||
boq.WorkItem, boq.WorkItem.id == DailyReportItem.work_item_id
|
||||
).filter(DailyReportItem.daily_report_id == report.id).all()
|
||||
report_volume = _round_money(sum((
|
||||
_performed_cost(item, line.completed_quantity) for line, item in report_lines
|
||||
), ZERO))
|
||||
system_names = sorted({item.system.name for _line, item in report_lines if item.system})
|
||||
recent_report_rows.append({
|
||||
"report": report,
|
||||
"systems": system_names or ([report.system.name] if report.system else []),
|
||||
"item_count": len(report_lines),
|
||||
"volume": report_volume,
|
||||
})
|
||||
|
||||
return {
|
||||
"current_boq": current_boq,
|
||||
"planned_cost": planned_total,
|
||||
"performed_cost": performed_total,
|
||||
"remaining_cost": remaining_total,
|
||||
"completion_percent": completion_percent,
|
||||
"system_progress": system_progress,
|
||||
"recent_reports": recent_report_rows,
|
||||
"over_plan_count": warning_count,
|
||||
"over_plan_items": over_plan_items,
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<!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>
|
||||
<div class="container mt-5">
|
||||
<h1 class="mb-4">Work Volume Tracker</h1>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h3>Projects</h3>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<a href="/projects/new" class="btn btn-primary mb-3">+ Новый проект</a>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Название</th>
|
||||
<th>Договор</th>
|
||||
<th>Заказчик</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colspan="6" class="text-center">Нет проектов</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,75 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ document_title }} — {{ project.name }}</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<main class="container my-4">
|
||||
<nav aria-label="Навигация" 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="/boq/{{ project.id }}">Ведомости</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Ведомость</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<div class="d-flex justify-content-between align-items-start mb-4">
|
||||
<div>
|
||||
<h1>{{ document_title }}</h1>
|
||||
<p class="text-muted mb-0">{{ project.name }}{% if document.source_file %} · {{ document.source_file }}{% endif %}</p>
|
||||
</div>
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}">К проекту</a>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-bordered table-sm align-middle">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for system_node in systems %}
|
||||
<tr class="table-primary">
|
||||
<th colspan="7">Система: {{ system_node.system.name }}</th>
|
||||
<th class="text-end">{{ system_node.total|money(project.currency) }}</th>
|
||||
</tr>
|
||||
{% for section_node in system_node.sections %}
|
||||
<tr class="table-success">
|
||||
<th colspan="7">Раздел: {{ section_node.section.name }}</th>
|
||||
<th class="text-end">{{ section_node.total|money(project.currency) }}</th>
|
||||
</tr>
|
||||
{% for item in section_node["items"] %}
|
||||
<tr>
|
||||
<td>{{ item.source_number or '' }}</td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td>{{ item.model or '' }}</td>
|
||||
<td>{{ item.manufacturer 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.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>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr><td colspan="8" class="text-center text-muted py-4">В документе нет рабочих позиций.</td></tr>
|
||||
{% endfor %}
|
||||
<tr class="table-dark fw-bold">
|
||||
<td colspan="7">Итого по ведомости</td>
|
||||
<td class="text-end">{{ total|money(project.currency) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% if unassigned_items %}
|
||||
<div class="alert alert-warning mt-3">В документе есть {{ unassigned_items|length }} позиций без полной привязки к системе и разделу.</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<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 aria-label="Навигация" 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 active" aria-current="page">Ведомости</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<div><h1 class="mb-1">Документы ведомости</h1><div class="text-muted">{{ project.name }}</div></div>
|
||||
<a class="btn btn-primary" href="/projects/{{ project.id }}/import">Импорт ведомости</a>
|
||||
</div>
|
||||
{% if documents %}
|
||||
<div class="list-group shadow-sm">
|
||||
{% 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 }}">
|
||||
<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 class="btn btn-sm btn-outline-primary">Открыть</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">Ведомостей пока нет. <a href="/projects/{{ project.id }}/import" class="alert-link">Импортировать первую</a>.</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,77 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<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">
|
||||
</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/{{ 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">{{ 'Редактирование' if report else 'Новый отчёт' }}</li></ol></nav>
|
||||
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
||||
{% 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">
|
||||
<label for="system-picker" class="form-label">Система</label>
|
||||
<div class="d-flex gap-2"><select id="system-picker" name="system_id" class="form-select" required>
|
||||
<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 %}
|
||||
</select><button class="btn btn-outline-primary" type="submit">Показать позиции</button></div>
|
||||
{% if report %}<div class="form-text">При смене системы сначала нажмите «Показать позиции»; несохранённые изменения формы будут сброшены.</div>{% endif %}
|
||||
</form>
|
||||
|
||||
{% if selected_system %}
|
||||
<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 }}">
|
||||
<div class="card card-body mb-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-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>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-header"><strong>{{ selected_system.name }}</strong> — укажите фактическое количество хотя бы для одной позиции</div>
|
||||
<div class="p-3 border-bottom">
|
||||
<label class="form-label" for="position-search">Поиск позиций</label>
|
||||
<input id="position-search" class="form-control" type="search" autocomplete="off" placeholder="Номер, наименование, модель или производитель">
|
||||
<div id="position-search-empty" class="form-text text-muted" hidden>Совпадений нет.</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.item.quantity if row.item.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>
|
||||
</form>
|
||||
<script>
|
||||
(() => {
|
||||
const search = document.getElementById('position-search');
|
||||
if (!search) return;
|
||||
const rows = [...document.querySelectorAll('.position-row')];
|
||||
const empty = document.getElementById('position-search-empty');
|
||||
const normalize = value => (value || '').toLocaleLowerCase('ru-RU').trim();
|
||||
search.addEventListener('input', () => {
|
||||
const query = normalize(search.value);
|
||||
let visible = 0;
|
||||
for (const row of rows) {
|
||||
const haystack = normalize(['number', 'name', 'model', 'manufacturer']
|
||||
.map(key => row.dataset[key]).join(' '));
|
||||
row.hidden = !haystack.includes(query);
|
||||
if (!row.hidden) visible++;
|
||||
}
|
||||
empty.hidden = visible !== 0;
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Daily Report {{ report.report_date.strftime('%d.%m.%Y') }} — {{ 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 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 }}</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>
|
||||
{% 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">
|
||||
<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>
|
||||
<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.item.quantity if row.item.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>
|
||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
||||
</table></div></div>
|
||||
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Daily Reports — {{ 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 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 active">Daily Reports</li></ol></nav>
|
||||
<div class="d-flex justify-content-between align-items-center mb-4"><div><h1>Daily Reports</h1><div class="text-muted">{{ project.name }}</div></div><a href="/projects/{{ project.id }}/daily-reports/new" class="btn btn-primary">Создать отчёт</a></div>
|
||||
{% if reports %}
|
||||
<div class="list-group shadow-sm">
|
||||
{% for report in reports %}
|
||||
<a href="/projects/{{ project.id }}/daily-reports/{{ report.id }}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
|
||||
<span><strong>{{ report.report_date.strftime('%d.%m.%Y') }}</strong> — {{ report.system.name }}{% if report.notes %}<br><small class="text-muted">{{ report.notes }}</small>{% endif %}</span>
|
||||
<span class="badge text-bg-primary rounded-pill">{{ report.items|length }} поз.</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}<div class="alert alert-info">Отчётов пока нет. Создайте первый Daily Report.</div>{% endif %}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,236 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{{ project.name }} — Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
.system-progress-table { min-width: 680px; table-layout: fixed; width: 100%; }
|
||||
.system-progress-table .system-name-cell { overflow-wrap: anywhere; }
|
||||
.system-progress-table .money-cell { min-width: 12rem; white-space: nowrap; }
|
||||
.system-progress-table .progress-cell { min-width: 14rem; }
|
||||
.system-progress-table .progress-summary { flex-wrap: nowrap; gap: .5rem; }
|
||||
.system-progress-table .progress-summary > * { white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<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>
|
||||
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
|
||||
<div>
|
||||
<h1 class="h2 mb-2">{{ project.name }}</h1>
|
||||
<div class="d-flex flex-wrap gap-3 text-secondary">
|
||||
<span>Договор: <strong class="text-dark">{{ project.contract_number or 'не указан' }}</strong></span>
|
||||
<span>Заказчик: <strong class="text-dark">{{ project.customer or 'не указан' }}</strong></span>
|
||||
<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>
|
||||
<span>Статус: <span class="badge text-bg-secondary">{{ project.status or 'не указан' }}</span></span>
|
||||
</div>
|
||||
{% if current_boq %}<div class="small text-muted mt-2">Текущая ведомость: {{ current_boq.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</div>{% endif %}
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<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 }}/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>
|
||||
</header>
|
||||
|
||||
<section class="mt-3" aria-live="polite">
|
||||
{% 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>
|
||||
{% else %}<div class="text-success small py-2">✓ Проверка плана: превышений нет</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="mb-4" aria-labelledby="kpi-heading">
|
||||
<h2 id="kpi-heading" class="h5 mb-3">План и выполнение</h2>
|
||||
<div class="row g-3">
|
||||
<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 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>
|
||||
<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>
|
||||
{% if not current_boq %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-8">
|
||||
<section class="card border-0 shadow-sm h-100">
|
||||
<div class="card-header bg-white"><h2 class="h5 mb-0">Прогресс по системам</h2></div>
|
||||
{% if system_progress %}
|
||||
<div class="table-responsive"><table class="table align-middle mb-0 system-progress-table">
|
||||
<colgroup><col><col style="width: 12rem"><col style="width: 12rem"><col style="width: 14rem"></colgroup>
|
||||
<thead><tr><th>Система</th><th class="text-end money-cell">План</th><th class="text-end money-cell">Выполнено</th><th class="progress-cell">Прогресс</th></tr></thead>
|
||||
<tbody>{% for row in system_progress %}
|
||||
<tr>
|
||||
<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">{{ 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>
|
||||
</tr>{% endfor %}</tbody>
|
||||
</table></div>
|
||||
{% else %}<div class="card-body text-muted">В проекте пока нет систем.</div>{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-4">
|
||||
<section class="card border-0 shadow-sm h-100">
|
||||
<div class="card-header bg-white d-flex justify-content-between align-items-center">
|
||||
<h2 class="h5 mb-0">Рабочий журнал</h2>
|
||||
<button class="btn btn-sm btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#journalModal" id="journal-add">+</button>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<h3 class="h6">Задачи</h3>
|
||||
<div id="journal-task-list">
|
||||
{% for entry in journal_tasks %}
|
||||
<div class="journal-entry border-bottom py-2" id="journal-entry-{{ entry.id }}">
|
||||
<div class="d-flex align-items-start gap-2">
|
||||
<input class="form-check-input journal-toggle mt-1" type="checkbox" aria-label="Отметить задачу выполненной" data-entry-id="{{ entry.id }}">
|
||||
<div class="flex-grow-1 min-w-0">
|
||||
<div class="journal-entry-text">{{ entry.text }}</div>
|
||||
{% if entry.due_date %}<small class="text-muted">Срок: {{ entry.due_date.strftime('%d.%m.%Y') }}</small>{% endif %}
|
||||
</div>
|
||||
<button type="button" class="btn btn-sm btn-link p-0 journal-edit" data-bs-toggle="modal" data-bs-target="#journalModal" data-entry-id="{{ entry.id }}" data-entry-type="task" data-entry-text="{{ entry.text }}" data-due-date="{{ entry.due_date.isoformat() if entry.due_date else '' }}" aria-label="Редактировать">✎</button>
|
||||
<button type="button" class="btn btn-sm btn-link text-danger p-0 journal-delete" data-entry-id="{{ entry.id }}" aria-label="Удалить">×</button>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}<div class="small text-muted mb-3" id="journal-no-tasks">Незавершённых задач нет.</div>{% endfor %}
|
||||
</div>
|
||||
<h3 class="h6 mt-3">Заметки</h3>
|
||||
{% for entry in journal_notes %}
|
||||
<div class="journal-entry border-bottom py-2" id="journal-entry-{{ entry.id }}">
|
||||
<div class="d-flex align-items-start gap-2">
|
||||
<div class="flex-grow-1 journal-entry-text">{{ entry.text }}</div>
|
||||
<button type="button" class="btn btn-sm btn-link p-0 journal-edit" data-bs-toggle="modal" data-bs-target="#journalModal" data-entry-id="{{ entry.id }}" data-entry-type="note" data-entry-text="{{ entry.text }}" data-due-date="" aria-label="Редактировать">✎</button>
|
||||
<button type="button" class="btn btn-sm btn-link text-danger p-0 journal-delete" data-entry-id="{{ entry.id }}" aria-label="Удалить">×</button>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}<div class="small text-muted">Заметок пока нет.</div>{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<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>
|
||||
{% 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>
|
||||
<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>
|
||||
</table></div>
|
||||
{% else %}<div class="card-body text-muted">Daily Reports ещё не создавались. Выполненные объёмы пока равны нулю.</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<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>
|
||||
{% 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>
|
||||
{% else %}<div class="card-body"><span class="text-muted">Ведомость не импортирована.</span> <a href="/projects/{{ project.id }}/import">Импортировать ведомость</a></div>{% endif %}
|
||||
</section>
|
||||
<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-header"><h2 class="modal-title fs-5" id="journalModalTitle">Запись рабочего журнала</h2><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button></div>
|
||||
<div class="modal-body">
|
||||
<input type="hidden" id="journal-entry-id">
|
||||
<div class="mb-3"><label class="form-label" for="journal-type">Тип записи</label><select class="form-select" id="journal-type" name="type"><option value="task">Задача</option><option value="note">Заметка</option></select></div>
|
||||
<div class="mb-3"><label class="form-label" for="journal-text">Текст</label><textarea class="form-control" id="journal-text" name="text" rows="3" required maxlength="4000"></textarea></div>
|
||||
<div class="mb-3" id="journal-due-wrap"><label class="form-label" for="journal-due-date">Срок</label><input class="form-control" id="journal-due-date" name="due_date" type="date"></div>
|
||||
<div class="text-danger small" id="journal-error" role="alert" hidden></div>
|
||||
</div>
|
||||
<div class="modal-footer"><button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Отмена</button><button class="btn btn-primary" type="submit">Сохранить</button></div>
|
||||
</form></div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="planWarningsModal" tabindex="-1" aria-labelledby="planWarningsTitle" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
|
||||
<div class="modal-header"><h2 class="modal-title fs-5" id="planWarningsTitle">Превышения планового количества</h2><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button></div>
|
||||
<div class="modal-body"><div class="table-responsive"><table class="table table-sm align-middle">
|
||||
<thead><tr><th>Система</th><th>Позиция</th><th class="text-end">Плановое количество</th><th class="text-end">Фактическое количество</th><th class="text-end">Превышение</th></tr></thead>
|
||||
<tbody>{% for warning in over_plan_items %}<tr><td>{{ warning.system.name if warning.system else '—' }}</td><td>{{ warning.item.source_number or '' }} {{ warning.item.name }}</td><td class="text-end">{{ warning.planned_quantity }}</td><td class="text-end">{{ warning.actual_quantity }}</td><td class="text-end">{{ warning.excess_quantity }}</td></tr>{% else %}<tr><td colspan="5" class="text-muted text-center">Превышений нет.</td></tr>{% endfor %}</tbody>
|
||||
</table></div></div>
|
||||
</div></div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
(() => {
|
||||
const projectId = {{ project.id }};
|
||||
const form = document.getElementById('journal-form');
|
||||
const modal = document.getElementById('journalModal');
|
||||
const type = document.getElementById('journal-type');
|
||||
const dueWrap = document.getElementById('journal-due-wrap');
|
||||
const dueDate = document.getElementById('journal-due-date');
|
||||
const entryId = document.getElementById('journal-entry-id');
|
||||
const text = document.getElementById('journal-text');
|
||||
const error = document.getElementById('journal-error');
|
||||
|
||||
function updateTypeFields() {
|
||||
const isTask = type.value === 'task';
|
||||
dueWrap.hidden = !isTask;
|
||||
if (!isTask) dueDate.value = '';
|
||||
}
|
||||
type.addEventListener('change', updateTypeFields);
|
||||
document.getElementById('journal-add').addEventListener('click', () => {
|
||||
entryId.value = '';
|
||||
type.value = 'task';
|
||||
text.value = '';
|
||||
dueDate.value = '';
|
||||
error.hidden = true;
|
||||
updateTypeFields();
|
||||
});
|
||||
document.querySelectorAll('.journal-edit').forEach(button => button.addEventListener('click', () => {
|
||||
entryId.value = button.dataset.entryId;
|
||||
type.value = button.dataset.entryType;
|
||||
text.value = button.dataset.entryText;
|
||||
dueDate.value = button.dataset.dueDate;
|
||||
error.hidden = true;
|
||||
updateTypeFields();
|
||||
}));
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
error.hidden = true;
|
||||
const id = entryId.value;
|
||||
const url = `/projects/${projectId}/journal${id ? `/${id}` : ''}`;
|
||||
try {
|
||||
const response = await fetch(url, {method: 'POST', body: new URLSearchParams(new FormData(form))});
|
||||
if (!response.ok) throw new Error('Не удалось сохранить запись. Проверьте введённые данные.');
|
||||
window.location.reload();
|
||||
} catch (e) {
|
||||
error.textContent = e.message;
|
||||
error.hidden = false;
|
||||
}
|
||||
});
|
||||
document.querySelectorAll('.journal-toggle').forEach(checkbox => checkbox.addEventListener('change', async () => {
|
||||
checkbox.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/projects/${projectId}/journal/${checkbox.dataset.entryId}/toggle`, {method: 'POST'});
|
||||
if (!response.ok) throw new Error('status');
|
||||
checkbox.closest('.journal-entry').remove();
|
||||
const list = document.getElementById('journal-task-list');
|
||||
if (!list.querySelector('.journal-entry')) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'small text-muted mb-3';
|
||||
empty.textContent = 'Незавершённых задач нет.';
|
||||
list.append(empty);
|
||||
}
|
||||
} catch {
|
||||
checkbox.checked = false;
|
||||
checkbox.disabled = false;
|
||||
}
|
||||
}));
|
||||
document.querySelectorAll('.journal-delete').forEach(button => button.addEventListener('click', async () => {
|
||||
if (!window.confirm('Удалить запись?')) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/projects/${projectId}/journal/${button.dataset.entryId}/delete`, {method: 'POST'});
|
||||
if (!response.ok) throw new Error('status');
|
||||
button.closest('.journal-entry').remove();
|
||||
window.location.reload();
|
||||
} catch {
|
||||
button.disabled = false;
|
||||
}
|
||||
}));
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
<!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" style="max-width: 900px">
|
||||
<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 active">Редактирование</li></ol></nav>
|
||||
<h1 class="h2 mb-4">Редактировать проект</h1>
|
||||
<form method="post" action="/projects/{{ project.id }}/edit" class="card border-0 shadow-sm">
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<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">
|
||||
{% 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 %}
|
||||
</select></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>
|
||||
</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>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Импорт ведомости - {{ project.name }} - Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Импорт ведомости</h1>
|
||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Загрузка Excel файла</h5>
|
||||
<form method="post" action="/boq/{{ project.id }}/import/upload" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label for="file" class="form-label">Выберите Excel файл</label>
|
||||
<input class="form-control" type="file" id="file" name="file" accept=".xlsx,.xls" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Загрузить</button>
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-secondary">Отмена</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Инструкция по импорту</h5>
|
||||
<ul>
|
||||
<li>Загрузите Excel файл с ведомостью объема работ</li>
|
||||
<li>Выберите лист в файле</li>
|
||||
<li>Настройте параметры импорта</li>
|
||||
<li>Просмотрите предварительный результат</li>
|
||||
<li>Подтвердите импорт</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,81 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Импорт завершен - {{ project.name }} - Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Импорт завершен</h1>
|
||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||
<p><strong>Файл:</strong> {{ filename }}</p>
|
||||
<p><strong>Лист:</strong> {{ sheet_name }}</p>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Результат импорта</h5>
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ import_result.systems }}</h3>
|
||||
<p class="card-text">Систем</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ import_result.sections }}</h3>
|
||||
<p class="card-text">Разделов</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ import_result.work_items }}</h3>
|
||||
<p class="card-text">Позиций</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ import_result.total_amount|money }}</h3>
|
||||
<p class="card-text">руб.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mt-3">
|
||||
<div class="col-md-6">
|
||||
<p><strong>Итог Excel:</strong> {{ import_result.excel_total|money }}</p>
|
||||
<p><strong>Сумма в базе данных:</strong> {{ import_result.db_total|money }}</p>
|
||||
<p><strong>Расхождение:</strong> {{ import_result.difference|money }}</p>
|
||||
{% if import_result.difference != 0 %}
|
||||
<div class="alert alert-warning">
|
||||
<strong>Внимание:</strong> Обнаружено расхождение между суммами!
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-success">
|
||||
<strong>Успех:</strong> Импорт завершен успешно. Расхождение отсутствует.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="/boq/{{ project.id }}" class="btn btn-success">Открыть ведомости проекта</a>
|
||||
<a href="/boq/{{ project.id }}/documents/{{ import_result.document_id }}" class="btn btn-outline-success">Открыть ведомость</a>
|
||||
<a href="/projects/{{ project.id }}" class="btn btn-primary">Перейти к проекту</a>
|
||||
<a href="/projects" class="btn btn-secondary">К списку проектов</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,109 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Предпросмотр импорта - {{ project.name }} - Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Предпросмотр импорта</h1>
|
||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||
<p><strong>Файл:</strong> {{ filename }}</p>
|
||||
<p><strong>Лист:</strong> {{ sheet_name }}</p>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Результат распознавания</h5>
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ preview_data.systems_count }}</h3>
|
||||
<p class="card-text">Систем</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ preview_data.sections_count }}</h3>
|
||||
<p class="card-text">Разделов</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ preview_data.work_items_count }}</h3>
|
||||
<p class="card-text">Рабочих позиций</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card text-center">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title">{{ preview_data.total_amount|money }}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mt-3">
|
||||
<div class="col-md-6">
|
||||
<p><strong>Итог Excel:</strong> {{ preview_data.excel_total|money }}</p>
|
||||
<p><strong>Расхождение:</strong> {{ preview_data.difference|money }}</p>
|
||||
{% if preview_data.difference != 0 %}
|
||||
<div class="alert alert-warning">
|
||||
<strong>Внимание:</strong> Обнаружено расхождение между суммами!
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Первые 20 распознанных рабочих позиций</h5>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Система</th>
|
||||
<th>Раздел</th>
|
||||
<th>Наименование</th>
|
||||
<th>Модель</th>
|
||||
<th>Производитель</th>
|
||||
<th>Ед. изм.</th>
|
||||
<th>Кол-во</th>
|
||||
<th>Цена</th>
|
||||
<th>Сумма</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<!-- In a real implementation, you'd iterate over the actual work items here -->
|
||||
<tr>
|
||||
<td colspan="10" class="text-center">Данные будут отображаться после импорта</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<form method="post" action="/boq/{{ project.id }}/import/confirm">
|
||||
<input type="hidden" name="filename" value="{{ filename }}">
|
||||
<input type="hidden" name="sheet_name" value="{{ sheet_name }}">
|
||||
<input type="hidden" name="header_row" value="{{ header_row }}">
|
||||
<input type="hidden" name="start_row" value="{{ start_row }}">
|
||||
<button type="submit" class="btn btn-success">Импортировать</button>
|
||||
<a href="/projects/{{ project.id }}/import" class="btn btn-secondary">Назад</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,62 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Выбор листа - {{ project.name }} - Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Выбор листа для импорта</h1>
|
||||
<p><strong>Проект:</strong> {{ project.name }}</p>
|
||||
<p><strong>Файл:</strong> {{ filename }}</p>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Доступные листы</h5>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Номер</th>
|
||||
<th>Название листа</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for sheet in sheets %}
|
||||
<tr>
|
||||
<td>{{ loop.index }}</td>
|
||||
<td>{{ sheet }}</td>
|
||||
<td>
|
||||
<form method="post" action="/boq/{{ project_id }}/import/preview">
|
||||
<input type="hidden" name="filename" value="{{ filename }}">
|
||||
<input type="hidden" name="sheet_name" value="{{ sheet }}">
|
||||
<input type="hidden" name="header_row" value="5">
|
||||
<input type="hidden" name="start_row" value="6">
|
||||
<button type="submit" class="btn btn-sm btn-primary">Выбрать</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Настройка импорта</h5>
|
||||
<p>В текущем файле:</p>
|
||||
<ul>
|
||||
<li>Строка заголовков: 5</li>
|
||||
<li>Начинать чтение с строки: 6</li>
|
||||
</ul>
|
||||
<p>Параметры импорта можно настроить для разных файлов.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Projects - Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Projects</h1>
|
||||
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
{% if projects %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Название</th>
|
||||
<th>Договор</th>
|
||||
<th>Заказчик</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for proj in projects %}
|
||||
<tr>
|
||||
<td>{{ proj.id }}</td>
|
||||
<td>{{ proj.name }}</td>
|
||||
<td>{{ proj.contract_number }}</td>
|
||||
<td>{{ proj.customer }}</td>
|
||||
<td>{{ proj.status }}</td>
|
||||
<td>
|
||||
<a href="/projects/{{ proj.id }}" class="btn btn-sm btn-outline-primary">Открыть</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">
|
||||
Нет проектов. <a href="/projects/new" class="alert-link">Создайте первый проект</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,85 @@
|
||||
<!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>
|
||||
<div class="container mt-5">
|
||||
<h1>Новый проект</h1>
|
||||
|
||||
<form method="post" action="/projects/create">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="name" class="form-label">Название проекта *</label>
|
||||
<input type="text" class="form-control" id="name" name="name" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="contract_number" class="form-label">Номер договора</label>
|
||||
<input type="text" class="form-control" id="contract_number" name="contract_number">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="contract_date" class="form-label">Дата договора</label>
|
||||
<input type="date" class="form-control" id="contract_date" name="contract_date">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="customer" class="form-label">Заказчик</label>
|
||||
<input type="text" class="form-control" id="customer" name="customer">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="currency" class="form-label">Валюта</label>
|
||||
<input type="text" class="form-control" id="currency" name="currency" value="RUB">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="status" class="form-label">Статус</label>
|
||||
<select class="form-select" id="status" name="status">
|
||||
<option value="active" selected>Активный</option>
|
||||
<option value="completed">Завершен</option>
|
||||
<option value="on_hold">В ожидании</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="start_date" class="form-label">Дата начала</label>
|
||||
<input type="date" class="form-control" id="start_date" name="start_date">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="end_date" class="form-label">Дата окончания</label>
|
||||
<input type="date" class="form-control" id="end_date" name="end_date">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-primary">Создать проект</button>
|
||||
<a href="/projects" class="btn btn-secondary">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
|
||||
|
||||
def format_money(value, currency="RUB"):
|
||||
"""Format a monetary value for display without changing stored/calculated values."""
|
||||
try:
|
||||
amount = Decimal(str(value if value is not None else 0))
|
||||
amount = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
amount = Decimal("0.00")
|
||||
|
||||
# Python's grouping is 1,234.56; convert it to Russian UI separators.
|
||||
formatted = f"{amount:,.2f}".replace(",", "\0").replace(".", ",").replace("\0", " ")
|
||||
currency = (currency or "RUB").strip()
|
||||
if currency.upper() == "RUB":
|
||||
return f"{formatted} ₽"
|
||||
return f"{formatted} {currency}"
|
||||
@@ -0,0 +1,6 @@
|
||||
fastapi==0.104.1
|
||||
sqlalchemy==2.0.23
|
||||
jinja2==3.1.2
|
||||
uvicorn==0.24.0
|
||||
openpyxl==3.1.2
|
||||
python-multipart==0.0.6
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add the app directory to the Python path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
from app.main import app
|
||||
print("Application initialized successfully")
|
||||
print("Run with: uvicorn app.main:app --reload")
|
||||
except Exception as e:
|
||||
print(f"Error initializing application: {e}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,91 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.database.database import Base
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, System, Section, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.routers import daily_reports
|
||||
|
||||
|
||||
def test_daily_report_create_view_edit_and_over_plan_is_saved():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
with TestingSession() as session:
|
||||
project = Project(name="Daily report integration")
|
||||
session.add(project)
|
||||
session.flush()
|
||||
system = System(project_id=project.id, name="System A")
|
||||
session.add(system)
|
||||
session.flush()
|
||||
section = Section(system_id=system.id, name="Section A")
|
||||
document = BoqDocument(project_id=project.id, name="BOQ")
|
||||
session.add_all([section, document])
|
||||
session.flush()
|
||||
item = WorkItem(project_id=project.id, boq_document_id=document.id,
|
||||
system_id=system.id, section_id=section.id,
|
||||
source_number="1", name="Install device", unit="pcs",
|
||||
quantity=Decimal("5"), amount=Decimal("50"))
|
||||
session.add(item)
|
||||
session.commit()
|
||||
project_id, system_id, item_id = project.id, system.id, item.id
|
||||
|
||||
app.dependency_overrides[daily_reports.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
assert client.get(f"/projects/{project_id}/daily-reports/new?system_id={system_id}").status_code == 200
|
||||
|
||||
first = client.post(f"/projects/{project_id}/daily-reports", data={
|
||||
"report_date": "2026-09-20", "system_id": str(system_id),
|
||||
f"quantity_{item_id}": "3",
|
||||
}, follow_redirects=False)
|
||||
assert first.status_code == 303
|
||||
first_id = int(first.headers["location"].rsplit("/", 1)[-1])
|
||||
assert client.get(first.headers["location"]).status_code == 200
|
||||
|
||||
second = client.post(f"/projects/{project_id}/daily-reports", data={
|
||||
"report_date": "2026-09-21", "system_id": str(system_id),
|
||||
f"quantity_{item_id}": "4",
|
||||
}, follow_redirects=False)
|
||||
assert second.status_code == 303
|
||||
second_id = int(second.headers["location"].rsplit("/", 1)[-1])
|
||||
second_view = client.get(second.headers["location"])
|
||||
assert second_view.status_code == 200
|
||||
assert "table-warning" in second_view.text
|
||||
assert "Превышен план" in second_view.text
|
||||
|
||||
edited = client.post(f"/projects/{project_id}/daily-reports/{first_id}/edit", data={
|
||||
"report_date": "2026-09-20", "system_id": str(system_id),
|
||||
f"quantity_{item_id}": "1",
|
||||
}, follow_redirects=False)
|
||||
assert edited.status_code == 303
|
||||
assert client.get(edited.headers["location"]).status_code == 200
|
||||
assert client.get(f"/projects/{project_id}/daily-reports").status_code == 200
|
||||
|
||||
with TestingSession() as session:
|
||||
assert session.query(DailyReport).filter(DailyReport.project_id == project_id).count() == 2
|
||||
lines = session.query(DailyReportItem).join(DailyReport).filter(
|
||||
DailyReport.project_id == project_id, DailyReportItem.work_item_id == item_id
|
||||
).all()
|
||||
assert len(lines) == 2
|
||||
assert session.query(WorkItem).filter(WorkItem.id == item_id).count() == 1
|
||||
assert sum((line.completed_quantity for line in lines), Decimal("0")) == Decimal("5.0000")
|
||||
assert date(2026, 9, 20) == session.query(DailyReport.report_date).filter(DailyReport.id == first_id).scalar()
|
||||
finally:
|
||||
app.dependency_overrides.pop(daily_reports.get_db, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,87 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
from copy import copy
|
||||
from openpyxl.styles import PatternFill, Font, Alignment
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base
|
||||
from app.importer.excel_importer import import_excel_data, parse_excel_data, preview_excel_data
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, System, Section, WorkItem
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workbook_file(tmp_path):
|
||||
path = tmp_path / "boq.xlsx"
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Ведомость ОВ"
|
||||
ws.append(["title"])
|
||||
ws.append([None]); ws.append([None]); ws.append([None])
|
||||
ws.append(["№ п/п", "Наименование", "Модель/Артикул", "Производитель", "Ед. изм.", "Кол-во", "Цена за ед.", "Сумма"])
|
||||
ws.merge_cells("A6:H6")
|
||||
ws["A6"] = "Система один"
|
||||
ws["A6"].fill = PatternFill("solid", fgColor="FFB4C6E7")
|
||||
ws["A6"].font = Font(size=11)
|
||||
ws.append(["Раздел один"])
|
||||
ws.append([1, "Работа 1", "M1", "Изготовитель", "шт", 2, 10, 20])
|
||||
ws.append(["Итого по разделу", None, None, None, None, None, None, 20])
|
||||
ws.append([None] * 8)
|
||||
ws.merge_cells("A11:H11")
|
||||
ws["A11"] = "Система два"
|
||||
ws["A11"].fill = PatternFill("solid", fgColor="FFB4C6E7")
|
||||
ws["A11"].font = Font(size=11)
|
||||
ws.append(["Раздел два"])
|
||||
ws.append([2, "Работа 2", None, None, "м", 3, 5, 15])
|
||||
ws.append(["ИТОГО ПО ВЕДОМОСТИ", None, None, None, None, None, None, 35])
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
def test_parser_and_preview_share_counts_and_totals(workbook_file):
|
||||
parsed = parse_excel_data(str(workbook_file), "Ведомость ОВ", 5, 6)
|
||||
preview = preview_excel_data(str(workbook_file), "Ведомость ОВ", 5, 6)
|
||||
assert (parsed["systems_count"], parsed["sections_count"], parsed["work_items_count"]) == (2, 2, 2)
|
||||
assert parsed["total_amount"] == Decimal("35")
|
||||
assert preview["difference"] == Decimal("0")
|
||||
assert not parsed["errors"]
|
||||
|
||||
|
||||
def test_import_persists_hierarchy_and_is_atomic(workbook_file):
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(engine)
|
||||
session = sessionmaker(bind=engine)()
|
||||
project = Project(name="Test")
|
||||
session.add(project); session.commit()
|
||||
result = import_excel_data(session, str(workbook_file), "Ведомость ОВ", 5, 6, project.id)
|
||||
assert (result["systems"], result["sections"], result["work_items"]) == (2, 2, 2)
|
||||
items = session.query(WorkItem).all()
|
||||
assert all(item.system_id and item.section_id for item in items)
|
||||
assert session.query(BoqDocument).count() == 1
|
||||
session.close()
|
||||
|
||||
|
||||
def test_bad_numeric_values_report_row_number(workbook_file):
|
||||
wb = openpyxl.load_workbook(workbook_file)
|
||||
wb["Ведомость ОВ"]["F8"] = "many"
|
||||
wb.save(workbook_file)
|
||||
parsed = parse_excel_data(str(workbook_file), "Ведомость ОВ", 5, 6)
|
||||
assert any("Строка 8" in message and "Кол-во" in message for message in parsed["errors"])
|
||||
|
||||
|
||||
def test_project_workbook_matches_expected_totals():
|
||||
path = next((__import__("pathlib").Path(__file__).resolve().parent.parent).glob("*.xlsx"), None)
|
||||
if path is None:
|
||||
pytest.skip("Project workbook is not present in the workspace")
|
||||
wb = openpyxl.load_workbook(path, read_only=True)
|
||||
try:
|
||||
sheet_name = wb.sheetnames[0]
|
||||
finally:
|
||||
wb.close()
|
||||
preview = preview_excel_data(str(path), sheet_name, 5, 6)
|
||||
assert (preview["systems_count"], preview["sections_count"], preview["work_items_count"]) == (11, 61, 463)
|
||||
assert preview["total_amount"] == Decimal("18600000.00")
|
||||
assert preview["difference"] == Decimal("0.00")
|
||||
@@ -0,0 +1,100 @@
|
||||
import shutil
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from app.database.database import DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.routers import daily_reports, projects
|
||||
from app.services.project_dashboard import build_project_dashboard
|
||||
|
||||
|
||||
def test_real_project_dashboard_with_daily_report_and_overrun(tmp_path):
|
||||
# Exercise the actual imported project and BOQ on a disposable copy of its database.
|
||||
db_path = tmp_path / "dashboard-copy.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
with TestingSession() as session:
|
||||
project = session.get(Project, 2)
|
||||
assert project is not None
|
||||
before = build_project_dashboard(session, project)
|
||||
assert before["planned_cost"] == Decimal("18600000.00")
|
||||
assert before["performed_cost"] >= 0
|
||||
assert before["completion_percent"] >= 0
|
||||
assert len(before["system_progress"]) == 11
|
||||
assert any(row["performed_cost"] == 0 for row in before["system_progress"])
|
||||
baseline_actual = before["performed_cost"]
|
||||
baseline_warning_count = before["over_plan_count"]
|
||||
baseline_recent_count = len(before["recent_reports"])
|
||||
baseline_report_count = session.query(DailyReport).filter_by(project_id=project.id).count()
|
||||
document = before["current_boq"]
|
||||
completed_ids = {row[0] for row in session.query(DailyReportItem.work_item_id).join(
|
||||
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||
).filter(DailyReport.project_id == project.id).all()}
|
||||
work_item = session.query(WorkItem).filter(
|
||||
WorkItem.boq_document_id == document.id,
|
||||
WorkItem.quantity > 0,
|
||||
WorkItem.unit_price > 0,
|
||||
WorkItem.system_id.is_not(None),
|
||||
~WorkItem.id.in_(completed_ids) if completed_ids else True,
|
||||
).first()
|
||||
assert work_item is not None
|
||||
project_id, system_id = project.id, work_item.system_id
|
||||
item_id = work_item.id
|
||||
planned_quantity = Decimal(str(work_item.quantity))
|
||||
unit_price = Decimal(str(work_item.unit_price))
|
||||
performed_quantity = planned_quantity + Decimal("1")
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
app.dependency_overrides[daily_reports.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
dashboard_response = client.get(f"/projects/{project_id}")
|
||||
assert dashboard_response.status_code == 200
|
||||
assert "18 600 000,00 ₽" in dashboard_response.text
|
||||
assert baseline_actual.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
assert " ₽" in dashboard_response.text
|
||||
|
||||
created = client.post(f"/projects/{project_id}/daily-reports", data={
|
||||
"report_date": "2026-09-24", "system_id": str(system_id),
|
||||
f"quantity_{item_id}": str(performed_quantity),
|
||||
}, follow_redirects=False)
|
||||
assert created.status_code == 303
|
||||
|
||||
after_response = client.get(f"/projects/{project_id}")
|
||||
assert after_response.status_code == 200
|
||||
assert "planWarningsModal" in after_response.text
|
||||
assert "Фактическое количество" in after_response.text
|
||||
expected_actual = (performed_quantity * unit_price).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
assert expected_actual > 0
|
||||
assert "system-progress-table .money-cell" in after_response.text
|
||||
assert "white-space: nowrap" in after_response.text
|
||||
assert "18 600 000,00" in after_response.text
|
||||
|
||||
with TestingSession() as session:
|
||||
after = build_project_dashboard(session, session.get(Project, project_id))
|
||||
assert after["performed_cost"] > baseline_actual
|
||||
assert after["remaining_cost"] == Decimal("18600000.00") - after["performed_cost"]
|
||||
assert after["completion_percent"] > 0
|
||||
assert after["over_plan_count"] == baseline_warning_count + 1
|
||||
assert len(after["recent_reports"]) == min(5, baseline_recent_count + 1)
|
||||
assert any(row["performed_cost"] == 0 for row in after["system_progress"])
|
||||
assert session.query(DailyReport).filter_by(project_id=project_id).count() == baseline_report_count + 1
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
app.dependency_overrides.pop(daily_reports.get_db, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,139 @@
|
||||
import shutil
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, func
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.boq import BoqDocument, WorkItem
|
||||
from app.models.daily_report import DailyReport
|
||||
from app.models.project import Project
|
||||
from app.routers import boq as boq_router
|
||||
from app.routers import daily_reports, projects
|
||||
|
||||
|
||||
def test_project_edit_real_file_import_and_daily_report_flow(tmp_path):
|
||||
workbook = next(Path(__file__).resolve().parent.parent.glob("*.xlsx"))
|
||||
upload_path = boq_router.UPLOAD_DIR / workbook.name
|
||||
previous_upload = upload_path.read_bytes() if upload_path.exists() else None
|
||||
|
||||
db_path = tmp_path / "workflow-copy.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
for dependency in (projects.get_db, boq_router.get_db, daily_reports.get_db):
|
||||
app.dependency_overrides[dependency] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
root = client.get("/", follow_redirects=False)
|
||||
assert root.status_code == 307 and root.headers["location"] == "/projects/"
|
||||
assert client.get("/projects/").status_code == 200
|
||||
dashboard = client.get("/projects/2")
|
||||
assert dashboard.status_code == 200
|
||||
assert "18 600 000,00 ₽" in dashboard.text
|
||||
|
||||
with TestingSession() as session:
|
||||
existing_system_id = session.query(WorkItem.system_id).filter(
|
||||
WorkItem.project_id == 2, WorkItem.system_id.is_not(None)
|
||||
).first()[0]
|
||||
form_response = client.get(f"/projects/2/daily-reports/new?system_id={existing_system_id}")
|
||||
assert form_response.status_code == 200
|
||||
assert 'id="position-search"' in form_response.text
|
||||
assert 'data-number=' in form_response.text and 'data-name=' in form_response.text
|
||||
assert 'data-model=' in form_response.text and 'data-manufacturer=' in form_response.text
|
||||
assert "addEventListener('input'" in form_response.text
|
||||
assert form_response.text.count('name="quantity_') > 1
|
||||
|
||||
edit_page = client.get("/projects/2/edit")
|
||||
assert edit_page.status_code == 200
|
||||
saved = client.post("/projects/2/edit", data={
|
||||
"name": "Dashboard regression project", "contract_number": "R-2026",
|
||||
"contract_date": "2026-01-15", "customer": "Regression customer",
|
||||
"currency": "RUB", "start_date": "2026-01-01",
|
||||
"end_date": "2026-12-31", "status": "active",
|
||||
}, follow_redirects=False)
|
||||
assert saved.status_code == 303 and saved.headers["location"] == "/projects/2"
|
||||
assert "Dashboard regression project" in client.get(saved.headers["location"]).text
|
||||
|
||||
with workbook.open("rb") as source:
|
||||
upload = client.post(f"/boq/2/import/upload", files={
|
||||
"file": (workbook.name, source, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
})
|
||||
assert upload.status_code == 200
|
||||
assert "Dashboard regression project" in upload.text
|
||||
assert "Ведомость ОВ" in upload.text
|
||||
|
||||
preview = client.post("/boq/2/import/preview", data={
|
||||
"filename": workbook.name, "sheet_name": "Ведомость ОВ",
|
||||
"header_row": "5", "start_row": "6",
|
||||
})
|
||||
assert preview.status_code == 200
|
||||
assert "11" in preview.text and "61" in preview.text and "463" in preview.text
|
||||
assert "18 600 000,00 ₽" in preview.text
|
||||
assert "0,00 ₽" in preview.text
|
||||
|
||||
confirmed = client.post("/boq/2/import/confirm", data={
|
||||
"filename": workbook.name, "sheet_name": "Ведомость ОВ",
|
||||
"header_row": "5", "start_row": "6",
|
||||
})
|
||||
assert confirmed.status_code == 200
|
||||
assert "/boq/2/documents/" in confirmed.text
|
||||
|
||||
with TestingSession() as session:
|
||||
project = session.get(Project, 2)
|
||||
latest = session.query(BoqDocument).filter_by(project_id=2).order_by(BoqDocument.id.desc()).first()
|
||||
latest_document_id = latest.id
|
||||
imported = session.query(WorkItem).filter_by(boq_document_id=latest.id).order_by(WorkItem.id).all()
|
||||
stored_amount = sum((Decimal(str(item.amount)) for item in imported), Decimal(0))
|
||||
stored_qxprice = sum((Decimal(str(item.quantity)) * Decimal(str(item.unit_price))
|
||||
for item in imported if item.quantity is not None and item.unit_price is not None), Decimal(0))
|
||||
assert len(imported) == 463
|
||||
assert stored_amount.quantize(Decimal("0.01")) == Decimal("18600000.00")
|
||||
assert stored_qxprice.quantize(Decimal("0.01")) == Decimal("18600000.00")
|
||||
daily_report_count_before_new = session.query(DailyReport).filter_by(project_id=2).count()
|
||||
assert daily_report_count_before_new >= 1
|
||||
assert session.get(DailyReport, 1) is not None
|
||||
assert project.name == "Dashboard regression project"
|
||||
item = next(item for item in imported if item.quantity and item.unit_price)
|
||||
item_id, new_system_id, quantity = item.id, item.system_id, item.quantity
|
||||
expected_percent = (Decimal(str(item.unit_price)) * Decimal(str(quantity)) /
|
||||
Decimal("18600000") * Decimal("100"))
|
||||
|
||||
document_page = client.get(f"/boq/2/documents/{latest_document_id}")
|
||||
assert document_page.status_code == 200
|
||||
assert "18 600 000,00 ₽" in document_page.text
|
||||
|
||||
assert client.get("/projects/2/daily-reports/1").status_code == 200
|
||||
created_report = client.post("/projects/2/daily-reports", data={
|
||||
"report_date": "2026-09-26", "system_id": str(new_system_id),
|
||||
f"quantity_{item_id}": str(quantity),
|
||||
}, follow_redirects=False)
|
||||
assert created_report.status_code == 303
|
||||
assert client.get(created_report.headers["location"]).status_code == 200
|
||||
with TestingSession() as session:
|
||||
assert session.query(DailyReport).filter_by(project_id=2).count() == daily_report_count_before_new + 1
|
||||
updated_dashboard = client.get("/projects/2")
|
||||
assert updated_dashboard.status_code == 200
|
||||
assert f"{expected_percent:.4f}%" in updated_dashboard.text
|
||||
assert "Последние Daily Reports" in updated_dashboard.text
|
||||
assert client.get("/projects/2/daily-reports/1").status_code == 200
|
||||
finally:
|
||||
for dependency in (projects.get_db, boq_router.get_db, daily_reports.get_db):
|
||||
app.dependency_overrides.pop(dependency, None)
|
||||
engine.dispose()
|
||||
if previous_upload is None:
|
||||
upload_path.unlink(missing_ok=True)
|
||||
else:
|
||||
upload_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
upload_path.write_bytes(previous_upload)
|
||||
@@ -0,0 +1,21 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
from app.utils.formatters import format_money
|
||||
|
||||
|
||||
def test_money_formatter_uses_russian_currency_display_without_mutating_decimal():
|
||||
value = Decimal("3287651.331719")
|
||||
assert format_money(value, "RUB") == "3 287 651,33 ₽"
|
||||
assert value == Decimal("3287651.331719")
|
||||
assert format_money(Decimal("804.036138")) == "804,04 ₽"
|
||||
assert format_money(Decimal("804.036138"), "USD") == "804,04 USD"
|
||||
|
||||
|
||||
def test_root_redirects_to_project_list():
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/", follow_redirects=False)
|
||||
assert response.status_code == 307
|
||||
assert response.headers["location"] == "/projects/"
|
||||
@@ -0,0 +1,100 @@
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from app.models.project import Project
|
||||
from app.routers import projects
|
||||
from app.services.project_dashboard import build_project_dashboard
|
||||
|
||||
|
||||
def test_project_work_journal_crud_and_dashboard_warnings(tmp_path):
|
||||
db_path = tmp_path / "work-journal-copy.db"
|
||||
shutil.copy2(DATABASE_PATH, db_path)
|
||||
engine = create_engine(f"sqlite:///{Path(db_path).as_posix()}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=engine)
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
dashboard = client.get("/projects/2")
|
||||
assert dashboard.status_code == 200
|
||||
assert "Рабочий журнал" in dashboard.text
|
||||
assert "planWarningsModal" in dashboard.text
|
||||
assert "Фактическое количество" in dashboard.text
|
||||
status_position = dashboard.text.find('aria-live="polite"')
|
||||
kpi_position = dashboard.text.find('id="kpi-heading"')
|
||||
assert 0 <= status_position < kpi_position
|
||||
assert 'class="alert alert-warning py-2 mb-0"' in dashboard.text[:kpi_position]
|
||||
with TestingSession() as session:
|
||||
real_project = session.get(Project, 2)
|
||||
warnings = build_project_dashboard(session, real_project)["over_plan_items"]
|
||||
assert warnings
|
||||
assert all(row["item"].name in dashboard.text for row in warnings)
|
||||
|
||||
with TestingSession() as session:
|
||||
journal_baseline_count = session.query(WorkJournalEntry).filter_by(project_id=2).count()
|
||||
no_warning_project = Project(name="No plan warnings test")
|
||||
session.add(no_warning_project)
|
||||
session.commit()
|
||||
no_warning_project_id = no_warning_project.id
|
||||
no_warning_dashboard = client.get(f"/projects/{no_warning_project_id}")
|
||||
assert no_warning_dashboard.status_code == 200
|
||||
assert 'class="text-success small py-2"' in no_warning_dashboard.text
|
||||
assert 'data-bs-target="#planWarningsModal"' not in no_warning_dashboard.text
|
||||
|
||||
task = client.post("/projects/2/journal", data={
|
||||
"type": "task", "text": "Проверить узел АУПС", "due_date": "2026-10-01",
|
||||
})
|
||||
note = client.post("/projects/2/journal", data={
|
||||
"type": "note", "text": "Уточнить поставку оборудования", "due_date": "",
|
||||
})
|
||||
assert task.status_code == note.status_code == 200
|
||||
dashboard = client.get("/projects/2")
|
||||
assert "Проверить узел АУПС" in dashboard.text
|
||||
assert "01.10.2026" in dashboard.text
|
||||
assert "Уточнить поставку оборудования" in dashboard.text
|
||||
|
||||
with TestingSession() as session:
|
||||
task_entry = session.query(WorkJournalEntry).filter_by(
|
||||
project_id=2, type="task", text="Проверить узел АУПС"
|
||||
).one()
|
||||
note_entry = session.query(WorkJournalEntry).filter_by(
|
||||
project_id=2, type="note", text="Уточнить поставку оборудования"
|
||||
).one()
|
||||
task_id, note_id = task_entry.id, note_entry.id
|
||||
|
||||
toggled = client.post(f"/projects/2/journal/{task_id}/toggle")
|
||||
assert toggled.status_code == 200 and toggled.json()["status"] == "done"
|
||||
assert f"Проверить узел АУПС" not in client.get("/projects/2").text
|
||||
|
||||
updated = client.post(f"/projects/2/journal/{note_id}", data={
|
||||
"type": "note", "text": "Поставка подтверждена", "due_date": "",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert "Поставка подтверждена" in client.get("/projects/2").text
|
||||
|
||||
deleted = client.post(f"/projects/2/journal/{note_id}/delete")
|
||||
assert deleted.status_code == 200
|
||||
assert "Поставка подтверждена" not in client.get("/projects/2").text
|
||||
|
||||
deleted_task = client.post(f"/projects/2/journal/{task_id}/delete")
|
||||
assert deleted_task.status_code == 200
|
||||
with TestingSession() as session:
|
||||
assert session.query(WorkJournalEntry).filter_by(project_id=2).count() == journal_baseline_count
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user