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:
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):
|
||||
"""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")
|
||||
_ins(acct, "needs_data")
|
||||
_ins(acct, "error")
|
||||
@@ -97,9 +98,13 @@ def test_badge_trimiteri_blocate(client):
|
||||
|
||||
resp = client.get("/")
|
||||
assert resp.status_code == 200
|
||||
link = _tab_link(resp.text, "tab-coada")
|
||||
assert "tab-badge" in link
|
||||
assert "2" in link
|
||||
html = resp.text
|
||||
assert 'id="tab-coada"' not in html # tab-ul a fost eliminat
|
||||
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):
|
||||
|
||||
@@ -100,13 +100,15 @@ def test_submissions_coloane_umane(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")
|
||||
_login(client, "et@test.com")
|
||||
resp = client.get("/?tab=coada")
|
||||
assert resp.status_code == 200
|
||||
assert "Trimiteri" in resp.text
|
||||
assert 'id="tab-coada"' in resp.text
|
||||
# Trimiterile traiesc acum pe Acasa, nu pe un tab separat.
|
||||
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):
|
||||
|
||||
@@ -162,36 +162,38 @@ def test_tab_activ_randat_server_side(client):
|
||||
# ============================================================
|
||||
|
||||
def test_fragmentele_inactive_lazy(client):
|
||||
"""Panourile inactive nu se cer la load — fara hx-trigger=load pe fragmentele inactive."""
|
||||
_create_account_user("lazy@test.com", "parolasecreta10")
|
||||
"""US-003 (3.6): Trimiterile sunt sectiune pe Acasa, nu un tab separat.
|
||||
|
||||
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")
|
||||
|
||||
# La tab implicit (Acasa): panoul de submissions (Coada) NU trebuie sa fie in HTML
|
||||
# cu hx-trigger="load" (ar insemna ca se incarca automat la deschiderea paginii)
|
||||
# First-run: fara trimiteri -> niciun poll de submissions pe Acasa.
|
||||
resp = client.get("/")
|
||||
assert resp.status_code == 200
|
||||
|
||||
html = resp.text
|
||||
# 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"
|
||||
assert "/_fragments/submissions" not in resp.text, (
|
||||
"Poll-ul de submissions nu trebuie sa apara cand contul nu are inca trimiteri"
|
||||
)
|
||||
|
||||
# La ?tab=coada: panoul de submissions TREBUIE sa fie in HTML (randat server-side sau cu poll)
|
||||
resp2 = client.get("/?tab=coada")
|
||||
# Seed o trimitere -> sectiunea Trimiteri apare pe Acasa.
|
||||
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
|
||||
html2 = resp2.text
|
||||
# Cand Coada e activ, containerul de submissions trebuie sa existe
|
||||
assert "/_fragments/submissions" in html2 or "Coada submissions" in html2, (
|
||||
"Panoul Coada nu contine referinta la submissions cand e tab-ul activ"
|
||||
assert "/_fragments/submissions" in resp2.text, (
|
||||
"Sectiunea Trimiteri de pe Acasa nu contine referinta la submissions"
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user