feat(web): editare celule in preview + Acasa unificata (PRD 3.6)
Implementeaza PRD 3.6 (US-001..007), pe canalul de import + stratul web;
worker / masina stari / idempotenta / mapare raman neatinse.
- US-003/004: tab-ul "Trimiteri" eliminat; Trimiterile devin sectiune
permanenta sub upload pe Acasa ("Trimiterile tale"); upload comprimat la
bara slim (hero pastrat la first-run); ?tab=coada si /_fragments/coada
servesc Acasa (fara fragment orfan); poll gated pe visibilityState.
- US-001: coloana noua import_rows.override_json (nullable, Fernet, Approach B)
+ _migrate defensiv; ruta v1 + alias web .../rand/{i}/editeaza aplica patch
canonic ULTIMUL in _resolve_row_for_preview si commit_import (mutatie pura,
status rederivat, fara drift). Scoping JOIN -> 404, guard committed -> 409,
semantica empty=clear, decrypt fail -> no-op.
- US-002: buton "Editeaza" pe rand; swap pe <tr> + OOB contoare (nu pe sectiune);
form propriu (confirm dezactivat la editare); refoloseste grila responsiva +
error-map din _trimitere_detaliu.html; mutual-exclusion intre randuri.
- US-005/006: "De rezolvat", "Operatii salvate" si "Formate de coloane" ca
tabele (.tablewrap); H4: comutatorul reflecta auto_send STOCAT.
- US-007: bifa "auto-send" devine comutator etichetat pe COADA ("Pune automat
in coada" / "Tine pentru verificare"), scoped pe operatie; name="auto_send"
pastrat (semantica de prezenta -> bool corect cu ambele parsere, zero backend).
Fix-uri gasite la verificarea E2E in browser (htmx 1.9.12, JS — invizibile la
TestClient): useTemplateFragments=true (raspuns <tr>+OOB era parsat in context
de tabel -> swapError + contoare pierdute); re-activarea confirm-btn dupa salvare
deferita pe tick (evita editing=true tranzitoriu); n-hint actualizat de updateN.
Teste: 523 passed. E2E browser: Acasa unificata, upload slim, editare rand
(needs_data -> ok, swap pe rand, contoare OOB), Mapari tabelar + comutator.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -42,6 +42,8 @@ from ..api.v1.import_router import (
|
||||
_fuzzy_suggest_column,
|
||||
_resolve_row_for_preview,
|
||||
_signature,
|
||||
apply_row_override,
|
||||
EDIT_FIELDS,
|
||||
)
|
||||
from ..config import get_settings
|
||||
from ..crypto import decrypt_creds, encrypt_creds
|
||||
@@ -130,7 +132,9 @@ def _rar_state(hb, worker_alive: bool) -> str:
|
||||
|
||||
# US-002: "import" nu mai e tab separat — importul traieste pe Acasa. ?tab=import
|
||||
# cade pe Acasa (tab invalid -> fallback "acasa" in dashboard()), fara 404.
|
||||
_TABS_VALIDE = {"acasa", "coada", "mapari", "cont", "nomenclator"}
|
||||
# US-003 (3.6): "coada" (Trimiteri) nu mai e tab — Trimiterile sunt sectiune pe Acasa.
|
||||
# ?tab=coada cade tot pe Acasa (fallback), fara 404, fara fragment orfan.
|
||||
_TABS_VALIDE = {"acasa", "mapari", "cont", "nomenclator"}
|
||||
|
||||
|
||||
def _get_acasa_context(request: Request, conn, account_id: int) -> dict:
|
||||
@@ -162,11 +166,17 @@ def _get_acasa_context(request: Request, conn, account_id: int) -> dict:
|
||||
).fetchone()
|
||||
are_cheie_folosita = row_key is not None
|
||||
|
||||
# US-003 (3.6): contorul de atentie (blocate) se reflecta in heading-ul
|
||||
# sectiunii "Trimiterile tale" de pe Acasa, nu pe un tab disparut.
|
||||
counts = _status_counts(conn, account_id)
|
||||
blocate_total = sum(counts.get(s, 0) for s in _BLOCKED)
|
||||
|
||||
return {
|
||||
"request": request,
|
||||
"are_creds": are_creds,
|
||||
"are_trimiteri": are_trimiteri,
|
||||
"are_cheie_folosita": are_cheie_folosita,
|
||||
"blocate_total": blocate_total,
|
||||
# US-002: Acasa include caseta de upload -> are nevoie de csrf_token
|
||||
"csrf_token": get_csrf_token(request),
|
||||
}
|
||||
@@ -190,9 +200,10 @@ def _render_panel_import(request: Request) -> str:
|
||||
})
|
||||
|
||||
|
||||
def _render_panel_coada(request: Request) -> str:
|
||||
"""Randeaza panoul Coada ca string HTML."""
|
||||
return templates.get_template("_coada.html").render({"request": request})
|
||||
def _render_panel_coada(request: Request, conn=None, account_id: int = 1) -> str:
|
||||
"""US-003 (3.6): "coada" nu mai e panou propriu — serveste continutul Acasa
|
||||
(Trimiterile sunt sectiune pe Acasa). Pastrat ca alias pentru deep-link/bookmark vechi."""
|
||||
return _render_panel_acasa(request, conn, account_id)
|
||||
|
||||
|
||||
def _render_panel_mapari(request: Request, conn, account_id: int) -> str:
|
||||
@@ -243,7 +254,7 @@ def _render_panel_for_tab(request: Request, conn, account_id: int, tab: str) ->
|
||||
if tab == "import":
|
||||
return _render_panel_import(request)
|
||||
if tab == "coada":
|
||||
return _render_panel_coada(request)
|
||||
return _render_panel_coada(request, conn, account_id)
|
||||
if tab == "mapari":
|
||||
return _render_panel_mapari(request, conn, account_id)
|
||||
if tab == "cont":
|
||||
@@ -266,11 +277,11 @@ def dashboard(request: Request, tab: str = "acasa") -> HTMLResponse:
|
||||
conn = get_connection()
|
||||
try:
|
||||
panel_html = _render_panel_for_tab(request, conn, account_id, active_tab)
|
||||
# Badge contoare pe tab-uri (US-011): needs_mapping -> Mapari, blocate -> Trimiteri.
|
||||
# Badge contoare pe tab-uri (US-011): needs_mapping -> Mapari. Blocatele
|
||||
# (fost badge "coada") se reflecta acum in heading-ul sectiunii Trimiteri (US-003).
|
||||
counts = _status_counts(conn, account_id)
|
||||
badges = {
|
||||
"mapari": counts.get("needs_mapping", 0),
|
||||
"coada": sum(counts.get(s, 0) for s in _BLOCKED),
|
||||
}
|
||||
ctx = {
|
||||
"request": request,
|
||||
@@ -308,9 +319,16 @@ def fragment_import(request: Request) -> HTMLResponse:
|
||||
|
||||
@router.get("/_fragments/coada", response_class=HTMLResponse)
|
||||
def fragment_coada(request: Request) -> HTMLResponse:
|
||||
"""Fragment HTMX pentru tab-ul Coada — include coada submissions (US-003)."""
|
||||
require_login(request)
|
||||
return templates.TemplateResponse("_coada.html", {"request": request})
|
||||
"""US-003 (3.6): "coada" nu mai are fragment propriu. Serveste continutul Acasa
|
||||
(Trimiterile sunt sectiune permanenta pe Acasa) — evita un fragment `_coada.html`
|
||||
orfan din bookmark-uri/HTMX vechi. Nu da 404."""
|
||||
account_id = require_login(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
ctx = _get_acasa_context(request, conn, account_id)
|
||||
return templates.TemplateResponse("_acasa.html", ctx)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/_fragments/nomenclator", response_class=HTMLResponse)
|
||||
@@ -1025,20 +1043,23 @@ def _web_compute_preview(
|
||||
return "Batch de import inexistent sau inaccesibil."
|
||||
|
||||
raw_rows_db = conn.execute(
|
||||
"SELECT row_index, raw_json FROM import_rows WHERE batch_id=? ORDER BY row_index",
|
||||
"SELECT row_index, raw_json, override_json FROM import_rows WHERE batch_id=? ORDER BY row_index",
|
||||
(import_id,),
|
||||
).fetchall()
|
||||
if not raw_rows_db:
|
||||
return "Niciun rand in batch."
|
||||
|
||||
# Decripteaza randurile
|
||||
# Decripteaza randurile + override-urile editate (3.6)
|
||||
rows: list[dict[str, Any]] = []
|
||||
overrides: list[dict[str, Any]] = []
|
||||
for r in raw_rows_db:
|
||||
try:
|
||||
row_data = decrypt_creds(r["raw_json"]) or {}
|
||||
except Exception:
|
||||
row_data = {}
|
||||
rows.append(row_data)
|
||||
ov = decrypt_creds(r["override_json"]) if r["override_json"] else None
|
||||
overrides.append(ov or {})
|
||||
|
||||
col_names = list(rows[0].keys()) if rows else []
|
||||
sig = _signature(col_names)
|
||||
@@ -1098,6 +1119,7 @@ def _web_compute_preview(
|
||||
mapping=mapping,
|
||||
mapping_meta=mapping_meta,
|
||||
formula_columns=formula_columns,
|
||||
override=overrides[i] or None,
|
||||
)
|
||||
|
||||
key: str | None = None
|
||||
@@ -1409,6 +1431,118 @@ def web_preview_import(
|
||||
conn.close()
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
# US-002 (3.6) — Editare celule in preview: mod editare pe rand. #
|
||||
# Swap pe rand (#preview-row-N) + OOB contoare, NU pe #import-section (D-3.1). #
|
||||
# Status rederivat DOAR prin _resolve_row_for_preview (H2 — fara clasificator). #
|
||||
# =========================================================================== #
|
||||
|
||||
def _preview_one_row(conn, import_id: int, account_id: int, row_index: int):
|
||||
"""Recalculeaza preview-ul si extrage un singur rand.
|
||||
|
||||
Statusul e rederivat prin `_resolve_row_for_preview` (H2, fara clasificator duplicat),
|
||||
iar `_web_compute_preview` persista `resolved_status` pentru toate randurile — astfel
|
||||
confirmarea (commit) vede starea editata. Intoarce (result, row) sau (mesaj, None)."""
|
||||
result = _web_compute_preview(conn, import_id, account_id)
|
||||
if isinstance(result, str):
|
||||
return result, None
|
||||
row = next((r for r in result["rows"] if r["row_index"] == row_index), None)
|
||||
return result, row
|
||||
|
||||
|
||||
def _render_preview_rand(
|
||||
request: Request, *, import_id: int, row: dict, editing: bool,
|
||||
include_oob: bool, summary: dict, message: str | None = None,
|
||||
) -> HTMLResponse:
|
||||
return templates.TemplateResponse("_preview_rand.html", {
|
||||
"request": request,
|
||||
"import_id": import_id,
|
||||
"row": row,
|
||||
"editing": editing,
|
||||
"include_oob": include_oob,
|
||||
"summary": summary,
|
||||
"message": message,
|
||||
"csrf_token": get_csrf_token(request),
|
||||
})
|
||||
|
||||
|
||||
@router.get("/_import/{import_id}/rand/{row_index}/editare", response_class=HTMLResponse)
|
||||
def web_rand_editare(request: Request, import_id: int, row_index: int) -> HTMLResponse:
|
||||
"""Intra in mod editare pe un rand de preview (randul devine FORM propriu, D-3.3)."""
|
||||
account_id = require_login(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
result, row = _preview_one_row(conn, import_id, account_id, row_index)
|
||||
if row is None or isinstance(result, str):
|
||||
raise HTTPException(status_code=404, detail="rand de import inexistent")
|
||||
return _render_preview_rand(
|
||||
request, import_id=import_id, row=row, editing=True,
|
||||
include_oob=False, summary=result["summary"],
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/_import/{import_id}/rand/{row_index}", response_class=HTMLResponse)
|
||||
def web_rand_display(request: Request, import_id: int, row_index: int) -> HTMLResponse:
|
||||
"""Iese din mod editare (Anuleaza) — re-randeaza randul read-only + OOB contoare."""
|
||||
account_id = require_login(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
result, row = _preview_one_row(conn, import_id, account_id, row_index)
|
||||
if row is None or isinstance(result, str):
|
||||
raise HTTPException(status_code=404, detail="rand de import inexistent")
|
||||
return _render_preview_rand(
|
||||
request, import_id=import_id, row=row, editing=False,
|
||||
include_oob=True, summary=result["summary"],
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/_import/{import_id}/rand/{row_index}/editeaza", response_class=HTMLResponse)
|
||||
async def web_editeaza_rand(request: Request, import_id: int, row_index: int) -> HTMLResponse:
|
||||
"""Alias web (US-001/US-002): persista override (mutatie pura) + re-randeaza DOAR randul.
|
||||
|
||||
Statusul e rederivat prin `_resolve_row_for_preview` (H2). Swap pe rand + OOB
|
||||
contoare (D-3.1). Daca raman erori de continut pe camp, randul ramane in editare
|
||||
cu valorile pastrate si mesajul pe campul vinovat (D-2.1/D-2.2)."""
|
||||
account_id = require_login(request)
|
||||
form = await request.form()
|
||||
verify_csrf(request, str(form.get("csrf_token") or ""))
|
||||
fields: dict[str, str | None] = {
|
||||
camp: (str(form.get(camp)) if form.get(camp) is not None else None)
|
||||
for camp in EDIT_FIELDS
|
||||
}
|
||||
conn = get_connection()
|
||||
try:
|
||||
# Mutatie pura de stocare (404/409/422 -> propaga; htmx hx-on::response-error
|
||||
# pastreaza randul + valorile la 4xx/5xx).
|
||||
apply_row_override(
|
||||
conn, import_id=import_id, account_id=account_id,
|
||||
row_index=row_index, fields=fields,
|
||||
)
|
||||
result, row = _preview_one_row(conn, import_id, account_id, row_index)
|
||||
if row is None or isinstance(result, str):
|
||||
raise HTTPException(status_code=404, detail="rand de import inexistent")
|
||||
field_errors = [
|
||||
e for e in (row.get("errors") or [])
|
||||
if isinstance(e, dict) and e.get("field")
|
||||
]
|
||||
if field_errors:
|
||||
return _render_preview_rand(
|
||||
request, import_id=import_id, row=row, editing=True,
|
||||
include_oob=True, summary=result["summary"],
|
||||
message="Mai sunt valori invalide — corecteaza campurile marcate.",
|
||||
)
|
||||
return _render_preview_rand(
|
||||
request, import_id=import_id, row=row, editing=False,
|
||||
include_oob=True, summary=result["summary"],
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/_import/{import_id}/mapare-operatie", response_class=HTMLResponse)
|
||||
async def web_mapare_operatie(
|
||||
request: Request,
|
||||
@@ -1514,11 +1648,14 @@ async def web_confirma_import(
|
||||
|
||||
# Incarca randurile cu stare ok si needs_review
|
||||
ok_rows_db = conn.execute(
|
||||
"SELECT row_index, raw_json, resolved_status FROM import_rows "
|
||||
"SELECT row_index, raw_json, override_json, resolved_status FROM import_rows "
|
||||
"WHERE batch_id=? AND resolved_status IN ('ok', 'needs_review') ORDER BY row_index",
|
||||
(import_id,),
|
||||
).fetchall()
|
||||
|
||||
def _override_of(r) -> dict:
|
||||
return (decrypt_creds(r["override_json"]) if r["override_json"] else None) or {}
|
||||
|
||||
if not ok_rows_db:
|
||||
# Re-arata preview cu eroare
|
||||
result = _web_compute_preview(conn, import_id, account_id)
|
||||
@@ -1542,7 +1679,8 @@ async def web_confirma_import(
|
||||
except Exception:
|
||||
continue
|
||||
if r["resolved_status"] == "ok":
|
||||
to_enqueue.append({"row_index": r["row_index"], "data": row_data, "status": "ok"})
|
||||
to_enqueue.append({"row_index": r["row_index"], "data": row_data,
|
||||
"override": _override_of(r), "status": "ok"})
|
||||
elif r["resolved_status"] == "needs_review":
|
||||
review_indices.add(r["row_index"])
|
||||
|
||||
@@ -1551,7 +1689,8 @@ async def web_confirma_import(
|
||||
if r["resolved_status"] == "needs_review" and r["row_index"] in reviewed_rows:
|
||||
try:
|
||||
row_data = decrypt_creds(r["raw_json"]) or {}
|
||||
to_enqueue.append({"row_index": r["row_index"], "data": row_data, "status": "needs_review"})
|
||||
to_enqueue.append({"row_index": r["row_index"], "data": row_data,
|
||||
"override": _override_of(r), "status": "needs_review"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1656,6 +1795,17 @@ async def web_confirma_import(
|
||||
"odometru_final": canon["odometru_final"],
|
||||
})
|
||||
|
||||
# Override editat in preview (3.6) — aplicat ULTIMUL, ca in resolver.
|
||||
override = item.get("override") or {}
|
||||
if override:
|
||||
mapped.update(override)
|
||||
canon = canonicalize_row(mapped)
|
||||
mapped.update({
|
||||
"vin": canon["vin"],
|
||||
"nr_inmatriculare": canon["nr_inmatriculare"],
|
||||
"odometru_final": canon["odometru_final"],
|
||||
})
|
||||
|
||||
key = build_key(account_id, canon)
|
||||
|
||||
rows_for_hash.append(json.dumps({
|
||||
@@ -1702,13 +1852,16 @@ async def web_confirma_import(
|
||||
(n_enqueued, import_id),
|
||||
)
|
||||
|
||||
# Succes → drop zone cu mesaj de confirmare
|
||||
# Succes → bara de upload slim cu mesaj de confirmare. are_trimiteri=True:
|
||||
# contul tocmai a pus randuri in coada -> bara ramane slim si dezvaluie
|
||||
# sectiunea "Trimiterile tale" de pe Acasa (US-003/US-004).
|
||||
toctou_msg = f" ({len(toctou)} coliziuni TOCTOU excluse)" if toctou else ""
|
||||
return templates.TemplateResponse("_upload.html", _ctx(
|
||||
request,
|
||||
are_trimiteri=True,
|
||||
message=(
|
||||
f"S-au pus in coada {n_enqueued} prezentari{toctou_msg}. "
|
||||
f"Procesarea incepe in cateva secunde — urmareste coada de mai jos."
|
||||
f"Procesarea incepe in cateva secunde — vezi mai jos, in Trimiterile tale."
|
||||
),
|
||||
))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user