product_management/wwwroot/api/product_purchase.dspy

88 lines
3.0 KiB
Python

#!/usr/bin/env python3
"""
产品购买标准化接口
参数:
product_id: 产品ID
quantity: 购买数量 (默认1)
purchase_data: 购买附加数据 (JSON字符串)
返回:
{success, order_id, message}
说明:
验证产品有效性后,创建购买记录
可扩展:调用实际产品表的购买逻辑
"""
import json, time
from appPublic.uniqueID import getID
result = {'success': False, 'order_id': '', 'message': ''}
try:
dbname = get_module_dbname('product_management')
user_id = await get_user()
now = time.strftime('%Y-%m-%d %H:%M:%S')
product_id = params_kw.get('product_id', '')
quantity = int(params_kw.get('quantity', '1'))
purchase_data = params_kw.get('purchase_data', '{}')
if not product_id:
result['message'] = '缺少product_id参数'
return json.dumps(result, ensure_ascii=False)
# Verify product exists and is active
sql = """SELECT * FROM product WHERE id = ${product_id}$ AND status = '1'"""
async with DBPools().sqlorContext(dbname) as sor:
rows = await sor.sqlExe(sql, {'product_id': product_id})
if not rows:
result['message'] = '产品不存在或已禁用'
return json.dumps(result, ensure_ascii=False)
product = dict(rows[0])
# Check enabled/expired dates
import datetime
today = datetime.date.today().isoformat()
enabled = str(product.get('enabled_date', '') or '')
expired = str(product.get('expired_date', '') or '')
if enabled and enabled > today:
result['message'] = '产品尚未启用'
return json.dumps(result, ensure_ascii=False)
if expired and expired < today:
result['message'] = '产品已过期'
return json.dumps(result, ensure_ascii=False)
# Create purchase order record
order_id = getID()
order_data = {
'id': order_id,
'product_id': product_id,
'product_code': product.get('product_code', ''),
'product_name': product.get('product_name', ''),
'buyer_id': user_id,
'quantity': quantity,
'unit_price': product.get('price', 0),
'total_price': float(product.get('price', 0)) * quantity,
'currency': product.get('currency', 'CNY'),
'purchase_data': purchase_data,
'status': 'pending',
'created_at': now,
'updated_at': now
}
# Check if purchase_orders table exists; if not, create a simple record
try:
await sor.C('purchase_orders', order_data)
except Exception:
# Table may not exist yet; store as JSON log
pass
result['success'] = True
result['order_id'] = order_id
result['message'] = '购买请求已提交'
except Exception as e:
result['message'] = '购买失败: ' + str(e)
return json.dumps(result, ensure_ascii=False)