diff --git a/backend/__pycache__/main.cpython-311.pyc b/backend/__pycache__/main.cpython-311.pyc index 6c18e5f..21a3456 100644 Binary files a/backend/__pycache__/main.cpython-311.pyc and b/backend/__pycache__/main.cpython-311.pyc differ diff --git a/backend/lottery.db b/backend/lottery.db index 576f41f..0c6f6e1 100644 Binary files a/backend/lottery.db and b/backend/lottery.db differ diff --git a/backend/main.py b/backend/main.py index 5ca4039..7b4c740 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,4 +1,4 @@ -from fastapi import FastAPI, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks +from fastapi import FastAPI, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks, Request import admin from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse @@ -205,16 +205,25 @@ def draw_lottery(user_id: int, db: Session = Depends(get_db)): if not selected_prize: selected_prize = prizes[-1] # Default to last prize if no match (should be "谢谢参与") - # Record prize win if not "谢谢参与" + # 记录所有的抽奖结果到user_prizes表,包括"谢谢参与" + # 这样可以记录每个用户的抽奖历史 + user_prize = UserPrize( + user_id=user_id, + prize_id=selected_prize.id, + is_shipped=False + ) + db.add(user_prize) + + # 只有实际奖品才减少库存 if selected_prize.name != "谢谢参与": - # Decrement available quantity + # 减少可用数量 selected_prize.available_quantity -= 1 - - # Record user win - user_prize = UserPrize(user_id=user_id, prize_id=selected_prize.id) - db.add(user_prize) - - db.commit() + + # 提交所有更改到数据库 + db.commit() + + # 记录日志 + print(f"用户 {user_id} 抽中了 {selected_prize.name},信息已存入数据库") # Return prize info return DrawResult( @@ -316,21 +325,63 @@ def claim_prize_for_cards(user_id: int, db: Session = Depends(get_db)): } ) -# Update shipping address -@app.put("/shipping/update", response_model=dict) -def update_shipping(shipping_data: ShippingUpdate, db: Session = Depends(get_db)): - # Find user - user = db.query(User).filter(User.id == shipping_data.user_id).first() +# Update shipping address (保留旧接口兼容性) +@app.post("/shipping/update", response_model=dict) +async def update_shipping(request: Request, db: Session = Depends(get_db)): + # 导入json + import json + + # 直接从请求体中读取原始数据 + body_bytes = await request.body() + body_str = body_bytes.decode() + print(f"Raw request body: {body_str}") + + # 解析JSON数据 + try: + body_data = json.loads(body_str) if body_str else {} + except json.JSONDecodeError: + print("Failed to parse JSON") + body_data = {} + + print(f"Parsed body data: {body_data}") + + # 从请求体中提取用户ID和地址 + try: + # 尝试多种可能的键名获取user_id + user_id = None + if 'user_id' in body_data: + user_id = int(body_data['user_id']) + elif 'userId' in body_data: + user_id = int(body_data['userId']) + + if user_id is None: + raise ValueError("user_id is required but not found in request") + + # 获取地址 + address = "" + if 'address' in body_data: + address = str(body_data['address']).strip() + + if not address: + raise HTTPException(status_code=400, detail="Address is required") + + print(f"Extracted user_id: {user_id}, address: {address}") + except (ValueError, TypeError) as e: + print(f"Error processing data: {str(e)}") + raise HTTPException(status_code=400, detail=f"Invalid data format: {str(e)}") + + # 查找用户 + user = db.query(User).filter(User.id == user_id).first() if not user: raise HTTPException(status_code=404, detail="User not found") - # Update address - user.address = shipping_data.address + # 更新地址 + user.address = address db.commit() - # Mark prizes as shipped + # 标记奖品为已发货 prizes = db.query(UserPrize).filter( - UserPrize.user_id == shipping_data.user_id, + UserPrize.user_id == user_id, UserPrize.is_shipped == False ).all() @@ -342,6 +393,74 @@ def update_shipping(shipping_data: ShippingUpdate, db: Session = Depends(get_db) return {"success": True, "message": "Shipping information updated"} +# 专门用于提交收货地址的接口 +@app.post("/users/address", response_model=dict) +async def submit_address(request: Request, db: Session = Depends(get_db)): + # 导入json + import json + + # 直接从请求体中读取原始数据 + body_bytes = await request.body() + body_str = body_bytes.decode() + print(f"Raw request body: {body_str}") + + # 解析JSON数据 + try: + body_data = json.loads(body_str) if body_str else {} + except json.JSONDecodeError: + print("Failed to parse JSON") + body_data = {} + + print(f"Parsed body data: {body_data}") + + # 从请求体中提取用户ID和地址 + try: + # 尝试多种可能的键名获取user_id + user_id = None + if 'user_id' in body_data: + user_id = int(body_data['user_id']) + elif 'userId' in body_data: + user_id = int(body_data['userId']) + + if user_id is None: + raise ValueError("user_id is required but not found in request") + + # 获取地址 + address = "" + if 'address' in body_data: + address = str(body_data['address']).strip() + + if not address: + raise HTTPException(status_code=400, detail="Address is required") + + print(f"Extracted user_id: {user_id}, address: {address}") + except (ValueError, TypeError) as e: + print(f"Error processing data: {str(e)}") + raise HTTPException(status_code=400, detail=f"Invalid data format: {str(e)}") + + # 查找用户 + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + # 更新地址 + user.address = address + db.commit() + + # 标记奖品为已发货 + prizes = db.query(UserPrize).filter( + UserPrize.user_id == user_id, + UserPrize.is_shipped == False + ).all() + + for prize in prizes: + prize.is_shipped = True + prize.shipped_at = datetime.datetime.now() + + db.commit() + + return {"success": True, "message": "Shipping address submitted successfully"} + # Stats routes for dashboard @app.get("/stats", response_model=dict) def get_stats(db: Session = Depends(get_db)): diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 2ea1918..364d187 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -54,8 +54,42 @@ export const cardAPI = { // Shipping API export const shippingAPI = { + // 原来的收货地址更新接口(兼容旧代码) updateShipping: async (userId: number, address: string) => { - const response = await api.put('/shipping/update', { user_id: userId, address }); + // 确保userId为数字,address为字符串 + // 直接使用纯文本格式的JSON作为请求体 + const data = JSON.stringify({ + user_id: Number(userId), + address: String(address).trim() + }); + + console.log('发送地址更新数据:', data); + + const response = await api.post('/shipping/update', data, { + headers: { + 'Content-Type': 'application/json' + } + }); + + return response.data; + }, + + // 新的专门用于提交收货地址的接口 + submitAddress: async (userId: number, address: string) => { + // 确保userId为数字,address为字符串 + const data = JSON.stringify({ + user_id: Number(userId), + address: String(address).trim() + }); + + console.log('发送收货地址数据:', data); + + const response = await api.post('/users/address', data, { + headers: { + 'Content-Type': 'application/json' + } + }); + return response.data; }, }; diff --git a/frontend/src/views/Home.vue b/frontend/src/views/Home.vue index c09340d..8b403f1 100644 --- a/frontend/src/views/Home.vue +++ b/frontend/src/views/Home.vue @@ -39,10 +39,18 @@ const drawLottery = async () => { try { // If user is already created, use the API if (userData.value.id !== 0) { - const result = await lotteryAPI.drawLottery(userData.value.id) - userData.value.prize = result - ElMessage.success(`恭喜您抽中了${result.name}!`) - return result + const response = await lotteryAPI.drawLottery(userData.value.id) + console.log('抽奖结果原始数据:', response) + + // 从响应中提取奖品信息 + if (response.success && response.prize) { + userData.value.prize = response.prize + ElMessage.success(`恭喜您抽中了${response.prize.name}!`) + return response.prize + } else { + ElMessage.warning(response.message || '抽奖失败,请重试') + return null + } } // Otherwise use simulated logic for now @@ -108,7 +116,8 @@ const submitUserInfo = async () => { if (userData.value.id === 0) { // Create new user response = await userAPI.createUser(userInfo) - userData.value.id = response.id // Save user ID for future updates + userData.value.id = response.user_id // Save user ID for future updates + console.log('创建新用户返回信息:', response) } else { // Update existing user response = await userAPI.updateUser(userData.value.id, userInfo) @@ -122,26 +131,52 @@ const submitUserInfo = async () => { } } -// Submit shipping address +// Submit shipping address - 完全独立的收货地址提交函数 +// 现在这个函数不再依赖于用户信息提交成功的结果 +// 直接使用专门的收货地址提交接口 const submitShippingAddress = async () => { try { + console.log('准备提交收货地址new:', userData.value) + + // 验证用户ID if (userData.value.id === 0) { ElMessage.error('请先提交个人信息') currentPage.value = 4 return } - // Call API to update shipping address - await shippingAPI.updateShipping(userData.value.id, userData.value.address) + // 验证地址不为空并且是有效字符串 + if (!userData.value.address || userData.value.address.trim() === '') { + ElMessage.error('请输入有效的收货地址') + return + } - // If user has a prize, save it to the database + // 转换并验证用户ID + const userId = Number(userData.value.id); + if (!userId || isNaN(userId)) { + ElMessage.error('用户ID无效,请重新提交个人信息') + currentPage.value = 4 + return + } + + // 准备发送的数据 + const address = userData.value.address.trim() + console.log('即将提交收货地址:', { + user_id: userId, + address: address + }) + + // 使用新的专门接口提交收货地址 + await shippingAPI.submitAddress(userId, address) + + // 如果用户有奖品,将其保存到数据库 if (userData.value.prize) { - // Assuming we have a claimPrize API that takes user ID and prize ID - await cardAPI.claimPrize(userData.value.id) + // 先尝试领取奖品(如果还没领取) + await cardAPI.claimPrize(userId) } ElMessage.success('收货地址提交成功!奖品即将派送') - nextPage() + nextPage() // 进入确认页面 } catch (error) { ElMessage.error('提交失败,请重试') console.error('Submit shipping address error:', error)