feat: auto-suggest KS-2/KS-3 document numbers
This commit is contained in:
@@ -9,6 +9,7 @@ WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq"
|
||||
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
|
||||
KS2_REPORTING_PERIOD_MIGRATION = "20260925_ks2_reporting_period"
|
||||
PAYMENT_STATUS_MIGRATION = "20260926_payment_status"
|
||||
KS3_NUMBER_UNIQUE_MIGRATION = "20260927_ks3_number_unique"
|
||||
|
||||
|
||||
def run_migrations(engine):
|
||||
@@ -186,6 +187,17 @@ def run_migrations(engine):
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_payments_status ON payments (status)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(PAYMENT_STATUS_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if KS3_NUMBER_UNIQUE_MIGRATION not in applied:
|
||||
duplicates = connection.execute(
|
||||
"SELECT project_id, number FROM ks3_documents GROUP BY project_id, number HAVING COUNT(*) > 1"
|
||||
).fetchall()
|
||||
if duplicates:
|
||||
raise RuntimeError(f"Cannot add unique KS3 numbers: duplicates found {duplicates[:10]}")
|
||||
connection.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS uq_ks3_project_number ON ks3_documents (project_id, number)"
|
||||
)
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(KS3_NUMBER_UNIQUE_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
||||
if violations:
|
||||
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
||||
|
||||
@@ -7,6 +7,7 @@ from app.database.database import Base
|
||||
|
||||
class KS3(Base):
|
||||
__tablename__ = "ks3_documents"
|
||||
__table_args__ = (UniqueConstraint("project_id", "number", name="uq_ks3_project_number"),)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
|
||||
+31
-5
@@ -55,13 +55,28 @@ def _entries_from_form(form):
|
||||
return entries
|
||||
|
||||
|
||||
def _render_selection(request, db, project, document=None, error=None, status_code=200):
|
||||
def _render_selection(request, db, project, document=None, error=None, status_code=200,
|
||||
suggested_number=None, form_values=None):
|
||||
balances = build_work_item_balances(db, project.id)
|
||||
selected = {line.work_item_id: line.quantity for line in document.items} if document else {}
|
||||
if document is not None:
|
||||
selected = {line.work_item_id: line.quantity for line in document.items}
|
||||
elif form_values:
|
||||
selected = {}
|
||||
for key, value in form_values.items():
|
||||
if key.startswith("include_") and value in ("1", "on", "true"):
|
||||
try:
|
||||
item_id = int(key.removeprefix("include_"))
|
||||
except ValueError:
|
||||
continue
|
||||
selected[item_id] = form_values.get(f"quantity_{item_id}", "")
|
||||
else:
|
||||
selected = {}
|
||||
visible = [row for row in balances if row.available_quantity > 0 or row.item.id in selected]
|
||||
return templates.TemplateResponse(name="ks2/form.html", context={
|
||||
"request": request, "project": project, "document": document, "balances": visible,
|
||||
"selected": selected, "error": error,
|
||||
"suggested_number": suggested_number or "",
|
||||
"form_values": form_values or {},
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@@ -77,7 +92,10 @@ async def ks2_list(request: Request, project_id: int, db: Session = Depends(get_
|
||||
@router.get("/{project_id}/ks2/new")
|
||||
async def ks2_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
return _render_selection(request, db, project)
|
||||
from app.models.ks2 import KS2
|
||||
from app.services.document_numbering import next_document_number
|
||||
suggested = next_document_number(db, KS2, project_id)
|
||||
return _render_selection(request, db, project, suggested_number=suggested)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks2")
|
||||
@@ -88,13 +106,19 @@ async def ks2_create(request: Request, project_id: int, number: str = Form(...),
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
entries = _entries_from_form(form)
|
||||
form_values = {key: value for key, value in form.multi_items() if not key.startswith("include_") and not key.startswith("quantity_")}
|
||||
form_values.update({key: value for key, value in form.multi_items()})
|
||||
try:
|
||||
parsed_date = date.fromisoformat(document_date)
|
||||
document = save_draft(db, project_id, number, parsed_date, comment, entries,
|
||||
reporting_period_from=reporting_period_from or None,
|
||||
reporting_period_to=reporting_period_to or None)
|
||||
except ValueError as exc:
|
||||
return _render_selection(request, db, project, error=str(exc), status_code=400)
|
||||
from app.models.ks2 import KS2
|
||||
from app.services.document_numbering import next_document_number
|
||||
suggested = next_document_number(db, KS2, project_id)
|
||||
return _render_selection(request, db, project, error=str(exc), status_code=400,
|
||||
suggested_number=suggested, form_values=form_values)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
||||
|
||||
|
||||
@@ -138,7 +162,9 @@ async def ks2_update(request: Request, project_id: int, ks2_id: int,
|
||||
except ValueError as exc:
|
||||
db.expire_all()
|
||||
document = _document(db, project_id, ks2_id)
|
||||
return _render_selection(request, db, project, document=document, error=str(exc), status_code=400)
|
||||
form_values = {key: value for key, value in form.multi_items()}
|
||||
return _render_selection(request, db, project, document=document, error=str(exc),
|
||||
status_code=400, form_values=form_values)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
||||
|
||||
|
||||
|
||||
+29
-5
@@ -50,12 +50,26 @@ def _ks2_total(ks2):
|
||||
return sum(Decimal(str(item.amount or 0)) for item in ks2.items)
|
||||
|
||||
|
||||
def _render_form(request, db, project, document=None, error=None, status_code=200):
|
||||
def _render_form(request, db, project, document=None, error=None, status_code=200,
|
||||
suggested_number=None, form_values=None):
|
||||
available = available_ks2(db, project.id)
|
||||
selected_ids = {link.ks2_id for link in document.links} if document else set()
|
||||
if document is not None:
|
||||
selected_ids = {link.ks2_id for link in document.links}
|
||||
elif form_values:
|
||||
selected_ids = set()
|
||||
for key, value in form_values.items():
|
||||
if key == "ks2_ids":
|
||||
try:
|
||||
selected_ids.add(int(value))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
else:
|
||||
selected_ids = set()
|
||||
return templates.TemplateResponse(name="ks3/form.html", context={
|
||||
"request": request, "project": project, "document": document,
|
||||
"available_ks2": available, "selected_ids": selected_ids, "error": error,
|
||||
"suggested_number": suggested_number or "",
|
||||
"form_values": form_values or {},
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@@ -71,7 +85,10 @@ async def ks3_list(request: Request, project_id: int, db: Session = Depends(get_
|
||||
@router.get("/{project_id}/ks3/new")
|
||||
async def ks3_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project = _project(db, project_id)
|
||||
return _render_form(request, db, project)
|
||||
from app.models.ks3 import KS3
|
||||
from app.services.document_numbering import next_document_number
|
||||
suggested = next_document_number(db, KS3, project_id)
|
||||
return _render_form(request, db, project, suggested_number=suggested)
|
||||
|
||||
|
||||
@router.post("/{project_id}/ks3")
|
||||
@@ -83,6 +100,7 @@ async def ks3_create(request: Request, project_id: int,
|
||||
project = _project(db, project_id)
|
||||
form = await request.form()
|
||||
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
|
||||
form_values = {key: value for key, value in form.multi_items()}
|
||||
try:
|
||||
parsed_date = date.fromisoformat(document_date)
|
||||
document = save_draft(
|
||||
@@ -91,7 +109,11 @@ async def ks3_create(request: Request, project_id: int,
|
||||
reporting_period_to=reporting_period_to or None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return _render_form(request, db, project, error=str(exc), status_code=400)
|
||||
from app.models.ks3 import KS3
|
||||
from app.services.document_numbering import next_document_number
|
||||
suggested = next_document_number(db, KS3, project_id)
|
||||
return _render_form(request, db, project, error=str(exc), status_code=400,
|
||||
suggested_number=suggested, form_values=form_values)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||
|
||||
|
||||
@@ -141,7 +163,9 @@ async def ks3_update(request: Request, project_id: int, ks3_id: int,
|
||||
except ValueError as exc:
|
||||
db.expire_all()
|
||||
document = _document(db, project_id, ks3_id)
|
||||
return _render_form(request, db, project, document=document, error=str(exc), status_code=400)
|
||||
form_values = {key: value for key, value in form.multi_items()}
|
||||
return _render_form(request, db, project, document=document, error=str(exc),
|
||||
status_code=400, form_values=form_values)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Next document number suggestions for KS-2 / KS-3.
|
||||
|
||||
Separate sequences per document type. Cancelled documents keep their numbers.
|
||||
Numbers stay strings in the model; suggestion is numeric max + 1.
|
||||
"""
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def next_document_number(db: Session, model, project_id: int) -> str:
|
||||
"""Return the next free number for the given document model in a project."""
|
||||
rows = db.query(model.number).filter(model.project_id == project_id).all()
|
||||
max_number = 0
|
||||
for (raw,) in rows:
|
||||
text = str(raw or "").strip()
|
||||
try:
|
||||
value = int(text)
|
||||
except ValueError:
|
||||
continue
|
||||
if value > max_number:
|
||||
max_number = value
|
||||
return str(max_number + 1)
|
||||
@@ -63,6 +63,11 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date,
|
||||
number = (number or "").strip()
|
||||
if not number:
|
||||
raise KS3ValidationError("Укажите номер КС-3")
|
||||
conflict = db.query(KS3).filter(KS3.project_id == project_id, KS3.number == number)
|
||||
if ks3_id is not None:
|
||||
conflict = conflict.filter(KS3.id != ks3_id)
|
||||
if conflict.first():
|
||||
raise KS3ValidationError("КС-3 с таким номером уже существует в проекте")
|
||||
|
||||
period_from = _parse_date(reporting_period_from, "Период с")
|
||||
period_to = _parse_date(reporting_period_to, "Период по")
|
||||
|
||||
@@ -23,29 +23,29 @@
|
||||
<div class="col-md-3">
|
||||
<label for="number" class="form-label">Номер КС-2</label>
|
||||
<input type="text" class="form-control" id="number" name="number" required
|
||||
value="{{ document.number if document else '' }}">
|
||||
value="{{ form_values.get('number', document.number if document else suggested_number) }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="document_date" name="document_date" required
|
||||
value="{{ document.date.isoformat() if document else '' }}">
|
||||
value="{{ form_values.get('document_date', document.date.isoformat() if document else '') }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_from" class="form-label">Период с</label>
|
||||
<input type="date" class="form-control" id="reporting_period_from" name="reporting_period_from" required
|
||||
value="{{ document.reporting_period_from.isoformat() if document and document.reporting_period_from else '' }}">
|
||||
value="{{ form_values.get('reporting_period_from', document.reporting_period_from.isoformat() if document and document.reporting_period_from else '') }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_to" class="form-label">Период по</label>
|
||||
<input type="date" class="form-control" id="reporting_period_to" name="reporting_period_to" required
|
||||
value="{{ document.reporting_period_to.isoformat() if document and document.reporting_period_to else '' }}">
|
||||
value="{{ form_values.get('reporting_period_to', document.reporting_period_to.isoformat() if document and document.reporting_period_to else '') }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-12">
|
||||
<label for="comment" class="form-label">Комментарий</label>
|
||||
<input type="text" class="form-control" id="comment" name="comment"
|
||||
value="{{ document.comment if document and document.comment else '' }}">
|
||||
value="{{ form_values.get('comment', document.comment if document and document.comment else '') }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -21,29 +21,29 @@
|
||||
<div class="col-md-3">
|
||||
<label for="number" class="form-label">Номер КС-3</label>
|
||||
<input type="text" class="form-control" id="number" name="number" required
|
||||
value="{{ document.number if document else '' }}">
|
||||
value="{{ form_values.get('number', document.number if document else suggested_number) }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="document_date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="document_date" name="document_date" required
|
||||
value="{{ document.date.isoformat() if document else '' }}">
|
||||
value="{{ form_values.get('document_date', document.date.isoformat() if document else '') }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_from" class="form-label">Период с</label>
|
||||
<input type="date" class="form-control" id="reporting_period_from" name="reporting_period_from" required
|
||||
value="{{ document.reporting_period_from.isoformat() if document and document.reporting_period_from else '' }}">
|
||||
value="{{ form_values.get('reporting_period_from', document.reporting_period_from.isoformat() if document and document.reporting_period_from else '') }}">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="reporting_period_to" class="form-label">Период по</label>
|
||||
<input type="date" class="form-control" id="reporting_period_to" name="reporting_period_to" required
|
||||
value="{{ document.reporting_period_to.isoformat() if document and document.reporting_period_to else '' }}">
|
||||
value="{{ form_values.get('reporting_period_to', document.reporting_period_to.isoformat() if document and document.reporting_period_to else '') }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-12">
|
||||
<label for="comment" class="form-label">Комментарий</label>
|
||||
<input type="text" class="form-control" id="comment" name="comment"
|
||||
value="{{ document.comment if document and document.comment else '' }}">
|
||||
value="{{ form_values.get('comment', document.comment if document and document.comment else '') }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user