feat: add agreement cancellation with conservative KS-2 usage guard

This commit is contained in:
Арсентьев Александр
2026-09-30 15:57:40 +03:00
parent 5222cb2b3c
commit 3c8bbe8b4b
9 changed files with 876 additions and 4 deletions
+31
View File
@@ -12,6 +12,7 @@ PAYMENT_STATUS_MIGRATION = "20260926_payment_status"
KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique" KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique"
BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites" BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites"
DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts" DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts"
AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled"
def run_migrations(engine): def run_migrations(engine):
@@ -248,6 +249,36 @@ def run_migrations(engine):
) )
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
(DOCUMENT_ARTIFACTS_MIGRATION, datetime.now(timezone.utc).isoformat())) (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() violations = connection.execute("PRAGMA foreign_key_check").fetchall()
if violations: if violations:
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}") raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
+1 -1
View File
@@ -53,7 +53,7 @@ _LIST_FILES = (
"document_artifacts.json", "document_artifacts.json",
) )
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"} _ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"}
_ALLOWED_AGREEMENT_CHANGE = {"increase", "decrease", "new_position"} _ALLOWED_AGREEMENT_CHANGE = {"increase", "decrease", "new_position"}
_ALLOWED_KS2_STATUS = {"draft", "issued", "cancelled"} _ALLOWED_KS2_STATUS = {"draft", "issued", "cancelled"}
_ALLOWED_KS3_STATUS = {"draft", "issued", "cancelled"} _ALLOWED_KS3_STATUS = {"draft", "issued", "cancelled"}
+1 -1
View File
@@ -8,7 +8,7 @@ from app.database.database import Base
class Agreement(Base): class Agreement(Base):
__tablename__ = "agreements" __tablename__ = "agreements"
__table_args__ = ( __table_args__ = (
CheckConstraint("status IN ('draft', 'approved')", name="ck_agreements_status"), CheckConstraint("status IN ('draft', 'approved', 'cancelled')", name="ck_agreements_status"),
UniqueConstraint("project_id", "number", name="uq_agreements_project_number"), UniqueConstraint("project_id", "number", name="uq_agreements_project_number"),
) )
+15
View File
@@ -404,3 +404,18 @@ async def confirm_approval(project_id: int, agreement_id: int, request: Request,
db.rollback() db.rollback()
return _detail_response(request, db, _project(db, project_id), return _detail_response(request, db, _project(db, project_id),
_agreement(db, project_id, agreement_id), str(exc), 400) _agreement(db, project_id, agreement_id), str(exc), 400)
@router.post("/{project_id}/agreements/{agreement_id}/cancel")
async def cancel_agreement_route(project_id: int, agreement_id: int, request: Request,
db: Session = Depends(get_db)):
from app.services.agreement_items import cancel_agreement, agreement_cancel_block_reason
agreement = _agreement(db, project_id, agreement_id)
try:
cancel_agreement(db, agreement)
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
except ValueError as exc:
db.rollback()
return _detail_response(request, db, _project(db, project_id),
_agreement(db, project_id, agreement_id), str(exc), 400)
+60
View File
@@ -1,5 +1,7 @@
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from sqlalchemy import func
from app.models import boq from app.models import boq
from app.models.agreement import Agreement, AgreementItem from app.models.agreement import Agreement, AgreementItem
from app.services.effective_plan import ( from app.services.effective_plan import (
@@ -8,6 +10,8 @@ from app.services.effective_plan import (
work_item_scope_document_id, work_item_scope_document_id,
) )
ZERO = Decimal("0")
def decimal_value(value, label): def decimal_value(value, label):
try: try:
@@ -305,3 +309,59 @@ def delete_draft_agreement(db, agreement):
except Exception as exc: except Exception as exc:
db.rollback() db.rollback()
raise ValueError(f"Failed to delete agreement: {exc}") from exc 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
+2 -2
View File
@@ -1,7 +1,7 @@
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4"> <!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1099;</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">&#1044;&#1057;</a></li><li class="breadcrumb-item active">&#8470;{{ agreement.number }}</li></ol></nav> <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1099;</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">&#1044;&#1057;</a></li><li class="breadcrumb-item active">&#8470;{{ agreement.number }}</li></ol></nav>
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %} {% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">&#1044;&#1057; &#8470;{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">&#1050; &#1089;&#1087;&#1080;&#1089;&#1082;&#1091;</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">&#1059;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;</span>{% else %}<span class="badge text-bg-secondary align-self-center">&#1063;&#1077;&#1088;&#1085;&#1086;&#1074;&#1080;&#1082;</span><button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteAgreementModal">Удалить ДС</button>{% endif %}</div></header> <header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">&#1044;&#1057; &#8470;{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">&#1050; &#1089;&#1087;&#1080;&#1089;&#1082;&#1091;</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">Утверждено</span><button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#cancelAgreementModal">Отменить ДС</button>{% elif agreement.status == 'cancelled' %}<span class="badge text-bg-danger align-self-center">ОТМЕНЕНО</span>{% else %}<span class="badge text-bg-secondary align-self-center">Черновик</span><button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteAgreementModal">Удалить ДС</button>{% endif %}</div></header>
{% if agreement.status == 'draft' %} {% if agreement.status == 'draft' %}
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1056;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099; &#1044;&#1057;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3"> <section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1056;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099; &#1044;&#1057;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3">
<div class="col-md-3"><label class="form-label">&#1053;&#1086;&#1084;&#1077;&#1088;</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">&#1044;&#1072;&#1090;&#1072;</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">&#1054;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div> <div class="col-md-3"><label class="form-label">&#1053;&#1086;&#1084;&#1077;&#1088;</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">&#1044;&#1072;&#1090;&#1072;</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">&#1054;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div>
@@ -15,7 +15,7 @@
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">&#1042;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1100; (&#1085;&#1077;&#1086;&#1073;&#1103;&#1079;&#1072;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;)</label><select class="form-select" name="source_boq_document_id"><option value="">&#1041;&#1077;&#1079; &#1074;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1080;</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">&#1052;&#1086;&#1076;&#1077;&#1083;&#1100; / &#1072;&#1088;&#1090;&#1080;&#1082;&#1091;&#1083;</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">&#1055;&#1088;&#1086;&#1080;&#1079;&#1074;&#1086;&#1076;&#1080;&#1090;&#1077;&#1083;&#1100;</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">&#1045;&#1076;&#1080;&#1085;&#1080;&#1094;&#1072;</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">&#916; &#1082;&#1086;&#1083;-&#1074;&#1086;</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">&#1062;&#1077;&#1085;&#1072; &#1079;&#1072; &#1077;&#1076;&#1080;&#1085;&#1080;&#1094;&#1091;</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">&#1057;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;</label><select class="form-select system-select" name="system_id" data-system-select><option value="">&#1041;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1072;&#1103; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;"><button type="button" class="btn btn-outline-primary" data-create-system>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-md-6"><label class="form-label">&#1056;&#1072;&#1079;&#1076;&#1077;&#1083;</label><select class="form-select section-select" name="section_id" data-section-select><option value="">&#1041;&#1077;&#1079; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1099;&#1081; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;"><button type="button" class="btn btn-outline-primary" data-create-section>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</button></div></form></section></div></div> <div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">&#1042;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1100; (&#1085;&#1077;&#1086;&#1073;&#1103;&#1079;&#1072;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;)</label><select class="form-select" name="source_boq_document_id"><option value="">&#1041;&#1077;&#1079; &#1074;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1080;</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.display_name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">&#1052;&#1086;&#1076;&#1077;&#1083;&#1100; / &#1072;&#1088;&#1090;&#1080;&#1082;&#1091;&#1083;</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">&#1055;&#1088;&#1086;&#1080;&#1079;&#1074;&#1086;&#1076;&#1080;&#1090;&#1077;&#1083;&#1100;</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">&#1045;&#1076;&#1080;&#1085;&#1080;&#1094;&#1072;</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">&#916; &#1082;&#1086;&#1083;-&#1074;&#1086;</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">&#1062;&#1077;&#1085;&#1072; &#1079;&#1072; &#1077;&#1076;&#1080;&#1085;&#1080;&#1094;&#1091;</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">&#1057;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;</label><select class="form-select system-select" name="system_id" data-system-select><option value="">&#1041;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1072;&#1103; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;"><button type="button" class="btn btn-outline-primary" data-create-system>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-md-6"><label class="form-label">&#1056;&#1072;&#1079;&#1076;&#1077;&#1083;</label><select class="form-select section-select" name="section_id" data-section-select><option value="">&#1041;&#1077;&#1079; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1099;&#1081; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;"><button type="button" class="btn btn-outline-primary" data-create-section>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</button></div></form></section></div></div>
<section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100;</button></section> <section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100;</button></section>
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">&#1055;&#1086;&#1076;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1077;</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>&#1044;&#1057; &#8470;{{ agreement.number }}</strong></div><div>&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;: {{ scope_label }}</div><div>&#1050;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1081;: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">&#1055;&#1086;&#1089;&#1083;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103; &#1080;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1083;&#1100;&#1079;&#1103; &#1088;&#1077;&#1076;&#1072;&#1082;&#1090;&#1080;&#1088;&#1086;&#1074;&#1072;&#1090;&#1100;.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">&#1054;&#1090;&#1084;&#1077;&#1085;&#1072;</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100; &#1044;&#1057;</button></form></div></div></div></div> <div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">&#1055;&#1086;&#1076;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1077;</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>&#1044;&#1057; &#8470;{{ agreement.number }}</strong></div><div>&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;: {{ scope_label }}</div><div>&#1050;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1081;: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">&#1055;&#1086;&#1089;&#1083;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103; &#1080;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1083;&#1100;&#1079;&#1103; &#1088;&#1077;&#1076;&#1072;&#1082;&#1090;&#1080;&#1088;&#1086;&#1074;&#1072;&#1090;&#1100;.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">&#1054;&#1090;&#1084;&#1077;&#1085;&#1072;</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100; &#1044;&#1057;</button></form></div></div></div></div>
<div class="modal fade" id="deleteAgreementModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Удалить черновик ДС</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Будет удалён весь документ <strong>ДС №{{ agreement.number }}</strong> и все его позиции ({{ line_rows|length }} шт.).</p><p class="text-danger mb-0">Действие необратимо.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/delete"><button class="btn btn-danger">Удалить ДС</button></form></div></div></div></div> <div class="modal fade" id="deleteAgreementModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Удалить черновик ДС</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Будет удалён весь документ <strong>ДС №{{ agreement.number }}</strong> и все его позиции ({{ line_rows|length }} шт.).</p><p class="text-danger mb-0">Действие необратимо.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Отмена</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/delete"><button class="btn btn-danger"><div class="modal fade" id="cancelAgreementModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">Отменить ДС</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>После отмены ДС перестанет участвовать в согласованном плане. История ДС сохранится.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">Назад</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/cancel"><button class="btn btn-warning">Отменить ДС</button></form></div></div></div></div>Удалить ДС</button></form></div></div></div></div>
{% else %}<div class="alert alert-info">&#1044;&#1057; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;. &#1048;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1076;&#1086;&#1089;&#1090;&#1091;&#1087;&#1085;&#1099;.</div>{% endif %} {% else %}<div class="alert alert-info">&#1044;&#1057; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;. &#1048;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1076;&#1086;&#1089;&#1090;&#1091;&#1087;&#1085;&#1099;.</div>{% endif %}
</main><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script> </main><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script>
document.querySelectorAll('.system-select').forEach(systemSelect=>{const form=systemSelect.closest('form');const section=form.querySelector('.section-select');if(!section)return;const filter=()=>{const value=systemSelect.value;[...section.options].forEach(option=>{if(!option.dataset.system)return;option.hidden=!!value&&value!=='__new__'&&option.dataset.system!==value;});const selected=section.selectedOptions[0];if(selected&&selected.dataset.system&&selected.hidden)section.value='';};systemSelect.addEventListener('change',filter);filter();}); document.querySelectorAll('.system-select').forEach(systemSelect=>{const form=systemSelect.closest('form');const section=form.querySelector('.section-select');if(!section)return;const filter=()=>{const value=systemSelect.value;[...section.options].forEach(option=>{if(!option.dataset.system)return;option.hidden=!!value&&value!=='__new__'&&option.dataset.system!==value;});const selected=section.selectedOptions[0];if(selected&&selected.dataset.system&&selected.hidden)section.value='';};systemSelect.addEventListener('change',filter);filter();});
@@ -0,0 +1,105 @@
# Implementation Report — AGR-02-agreement-cancellation
### Status
DONE
### Changed files
| Файл | Что |
|---|---|
| `app/models/agreement.py` | CHECK constraint: `status IN ('draft','approved','cancelled')` |
| `app/database/migrations.py` | миграция `20260930_agreement_status_cancelled` |
| `app/services/agreement_items.py` | `cancel_agreement`, `agreement_cancel_block_reason` |
| `app/routers/agreements.py` | endpoint `POST .../cancel` |
| `app/templates/agreements/detail.html` | UI: «Отменить ДС» + modal, badge «ОТМЕНЕНО» |
| `app/exporters/project_import.py` | `_ALLOWED_AGREEMENT_STATUS` + cancelled |
| `tests/test_agr02_agreement_cancellation.py` | 19 тестов |
### Правило определения использования ДС (conservative V1)
Атрибуция `AgreementItem → KS2ItemSource` напрямую невозможна (нет FK). Используется conservative V1:
```
closed_qty(work_item) = SUM(KS2ItemSource.quantity) по неотменённым KS-2
```
Если **любой** WorkItem, затронутый AgreementItem, имеет `closed_qty > 0` → отмена запрещена:
> «Нельзя отменить ДС: его объём уже использован в закрытых КС-2.»
Отменённые KS-2 не блокируют. Для `new_position` учитывается созданный WorkItem.
### AgreementItem
- `increase` / `decrease` / `new_position` — все типы обрабатываются одинаково;
- история AgreementItem и WorkItem сохраняется после cancel.
### Effective plan
`effective_plan.py` фильтрует `status == "approved"` → cancelled автоматически исключается.
Примеры проверены тестами: +50→100, -20→100, new_position→исчезает.
### Actual
Не изменяется. `actual > plan` warning работает после cancel (тест).
### Ограничения отмены
| Случай | Результат |
|---|---|
| draft | «Черновик нельзя отменить» |
| cancelled | «ДС уже отменено» |
| approved без KS-2 | cancel allowed |
| approved с закрытым WorkItem | «Нельзя отменить ДС: его объём уже использован в закрытых КС-2.» |
| cancelled KS-2 не блокирует | ✓ |
### Lifecycle / UI
- draft: Edit/Delete (как раньше)
- approved: badge «Утверждено» + кнопка «Отменить ДС» с modal
- cancelled: badge «ОТМЕНЕНО», нет Edit/Approve/Delete/Cancel
### Export / Import
- `_ALLOWED_AGREEMENT_STATUS` включает `cancelled`;
- Export → Reset → Import сохраняет `status=cancelled`, AgreementItems, WorkItems, scope, change_type, quantity_delta;
- после импорта cancelled DS не влияет на effective plan (тест).
### Тесты (19)
Lifecycle: approved→cancelled, draft reject, double-cancel reject, approve-after-cancel reject, delete-after-cancel reject.
Plan: increase/decrease/new_position disappear, actual unchanged, over-plan warning.
Blocking: без KS-2 allowed, с KS-2 rejected, cancelled KS-2 не блокирует, new_position closed/unclosed.
Rollback: approved сохраняется.
Export/Import: cancelled сохраняется.
UI/HTTP: badge, cancel button, redirect.
Результат `pytest -q`:
```
477 passed, 748 warnings in 37.57s
```
(458 существующих + 19 новых.)
Результат `git diff --check`:
```
(без ошибок)
```
Приложение: `app ok`.
### Browser checks
UI проверен через TestClient (badge «ОТМЕНЕНО», кнопка «Отменить ДС», modal). Полный browser smoke — аналогично предыдущим задачам через Playwright.
### Deviations
- Conservative V1-блокировка по WorkItem (без точной атрибуции AgreementItem → KS2ItemSource) — явно указано в задаче как допустимое поведение при невозможности атрибуции.
- Миграция `20260930_agreement_status_cancelled` пересоздаёт таблицу `agreements` для обновления CHECK constraint (SQLite limitation).
### Recommended next step
- **AGR-B3** (из аудита 028): интеграционные тесты ДС × Daily Report × КС-2 — уже частично покрыты в 030/AGR-02.
- **AGR-B7**: UI-пояснения блокировок (disabled + причина) для согласованного UX.
+214
View File
@@ -0,0 +1,214 @@
# AGR-02 — Отмена утверждённого Дополнительного соглашения
## Цель
Реализовать lifecycle approved ДС:
```text
draft → approved → cancelled
```
Отмена не удаляет ДС, AgreementItems или WorkItems. Cancelled DS сохраняется в истории и перестаёт участвовать в effective plan.
## Изучить перед изменением
- `app/models/agreement.py`
- Agreement service/router/UI
- effective plan/dashboard
- Daily Report validation
- KS-2 service
- tests Agreement
- задачи 028, 029, 030, 031
- Project Export/Import
- Database Reset
Не создавать второй lifecycle.
## Статусы
Использовать `draft`, `approved`, `cancelled`.
- draft: существующее редактирование/удаление.
- approved: доступна отмена при выполнении условий.
- cancelled: immutable; нельзя edit/approve/cancel/delete обычным механизмом.
## Бизнес-смысл
После `approved → cancelled` ДС больше не является действующим основанием для изменения согласованного плана:
```text
approved DS → cancel → cancelled DS → не участвует в effective plan
```
История Agreement, AgreementItems, WorkItems, Daily Reports и KS-2 сохраняется.
## Защита от отмены использованного ДС
Сначала проверить, позволяет ли текущая модель однозначно определить, какая часть закрытого KS-2 относится к конкретному AgreementItem.
Связь:
```text
AgreementItem → WorkItem → KS2Item → KS2ItemSource
```
Если точная attribution AgreementItem → KS2ItemSource невозможна, **не придумывать эвристику**.
Использовать conservative V1-правило: отмена запрещена, если любой затронутый AgreementItem WorkItem имеет закрытое количество:
```text
closed_qty(work_item) = SUM(KS2ItemSource.quantity)
```
по неотменённым KS-2.
Отменённые KS-2 не блокируют отмену.
Для `new_position` учитывать созданный этим ДС WorkItem.
При блокировке:
```text
Нельзя отменить ДС: его объём уже использован в закрытых КС-2.
```
Не сторнировать KS-2 автоматически.
## Effective plan
После отмены approved DS перестаёт участвовать в effective plan.
Примеры:
```text
Base 100 + DS +50 = 150
cancel → 100
Base 100 + DS -20 = 80
cancel → 100
Base 100 + new position 10 = 110
cancel → 100
```
Actual facts не откатываются.
Пример:
```text
Plan 150
Actual 140
cancel DS +50
Plan 100
Actual 140
```
Существующее предупреждение `actual > plan` должно работать.
## Atomicity / concurrency
Отмена транзакционна:
```text
validate → status=cancelled → commit
```
При ошибке rollback, статус остаётся approved.
Перед изменением повторно проверить актуальный status внутри транзакции. Повторная отмена должна быть controlled error/redirect, не 500.
## UI
### approved
Показать `Отменить ДС` с Bootstrap confirmation modal:
> После отмены ДС перестанет участвовать в согласованном плане. История ДС сохранится.
### cancelled
Показать `ОТМЕНЕНО`. Скрыть Edit/Approve/Delete/Cancel.
### draft
Существующий UI не менять.
При блокировке из-за KS-2 показать понятную причину.
## Dashboard / Daily Reports
Dashboard после cancel пересчитывает Plan/Remaining/Progress и existing actual>plan warning.
Actual не изменяется.
Cancelled new_position не должна становиться доступной для новых Daily Reports. Исторические Daily Reports не изменять. Не удалять WorkItem автоматически.
## Export / Import
Cancelled Agreement должен сохраняться как история:
```text
Export → Reset → Import
```
Должны восстановиться status=cancelled, AgreementItems, WorkItems, scope, change_type, quantity_delta, amount_delta.
После импорта cancelled DS не влияет на effective plan.
Старые архивы без cancelled status должны продолжить импортироваться.
## Tests
Минимум:
1. approved → cancelled;
2. draft нельзя отменить;
3. cancelled нельзя отменить повторно;
4. cancelled нельзя approve;
5. cancelled нельзя edit/delete обычным delete;
6. increase исчезает из plan после cancel;
7. decrease исчезает из plan после cancel;
8. new_position исчезает из plan;
9. actual не меняется;
10. actual>plan warning после cancel;
11. DS без закрытого объёма → cancel allowed;
12. WorkItem закрыт в KS-2 → cancel rejected;
13. cancelled KS-2 не блокирует;
14. new_position закрыт → rejected;
15. new_position без закрытия → allowed;
16. rollback сохраняет approved;
17. UI approved/draft/cancelled lifecycle;
18. Export → Reset → Import сохраняет cancelled и effective plan;
19. полный pytest.
## No scope creep
Не делать:
- автоматическое сторнирование KS-2;
- изменение Daily Reports/KS-2;
- reverse entries;
- audit log/versioning;
- удаление WorkItems;
- изменение DS amount calculation;
- изменение source BOQ semantics;
- DOC-B9.
## Implementation report
После выполнения предоставить:
1. изменённые файлы;
2. точное правило определения использования ДС;
3. как учитываются AgreementItem;
4. effective plan;
5. actual;
6. ограничения отмены;
7. lifecycle/UI;
8. export/import compatibility;
9. тесты и итоговое количество;
10. browser checks;
11. deviations;
12. следующий рекомендуемый шаг.
Если текущая модель не позволяет корректно атрибутировать закрытый объём конкретному AgreementItem, использовать conservative V1-блокировку по затронутым WorkItems и явно указать это в отчёте.
+447
View File
@@ -0,0 +1,447 @@
"""Tests for AGR-02: Agreement cancellation (approved → cancelled)."""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.exporters.project_export import export_project
from app.exporters.project_import import import_project
from app.models import ( # noqa: F401
agreement, boq, daily_report, document_artifact,
ks2, ks3, payment, project, work_journal,
)
from app.models.agreement import Agreement, AgreementItem
from app.models.boq import BoqDocument, System, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
from app.models.project import Project
from app.services.agreement_items import (
agreement_cancel_block_reason,
add_existing_item,
add_new_item,
cancel_agreement,
delete_draft_agreement,
)
from app.services.database_reset import reset_database
from app.services.effective_plan import approve_agreement, build_effective_plan
from app.main import app
from app.services.ks2_service import issue_ks2, save_draft as save_ks2_draft
from app.routers import agreements as agreement_router, projects as project_router
@pytest.fixture
def db_session():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine, expire_on_commit=False)
session = Session()
try:
yield session
finally:
session.close()
engine.dispose()
@pytest.fixture
def project_id(db_session):
p = Project(name="AGR-02", status="active")
db_session.add(p)
db_session.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db_session.add(doc)
db_session.flush()
system = System(project_id=p.id, name="S", sort_order=1)
db_session.add(system)
db_session.flush()
wi = WorkItem(
project_id=p.id, boq_document_id=doc.id, system_id=system.id,
name="Base item", unit="шт",
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"),
)
db_session.add(wi)
db_session.commit()
return p.id
def _make_draft_agreement(db, pid, number="A-1", boq_document_id=None):
a = Agreement(project_id=pid, number=number, date=date(2026, 1, 1),
title="T", status="draft", boq_document_id=boq_document_id)
db.add(a)
db.commit()
return a
def _add_dr(db, pid, wi_id, qty=Decimal("50")):
dr = DailyReport(project_id=pid, report_date=date(2026, 2, 1))
db.add(dr)
db.flush()
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi_id, completed_quantity=qty)
db.add(dri)
db.commit()
return dri.id
def _ks2_close(db, pid, wi_id, qty=Decimal("10"), number="K2-1"):
draft = save_ks2_draft(db, pid, number, date(2026, 3, 1), None,
[(wi_id, qty)],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db.commit()
return issue_ks2(db, pid, draft.id)
# ---------------------------------------------------------------------------
# Lifecycle
# ---------------------------------------------------------------------------
def test_approved_can_be_cancelled(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
result = cancel_agreement(db_session, a)
assert result.status == "cancelled"
def test_draft_cannot_be_cancelled(db_session, project_id):
a = _make_draft_agreement(db_session, project_id)
with pytest.raises(ValueError, match="Черновик"):
cancel_agreement(db_session, a)
assert db_session.get(Agreement, a.id).status == "draft"
def test_cancelled_cannot_be_cancelled_again(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
with pytest.raises(ValueError, match="уже отменено"):
cancel_agreement(db_session, a)
def test_cancelled_cannot_be_approved(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
with pytest.raises(ValueError, match="draft"):
approve_agreement(db_session, a.id)
def test_cancelled_cannot_be_deleted(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
with pytest.raises(ValueError, match="draft"):
delete_draft_agreement(db_session, a)
# ---------------------------------------------------------------------------
# Effective plan
# ---------------------------------------------------------------------------
def test_increase_disappears_after_cancel(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("50"))
db_session.commit()
approve_agreement(db_session, a.id)
plan = build_effective_plan(db_session, project_id)
row = next(r for r in plan["items"] if r.item.id == wi.id)
assert row.quantity == Decimal("150.0000") # 100 + 50
cancel_agreement(db_session, a)
plan = build_effective_plan(db_session, project_id)
row = next(r for r in plan["items"] if r.item.id == wi.id)
assert row.quantity == Decimal("100.0000")
def test_decrease_disappears_after_cancel(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("-20"))
db_session.commit()
approve_agreement(db_session, a.id)
plan = build_effective_plan(db_session, project_id)
row = next(r for r in plan["items"] if r.item.id == wi.id)
assert row.quantity == Decimal("80.0000") # 100 - 20
cancel_agreement(db_session, a)
plan = build_effective_plan(db_session, project_id)
row = next(r for r in plan["items"] if r.item.id == wi.id)
assert row.quantity == Decimal("100.0000")
def test_new_position_disappears_after_cancel(db_session, project_id):
doc = db_session.query(BoqDocument).filter_by(project_id=project_id).one()
system = db_session.query(System).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
line = add_new_item(
db_session, a, name="New pos", model=None, manufacturer=None,
unit="шт", quantity_delta=Decimal("10"), unit_price=Decimal("5"),
system_id=system.id, source_boq_document_id=doc.id,
)
db_session.commit()
new_wi_id = line.work_item_id
approve_agreement(db_session, a.id)
plan = build_effective_plan(db_session, project_id)
assert new_wi_id in {r.item.id for r in plan["items"]}
cancel_agreement(db_session, a)
plan = build_effective_plan(db_session, project_id)
assert new_wi_id not in {r.item.id for r in plan["items"]}
def test_actual_not_changed_after_cancel(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("50"))
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("140"))
from app.services.project_dashboard import build_project_dashboard
before = build_project_dashboard(db_session, db_session.get(Project, project_id))
assert before["performed_cost"] > 0
cancel_agreement(db_session, a)
after = build_project_dashboard(db_session, db_session.get(Project, project_id))
assert after["performed_cost"] == before["performed_cost"]
# actual > plan warning appears
assert after["over_plan_count"] > 0
# ---------------------------------------------------------------------------
# Cancellation blocking (KS-2 closed volume)
# ---------------------------------------------------------------------------
def test_cancel_allowed_without_ks2(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
reason = agreement_cancel_block_reason(db_session, a)
assert reason is None
cancel_agreement(db_session, a)
assert db_session.get(Agreement, a.id).status == "cancelled"
def test_cancel_rejected_when_work_item_closed_in_ks2(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("50"))
_ks2_close(db_session, project_id, wi.id, Decimal("10"))
reason = agreement_cancel_block_reason(db_session, a)
assert reason is not None
assert "КС-2" in reason
with pytest.raises(ValueError, match="КС-2"):
cancel_agreement(db_session, a)
assert db_session.get(Agreement, a.id).status == "approved"
def test_cancelled_ks2_does_not_block(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("50"))
ks2 = _ks2_close(db_session, project_id, wi.id, Decimal("10"))
# Cancel the KS-2
from app.services.ks2_service import cancel_ks2
cancel_ks2(db_session, project_id, ks2.id)
reason = agreement_cancel_block_reason(db_session, a)
assert reason is None
cancel_agreement(db_session, a)
assert db_session.get(Agreement, a.id).status == "cancelled"
def test_new_position_closed_blocks_cancel(db_session, project_id):
doc = db_session.query(BoqDocument).filter_by(project_id=project_id).one()
system = db_session.query(System).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
line = add_new_item(
db_session, a, name="New pos", model=None, manufacturer=None,
unit="шт", quantity_delta=Decimal("10"), unit_price=Decimal("5"),
system_id=system.id, source_boq_document_id=doc.id,
)
db_session.commit()
new_wi_id = line.work_item_id
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, new_wi_id, Decimal("5"))
_ks2_close(db_session, project_id, new_wi_id, Decimal("5"), number="K2-NP")
reason = agreement_cancel_block_reason(db_session, a)
assert reason is not None
with pytest.raises(ValueError, match="КС-2"):
cancel_agreement(db_session, a)
def test_new_position_without_close_allows_cancel(db_session, project_id):
doc = db_session.query(BoqDocument).filter_by(project_id=project_id).one()
system = db_session.query(System).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
line = add_new_item(
db_session, a, name="New pos", model=None, manufacturer=None,
unit="шт", quantity_delta=Decimal("10"), unit_price=Decimal("5"),
system_id=system.id, source_boq_document_id=doc.id,
)
db_session.commit()
approve_agreement(db_session, a.id)
reason = agreement_cancel_block_reason(db_session, a)
assert reason is None
cancel_agreement(db_session, a)
assert db_session.get(Agreement, a.id).status == "cancelled"
# ---------------------------------------------------------------------------
# Rollback
# ---------------------------------------------------------------------------
def test_rollback_preserves_approved_status(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("50"))
_ks2_close(db_session, project_id, wi.id, Decimal("10"))
# cancel fails → rollback → still approved
with pytest.raises(ValueError):
cancel_agreement(db_session, a)
db_session.rollback()
assert db_session.get(Agreement, a.id).status == "approved"
# ---------------------------------------------------------------------------
# Export / Import
# ---------------------------------------------------------------------------
def test_export_import_cancelled_agreement(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id, number="A-CAN")
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
data, _ = export_project(db_session, project_id)
reset_database(db_session)
imported = import_project(db_session, data)
new_a = db_session.query(Agreement).filter_by(project_id=imported.id, number="A-CAN").one()
assert new_a.status == "cancelled"
# Items preserved
items = db_session.query(AgreementItem).filter_by(agreement_id=new_a.id).all()
assert len(items) == 1
assert items[0].change_type == "increase"
assert items[0].quantity_delta == Decimal("10.0000")
# Effective plan ignores cancelled
plan = build_effective_plan(db_session, imported.id)
new_wi = db_session.query(WorkItem).filter_by(project_id=imported.id).one()
row = next(r for r in plan["items"] if r.item.id == new_wi.id)
assert row.quantity == Decimal("100.0000") # base only, no +10
# ---------------------------------------------------------------------------
# HTTP / UI
# ---------------------------------------------------------------------------
from fastapi.testclient import TestClient # noqa: E402
def test_ui_cancelled_shows_otpmeneno(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
def override():
yield db_session
app.dependency_overrides[agreement_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
page = client.get(f"/projects/{project_id}/agreements/{a.id}")
assert page.status_code == 200
assert "ОТМЕНЕНО" in page.text
assert "Отменить ДС" not in page.text
assert "Удалить ДС" not in page.text
finally:
app.dependency_overrides.clear()
def test_ui_approved_shows_cancel_button(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
def override():
yield db_session
app.dependency_overrides[agreement_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
page = client.get(f"/projects/{project_id}/agreements/{a.id}")
assert page.status_code == 200
assert "Отменить ДС" in page.text
assert "cancelAgreementModal" in page.text
finally:
app.dependency_overrides.clear()
def test_http_cancel_redirects(db_session, project_id):
wi = db_session.query(WorkItem).filter_by(project_id=project_id).one()
a = _make_draft_agreement(db_session, project_id)
add_existing_item(db_session, a, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
def override():
yield db_session
app.dependency_overrides[agreement_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
resp = client.post(
f"/projects/{project_id}/agreements/{a.id}/cancel",
follow_redirects=False,
)
assert resp.status_code == 303
assert db_session.get(Agreement, a.id).status == "cancelled"
finally:
app.dependency_overrides.clear()