#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Contract create API""" import json, uuid, time result = {'widgettype': 'Message', 'options': {'title': 'Error', 'message': 'Invalid request', 'type': 'error'}} try: contract_number = params_kw.get('contract_number', '').strip() title = params_kw.get('title', '').strip() party_a = params_kw.get('party_a', '').strip() party_b = params_kw.get('party_b', '').strip() contract_type = params_kw.get('contract_type', '').strip() amount = params_kw.get('amount', '0').strip() start_date = params_kw.get('start_date', '').strip() or None end_date = params_kw.get('end_date', '').strip() or None owner_id = params_kw.get('owner_id', '').strip() if not contract_number or not title or not party_a or not party_b or not owner_id: result['options'] = {'title': 'Error', 'message': '请填写必填字段', 'type': 'error'} else: dbname = get_module_dbname('contract_management') new_id = str(uuid.uuid4()).replace('-', '') now = time.strftime('%Y-%m-%d %H:%M:%S') sign_date = params_kw.get('sign_date', '').strip() or None org_id = params_kw.get('org_id', '').strip() or 'org001' async with DBPools().sqlorContext(dbname) as sor: existing = await sor.sqlExe("SELECT id FROM contract WHERE contract_number = ${contract_number}$", {'contract_number': contract_number}) if existing: result['options'] = {'title': 'Error', 'message': '合同编号已存在', 'type': 'error'} else: await sor.sqlExe("""INSERT INTO contract (id, contract_number, title, party_a, party_b, contract_type, amount, start_date, end_date, sign_date, status, owner_id, org_id, created_at) VALUES (${id}$, ${contract_number}$, ${title}$, ${party_a}$, ${party_b}$, ${contract_type}$, ${amount}$, ${start_date}$, ${end_date}$, ${sign_date}$, ${status}$, ${owner_id}$, ${org_id}$, ${created_at}$)""", { 'id': new_id, 'contract_number': contract_number, 'title': title, 'party_a': party_a, 'party_b': party_b, 'contract_type': contract_type, 'amount': float(amount) if amount else 0, 'start_date': start_date, 'end_date': end_date, 'sign_date': sign_date, 'status': params_kw.get('status', 'draft').strip(), 'owner_id': owner_id, 'org_id': org_id, 'created_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)