feat(T3): validare completa prezentari + 29 teste
- app/validation.py: reguli de continut (VIN ^[A-HJ-NPR-Z0-9]{17}$ fara O/I/Q,
nrInm ^[A-Z0-9]{1,10}$, dataPrestatie ∈ [2024-12-01, azi] TZ Bucuresti,
R-ODO/I-ODO -> odometruInitial obligatoriu, odometruInitial<=odometruFinal,
odometruFinal numeric, prestatii nevide, b64Image base64 valid)
- erori structurate {field, message} (aceeasi forma ca raspunsul RAR), fara exceptii
- modele Pydantic: normalizare strip/upper pe vin/nrInm/coduri
- router /v1/prezentari: validare inainte de enqueue; esec continut -> needs_data
(tinut, vizibil in dashboard cu motiv), NU 422; JSON malformat -> 422 (shape)
- tests/: 29 teste (per regula + rutare API + idempotenta)
Verify: pytest 29 passed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,7 @@ from fastapi import APIRouter, HTTPException
|
||||
from ...db import get_connection
|
||||
from ...idempotency import idempotency_key
|
||||
from ...models import PrezentareRequest, PrezentariResponse, SubmissionResult
|
||||
from ...validation import validate_prezentare
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["v1"])
|
||||
|
||||
@@ -26,8 +27,9 @@ router = APIRouter(prefix="/v1", tags=["v1"])
|
||||
def create_prezentari(req: PrezentareRequest) -> PrezentariResponse:
|
||||
"""Enqueue una/mai multe prezentari. Idempotent: continut identic -> acelasi submission.
|
||||
|
||||
TODO(T3): validare Pydantic completa inainte de enqueue (VIN/data/nrInm),
|
||||
ruteaza needs_data/needs_mapping.
|
||||
Validarea de continut (T3, app.validation) ruleaza inainte de enqueue:
|
||||
esecurile NU resping cererea, ci enqueue-aza cu status `needs_data` + motiv
|
||||
(plan.md sect. 3). JSON malformat -> 422 din Pydantic (validare de shape).
|
||||
TODO(auth): rezolva account_id din API key (acum None).
|
||||
Nota: rar_credentials NU se persista (zero-storage) — worker-ul le va primi
|
||||
pe alt canal (T2); in schelet enqueue-ul doar stocheaza prezentarea.
|
||||
@@ -53,12 +55,20 @@ def create_prezentari(req: PrezentareRequest) -> PrezentariResponse:
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
# T3: validare de continut -> queued daca e curat, altfel needs_data + motiv.
|
||||
errors = validate_prezentare(content)
|
||||
if errors:
|
||||
status, rar_error = "needs_data", json.dumps(errors, ensure_ascii=False)
|
||||
else:
|
||||
status, rar_error = "queued", None
|
||||
|
||||
cur = conn.execute(
|
||||
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
|
||||
"VALUES (?, ?, 'queued', ?)",
|
||||
(key, account_id, json.dumps(content, ensure_ascii=False)),
|
||||
"INSERT INTO submissions (idempotency_key, account_id, status, payload_json, rar_error) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
(key, account_id, status, json.dumps(content, ensure_ascii=False), rar_error),
|
||||
)
|
||||
results.append(SubmissionResult(submission_id=int(cur.lastrowid), status="queued"))
|
||||
results.append(SubmissionResult(submission_id=int(cur.lastrowid), status=status))
|
||||
finally:
|
||||
conn.close()
|
||||
return PrezentariResponse(results=results)
|
||||
|
||||
@@ -8,7 +8,7 @@ obligatoriu, odometruInitial <= odometruFinal, normalizare strip/upper) este
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class RarCredentials(BaseModel):
|
||||
@@ -21,13 +21,24 @@ class RarCredentials(BaseModel):
|
||||
class PrestatieItem(BaseModel):
|
||||
cod_prestatie: str = Field(..., description="cod din nomenclator RAR, ex. OE-1")
|
||||
|
||||
@field_validator("cod_prestatie")
|
||||
@classmethod
|
||||
def _norm_cod(cls, v: str) -> str:
|
||||
return v.strip().upper()
|
||||
|
||||
|
||||
class PrezentareIn(BaseModel):
|
||||
"""O prezentare de declarat la RAR (inainte de validarea T3)."""
|
||||
"""O prezentare de declarat la RAR.
|
||||
|
||||
Pydantic doar NORMALIZEAZA aici (strip/upper pe vin/nrInm). Validarea de
|
||||
continut (regex VIN, interval data, R-ODO/I-ODO, odometru) e in
|
||||
app.validation.validate_prezentare si NU resping cererea — marcheaza
|
||||
`needs_data` (plan.md sect. 3).
|
||||
"""
|
||||
|
||||
vin: str
|
||||
nr_inmatriculare: str
|
||||
data_prestatie: str # YYYY-MM-DD; validare interval = T3
|
||||
data_prestatie: str # YYYY-MM-DD
|
||||
odometru_final: str # string per contract
|
||||
odometru_initial: str | None = None
|
||||
prestatii: list[PrestatieItem]
|
||||
@@ -35,6 +46,16 @@ class PrezentareIn(BaseModel):
|
||||
obs: str | None = None
|
||||
b64_image: str | None = None
|
||||
|
||||
@field_validator("vin", "nr_inmatriculare")
|
||||
@classmethod
|
||||
def _norm_upper(cls, v: str) -> str:
|
||||
return v.strip().upper()
|
||||
|
||||
@field_validator("data_prestatie", "odometru_final")
|
||||
@classmethod
|
||||
def _norm_strip(cls, v: str) -> str:
|
||||
return v.strip()
|
||||
|
||||
|
||||
class PrezentareRequest(BaseModel):
|
||||
"""Body pentru POST /v1/prezentari — una sau mai multe prezentari + creds RAR."""
|
||||
|
||||
136
app/validation.py
Normal file
136
app/validation.py
Normal file
@@ -0,0 +1,136 @@
|
||||
"""Validare de domeniu pentru prezentari (T3).
|
||||
|
||||
Replica regulile RAR (docs/api-rar-contract.md sect. "Reguli de validare") ÎNAINTE
|
||||
de enqueue, ca sa nu primim 4xx de la RAR. Spre deosebire de validarea de SHAPE
|
||||
(Pydantic, da 422 la JSON malformat), aceasta e validare de CONTINUT: esecurile NU
|
||||
resping cererea, ci marcheaza submission-ul `needs_data` (plan.md sect. 3 — masina de
|
||||
stari + failure registry). Asa apar in dashboard cu motiv, corectabile.
|
||||
|
||||
Functiile sunt pure (dict -> listă erori), unit-testabile fara DB/HTTP.
|
||||
Erorile au forma {field, message} — aceeasi ca raspunsul de eroare RAR.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
from datetime import date
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
# VIN: 17 caractere, majuscule, fara O/I/Q (plan §2 + contract).
|
||||
VIN_RE = re.compile(r"^[A-HJ-NPR-Z0-9]{17}$")
|
||||
# Numar inmatriculare: max 10, litere + cifre majuscule.
|
||||
NRINM_RE = re.compile(r"^[A-Z0-9]{1,10}$")
|
||||
# Coduri care fac odometruInitial obligatoriu.
|
||||
ODOMETER_CODES = {"R-ODO", "I-ODO"}
|
||||
# Interval dataPrestatie.
|
||||
MIN_DATA_PRESTATIE = date(2024, 12, 1)
|
||||
TZ_BUCURESTI = ZoneInfo("Europe/Bucharest")
|
||||
|
||||
|
||||
def _norm(value: object) -> str:
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
|
||||
def _codes(prestatii: list | None) -> list[str]:
|
||||
out: list[str] = []
|
||||
for p in prestatii or []:
|
||||
cod = p.get("cod_prestatie") if isinstance(p, dict) else getattr(p, "cod_prestatie", None)
|
||||
if cod:
|
||||
out.append(str(cod).strip().upper())
|
||||
return out
|
||||
|
||||
|
||||
def _parse_int(value: object) -> int | None:
|
||||
s = str(value or "").strip()
|
||||
if s.isdigit():
|
||||
return int(s)
|
||||
return None
|
||||
|
||||
|
||||
def today_bucuresti() -> date:
|
||||
from datetime import datetime
|
||||
|
||||
return datetime.now(TZ_BUCURESTI).date()
|
||||
|
||||
|
||||
def validate_prezentare(content: dict) -> list[dict]:
|
||||
"""Intoarce lista erorilor de continut [{field, message}]. Goala = valid.
|
||||
|
||||
`content` = PrezentareIn.model_dump() (campuri snake_case interne).
|
||||
"""
|
||||
errors: list[dict] = []
|
||||
|
||||
# --- VIN ---
|
||||
vin = _norm(content.get("vin"))
|
||||
if not VIN_RE.match(vin):
|
||||
errors.append({
|
||||
"field": "vin",
|
||||
"message": "VIN trebuie sa aiba exact 17 caractere majuscule, fara spatii/caractere speciale si fara O, I, Q.",
|
||||
})
|
||||
|
||||
# --- nrInmatriculare ---
|
||||
nrinm = _norm(content.get("nr_inmatriculare"))
|
||||
if not NRINM_RE.match(nrinm):
|
||||
errors.append({
|
||||
"field": "nr_inmatriculare",
|
||||
"message": "Numarul de inmatriculare trebuie sa aiba max 10 caractere, doar litere si cifre majuscule.",
|
||||
})
|
||||
|
||||
# --- dataPrestatie ∈ [2024-12-01, azi] TZ Bucuresti ---
|
||||
raw_data = str(content.get("data_prestatie") or "").strip()
|
||||
try:
|
||||
d = date.fromisoformat(raw_data)
|
||||
except ValueError:
|
||||
errors.append({"field": "data_prestatie", "message": "Format data invalid; foloseste YYYY-MM-DD."})
|
||||
d = None
|
||||
if d is not None:
|
||||
if d < MIN_DATA_PRESTATIE:
|
||||
errors.append({"field": "data_prestatie", "message": "Data prestatiei nu poate fi anterioara datei de 01.12.2024."})
|
||||
elif d > today_bucuresti():
|
||||
errors.append({"field": "data_prestatie", "message": "Data prestatiei nu poate fi in viitor."})
|
||||
|
||||
# --- odometruFinal (string numeric) ---
|
||||
odo_final = _parse_int(content.get("odometru_final"))
|
||||
if odo_final is None:
|
||||
errors.append({"field": "odometru_final", "message": "odometruFinal trebuie sa fie un numar intreg (ca string)."})
|
||||
|
||||
# --- odometruInitial: obligatoriu daca prestatii ∋ R-ODO/I-ODO; <= odometruFinal ---
|
||||
codes = _codes(content.get("prestatii"))
|
||||
needs_initial = bool(set(codes) & ODOMETER_CODES)
|
||||
raw_initial = content.get("odometru_initial")
|
||||
has_initial = str(raw_initial or "").strip() != ""
|
||||
if needs_initial and not has_initial:
|
||||
errors.append({
|
||||
"field": "odometru_initial",
|
||||
"message": "odometruInitial este obligatoriu cand prestatiile contin R-ODO sau I-ODO.",
|
||||
})
|
||||
if has_initial:
|
||||
odo_initial = _parse_int(raw_initial)
|
||||
if odo_initial is None:
|
||||
errors.append({"field": "odometru_initial", "message": "odometruInitial trebuie sa fie un numar intreg."})
|
||||
elif odo_final is not None and odo_initial > odo_final:
|
||||
errors.append({"field": "odometru_initial", "message": "odometruInitial trebuie sa fie <= odometruFinal."})
|
||||
|
||||
# --- prestatii nevide ---
|
||||
if not codes:
|
||||
errors.append({"field": "prestatii", "message": "Lista de prestatii nu poate fi goala."})
|
||||
|
||||
# --- b64Image: optional, dar daca e prezent trebuie base64 valid ---
|
||||
b64 = content.get("b64_image")
|
||||
if b64:
|
||||
if not _is_valid_base64(str(b64)):
|
||||
errors.append({"field": "b64_image", "message": "b64Image nu este base64 valid."})
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def _is_valid_base64(value: str) -> bool:
|
||||
s = value.strip()
|
||||
if not s:
|
||||
return False
|
||||
try:
|
||||
base64.b64decode(s, validate=True)
|
||||
return True
|
||||
except (ValueError, base64.binascii.Error): # type: ignore[attr-defined]
|
||||
return False
|
||||
Reference in New Issue
Block a user