File size: 17,718 Bytes
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""One business conversation controller for ERP, WMS and equipment MCP tools."""
import re
from datetime import datetime, timezone
from pathlib import Path

from src.adapters.mcp.erp_knowledge import MCPClient
from src.modules.knowledge.erp_mcp import PROJECTS, VERSION
from src.modules.skill.domain.models import SkillError


class ERPFlow:
    def __init__(self, identity, path):
        self.identity, self.path = identity, Path(path)

    def client(self, actor, scenario):
        if scenario not in PROJECTS:
            raise SkillError('SCENARIO_INVALID', '业务场景无效。')
        current = self.identity.actor(actor.user_id)
        if current.tenant_id != actor.tenant_id:
            raise SkillError('PROJECT_NOT_FOUND', '项目不存在或不可见。', 404)
        self.identity.project_access(current, PROJECTS[scenario])
        return MCPClient(self.path, self.identity.path, actor.user_id)

    def catalog(self, actor, scenario='erp'):
        exchange = self.client(actor, scenario).exchange([])
        return dict(scenario=scenario, project_id=PROJECTS[scenario], knowledge_version=VERSION,
                    simulated=True, health=exchange['health'],
                    tools=[t for t in exchange['tools'] if t['name'].startswith(scenario + '_') or t['name'] in ('knowledge_search', 'business_demo_reset')])

    @staticmethod
    def action(scenario, record, kind=None, quantity=None):
        if scenario == 'erp' and record['status'] == 'TO_RECEIVE':
            return dict(kind='receive', entity_id=record['entity_id'],
                        parameters={'quantity': record['ordered_qty'] - record['received_qty'] if quantity is None else quantity},
                        expected_version=record['version'], label='确认登记模拟收货')
        if scenario == 'wms':
            kind = kind or 'receive'
            return dict(kind=kind, entity_id=record['entity_id'], parameters={'quantity': 5 if quantity is None else quantity},
                        expected_version=record['version'], label='确认登记模拟' + ('出库' if kind == 'issue' else '入库'))
        if scenario == 'equipment' and record['status'] in ('OPEN', 'IN_PROGRESS'):
            next_kind = 'start' if record['status'] == 'OPEN' else 'complete'
            if kind is not None and kind != next_kind:
                return None
            kind = next_kind
            return dict(kind=kind, entity_id=record['entity_id'], parameters={}, expected_version=record['version'],
                        label='确认' + ('开始巡检' if kind == 'start' else '完成巡检'))
        return None

    def result(self, scenario, records, citations, exchange, action=None):
        return dict(scenario=scenario, project_id=PROJECTS[scenario], mode='mcp-knowledge-business-flow',
                    simulated_erp=True, simulated=True, read_only=True, knowledge_version=VERSION,
                    records=records, orders=records if scenario == 'erp' else [], citations=citations,
                    steps=list(dict.fromkeys(step for c in citations for step in c.get('steps', [])))[:6],
                    tool_calls=exchange['tool_calls'], connection=exchange['health'], action=action,
                    queried_at=datetime.now(timezone.utc).isoformat(), human_acceptance=False,
                    boundary='本地模拟业务知识库;操作仅影响当前用户的演示记录。')

    def ask(self, actor, question, scenario='erp'):
        client = self.client(actor, scenario)
        if not isinstance(question, str) or not 2 <= len(question.strip()) <= 500:
            raise SkillError('QUESTION_INVALID', '请输入2–500字的业务问题。')
        question = question.strip()
        calls = [('knowledge_search', {'scenario': scenario, 'question': question})]
        action_kind = quantity = None
        dangerous = bool(re.search(r'删除|执行\s*sql|drop\s+table|delete\s+from', question, re.I))
        payment = bool(re.search(r'付款|支付|转账', question, re.I))
        # Asking which orders remain unpaid is a supported query; requesting payment is not.
        unsupported = dangerous or (payment and not ('哪些' in question or '未付款' in question or '未付' in question or '没有付款' in question))
        negated_action = any(word in question for word in ('不要', '别再', '不必', '不需要', '无需', '禁止', '不能', '不应', '不允许', '不得', '不想', '不做', '不执行')) and any(
            word in question for word in ('收货', '入库', '出库', '增加', '减少', '扣减', '开始', '启动', '接单', '完成', '关闭', '完工', '结束', '修改', '更改', '变更', '操作'))
        negated_action = negated_action or any(word in question for word in ('仅查询', '只查询', '只查', '只读')) or bool(re.search(
            r'(?:不|别)(?:要|再|用|必|需(?:要)?|执行|进行|提交)?\s*(?:收货|入库|出库|增加|减少|扣减|开始|启动|接单|完成|关闭|完工)', question))
        ambiguous_action = False
        equipment_intent = None
        if scenario == 'erp':
            order = re.search(r'(?<![A-Za-z0-9-])PO-2026-\d{4}(?![A-Za-z0-9-])', question, re.I)
            if order:
                calls.append(('erp_order_get', {'order_no': order.group().upper()}))
            elif '订单' in question and any(word in question for word in ('查询', '查一下', '查找', '最新', '最近', '列出', '显示', '哪些', '未完成订单', '待收货订单')):
                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笔订单。')
                unfinished = any(w in question for w in ['未完成', '没完成', '待收货', '尚未完结'])
                calls.append(('erp_orders_list', {'filter': 'unfinished' if unfinished else 'completed', 'limit': limit}))
            operations = list(re.finditer(r'(收货|入库)(?:\s*([+-]?\d+(?:\.\d+)?))?', question))
            ambiguous_action = len(operations) > 1
            quantity = operations[0].group(2) if len(operations) == 1 else None
        elif scenario == 'wms':
            entity = re.search(r'SKU-[A-Z0-9-]+', question, re.I)
            calls.append(('wms_stock_get', {'sku': entity.group().upper() if entity else 'SKU-DEMO-001'}))
            # Direction and quantity must belong to the same verb occurrence.
            # Multiple operations or a negated clause require a separate user instruction.
            operations = list(re.finditer(r'(入库|出库|增加|减少|扣减)(?:\s*([+-]?\d+(?:\.\d+)?))?', question))
            ambiguous_action = len(operations) > 1
            if len(operations) == 1:
                operation = operations[0]
                action_kind = 'issue' if operation.group(1) in ('出库', '减少', '扣减') else 'receive'
                quantity = operation.group(2)
        else:
            entity = re.search(r'WO-[A-Z0-9-]+', question, re.I)
            calls.append(('equipment_work_order_get', {'work_order': entity.group().upper() if entity else 'WO-DEMO-001'}))
            starts = any(word in question for word in ('开始', '启动', '接单'))
            completes = any(word in question for word in ('完成巡检', '完成工单', '完成处理', '关闭工单', '完工', '结束巡检'))
            equipment_intent = 'workflow' if starts and completes else 'start' if starts else 'complete' if completes else None
            action_kind = equipment_intent if equipment_intent in ('start', 'complete') else None
        if quantity is not None and not (negated_action or ambiguous_action):
            if not re.fullmatch(r'\+?\d+', str(quantity)) or not 1 <= int(quantity) <= 1000000:
                raise SkillError('QUANTITY_INVALID', '操作数量必须为1–1000000的正整数。')
            quantity = int(quantity)
        exchange = client.exchange(calls)
        knowledge = exchange['results'][0]
        data = exchange['results'][1] if len(exchange['results']) > 1 else {}
        records = data.get('records', [data['record']] if 'record' in data else [])
        proposal = self.action(scenario, records[0], action_kind, quantity) if len(records) == 1 and not (unsupported or negated_action or ambiguous_action) else None
        if scenario == 'wms' and (action_kind is None or quantity is None):
            proposal = None
        if scenario == 'equipment' and equipment_intent is None:
            proposal = None
        result = self.result(scenario, records, knowledge['citations'], exchange, proposal)
        result['intent'] = 'unsupported_write' if unsupported else 'business_record_query'
        if unsupported:
            result['answer'] = '此场景支持查询、模拟收货、库存出入库和工单流转;不执行付款、删除或任意 SQL。'
        elif scenario == 'erp' and len(calls) == 1:
            matching = [card for card in knowledge['citations'] if any(tag in question for tag in card.get('tags', []))]
            result['citations'] = matching
            result['steps'] = list(dict.fromkeys(step for card in matching for step in card.get('steps', [])))[:6]
            result['intent'] = 'procedure_guidance' if matching else 'needs_clarification'
            result['answer'] = matching[0]['text'] if matching else '当前 ERP 知识范围为采购订单、收货验收、质量异常和发票核对;请补充相关业务环节或订单号。'
        elif scenario == 'erp':
            result['answer'] = f'已通过 MCP 从本地 ERP 知识库读取 {len(records)} 笔订单。完成状态与付款余额分别核对。'
            result['diagnosis'] = []
            for record in records:
                actions = []
                if record['received_qty'] < record['ordered_qty']:
                    actions.append(f"未收货 {record['ordered_qty'] - record['received_qty']} 件。")
                if record['billed_qty'] < record['received_qty']:
                    actions.append('已收数量大于已开票数量,需核对发票。')
                if record['outstanding_cents']:
                    actions.append(f"未付金额 {record['outstanding_cents'] / 100:.2f} 元。")
                result['diagnosis'].append({'order_no': record['order_no'], 'actions': actions or ['无收货、开票或付款余额缺口。']})
            if proposal:
                result['answer'] += f" {proposal['entity_id']} 可登记本次 {proposal['parameters']['quantity']} 件收货,确认后将更新知识记录并回读状态。"
                result['proposal'] = dict(order_no=proposal['entity_id'], quantity=proposal['parameters']['quantity'], expected_version=proposal['expected_version'])
        elif scenario == 'wms':
            result['answer'] = f"MCP 已读取 {records[0]['sku']},库存为 {records[0]['quantity']} 件,版本 {records[0]['version']}。"
            if proposal:
                result['answer'] += f"确认后登记{'出库' if action_kind == 'issue' else '入库'} {quantity} 件并回读库存。"
            elif action_kind and quantity is None and not (negated_action or ambiguous_action):
                result['answer'] += '请补充要登记的数量。'
            result['suggestions'] = ['SKU-DEMO-001 入库5件并复查', 'SKU-DEMO-001 出库3件并复查']
        else:
            state = records[0]['status']
            result['answer'] = f"MCP 已读取工单 {records[0]['work_order']},状态为 {state},版本 {records[0]['version']}。"
            if proposal:
                result['answer'] += '请确认当前工序,系统将更新并回读状态。'
            elif state == 'CLOSED':
                result['answer'] += '工单已关闭,不能重复开始或完成。'
            elif equipment_intent == 'complete' and state == 'OPEN':
                result['answer'] += '工单尚未开始;需先开始处理,再确认完成。当前没有提交任何变更。'
            elif equipment_intent == 'start' and state == 'IN_PROGRESS':
                result['answer'] += '工单已经开始处理,本次不会重复开始或自动完工。'
            else:
                result['answer'] += '已完成状态查询;需要处理时,请明确开始或完成工序。'
            result['suggestions'] = [f"{records[0]['work_order']} " + ('开始处理并复查状态' if state == 'OPEN' else '完成工单并复查状态')] if state != 'CLOSED' else []
        if negated_action or ambiguous_action:
            result['intent'] = 'read_only_ambiguous_action'
            result['answer'] += '本句包含否定或多个操作,仅查询记录,不创建可执行操作。需要变更时,请分步单独说明一项操作及数量。'
        return result

    def act(self, actor, scenario, action, entity_id, parameters, expected_version, request_key):
        client = self.client(actor, scenario)
        if not isinstance(parameters, dict):
            raise SkillError('ACTION_INVALID', '操作参数无效。')
        common = {'expected_version': expected_version, 'request_key': request_key}
        if scenario == 'erp' and action == 'receive' and set(parameters) == {'quantity'}:
            call = ('erp_receive_order', dict(common, order_no=entity_id, quantity=parameters['quantity']))
            read = ('erp_order_get', {'order_no': entity_id})
        elif scenario == 'wms' and action in ('receive', 'issue') and set(parameters) == {'quantity'}:
            call = ('wms_stock_adjust', dict(common, sku=entity_id, action=action, quantity=parameters['quantity']))
            read = ('wms_stock_get', {'sku': entity_id})
        elif scenario == 'equipment' and action in ('start', 'complete') and not parameters:
            call = ('equipment_work_order_transition', dict(common, work_order=entity_id, action=action))
            read = ('equipment_work_order_get', {'work_order': entity_id})
        else:
            raise SkillError('ACTION_INVALID', '操作不属于该场景批准范围。')
        exchange = client.exchange([call, read])
        changed, readback = exchange['results']
        record = readback['record']
        result = self.result(scenario, [record], [], exchange, self.action(scenario, record) if scenario == 'equipment' else None)
        superseded = record['version'] != changed['after']['version'] or record['content_digest'] != changed['after']['content_digest']
        result.update(before=changed['before'], after=changed['after'], readback=record,
                      replayed=changed['replayed'], request_key=request_key, read_only=False,
                      superseded=superseded, receipt_committed=True, readback_matches_receipt=not superseded,
                      persisted=not superseded,
                      audit_id=changed['audit_id'], answer=('此请求以前已执行;本次返回原操作回执,没有重复修改。' if changed['replayed'] else '模拟业务操作已持久保存。') + '已通过独立 MCP 查询回读。')
        if scenario == 'erp':
            result['answer'] += f"当次订单 {entity_id}:{changed['before']['status']} → {changed['after']['status']},累计收货 {changed['after']['received_qty']}/{changed['after']['ordered_qty']} 件。"
        elif scenario == 'wms':
            result['answer'] += f"当次库存 {entity_id}:{changed['before']['quantity']} → {changed['after']['quantity']} 件。"
        else:
            result['answer'] += f"当次工单 {entity_id}:{changed['before']['status']} → {changed['after']['status']}。"
        if superseded:
            result['answer'] += f"当前记录已被后续操作更新至版本 {record['version']},本次回执的版本为 {changed['after']['version']};请以当前回读记录为准。"
        return result

    def apply(self, actor, order_no, quantity, expected_version, request_key):
        return self.act(actor, 'erp', 'receive', order_no, {'quantity': quantity}, expected_version, request_key)

    def reset(self, actor, scenario, request_key):
        exchange = self.client(actor, scenario).exchange([('business_demo_reset', {'scenario': scenario, 'request_key': request_key})])
        changed = exchange['results'][0]
        # Read independently after committing the reset; never use the request's proposed state as evidence.
        question = {'erp': '查询 PO-2026-1003 的收货状态', 'wms': '查询 SKU-DEMO-001 库存',
                    'equipment': '查询 WO-DEMO-001 工单状态'}[scenario]
        result = self.ask(actor, question, scenario)
        receipt_records = {record['entity_id']: record for record in changed['after']}
        matches = all(record['content_digest'] == receipt_records[record['entity_id']]['content_digest'] for record in result['records'])
        result.update(answer=('该重置请求以前已执行;本次找回历史重置回执,没有再次重置。' if changed['replayed'] else '当前用户的演示场景已重置并回读,可再次操作;历史审计保留。') + ('当前记录已有后续变更,请以回读记录为准。' if not matches else ''),
                      before=changed['before'], after=changed['after'], replayed=changed['replayed'], read_only=False,
                      readback=result['records'], receipt_committed=True, readback_matches_receipt=matches,
                      superseded=not matches, persisted=matches,
                      request_key=request_key, tool_calls=exchange['tool_calls'] + result['tool_calls'])
        return result