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:
@@ -124,6 +124,7 @@ def _resolve_row_for_preview(
|
|||||||
mapping: dict[str, str],
|
mapping: dict[str, str],
|
||||||
mapping_meta: dict[str, dict],
|
mapping_meta: dict[str, dict],
|
||||||
formula_columns: list[str],
|
formula_columns: list[str],
|
||||||
|
override: dict[str, Any] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Rezolva un rand din import pentru preview: aplica mapare coloane + validare.
|
"""Rezolva un rand din import pentru preview: aplica mapare coloane + validare.
|
||||||
|
|
||||||
@@ -132,6 +133,11 @@ def _resolve_row_for_preview(
|
|||||||
resolved: valorile finale rezolvate (VIN, data, km, prestatii)
|
resolved: valorile finale rezolvate (VIN, data, km, prestatii)
|
||||||
errors: lista erori validare
|
errors: lista erori validare
|
||||||
flags: motive needs_review
|
flags: motive needs_review
|
||||||
|
|
||||||
|
`override` (3.6, Approach B): patch CANONIC editat in preview, aplicat ULTIMUL
|
||||||
|
peste valorile mapate (dupa `json_mapare` si canonicalizare). Permite corectarea
|
||||||
|
unei valori sau completarea unui camp a carui coloana LIPSESTE din fisier, fara
|
||||||
|
sa atinga `raw_json`/idempotency.
|
||||||
"""
|
"""
|
||||||
# Aplica maparea de coloane
|
# Aplica maparea de coloane
|
||||||
mapped: dict[str, Any] = {}
|
mapped: dict[str, Any] = {}
|
||||||
@@ -182,6 +188,11 @@ def _resolve_row_for_preview(
|
|||||||
"odometru_final": canon["odometru_final"],
|
"odometru_final": canon["odometru_final"],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Override editat in preview (3.6) — aplicat ULTIMUL, peste valorile mapate +
|
||||||
|
# canonicalizate. Valorile din override sunt deja canonice (vezi _merge_override).
|
||||||
|
if override:
|
||||||
|
mapped.update(override)
|
||||||
|
|
||||||
# Flags needs_review acumulate
|
# Flags needs_review acumulate
|
||||||
all_flags = list(coercion_flags) + formula_flag
|
all_flags = list(coercion_flags) + formula_flag
|
||||||
if is_ambiguous_date:
|
if is_ambiguous_date:
|
||||||
@@ -244,6 +255,86 @@ def _build_idempotency_key(account_id: int | None, resolved: dict[str, Any]) ->
|
|||||||
return build_key(account_id, canon)
|
return build_key(account_id, canon)
|
||||||
|
|
||||||
|
|
||||||
|
# Campuri de continut editabile in preview (3.6). Operatia/codul RAR NU se editeaza
|
||||||
|
# aici (raman in panoul de mapare) — vezi Non-Goals din PRD 3.6.
|
||||||
|
EDIT_FIELDS = ("vin", "nr_inmatriculare", "data_prestatie", "odometru_initial", "odometru_final")
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_override(current: dict[str, Any], fields: dict[str, str | None]) -> dict[str, Any]:
|
||||||
|
"""Aplica campurile editate peste override-ul curent (mutatie pura).
|
||||||
|
|
||||||
|
Semantica:
|
||||||
|
- valoare None -> camp ne-trimis in cerere -> neschimbat.
|
||||||
|
- valoare "" -> STERGE cheia din override (revine la valoarea din fisier).
|
||||||
|
- valoare negoala -> set valoare CANONICA (vin/nr upper, odometru_final fara ".0").
|
||||||
|
`odometru_initial`/`data_prestatie` se pastreaza stripped (canonicalize_row normeaza
|
||||||
|
doar `_final`; validarea le verifica direct).
|
||||||
|
"""
|
||||||
|
out = dict(current)
|
||||||
|
raw: dict[str, str] = {}
|
||||||
|
for camp in EDIT_FIELDS:
|
||||||
|
val = fields.get(camp)
|
||||||
|
if val is None:
|
||||||
|
continue
|
||||||
|
s = str(val).strip()
|
||||||
|
if s == "":
|
||||||
|
out.pop(camp, None) # empty = clear
|
||||||
|
else:
|
||||||
|
raw[camp] = s
|
||||||
|
if raw:
|
||||||
|
canon = canonicalize_row(raw)
|
||||||
|
for camp in raw:
|
||||||
|
if camp in ("vin", "nr_inmatriculare", "odometru_final"):
|
||||||
|
out[camp] = canon[camp]
|
||||||
|
else:
|
||||||
|
out[camp] = raw[camp]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def apply_row_override(
|
||||||
|
conn,
|
||||||
|
*,
|
||||||
|
import_id: int,
|
||||||
|
account_id: int | None,
|
||||||
|
row_index: int,
|
||||||
|
fields: dict[str, str | None],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Persista override-ul canonic pentru un rand de preview (mutatie PURA de stocare).
|
||||||
|
|
||||||
|
NU recalculeaza statusul si NU atinge `submissions` — preview-ul rederiva statusul
|
||||||
|
prin `_resolve_row_for_preview` (un singur clasificator, fara drift).
|
||||||
|
|
||||||
|
Ridica HTTPException: 404 (rand/batch inexistent sau alt cont — scoping JOIN),
|
||||||
|
409 (batch deja comis), 422 (override curent corupt -> no-op defensiv, fara scriere goala).
|
||||||
|
Intoarce noul dict de override (gol = override sters).
|
||||||
|
"""
|
||||||
|
acct = account_or_default(account_id)
|
||||||
|
# Scoping intr-o singura interogare JOIN -> 404 pe gol (alt cont / batch / row_index).
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT r.id AS rid, r.override_json AS oj, b.status AS bstatus "
|
||||||
|
"FROM import_rows r JOIN import_batches b ON b.id = r.batch_id "
|
||||||
|
"WHERE b.id=? AND b.account_id=? AND r.row_index=?",
|
||||||
|
(import_id, acct, row_index),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="rand de import inexistent")
|
||||||
|
if row["bstatus"] == "committed":
|
||||||
|
raise HTTPException(status_code=409, detail="batch deja comis; editarea nu mai are efect")
|
||||||
|
|
||||||
|
current: dict[str, Any] = {}
|
||||||
|
if row["oj"]:
|
||||||
|
dec = decrypt_creds(row["oj"])
|
||||||
|
if dec is None:
|
||||||
|
# Decrypt fail (cheie schimbata / token corupt): no-op defensiv, NICIODATA scriere goala.
|
||||||
|
raise HTTPException(status_code=422, detail="override curent ilizibil; editare anulata")
|
||||||
|
current = dec
|
||||||
|
|
||||||
|
new_override = _merge_override(current, fields)
|
||||||
|
enc = encrypt_creds(new_override) if new_override else None
|
||||||
|
conn.execute("UPDATE import_rows SET override_json=? WHERE id=?", (enc, row["rid"]))
|
||||||
|
return new_override
|
||||||
|
|
||||||
|
|
||||||
def _already_sent_lookup(conn, account_id: int, keys: list[str]) -> dict[str, dict]:
|
def _already_sent_lookup(conn, account_id: int, keys: list[str]) -> dict[str, dict]:
|
||||||
"""Cauta cheile de idempotenta in submissions (batch, nu N+1 — Eng#5).
|
"""Cauta cheile de idempotenta in submissions (batch, nu N+1 — Eng#5).
|
||||||
|
|
||||||
@@ -589,21 +680,24 @@ def preview_import(
|
|||||||
|
|
||||||
# Incarca toate randurile
|
# Incarca toate randurile
|
||||||
raw_rows_db = conn.execute(
|
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,),
|
(import_id,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
|
||||||
if not raw_rows_db:
|
if not raw_rows_db:
|
||||||
return {"rows": [], "summary": {}}
|
return {"rows": [], "summary": {}}
|
||||||
|
|
||||||
# Decripteaza si reconstruieste randurile
|
# Decripteaza si reconstruieste randurile + override-urile editate (3.6)
|
||||||
rows: list[dict] = []
|
rows: list[dict] = []
|
||||||
|
overrides: list[dict] = []
|
||||||
for r in raw_rows_db:
|
for r in raw_rows_db:
|
||||||
try:
|
try:
|
||||||
row_data = decrypt_creds(r["raw_json"])
|
row_data = decrypt_creds(r["raw_json"])
|
||||||
rows.append(row_data or {})
|
rows.append(row_data or {})
|
||||||
except Exception:
|
except Exception:
|
||||||
rows.append({})
|
rows.append({})
|
||||||
|
ov = decrypt_creds(r["override_json"]) if r["override_json"] else None
|
||||||
|
overrides.append(ov or {})
|
||||||
|
|
||||||
# Obtine coloanele
|
# Obtine coloanele
|
||||||
col_names = list(rows[0].keys()) if rows else []
|
col_names = list(rows[0].keys()) if rows else []
|
||||||
@@ -681,6 +775,7 @@ def preview_import(
|
|||||||
mapping=mapping,
|
mapping=mapping,
|
||||||
mapping_meta=mapping_meta,
|
mapping_meta=mapping_meta,
|
||||||
formula_columns=formula_columns,
|
formula_columns=formula_columns,
|
||||||
|
override=overrides[i] or None,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Calculeaza cheia de idempotenta pentru randurile ok/needs_review
|
# Calculeaza cheia de idempotenta pentru randurile ok/needs_review
|
||||||
@@ -824,7 +919,7 @@ def commit_import(
|
|||||||
|
|
||||||
# Incarca randurile cu stare ok sau needs_review
|
# Incarca randurile cu stare ok sau needs_review
|
||||||
ok_rows_db = conn.execute(
|
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",
|
"WHERE batch_id=? AND resolved_status IN ('ok', 'needs_review') ORDER BY row_index",
|
||||||
(import_id,),
|
(import_id,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
@@ -832,6 +927,9 @@ def commit_import(
|
|||||||
if not ok_rows_db:
|
if not ok_rows_db:
|
||||||
raise HTTPException(status_code=422, detail="Niciun rand ok de confirmat in acest batch.")
|
raise HTTPException(status_code=422, detail="Niciun rand ok de confirmat in acest batch.")
|
||||||
|
|
||||||
|
def _override_of(r) -> dict:
|
||||||
|
return (decrypt_creds(r["override_json"]) if r["override_json"] else None) or {}
|
||||||
|
|
||||||
# Decripteaza randurile ok
|
# Decripteaza randurile ok
|
||||||
ok_rows: list[dict] = []
|
ok_rows: list[dict] = []
|
||||||
ok_indices: list[int] = []
|
ok_indices: list[int] = []
|
||||||
@@ -846,7 +944,8 @@ def commit_import(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if r["resolved_status"] == "ok":
|
if r["resolved_status"] == "ok":
|
||||||
ok_rows.append({"row_index": r["row_index"], "data": row_data, "status": "ok"})
|
ok_rows.append({"row_index": r["row_index"], "data": row_data,
|
||||||
|
"override": _override_of(r), "status": "ok"})
|
||||||
ok_indices.append(r["row_index"])
|
ok_indices.append(r["row_index"])
|
||||||
elif r["resolved_status"] == "needs_review":
|
elif r["resolved_status"] == "needs_review":
|
||||||
review_indices.add(r["row_index"])
|
review_indices.add(r["row_index"])
|
||||||
@@ -860,7 +959,8 @@ def commit_import(
|
|||||||
try:
|
try:
|
||||||
row_data = decrypt_creds(r["raw_json"])
|
row_data = decrypt_creds(r["raw_json"])
|
||||||
if row_data:
|
if row_data:
|
||||||
ok_rows.append({"row_index": idx, "data": row_data, "status": "needs_review"})
|
ok_rows.append({"row_index": idx, "data": row_data,
|
||||||
|
"override": _override_of(r), "status": "needs_review"})
|
||||||
ok_indices.append(idx)
|
ok_indices.append(idx)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -964,6 +1064,19 @@ def commit_import(
|
|||||||
"odometru_final": canon["odometru_final"],
|
"odometru_final": canon["odometru_final"],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Override editat in preview (3.6) — aplicat ULTIMUL, ca in resolver.
|
||||||
|
override = ok_row.get("override") or {}
|
||||||
|
if override:
|
||||||
|
mapped.update(override)
|
||||||
|
# Re-canonicalizeaza pentru a obtine cheia IDENTICA cu cea din preview
|
||||||
|
# (_build_idempotency_key = canonicalize_row + build_key peste mapped).
|
||||||
|
canon = canonicalize_row(mapped)
|
||||||
|
mapped.update({
|
||||||
|
"vin": canon["vin"],
|
||||||
|
"nr_inmatriculare": canon["nr_inmatriculare"],
|
||||||
|
"odometru_final": canon["odometru_final"],
|
||||||
|
})
|
||||||
|
|
||||||
# Cheia de idempotenta (identica cu cheia din preview — aceeasi ordine)
|
# Cheia de idempotenta (identica cu cheia din preview — aceeasi ordine)
|
||||||
key = build_key(account_id, canon)
|
key = build_key(account_id, canon)
|
||||||
|
|
||||||
@@ -1033,6 +1146,46 @@ def commit_import(
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# POST /v1/import/{id}/rand/{row_index}/editeaza — editare celule preview (3.6) #
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
class RandEditIn(BaseModel):
|
||||||
|
"""Campuri de continut editabile in preview. None = ne-trimis (neschimbat);
|
||||||
|
"" = sterge override-ul (revine la valoarea din fisier)."""
|
||||||
|
vin: str | None = None
|
||||||
|
nr_inmatriculare: str | None = None
|
||||||
|
data_prestatie: str | None = None
|
||||||
|
odometru_initial: str | None = None
|
||||||
|
odometru_final: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{import_id}/rand/{row_index}/editeaza")
|
||||||
|
def editeaza_rand(
|
||||||
|
import_id: int,
|
||||||
|
row_index: int,
|
||||||
|
req: RandEditIn,
|
||||||
|
account_id: int = Depends(resolve_account_id),
|
||||||
|
) -> dict:
|
||||||
|
"""Persista editarea unui rand de preview (mutatie pura — Approach B, 3.6).
|
||||||
|
|
||||||
|
NU recalculeaza statusul si NU atinge `submissions`; preview-ul rederiva statusul
|
||||||
|
prin `_resolve_row_for_preview` cu override aplicat ultimul.
|
||||||
|
"""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
override = apply_row_override(
|
||||||
|
conn,
|
||||||
|
import_id=import_id,
|
||||||
|
account_id=account_id,
|
||||||
|
row_index=row_index,
|
||||||
|
fields=req.model_dump(),
|
||||||
|
)
|
||||||
|
return {"ok": True, "import_id": import_id, "row_index": row_index, "override": override}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
# GET /v1/import/{id}/export-failed — CSV randuri esuate (T8) #
|
# GET /v1/import/{id}/export-failed — CSV randuri esuate (T8) #
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
|
|||||||
11
app/db.py
11
app/db.py
@@ -79,6 +79,17 @@ def _migrate(conn: sqlite3.Connection) -> None:
|
|||||||
if "email_verified" not in user_cols:
|
if "email_verified" not in user_cols:
|
||||||
conn.execute("ALTER TABLE users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 0")
|
conn.execute("ALTER TABLE users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 0")
|
||||||
|
|
||||||
|
# Coloana import_rows.override_json (3.6, Approach B): patch canonic editat in
|
||||||
|
# preview, criptat Fernet. Defensiv idempotent (ca is_admin in 3.3b) — DB create
|
||||||
|
# inainte de 3.6 nu au coloana.
|
||||||
|
irows_tbl = conn.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='import_rows'"
|
||||||
|
).fetchone()
|
||||||
|
if irows_tbl:
|
||||||
|
irows_cols = {r["name"] for r in conn.execute("PRAGMA table_info(import_rows)").fetchall()}
|
||||||
|
if "override_json" not in irows_cols:
|
||||||
|
conn.execute("ALTER TABLE import_rows ADD COLUMN override_json TEXT")
|
||||||
|
|
||||||
# Index batch_id pe submissions (poate lipsi pe DB veche)
|
# Index batch_id pe submissions (poate lipsi pe DB veche)
|
||||||
existing_idx = {r["name"] for r in conn.execute(
|
existing_idx = {r["name"] for r in conn.execute(
|
||||||
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='submissions'"
|
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='submissions'"
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ CREATE TABLE IF NOT EXISTS import_rows (
|
|||||||
batch_id INTEGER NOT NULL REFERENCES import_batches(id) ON DELETE CASCADE,
|
batch_id INTEGER NOT NULL REFERENCES import_batches(id) ON DELETE CASCADE,
|
||||||
row_index INTEGER NOT NULL,
|
row_index INTEGER NOT NULL,
|
||||||
raw_json TEXT NOT NULL, -- PII criptat (Fernet, ca submissions)
|
raw_json TEXT NOT NULL, -- PII criptat (Fernet, ca submissions)
|
||||||
|
override_json TEXT, -- patch CANONIC editat in preview, criptat Fernet (3.6, Approach B); NULL = fara editare
|
||||||
resolved_status TEXT NOT NULL DEFAULT 'pending'
|
resolved_status TEXT NOT NULL DEFAULT 'pending'
|
||||||
CHECK (resolved_status IN (
|
CHECK (resolved_status IN (
|
||||||
'pending','ok','needs_mapping','needs_data',
|
'pending','ok','needs_mapping','needs_data',
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ from ..api.v1.import_router import (
|
|||||||
_fuzzy_suggest_column,
|
_fuzzy_suggest_column,
|
||||||
_resolve_row_for_preview,
|
_resolve_row_for_preview,
|
||||||
_signature,
|
_signature,
|
||||||
|
apply_row_override,
|
||||||
|
EDIT_FIELDS,
|
||||||
)
|
)
|
||||||
from ..config import get_settings
|
from ..config import get_settings
|
||||||
from ..crypto import decrypt_creds, encrypt_creds
|
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
|
# 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.
|
# 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:
|
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()
|
).fetchone()
|
||||||
are_cheie_folosita = row_key is not None
|
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 {
|
return {
|
||||||
"request": request,
|
"request": request,
|
||||||
"are_creds": are_creds,
|
"are_creds": are_creds,
|
||||||
"are_trimiteri": are_trimiteri,
|
"are_trimiteri": are_trimiteri,
|
||||||
"are_cheie_folosita": are_cheie_folosita,
|
"are_cheie_folosita": are_cheie_folosita,
|
||||||
|
"blocate_total": blocate_total,
|
||||||
# US-002: Acasa include caseta de upload -> are nevoie de csrf_token
|
# US-002: Acasa include caseta de upload -> are nevoie de csrf_token
|
||||||
"csrf_token": get_csrf_token(request),
|
"csrf_token": get_csrf_token(request),
|
||||||
}
|
}
|
||||||
@@ -190,9 +200,10 @@ def _render_panel_import(request: Request) -> str:
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
def _render_panel_coada(request: Request) -> str:
|
def _render_panel_coada(request: Request, conn=None, account_id: int = 1) -> str:
|
||||||
"""Randeaza panoul Coada ca string HTML."""
|
"""US-003 (3.6): "coada" nu mai e panou propriu — serveste continutul Acasa
|
||||||
return templates.get_template("_coada.html").render({"request": request})
|
(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:
|
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":
|
if tab == "import":
|
||||||
return _render_panel_import(request)
|
return _render_panel_import(request)
|
||||||
if tab == "coada":
|
if tab == "coada":
|
||||||
return _render_panel_coada(request)
|
return _render_panel_coada(request, conn, account_id)
|
||||||
if tab == "mapari":
|
if tab == "mapari":
|
||||||
return _render_panel_mapari(request, conn, account_id)
|
return _render_panel_mapari(request, conn, account_id)
|
||||||
if tab == "cont":
|
if tab == "cont":
|
||||||
@@ -266,11 +277,11 @@ def dashboard(request: Request, tab: str = "acasa") -> HTMLResponse:
|
|||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
try:
|
try:
|
||||||
panel_html = _render_panel_for_tab(request, conn, account_id, active_tab)
|
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)
|
counts = _status_counts(conn, account_id)
|
||||||
badges = {
|
badges = {
|
||||||
"mapari": counts.get("needs_mapping", 0),
|
"mapari": counts.get("needs_mapping", 0),
|
||||||
"coada": sum(counts.get(s, 0) for s in _BLOCKED),
|
|
||||||
}
|
}
|
||||||
ctx = {
|
ctx = {
|
||||||
"request": request,
|
"request": request,
|
||||||
@@ -308,9 +319,16 @@ def fragment_import(request: Request) -> HTMLResponse:
|
|||||||
|
|
||||||
@router.get("/_fragments/coada", response_class=HTMLResponse)
|
@router.get("/_fragments/coada", response_class=HTMLResponse)
|
||||||
def fragment_coada(request: Request) -> HTMLResponse:
|
def fragment_coada(request: Request) -> HTMLResponse:
|
||||||
"""Fragment HTMX pentru tab-ul Coada — include coada submissions (US-003)."""
|
"""US-003 (3.6): "coada" nu mai are fragment propriu. Serveste continutul Acasa
|
||||||
require_login(request)
|
(Trimiterile sunt sectiune permanenta pe Acasa) — evita un fragment `_coada.html`
|
||||||
return templates.TemplateResponse("_coada.html", {"request": request})
|
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)
|
@router.get("/_fragments/nomenclator", response_class=HTMLResponse)
|
||||||
@@ -1025,20 +1043,23 @@ def _web_compute_preview(
|
|||||||
return "Batch de import inexistent sau inaccesibil."
|
return "Batch de import inexistent sau inaccesibil."
|
||||||
|
|
||||||
raw_rows_db = conn.execute(
|
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,),
|
(import_id,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
if not raw_rows_db:
|
if not raw_rows_db:
|
||||||
return "Niciun rand in batch."
|
return "Niciun rand in batch."
|
||||||
|
|
||||||
# Decripteaza randurile
|
# Decripteaza randurile + override-urile editate (3.6)
|
||||||
rows: list[dict[str, Any]] = []
|
rows: list[dict[str, Any]] = []
|
||||||
|
overrides: list[dict[str, Any]] = []
|
||||||
for r in raw_rows_db:
|
for r in raw_rows_db:
|
||||||
try:
|
try:
|
||||||
row_data = decrypt_creds(r["raw_json"]) or {}
|
row_data = decrypt_creds(r["raw_json"]) or {}
|
||||||
except Exception:
|
except Exception:
|
||||||
row_data = {}
|
row_data = {}
|
||||||
rows.append(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 []
|
col_names = list(rows[0].keys()) if rows else []
|
||||||
sig = _signature(col_names)
|
sig = _signature(col_names)
|
||||||
@@ -1098,6 +1119,7 @@ def _web_compute_preview(
|
|||||||
mapping=mapping,
|
mapping=mapping,
|
||||||
mapping_meta=mapping_meta,
|
mapping_meta=mapping_meta,
|
||||||
formula_columns=formula_columns,
|
formula_columns=formula_columns,
|
||||||
|
override=overrides[i] or None,
|
||||||
)
|
)
|
||||||
|
|
||||||
key: str | None = None
|
key: str | None = None
|
||||||
@@ -1409,6 +1431,118 @@ def web_preview_import(
|
|||||||
conn.close()
|
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)
|
@router.post("/_import/{import_id}/mapare-operatie", response_class=HTMLResponse)
|
||||||
async def web_mapare_operatie(
|
async def web_mapare_operatie(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -1514,11 +1648,14 @@ async def web_confirma_import(
|
|||||||
|
|
||||||
# Incarca randurile cu stare ok si needs_review
|
# Incarca randurile cu stare ok si needs_review
|
||||||
ok_rows_db = conn.execute(
|
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",
|
"WHERE batch_id=? AND resolved_status IN ('ok', 'needs_review') ORDER BY row_index",
|
||||||
(import_id,),
|
(import_id,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
|
||||||
|
def _override_of(r) -> dict:
|
||||||
|
return (decrypt_creds(r["override_json"]) if r["override_json"] else None) or {}
|
||||||
|
|
||||||
if not ok_rows_db:
|
if not ok_rows_db:
|
||||||
# Re-arata preview cu eroare
|
# Re-arata preview cu eroare
|
||||||
result = _web_compute_preview(conn, import_id, account_id)
|
result = _web_compute_preview(conn, import_id, account_id)
|
||||||
@@ -1542,7 +1679,8 @@ async def web_confirma_import(
|
|||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
if r["resolved_status"] == "ok":
|
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":
|
elif r["resolved_status"] == "needs_review":
|
||||||
review_indices.add(r["row_index"])
|
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:
|
if r["resolved_status"] == "needs_review" and r["row_index"] in reviewed_rows:
|
||||||
try:
|
try:
|
||||||
row_data = decrypt_creds(r["raw_json"]) or {}
|
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:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -1656,6 +1795,17 @@ async def web_confirma_import(
|
|||||||
"odometru_final": canon["odometru_final"],
|
"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)
|
key = build_key(account_id, canon)
|
||||||
|
|
||||||
rows_for_hash.append(json.dumps({
|
rows_for_hash.append(json.dumps({
|
||||||
@@ -1702,13 +1852,16 @@ async def web_confirma_import(
|
|||||||
(n_enqueued, import_id),
|
(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 ""
|
toctou_msg = f" ({len(toctou)} coliziuni TOCTOU excluse)" if toctou else ""
|
||||||
return templates.TemplateResponse("_upload.html", _ctx(
|
return templates.TemplateResponse("_upload.html", _ctx(
|
||||||
request,
|
request,
|
||||||
|
are_trimiteri=True,
|
||||||
message=(
|
message=(
|
||||||
f"S-au pus in coada {n_enqueued} prezentari{toctou_msg}. "
|
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."
|
||||||
),
|
),
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div id="acasa-section">
|
<div id="acasa-section">
|
||||||
|
|
||||||
{# === Centru de greutate: caseta de upload (importul e operatia principala) === #}
|
{# === Centru de greutate: bara de upload (importul e operatia principala) === #}
|
||||||
{% include '_upload.html' %}
|
{% include '_upload.html' %}
|
||||||
|
|
||||||
{# === Subordonat: primii pasi pe un singur rand compact === #}
|
{# === Subordonat: primii pasi pe un singur rand compact === #}
|
||||||
@@ -44,13 +44,21 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{# === Subordonat: ajutor rapid pe un rand discret === #}
|
{# === Subordonat: ajutor rapid pe un rand discret ===
|
||||||
|
US-003 (3.6): linkul redundant "Trimiteri" a fost scos (Trimiterile sunt mai jos
|
||||||
|
pe aceeasi pagina). Wayfinding "Mapari"/"Coduri RAR" pastrat pentru operatori. #}
|
||||||
<div style="margin-top:10px; font-size:13px; color:var(--muted);
|
<div style="margin-top:10px; font-size:13px; color:var(--muted);
|
||||||
display:flex; gap:16px; flex-wrap:wrap; align-items:center;">
|
display:flex; gap:16px; flex-wrap:wrap; align-items:center;">
|
||||||
<span>Ajutor:</span>
|
<span>Ajutor:</span>
|
||||||
<a href="/?tab=coada">Trimiteri</a>
|
|
||||||
<a href="/?tab=mapari">Mapari</a>
|
<a href="/?tab=mapari">Mapari</a>
|
||||||
<a href="/?tab=nomenclator">Coduri RAR</a>
|
<a href="/?tab=nomenclator">Coduri RAR</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{# === Sectiunea Trimiteri ("Trimiterile tale"), permanenta sub upload (US-003).
|
||||||
|
Suprimata la first-run (zero trimiteri): bara de upload acopera deja CTA-ul,
|
||||||
|
iar empty-state-ul tabelului ar fi redundant (US-004 / D-5.1). === #}
|
||||||
|
{% if are_trimiteri %}
|
||||||
|
{% include '_coada.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,20 @@
|
|||||||
<div id="coada-section">
|
{#
|
||||||
|
_coada.html — repurposat in 3.6 (US-003).
|
||||||
|
Nu mai e un tab/panou separat: e sectiunea "Trimiterile tale" inclusa pe Acasa,
|
||||||
|
sub zona de upload. Pastreaza filtrele (US-009), tabelul (_submissions.html) si
|
||||||
|
panoul de detaliu (#trimitere-detaliu). Poll aliniat la 15s (anti dublu-poll, M5).
|
||||||
|
#}
|
||||||
|
<section id="trimiteri-section" aria-labelledby="trimiteri-heading"
|
||||||
|
style="margin-top:22px; padding-top:18px; border-top:2px solid var(--line);">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:0 0 12px;">
|
<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:0 0 12px;">
|
||||||
<h2 style="font-size:15px; margin:0;">Trimiteri catre RAR</h2>
|
<h2 id="trimiteri-heading" style="font-size:15px; margin:0;">
|
||||||
|
Trimiterile tale
|
||||||
|
{% if blocate_total %}
|
||||||
|
<span class="tab-badge" title="{{ blocate_total }} necesita atentie"
|
||||||
|
style="display:inline-flex; align-items:center; justify-content:center; min-width:18px; height:18px; margin-left:6px; padding:0 5px; border-radius:99px; background:var(--err); color:#fff; font-size:11px; font-weight:700;">{{ blocate_total }}</span>
|
||||||
|
{% endif %}
|
||||||
|
</h2>
|
||||||
<span style="margin-left:auto; display:flex; gap:8px; flex-wrap:wrap;">
|
<span style="margin-left:auto; display:flex; gap:8px; flex-wrap:wrap;">
|
||||||
<a class="cardlink" href="/v1/audit/export?status=sent" download>export CSV: trimise</a>
|
<a class="cardlink" href="/v1/audit/export?status=sent" download>export CSV: trimise</a>
|
||||||
<a class="cardlink" href="/v1/audit/export?status=all" download>toate</a>
|
<a class="cardlink" href="/v1/audit/export?status=all" download>toate</a>
|
||||||
@@ -42,14 +55,15 @@
|
|||||||
<button type="submit">Filtreaza</button>
|
<button type="submit">Filtreaza</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<!-- Poll aliniat la 15s ca status-ul (M5: nu doua timere perpetue pe pagina mereu deschisa) -->
|
||||||
<div id="submissions-wrap"
|
<div id="submissions-wrap"
|
||||||
hx-get="/_fragments/submissions" hx-trigger="load, every 10s"
|
hx-get="/_fragments/submissions" hx-trigger="load, every 15s"
|
||||||
hx-include="#filtre-trimiteri" hx-swap="innerHTML">
|
hx-include="#filtre-trimiteri" hx-swap="innerHTML">
|
||||||
<div class="empty">se incarca…</div>
|
<div class="empty">se incarca…</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Panou dedicat pentru detaliul trimiterii (NU inline in tabel: poll-ul de 10s
|
<!-- Panou dedicat pentru detaliul trimiterii (NU inline in tabel: poll-ul din tabel
|
||||||
din tabel ar sterge un expand inline). Gol pana la click pe un rand. -->
|
ar sterge un expand inline). Gol pana la click pe un rand. -->
|
||||||
<div id="trimitere-detaliu"></div>
|
<div id="trimitere-detaliu"></div>
|
||||||
</div>
|
</section>
|
||||||
|
|||||||
26
app/web/templates/_macros.html
Normal file
26
app/web/templates/_macros.html
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{# Macro-uri partajate intre template-urile de import si mapari. #}
|
||||||
|
|
||||||
|
{# US-007: comutator pe COADA in loc de bifa "auto-send".
|
||||||
|
Framing pe punerea in coada, NU pe trimitere (poarta autoplan UC-A): etichetele
|
||||||
|
poarta singure sensul de send-safety. `name="auto_send" value="true"` pastrat cu
|
||||||
|
semantica de prezenta (bifat -> True, nebifat -> absent -> False) ca sa produca
|
||||||
|
bool corect cu AMBELE parsere backend (Form(bool) la /mapari, bool(form.get())
|
||||||
|
la /_import/.../mapare-operatie). Zero atingere backend.
|
||||||
|
- form_id: leaga input-ul de un <form> extern (necesar in celulele de tabel).
|
||||||
|
- checked: starea initiala (H4 - reflecta valoarea STOCATA per mapare). #}
|
||||||
|
{% macro autosend_toggle(form_id='', checked=True) -%}
|
||||||
|
<div class="autosend-toggle" style="display:flex; flex-direction:column; gap:4px;">
|
||||||
|
<span class="muted" style="font-size:12px;">La fisierele viitoare cu aceasta operatie:</span>
|
||||||
|
<label class="chk" style="display:inline-flex; align-items:center; gap:8px; min-height:44px;">
|
||||||
|
<input type="checkbox" name="auto_send" value="true"
|
||||||
|
{%- if form_id %} form="{{ form_id }}"{% endif %}
|
||||||
|
{%- if checked %} checked{% endif %}
|
||||||
|
aria-label="Pune automat in coada la fisierele viitoare cu aceasta operatie">
|
||||||
|
<span><strong>Pune automat in coada</strong></span>
|
||||||
|
</label>
|
||||||
|
<span class="muted" style="font-size:11px;">
|
||||||
|
Nebifat = "Tine pentru verificare". Doar pentru aceasta operatie;
|
||||||
|
nimic nu pleaca la RAR pana confirmi.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{%- endmacro %}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
{% import '_macros.html' as ui %}
|
||||||
<div id="mapari-section">
|
<div id="mapari-section">
|
||||||
|
|
||||||
{% if message %}
|
{% if message %}
|
||||||
@@ -21,47 +22,58 @@
|
|||||||
Alege codul RAR (sugestia fuzzy e preselectata) si salveaza — submission-urile se deblocheaza automat.
|
Alege codul RAR (sugestia fuzzy e preselectata) si salveaza — submission-urile se deblocheaza automat.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{% for e in pending %}
|
<div class="tablewrap">
|
||||||
{% set top = e.suggestions[0] if e.suggestions else None %}
|
<table>
|
||||||
{% set preselect = top.cod_prestatie if (top and top.score >= 60) else '' %}
|
<thead><tr>
|
||||||
<form class="maprow" hx-post="/mapari" hx-target="#mapari-section" hx-swap="outerHTML">
|
<th>Operatie</th>
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
<th>Sugestii</th>
|
||||||
<input type="hidden" name="cod_op_service" value="{{ e.cod_op_service }}">
|
<th>Cod RAR</th>
|
||||||
|
<th>Punere in coada</th>
|
||||||
<div class="mapcol grow">
|
<th></th>
|
||||||
<div><strong>{{ e.cod_op_service }}</strong>
|
</tr></thead>
|
||||||
<span class="pill" title="submission-uri blocate">{{ e.blocked }} blocate</span></div>
|
<tbody>
|
||||||
<div class="muted">{{ e.denumire or '(fara denumire)' }}</div>
|
{% for e in pending %}
|
||||||
{% if e.suggestions %}
|
{% set top = e.suggestions[0] if e.suggestions else None %}
|
||||||
<div class="muted" style="font-size:12px; margin-top:4px;">
|
{% set preselect = top.cod_prestatie if (top and top.score >= 60) else '' %}
|
||||||
sugestii:
|
<tr>
|
||||||
{% for s in e.suggestions[:3] %}
|
<td>
|
||||||
<span class="sugg">{{ s.cod_prestatie }} ({{ s.score|round|int }}%)</span>{% if not loop.last %}, {% endif %}
|
<form id="map-rez-{{ loop.index }}" hx-post="/mapari" hx-target="#mapari-section" hx-swap="outerHTML">
|
||||||
{% endfor %}
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
</div>
|
<input type="hidden" name="cod_op_service" value="{{ e.cod_op_service }}">
|
||||||
{% endif %}
|
</form>
|
||||||
</div>
|
<div><strong>{{ e.cod_op_service }}</strong>
|
||||||
|
<span class="pill" title="submission-uri blocate">{{ e.blocked }} blocate</span></div>
|
||||||
<div class="mapcol">
|
<div class="muted">{{ e.denumire or '(fara denumire)' }}</div>
|
||||||
<select name="cod_prestatie" required>
|
</td>
|
||||||
<option value="">— alege cod RAR —</option>
|
<td class="muted" style="font-size:12px;">
|
||||||
{% for n in nomenclator %}
|
{% if e.suggestions %}
|
||||||
<option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == preselect %}selected{% endif %}>
|
{% for s in e.suggestions[:3] %}
|
||||||
{{ n.cod_prestatie }} — {{ n.nume_prestatie }}
|
<span class="sugg">{{ s.cod_prestatie }} ({{ s.score|round|int }}%)</span>{% if not loop.last %}, {% endif %}
|
||||||
</option>
|
{% endfor %}
|
||||||
{% endfor %}
|
{% else %}—{% endif %}
|
||||||
</select>
|
</td>
|
||||||
</div>
|
<td>
|
||||||
|
<select name="cod_prestatie" form="map-rez-{{ loop.index }}" required
|
||||||
<div class="mapcol">
|
aria-label="Cod RAR pentru {{ e.cod_op_service }}">
|
||||||
<label class="chk"><input type="checkbox" name="auto_send" value="true" checked> auto-send</label>
|
<option value="">— alege cod RAR —</option>
|
||||||
</div>
|
{% for n in nomenclator %}
|
||||||
|
<option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == preselect %}selected{% endif %}>
|
||||||
<div class="mapcol">
|
{{ n.cod_prestatie }} — {{ n.nume_prestatie }}
|
||||||
<button type="submit">Salveaza</button>
|
</option>
|
||||||
</div>
|
{% endfor %}
|
||||||
</form>
|
</select>
|
||||||
{% endfor %}
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ ui.autosend_toggle(form_id="map-rez-" ~ loop.index, checked=True) }}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button type="submit" form="map-rez-{{ loop.index }}">Salveaza</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -77,50 +89,61 @@
|
|||||||
</div>
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="muted" style="margin:0 0 12px; font-size:13px;">
|
<p class="muted" style="margin:0 0 12px; font-size:13px;">
|
||||||
Maparile operatie -> cod RAR retinute pentru contul tau. Schimba codul sau auto-send si salveaza;
|
Maparile operatie -> cod RAR retinute pentru contul tau. Schimba codul sau punerea in coada si salveaza;
|
||||||
la schimbarea unui cod, submission-urile blocate pe acea operatie se re-rezolva automat.
|
la schimbarea unui cod, submission-urile blocate pe acea operatie se re-rezolva automat.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{% for m in saved_mappings %}
|
<div class="tablewrap">
|
||||||
<form class="maprow" hx-post="/mapari/salvate" hx-target="#mapari-section" hx-swap="outerHTML">
|
<table>
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
<thead><tr>
|
||||||
<input type="hidden" name="cod_op_service" value="{{ m.cod_op_service }}">
|
<th>Operatie</th>
|
||||||
|
<th>Cod RAR</th>
|
||||||
<div class="mapcol grow">
|
<th>Punere in coada</th>
|
||||||
<div><strong>{{ m.cod_op_service }}</strong></div>
|
<th>Actiuni</th>
|
||||||
<div class="muted" style="font-size:12px;">
|
</tr></thead>
|
||||||
acum: {{ m.cod_prestatie }}{% if m.nume_prestatie %} — {{ m.nume_prestatie }}{% endif %}
|
<tbody>
|
||||||
</div>
|
{% for m in saved_mappings %}
|
||||||
</div>
|
<tr>
|
||||||
|
<td>
|
||||||
<div class="mapcol">
|
<form id="map-salv-{{ loop.index }}" hx-post="/mapari/salvate" hx-target="#mapari-section" hx-swap="outerHTML">
|
||||||
<select name="cod_prestatie" required aria-label="Cod RAR pentru {{ m.cod_op_service }}">
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
{% for n in nomenclator %}
|
<input type="hidden" name="cod_op_service" value="{{ m.cod_op_service }}">
|
||||||
<option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == m.cod_prestatie %}selected{% endif %}>
|
</form>
|
||||||
{{ n.cod_prestatie }} — {{ n.nume_prestatie }}
|
<form id="map-del-{{ loop.index }}" hx-post="/mapari/salvate/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
|
||||||
</option>
|
hx-confirm="Stergi maparea pentru {{ m.cod_op_service }}?">
|
||||||
{% endfor %}
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
</select>
|
<input type="hidden" name="cod_op_service" value="{{ m.cod_op_service }}">
|
||||||
</div>
|
</form>
|
||||||
|
<div><strong>{{ m.cod_op_service }}</strong></div>
|
||||||
<div class="mapcol">
|
<div class="muted" style="font-size:12px;">
|
||||||
<label class="chk"><input type="checkbox" name="auto_send" value="true"
|
acum: {{ m.cod_prestatie }}{% if m.nume_prestatie %} — {{ m.nume_prestatie }}{% endif %}
|
||||||
{% if m.auto_send %}checked{% endif %}> auto-send</label>
|
</div>
|
||||||
</div>
|
</td>
|
||||||
|
<td>
|
||||||
<div class="mapcol" style="display:flex; gap:6px;">
|
<select name="cod_prestatie" form="map-salv-{{ loop.index }}" required
|
||||||
<button type="submit">Salveaza</button>
|
aria-label="Cod RAR pentru {{ m.cod_op_service }}">
|
||||||
</div>
|
{% for n in nomenclator %}
|
||||||
<div class="mapcol">
|
<option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == m.cod_prestatie %}selected{% endif %}>
|
||||||
<button type="submit"
|
{{ n.cod_prestatie }} — {{ n.nume_prestatie }}
|
||||||
hx-post="/mapari/salvate/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
|
</option>
|
||||||
hx-confirm="Stergi maparea pentru {{ m.cod_op_service }}?"
|
{% endfor %}
|
||||||
style="background:var(--card); color:var(--err); border-color:var(--err);">
|
</select>
|
||||||
Sterge
|
</td>
|
||||||
</button>
|
<td>
|
||||||
</div>
|
{{ ui.autosend_toggle(form_id="map-salv-" ~ loop.index, checked=m.auto_send) }}
|
||||||
</form>
|
</td>
|
||||||
{% endfor %}
|
<td style="white-space:nowrap;">
|
||||||
|
<button type="submit" form="map-salv-{{ loop.index }}">Salveaza</button>
|
||||||
|
<button type="submit" form="map-del-{{ loop.index }}"
|
||||||
|
style="background:var(--card); color:var(--err); border-color:var(--err);">
|
||||||
|
Sterge
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -140,42 +163,51 @@
|
|||||||
Antetele de fisier recunoscute. Un fisier cu alte coloane = format nou separat (nu suprascrie).
|
Antetele de fisier recunoscute. Un fisier cu alte coloane = format nou separat (nu suprascrie).
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{% for f in column_formats %}
|
<div class="tablewrap">
|
||||||
<div class="maprow" style="align-items:flex-start;">
|
<table>
|
||||||
<div class="mapcol grow">
|
<thead><tr>
|
||||||
<div style="font-size:13px; margin-bottom:4px;">
|
<th>Coloane</th>
|
||||||
<strong>{{ f.columns | length }} coloane recunoscute</strong>
|
<th>Mapari (coloana → camp)</th>
|
||||||
{% if f.format_data %}
|
<th>Format data</th>
|
||||||
<span class="pill" title="format data">data: {{ f.format_data }}</span>
|
<th></th>
|
||||||
{% endif %}
|
</tr></thead>
|
||||||
</div>
|
<tbody>
|
||||||
<div class="muted" style="font-size:12px;">
|
{% for f in column_formats %}
|
||||||
{% for col, camp in f.mappings.items() %}
|
<tr>
|
||||||
<span class="sugg">{{ col }}</span> → {{ camp }}{% if not loop.last %}; {% endif %}
|
<td style="white-space:nowrap;">
|
||||||
{% endfor %}
|
<strong>{{ f.columns | length }} coloane</strong>
|
||||||
</div>
|
</td>
|
||||||
</div>
|
<td class="muted" style="font-size:12px; white-space:normal; max-width:340px;">
|
||||||
|
{% for col, camp in f.mappings.items() %}
|
||||||
<form class="mapcol" style="display:flex; gap:6px; align-items:center;"
|
<span class="sugg">{{ col }}</span> → {{ camp }}{% if not loop.last %}; {% endif %}
|
||||||
hx-post="/formate-coloane/editeaza" hx-target="#mapari-section" hx-swap="outerHTML">
|
{% endfor %}
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
</td>
|
||||||
<input type="hidden" name="format_id" value="{{ f.id }}">
|
<td>
|
||||||
<input type="text" name="format_data" value="{{ f.format_data or '' }}"
|
<form id="fmt-edit-{{ loop.index }}" hx-post="/formate-coloane/editeaza"
|
||||||
placeholder="ex. DD.MM.YYYY" aria-label="Format data" style="max-width:130px;">
|
hx-target="#mapari-section" hx-swap="outerHTML"
|
||||||
<button type="submit">Salveaza data</button>
|
style="display:flex; gap:6px; align-items:center;">
|
||||||
</form>
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
|
<input type="hidden" name="format_id" value="{{ f.id }}">
|
||||||
<form class="mapcol"
|
<input type="text" name="format_data" value="{{ f.format_data or '' }}"
|
||||||
hx-post="/formate-coloane/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
|
placeholder="ex. DD.MM.YYYY" aria-label="Format data" style="max-width:130px;">
|
||||||
hx-confirm="Stergi acest format de coloane?">
|
<button type="submit">Salveaza data</button>
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
</form>
|
||||||
<input type="hidden" name="format_id" value="{{ f.id }}">
|
</td>
|
||||||
<button type="submit" style="background:var(--card); color:var(--err); border-color:var(--err);">
|
<td>
|
||||||
Sterge
|
<form hx-post="/formate-coloane/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
|
||||||
</button>
|
hx-confirm="Stergi acest format de coloane?">
|
||||||
</form>
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
|
<input type="hidden" name="format_id" value="{{ f.id }}">
|
||||||
|
<button type="submit" style="background:var(--card); color:var(--err); border-color:var(--err);">
|
||||||
|
Sterge
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
{% import '_macros.html' as ui %}
|
||||||
<div id="import-section">
|
<div id="import-section">
|
||||||
{% set pas = 3 %}{% include '_stepper.html' %}
|
{% set pas = 3 %}{% include '_stepper.html' %}
|
||||||
<div class="card">
|
<div class="card">
|
||||||
@@ -16,16 +17,16 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- Rezumat stari -->
|
<!-- Rezumat stari (id stabil pentru OOB swap dupa editarea unui rand — US-002) -->
|
||||||
<div style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:12px;">
|
{% set status_labels = [
|
||||||
{% set status_labels = [
|
('ok', 'gata de trimis'),
|
||||||
('ok', 'gata de trimis'),
|
('needs_review', 'verifica valori'),
|
||||||
('needs_review', 'verifica valori'),
|
('needs_mapping', 'fara cod RAR'),
|
||||||
('needs_mapping', 'fara cod RAR'),
|
('needs_data', 'date lipsa'),
|
||||||
('needs_data', 'date lipsa'),
|
('already_sent', 'deja trimis'),
|
||||||
('already_sent', 'deja trimis'),
|
('duplicate_in_file','dublicat in fisier'),
|
||||||
('duplicate_in_file','dublicat in fisier'),
|
] %}
|
||||||
] %}
|
<div id="preview-rezumat" style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:12px;">
|
||||||
{% for status_key, label in status_labels %}
|
{% for status_key, label in status_labels %}
|
||||||
{%- set cnt = summary.get(status_key, 0) -%}
|
{%- set cnt = summary.get(status_key, 0) -%}
|
||||||
{% if cnt > 0 %}
|
{% if cnt > 0 %}
|
||||||
@@ -96,7 +97,7 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="mapcol">
|
<div class="mapcol">
|
||||||
<label class="chk"><input type="checkbox" name="auto_send" value="true" checked> auto-send</label>
|
{{ ui.autosend_toggle(checked=True) }}
|
||||||
</div>
|
</div>
|
||||||
<div class="mapcol">
|
<div class="mapcol">
|
||||||
<button type="submit" style="min-height:44px;">Salveaza</button>
|
<button type="submit" style="min-height:44px;">Salveaza</button>
|
||||||
@@ -106,85 +107,39 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- Tabel preview + bara confirmare (un singur form) -->
|
<!-- Tabel preview. Randurile au FORM PROPRIU pentru editare (NU sunt in #confirm-form,
|
||||||
|
altfel Enter intr-un camp ar declansa trimiterea ireversibila — D-3.3). Bifele
|
||||||
|
needs_review se asociaza la #confirm-form prin atributul form=. -->
|
||||||
|
<div class="tablewrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>#</th>
|
||||||
|
<th>VIN</th>
|
||||||
|
<th>Nr. Inm.</th>
|
||||||
|
<th>Data</th>
|
||||||
|
<th>KM final</th>
|
||||||
|
<th>Operatie</th>
|
||||||
|
<th>Stare</th>
|
||||||
|
<th>Note</th>
|
||||||
|
<th>Verificat?</th>
|
||||||
|
<th>Actiuni</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
{% include '_preview_rand.html' %}
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Bara confirmare (sticky jos) — singurul formular care trimite la RAR -->
|
||||||
<form id="confirm-form"
|
<form id="confirm-form"
|
||||||
hx-post="/_import/{{ import_id }}/confirma"
|
hx-post="/_import/{{ import_id }}/confirma"
|
||||||
hx-target="#import-section"
|
hx-target="#import-section"
|
||||||
hx-swap="outerHTML">
|
hx-swap="outerHTML">
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
|
|
||||||
<div class="tablewrap">
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>#</th>
|
|
||||||
<th>VIN</th>
|
|
||||||
<th>Nr. Inm.</th>
|
|
||||||
<th>Data</th>
|
|
||||||
<th>KM final</th>
|
|
||||||
<th>Operatie</th>
|
|
||||||
<th>Stare</th>
|
|
||||||
<th>Note</th>
|
|
||||||
<th>Verificat?</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{% for row in rows %}
|
|
||||||
{%- set res = row.resolved -%}
|
|
||||||
{%- set status = row.resolved_status -%}
|
|
||||||
{%- set prestatii = res.get('prestatii') or [] -%}
|
|
||||||
{%- set op = (prestatii[0].get('cod_prestatie') or prestatii[0].get('cod_op_service', '')) if prestatii else '' -%}
|
|
||||||
<tr data-status="{{ status }}"
|
|
||||||
style="{% if status == 'needs_review' %}background:rgba(230,179,74,.04);{% elif status in ('already_sent', 'duplicate_in_file') %}opacity:.65;{% endif %}">
|
|
||||||
<td class="muted">{{ row.row_index + 1 }}</td>
|
|
||||||
<td>{{ res.get('vin') or '<span class="muted">—</span>' | safe }}</td>
|
|
||||||
<td>{{ res.get('nr_inmatriculare') or '' }}</td>
|
|
||||||
<td>{{ res.get('data_prestatie') or '' }}</td>
|
|
||||||
<td>{{ res.get('odometru_final') or '' }}</td>
|
|
||||||
<td>{{ op or '<span class="muted">—</span>' | safe }}</td>
|
|
||||||
<td>
|
|
||||||
<span class="pill s-{{ status }}">{{ status }}</span>
|
|
||||||
</td>
|
|
||||||
<td class="muted" style="font-size:12px; white-space:normal; max-width:220px;">
|
|
||||||
{% if status == 'already_sent' and row.get('already_sent_info') %}
|
|
||||||
{% set ai = row.already_sent_info %}
|
|
||||||
deja trimis {{ (ai.get('created_at') or '')[:10] }}
|
|
||||||
{% if ai.get('id_prezentare') %}(#{{ ai.id_prezentare }}){% endif %}
|
|
||||||
{% elif status == 'duplicate_in_file' and row.get('duplicate_with') %}
|
|
||||||
dubla cu randul
|
|
||||||
{% for idx in row.duplicate_with %}{{ idx + 1 }}{% if not loop.last %}, {% endif %}{% endfor %}
|
|
||||||
{% elif row.flags %}
|
|
||||||
{{ row.flags[0] }}
|
|
||||||
{% elif row.errors %}
|
|
||||||
{# US-008: arata MOTIVUL (mesajul de validare), nu numele campului #}
|
|
||||||
{%- for e in row.errors -%}
|
|
||||||
{%- if e is mapping -%}
|
|
||||||
{{ e.get('message') or e.get('msg') or (e.values() | list | first) }}
|
|
||||||
{%- else -%}
|
|
||||||
{{ e }}
|
|
||||||
{%- endif -%}
|
|
||||||
{%- if not loop.last %}; {% endif -%}
|
|
||||||
{%- endfor -%}
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
<td style="text-align:center;">
|
|
||||||
{% if status == 'needs_review' %}
|
|
||||||
<label class="chk" style="min-height:44px; justify-content:center; cursor:pointer;"
|
|
||||||
title="Bifat inseamna ca ai verificat valorile si le incluzi in trimitere">
|
|
||||||
<input type="checkbox" name="reviewed_rows" value="{{ row.row_index }}"
|
|
||||||
onchange="updateN()"
|
|
||||||
aria-label="Verificat — randul {{ row.row_index + 1 }} (VIN: {{ res.get('vin', '') }})">
|
|
||||||
verif.
|
|
||||||
</label>
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endfor %}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Bara confirmare (sticky jos) -->
|
|
||||||
<div class="sticky-bar">
|
<div class="sticky-bar">
|
||||||
<div style="flex:1; min-width:280px;">
|
<div style="flex:1; min-width:280px;">
|
||||||
<!-- Banner declarant (D12) — direct deasupra input-ului N -->
|
<!-- Banner declarant (D12) — direct deasupra input-ului N -->
|
||||||
@@ -207,7 +162,7 @@
|
|||||||
style="max-width:80px;"
|
style="max-width:80px;"
|
||||||
aria-describedby="n-hint">
|
aria-describedby="n-hint">
|
||||||
<span id="n-hint" class="muted" style="font-size:12px; margin-left:6px;">
|
<span id="n-hint" class="muted" style="font-size:12px; margin-left:6px;">
|
||||||
({{ summary.get('ok', 0) }} ok
|
(<span id="n-hint-ok">{{ summary.get('ok', 0) }}</span> ok
|
||||||
{% if summary.get('needs_review', 0) %}
|
{% if summary.get('needs_review', 0) %}
|
||||||
+ pana la {{ summary.get('needs_review', 0) }} verificate manual
|
+ pana la {{ summary.get('needs_review', 0) }} verificate manual
|
||||||
{% endif %})
|
{% endif %})
|
||||||
@@ -241,9 +196,12 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<!-- Contor "gata de trimis" citit din DOM (data-ok), ca OOB swap-ul de la editare
|
||||||
|
sa actualizeze N fara a re-randa sectiunea (US-002). -->
|
||||||
|
<span id="preview-ok-count" data-ok="{{ summary.get('ok', 0) }}" hidden></span>
|
||||||
|
|
||||||
<div style="padding:8px 0 4px;">
|
<div style="padding:8px 0 4px;">
|
||||||
<a href="#" class="muted" style="font-size:13px;"
|
<a href="#" class="muted" style="font-size:13px;"
|
||||||
hx-get="/_import/reset" hx-target="#import-section" hx-swap="outerHTML">Incarca alt fisier</a>
|
hx-get="/_import/reset" hx-target="#import-section" hx-swap="outerHTML">Incarca alt fisier</a>
|
||||||
@@ -254,18 +212,32 @@
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function() {
|
(function() {
|
||||||
var nOk = {{ summary.get('ok', 0) | int }};
|
/* D-1.2: un singur sticky bar pe ecran — cat preview-ul de import e activ,
|
||||||
|
ascunde sectiunea Trimiteri de pe Acasa (se reveleaza la reset/commit din _upload.html). */
|
||||||
|
var trim = document.getElementById('trimiteri-section');
|
||||||
|
if (trim) trim.style.display = 'none';
|
||||||
|
|
||||||
/* Actualizeaza N si bannerul cand se bifeaza needs_review */
|
/* nOk se citeste din DOM (#preview-ok-count[data-ok]) ca OOB swap-ul de la editare
|
||||||
|
sa-l poata actualiza fara re-randarea sectiunii (D-3.1/D-3.4). */
|
||||||
|
function getOk() {
|
||||||
|
var el = document.getElementById('preview-ok-count');
|
||||||
|
return el ? parseInt(el.dataset.ok || '0', 10) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Actualizeaza N si bannerul cand se bifeaza needs_review SAU cand se editeaza un rand. */
|
||||||
function updateN() {
|
function updateN() {
|
||||||
var checked = document.querySelectorAll('input[name="reviewed_rows"]:checked').length;
|
var checked = document.querySelectorAll('input[name="reviewed_rows"]:checked').length;
|
||||||
var total = nOk + checked;
|
var total = getOk() + checked;
|
||||||
var inp = document.getElementById('n-confirmat');
|
var inp = document.getElementById('n-confirmat');
|
||||||
var disp = document.getElementById('n-display');
|
var disp = document.getElementById('n-display');
|
||||||
var btn = document.getElementById('confirm-btn');
|
var btn = document.getElementById('confirm-btn');
|
||||||
|
/* Nu re-activa confirm cat un rand e in editare (mutual-exclusion D-3.2). */
|
||||||
|
var editing = document.querySelector('tr[data-editing="1"]') !== null;
|
||||||
if (inp) inp.value = total;
|
if (inp) inp.value = total;
|
||||||
if (disp) disp.textContent = total;
|
if (disp) disp.textContent = total;
|
||||||
if (btn) btn.disabled = (total === 0);
|
var hintOk = document.getElementById('n-hint-ok');
|
||||||
|
if (hintOk) hintOk.textContent = getOk();
|
||||||
|
if (btn) btn.disabled = (total === 0) || editing;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Filtrare randuri dupa stare */
|
/* Filtrare randuri dupa stare */
|
||||||
@@ -281,15 +253,12 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Expune functiile global pentru onclick inline */
|
/* Expune functiile global pentru onclick/hx-on inline si OOB swap */
|
||||||
window.updateN = updateN;
|
window.updateN = updateN;
|
||||||
window.filterRows = filterRows;
|
window.filterRows = filterRows;
|
||||||
|
|
||||||
/* Filtru implicit "Toate" activ la incarcare */
|
/* Filtru implicit "Toate" activ la incarcare */
|
||||||
filterRows('all');
|
filterRows('all');
|
||||||
|
updateN();
|
||||||
/* Focus pe campul N la deschidere (a11y — D12) */
|
|
||||||
var ni = document.getElementById('n-confirmat');
|
|
||||||
if (ni) { ni.focus(); ni.select(); }
|
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
168
app/web/templates/_preview_rand.html
Normal file
168
app/web/templates/_preview_rand.html
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
{#
|
||||||
|
_preview_rand.html — un singur rand de preview import (US-002, 3.6).
|
||||||
|
Doua moduri:
|
||||||
|
- display (editing falsy): <tr> normal + buton "Editeaza" pe coloana de actiuni.
|
||||||
|
- edit (editing truthy): <tr> cu un singur <td colspan> ce contine un FORM PROPRIU
|
||||||
|
(NU #confirm-form) cu grila responsiva refolosita din _trimitere_detaliu.html.
|
||||||
|
Swap pe RAND (hx-target pe #preview-row-N, outerHTML), NU pe #import-section (D-3.1).
|
||||||
|
La save, optional OOB pe rezumat + contor "gata de trimis" (include_oob).
|
||||||
|
#}
|
||||||
|
{%- set res = row.resolved -%}
|
||||||
|
{%- set status = row.resolved_status -%}
|
||||||
|
{%- set prestatii = res.get('prestatii') or [] -%}
|
||||||
|
{%- set op = (prestatii[0].get('cod_prestatie') or prestatii[0].get('cod_op_service', '')) if prestatii else '' -%}
|
||||||
|
{% if editing %}
|
||||||
|
{%- set err_map = {} -%}
|
||||||
|
{%- for e in row.errors -%}{%- if e is mapping and e.get('field') -%}{%- set _ = err_map.update({e.field: (e.get('message') or e.get('msg'))}) -%}{%- endif -%}{%- endfor -%}
|
||||||
|
<tr id="preview-row-{{ row.row_index }}" data-status="{{ status }}" data-editing="1">
|
||||||
|
<td colspan="10" style="background:rgba(91,141,239,.06);">
|
||||||
|
<form class="rand-editare"
|
||||||
|
hx-post="/_import/{{ import_id }}/rand/{{ row.row_index }}/editeaza"
|
||||||
|
hx-target="#preview-row-{{ row.row_index }}"
|
||||||
|
hx-swap="outerHTML"
|
||||||
|
hx-indicator="#rand-spinner-{{ row.row_index }}"
|
||||||
|
hx-disabled-elt="find button"
|
||||||
|
hx-on::response-error="this.querySelector('.rand-eroare-banner').style.display='block';">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
|
||||||
|
|
||||||
|
<div style="display:flex; align-items:center; gap:8px; margin-bottom:8px;">
|
||||||
|
<strong style="font-size:13px;">Editare rand {{ row.row_index + 1 }}</strong>
|
||||||
|
<span class="pill s-{{ status }}" style="font-size:11px;">{{ status }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if message %}
|
||||||
|
<div class="flash" style="border-color:var(--err); background:#241a1a; margin-bottom:10px;"
|
||||||
|
role="alert">{{ message }}</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="rand-eroare-banner" role="alert"
|
||||||
|
style="display:none; margin-bottom:10px; padding:8px 12px; border:1px solid var(--err);
|
||||||
|
background:#241a1a; border-radius:6px; font-size:13px;">
|
||||||
|
Salvarea nu a reusit (retea / sesiune). Valorile introduse sunt pastrate — reincearca.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% macro camp(nume, eticheta, valoare, tip='text') %}
|
||||||
|
<div>
|
||||||
|
<label for="e-{{ row.row_index }}-{{ nume }}" class="muted" style="font-size:12px; display:block;">{{ eticheta }}</label>
|
||||||
|
<input id="e-{{ row.row_index }}-{{ nume }}" type="{{ tip }}" name="{{ nume }}" value="{{ valoare or '' }}"
|
||||||
|
style="width:100%; {% if err_map.get(nume) %}border-color:var(--err);{% endif %}"
|
||||||
|
aria-label="{{ eticheta }} — randul {{ row.row_index + 1 }} (VIN: {{ res.get('vin') or '' }})"
|
||||||
|
{% if err_map.get(nume) %}aria-invalid="true"{% endif %}>
|
||||||
|
{% if err_map.get(nume) %}
|
||||||
|
<div class="s-error" style="font-size:12px; margin-top:2px;">{{ err_map.get(nume) }}</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:10px 16px;">
|
||||||
|
{{ camp('nr_inmatriculare', 'Numar inmatriculare', res.get('nr_inmatriculare')) }}
|
||||||
|
{{ camp('vin', 'VIN (serie sasiu)', res.get('vin')) }}
|
||||||
|
{{ camp('data_prestatie', 'Data prestatie (YYYY-MM-DD)', res.get('data_prestatie')) }}
|
||||||
|
{{ camp('odometru_final', 'Odometru final', res.get('odometru_final')) }}
|
||||||
|
{{ camp('odometru_initial', 'Odometru initial (daca e cerut)', res.get('odometru_initial')) }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:10px; display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
|
||||||
|
<button type="submit" style="min-height:44px; padding:8px 18px;">Salveaza</button>
|
||||||
|
<button type="button" style="min-height:44px; padding:8px 18px;
|
||||||
|
background:var(--card); color:var(--muted); border-color:var(--line);"
|
||||||
|
hx-get="/_import/{{ import_id }}/rand/{{ row.row_index }}"
|
||||||
|
hx-target="#preview-row-{{ row.row_index }}" hx-swap="outerHTML">Anuleaza</button>
|
||||||
|
<span id="rand-spinner-{{ row.row_index }}" class="htmx-indicator muted" style="font-size:13px;">
|
||||||
|
se salveaza…
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
/* Mutual-exclusion (D-3.2/3.6): cat un rand e in editare, dezactiveaza confirm + alte Editeaza. */
|
||||||
|
var btn = document.getElementById('confirm-btn');
|
||||||
|
if (btn) { btn.disabled = true; btn.title = 'Termina editarea randului inainte de a trimite.'; }
|
||||||
|
document.querySelectorAll('.btn-editeaza').forEach(function(b) { b.disabled = true; });
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% else %}
|
||||||
|
<tr id="preview-row-{{ row.row_index }}" data-status="{{ status }}"
|
||||||
|
style="{% if status == 'needs_review' %}background:rgba(230,179,74,.04);{% elif status in ('already_sent', 'duplicate_in_file') %}opacity:.65;{% endif %}">
|
||||||
|
<td class="muted">{{ row.row_index + 1 }}</td>
|
||||||
|
<td>{{ res.get('vin') or '<span class="muted">—</span>' | safe }}</td>
|
||||||
|
<td>{{ res.get('nr_inmatriculare') or '' }}</td>
|
||||||
|
<td>{{ res.get('data_prestatie') or '' }}</td>
|
||||||
|
<td>{{ res.get('odometru_final') or '' }}</td>
|
||||||
|
<td>{{ op or '<span class="muted">—</span>' | safe }}</td>
|
||||||
|
<td><span class="pill s-{{ status }}">{{ status }}</span></td>
|
||||||
|
<td class="muted" style="font-size:12px; white-space:normal; max-width:220px;">
|
||||||
|
{% if status == 'already_sent' and row.get('already_sent_info') %}
|
||||||
|
{% set ai = row.already_sent_info %}
|
||||||
|
deja trimis {{ (ai.get('created_at') or '')[:10] }}
|
||||||
|
{% if ai.get('id_prezentare') %}(#{{ ai.id_prezentare }}){% endif %}
|
||||||
|
{% elif status == 'duplicate_in_file' and row.get('duplicate_with') %}
|
||||||
|
dubla cu randul
|
||||||
|
{% for idx in row.duplicate_with %}{{ idx + 1 }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||||
|
{% elif row.flags %}
|
||||||
|
{{ row.flags[0] }}
|
||||||
|
{% elif row.errors %}
|
||||||
|
{%- for e in row.errors -%}
|
||||||
|
{%- if e is mapping -%}
|
||||||
|
{{ e.get('message') or e.get('msg') or (e.values() | list | first) }}
|
||||||
|
{%- else -%}
|
||||||
|
{{ e }}
|
||||||
|
{%- endif -%}
|
||||||
|
{%- if not loop.last %}; {% endif -%}
|
||||||
|
{%- endfor -%}
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td style="text-align:center;">
|
||||||
|
{% if status == 'needs_review' %}
|
||||||
|
<label class="chk" style="min-height:44px; justify-content:center; cursor:pointer;"
|
||||||
|
title="Bifat inseamna ca ai verificat valorile si le incluzi in trimitere">
|
||||||
|
<input type="checkbox" form="confirm-form" name="reviewed_rows" value="{{ row.row_index }}"
|
||||||
|
onchange="window.updateN && window.updateN()"
|
||||||
|
aria-label="Verificat — randul {{ row.row_index + 1 }} (VIN: {{ res.get('vin', '') }})">
|
||||||
|
verif.
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td style="text-align:center;">
|
||||||
|
{% if status not in ('already_sent', 'duplicate_in_file') %}
|
||||||
|
<button type="button" class="btn-editeaza"
|
||||||
|
style="min-height:44px; padding:6px 14px; font-size:13px;
|
||||||
|
background:transparent; border-color:var(--line); color:var(--ink);"
|
||||||
|
hx-get="/_import/{{ import_id }}/rand/{{ row.row_index }}/editare"
|
||||||
|
hx-target="#preview-row-{{ row.row_index }}" hx-swap="outerHTML"
|
||||||
|
aria-label="Editeaza randul {{ row.row_index + 1 }} (VIN: {{ res.get('vin', '') }})">
|
||||||
|
Editeaza
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% if include_oob %}
|
||||||
|
{# OOB: actualizeaza rezumatul si contorul "gata de trimis" dupa save, fara a re-randa sectiunea (D-3.1). #}
|
||||||
|
{% set status_labels = [
|
||||||
|
('ok','gata de trimis'), ('needs_review','verifica valori'), ('needs_mapping','fara cod RAR'),
|
||||||
|
('needs_data','date lipsa'), ('already_sent','deja trimis'), ('duplicate_in_file','dublicat in fisier')] %}
|
||||||
|
<div id="preview-rezumat" hx-swap-oob="true"
|
||||||
|
style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:12px;">
|
||||||
|
{% for status_key, label in status_labels %}
|
||||||
|
{%- set cnt = summary.get(status_key, 0) -%}
|
||||||
|
{% if cnt > 0 %}<span class="pill s-{{ status_key }}">{{ cnt }} {{ label }}</span>{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<span id="preview-ok-count" hx-swap-oob="true" data-ok="{{ summary.get('ok', 0) }}" hidden></span>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
/* Editare incheiata: re-activeaza confirm + butoanele Editeaza, recalculeaza N.
|
||||||
|
Defer pe tick-ul urmator: la momentul rularii scriptului, swap-ul randului poate
|
||||||
|
sa nu se fi asezat inca, deci tr[data-editing] ar fi inca prezent si updateN ar
|
||||||
|
lasa confirm dezactivat (editing=true). Dupa setTimeout(0) randul e in mod display. */
|
||||||
|
setTimeout(function() {
|
||||||
|
document.querySelectorAll('.btn-editeaza').forEach(function(b) { b.disabled = false; });
|
||||||
|
var btn = document.getElementById('confirm-btn');
|
||||||
|
if (btn) btn.title = '';
|
||||||
|
if (window.updateN) window.updateN();
|
||||||
|
}, 0);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
<div id="import-section">
|
<div id="import-section">
|
||||||
{% set pas = 1 %}{% include '_stepper.html' %}
|
{% set pas = 1 %}{% include '_stepper.html' %}
|
||||||
<div class="card">
|
{# US-004 (3.6): bara de upload accentuata (border de accent) ca sa ramana punctul
|
||||||
<h2 style="font-size:15px; margin:0 0 12px;">Import fisier (xlsx / csv)</h2>
|
de intrare evident chiar cu tabelul Trimiteri lung dedesubt (D-1.1/D-5.2). #}
|
||||||
|
<div class="card" style="border-color:var(--accent);">
|
||||||
|
|
||||||
{% if message %}
|
{% if message %}
|
||||||
<div class="flash" style="margin-bottom:12px;">{{ message }}</div>
|
<div class="flash" style="margin-bottom:12px;">{{ message }}</div>
|
||||||
@@ -40,6 +41,26 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{% if are_trimiteri and not sheets %}
|
||||||
|
{# === Bara slim (returning user): eticheta + buton + zona de trage, pe un rand === #}
|
||||||
|
<div class="drop-zone" id="drop-zone"
|
||||||
|
role="region" aria-label="Zona de incarcare fisier"
|
||||||
|
style="display:flex; align-items:center; gap:14px; flex-wrap:wrap;
|
||||||
|
padding:12px 16px; text-align:left;">
|
||||||
|
<strong style="font-size:14px;">Importa:</strong>
|
||||||
|
<input id="file-input" type="file" name="file" accept=".xlsx,.xls,.csv"
|
||||||
|
style="display:none;" aria-label="Selecteaza fisier xlsx sau csv">
|
||||||
|
<button type="button" id="upload-btn"
|
||||||
|
style="min-height:44px; padding:10px 20px; font-size:14px;">
|
||||||
|
Alege fisier (xlsx/csv)
|
||||||
|
</button>
|
||||||
|
<span class="muted" style="font-size:13px;">sau trage aici</span>
|
||||||
|
<span class="muted" style="font-size:12px; margin-left:auto;">
|
||||||
|
NU se trimite nimic la RAR pana confirmi.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
{# === Hero first-run (sau re-upload multi-foaie): pastreaza copy-ul de bun venit === #}
|
||||||
<div class="drop-zone" id="drop-zone"
|
<div class="drop-zone" id="drop-zone"
|
||||||
role="region" aria-label="Zona de incarcare fisier">
|
role="region" aria-label="Zona de incarcare fisier">
|
||||||
{% if not sheets %}
|
{% if not sheets %}
|
||||||
@@ -55,13 +76,14 @@
|
|||||||
style="display:none;" aria-label="Selecteaza fisier xlsx sau csv">
|
style="display:none;" aria-label="Selecteaza fisier xlsx sau csv">
|
||||||
<button type="button" id="upload-btn"
|
<button type="button" id="upload-btn"
|
||||||
style="min-height:44px; padding:10px 24px; font-size:14px;">
|
style="min-height:44px; padding:10px 24px; font-size:14px;">
|
||||||
Alege fisier
|
Alege fisier (xlsx/csv)
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="muted" style="margin:8px 0 0; font-size:12px;">
|
<p class="muted" style="margin:8px 0 0; font-size:12px;">
|
||||||
NU se trimite nimic la RAR pana confirmi explicit.
|
NU se trimite nimic la RAR pana confirmi explicit.
|
||||||
</p>
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<span id="upload-spinner" class="htmx-indicator muted"
|
<span id="upload-spinner" class="htmx-indicator muted"
|
||||||
style="font-size:13px; margin-top:6px; display:inline;">
|
style="font-size:13px; margin-top:6px; display:inline;">
|
||||||
@@ -77,6 +99,17 @@
|
|||||||
var fi = document.getElementById('file-input');
|
var fi = document.getElementById('file-input');
|
||||||
var dz = document.getElementById('drop-zone');
|
var dz = document.getElementById('drop-zone');
|
||||||
var frm = document.getElementById('upload-form');
|
var frm = document.getElementById('upload-form');
|
||||||
|
|
||||||
|
/* US-003 (3.6): un singur sticky bar pe ecran — cand re-apare zona de upload
|
||||||
|
(reset sau dupa commit), sectiunea Trimiteri redevine vizibila. */
|
||||||
|
var trim = document.getElementById('trimiteri-section');
|
||||||
|
if (trim) trim.style.display = '';
|
||||||
|
|
||||||
|
/* Dupa un commit reusit (mesaj de succes), du utilizatorul la Trimiteri. */
|
||||||
|
{% if message and not error %}
|
||||||
|
if (trim) trim.scrollIntoView({behavior: 'smooth', block: 'start'});
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
if (!btn || !fi || !frm) return;
|
if (!btn || !fi || !frm) return;
|
||||||
|
|
||||||
btn.addEventListener('click', function() { fi.click(); });
|
btn.addEventListener('click', function() { fi.click(); });
|
||||||
|
|||||||
@@ -5,6 +5,14 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>{% block title %}Gateway RAR AUTOPASS{% endblock %}</title>
|
<title>{% block title %}Gateway RAR AUTOPASS{% endblock %}</title>
|
||||||
<script src="/static/htmx.min.js"></script>
|
<script src="/static/htmx.min.js"></script>
|
||||||
|
<script>
|
||||||
|
// US-002 (3.6): raspunsurile de editare-rand contin un <tr> (swap pe rand) PLUS
|
||||||
|
// elemente OOB non-rand (#preview-rezumat, #preview-ok-count). Fara fragmente-template,
|
||||||
|
// htmx parseaza raspunsul care incepe cu <tr> in context de tabel (<table><tbody>) si
|
||||||
|
// "foster-parent"-eaza div/span-urile OOB afara din fragment -> swapError + contoare pierdute.
|
||||||
|
// useTemplateFragments parseaza tot intr-un <template>, pastrand rand + OOB impreuna.
|
||||||
|
htmx.config.useTemplateFragments = true;
|
||||||
|
</script>
|
||||||
<style>
|
<style>
|
||||||
:root { --bg:#0f1115; --card:#181b22; --ink:#e6e9ef; --muted:#8b93a7; --line:#262b36;
|
:root { --bg:#0f1115; --card:#181b22; --ink:#e6e9ef; --muted:#8b93a7; --line:#262b36;
|
||||||
--ok:#3ecf8e; --warn:#e6b34a; --err:#e5605e; --accent:#5b8def; }
|
--ok:#3ecf8e; --warn:#e6b34a; --err:#e5605e; --accent:#5b8def; }
|
||||||
|
|||||||
@@ -20,9 +20,10 @@
|
|||||||
|
|
||||||
<!-- Tab-bar: navigare intre sectiuni -->
|
<!-- Tab-bar: navigare intre sectiuni -->
|
||||||
<div role="tablist" class="tab-bar" aria-label="Sectiuni dashboard">
|
<div role="tablist" class="tab-bar" aria-label="Sectiuni dashboard">
|
||||||
|
{# US-003 (3.6): tab-ul "Trimiteri" (coada) a fost eliminat — Trimiterile traiesc
|
||||||
|
ca sectiune permanenta pe Acasa. Raman: Acasa·Mapari·Cont·Nomenclator. #}
|
||||||
{% set tabs = [
|
{% set tabs = [
|
||||||
("acasa", "Acasa", "tab-acasa"),
|
("acasa", "Acasa", "tab-acasa"),
|
||||||
("coada", "Trimiteri", "tab-coada"),
|
|
||||||
("mapari", "Mapari", "tab-mapari"),
|
("mapari", "Mapari", "tab-mapari"),
|
||||||
("cont", "Cont", "tab-cont"),
|
("cont", "Cont", "tab-cont"),
|
||||||
("nomenclator", "Nomenclator", "tab-nomenclator")
|
("nomenclator", "Nomenclator", "tab-nomenclator")
|
||||||
|
|||||||
3
tests/fixtures/import_antet_necanonic.csv
vendored
Normal file
3
tests/fixtures/import_antet_necanonic.csv
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
Serie sasiu,Nr,Data,KM,Operatie
|
||||||
|
WVWZZZ1KZAW000123,B001TST,,123456,OP-1
|
||||||
|
WVWZZZ1KZAW000999,B009TST,2026-06-10,55000,OP-1
|
||||||
|
2
tests/fixtures/import_lipsa_coloana.csv
vendored
Normal file
2
tests/fixtures/import_lipsa_coloana.csv
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
Serie sasiu,Nr,KM,Operatie
|
||||||
|
WVWZZZ1KZAW000456,B002TST,98765,OP-1
|
||||||
|
131
tests/test_acasa_trimiteri.py
Normal file
131
tests/test_acasa_trimiteri.py
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
"""Teste US-003 (PRD 3.6): Acasa unificata — Trimiteri ca sectiune permanenta.
|
||||||
|
|
||||||
|
Tab-ul "Trimiteri" (coada) eliminat din tab-bar; Trimiterile devin o sectiune sub
|
||||||
|
upload pe Acasa, cu heading "Trimiterile tale". ?tab=coada si /_fragments/coada
|
||||||
|
servesc continutul Acasa (nu 404, nu fragment orfan). Poll aliniat la 15s (M5).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "acasa.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "false")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.crypto import reset_cache
|
||||||
|
reset_cache()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
get_settings.cache_clear()
|
||||||
|
reset_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_submission(status: str = "sent", n: int = 1) -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
for i in range(n):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||||
|
"VALUES (?, 1, ?, ?)",
|
||||||
|
(f"k-{status}-{os.urandom(5).hex()}", status,
|
||||||
|
json.dumps({"vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B001TST",
|
||||||
|
"data_prestatie": "2026-06-10", "odometru_final": "123456",
|
||||||
|
"prestatii": [{"cod_prestatie": "R-FRANE"}]})),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tab_bar_fara_trimiteri(client):
|
||||||
|
"""Tab-bar-ul nu mai contine tab-ul 'Trimiteri' (coada); raman 4 tab-uri."""
|
||||||
|
r = client.get("/")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert 'id="tab-coada"' not in html
|
||||||
|
assert 'href="/?tab=coada"' not in html
|
||||||
|
for label in ("Acasa", "Mapari", "Cont", "Nomenclator"):
|
||||||
|
assert f">{label}" in html or f"{label}<" in html, f"lipseste tab {label}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_acasa_contine_sectiunea_trimiteri(client):
|
||||||
|
"""Acasa randeaza sectiunea Trimiteri (filtre + tabel) cand contul are trimiteri."""
|
||||||
|
_seed_submission("sent")
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert 'id="filtre-trimiteri"' in html
|
||||||
|
assert "/_fragments/submissions" in html
|
||||||
|
assert 'id="trimitere-detaliu"' in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_sectiune_trimiteri_are_heading(client):
|
||||||
|
"""Sectiunea Trimiteri are heading 'Trimiterile tale'."""
|
||||||
|
_seed_submission("sent")
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
assert "Trimiterile tale" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_tab_coada_redirect_la_acasa(client):
|
||||||
|
"""?tab=coada nu da 404 si serveste continutul Acasa (upload-ul de import)."""
|
||||||
|
r = client.get("/?tab=coada")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert 'id="import-section"' in r.text or 'id="acasa-section"' in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_fragment_coada_serveste_acasa(client):
|
||||||
|
"""/_fragments/coada serveste continutul Acasa (fara fragment _coada orfan)."""
|
||||||
|
_seed_submission("sent")
|
||||||
|
r = client.get("/_fragments/coada")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert 'id="acasa-section"' in html
|
||||||
|
assert "Trimiterile tale" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_acasa_fara_linkuri_ajutor(client):
|
||||||
|
"""Linkul redundant 'Trimiteri' din randul de ajutor a fost eliminat."""
|
||||||
|
_seed_submission("sent")
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
assert 'href="/?tab=coada"' not in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_acasa_pastreaza_wayfinding_mapari_coduri(client):
|
||||||
|
"""Wayfinding-ul pastreaza 'Mapari' si 'Coduri RAR'."""
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
html = r.text
|
||||||
|
assert 'href="/?tab=mapari"' in html
|
||||||
|
assert "Coduri RAR" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_badge_trimiteri_scoped_pe_acasa(client):
|
||||||
|
"""Contorul de atentie (blocate) se reflecta in heading-ul sectiunii Trimiteri."""
|
||||||
|
_seed_submission("needs_data", n=2)
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
html = r.text
|
||||||
|
assert "Trimiterile tale" in html
|
||||||
|
# Badge cu numarul de blocate (2) langa heading.
|
||||||
|
idx = html.find("Trimiterile tale")
|
||||||
|
assert idx != -1
|
||||||
|
assert "2" in html[idx:idx + 400]
|
||||||
|
|
||||||
|
|
||||||
|
def test_trimiteri_poll_aliniat_15s(client):
|
||||||
|
"""Poll-ul de trimiteri e aliniat la 15s (anti dublu-poll M5), nu 10s."""
|
||||||
|
_seed_submission("sent")
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
html = r.text
|
||||||
|
assert "every 15s" in html
|
||||||
|
assert "every 10s" not in html
|
||||||
214
tests/test_autosend_toggle.py
Normal file
214
tests/test_autosend_toggle.py
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
"""Teste US-007 (PRD 3.6): bifa "auto-send" devine un comutator cu doua stari,
|
||||||
|
etichetat pe COADA (nu pe trimitere).
|
||||||
|
|
||||||
|
Framing decis la poarta autoplan (UC-A): "Pune automat in coada" / "Tine pentru
|
||||||
|
verificare". NU "Automat/Manual" (risc de send-safety peste declaratii ireversibile).
|
||||||
|
`name="auto_send"` pastrat cu semantica de prezenta (checkbox value="true"):
|
||||||
|
bifat -> auto_send True, nebifat -> absent -> False. Zero atingere backend, identic
|
||||||
|
cu ambele parsere existente (`Form(bool)` la /mapari si `bool(form.get())` la preview).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from starlette.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
# --- helpers comune (mirror test_mapari_tabel.py) ---
|
||||||
|
|
||||||
|
def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
|
||||||
|
from app.accounts import create_account
|
||||||
|
from app.users import create_user
|
||||||
|
from app.db import get_connection
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
acct_id = create_account(conn, name, active=True)
|
||||||
|
create_user(conn, acct_id, email, password)
|
||||||
|
return acct_id
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client, email: str, password: str = "parolasecreta10") -> None:
|
||||||
|
resp = client.get("/login")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
|
||||||
|
assert m
|
||||||
|
resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
|
||||||
|
assert resp.status_code == 303
|
||||||
|
|
||||||
|
|
||||||
|
def _csrf(client) -> str:
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
|
||||||
|
assert m, "csrf_token negasit"
|
||||||
|
return m.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_nomenclator(cod: str, nume: str = "Test prestatie") -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
|
||||||
|
(cod, nume),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _auto_send_of(acct: int, op: str) -> int | None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
r = conn.execute(
|
||||||
|
"SELECT auto_send FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
|
||||||
|
(acct, op),
|
||||||
|
).fetchone()
|
||||||
|
return None if r is None else int(r["auto_send"])
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "autosend_toggle.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.web import ratelimit
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app, follow_redirects=False) as c:
|
||||||
|
yield c
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def _macro_html(checked: bool = True, form_id: str = "") -> str:
|
||||||
|
"""Randeaza direct macro-ul comutatorului, izolat de restul paginii."""
|
||||||
|
from app.web.routes import templates
|
||||||
|
mod = templates.env.get_template("_macros.html").make_module({})
|
||||||
|
return str(mod.autosend_toggle(form_id=form_id, checked=checked))
|
||||||
|
|
||||||
|
|
||||||
|
# --- markup / copy ---
|
||||||
|
|
||||||
|
def test_comutator_coada_prezent():
|
||||||
|
"""Textul tinteste COADA ("in coada"/"verificare"), NU "trimite"/"Manual" gol."""
|
||||||
|
html = _macro_html()
|
||||||
|
assert "in coada" in html, "comutatorul trebuie sa vorbeasca despre coada"
|
||||||
|
assert "verificare" in html, "optiunea de verificare manuala trebuie prezenta"
|
||||||
|
assert "name=\"auto_send\"" in html and 'value="true"' in html
|
||||||
|
# framing periculos interzis (citit global = send-safety):
|
||||||
|
assert "Manual" not in html, "fara 'Manual' gol (sugereaza bypass al confirmarii RAR)"
|
||||||
|
assert "trimite" not in html.lower(), "fara cuvantul 'trimite' izolat in eticheta"
|
||||||
|
assert "auto-send" not in html, "jargonul 'auto-send' trebuie inlocuit"
|
||||||
|
|
||||||
|
|
||||||
|
def test_eticheta_scoped_pe_operatie():
|
||||||
|
"""Microcopy scoped pe operatie (NU global)."""
|
||||||
|
html = _macro_html()
|
||||||
|
assert "aceasta operatie" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_pune_automat():
|
||||||
|
"""Default = "Pune automat in coada" (mirror la checkbox-ul `checked` de azi)."""
|
||||||
|
html_default = _macro_html(checked=True)
|
||||||
|
assert "checked" in html_default
|
||||||
|
html_off = _macro_html(checked=False)
|
||||||
|
assert "checked" not in html_off, "starea stocata False nu trebuie bifata (H4)"
|
||||||
|
|
||||||
|
|
||||||
|
# --- comportament (zero atingere backend) ---
|
||||||
|
|
||||||
|
def test_pune_automat_mapeaza_auto_send_true(client):
|
||||||
|
"""Bifat -> auto_send=true trimis -> stocat True (identic cu azi)."""
|
||||||
|
acct = _create_account_user("pa@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE")
|
||||||
|
_login(client, "pa@test.com")
|
||||||
|
csrf = _csrf(client)
|
||||||
|
resp = client.post("/mapari", data={
|
||||||
|
"cod_op_service": "OP-A", "cod_prestatie": "R-FRANE",
|
||||||
|
"auto_send": "true", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert _auto_send_of(acct, "OP-A") == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_tine_pentru_verificare_mapeaza_auto_send_false(client):
|
||||||
|
"""Nebifat -> camp absent -> stocat False (semantica de prezenta a checkbox-ului)."""
|
||||||
|
acct = _create_account_user("tv@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE")
|
||||||
|
_login(client, "tv@test.com")
|
||||||
|
csrf = _csrf(client)
|
||||||
|
# "Tine pentru verificare" = comutatorul nebifat -> name=auto_send NU se trimite
|
||||||
|
resp = client.post("/mapari", data={
|
||||||
|
"cod_op_service": "OP-B", "cod_prestatie": "R-FRANE", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert _auto_send_of(acct, "OP-B") == 0
|
||||||
|
|
||||||
|
|
||||||
|
# --- prezent in AMBELE locuri (mapari tab + panou preview) ---
|
||||||
|
|
||||||
|
def test_comutator_in_tab_mapari(client):
|
||||||
|
"""Tabul Mapari (de-rezolvat) foloseste comutatorul de coada, nu jargonul vechi."""
|
||||||
|
from app.db import get_connection
|
||||||
|
import json
|
||||||
|
acct = _create_account_user("tm@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE")
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||||
|
"VALUES (?, ?, 'needs_mapping', ?)",
|
||||||
|
("k-tm", acct, json.dumps({"prestatii": [{"cod_op_service": "OP-NM", "denumire": "x"}]})),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
_login(client, "tm@test.com")
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert "Pune automat in coada" in resp.text
|
||||||
|
assert "aceasta operatie" in resp.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_comutator_in_panou_preview(client):
|
||||||
|
"""Panoul de mapare din preview are si el comutatorul + caption (azi lipsea caption)."""
|
||||||
|
_create_account_user("pp@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE")
|
||||||
|
_login(client, "pp@test.com")
|
||||||
|
csrf = _csrf(client)
|
||||||
|
|
||||||
|
buf = io.StringIO()
|
||||||
|
w = csv.DictWriter(buf, fieldnames=["VIN", "Nr", "Data", "Odo", "Operatie"], delimiter=";")
|
||||||
|
w.writeheader()
|
||||||
|
w.writerow({"VIN": "WVWZZZ1KZAW000123", "Nr": "B001TST",
|
||||||
|
"Data": "15.06.2026", "Odo": "123456", "Operatie": "OP-NEMAPAT"})
|
||||||
|
data = buf.getvalue().encode("utf-8")
|
||||||
|
|
||||||
|
r = client.post("/_import/upload", files={"file": ("t.csv", data, "text/csv")},
|
||||||
|
data={"csrf_token": csrf})
|
||||||
|
assert r.status_code == 200
|
||||||
|
m = re.search(r"/_import/(\d+)/mapare-coloane", r.text)
|
||||||
|
assert m
|
||||||
|
import_id = int(m.group(1))
|
||||||
|
r = client.post(f"/_import/{import_id}/mapare-coloane", data={
|
||||||
|
"colname": ["VIN", "Nr", "Data", "Odo", "Operatie"],
|
||||||
|
"canon": ["vin", "nr_inmatriculare", "data_prestatie", "odometru_final", "operatie"],
|
||||||
|
"format_data": "DD.MM.YYYY", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "OP-NEMAPAT" in r.text, "operatia nemapata trebuie sa apara in panoul de mapare"
|
||||||
|
assert "Pune automat in coada" in r.text
|
||||||
|
assert "aceasta operatie" in r.text
|
||||||
136
tests/test_formate_tabel.py
Normal file
136
tests/test_formate_tabel.py
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
"""Teste US-006 (PRD 3.6): "Formate de coloane salvate" randate ca TABEL.
|
||||||
|
|
||||||
|
Doar marcaj de template — POST-urile /formate-coloane/editeaza si /formate-coloane/sterge
|
||||||
|
raman identice. .tablewrap pentru consistenta cu celelalte tabele.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from starlette.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
|
||||||
|
from app.accounts import create_account
|
||||||
|
from app.users import create_user
|
||||||
|
from app.db import get_connection
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
acct_id = create_account(conn, name, active=True)
|
||||||
|
create_user(conn, acct_id, email, password)
|
||||||
|
return acct_id
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client, email: str, password: str = "parolasecreta10") -> None:
|
||||||
|
resp = client.get("/login")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
|
||||||
|
re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
|
||||||
|
assert m
|
||||||
|
resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
|
||||||
|
assert resp.status_code == 303
|
||||||
|
|
||||||
|
|
||||||
|
def _csrf(client) -> str:
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
|
||||||
|
re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
|
||||||
|
assert m
|
||||||
|
return m.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_format(acct: int, sig: str, mapare: dict, fmt: str | None) -> int:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO column_mappings (account_id, signature_coloane, json_mapare, format_data) "
|
||||||
|
"VALUES (?, ?, ?, ?)",
|
||||||
|
(acct, sig, json.dumps(mapare, ensure_ascii=False), fmt),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return int(cur.lastrowid)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _slice(text: str, start_marker: str, end_marker: str | None) -> str:
|
||||||
|
i = text.index(start_marker)
|
||||||
|
j = text.index(end_marker, i) if end_marker else len(text)
|
||||||
|
return text[i:j]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "formate_tabel.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.web import ratelimit
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app, follow_redirects=False) as c:
|
||||||
|
yield c
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_formate_coloane_in_tabel(client):
|
||||||
|
"""Sectiunea "Formate de coloane salvate" randata ca tabel: nr coloane / mapari / format data / Sterge."""
|
||||||
|
acct = _create_account_user("ft@test.com")
|
||||||
|
_seed_format(acct, "sig-1", {"Serie sasiu": "vin", "Nr auto": "nr_inmatriculare"}, "DD.MM.YYYY")
|
||||||
|
_login(client, "ft@test.com")
|
||||||
|
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
sec = _slice(resp.text, "Formate de coloane salvate", None)
|
||||||
|
|
||||||
|
assert "tablewrap" in sec, "tabelul Formate trebuie sa foloseasca .tablewrap"
|
||||||
|
assert "<table" in sec and "<th" in sec, "Formate trebuie randat ca tabel cu antet"
|
||||||
|
# nr coloane + maparile col -> camp
|
||||||
|
assert "2" in sec
|
||||||
|
assert "Serie sasiu" in sec and "vin" in sec
|
||||||
|
# format data editabil prezent
|
||||||
|
assert 'name="format_data"' in sec
|
||||||
|
assert "DD.MM.YYYY" in sec
|
||||||
|
# POST-urile neschimbate
|
||||||
|
assert 'hx-post="/formate-coloane/editeaza"' in sec
|
||||||
|
assert 'hx-post="/formate-coloane/sterge"' in sec
|
||||||
|
|
||||||
|
|
||||||
|
def test_formate_editare_data_si_stergere_inca_functioneaza(client):
|
||||||
|
"""POST /formate-coloane/editeaza (schimba format_data) si /sterge neschimbate."""
|
||||||
|
acct = _create_account_user("fts@test.com")
|
||||||
|
fid = _seed_format(acct, "sig-2", {"Data": "data_prestatie"}, "DD.MM.YYYY")
|
||||||
|
_login(client, "fts@test.com")
|
||||||
|
csrf = _csrf(client)
|
||||||
|
|
||||||
|
resp = client.post("/formate-coloane/editeaza", data={
|
||||||
|
"format_id": str(fid), "format_data": "YYYY-MM-DD", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT format_data FROM column_mappings WHERE id=?", (fid,)).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert row["format_data"] == "YYYY-MM-DD"
|
||||||
|
|
||||||
|
resp = client.post("/formate-coloane/sterge", data={"format_id": str(fid), "csrf_token": csrf})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT 1 FROM column_mappings WHERE id=?", (fid,)).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert row is None
|
||||||
275
tests/test_import_edit_row.py
Normal file
275
tests/test_import_edit_row.py
Normal file
@@ -0,0 +1,275 @@
|
|||||||
|
"""Teste US-001 (PRD 3.6): backend — persista editarea unui rand de preview.
|
||||||
|
|
||||||
|
Approach B: editarea scrie un patch CANONIC in import_rows.override_json (criptat
|
||||||
|
Fernet), aplicat ULTIMUL in _resolve_row_for_preview + commit. raw_json/idempotency
|
||||||
|
raman neatinse. Ruta editare = mutatie PURA (nu re-deriva status, nu atinge submissions).
|
||||||
|
|
||||||
|
TDD: testele se scriu inainte de implementare (RED -> GREEN).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
_FIXTURES = pathlib.Path(__file__).parent / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "edit.db"))
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.crypto import reset_cache
|
||||||
|
reset_cache()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
get_settings.cache_clear()
|
||||||
|
reset_cache()
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Helpere #
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _seed_op1(account_id: int = 1) -> None:
|
||||||
|
"""Nomenclator + mapare OP-1 -> R-FRANE (auto_send=1) pentru contul dat."""
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) "
|
||||||
|
"VALUES ('R-FRANE','Reparatie frane')"
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) "
|
||||||
|
"VALUES (?, 'OP-1', 'R-FRANE', 1)",
|
||||||
|
(account_id,),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _upload(client: TestClient, fixture: str, headers: dict | None = None) -> int:
|
||||||
|
data = (_FIXTURES / fixture).read_bytes()
|
||||||
|
r = client.post(
|
||||||
|
"/v1/import",
|
||||||
|
files={"file": (fixture, io.BytesIO(data), "text/csv")},
|
||||||
|
headers=headers or {},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return int(r.json()["import_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def _save_mapping(client: TestClient, import_id: int, json_mapare: dict,
|
||||||
|
headers: dict | None = None) -> None:
|
||||||
|
r = client.post(
|
||||||
|
f"/v1/import/{import_id}/column-mapping",
|
||||||
|
json={"json_mapare": json_mapare, "format_data": "YYYY-MM-DD"},
|
||||||
|
headers=headers or {},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
|
||||||
|
|
||||||
|
def _preview(client: TestClient, import_id: int, headers: dict | None = None) -> list[dict]:
|
||||||
|
r = client.get(f"/v1/import/{import_id}/preview", headers=headers or {})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return r.json()["rows"]
|
||||||
|
|
||||||
|
|
||||||
|
def _status_for(rows: list[dict], row_index: int) -> str:
|
||||||
|
return next(r["resolved_status"] for r in rows if r["row_index"] == row_index)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolved_for(rows: list[dict], row_index: int) -> dict:
|
||||||
|
return next(r["resolved"] for r in rows if r["row_index"] == row_index)
|
||||||
|
|
||||||
|
|
||||||
|
_MAP_NECANONIC = {
|
||||||
|
"Serie sasiu": "vin",
|
||||||
|
"Nr": "nr_inmatriculare",
|
||||||
|
"Data": "data_prestatie",
|
||||||
|
"KM": "odometru_final",
|
||||||
|
"Operatie": "operatie",
|
||||||
|
}
|
||||||
|
_MAP_LIPSA = {
|
||||||
|
"Serie sasiu": "vin",
|
||||||
|
"Nr": "nr_inmatriculare",
|
||||||
|
"KM": "odometru_final",
|
||||||
|
"Operatie": "operatie",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Teste #
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def test_editeaza_rand_antet_necanonic_devine_ok(client):
|
||||||
|
"""Fisier cu antet ne-canonic (Serie sasiu/Data): rand needs_data -> editez data -> ok.
|
||||||
|
|
||||||
|
Prinde bug-ul de stocare: o editare pe cheia canonica trebuie sa se aplice chiar
|
||||||
|
daca raw_json e cheiat pe anteturi ne-canonice.
|
||||||
|
"""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
assert _status_for(_preview(client, iid), 0) == "needs_data"
|
||||||
|
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
|
||||||
|
assert _status_for(_preview(client, iid), 0) == "ok"
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_completeaza_coloana_absenta(client):
|
||||||
|
"""Fisier FARA coloana de data: editarea adauga data_prestatie -> ok.
|
||||||
|
|
||||||
|
Demonstreaza ca override poate exprima un camp a carui coloana LIPSESTE din fisier.
|
||||||
|
"""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_lipsa_coloana.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_LIPSA)
|
||||||
|
assert _status_for(_preview(client, iid), 0) == "needs_data"
|
||||||
|
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
|
||||||
|
assert _status_for(_preview(client, iid), 0) == "ok"
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_status_identic_cu_GET_preview(client):
|
||||||
|
"""Ruta editare NU re-deriva status (intoarce doar override); statusul vine din GET preview."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.json()
|
||||||
|
# Mutatie pura: raspunsul nu contine un status rederivat in ruta.
|
||||||
|
assert "resolved_status" not in body
|
||||||
|
assert body.get("override", {}).get("data_prestatie") == "2026-06-10"
|
||||||
|
# Statusul se rederiva DOAR prin preview.
|
||||||
|
assert _status_for(_preview(client, iid), 0) == "ok"
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_rand_scoped_alt_cont_404(client):
|
||||||
|
"""Editarea unui rand al altui cont -> 404 (scoping JOIN, fara leak)."""
|
||||||
|
from app.db import get_connection
|
||||||
|
from app.accounts import create_account
|
||||||
|
from app.auth import create_api_key
|
||||||
|
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv") # cont 1 (default)
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
acct2 = create_account(conn, "Alt cont", active=True)
|
||||||
|
key2 = create_api_key(conn, acct2)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
r = client.post(
|
||||||
|
f"/v1/import/{iid}/rand/0/editeaza",
|
||||||
|
json={"data_prestatie": "2026-06-10"},
|
||||||
|
headers={"X-API-Key": key2},
|
||||||
|
)
|
||||||
|
assert r.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_batch_inexistent_404(client):
|
||||||
|
r = client.post("/v1/import/99999/rand/0/editeaza", json={"vin": "WVWZZZ1KZAW000123"})
|
||||||
|
assert r.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_row_index_invalid_pe_batch_valid_404(client):
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/9999/editeaza", json={"vin": "WVWZZZ1KZAW000123"})
|
||||||
|
assert r.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_pastreaza_campuri_neatinse(client):
|
||||||
|
"""Editarea unui camp nu pierde prestatiile/operatia rezolvate ale randului."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
|
||||||
|
client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
res = _resolved_for(_preview(client, iid), 0)
|
||||||
|
prestatii = res.get("prestatii") or []
|
||||||
|
assert prestatii, "prestatiile au disparut dupa editare"
|
||||||
|
assert (prestatii[0].get("cod_prestatie") or prestatii[0].get("cod_op_service")) in ("R-FRANE", "OP-1")
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_batch_committed_409(client):
|
||||||
|
"""Editarea pe un batch deja comis -> 409 (nu mai are efect downstream)."""
|
||||||
|
from app.db import get_connection
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute("UPDATE import_batches SET status='committed' WHERE id=?", (iid,))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_raw_corupt_no_op(client):
|
||||||
|
"""Override curent ilizibil (decrypt fail) -> 422/no-op, fara scriere goala, fara crash."""
|
||||||
|
from app.db import get_connection
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE import_rows SET override_json=? WHERE batch_id=? AND row_index=0",
|
||||||
|
("token-corupt-nedecriptabil", iid),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
r = client.post(f"/v1/import/{iid}/rand/0/editeaza", json={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 422
|
||||||
|
|
||||||
|
# override_json NU a fost suprascris cu o valoare goala
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
oj = conn.execute(
|
||||||
|
"SELECT override_json FROM import_rows WHERE batch_id=? AND row_index=0", (iid,)
|
||||||
|
).fetchone()["override_json"]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert oj == "token-corupt-nedecriptabil"
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_empty_input_sterge_campul(client):
|
||||||
|
"""Semantica empty: input gol = STERGE cheia din override (revine la valoarea din fisier)."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload(client, "import_antet_necanonic.csv")
|
||||||
|
_save_mapping(client, iid, _MAP_NECANONIC)
|
||||||
|
|
||||||
|
# Randul 1 are odometru_final 55000 in fisier. Suprascriem cu 77000 prin override.
|
||||||
|
client.post(f"/v1/import/{iid}/rand/1/editeaza", json={"odometru_final": "77000"})
|
||||||
|
assert _resolved_for(_preview(client, iid), 1).get("odometru_final") == "77000"
|
||||||
|
|
||||||
|
# Input gol -> sterge override-ul -> revine la valoarea din fisier (55000).
|
||||||
|
client.post(f"/v1/import/{iid}/rand/1/editeaza", json={"odometru_final": ""})
|
||||||
|
assert _resolved_for(_preview(client, iid), 1).get("odometru_final") == "55000"
|
||||||
232
tests/test_mapari_tabel.py
Normal file
232
tests/test_mapari_tabel.py
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
"""Teste US-005 (PRD 3.6): "De rezolvat" si "Operatii salvate" randate ca TABELE.
|
||||||
|
|
||||||
|
Doar marcaj de template — POST-urile /mapari, /mapari/salvate, /mapari/salvate/sterge
|
||||||
|
raman identice. H4: comutatorul auto-send din tabelul salvate reflecta valoarea STOCATA
|
||||||
|
per mapare (din _load_saved_op_mappings), nu un default hard.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from starlette.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
|
||||||
|
from app.accounts import create_account
|
||||||
|
from app.users import create_user
|
||||||
|
from app.db import get_connection
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
acct_id = create_account(conn, name, active=True)
|
||||||
|
create_user(conn, acct_id, email, password)
|
||||||
|
return acct_id
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client, email: str, password: str = "parolasecreta10") -> None:
|
||||||
|
resp = client.get("/login")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
|
||||||
|
re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
|
||||||
|
assert m
|
||||||
|
resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
|
||||||
|
assert resp.status_code == 303
|
||||||
|
|
||||||
|
|
||||||
|
def _csrf(client) -> str:
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
|
||||||
|
re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
|
||||||
|
assert m, "csrf_token negasit"
|
||||||
|
return m.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_nomenclator(cod: str, nume: str = "Test prestatie") -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
|
||||||
|
(cod, nume),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_op_mapping(acct: int, op: str, cod: str, auto_send: int = 1) -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) "
|
||||||
|
"VALUES (?, ?, ?, ?)",
|
||||||
|
(acct, op, cod, auto_send),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_needs_mapping(acct: int, op: str) -> int:
|
||||||
|
"""Submission needs_mapping (canal API, batch_id NULL) cu o operatie nemapata."""
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||||
|
"VALUES (?, ?, 'needs_mapping', ?)",
|
||||||
|
(
|
||||||
|
f"k-{op}-{os.urandom(4).hex()}",
|
||||||
|
acct,
|
||||||
|
json.dumps({
|
||||||
|
"vin": "WVWZZZ1JZXW000111",
|
||||||
|
"nr_inmatriculare": "B11AAA",
|
||||||
|
"data_prestatie": "2026-06-18",
|
||||||
|
"odometru_final": "12345",
|
||||||
|
"prestatii": [{"cod_op_service": op, "denumire": "ceva"}],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return cur.lastrowid
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _status_of(sid: int) -> str:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
return conn.execute("SELECT status FROM submissions WHERE id=?", (sid,)).fetchone()["status"]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _slice(text: str, start_marker: str, end_marker: str | None) -> str:
|
||||||
|
i = text.index(start_marker)
|
||||||
|
j = text.index(end_marker, i) if end_marker else len(text)
|
||||||
|
return text[i:j]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "mapari_tabel.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.web import ratelimit
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app, follow_redirects=False) as c:
|
||||||
|
yield c
|
||||||
|
ratelimit._hits.clear()
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapari_de_rezolvat_in_tabel(client):
|
||||||
|
"""Sectiunea "De rezolvat" randata ca tabel (.tablewrap + <table> + un rand per operatie)."""
|
||||||
|
acct = _create_account_user("rez@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE", "Reparatie frane")
|
||||||
|
_seed_needs_mapping(acct, "OP-REZ1")
|
||||||
|
_login(client, "rez@test.com")
|
||||||
|
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
sec = _slice(resp.text, "De rezolvat", "Mapari operatii salvate")
|
||||||
|
|
||||||
|
assert "tablewrap" in sec, "tabelul De rezolvat trebuie sa foloseasca .tablewrap"
|
||||||
|
assert "<table" in sec and "<th" in sec, "De rezolvat trebuie randat ca tabel cu antet"
|
||||||
|
assert "OP-REZ1" in sec, "operatia nemapata trebuie sa apara ca rand"
|
||||||
|
# POST neschimbat: forma trimite tot la /mapari
|
||||||
|
assert 'hx-post="/mapari"' in sec
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapari_salvate_in_tabel(client):
|
||||||
|
"""Sectiunea "Operatii salvate" randata ca tabel; H4: auto-send reflecta valoarea STOCATA."""
|
||||||
|
acct = _create_account_user("salv@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE", "Reparatie frane")
|
||||||
|
_seed_nomenclator("R-MOTOR", "Reparatie motor")
|
||||||
|
_seed_op_mapping(acct, "OP-AUTO", "R-FRANE", auto_send=1)
|
||||||
|
_seed_op_mapping(acct, "OP-MANUAL", "R-MOTOR", auto_send=0)
|
||||||
|
_login(client, "salv@test.com")
|
||||||
|
|
||||||
|
resp = client.get("/?tab=mapari")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
sec = _slice(resp.text, "Mapari operatii salvate", "Formate de coloane salvate")
|
||||||
|
|
||||||
|
assert "tablewrap" in sec, "tabelul Operatii salvate trebuie sa foloseasca .tablewrap"
|
||||||
|
assert "<table" in sec and "<th" in sec, "Operatii salvate trebuie randat ca tabel cu antet"
|
||||||
|
assert "OP-AUTO" in sec and "OP-MANUAL" in sec
|
||||||
|
assert 'name="auto_send"' in sec
|
||||||
|
# H4: exact maparile cu auto_send STOCAT True sunt bifate (aici: o singura)
|
||||||
|
assert sec.count("checked") == 1, "comutatorul auto-send trebuie sa reflecte valoarea stocata, nu un default"
|
||||||
|
# POST-urile neschimbate
|
||||||
|
assert 'hx-post="/mapari/salvate"' in sec
|
||||||
|
assert 'hx-post="/mapari/salvate/sterge"' in sec
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapari_salvare_si_stergere_inca_functioneaza(client):
|
||||||
|
"""POST /mapari (salveaza), /mapari/salvate (edit), /mapari/salvate/sterge (delete) neschimbate."""
|
||||||
|
acct = _create_account_user("func@test.com")
|
||||||
|
_seed_nomenclator("R-FRANE", "Reparatie frane")
|
||||||
|
_seed_nomenclator("R-MOTOR", "Reparatie motor")
|
||||||
|
sid = _seed_needs_mapping(acct, "OP-300")
|
||||||
|
assert _status_of(sid) == "needs_mapping"
|
||||||
|
_login(client, "func@test.com")
|
||||||
|
csrf = _csrf(client)
|
||||||
|
|
||||||
|
# Salveaza o mapare noua pentru operatia nemapata -> se deblocheaza
|
||||||
|
resp = client.post("/mapari", data={
|
||||||
|
"cod_op_service": "OP-300", "cod_prestatie": "R-FRANE", "auto_send": "true", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert _status_of(sid) != "needs_mapping"
|
||||||
|
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT cod_prestatie FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
|
||||||
|
(acct, "OP-300"),
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert row and row["cod_prestatie"] == "R-FRANE"
|
||||||
|
|
||||||
|
# Editeaza maparea salvata
|
||||||
|
resp = client.post("/mapari/salvate", data={
|
||||||
|
"cod_op_service": "OP-300", "cod_prestatie": "R-MOTOR", "auto_send": "true", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT cod_prestatie FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
|
||||||
|
(acct, "OP-300"),
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert row["cod_prestatie"] == "R-MOTOR"
|
||||||
|
|
||||||
|
# Sterge maparea salvata
|
||||||
|
resp = client.post("/mapari/salvate/sterge", data={
|
||||||
|
"cod_op_service": "OP-300", "csrf_token": csrf,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
|
||||||
|
(acct, "OP-300"),
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
assert row is None
|
||||||
137
tests/test_preview_edit_ui.py
Normal file
137
tests/test_preview_edit_ui.py
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
"""Teste US-002 (PRD 3.6): buton "Editeaza" pe rand in tabelul de preview.
|
||||||
|
|
||||||
|
Mod editare pe rand (form propriu, NU #confirm-form). Swap pe rand + OOB contoare,
|
||||||
|
NU pe #import-section (D-3.1). La eroare de validare randul ramane in editare cu
|
||||||
|
valorile pastrate (D-2.1/D-2.2). Enter intr-un camp salveaza randul, nu confirma (D-3.3).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
_FIXTURES = pathlib.Path(__file__).parent / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "edit_ui.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "false")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.crypto import reset_cache
|
||||||
|
reset_cache()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
get_settings.cache_clear()
|
||||||
|
reset_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_op1() -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) "
|
||||||
|
"VALUES ('R-FRANE','Reparatie frane')"
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) "
|
||||||
|
"VALUES (1, 'OP-1', 'R-FRANE', 1)"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _upload_and_preview(client: TestClient) -> int:
|
||||||
|
"""Upload fixture necanonic + salveaza maparea -> preview. Intoarce import_id."""
|
||||||
|
data = (_FIXTURES / "import_antet_necanonic.csv").read_bytes()
|
||||||
|
r = client.post(
|
||||||
|
"/_import/upload",
|
||||||
|
files={"file": ("import_antet_necanonic.csv", io.BytesIO(data), "text/csv")},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
m = re.search(r"/_import/(\d+)/mapare-coloane", r.text)
|
||||||
|
assert m, "import_id negasit in formularul de mapare"
|
||||||
|
iid = int(m.group(1))
|
||||||
|
r = client.post(f"/_import/{iid}/mapare-coloane", data={
|
||||||
|
"colname": ["Serie sasiu", "Nr", "Data", "KM", "Operatie"],
|
||||||
|
"canon": ["vin", "nr_inmatriculare", "data_prestatie", "odometru_final", "operatie"],
|
||||||
|
"format_data": "YYYY-MM-DD",
|
||||||
|
})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return iid
|
||||||
|
|
||||||
|
|
||||||
|
def test_preview_are_buton_editeaza_pe_rand(client):
|
||||||
|
"""Tabelul de preview are buton 'Editeaza' pe rand (coloana de actiuni)."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload_and_preview(client)
|
||||||
|
r = client.get(f"/_import/{iid}/preview")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "Editeaza" in r.text
|
||||||
|
assert f"/_import/{iid}/rand/0/editare" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_editeaza_intra_in_mod_editare_form_propriu(client):
|
||||||
|
"""GET editare: randul devine un FORM separat care posteaza la .../editeaza, NU #confirm-form."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload_and_preview(client)
|
||||||
|
r = client.get(f"/_import/{iid}/rand/0/editare")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert f'hx-post="/_import/{iid}/rand/0/editeaza"' in html
|
||||||
|
# Inputurile de editare NU stau in #confirm-form (form propriu).
|
||||||
|
assert 'id="confirm-form"' not in html
|
||||||
|
assert 'name="data_prestatie"' in html and 'name="vin"' in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_salveaza_reda_doar_randul(client):
|
||||||
|
"""POST editeaza: raspuns = fragmentul randului + OOB contoare, NU tot #import-section (D-3.1)."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload_and_preview(client)
|
||||||
|
r = client.post(f"/_import/{iid}/rand/0/editeaza", data={"data_prestatie": "2026-06-10"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert 'id="preview-row-0"' in html
|
||||||
|
# OOB pe rezumat (contoare), NU re-randarea sectiunii intregi.
|
||||||
|
assert 'id="preview-rezumat"' in html and 'hx-swap-oob="true"' in html
|
||||||
|
assert 'id="import-section"' not in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_enter_in_camp_editare_nu_declanseaza_confirm(client):
|
||||||
|
"""Inputurile de editare sunt in form propriu (post editeaza); Enter salveaza randul,
|
||||||
|
nu declanseaza confirmarea ireversibila. Niciun input de editare nu e legat de #confirm-form."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload_and_preview(client)
|
||||||
|
r = client.get(f"/_import/{iid}/rand/0/editare")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
# Formul de editare posteaza la editeaza (Enter -> save), nu la /confirma.
|
||||||
|
assert f'hx-post="/_import/{iid}/rand/0/editeaza"' in html
|
||||||
|
assert "/confirma" not in html
|
||||||
|
# Inputurile NU sunt asociate explicit la #confirm-form.
|
||||||
|
assert 'form="confirm-form"' not in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_eroare_validare_pastreaza_valorile_introduse(client):
|
||||||
|
"""Data invalida -> randul ramane in editare, valoarea introdusa pastrata, mesaj pe camp."""
|
||||||
|
_seed_op1()
|
||||||
|
iid = _upload_and_preview(client)
|
||||||
|
r = client.post(f"/_import/{iid}/rand/0/editeaza", data={"data_prestatie": "data-gresita"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
# Inca in editare (form propriu prezent) cu valoarea pastrata.
|
||||||
|
assert f'hx-post="/_import/{iid}/rand/0/editeaza"' in html
|
||||||
|
assert "data-gresita" in html
|
||||||
|
# Mesaj de validare pentru data.
|
||||||
|
assert "data" in html.lower() and ("invalid" in html.lower() or "YYYY-MM-DD" in html)
|
||||||
100
tests/test_upload_slim.py
Normal file
100
tests/test_upload_slim.py
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
"""Teste US-004 (PRD 3.6): zona de upload comprimata la o bara slim.
|
||||||
|
|
||||||
|
Cand contul are deja trimiteri, upload-ul devine o bara pe un rand (eticheta + buton
|
||||||
|
+ zona de trage). First-run pastreaza hero-ul "Primul fisier?". Drag-drop + input file
|
||||||
|
+ select-foaie (multi-sheet) raman functionale.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(monkeypatch):
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "slim.db"))
|
||||||
|
monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "false")
|
||||||
|
from app.config import get_settings
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.crypto import reset_cache
|
||||||
|
reset_cache()
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
get_settings.cache_clear()
|
||||||
|
reset_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_submission() -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||||
|
"VALUES (?, 1, 'sent', ?)",
|
||||||
|
(f"k-{os.urandom(5).hex()}",
|
||||||
|
json.dumps({"vin": "WVWZZZ1KZAW000123", "prestatii": [{"cod_prestatie": "R-FRANE"}]})),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _multi_sheet_xlsx() -> bytes:
|
||||||
|
openpyxl = pytest.importorskip("openpyxl")
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws1 = wb.active
|
||||||
|
ws1.title = "Iunie"
|
||||||
|
ws1.append(["VIN", "Nr inmatriculare", "Data prestatie", "Odometru final", "Operatie"])
|
||||||
|
ws1.append(["WVWZZZ1KZAW000123", "B001TST", "2026-06-10", "123456", "OP-1"])
|
||||||
|
ws2 = wb.create_sheet("Mai")
|
||||||
|
ws2.append(["VIN", "Nr inmatriculare", "Data prestatie", "Odometru final", "Operatie"])
|
||||||
|
ws2.append(["WVWZZZ1KZAW000999", "B009TST", "2026-05-10", "55000", "OP-1"])
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_slim_pe_un_rand(client):
|
||||||
|
"""Cand contul are trimiteri, bara de upload e compacta ('Importa:'), fara hero-ul mare."""
|
||||||
|
_seed_submission()
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert "Importa:" in html, "bara slim ('Importa:') lipseste cand contul are trimiteri"
|
||||||
|
assert "Primul fisier" not in html, "hero-ul mare nu ar trebui sa apara pentru un cont cu trimiteri"
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_run_pastreaza_hero(client):
|
||||||
|
"""First-run (zero trimiteri): hero-ul 'Primul fisier?' este pastrat."""
|
||||||
|
r = client.get("/?tab=acasa")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "Primul fisier" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_pastreaza_drag_drop_si_input(client):
|
||||||
|
"""Input file ascuns + handler drag-drop raman functionale (JS refolosit)."""
|
||||||
|
r = client.get("/_import/reset")
|
||||||
|
assert r.status_code == 200
|
||||||
|
html = r.text
|
||||||
|
assert 'id="file-input"' in html
|
||||||
|
assert 'id="drop-zone"' in html
|
||||||
|
assert "dragover" in html and "drop" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_pastreaza_select_foaie(client):
|
||||||
|
"""Cazul multi-sheet inca apare: selectorul de foaie e prezent."""
|
||||||
|
data = _multi_sheet_xlsx()
|
||||||
|
r = client.post(
|
||||||
|
"/_import/upload",
|
||||||
|
files={"file": ("multi.xlsx", io.BytesIO(data), "application/octet-stream")},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert 'name="sheet_name"' in r.text
|
||||||
@@ -89,7 +89,8 @@ def test_badge_mapari(client):
|
|||||||
|
|
||||||
|
|
||||||
def test_badge_trimiteri_blocate(client):
|
def test_badge_trimiteri_blocate(client):
|
||||||
"""Cu randuri blocate, tab-ul Trimiteri poarta marcaj."""
|
"""US-003 (3.6): cu randuri blocate, marcajul de atentie apare in heading-ul
|
||||||
|
sectiunii 'Trimiterile tale' de pe Acasa (tab-ul Trimiteri a disparut)."""
|
||||||
acct = _create_account_user("bt@test.com")
|
acct = _create_account_user("bt@test.com")
|
||||||
_ins(acct, "needs_data")
|
_ins(acct, "needs_data")
|
||||||
_ins(acct, "error")
|
_ins(acct, "error")
|
||||||
@@ -97,9 +98,13 @@ def test_badge_trimiteri_blocate(client):
|
|||||||
|
|
||||||
resp = client.get("/")
|
resp = client.get("/")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
link = _tab_link(resp.text, "tab-coada")
|
html = resp.text
|
||||||
assert "tab-badge" in link
|
assert 'id="tab-coada"' not in html # tab-ul a fost eliminat
|
||||||
assert "2" in link
|
idx = html.find("Trimiterile tale")
|
||||||
|
assert idx != -1, "sectiunea Trimiteri lipseste de pe Acasa"
|
||||||
|
near = html[idx:idx + 400]
|
||||||
|
assert "tab-badge" in near
|
||||||
|
assert "2" in near
|
||||||
|
|
||||||
|
|
||||||
def test_badge_zero_ascuns(client):
|
def test_badge_zero_ascuns(client):
|
||||||
|
|||||||
@@ -100,13 +100,15 @@ def test_submissions_coloane_umane(client):
|
|||||||
|
|
||||||
|
|
||||||
def test_tab_eticheta_trimiteri(client):
|
def test_tab_eticheta_trimiteri(client):
|
||||||
"""Eticheta tab e 'Trimiteri' dar deep-link ?tab=coada ramane valid."""
|
"""US-003 (3.6): tab-ul 'Trimiteri' a fost eliminat; deep-link ?tab=coada ramane
|
||||||
|
valid (nu 404) si serveste continutul Acasa."""
|
||||||
_create_account_user("et@test.com")
|
_create_account_user("et@test.com")
|
||||||
_login(client, "et@test.com")
|
_login(client, "et@test.com")
|
||||||
resp = client.get("/?tab=coada")
|
resp = client.get("/?tab=coada")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert "Trimiteri" in resp.text
|
# Trimiterile traiesc acum pe Acasa, nu pe un tab separat.
|
||||||
assert 'id="tab-coada"' in resp.text
|
assert 'id="tab-coada"' not in resp.text
|
||||||
|
assert 'id="acasa-section"' in resp.text or 'id="import-section"' in resp.text
|
||||||
|
|
||||||
|
|
||||||
def test_motiv_needs_data_afisat(client):
|
def test_motiv_needs_data_afisat(client):
|
||||||
|
|||||||
@@ -162,36 +162,38 @@ def test_tab_activ_randat_server_side(client):
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
def test_fragmentele_inactive_lazy(client):
|
def test_fragmentele_inactive_lazy(client):
|
||||||
"""Panourile inactive nu se cer la load — fara hx-trigger=load pe fragmentele inactive."""
|
"""US-003 (3.6): Trimiterile sunt sectiune pe Acasa, nu un tab separat.
|
||||||
_create_account_user("lazy@test.com", "parolasecreta10")
|
|
||||||
|
First-run (zero trimiteri): sectiunea Trimiteri (si poll-ul ei) e suprimata.
|
||||||
|
Dupa ce contul are trimiteri, sectiunea apare pe Acasa cu poll-ul ei.
|
||||||
|
"""
|
||||||
|
acct, _ = _create_account_user("lazy@test.com", "parolasecreta10")
|
||||||
_login(client, "lazy@test.com", "parolasecreta10")
|
_login(client, "lazy@test.com", "parolasecreta10")
|
||||||
|
|
||||||
# La tab implicit (Acasa): panoul de submissions (Coada) NU trebuie sa fie in HTML
|
# First-run: fara trimiteri -> niciun poll de submissions pe Acasa.
|
||||||
# cu hx-trigger="load" (ar insemna ca se incarca automat la deschiderea paginii)
|
|
||||||
resp = client.get("/")
|
resp = client.get("/")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
|
assert "/_fragments/submissions" not in resp.text, (
|
||||||
html = resp.text
|
"Poll-ul de submissions nu trebuie sa apara cand contul nu are inca trimiteri"
|
||||||
# Verificam ca nu exista un container de submissions cu hx-trigger care include "load"
|
|
||||||
# cand Coada NU e tab-ul activ
|
|
||||||
# Pattern: hx-get="/_fragments/submissions" ... hx-trigger="load..."
|
|
||||||
# Aceasta combinatie NU trebuie sa apara cand tab-ul activ e Acasa
|
|
||||||
submissions_load_pattern = re.search(
|
|
||||||
r'hx-get="/_fragments/submissions"[^>]*hx-trigger="[^"]*load|'
|
|
||||||
r'hx-trigger="[^"]*load[^"]*"[^>]*hx-get="/_fragments/submissions"',
|
|
||||||
html
|
|
||||||
)
|
|
||||||
assert not submissions_load_pattern, (
|
|
||||||
"Fragmentul de submissions (Coada) are hx-trigger=load cand tab-ul activ nu e Coada"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# La ?tab=coada: panoul de submissions TREBUIE sa fie in HTML (randat server-side sau cu poll)
|
# Seed o trimitere -> sectiunea Trimiteri apare pe Acasa.
|
||||||
resp2 = client.get("/?tab=coada")
|
from app.db import get_connection
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||||
|
"VALUES (?, ?, 'sent', '{}')",
|
||||||
|
("k-lazy-1", acct),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
resp2 = client.get("/?tab=coada") # ?tab=coada cade pe Acasa, fara 404
|
||||||
assert resp2.status_code == 200
|
assert resp2.status_code == 200
|
||||||
html2 = resp2.text
|
assert "/_fragments/submissions" in resp2.text, (
|
||||||
# Cand Coada e activ, containerul de submissions trebuie sa existe
|
"Sectiunea Trimiteri de pe Acasa nu contine referinta la submissions"
|
||||||
assert "/_fragments/submissions" in html2 or "Coada submissions" in html2, (
|
|
||||||
"Panoul Coada nu contine referinta la submissions cand e tab-ul activ"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user