build_agent_patch.py 21.2 KB
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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
#!/usr/bin/env python3
"""Rebuild the reservation conversation flow on agent_chat_page.dart."""
import sys

PATH = 'lib/pages/agent/agent_chat_page.dart'

with open(PATH, 'r') as f:
    content = f.read()

# ============================================================
# BLOCK A: Add the entire reservation conversation code block
# Insert right before "Widget build(BuildContext context)" in _AgentChatPageState
# ============================================================

# Find where to insert the new methods
insert_marker = '\n  bool _usingCloudAsr = false;'
if insert_marker not in content:
    print("ERROR: insert_marker not found")
    sys.exit(1)

# The new state variables and methods to insert
new_block = '''
  /// ---- 预订会话式录入 ----
  ReservationImageParseResult? _pendingReservation;
  bool _reservationAwaitingConfirm = false;

  /// 辅助:图片/文字预订的必填字段是否齐全。
  bool _reservationRequiredComplete(ReservationImageParseResult result) {
    return result.name.isNotEmpty &&
        result.phone.isNotEmpty &&
        result.party.isNotEmpty &&
        result.date.isNotEmpty;
  }

  /// 合并两次解析结果:新解析的非空字段覆盖旧值。
  ReservationImageParseResult _mergeReservation(
    ReservationImageParseResult old,
    ReservationImageParseResult next,
  ) {
    return ReservationImageParseResult(
      name: next.name.isNotEmpty ? next.name : old.name,
      sex: next.sex.isNotEmpty ? next.sex : old.sex,
      phone: next.phone.isNotEmpty ? next.phone : old.phone,
      party: next.party.isNotEmpty ? next.party : old.party,
      date: next.date.isNotEmpty ? next.date : old.date,
      meal: next.meal.isNotEmpty ? next.meal : old.meal,
      time: next.time.isNotEmpty ? next.time : old.time,
      table: next.table.isNotEmpty ? next.table : old.table,
      remark: next.remark.isNotEmpty ? next.remark : old.remark,
      rawText: next.rawText.isNotEmpty ? next.rawText : old.rawText,
    );
  }

  /// 将相对日期转为未来具体日期。
  ReservationImageParseResult _normalizeReservationDate(ReservationImageParseResult result) {
    final DateTime now = DateTime.now();
    String date = result.date.trim();
    if (date.isEmpty) return result;

    if (date == '今天' || date == '今日') {
      date = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
    } else if (date == '明天' || date == '明日') {
      final DateTime t = now.add(const Duration(days: 1));
      date = '${t.year}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}';
    } else if (date == '后天') {
      final DateTime t = now.add(const Duration(days: 2));
      date = '${t.year}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}';
    } else if (RegExp(r'^\\d{1,2}月\\d{1,2}日$').hasMatch(date)) {
      final Match? m = RegExp(r'(\\d{1,2})月(\\d{1,2})日').firstMatch(date);
      if (m != null) {
        final int month = int.parse(m.group(1)!);
        final int day = int.parse(m.group(2)!);
        int year = now.year;
        final DateTime target = DateTime(year, month, day);
        if (target.isBefore(DateTime(now.year, now.month, now.day))) {
          year++;
        }
        date = '$year-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
      }
    }
    return ReservationImageParseResult(
      name: result.name, sex: result.sex, phone: result.phone,
      party: result.party, date: date, meal: result.meal,
      time: result.time, table: result.table, remark: result.remark,
      rawText: result.rawText,
    );
  }

  String _reservationIntro(ReservationImageParseResult result) {
    final List<String> parts = <String>[];
    if (result.name.isNotEmpty) parts.add('预订人: ${result.name}');
    if (result.phone.isNotEmpty) parts.add('电话: ${result.phone}');
    if (result.party.isNotEmpty) parts.add('人数: ${result.party}人');
    if (result.date.isNotEmpty) parts.add('日期: ${result.date}');
    if (parts.isEmpty) {
      return '我从截图中没有识别到完整的预订信息,咱们一起补全吧。\\n请告诉我预订人姓名、电话、人数和日期。';
    }
    return '我从截图中识别到以下信息,请核对:\\n${parts.join('\\n')}\\n\\n如有遗漏,直接回复补充即可。';
  }

  String _reservationSummaryText(ReservationImageParseResult result) {
    final List<String> parts = <String>[];
    if (result.name.isNotEmpty) parts.add('姓名: ${result.name}');
    if (result.phone.isNotEmpty) parts.add('电话: ${result.phone}');
    if (result.party.isNotEmpty) parts.add('人数: ${result.party}人');
    if (result.date.isNotEmpty) parts.add('日期: ${result.date}');
    if (result.meal.isNotEmpty) parts.add('时段: ${result.meal}');
    if (result.time.isNotEmpty) parts.add('到店时间: ${result.time}');
    if (result.table.isNotEmpty) parts.add('桌台: ${result.table}');
    return parts.join('\\n');
  }

  String _nextReservationQuestion(ReservationImageParseResult result) {
    final List<String> missing = <String>[];
    if (result.name.isEmpty) missing.add('预订人姓名');
    if (result.phone.isEmpty) missing.add('手机号');
    if (result.party.isEmpty) missing.add('用餐人数');
    if (result.date.isEmpty) missing.add('预订日期');
    if (missing.isEmpty) return '信息已经齐全啦,确认一下就可以录入。';
    return '还缺${missing.join('、')},直接回复我即可,例如"王先生 13800138000 8人 明晚"。';
  }

  _AgentCard _reservationDraftCard(ReservationImageParseResult result,
      {List<String> quickActions = const <String>[]}) {
    final List<String> actions = quickActions.isNotEmpty
        ? quickActions
        : const <String>['确认录入', '好了,没问题', '修改信息', '取消'];
    return _AgentCard(
      kind: _CardKind.reservationDraft,
      title: '预订信息草稿',
      items: <Map<String, dynamic>>[
        {'label': '姓名', 'value': result.name.isEmpty ? '待补充' : result.name},
        {'label': '电话', 'value': result.phone.isEmpty ? '待补充' : result.phone},
        {'label': '人数', 'value': result.party.isEmpty ? '待补充' : '${result.party}人'},
        {'label': '日期', 'value': result.date.isEmpty ? '待补充' : result.date},
        if (result.meal.isNotEmpty) {'label': '时段', 'value': result.meal},
        if (result.time.isNotEmpty) {'label': '到店时间', 'value': result.time},
        if (result.table.isNotEmpty) {'label': '桌台', 'value': result.table},
      ],
      quickActions: _reservationAwaitingConfirm ? actions : const <String>[],
    );
  }

  bool _isReservationConfirmText(String text) {
    final String trimmed = text.trim();
    if (RegExp(r'^(确认|确认录入|好了|好的|可以|可以录入|没问题|没问题了|录入|行|对|ok|yes)$', caseSensitive: false)
        .hasMatch(trimmed)) {
      return true;
    }
    if (trimmed.contains('确认') && !trimmed.contains('改') && !trimmed.contains('换') && !trimmed.contains('不是') && !trimmed.contains('错了')) {
      return true;
    }
    if ((trimmed.contains('好了') || trimmed.contains('没问题')) && !trimmed.contains('改') && !trimmed.contains('不是')) {
      return true;
    }
    return false;
  }

  bool _isModificationIntent(String text) {
    final String trimmed = text.trim();
    return trimmed == '修改信息' || trimmed == '修改' || trimmed == '改一下' || trimmed == '改' || trimmed == '我要修改' || trimmed == '需要修改';
  }

  String _describeChanges(ReservationImageParseResult before, ReservationImageParseResult after) {
    final List<String> fields = <String>[];
    if (after.name.isNotEmpty && after.name != before.name) fields.add('姓名');
    if (after.phone.isNotEmpty && after.phone != before.phone) fields.add('手机号');
    if (after.party.isNotEmpty && after.party != before.party) fields.add('人数');
    if (after.date.isNotEmpty && after.date != before.date) fields.add('日期');
    if (after.meal.isNotEmpty && after.meal != before.meal) fields.add('时段');
    if (after.time.isNotEmpty && after.time != before.time) fields.add('到店时间');
    if (after.table.isNotEmpty && after.table != before.table) fields.add('桌台');
    if (fields.isEmpty) return '';
    return fields.join('、');
  }

  Map<String, String> _reservationToFields(ReservationImageParseResult result) {
    return <String, String>{
      'name': result.name, 'sex': result.sex, 'phone': result.phone,
      'party': result.party, 'date': result.date, 'meal': result.meal,
      'time': result.time, 'table': result.table, 'remark': result.remark,
    };
  }

  Future<void> _startReservationConversation(ReservationImageParseResult result, {String? imagePath}) async {
    if (!mounted) return;
    _pendingReservation = _normalizeReservationDate(result);
    _reservationAwaitingConfirm = _reservationRequiredComplete(_pendingReservation!);
    setState(() {
      _messages.add(_ChatMessage(
        role: _Role.user,
        text: imagePath != null && imagePath.isNotEmpty ? '我发来一张预订截图' : '语音录入预订信息',
        imagePath: imagePath,
      ));
      _messages.add(_ChatMessage(
        role: _Role.agent,
        text: _reservationIntro(_pendingReservation!),
        card: _reservationDraftCard(_pendingReservation!),
      ));
    });
    _scrollToBottom();
    _persist();
  }

  Future<void> _handleReservationClarification(String text) async {
    final ReservationImageParseResult? current = _pendingReservation;
    if (current == null || !mounted) return;

    if (text.contains('取消') || text.contains('算了') || text.contains('不用')) {
      _pendingReservation = null;
      _reservationAwaitingConfirm = false;
      setState(() {
        _messages.add(_ChatMessage(role: _Role.user, text: text));
        _messages.add(_ChatMessage(role: _Role.agent, text: '好的,已取消这次预订录入。还想查什么随时问我~'));
      });
      _scrollToBottom();
      _persist();
      return;
    }

    setState(() { _messages.add(_ChatMessage(role: _Role.user, text: text)); });
    _scrollToBottom();
    _persist();

    if (_reservationAwaitingConfirm) {
      if (_isReservationConfirmText(text)) {
        _pendingReservation = null;
        _reservationAwaitingConfirm = false;
        setState(() {
          _messages.add(_ChatMessage(role: _Role.agent, text: '好嘞,这就帮你带入预订信息,请在下个页面最后提交一下 👇'));
        });
        _scrollToBottom();
        _persist();
        _openBookingWithFields(_reservationToFields(current));
        return;
      }

      if (_isModificationIntent(text)) {
        setState(() {
          _messages.add(_ChatMessage(role: _Role.agent,
            text: '好的,请问要修改哪一项?直接告诉我就行,比如"手机号改成138xxxx""姓名改成张三"。',
            card: _reservationDraftCard(current),
          ));
        });
        _scrollToBottom();
        _persist();
        return;
      }

      final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
      final bool hasUpdate = parsed.hasAny;
      final ReservationImageParseResult merged = _normalizeReservationDate(_mergeReservation(current, parsed));
      _pendingReservation = merged;
      _reservationAwaitingConfirm = _reservationRequiredComplete(merged);
      final String changed = hasUpdate ? _describeChanges(current, parsed) : '';
      setState(() {
        _messages.add(_ChatMessage(role: _Role.agent,
          text: hasUpdate
            ? (_reservationAwaitingConfirm ? '已修改$changed,确认无误回复"确认"即可录入。' : '已修改$changed,${_nextReservationQuestion(merged)}')
            : '没有识别到具体要修改的内容,能再说一遍吗?比如"手机号改成138xxxx""姓名改成张三"。',
          card: _reservationDraftCard(merged),
        ));
      });
      _scrollToBottom();
      _persist();
      return;
    }

    final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
    final ReservationImageParseResult merged = _normalizeReservationDate(_mergeReservation(current, parsed));
    if (_reservationRequiredComplete(merged)) {
      _pendingReservation = merged;
      _reservationAwaitingConfirm = true;
      setState(() {
        _messages.add(_ChatMessage(role: _Role.agent,
          text: '信息已经齐全:\\n${_reservationSummaryText(merged)}\\n\\n确认无误就回复"确认",我直接帮你录入;要修改哪一项也直接告诉我。',
          card: _reservationDraftCard(merged),
        ));
      });
      _scrollToBottom();
      _persist();
      return;
    }
    _pendingReservation = merged;
    _reservationAwaitingConfirm = false;
    setState(() {
      _messages.add(_ChatMessage(role: _Role.agent,
        text: _nextReservationQuestion(merged),
        card: _reservationDraftCard(merged),
      ));
    });
    _scrollToBottom();
    _persist();
  }

  void _maybeEnterReservationFlow(String text) {
    final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
    if (parsed.hasAny) {
      _startReservationConversation(parsed);
    }
  }

  // ---- 追问词条 & 卡片辅助 ----
  List<String> _followUpsFor(_CardKind kind) {
    switch (kind) {
      case _CardKind.kpi: return const <String>['昨天呢?', '近7天统计', '同比环比'];
      case _CardKind.tableList: return const <String>['今晚空桌呢?', '4人可用桌位', '桌位状态'];
      case _CardKind.bookingList: return const <String>['未确认的预订', '预订详情'];
      case _CardKind.orderList: return const <String>['支付状态', '指定桌位订单'];
      case _CardKind.dishRank: return const <String>['销量排行', '销售额排行', '滞销菜品'];
      case _CardKind.reservationDraft:
      case _CardKind.plain: return const <String>[];
    }
  }

  _AgentCard _withFollowUps(_AgentCard card) {
    return _AgentCard(
      kind: card.kind, title: card.title, items: card.items,
      followUps: _followUpsFor(card.kind), quickActions: card.quickActions,
    );
  }
'''

content = content.replace(insert_marker, new_block + insert_marker, 1)

# ============================================================
# BLOCK B: Update _toRecords serialization
# ============================================================
old_ser = "                'card': message.card == null\n            ? null\n            : <String, dynamic>{\n                'kind': _cardKindName(message.card!.kind),\n                'title': message.card!.title,\n                'items': message.card!.items,\n              },"
new_ser = "                'card': message.card == null\n            ? null\n            : <String, dynamic>{\n                'kind': _cardKindName(message.card!.kind),\n                'title': message.card!.title,\n                'items': message.card!.items,\n                'followUps': message.card!.followUps,\n                'quickActions': message.card!.quickActions,\n              },"
content = content.replace(old_ser, new_ser, 1)

# ============================================================
# BLOCK C: Update _CardView to support onAction + quickActions
# ============================================================
old_cv = '''class _CardView extends StatelessWidget {
  const _CardView({required this.card, required this.themeColor});

  final _AgentCard card;
  final Color themeColor;'''
new_cv = '''class _CardView extends StatelessWidget {
  const _CardView({required this.card, required this.themeColor, this.onAction});

  final _AgentCard card;
  final Color themeColor;
  final ValueChanged<String>? onAction;'''
content = content.replace(old_cv, new_cv, 1)

# Add quickActions buttons rendering - find the "点击查看详情" section base
old_detail_tap = '''          if (card.kind != _CardKind.plain) ...[
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '点击查看详情',
                  style: TextStyle(fontSize: 10, color: themeColor),
                ),
                const SizedBox(width: 2),
                Icon(Icons.chevron_right, size: 12, color: themeColor),
              ],
            ),
          ],'''
new_detail_tap = '''          if (card.quickActions.isNotEmpty && onAction != null) ...[
            const SizedBox(height: 10),
            Wrap(
              spacing: 6,
              runSpacing: 6,
              children: card.quickActions.map((String action) {
                final bool isPrimary = action.contains('确认') || action.contains('好了');
                return GestureDetector(
                  onTap: () => onAction?.call(action),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: isPrimary ? themeColor : themeColor.withValues(alpha: 0.10),
                      borderRadius: BorderRadius.circular(16),
                      border: isPrimary ? null : Border.all(color: themeColor.withValues(alpha: 0.25)),
                    ),
                    child: Text(action,
                      style: TextStyle(fontSize: 12, fontWeight: isPrimary ? FontWeight.w600 : FontWeight.w400,
                        color: isPrimary ? Colors.white : themeColor),
                    ),
                  ),
                );
              }).toList(),
            ),
          ],
          if (card.kind != _CardKind.plain) ...[
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '点击查看详情',
                  style: TextStyle(fontSize: 10, color: themeColor),
                ),
                const SizedBox(width: 2),
                Icon(Icons.chevron_right, size: 12, color: themeColor),
              ],
            ),
          ],'''
content = content.replace(old_detail_tap, new_detail_tap, 1)

# ============================================================
# BLOCK D: Update _MessageBubble to pass onAction + show image
# ============================================================
old_mb_card = '                child: _CardView(card: message.card!, themeColor: themeColor),'
new_mb_card = '                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),'
content = content.replace(old_mb_card, new_mb_card, 1)

# Add image display in _MessageBubble (before text content)
old_mb_content = '            _buildContent(textColor),'
new_mb_content = '''            if (message.imagePath != null && File(message.imagePath!).existsSync()) ...[
              Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.file(File(message.imagePath!), width: 180, height: 160, fit: BoxFit.cover),
                ),
              ),
            ],
            _buildContent(textColor),'''
content = content.replace(old_mb_content, new_mb_content, 1)

# Add followUps rendering in _MessageBubble after card
old_mb_postcard = '            if (message.card != null) ...['
new_mb_postcard = '''            if (message.card != null) ...[
              const SizedBox(height: 8),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) => _AgentCardDetailPage(card: message.card!, themeColor: themeColor),
                  ));
                },'''
content = content.replace(old_mb_postcard, new_mb_postcard, 1)

# Add followUps tags
if 'if (message.card != null)' in content:
    # We already changed the structure above. Now add followUps rendering after _CardView
    old_mb_aftercard = '                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),'
    new_mb_aftercard = '''                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),
              ),
            ],
            if (message.card != null && message.status == _MessageStatus.done && message.card!.followUps.isNotEmpty) ...[
              const SizedBox(height: 8),
              Wrap(
                spacing: 6,
                runSpacing: 6,
                children: message.card!.followUps.map((String item) {
                  return GestureDetector(
                    onTap: () => onSuggestion(item),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      decoration: BoxDecoration(
                        color: themeColor.withValues(alpha: 0.10),
                        borderRadius: BorderRadius.circular(14),
                        border: Border.all(color: themeColor.withValues(alpha: 0.18)),
                      ),
                      child: Text(item, style: TextStyle(fontSize: 12, color: themeColor)),
                    ),
                  );
                }).toList(),
              ),'''
    content = content.replace(old_mb_aftercard, new_mb_aftercard, 1)

with open(PATH, 'w') as f:
    f.write(content)
print(f"SUCCESS: All changes applied. Lines: {content.count(chr(10))}")