#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Opportunity create API""" import json, uuid, time result = {'widgettype': 'Message', 'options': {'title': 'Error', 'message': 'Invalid request', 'type': 'error'}} try: opportunity_name = params_kw.get('opportunity_name', '').strip() customer_id = params_kw.get('customer_id', '').strip() customer_name = params_kw.get('customer_name', '').strip() estimated_amount = params_kw.get('estimated_amount', '0').strip() current_stage = params_kw.get('current_stage', '').strip() expected_close_date = params_kw.get('expected_close_date', '').strip() owner_id = params_kw.get('owner_id', '').strip() owner_name = params_kw.get('owner_name', '').strip() if not opportunity_name or not customer_id or not current_stage or not owner_id: result['options'] = {'title': 'Error', 'message': '请填写必填字段', 'type': 'error'} else: dbname = get_module_dbname('opportunity_management') new_id = str(uuid.uuid4()).replace('-', '') now = time.strftime('%Y-%m-%d %H:%M:%S') async with DBPools().sqlorContext(dbname) as sor: await sor.sqlExe("""INSERT INTO opportunities (id, customer_id, customer_name, opportunity_name, estimated_amount, current_stage, expected_close_date, source_type, owner_id, owner_name, region, description, probability, predicted_revenue, status, created_at, updated_at) VALUES (${id}$, ${customer_id}$, ${customer_name}$, ${opportunity_name}$, ${estimated_amount}$, ${current_stage}$, ${expected_close_date}$, ${source_type}$, ${owner_id}$, ${owner_name}$, ${region}$, ${description}$, ${probability}$, ${predicted_revenue}$, ${status}$, ${created_at}$, ${updated_at}$)""", { 'id': new_id, 'customer_id': customer_id, 'customer_name': customer_name, 'opportunity_name': opportunity_name, 'estimated_amount': float(estimated_amount) if estimated_amount else 0, 'current_stage': current_stage, 'expected_close_date': expected_close_date, 'source_type': params_kw.get('source_type', 'manual').strip(), 'owner_id': owner_id, 'owner_name': owner_name, 'region': params_kw.get('region', '').strip(), 'description': params_kw.get('description', '').strip(), 'probability': float(params_kw.get('probability', '0').strip()) if params_kw.get('probability') else 0, 'predicted_revenue': float(params_kw.get('predicted_revenue', '0').strip()) if params_kw.get('predicted_revenue') else 0, 'status': params_kw.get('status', 'active').strip(), 'created_at': now, 'updated_at': now }) result = {'widgettype': 'Message', 'options': {'title': 'Success', 'message': '商机创建成功', 'type': 'success'}} except Exception as e: result['options'] = {'title': 'Error', 'message': f'创建失败: {str(e)}', 'type': 'error'} return json.dumps(result, ensure_ascii=False)