Files
happy-up/apps/api/app/db/seed.py
T
john 1aaef71f52 Initial commit: Happy Up monorepo through Sprint 5.
Document-driven MVP with FastAPI backend, Vue H5, WeChat mini shell, product demo, and Docker dev stack.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 11:42:40 +08:00

90 lines
2.8 KiB
Python

"""Seed demo tenant, parent user and child for local development."""
from datetime import date, datetime, timezone
from sqlalchemy import select
from app.core.security import hash_phone
from app.db.models import Child, Tenant, TrainingPlan, User
from app.db.session import SessionLocal
from app.services.training import build_plan_detail, ensure_default_exercises
from app.schemas.models import TrainingPlanCreateRequest
def seed() -> None:
db = SessionLocal()
try:
tenant = db.scalar(select(Tenant).where(Tenant.name == "Demo Organization"))
if not tenant:
tenant = Tenant(name="Demo Organization", type="organization", status="active")
db.add(tenant)
db.flush()
phone = "18600000000"
phone_hash = hash_phone(phone)
user = db.scalar(select(User).where(User.phone_hash == phone_hash))
if not user:
user = User(
tenant_id=tenant.id,
phone=phone,
phone_hash=phone_hash,
role="parent",
status="active",
consent_signed=True,
)
db.add(user)
db.flush()
child = db.scalar(
select(Child).where(Child.parent_user_id == user.id, Child.name == "小明")
)
if not child:
child = Child(
parent_user_id=user.id,
tenant_id=tenant.id,
name="小明",
gender="male",
birthday=date(2016, 3, 15),
height=142.5,
weight=36.0,
status="active",
)
db.add(child)
db.flush()
ensure_default_exercises(db)
plan = db.scalar(
select(TrainingPlan).where(
TrainingPlan.child_id == child.id, TrainingPlan.status == "active"
)
)
if not plan:
body = TrainingPlanCreateRequest.model_validate(
{"childId": child.id, "goal": "改善头前伸与高低肩", "cycleDays": 28}
)
detail = build_plan_detail(body)
detail["completedDays"] = 2
detail["currentDay"] = 3
plan = TrainingPlan(
child_id=child.id,
goal=body.goal,
cycle_days=28,
status="active",
plan_detail=detail,
started_at=datetime.now(timezone.utc),
)
db.add(plan)
db.commit()
child_row = db.scalar(
select(Child).where(Child.parent_user_id == user.id, Child.name == "小明")
)
print(f"Seed OK · tenant={tenant.id} user={user.id} child={child_row.id if child_row else '-'}")
finally:
db.close()
if __name__ == "__main__":
seed()