Spaces:
Sleeping
Sleeping
Download src/modules/knowledge/erp_assistant.py from dellweb3/VibeCoding: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/knowledge/erp_assistant.py
- Command line
-
hf download hf://spaces/dellweb3/VibeCoding/src/modules/knowledge/erp_assistant.py
-
curl -L -o erp_assistant.py https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/knowledge/erp_assistant.py
10.5 kB
| """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'(?<![A-Za-z0-9-])PO-2026-\d{4}(?![A-Za-z0-9-])',question,re.I) | |
| unfinished=any(w in question for w in ['未完成','没完成','尚未完结']) and '订单' in question | |
| latest=any(w in question for w in ['最新','最近','查询','查一下','查找']) and '完成' in question and '订单' in question | |
| if order or latest or unfinished: | |
| if order: | |
| sql='SELECT * FROM demo_orders WHERE project_id=? AND order_no=?' | |
| params=['erp-demo',order.group().upper()] | |
| else: | |
| count=re.search(r'(\d+)\s*[笔条个张]',question) | |
| limit=int(count.group(1)) if count else 5 | |
| if not 1<=limit<=20: | |
| raise SkillError('QUERY_LIMIT','一次只能查询1–20笔订单。') | |
| sql= ("SELECT * FROM demo_orders WHERE project_id=? AND status IN ('TO_RECEIVE','TO_BILL') ORDER BY order_no DESC LIMIT ?" | |
| if unfinished else LATEST_SQL) | |
| params=['erp-demo',limit] | |
| with closing(sqlite3.connect(self.path)) as db: | |
| db.row_factory=sqlite3.Row | |
| db.execute('PRAGMA query_only=ON') | |
| result['orders']=[dict(row) for row in db.execute(sql,params)] | |
| result['query']={'template':sql,'parameters':params,'database':'local simulated SQLite ERP'} | |
| result['intent']='order_diagnosis' if order else 'unfinished_orders' if unfinished else 'latest_completed_orders' | |
| result['answer']=f"已从模拟 ERP 数据库实际读取 {len(result['orders'])} 笔订单。完成状态不代表付款结清。" | |
| if not citations: citations=[cards[-1]] | |
| status_card=next(c for c in cards if c['id']=='PO-STATUS') | |
| if status_card not in citations: citations=[status_card,*citations][:3] | |
| result['citations']=citations | |
| for row in result['orders']: | |
| actions=[] | |
| if row['status']=='CLOSED': actions.append('此订单为关闭,不能作为全部履行完成;检查关闭原因。') | |
| elif row['received_qty']<row['ordered_qty']: actions.append(f"仍有 {row['ordered_qty']-row['received_qty']} 件未收;仓管员核对在途与收货单。") | |
| if row['billed_qty']<row['received_qty']: actions.append('已收数量大于已开票数量;应付会计检查关联发票。') | |
| if row['outstanding_cents']>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 | |