diff --git a/app/database/migrations.py b/app/database/migrations.py index 4c117fd..e52003e 100644 --- a/app/database/migrations.py +++ b/app/database/migrations.py @@ -12,6 +12,7 @@ PAYMENT_STATUS_MIGRATION = "20260926_payment_status" KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique" BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites" DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts" +AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled" def run_migrations(engine): @@ -248,6 +249,36 @@ def run_migrations(engine): ) connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (DOCUMENT_ARTIFACTS_MIGRATION, datetime.now(timezone.utc).isoformat())) + if AGREEMENT_STATUS_CANCELLED_MIGRATION not in applied: + tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")} + if "agreements" in tables: + # SQLite CHECK constraints are baked into table definition. + # Recreate agreements with the expanded status set. + connection.execute("""CREATE TABLE agreements_new ( + id INTEGER NOT NULL PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id), + boq_document_id INTEGER REFERENCES boq_documents(id), + number VARCHAR NOT NULL, + date DATE NOT NULL, + title VARCHAR NOT NULL, + description TEXT, + status VARCHAR NOT NULL DEFAULT 'draft', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_agreements_status CHECK (status IN ('draft', 'approved', 'cancelled')), + CONSTRAINT uq_agreements_project_number UNIQUE (project_id, number) + )""") + connection.execute("""INSERT INTO agreements_new + (id, project_id, boq_document_id, number, date, title, description, status, created_at, updated_at) + SELECT id, project_id, boq_document_id, number, date, title, description, status, created_at, updated_at + FROM agreements""") + connection.execute("DROP TABLE agreements") + connection.execute("ALTER TABLE agreements_new RENAME TO agreements") + connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_id ON agreements (id)") + connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_project_id ON agreements (project_id)") + connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)") + connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", + (AGREEMENT_STATUS_CANCELLED_MIGRATION, datetime.now(timezone.utc).isoformat())) violations = connection.execute("PRAGMA foreign_key_check").fetchall() if violations: raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}") diff --git a/app/exporters/project_import.py b/app/exporters/project_import.py index 9d41546..2ffb69f 100644 --- a/app/exporters/project_import.py +++ b/app/exporters/project_import.py @@ -53,7 +53,7 @@ _LIST_FILES = ( "document_artifacts.json", ) -_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"} +_ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"} _ALLOWED_AGREEMENT_CHANGE = {"increase", "decrease", "new_position"} _ALLOWED_KS2_STATUS = {"draft", "issued", "cancelled"} _ALLOWED_KS3_STATUS = {"draft", "issued", "cancelled"} diff --git a/app/models/agreement.py b/app/models/agreement.py index 69e1ac5..244f007 100644 --- a/app/models/agreement.py +++ b/app/models/agreement.py @@ -8,7 +8,7 @@ from app.database.database import Base class Agreement(Base): __tablename__ = "agreements" __table_args__ = ( - CheckConstraint("status IN ('draft', 'approved')", name="ck_agreements_status"), + CheckConstraint("status IN ('draft', 'approved', 'cancelled')", name="ck_agreements_status"), UniqueConstraint("project_id", "number", name="uq_agreements_project_number"), ) diff --git a/app/routers/agreements.py b/app/routers/agreements.py index 36452b9..1f3a9e3 100644 --- a/app/routers/agreements.py +++ b/app/routers/agreements.py @@ -404,3 +404,18 @@ async def confirm_approval(project_id: int, agreement_id: int, request: Request, db.rollback() return _detail_response(request, db, _project(db, project_id), _agreement(db, project_id, agreement_id), str(exc), 400) + + +@router.post("/{project_id}/agreements/{agreement_id}/cancel") +async def cancel_agreement_route(project_id: int, agreement_id: int, request: Request, + db: Session = Depends(get_db)): + from app.services.agreement_items import cancel_agreement, agreement_cancel_block_reason + + agreement = _agreement(db, project_id, agreement_id) + try: + cancel_agreement(db, agreement) + return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303) + except ValueError as exc: + db.rollback() + return _detail_response(request, db, _project(db, project_id), + _agreement(db, project_id, agreement_id), str(exc), 400) diff --git a/app/services/agreement_items.py b/app/services/agreement_items.py index 289a9d8..c351cc0 100644 --- a/app/services/agreement_items.py +++ b/app/services/agreement_items.py @@ -1,5 +1,7 @@ from decimal import Decimal, InvalidOperation +from sqlalchemy import func + from app.models import boq from app.models.agreement import Agreement, AgreementItem from app.services.effective_plan import ( @@ -8,6 +10,8 @@ from app.services.effective_plan import ( work_item_scope_document_id, ) +ZERO = Decimal("0") + def decimal_value(value, label): try: @@ -305,3 +309,59 @@ def delete_draft_agreement(db, agreement): except Exception as exc: db.rollback() raise ValueError(f"Failed to delete agreement: {exc}") from exc + + +def _closed_quantity_for_work_item(db, work_item_id: int) -> Decimal: + """Sum of KS2ItemSource quantities for a work item, excluding cancelled KS-2.""" + from app.models.ks2 import KS2, KS2Item, KS2ItemSource + from app.models.daily_report import DailyReportItem + + total = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).join( + KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id + ).join( + KS2, KS2.id == KS2Item.ks2_id + ).filter( + KS2Item.work_item_id == work_item_id, + KS2.status != "cancelled", + ).scalar() + return Decimal(str(total or 0)) + + +def agreement_cancel_block_reason(db, agreement) -> str | None: + """Return why an approved agreement cannot be cancelled, or None.""" + if agreement.status == "draft": + return "Черновик нельзя отменить. Сначала утвердите ДС." + if agreement.status == "cancelled": + return "ДС уже отменено." + # Conservative V1: block if any affected WorkItem has closed volume in non-cancelled KS-2 + for line in agreement.items: + closed = _closed_quantity_for_work_item(db, line.work_item_id) + if closed > ZERO: + return "Нельзя отменить ДС: его объём уже использован в закрытых КС-2." + return None + + +def cancel_agreement(db, agreement): + """ + Cancel an approved agreement atomically. + + The agreement becomes cancelled and drops out of the effective plan. + AgreementItems, WorkItems and history are preserved. + """ + try: + reason = agreement_cancel_block_reason(db, agreement) + if reason is not None: + raise ValueError(reason) + # Re-check status inside the transaction + if agreement.status != "approved": + raise ValueError("Отменить можно только утверждённое ДС") + agreement.status = "cancelled" + db.commit() + db.refresh(agreement) + return agreement + except ValueError: + db.rollback() + raise + except Exception as exc: + db.rollback() + raise ValueError(f"Не удалось отменить ДС: {exc}") from exc diff --git a/app/templates/agreements/detail.html b/app/templates/agreements/detail.html index 6a6721e..39226eb 100644 --- a/app/templates/agreements/detail.html +++ b/app/templates/agreements/detail.html @@ -1,7 +1,7 @@