"""Bounded procurement knowledge retrieval and read-only demo ERP diagnosis. Reference cards are original summaries, never customer policy or executable text. """ import json import re import sqlite3 import uuid from contextlib import closing from datetime import datetime, timezone from pathlib import Path from src.modules.skill.domain.models import SkillError, digest CARDS = [ dict(id='PO-STATUS', title='采购订单完成、关闭与付款的区别', tags=['完成','状态','关闭','付款','订单'], text='采购订单 Completed 表示应收货和应开票部分已完成;Closed 表示剩余部分不再履行。付款结清需要另查采购发票未付金额,不能从订单完成状态推断。', steps=['采购员:核对采购订单的收货比例与开票比例。','仓管员:核对关联收货单及退货记录。','应付会计:另查关联发票未付金额,确认是否需要付款。'], url='https://docs.frappe.io/erpnext/purchase-order'), dict(id='PO-RECEIPT', title='采购到货与分批收货', tags=['到货','收货','验收','部分','入库','工序'], text='收货单承接供应商到货及接受数量。分批到货需保留与原采购订单行的关联,区分接受数量和拒收数量;记录仓库、单位和批次等适用信息。', steps=['仓管员:从已提交采购订单创建收货单并核对物料与计量单位。','质检员:按适用要求记录检验,分别处理接受与拒收数量。','仓管员:复核仓库和订单关联后提交收货单,再检查未收数量。'], url='https://docs.frappe.io/erpnext/purchase-receipt'), dict(id='PO-QUALITY', title='来料质量异常的处理依据', tags=['质检','检验','不合格','拒收','质量','退货'], text='质量检验可关联收货等单据,记录检验结果。是否强制检验以及接受标准由物料设置和企业规程决定;不能仅凭助手回答把不合格品标为合格。', steps=['质检员:定位关联收货单、物料与检验模板。','质检员:记录实测结果和不合格原因,提交有权限人员复核。','采购员与仓管员:依据企业规程选择隔离、拒收或退货并保留原单据关联。'], url='https://docs.frappe.io/erpnext/quality-inspection'), dict(id='PO-INVOICE', title='采购发票核对与待开票排查', tags=['开票','发票','对账','应付','三单','付款'], text='采购发票用于供应商应付记账。核对供应商、数量、价格、税额及关联订单和收货记录;付款状态与订单履行状态应分别查看。演示使用订单、收货、发票三类单据辅助核对。', steps=['应付会计:打开关联采购发票,核对订单和收货引用。','采购员与仓管员:对数量或价格差异查明原因,按企业审批规则处理。','应付会计:核对未付金额,进入经批准的付款流程。'], url='https://docs.frappe.io/erpnext/purchase-invoice'), ] for card in CARDS: card.update(version='demo-procurement-v1', retrieved_on='2026-10-23', source_type='official-public-documentation', quality_status='reference_not_enterprise_approved', license='Original paraphrase with source link; no source redistribution', applicable_system='ERPNext public documentation; customer ERP mapping pending') card['content_digest'] = digest(card) LATEST_SQL = '''SELECT * FROM demo_orders WHERE project_id=? AND status='COMPLETED' ORDER BY completed_at DESC,order_no DESC LIMIT ?''' class ERPAssistant: def __init__(self, path, project_access): self.path, self.project_access = Path(path), project_access self.path.parent.mkdir(parents=True, exist_ok=True) with closing(sqlite3.connect(self.path)) as db, db: db.executescript(''' CREATE TABLE IF NOT EXISTS demo_orders(project_id TEXT,order_no TEXT PRIMARY KEY,supplier TEXT, status TEXT,ordered_qty INTEGER,received_qty INTEGER,billed_qty INTEGER,outstanding_cents INTEGER,completed_at TEXT); CREATE TABLE IF NOT EXISTS assistant_audit(id TEXT PRIMARY KEY,at TEXT,actor TEXT,project TEXT,question_digest TEXT,result_digest TEXT); CREATE TABLE IF NOT EXISTS knowledge_cards(id TEXT PRIMARY KEY,body TEXT); ''') for card in CARDS: db.execute('INSERT OR REPLACE INTO knowledge_cards VALUES(?,?)',(card['id'],json.dumps(card,ensure_ascii=False))) for row in [ ('PO-2026-1001','模拟供应商·精工','COMPLETED',100,100,100,125000,'2026-10-23T14:30:00+08:00'), ('PO-2026-1002','模拟供应商·新材','COMPLETED',50,50,50,0,'2026-10-23T16:10:00+08:00'), ('PO-2026-1003','模拟供应商·机电','TO_RECEIVE',80,40,80,80000,None), ('PO-2026-1004','模拟供应商·辅料','TO_BILL',200,200,100,50000,None), ('PO-2026-1005','模拟供应商·新材','CLOSED',60,40,40,0,None), ('PO-2026-1006','模拟供应商·精工','COMPLETED',30,30,30,0,'2026-10-23T17:00:00+08:00')]: db.execute('INSERT OR IGNORE INTO demo_orders VALUES(?,?,?,?,?,?,?,?,?)',('erp-demo',*row)) def catalog(self, actor): self.project_access(actor,'erp-demo') with closing(sqlite3.connect(self.path)) as db: return [json.loads(row[0]) for row in db.execute('SELECT body FROM knowledge_cards ORDER BY id')] def ask(self, actor, question): self.project_access(actor,'erp-demo') if not isinstance(question,str) or not 2 <= len(question.strip()) <= 500: raise SkillError('QUESTION_INVALID','请输入2–500字的采购业务问题。') question=question.strip() cards=self.catalog(actor) ranked=sorted([(sum(tag in question for tag in c['tags']),c) for c in cards],key=lambda x:(-x[0],x[1]['id'])) citations=[c for score,c in ranked if score][:3] result={'mode':'knowledge-retrieval-and-rule-diagnosis','simulated_erp':True,'read_only':True, 'knowledge_version':'demo-procurement-v1','citations':citations,'orders':[], 'steps':[],'diagnosis':[],'query':None,'human_acceptance':False} if any(w in question.lower() for w in ['删除','更新数据库','执行sql','drop table','delete from']): result.update(answer='当前助手只提供采购流程参考和只读查询,不能修改业务单据。',intent='unsupported_write') else: order=re.search(r'(?0: actions.append(f"仍有未付金额 {row['outstanding_cents']/100:.2f} 元;应付会计核对付款计划。") if not actions: actions.append('本模拟快照未发现收货、开票或付款余额缺口。') result['diagnosis'].append({'order_no':row['order_no'],'actions':actions}) elif citations: result.update(intent='procedure_guidance',answer=citations[0]['text']) else: result.update(intent='needs_clarification',answer='当前知识范围是采购订单、收货验收、质量异常和采购发票。请补充业务环节或订单号;其他领域暂无依据。') result['steps']=list(dict.fromkeys(step for c in citations for step in c['steps']))[:6] result.update(audit_id='erp-'+uuid.uuid4().hex,queried_at=datetime.now(timezone.utc).isoformat(), boundary='演示参考规程,未经过企业业务负责人批准;查询与建议不会提交、审批或修改单据。') with closing(sqlite3.connect(self.path)) as db, db: db.execute('INSERT INTO assistant_audit VALUES(?,?,?,?,?,?)',(result['audit_id'],result['queried_at'],actor.user_id,'erp-demo',digest(question),digest(result))) return result