chore: import WonderQ project

This commit is contained in:
duanshuwen committed 2026-08-11 19:19:11 +08:00
commit f5a9e4403a
452 files changed
+34173

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""API routers."""
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_, select
from sqlalchemy.orm import Session, selectinload
from .shared import site_config
from ..auth import create_customer_token, require_customer
from ..database import get_db
from ..models import Customer, Destination, DestinationAlias, Lead, Product
from ..schemas import LeadCreateIn, PhoneLoginIn, ProductQuery, ProductStatus
from ..serializers import destination_dict, public_product_dict
from ..wechat import WechatApiError, WechatConfigError, exchange_phone_code
router = APIRouter()
def mask_phone(phone: str) -> str:
normalized = phone.strip()
if len(normalized) <= 7:
return "***"
return f"{normalized[:3]}****{normalized[-4:]}"
def public_customer_dict(customer: Customer) -> dict:
return {"id": customer.id, "phoneMasked": mask_phone(customer.phone)}
@router.get("/health")
def health():
return {"ok": True, "service": "miniapp-api"}
@router.get("/api/public/site-config")
def get_site_config(db: Session = Depends(get_db)):
return site_config(db, active_only=True)
@router.get("/api/public/products")
def list_products(
keyword: str | None = None,
destinationId: str | None = None,
status_value: ProductStatus = Query(default="published", alias="status"),
take: int = Query(default=48, ge=1, le=100),
db: Session = Depends(get_db),
):
query = ProductQuery(keyword=keyword, destinationId=destinationId, status=status_value, take=take)
stmt = (
select(Product)
.options(selectinload(Product.destination).selectinload(Destination.aliases), selectinload(Product.images))
.where(Product.status == query.status)
.order_by(Product.sortWeight.asc(), Product.createdAt.asc())
.limit(query.take)
)
if query.destinationId:
stmt = stmt.where(Product.destinationId == query.destinationId)
if query.keyword:
pattern = f"%{query.keyword}%"
stmt = (
stmt.outerjoin(Product.destination)
.outerjoin(Destination.aliases)
.where(
or_(
Product.title.ilike(pattern),
Product.subtitle.ilike(pattern),
Product.tags.any(query.keyword),
Destination.name.ilike(pattern),
DestinationAlias.alias.ilike(pattern),
)
)
.distinct()
)
products = db.scalars(stmt).unique().all()
return {"items": [public_product_dict(product) for product in products]}
@router.get("/api/public/products/{product_id}")
def get_product(product_id: str, db: Session = Depends(get_db)):
stmt = select(Product).options(selectinload(Product.destination), selectinload(Product.images))
if product_id.isdigit():
stmt = stmt.where(Product.sourceId == int(product_id))
else:
stmt = stmt.where(Product.id == product_id)
product = db.scalars(stmt).first()
if not product:
raise HTTPException(status_code=404, detail="线路不存在")
return public_product_dict(product)
@router.get("/api/public/destinations")
def list_destinations(db: Session = Depends(get_db)):
destinations = db.scalars(
select(Destination)
.options(selectinload(Destination.aliases))
.where(Destination.isActive.is_(True))
.order_by(Destination.sortOrder.asc())
).all()
return {"items": [destination_dict(destination) for destination in destinations]}
@router.post("/api/public/auth/phone-login")
def phone_login(body: PhoneLoginIn, db: Session = Depends(get_db)):
try:
phone = exchange_phone_code(body.code)
except WechatConfigError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
except WechatApiError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
customer = db.scalar(select(Customer).where(Customer.phone == phone))
if not customer:
customer = Customer(phone=phone)
db.add(customer)
db.flush()
db.commit()
db.refresh(customer)
return {"token": create_customer_token(customer), "customer": public_customer_dict(customer)}
@router.get("/api/public/auth/me")
def current_customer(customer: Customer = Depends(require_customer)):
return public_customer_dict(customer)
@router.post("/api/public/leads", status_code=status.HTTP_201_CREATED)
def create_lead(body: LeadCreateIn, db: Session = Depends(get_db)):
lead = Lead(**body.model_dump(exclude_none=True), status="new")
db.add(lead)
db.commit()
db.refresh(lead)
return {"id": lead.id, "status": lead.status}
+68
View File
@@ -0,0 +1,68 @@
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload
from ..models import Campaign, CtaBanner, DemandFeatureCard, DemandForm, DemandHero, Destination, DestinationHero, DestinationRegion, HeroSlide, HotelGroup, MapImage, ThemeCard, VehicleOption
from ..demand_recommendations import demand_recommendation_dict, demand_recommendation_query
from ..route_sections import route_section_dict, route_section_query
from ..serializers import destination_dict, hotel_group_dict, model_dict
def site_config(db: Session, active_only: bool, include_public_extras: bool = True) -> dict:
hero_stmt = select(HeroSlide).order_by(HeroSlide.sortOrder.asc())
destination_stmt = select(Destination).options(selectinload(Destination.aliases)).order_by(Destination.sortOrder.asc())
destination_hero_stmt = select(DestinationHero).order_by(DestinationHero.sortOrder.asc())
destination_region_stmt = select(DestinationRegion).order_by(DestinationRegion.sortOrder.asc())
map_stmt = select(MapImage).order_by(MapImage.createdAt.asc())
theme_stmt = select(ThemeCard).order_by(ThemeCard.sortOrder.asc())
cta_stmt = select(CtaBanner).order_by(CtaBanner.sortOrder.asc())
hotel_stmt = select(HotelGroup).order_by(HotelGroup.sortOrder.asc())
vehicle_stmt = select(VehicleOption).order_by(VehicleOption.sortOrder.asc())
demand_hero_stmt = select(DemandHero).order_by(DemandHero.sortOrder.asc())
demand_feature_card_stmt = select(DemandFeatureCard).order_by(DemandFeatureCard.sortOrder.asc())
demand_form_stmt = select(DemandForm).order_by(DemandForm.createdAt.asc())
if active_only:
hero_stmt = hero_stmt.where(HeroSlide.isActive.is_(True))
destination_stmt = destination_stmt.where(Destination.isActive.is_(True))
destination_hero_stmt = destination_hero_stmt.where(DestinationHero.isActive.is_(True))
destination_region_stmt = destination_region_stmt.where(DestinationRegion.isActive.is_(True))
map_stmt = map_stmt.where(MapImage.isActive.is_(True))
theme_stmt = theme_stmt.where(ThemeCard.isActive.is_(True))
cta_stmt = cta_stmt.where(CtaBanner.isActive.is_(True))
hotel_stmt = hotel_stmt.where(HotelGroup.isActive.is_(True), HotelGroup.status == "published")
vehicle_stmt = vehicle_stmt.where(VehicleOption.isActive.is_(True))
demand_hero_stmt = demand_hero_stmt.where(DemandHero.isActive.is_(True))
demand_feature_card_stmt = demand_feature_card_stmt.where(DemandFeatureCard.isActive.is_(True))
demand_form_stmt = demand_form_stmt.where(DemandForm.isActive.is_(True))
hero_slides = db.scalars(hero_stmt).all()
destinations = db.scalars(destination_stmt).all()
destination_hero = db.scalars(destination_hero_stmt).all()
destination_regions = db.scalars(destination_region_stmt).all()
map_images = db.scalars(map_stmt).all()
themes = db.scalars(theme_stmt).all()
cta_banners = db.scalars(cta_stmt).all()
result = {
"heroSlides": [model_dict(item) for item in hero_slides],
"destinations": [destination_dict(item) for item in destinations],
"destinationHero": [model_dict(item) for item in destination_hero],
"destinationRegions": [model_dict(item) for item in destination_regions],
"map": [model_dict(item) for item in map_images],
"themes": [model_dict(item) for item in themes],
"ctaBanners": [model_dict(item) for item in cta_banners],
}
if include_public_extras:
campaigns = db.scalars(select(Campaign).where(Campaign.status == "published").order_by(Campaign.updatedAt.desc())).all()
route_sections = db.scalars(route_section_query()).all()
if active_only:
route_sections = [section for section in route_sections if section.isActive]
result["campaigns"] = [model_dict(item) for item in campaigns]
result["routeSections"] = [route_section_dict(item, public=True) for item in route_sections]
result["hotelGroups"] = [hotel_group_dict(item) for item in db.scalars(hotel_stmt).all()]
result["vehicleOptions"] = [model_dict(item) for item in db.scalars(vehicle_stmt).all()]
result["demandHero"] = [model_dict(item) for item in db.scalars(demand_hero_stmt).all()]
result["demandFeatureCards"] = [model_dict(item) for item in db.scalars(demand_feature_card_stmt).all()]
result["demandForm"] = [model_dict(item) for item in db.scalars(demand_form_stmt).all()]
demand_recommendations = db.scalars(demand_recommendation_query()).all()
if active_only:
demand_recommendations = [item for item in demand_recommendations if item.isActive]
result["demandRecommendations"] = [demand_recommendation_dict(item, public=active_only) for item in demand_recommendations]
return result