keyvault-api / scripts /seed_demo.py
hashir-qt's picture
Upload folder using huggingface_hub
e656014 verified
Raw History Blame Contribute Delete
21.4 kB
"""
Demo seed script โ€” populates the database with realistic demo data.
Usage (from marketplace-backend directory):
"d:/All Projects/E-Marketplace-Suffi/marketplace-backend/.venv/Scripts/python.exe" scripts/seed_demo.py
Creates:
- 4 seller accounts (gamedeals, keymaster, digitalvault, softwarehub)
- 1 buyer account (buyer@demo.com)
- 1 admin account (admin@demo.com)
- 8 product listings with 20 keys each
- 5 demo orders (buyer purchases from different sellers)
All accounts use password: Demo1234!
"""
import asyncio
import random
import string
import sys
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
# โ”€โ”€ Ensure `src` package is importable โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
sys.path.insert(0, str(Path(__file__).parent.parent))
import src.models # noqa: F401 โ€” registers SQLModel metadata
from src.database import AsyncSessionLocal, init_db
from src.models.order import Order, OrderItem, OrderStatus
from src.models.product import ProductCategory, ProductKey, ProductListing, ProductStatus
from src.models.seller_profile import SellerProfile, SellerStatus, SellerTier
from src.models.user import User, UserRole
from src.utils.encryption import encrypt_key
from src.utils.security import hash_password
from sqlalchemy import delete
from sqlmodel import select
# โ”€โ”€ Key generators โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def _rnd(n: int) -> str:
return "".join(random.choices(string.ascii_uppercase + string.digits, k=n))
def gen_key(platform: str) -> str:
"""Generate a realistic-looking product key for the given platform."""
if platform in ("Steam",):
return f"{_rnd(5)}-{_rnd(5)}-{_rnd(5)}"
if platform in ("Xbox", "Xbox / PC"):
return f"{_rnd(5)}-{_rnd(5)}-{_rnd(5)}-{_rnd(5)}-{_rnd(5)}"
if platform in ("PlayStation 5",):
return f"{_rnd(4)}-{_rnd(4)}-{_rnd(4)}-{_rnd(4)}"
if platform in ("PC / Mac",):
return f"{_rnd(4)}-{_rnd(4)}-{_rnd(4)}-{_rnd(4)}-{_rnd(4)}"
return f"{_rnd(4)}-{_rnd(4)}-{_rnd(4)}-{_rnd(4)}"
# โ”€โ”€ Demo data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
DEMO_PASSWORD = "Demo1234!"
SELLERS = [
{
"email": "gamedeals@demo.com",
"username": "GameDeals",
"full_name": "Game Deals Store",
"tier": SellerTier.GOLD,
"store_name": "GameDeals",
"store_description": "Premium digital game keys at the lowest prices. 12,000+ satisfied customers.",
},
{
"email": "keymaster@demo.com",
"username": "KeyMaster",
"full_name": "Key Master Digital",
"tier": SellerTier.SILVER,
"store_name": "KeyMaster",
"store_description": "Your trusted source for PC and console game keys since 2022.",
},
{
"email": "digitalvault@demo.com",
"username": "DigitalVault",
"full_name": "Digital Vault",
"tier": SellerTier.BRONZE,
"store_name": "DigitalVault",
"store_description": "Affordable console keys and gift cards, fast delivery.",
},
{
"email": "softwarehub@demo.com",
"username": "SoftwareHub",
"full_name": "Software Hub",
"tier": SellerTier.GOLD,
"store_name": "SoftwareHub",
"store_description": "Top-tier software subscriptions and creative tools. 8,900+ sales.",
},
]
PRODUCTS = [
# โ”€โ”€ GameDeals โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
{
"seller": "GameDeals",
"title": "Grand Theft Auto V โ€” Premium Edition",
"description": (
"Grand Theft Auto V for PC offers players the option to explore the award-winning world "
"of Los Santos and Blaine County in resolutions of up to 4k and beyond, with a range of "
"graphical and technical upgrades. The Premium Edition includes the complete GTA Online "
"Criminal Enterprise Starter Pack."
),
"price": 14.99,
"original_price": 29.99,
"platform": "Steam",
"region": "Global",
"category": ProductCategory.GAME_KEY,
"image_url": "https://cdn.cloudflare.steamstatic.com/steam/apps/271590/header.jpg",
"activation_steps": [
"Download and install Steam from steampowered.com",
"Create a free Steam account or log in",
"Click 'Add a Game' in the bottom-left of Steam and select 'Activate a Product on Steam'",
"Enter your product key when prompted",
"The game will appear in your Steam library โ€” click Install to begin downloading",
],
"is_flash_deal": True,
"key_count": 20,
"total_sold": 86,
},
{
"seller": "GameDeals",
"title": "Call of Duty: Black Ops 6",
"description": (
"Black Ops is back! Featuring round-based Zombies, ground-breaking movement, and the most "
"responsive Call of Dutyยฎ gameplay ever. Experience an epic single-player campaign and "
"the best Multiplayer suite in series history."
),
"price": 39.99,
"original_price": 59.99,
"platform": "Xbox",
"region": "Global",
"category": ProductCategory.GAME_KEY,
"image_url": "https://cdn.cloudflare.steamstatic.com/steam/apps/2933620/header.jpg",
"activation_steps": [
"Open the Xbox app on PC or go to xbox.com",
"Sign in to your Microsoft account",
"Select 'Redeem Code' from the menu",
"Enter your 25-character code and confirm",
"Download the game from your library",
],
"is_flash_deal": True,
"key_count": 20,
"total_sold": 54,
},
{
"seller": "GameDeals",
"title": "Xbox Game Pass Ultimate โ€” 3 Months",
"description": (
"Xbox Game Pass Ultimate includes Xbox Live Gold + 100+ high-quality games on Console, "
"PC, and Android + EA Play on Xbox and PC. New games added all the time with day-one "
"access to every first-party Xbox title."
),
"price": 24.99,
"original_price": 44.99,
"platform": "Xbox / PC",
"region": "US",
"category": ProductCategory.SUBSCRIPTION,
"image_url": "https://placehold.co/460x215/1a1a2e/7c3aed?text=Xbox+Game+Pass+Ultimate",
"activation_steps": [
"Go to xbox.com/redeem or open the Xbox app",
"Sign in with your Microsoft account",
"Enter your 25-character code",
"Your membership is activated instantly",
],
"is_flash_deal": True,
"key_count": 20,
"total_sold": 210,
},
# โ”€โ”€ KeyMaster โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
{
"seller": "KeyMaster",
"title": "Minecraft Java & Bedrock Edition",
"description": (
"Get both Minecraft Java Edition and Bedrock Edition together. Play on PC, join Java "
"servers, explore Realms, and create with community mods. One purchase unlocks both "
"editions on your Microsoft account."
),
"price": 19.99,
"original_price": 29.99,
"platform": "PC",
"region": "Global",
"category": ProductCategory.GAME_KEY,
"image_url": "https://placehold.co/460x215/1a1a2e/22c55e?text=Minecraft+Java+%26+Bedrock",
"activation_steps": [
"Visit minecraft.net and sign in with your Microsoft account",
"Click 'Redeem' in your account settings",
"Enter your code and click Confirm",
"Download the Minecraft Launcher from minecraft.net",
"Launch and enjoy both Java and Bedrock editions",
],
"is_flash_deal": True,
"key_count": 20,
"total_sold": 118,
},
{
"seller": "KeyMaster",
"title": "Cyberpunk 2077 Ultimate Edition",
"description": (
"Includes the base game + Phantom Liberty expansion. An open-world action-adventure story "
"set in Night City, a megalopolis obsessed with power, glamour and body modification. "
"Now fully patched and optimized โ€” the definitive Night City experience."
),
"price": 29.99,
"original_price": 59.99,
"platform": "Steam",
"region": "Global",
"category": ProductCategory.GAME_KEY,
"image_url": "https://cdn.cloudflare.steamstatic.com/steam/apps/1091500/header.jpg",
"activation_steps": [
"Open Steam and click 'Add a Game' โ†’ 'Activate a Product on Steam'",
"Enter your product key when prompted",
"The game will appear in your Steam library",
"Click Install to begin downloading",
],
"is_flash_deal": False,
"key_count": 20,
"total_sold": 62,
},
# โ”€โ”€ DigitalVault โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
{
"seller": "DigitalVault",
"title": "FIFA 25 Standard Edition",
"description": (
"EA SPORTS FC 25 brings unmatched authenticity with HyperMotionV technology. "
"Experience the most realistic player movement and stadium atmosphere ever. "
"Includes Ultimate Team, Career Mode, VOLTA FOOTBALL, and Pro Clubs."
),
"price": 49.99,
"original_price": 69.99,
"platform": "PlayStation 5",
"region": "US",
"category": ProductCategory.GAME_KEY,
"image_url": "https://cdn.cloudflare.steamstatic.com/steam/apps/2669320/header.jpg",
"activation_steps": [
"On your PS5, navigate to the PlayStation Store",
"Select 'Redeem Codes' from the account menu",
"Enter your 12-digit code exactly as shown",
"The game will be added to your library for download",
],
"is_flash_deal": False,
"key_count": 20,
"total_sold": 43,
},
{
"seller": "DigitalVault",
"title": "Steam Wallet Gift Card โ€” $50",
"description": (
"Add $50 USD to your Steam Wallet instantly. Use it to buy games, DLC, in-game items, "
"and more on the Steam platform. Works with any Steam account. No expiry date."
),
"price": 47.99,
"original_price": 50.00,
"platform": "Steam",
"region": "US",
"category": ProductCategory.GIFT_CARD,
"image_url": "https://placehold.co/460x215/1a1a2e/3b82f6?text=Steam+Wallet+%2450",
"activation_steps": [
"Open Steam and click your username at the top",
"Select 'Account Details'",
"Click 'Add funds to your Steam Wallet'",
"Select 'Redeem a Steam Gift Card or Wallet Code'",
"Enter your code to add $50 to your wallet",
],
"is_flash_deal": False,
"key_count": 20,
"total_sold": 31,
},
# โ”€โ”€ SoftwareHub โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
{
"seller": "SoftwareHub",
"title": "Adobe Creative Cloud โ€” 1 Year",
"description": (
"Get full access to 20+ creative desktop and mobile apps including Photoshop, "
"Illustrator, Premiere Pro, After Effects, Lightroom, and more. Includes 100GB "
"cloud storage. Perfect for designers, photographers, and video editors."
),
"price": 54.99,
"original_price": 89.99,
"platform": "PC / Mac",
"region": "Global",
"category": ProductCategory.SUBSCRIPTION,
"image_url": "https://placehold.co/460x215/1a1a2e/ef4444?text=Adobe+Creative+Cloud",
"activation_steps": [
"Go to redeem.adobe.com in your browser",
"Sign in or create a free Adobe account",
"Enter your redemption code in the provided field",
"Download the Creative Cloud app",
"Install any of the 20+ included apps",
],
"is_flash_deal": False,
"key_count": 20,
"total_sold": 72,
},
]
# Demo orders: buyer purchases these products (in order of creation, oldest first)
DEMO_ORDER_PLANS = [
{
"products": ["Adobe Creative Cloud โ€” 1 Year"],
"payment_method": "stripe",
"days_ago": 14,
},
{
"products": ["FIFA 25 Standard Edition"],
"payment_method": "paypal",
"days_ago": 10,
},
{
"products": ["Cyberpunk 2077 Ultimate Edition", "Minecraft Java & Bedrock Edition"],
"payment_method": "stripe",
"days_ago": 6,
},
{
"products": ["Xbox Game Pass Ultimate โ€” 3 Months"],
"payment_method": "jazzcash",
"days_ago": 3,
},
{
"products": ["Grand Theft Auto V โ€” Premium Edition"],
"payment_method": "stripe",
"days_ago": 1,
},
]
# โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async def clear_db(db) -> None:
"""Delete all rows from every table in FK-safe order."""
print("[CLEAR] Wiping all existing data...")
await db.execute(delete(OrderItem))
await db.execute(delete(Order))
await db.execute(delete(ProductKey))
await db.execute(delete(ProductListing))
await db.execute(delete(SellerProfile))
await db.execute(delete(User))
await db.flush()
print("[CLEAR] All tables cleared.\n")
async def create_user(db, email: str, username: str, full_name: str, role: UserRole) -> User:
user = User(
id=str(uuid.uuid4()),
email=email,
username=username,
full_name=full_name,
hashed_password=hash_password(DEMO_PASSWORD),
role=role,
is_active=True,
)
db.add(user)
await db.flush()
print(f" [+] Created user: {email}")
return user
async def create_seller_profile(db, user_id: str, store_name: str, store_desc: str, tier: SellerTier) -> SellerProfile:
profile = SellerProfile(
id=str(uuid.uuid4()),
user_id=user_id,
store_name=store_name,
store_description=store_desc,
status=SellerStatus.APPROVED,
tier=tier,
id_submitted=True,
)
db.add(profile)
await db.flush()
return profile
async def seed():
print("\n[SEED] Demo seed starting...\n")
# Ensure tables exist
await init_db()
async with AsyncSessionLocal() as db:
# --- 0. Clear existing data ---
await clear_db(db)
# --- 1. Admin ---
print("--- Admin ---")
await create_user(db, "admin@demo.com", "admin", "Site Admin", UserRole.ADMIN)
# --- 2. Buyer ---
print("\n--- Buyer ---")
buyer = await create_user(db, "buyer@demo.com", "demoBuyer", "Demo Buyer", UserRole.BUYER)
# --- 3. Sellers + profiles ---
print("\n--- Sellers ---")
seller_profiles: dict[str, SellerProfile] = {}
for s in SELLERS:
user = await create_user(db, s["email"], s["username"], s["full_name"], UserRole.SELLER)
profile = await create_seller_profile(
db, user.id, s["store_name"], s["store_description"], s["tier"]
)
seller_profiles[s["store_name"]] = profile
# --- 4. Products + keys ---
print("\n--- Products ---")
product_map: dict[str, ProductListing] = {}
for p_data in PRODUCTS:
seller_name = p_data["seller"]
profile = seller_profiles[seller_name]
product = ProductListing(
id=str(uuid.uuid4()),
seller_id=profile.id,
title=p_data["title"],
description=p_data["description"],
price=p_data["price"],
original_price=p_data["original_price"],
platform=p_data["platform"],
region=p_data["region"],
category=p_data["category"],
image_url=p_data["image_url"],
activation_steps=p_data["activation_steps"],
is_flash_deal=p_data["is_flash_deal"],
status=ProductStatus.ACTIVE,
stock_count=p_data["key_count"],
total_sold=p_data["total_sold"],
)
db.add(product)
await db.flush()
for _ in range(p_data["key_count"]):
key = ProductKey(
id=str(uuid.uuid4()),
product_id=product.id,
encrypted_key=encrypt_key(gen_key(p_data["platform"])),
is_sold=False,
)
db.add(key)
product_map[p_data["title"]] = product
print(f" [+] Created: {p_data['title']} ({p_data['key_count']} keys, {p_data['total_sold']} historical sales)")
await db.flush()
# --- 5. Demo orders ---
print("\n--- Demo orders ---")
for plan in DEMO_ORDER_PLANS:
order_id = "ORD-" + uuid.uuid4().hex[:8].upper()
order_date = datetime.now(timezone.utc) - timedelta(days=plan["days_ago"])
line_items = []
for title in plan["products"]:
if title not in product_map:
print(f" [skip] Product not found: {title}")
continue
product = product_map[title]
# Pick an unsold key
keys_result = await db.execute(
select(ProductKey)
.where(ProductKey.product_id == product.id)
.where(ProductKey.is_sold == False) # noqa: E712
.limit(1)
)
key = keys_result.scalars().first()
if not key:
print(f" [skip] No available keys for: {title}")
continue
line_items.append((product, key))
if not line_items:
continue
platform_fee = 0.49
subtotal = sum(p.price for p, _ in line_items)
total = round(subtotal + platform_fee, 2)
order = Order(
id=order_id,
buyer_id=buyer.id,
total_price=total,
platform_fee=platform_fee,
payment_method=plan["payment_method"],
status=OrderStatus.COMPLETED,
created_at=order_date,
)
db.add(order)
await db.flush()
for product, key in line_items:
oi_id = str(uuid.uuid4())
order_item = OrderItem(
id=oi_id,
order_id=order_id,
product_id=product.id,
product_key_id=key.id,
price_at_purchase=product.price,
title_at_purchase=product.title,
platform_at_purchase=product.platform,
)
db.add(order_item)
key.is_sold = True
key.sold_at = order_date
key.order_item_id = oi_id
db.add(key)
product.total_sold += 1
product.stock_count -= 1
if product.stock_count == 0:
product.status = ProductStatus.OUT_OF_STOCK
db.add(product)
titles = ", ".join(p.title for p, _ in line_items)
print(f" [+] Order {order_id}: {titles} (${total:.2f}, {plan['days_ago']}d ago)")
await db.commit()
print("\n[DONE] Seed complete!\n")
print("Demo accounts (password: Demo1234!)")
print(" Sellers : gamedeals@demo.com | keymaster@demo.com | digitalvault@demo.com | softwarehub@demo.com")
print(" Buyer : buyer@demo.com")
print(" Admin : admin@demo.com")
if __name__ == "__main__":
asyncio.run(seed())