feat(ocr): Add modular store profiles with hot-reload support

## Store Profiles System
- Add ProfileRegistry for CUI-based profile lookup
- Add BaseStoreProfile with generic extraction patterns
- Implement hot-reload via POST /api/data-entry/ocr/profiles/reload

## 12 Store Profiles
- LIDL: Multi-rate TVA (A, B, C, D codes)
- OMV, SOCAR: B2B with client CUI, YYYY.MM.DD dates
- BRICK, DEDEMAN: Standard TVA, e-factura support
- KINETERRA, BEST PRINT: Non-VAT payers (returns [])
- STEPOUT MARKET: TVA 5% (books/reduced rate)
- UNLIMITED KEYS: NUMERAR payment detection
- GAMA INK, ELECTROBERING, PICTUS VELUM: Standard TVA

## Flexible TVA Patterns
- All patterns use (\d{1,2})% to accept any rate
- Supports historical (19%, 9%, 5%) and current (21%, 11%)

## Payment Methods Fix
- Fixed base.py to support multiple payments of same type
- Changed deduplication from method-only to (method, amount) tuple
- Returns separate entries for split payments

## Tools
- Add generate_store_profile.py for automatic profile generation
- Analyzes PDFs via OCR API and detects patterns

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Claude Agent
2026-01-06 23:07:07 +00:00
parent 67b0082df0
commit 099556213d
25 changed files with 3707 additions and 114 deletions

View File

@@ -0,0 +1,106 @@
# Claude Learn: Backend
**Domain**: backend
**Last updated**: 2026-01-06
**Sessions recorded**: 1
Knowledge about FastAPI, Python services, Oracle DB, and backend architecture.
---
## Patterns
### ProfileRegistry cu Hot-Reload pentru Store Profiles
**Discovered**: 2026-01-06 (feature: ocr-store-profiles)
**Description**: Sistem de înregistrare profile OCR folosind decorator `@ProfileRegistry.register` cu hot-reload via `importlib.reload()`. Permite adăugarea/modificarea profilelor fără restart server.
**Example** (`backend/modules/data_entry/services/ocr/profiles/__init__.py`):
```python
class ProfileRegistry:
_profiles: Dict[str, Type["BaseStoreProfile"]] = {}
_instances: Dict[str, "BaseStoreProfile"] = {}
@classmethod
def register(cls, profile_class):
"""Decorator to register a store profile class."""
for cui in profile_class.CUI_LIST:
cls._profiles[cls._normalize_cui(cui)] = profile_class
return profile_class
@classmethod
def reload_all(cls):
"""Hot-reload all profile modules via importlib.reload()."""
cls._instances.clear()
for module_name in cls._get_profile_module_names():
importlib.reload(sys.modules[f"backend...profiles.{module_name}"])
```
**Usage**:
```python
@ProfileRegistry.register
class LidlProfile(BaseStoreProfile):
CUI_LIST = ["22891860"]
STORE_NAME = "LIDL DISCOUNT S.R.L."
# Lookup
profile = ProfileRegistry.get_profile("22891860")
# Hot-reload (endpoint)
POST /api/data-entry/ocr/profiles/reload
```
**Tags**: registry-pattern, hot-reload, decorator, ocr, singleton
---
### Script generare cod Python din analiză PDF
**Discovered**: 2026-01-06 (feature: ocr-store-profiles)
**Description**: Script care analizează PDF-uri via OCR API, detectează pattern-uri (TVA format, date format, payment) și generează automat cod Python pentru profile noi. Include JWT auth, async polling, și verificare sintaxă.
**Example** (`scripts/generate_store_profile.py`):
```python
def analyze_tva_patterns(results: List[Dict]) -> Dict:
"""Detectează format TVA dominant din rezultatele OCR."""
tva_formats = defaultdict(int)
for text in raw_texts:
if re.search(r'TVA\s+[A-D]\s+\d{1,2}', text_upper):
tva_formats["lidl_multi_rate"] += 1
if re.search(r'BAZA\s+TVA', text_upper):
tva_formats["table"] += 1
return {"dominant_format": max(tva_formats, key=tva_formats.get)}
def generate_profile_code(store_name, cui, tva_analysis, ...):
"""Generează cod Python pentru clasa de profil."""
# Template-based generation cu OCR error variants
```
**Usage**:
```bash
# Dry-run pentru preview
python scripts/generate_store_profile.py \
--name "Magazin Nou" --cui "12345678" \
--receipts "docs/data-entry/MagazinNou*.pdf" --dry-run
# Generează și salvează
python scripts/generate_store_profile.py \
--name "Magazin Nou" --cui "12345678" \
--receipts "docs/data-entry/MagazinNou*.pdf" \
--output backend/.../profiles/magazin_nou.py
```
**Tags**: code-generation, ocr, automation, cli-tool
---
## Gotchas
_(None recorded yet)_
---
## Statistics
- **Total Patterns**: 2
- **Total Gotchas**: 0
- **Last Session**: 2026-01-06
- **Sessions Recorded**: 1