Files
service-finder/backend/app/tests_internal/seeds/seed_data.py
2026-03-13 10:22:41 +00:00

156 lines
7.2 KiB
Python
Executable File
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# /opt/docker/dev/service_finder/backend/app/seed_data.py
import asyncio
import uuid
from datetime import datetime, timedelta, timezone
from sqlalchemy import text, select
from app.database import AsyncSessionLocal
from app.models.identity import User, Person, UserRole
from app.models.social import ServiceProvider, Vote, ModerationStatus, Competition
from app.services.social_service import SocialService
from app.core.security import get_password_hash
async def run_simulation():
async with AsyncSessionLocal() as db:
print("--- 1. TAKARÍTÁS (MB2.0 Séma-tisztítás) ---")
# Szigorú sorrend a kényszerek miatt (Cascade)
# Ellenőrizzük, mely táblák léteznek
tables_to_check = [
("identity.users", "users"),
("identity.persons", "persons"),
("marketplace.service_providers", "service_providers"),
("marketplace.votes", "votes"),
("system.competitions", "competitions")
]
existing_tables = []
for full_name, table_name in tables_to_check:
try:
result = await db.execute(text(f"SELECT 1 FROM information_schema.tables WHERE table_schema = '{full_name.split('.')[0]}' AND table_name = '{table_name}'"))
if result.scalar() == 1:
existing_tables.append(full_name)
else:
print(f"⚠️ {full_name} tábla nem létezik, kihagyva a törlést")
except Exception:
print(f"⚠️ {full_name} tábla nem létezik, kihagyva a törlést")
if existing_tables:
tables_str = ", ".join(existing_tables)
await db.execute(text(f"TRUNCATE {tables_str} RESTART IDENTITY CASCADE"))
await db.commit()
else:
print(" Nincs törlendő tábla")
print("\n--- 2. SZEREPLŐK LÉTREHOZÁSA (Person + User) ---")
users_to_create = [
("admin@test.com", "Adminisztrátor", UserRole.superadmin),
("good@test.com", "Rendes Srác", UserRole.user),
("bad@test.com", "Spammer Aladár", UserRole.user),
("voter@test.com", "Szavazó Gép", UserRole.user)
]
created_users = {}
for email, name, role in users_to_create:
name_parts = name.split()
first_name = name_parts[0] if name_parts else "Unknown"
last_name = name_parts[1] if len(name_parts) > 1 else "User"
p = Person(id_uuid=uuid.uuid4(), first_name=first_name, last_name=last_name, is_active=True)
db.add(p)
await db.flush()
u = User(
email=email,
hashed_password=get_password_hash("test1234"),
person_id=p.id,
role=role,
is_active=True
)
db.add(u)
await db.flush()
created_users[email] = u
await db.commit()
print("\n--- 3. VERSENY INDÍTÁSA ---")
# Ellenőrizzük, hogy a competitions tábla létezik-e
try:
result = await db.execute(text("SELECT 1 FROM information_schema.tables WHERE table_schema = 'system' AND table_name = 'competitions'"))
if result.scalar() == 1:
race = Competition(
name="Téli Szervizvadászat",
start_date=datetime.now(timezone.utc) - timedelta(days=1),
end_date=datetime.now(timezone.utc) + timedelta(days=30),
is_active=True
)
db.add(race)
await db.commit()
print("✅ Verseny létrehozva")
else:
print("⚠️ system.competitions tábla nem létezik, kihagyva a verseny létrehozását")
except Exception as e:
print(f"⚠️ Hiba a competitions tábla ellenőrzése közben: {e}, kihagyva a verseny létrehozását")
# Szereplők kiemelése a szimulációhoz
good_user = created_users["good@test.com"]
bad_user = created_users["bad@test.com"]
voter = created_users["voter@test.com"]
# Ellenőrizzük, hogy a szükséges táblák léteznek-e a szociális szimulációhoz
try:
result = await db.execute(text("SELECT 1 FROM information_schema.tables WHERE table_schema = 'marketplace' AND table_name = 'service_providers'"))
service_providers_exists = result.scalar() == 1
result = await db.execute(text("SELECT 1 FROM information_schema.tables WHERE table_schema = 'marketplace' AND table_name = 'votes'"))
votes_exists = result.scalar() == 1
if service_providers_exists and votes_exists:
print("\n--- 4. SZCENÁRIÓ A: POZITÍV VALIDÁCIÓ ---")
# Rendes srác beküld egy szervizt
shop = ServiceProvider(
name="Profi Gumis",
address="Budapest, Váci út 10.",
added_by_user_id=good_user.id,
status=ModerationStatus.pending
)
db.add(shop)
await db.flush()
# Szavazatok szimulálása (SocialService használatával a pontszámítás miatt)
print(f"Szavazás a '{shop.name}'-re...")
# Szimulálunk 5 pozitív szavazatot különböző "virtuális" szavazóktól
for _ in range(5):
await SocialService.vote_for_provider(db, voter.id, shop.id, 1)
await db.refresh(good_user)
print(f"Jó felhasználó hírneve: {good_user.reputation_score}")
print("\n--- 5. SZCENÁRIÓ B: AUTO-BAN (SPAM SZŰRÉS) ---")
fake_shop = ServiceProvider(
name="KAMU SZERVIZ",
address="Nincs ilyen utca 0.",
added_by_user_id=bad_user.id,
status=ModerationStatus.pending
)
db.add(fake_shop)
await db.flush()
# Leszavazás (Kell -3 a bukáshoz)
print("Spam jelentése...")
await SocialService.vote_for_provider(db, voter.id, fake_shop.id, -1)
await SocialService.vote_for_provider(db, voter.id, fake_shop.id, -1)
await SocialService.vote_for_provider(db, voter.id, fake_shop.id, -1)
await db.refresh(bad_user)
print(f"Rossz felhasználó hírneve: {bad_user.reputation_score}")
print(f"Fiók státusza: {'KITILTVA' if not bad_user.is_active else 'AKTÍV'}")
if not bad_user.is_active:
print("✅ SIKER: A Sentinel automatikusan leállította a spammert!")
else:
print("\n⚠️ Marketplace táblák (service_providers, votes) nem léteznek, kihagyva a szociális szimulációt")
print(" Alap felhasználók sikeresen létrehozva")
except Exception as e:
print(f"\n⚠️ Hiba a táblák ellenőrzése közben: {e}, kihagyva a szociális szimulációt")
print(" Alap felhasználók sikeresen létrehozva")
if __name__ == "__main__":
asyncio.run(run_simulation())