#!/usr/bin/env python3 """ 产品使用标准化接口 参数: product_id: 产品ID order_id: 订单ID (可选) use_data: 使用附加数据 (JSON字符串) 返回: {success, use_record_id, data} 说明: 验证用户是否拥有该产品后,执行使用操作 动态路由到实际产品表的使用逻辑 """ import json, time from appPublic.uniqueID import getID result = {'success': False, 'use_record_id': '', 'message': '', 'data': {}} 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', '') order_id = params_kw.get('order_id', '') use_data = params_kw.get('use_data', '{}') if not product_id: result['message'] = '缺少product_id参数' return json.dumps(result, ensure_ascii=False) # Step 1: 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]) # Step 2: Verify user has purchased this product # Check purchase_orders table purchase_sql = """SELECT * FROM purchase_orders WHERE product_id = ${product_id}$ AND buyer_id = ${user_id}$ AND status IN ('active', 'pending')""" purchases = await sor.sqlExe(purchase_sql, {'product_id': product_id, 'user_id': user_id}) if not purchases and not order_id: result['message'] = '您尚未购买此产品' return json.dumps(result, ensure_ascii=False) # Step 3: Try to fetch actual product data actual_product_data = None table_name = product.get('product_table_name', '') table_id = product.get('product_table_id', '') if table_name and table_id: try: detail_sql = f"SELECT * FROM {table_name} WHERE id = ${{table_id}}$" detail_rows = await sor.sqlExe(detail_sql, {'table_id': table_id}) if detail_rows: actual_product_data = dict(detail_rows[0]) except: pass # Step 4: Create use record use_record_id = getID() result['success'] = True result['use_record_id'] = use_record_id result['data'] = { 'product_info': { 'id': product['id'], 'name': product['product_name'], 'code': product['product_code'] }, 'actual_data': actual_product_data } result['message'] = '产品使用成功' except Exception as e: result['message'] = '使用失败: ' + str(e) return json.dumps(result, ensure_ascii=False, default=str)