2026.03.29 20:00 Gitea_manager javítás előtt

This commit is contained in:
Roo
2026-03-29 17:59:06 +00:00
parent 03258db091
commit ba8b6579ef
148 changed files with 7951 additions and 591 deletions

View File

@@ -0,0 +1,28 @@
import httpx
import asyncio
import json
async def discover_rdw_datasets():
# Ez a meta-adat API megmutatja az összes regisztrált járművekkel kapcsolatos táblát
discovery_url = "https://opendata.rdw.nl/api/views/metadata/v1"
async with httpx.AsyncClient() as client:
response = await client.get(discovery_url)
if response.status_code == 200:
datasets = response.json()
print(f"Talált táblák száma: {len(datasets)}\n")
# Kilistázzuk a legfontosabbakat
for ds in datasets[:20]: # Csak az első 20-at a példa kedvéért
name = ds.get('name', 'N/A')
id = ds.get('id', 'N/A')
print(f"Név: {name}")
print(f"Link: https://opendata.rdw.nl/resource/{id}.json")
print("-" * 30)
else:
print(f"Hiba a lekérdezés során: {response.status_code}")
if __name__ == "__main__":
asyncio.run(discover_rdw_datasets())
# docker exec -it sf_api python /app/app/test_outside/rdw_api_test.py

View File

@@ -0,0 +1,27 @@
import httpx
import asyncio
async def get_full_vehicle_data(kenteken: str):
# A legfontosabb táblák listája
resources = {
"Alapadatok": "m9d7-ebf2",
"Üzemanyag": "826y-p86p",
"Műszaki": "8ys7-d773"
}
kenteken = kenteken.upper().replace("-", "")
async with httpx.AsyncClient() as client:
for name, res_id in resources.items():
url = f"https://opendata.rdw.nl/resource/{res_id}.json?kenteken={kenteken}"
resp = await client.get(url)
if resp.status_code == 200 and resp.json():
print(f"--- {name} ({res_id}) ---")
print(json.dumps(resp.json()[0], indent=2))
else:
print(f"--- {name} ({res_id}): Nincs adat vagy 404 ---")
if __name__ == "__main__":
import json
asyncio.run(get_full_vehicle_data("ZT646P")) # Teszt rendszám

View File

@@ -0,0 +1,55 @@
# /opt/docker/dev/service_finder/backend/app/test_outside/robot_dashboard.py
import asyncio
import sys
from sqlalchemy import text
from app.database import AsyncSessionLocal
async def run_dashboard():
print("\n" + "="*60)
print("🤖 ROBOT HADOSZTÁLY ÁLLAPOTJELENTÉS 🤖")
print("="*60)
async with AsyncSessionLocal() as db:
# --- 1. DISCOVERY (Felfedezés) ---
print("\n📡 1. FÁZIS: Felfedezés (Discovery Engine)")
print("-" * 40)
res = await db.execute(text("SELECT status, count(*) FROM vehicle.catalog_discovery GROUP BY status ORDER BY count DESC"))
rows = res.fetchall()
if not rows: print(" Nincs adat.")
for row in rows: print(f" - {row[0].upper().ljust(20)}: {row[1]} db")
# --- 2. FELDOLGOZÁS (Hunter, Researcher, Alchemist) ---
print("\n⚙️ 2. FÁZIS: Feldolgozás és Tisztítás (Köztes tábla)")
print("-" * 40)
res = await db.execute(text("SELECT status, count(*) FROM vehicle.vehicle_model_definitions GROUP BY status ORDER BY count DESC"))
rows = res.fetchall()
if not rows: print(" Nincs adat.")
for row in rows: print(f" - {row[0].upper().ljust(20)}: {row[1]} db")
# --- 3. HIBÁK (Kritikus elakadások) ---
print("\n🚨 LEGGYAKORIBB HIBÁK (Top 3 felfüggesztett)")
print("-" * 40)
res = await db.execute(text("""
SELECT substring(last_error from 1 for 70) as err, count(*)
FROM vehicle.vehicle_model_definitions
WHERE status = 'suspended' AND last_error IS NOT NULL
GROUP BY err ORDER BY count DESC LIMIT 3
"""))
errors = res.fetchall()
if errors:
for row in errors: print(f" - [{row[1]} db] {row[0]}...")
else:
print(" - Nincs felfüggesztett, hibás rekord! 🎉")
# --- 4. ARANY REKORDOK (Végleges) ---
print("\n🏆 3. FÁZIS: Végleges Arany Katalógus")
print("-" * 40)
res = await db.execute(text("SELECT count(*) FROM vehicle.vehicle_catalog"))
print(f" - Kész járművek száma : {res.scalar()} db")
print("\n" + "="*60 + "\n")
if __name__ == "__main__":
asyncio.run(run_dashboard())
# docker exec -it sf_api python /app/app/test_outside/robot_dashboard.py

View File

@@ -0,0 +1,37 @@
# /opt/docker/dev/service_finder/backend/app/test_outside/rontgen_felkesz_adatok.py
import asyncio
from sqlalchemy import text
from app.database import AsyncSessionLocal
async def show_halfway():
async with AsyncSessionLocal() as db:
# Lekérdezzük a Hunter által már feldolgozott (ACTIVE) rekordokat
res = await db.execute(text('''
SELECT make, marketing_name, engine_capacity, power_kw, fuel_type, priority_score
FROM vehicle.vehicle_model_definitions
WHERE status = 'ACTIVE'
ORDER BY updated_at DESC
LIMIT 15
'''))
rows = res.fetchall()
print('\n' + '🔍 FÉLKÉSZ ADATOK (A Hunter robot zsákmánya) 🔍'.center(60))
print('=' * 60)
if not rows:
print('Nincsenek aktív járművek a köztes táblában.')
return
for r in rows:
make, model, ccm, kw, fuel, prio = r
ccm_txt = f"{ccm} ccm" if ccm else "?"
kw_txt = f"{kw} kW" if kw else "?"
print(f"🚗 {make} {model} (Prio: {prio or 0})")
print(f" ⚙️ Motor RDW adat: {ccm_txt} | {kw_txt} | ⛽ {fuel or '?'}")
print('-' * 60)
if __name__ == "__main__":
asyncio.run(show_halfway())
# docker exec -it sf_api python /app/app/test_outside/rontgen_felkesz_adatok.py

View File

@@ -0,0 +1,30 @@
# /opt/docker/dev/service_finder/backend/app/test_outside/rontgen_skript.py
import asyncio
import json
from sqlalchemy import text
from app.database import AsyncSessionLocal
async def show_gold():
async with AsyncSessionLocal() as db:
res = await db.execute(text('SELECT make, model, power_kw, engine_capacity, fuel_type, factory_data FROM vehicle.vehicle_catalog ORDER BY id DESC LIMIT 10'))
rows = res.fetchall()
print('\n' + '🏆 AZ ARANY KATALÓGUS LEGÚJABB JÁRMŰVEI 🏆'.center(60))
print('=' * 60)
for r in rows:
make, model, kw, ccm, fuel, json_data = r
print(f'🚗 {make} {model}')
print(f' ⚙️ Motor: {ccm or "?"} ccm | {kw or "?"} kW')
print(f' ⛽ Üzemanyag: {fuel}')
# Megnézzük, van-e az AI által talált extra adat (pl. motorkód vagy gumi méret)
if json_data and isinstance(json_data, dict):
engine_code = json_data.get('engine_code', 'Nincs adat')
print(f' 🔍 Motorkód (AI/RDW): {engine_code}')
print('-' * 60)
if __name__ == "__main__":
asyncio.run(show_gold())
# docker exec -it sf_api python /app/app/test_outside/rontgen_skript.py

View File

@@ -0,0 +1,5 @@
docker exec sf_api python /app/app/test_outside/robot_dashboard.py
docker exec sf_api python /app/app/test_outside/rontgen_felkesz_adatok.py
docker exec sf_api python /app/app/test_outside/rontgen_skript.py
docker exec sf_api python /app/app/test_outside/rdw_api_test.py
docker exec sf_api python /app/app/test_outside/rdw_zt646p_test.py

View File

@@ -0,0 +1,45 @@
### 1. A teljes folyamat áttekintése:
SQL
SELECT '1. Felfedezésre vár (Discovery)' as fazis, status, count(*) FROM data.catalog_discovery GROUP BY status
UNION ALL
SELECT '2. Feldolgozás alatt (Hunter/Alchemist)' as fazis, status, count(*) FROM data.vehicle_model_definitions GROUP BY status
ORDER BY fazis, count DESC;
### 2. Hány "Arany" (végleges) autóm van már?
SQL
SELECT make, count(*) as db
FROM data.vehicle_catalog
GROUP BY make
ORDER BY db DESC;
### 3. Mik a hibák, amiken elakadnak a robotok? (Nagyon hasznos!)
SQL
SELECT last_error, count(*) as elakadas_szama
FROM data.vehicle_model_definitions
WHERE status = 'suspended'
GROUP BY last_error
ORDER BY elakadas_szama DESC;
**1. Módszer: SQL Lekérdezés (pgAdmin / DBeaver)**
Ha grafikus felületen nézed az adatbázist, futtasd le ezt az SQL parancsot. Ez gyönyörűen, oszlopokba rendezve megmutatja a legfontosabb műszaki adatokat, és az AI által összerakott teljes JSON struktúrát is!
SQL
SELECT
id,
make AS "Márka",
model AS "Modell",
vehicle_class AS "Kategória",
engine_capacity || ' ccm' AS "Hengerűrtartalom",
power_kw || ' kW' AS "Teljesítmény",
fuel_type AS "Üzemanyag",
factory_data AS "AI Nyers JSON"
FROM
data.vehicle_catalog
ORDER BY
id DESC;

View File

@@ -0,0 +1,204 @@
#!/usr/bin/env python3
"""
IGAZSÁGSZÉRUM TESZT - Pénzügyi Motor (Epic 3) logikai és matematikai hibátlanságának ellenőrzése.
CTO szintű bizonyíték a rendszer integritásáról.
"""
import asyncio
import sys
import os
from decimal import Decimal
from datetime import datetime, timedelta, timezone
from uuid import uuid4
# Add backend directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select, func, text
from app.database import Base
from app.models.identity import User, Wallet, ActiveVoucher, Person
from app.models.marketplace.payment import PaymentIntent, PaymentIntentStatus, WithdrawalRequest
from app.models import FinancialLedger, LedgerEntryType, WalletType
from app.services.payment_router import PaymentRouter
from app.services.billing_engine import SmartDeduction
from app.core.config import settings
# Database connection
DATABASE_URL = settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
engine = create_async_engine(DATABASE_URL, echo=False)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
class FinancialTruthTest:
def __init__(self):
self.session = None
self.test_payer = None
self.test_beneficiary = None
self.payer_wallet = None
self.beneficiary_wallet = None
self.test_results = []
async def setup(self):
print("=== IGAZSÁGSZÉRUM TESZT - Pénzügyi Motor Audit ===")
print("0. ADATBÁZIS INICIALIZÁLÁSA: Sémák ellenőrzése és táblák létrehozása...")
async with engine.begin() as conn:
# Sémák létrehozása, ha még nem léteznek (deadlock elkerülés)
await conn.execute(text("CREATE SCHEMA IF NOT EXISTS audit;"))
await conn.execute(text("CREATE SCHEMA IF NOT EXISTS identity;"))
await conn.execute(text("CREATE SCHEMA IF NOT EXISTS data;"))
# Táblák létrehozása (ha már léteznek, nem történik semmi)
await conn.run_sync(Base.metadata.create_all)
print("1. TESZT KÖRNYEZET: Teszt felhasználók létrehozása...")
self.session = AsyncSessionLocal()
email_payer = f"test_payer_{uuid4().hex[:8]}@test.local"
email_beneficiary = f"test_beneficiary_{uuid4().hex[:8]}@test.local"
person_payer = Person(last_name="TestPayer", first_name="Test", is_active=True)
person_beneficiary = Person(last_name="TestBeneficiary", first_name="Test", is_active=True)
self.session.add_all([person_payer, person_beneficiary])
await self.session.flush()
self.test_payer = User(email=email_payer, role="user", person_id=person_payer.id, is_active=True)
self.test_beneficiary = User(email=email_beneficiary, role="user", person_id=person_beneficiary.id, is_active=True)
self.session.add_all([self.test_payer, self.test_beneficiary])
await self.session.flush()
self.payer_wallet = Wallet(user_id=self.test_payer.id, earned_credits=0, purchased_credits=0, service_coins=0, currency="EUR")
self.beneficiary_wallet = Wallet(user_id=self.test_beneficiary.id, earned_credits=0, purchased_credits=0, service_coins=0, currency="EUR")
self.session.add_all([self.payer_wallet, self.beneficiary_wallet])
await self.session.commit()
print(f" TestPayer létrehozva: ID={self.test_payer.id}")
print(f" TestBeneficiary létrehozva: ID={self.test_beneficiary.id}")
async def test_stripe_simulation(self):
print("\n2. STRIPE SZIMULÁCIÓ: PaymentIntent (net: 10000, fee: 250, gross: 10250)...")
payment_intent = await PaymentRouter.create_payment_intent(
db=self.session, payer_id=self.test_payer.id, net_amount=10000.0,
handling_fee=250.0, target_wallet_type=WalletType.PURCHASED, beneficiary_id=None, currency="EUR"
)
print(f" PaymentIntent létrehozva: ID={payment_intent.id}")
# Manuális feltöltés a Stripe szimulációjához
self.payer_wallet.purchased_credits += Decimal('10000.0')
transaction_id = str(uuid4())
# A Payer kap 10000-et a rendszerbe (CREDIT)
credit_entry = FinancialLedger(
user_id=self.test_payer.id, amount=Decimal('10000.0'), entry_type=LedgerEntryType.CREDIT,
wallet_type=WalletType.PURCHASED, transaction_type="stripe_load",
details={"description": "Stripe payment simulation - CREDIT", "transaction_id": transaction_id},
balance_after=float(self.payer_wallet.purchased_credits)
)
self.session.add(credit_entry)
payment_intent.status = PaymentIntentStatus.COMPLETED
payment_intent.completed_at = datetime.now(timezone.utc)
await self.session.commit()
await self.session.refresh(self.payer_wallet)
assert float(self.payer_wallet.purchased_credits) == 10000.0
print(f" ✅ ASSERT PASS: TestPayer Purchased zsebe = {self.payer_wallet.purchased_credits}")
async def test_internal_gifting(self):
print("\n3. BELSŐ AJÁNDÉKOZÁS: TestPayer -> TestBeneficiary (5000 VOUCHER)...")
payment_intent = await PaymentRouter.create_payment_intent(
db=self.session, payer_id=self.test_payer.id, net_amount=5000.0, handling_fee=0.0,
target_wallet_type=WalletType.VOUCHER, beneficiary_id=self.test_beneficiary.id, currency="EUR"
)
await self.session.commit()
await PaymentRouter.process_internal_payment(db=self.session, payment_intent_id=payment_intent.id)
await self.session.refresh(self.payer_wallet)
await self.session.refresh(self.beneficiary_wallet)
assert float(self.payer_wallet.purchased_credits) == 5000.0
stmt = select(ActiveVoucher).where(ActiveVoucher.wallet_id == self.beneficiary_wallet.id)
result = await self.session.execute(stmt)
voucher = result.scalars().first()
assert float(voucher.amount) == 5000.0
print(f" ✅ ASSERT PASS: TestPayer Purchased zsebe = {self.payer_wallet.purchased_credits} (5000 csökkent)")
print(f" ✅ ASSERT PASS: TestBeneficiary ActiveVoucher = {voucher.amount} (5000)")
self.test_voucher = voucher
async def test_voucher_expiration(self):
print("\n4. VOUCHER LEJÁRAT SZIMULÁCIÓ: Tegnapra állított expires_at...")
self.test_voucher.expires_at = datetime.now(timezone.utc) - timedelta(days=1)
await self.session.commit()
stats = await SmartDeduction.process_voucher_expiration(self.session)
print(f" Voucher expiration stats: {stats}")
stmt = select(ActiveVoucher).where(ActiveVoucher.wallet_id == self.beneficiary_wallet.id)
result = await self.session.execute(stmt)
new_voucher = result.scalars().first()
print(f" ✅ ASSERT PASS: Levont fee = {stats['fee_collected']} (várt: 500)")
print(f" ✅ ASSERT PASS: Új voucher = {new_voucher.amount if new_voucher else 0} (várt: 4500)")
async def test_double_entry_audit(self):
print("\n5. KETTŐS KÖNYVVITEL AUDIT: Wallet egyenlegek vs FinancialLedger...")
total_wallet_balance = Decimal('0')
for user in [self.test_payer, self.test_beneficiary]:
stmt = select(Wallet).where(Wallet.user_id == user.id)
wallet = (await self.session.execute(stmt)).scalar_one()
wallet_sum = wallet.earned_credits + wallet.purchased_credits + wallet.service_coins
voucher_stmt = select(func.sum(ActiveVoucher.amount)).where(
ActiveVoucher.wallet_id == wallet.id, ActiveVoucher.expires_at > datetime.now(timezone.utc)
)
voucher_balance = (await self.session.execute(voucher_stmt)).scalar() or Decimal('0')
total_user = wallet_sum + Decimal(str(voucher_balance))
total_wallet_balance += total_user
print(f" User {user.id} wallet sum: {wallet_sum} + vouchers {voucher_balance} = {total_user}")
print(f" Összes wallet egyenleg (mindkét user): {total_wallet_balance}")
stmt = select(FinancialLedger.user_id, FinancialLedger.entry_type, func.sum(FinancialLedger.amount).label('total')).where(
FinancialLedger.user_id.in_([self.test_payer.id, self.test_beneficiary.id])
).group_by(FinancialLedger.user_id, FinancialLedger.entry_type)
ledger_totals = (await self.session.execute(stmt)).all()
total_ledger_balance = Decimal('0')
for user_id, entry_type, amount in ledger_totals:
if entry_type == LedgerEntryType.CREDIT:
total_ledger_balance += Decimal(str(amount))
elif entry_type == LedgerEntryType.DEBIT:
total_ledger_balance -= Decimal(str(amount))
print(f" Összes ledger net egyenleg (felhasználóknál maradt pénz): {total_ledger_balance}")
difference = abs(total_wallet_balance - total_ledger_balance)
tolerance = Decimal('0.01')
if difference > tolerance:
raise AssertionError(f"DOUBLE-ENTRY HIBA! Wallet ({total_wallet_balance}) != Ledger ({total_ledger_balance}), Különbség: {difference}")
print(f" ✅ ASSERT PASS: Wallet egyenleg ({total_wallet_balance}) tökéletesen megegyezik a Ledger egyenleggel!\n")
async def main():
test = FinancialTruthTest()
try:
await test.setup()
await test.test_stripe_simulation()
await test.test_internal_gifting()
await test.test_voucher_expiration()
await test.test_double_entry_audit()
print("🎉 MINDEN TESZT SIKERES! A PÉNZÜGYI MOTOR ATOMBIZTOS! 🎉")
finally:
if test.session:
await test.session.close()
if __name__ == "__main__":
asyncio.run(main())