waybill_api.py 22.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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
#!/usr/bin/env python3
"""
运单查询 API 模块
包含运单查询相关的所有函数
"""

import requests
import json
from .api_config import API_CONFIG


def _create_error_response(message: str, consignmentCode: str) -> str:
    """创建错误响应的辅助函数
    
    Args:
        message: 错误消息
        consignmentCode: 运单编号
    
    Returns:
        JSON格式的错误响应字符串
    """
    error_data = {
        "message": message,
        "consignmentCode": consignmentCode,
        "waybill_id": "",
        "operate_unit_name": "",
        "operate_unit_code": "",
        "detailList": []
    }
    return json.dumps(error_data, ensure_ascii=False, indent=2)


def create_waybill_d(consignmentCode: str, Authorization: str = None) -> str:
    """根据运单号创建D类运单
    
    Args:
        consignmentCode: 运单号(必填)
        Authorization: 授权令牌,如果提供则使用该值,否则使用 API_CONFIG 中的默认值
    
    Returns:
        创建结果信息(JSON字符串),包含:
        - message: 创建结果描述(成功时:"创建运单成功",失败时:具体的失败原因)
        - consignmentCode: 运单编号
        - waybill_id: 运单ID
        - consStatus: 运单状态
        - operate_unit_name: 操作单位名称
        - operate_unit_code: 操作单位代码
        - detailList: 明细列表
    """
    try:
        url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/createChmConsignmentD"
        
        # 构建请求数据
        data = {
            "consignmentCode": consignmentCode,
            "consignmentId": "",
            "isAIRecognition": 0
        }
        
        # 构建 headers,优先使用传入的 Authorization
        headers = dict(API_CONFIG['headers'])
        if Authorization:
            headers['Authorization'] = Authorization
        
        # 发送POST请求
        response = requests.post(
            url,
            headers=headers,
            json=data,
            timeout=30
        )
        
        # 检查响应状态
        if response.status_code != 200:
            return _create_error_response(
                f"创建运单失败: HTTP {response.status_code}, 错误信息: {response.text}",
                consignmentCode
            )

        result = response.json()

        # 添加调试信息
        print(f"创建D类运单API响应: {result}")

        # 业务状态判定(保守容错)
        if result.get('success') is False:
            error_msg = result.get('message', '未知错误')
            return _create_error_response(f"创建运单失败: {error_msg}", consignmentCode)

        # 提取新建的运单ID与编号
        data = result.get('data') or {}
        extra = data.get('extra') or {}
        waybill_id = extra.get('id')
        code = extra.get('consignmentCode') or consignmentCode or ""

        # 初始化返回数据
        result_data = {
            "consignmentCode": code,
            "waybill_id": str(waybill_id) if waybill_id else "",
            "consStatus": "",
            "operate_unit_name": "",
            "operate_unit_code": "",
            "detailList": []
        }

        # 若拿不到ID,直接返回空数据
        if not waybill_id:
            result_data["message"] = "创建运单失败:未获取到运单ID"
            return json.dumps(result_data, ensure_ascii=False, indent=2)

        # 请求表头详情获取 operate_unit_name 和 operate_unit_code
        head_url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/headInfo"
        try:
            head_resp = requests.post(
                head_url,
                headers=headers,
                json={"id": waybill_id},
                timeout=30,
            )
            if head_resp.status_code == 200:
                head_json = head_resp.json()
                head_extra = (head_json.get("data") or {}).get("extra") or {}
                result_data["consStatus"] = head_extra.get("consStatus") or ""
                result_data["operate_unit_name"] = head_extra.get("operateUnitName") or ""
                result_data["operate_unit_code"] = head_extra.get("operateUnitCode") or ""
        except Exception:
            pass

        # 请求表体明细获取所有商品明细(sku_code 和 sku_name)
        detail_url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/detail/list"
        try:
            detail_payload = {
                "consType": "consType_D",
                "consignmentId": waybill_id,
                "pageIndex": 1,
                "pageSize": 100,  # 增加页面大小以获取更多记录
            }
            detail_resp = requests.post(
                detail_url,
                headers=headers,
                json=detail_payload,
                timeout=30,
            )
            if detail_resp.status_code == 200:
                detail_json = detail_resp.json()
                records = (detail_json.get("data") or {}).get("records") or []
                if isinstance(records, list):
                    # 遍历所有记录,构建 detailList
                    for item in records:
                        if isinstance(item, dict):
                            detail_item = {
                                "sku_code": item.get("skuCode") or "",
                                "sku_name": item.get("skuName") or ""
                            }
                            result_data["detailList"].append(detail_item)
        except Exception:
            pass

        # 添加成功消息
        result_data["message"] = "创建运单成功"
        
        # 返回 JSON 格式数据
        return json.dumps(result_data, ensure_ascii=False, indent=2)
            
    except requests.exceptions.RequestException as e:
        return _create_error_response(f"创建运单失败: 网络请求失败 - {str(e)}", consignmentCode)
    except json.JSONDecodeError as e:
        return _create_error_response(f"创建运单失败: 响应解析失败 - {str(e)}", consignmentCode)
    except Exception as e:
        return _create_error_response(f"创建运单失败: {str(e)}", consignmentCode)


def create_waybill_d_with_id(
    consignmentCode: str,
    consignmentId: str,
    Authorization: str = None,
) -> str:
    """根据运单ID及运单号创建D类运单
    
    Args:
        consignmentCode: 运单号(必填)
        consignmentId: 运单ID(必填)
        Authorization: 授权令牌,如果提供则使用该值,否则使用 API_CONFIG 中的默认值
    
    Returns:
        创建结果,成功时返回序列化的JSON,失败时返回错误信息
    """
    try:
        url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/createChmConsignmentD/demo"
        
        # 构建请求数据
        data = {
            "consignmentCode": consignmentCode,
            "consignmentId": consignmentId,
            "isAIRecognition": 1,  # 写死为1
            "loginName": "CL1",  # 硬编码
            "userId": 73768  # 硬编码
        }
        
        # 构建 headers,优先使用传入的 Authorization
        headers = dict(API_CONFIG['headers'])
        if Authorization:
            headers['Authorization'] = Authorization
        
        # 发送POST请求
        response = requests.post(
            url,
            headers=headers,
            json=data,
            timeout=30
        )
        
        # 检查响应状态
        if response.status_code == 200:
            result = response.json()
            # 提取运单ID
            data = result.get('data') or {}
            extra = data.get('extra') or {}
            waybill_id = extra.get('id')
            if waybill_id is not None:
                # 返回包含 waybill_id 和 message 的JSON
                return json.dumps({
                    "waybill_id": waybill_id,
                    "message": "创建运单成功"
                }, ensure_ascii=False)
            return f"❌ 创建失败: 响应中未找到运单ID"
        return f"❌ 创建失败: HTTP {response.status_code}, 错误信息: {response.text}"
            
    except requests.exceptions.RequestException as e:
        return f"❌ 网络请求失败: {str(e)}"
    except json.JSONDecodeError as e:
        return f"❌ 响应解析失败: {str(e)}"
    except Exception as e:
        return f"❌ 创建D类运单失败: {str(e)}"


def query_waybill_info(consignmentCode: str, Authorization: str = None) -> str:
    """根据运单编号查询运单信息
    
    Args:
        consignmentCode: 运单编号(必填)
        Authorization: 授权令牌,如果提供则使用该值,否则使用 API_CONFIG 中的默认值
    
    Returns:
        运单信息(JSON字符串),包含:
        - message: 查询结果描述(成功时:"查询详情成功",失败时:具体的失败原因)
        - consignmentCode: 运单编号
        - waybill_id: 运单ID
        - consStatus: 运单状态
        - operate_unit_name: 操作单位名称
        - operate_unit_code: 操作单位代码
        - detailList: 明细列表
    """
    try:
        # 构建 headers,优先使用传入的 Authorization
        headers = dict(API_CONFIG['headers'])
        if Authorization:
            headers['Authorization'] = Authorization
        
        # 初始化返回数据
        result_data = {
            "consignmentCode": consignmentCode,
            "waybill_id": "",
            "consStatus": "",
            "operate_unit_name": "",
            "operate_unit_code": "",
            "detailList": []
        }
        
        # 请求表头详情,使用运单编号(chmCode)查询
        head_url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/headInfo"
        waybill_id = None
        cons_type_code = "consType_D"  # 默认值
        try:
            head_resp = requests.post(
                head_url,
                headers=headers,
                json={"chmCode": consignmentCode},
                timeout=30,
            )
            if head_resp.status_code == 200:
                head_json = head_resp.json()
                head_extra = (head_json.get("data") or {}).get("extra") or {}
                
                # 提取运单ID
                waybill_id = head_extra.get("id")
                
                # 提取运单编号(如果返回的与输入不一致,使用返回的)
                returned_code = head_extra.get("consignmentCode") or consignmentCode
                result_data["consignmentCode"] = returned_code
                result_data["waybill_id"] = str(waybill_id) if waybill_id else ""
                
                # 提取运单状态
                result_data["consStatus"] = head_extra.get("consStatus") or ""
                
                # 提取公司信息
                result_data["operate_unit_name"] = head_extra.get("operateUnitName") or ""
                result_data["operate_unit_code"] = head_extra.get("operateUnitCode") or ""
                
                # 提取运单类型(用于后续查询明细)
                cons_type_code = head_extra.get("consTypeDicCode") or "consType_D"
            else:
                return _create_error_response(
                    f"查询详情失败: HTTP {head_resp.status_code}, 错误信息: {head_resp.text}",
                    consignmentCode
                )
        except Exception as e:
            return _create_error_response(f"查询详情失败: 查询表头信息失败 - {str(e)}", consignmentCode)
        
        # 若拿不到ID,直接返回已有数据
        if not waybill_id:
            result_data["message"] = "查询详情失败:未获取到运单ID"
            return json.dumps(result_data, ensure_ascii=False, indent=2)
        
        # 请求表体明细获取所有商品明细(sku_code 和 sku_name)
        detail_url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/detail/list"
        try:
            detail_payload = {
                "consType": cons_type_code,
                "consignmentId": waybill_id,
                "pageIndex": 1,
                "pageSize": 100,  # 增加页面大小以获取更多记录
            }
            detail_resp = requests.post(
                detail_url,
                headers=headers,
                json=detail_payload,
                timeout=30,
            )
            if detail_resp.status_code == 200:
                detail_json = detail_resp.json()
                records = (detail_json.get("data") or {}).get("records") or []
                if isinstance(records, list):
                    # 遍历所有记录,构建 detailList
                    for item in records:
                        if isinstance(item, dict):
                            detail_item = {
                                "sku_code": item.get("skuCode") or "",
                                "sku_name": item.get("skuName") or ""
                            }
                            result_data["detailList"].append(detail_item)
        except Exception:
            pass
        
        # 添加成功消息
        result_data["message"] = "查询详情成功"
        
        # 返回 JSON 格式数据
        return json.dumps(result_data, ensure_ascii=False, indent=2)
            
    except requests.exceptions.RequestException as e:
        return _create_error_response(f"查询详情失败: 网络请求失败 - {str(e)}", consignmentCode)
    except json.JSONDecodeError as e:
        return _create_error_response(f"查询详情失败: 响应解析失败 - {str(e)}", consignmentCode)
    except Exception as e:
        return _create_error_response(f"查询详情失败: {str(e)}", consignmentCode)


def query_waybill_list(initialize: int = 1, consStatusName: str = "等待录入", Authorization: str = None) -> str:
    """查询运单列表信息
    
    Args:
        initialize: 初始化标志,默认为1
        consStatusName: 运单状态名称,默认为"等待录入"
        Authorization: 授权令牌,如果提供则使用该值,否则使用 API_CONFIG 中的默认值
    
    Returns:
        运单查询结果
    """
    try:
        url = f"{API_CONFIG['base_url']}{API_CONFIG['endpoint']}"
        
        # 构建请求数据
        data = {
            "consStatusName": consStatusName,
            "consTypeId": None,
            "consignmentCode": [],
            "endTime": None,
            "sender": None,
            "startTime": None,
            "initialize": initialize,
            "pageIndex": 1,
            "pageSize": 5,
            "total": 0
        }
        
        # 构建 headers,优先使用传入的 Authorization
        headers = dict(API_CONFIG['headers'])
        if Authorization:
            headers['Authorization'] = Authorization
        
        # 发送POST请求
        response = requests.post(
            url,
            headers=headers,
            json=data,
            timeout=30
        )
        
        # 检查响应状态
        if response.status_code == 200:
            result = response.json()
            
            # 添加调试信息
            print(f"API 响应结构: {type(result)}")
            print(f"响应内容: {result}")
            
            # 正确提取 records 数组
            data = result.get('data', {}).get('records', [])
            
            # 添加数据类型检查
            if not isinstance(data, list):
                return f"查询成功但数据格式错误: records 字段类型为 {type(data)},内容: {data}"
            
            if not data:
                return f"查询成功: 未找到状态为 '{consStatusName}' 的运单记录。"
            
            # 提取所需字段并返回 JSON 格式
            result_list = []
            for item in data:
                if isinstance(item, dict):
                    result_item = {
                        "consignmentCode": item.get('consignmentCode', ''),
                        "consType": item.get('consType', ''),
                        "consStatus": item.get('consStatus', ''),
                        "sender": item.get('sender', ''),
                        "createTime": item.get('createTime', '')
                    }
                    result_list.append(result_item)
            
            # 返回 JSON 格式数据
            return json.dumps(result_list, ensure_ascii=False, indent=2)
        else:
            return f"查询失败: HTTP {response.status_code}, 错误信息: {response.text}"
            
    except requests.exceptions.RequestException as e:
        return f"网络请求失败: {str(e)}"
    except json.JSONDecodeError as e:
        return f"响应解析失败: {str(e)}"
    except Exception as e:
        return f"查询运单失败: {str(e)}"


def get_waybill_head_info(waybill_id: int) -> str:
    """根据运单ID查询表头详情并返回指定字段
    
    Args:
        waybill_id: 运单ID(必填)
    
    Returns:
        格式化字符串:
        您好!运单号:XXXX\n
    \t公司信息\n
    \t发件人公司:XXXXX\n
    \t海关编码:XXXX
    """
    try:
        url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/headInfo"

        payload = {"id": waybill_id}

        response = requests.post(
            url,
            headers=API_CONFIG["headers"],
            json=payload,
            timeout=30,
        )

        if response.status_code != 200:
            return f"查询失败: HTTP {response.status_code}, 错误信息: {response.text}"

        result = response.json()

        # 容错解析:期望字段位于 data.extra
        data = result.get("data") or {}
        extra = data.get("extra") or {}

        consignment_code = extra.get("consignmentCode") or ""
        operate_unit_name = extra.get("operateUnitName") or ""
        operate_unit_code = extra.get("operateUnitCode") or ""

        return (
            f"您好!运单号:{consignment_code}\n"
            f"\t公司信息\n"
            f"\t发件人公司:{operate_unit_name}\n"
            f"\t海关编码:{operate_unit_code}"
        )

    except requests.exceptions.RequestException as e:
        return f"网络请求失败: {str(e)}"
    except json.JSONDecodeError as e:
        return f"响应解析失败: {str(e)}"
    except Exception as e:
        return f"查询表头详情失败: {str(e)}"


def get_waybill_detail_list(
    consignment_id: int,
    cons_type: str = "consType_D",
    page_index: int = 1,
    page_size: int = 5,
) -> str:
    """根据运单ID查询表体明细列表,仅返回 skuCode 与 skuName。

    Args:
        consignment_id: 运单ID(必填)。
        cons_type: 运单类型,默认 "consType_D"。
        page_index: 页码,默认 1。
        page_size: 每页数量,默认 5。

    Returns:
        多行文本:
        \t商品明细信息\n
        \t出口商品编码:XXXX\n
        \t中文品名:XXXX
        若数据为空,则两个字段均为空字符。
    """
    try:
        url = f"{API_CONFIG['base_url']}/Exp/bus-customer/consignment/detail/list"

        payload = {
            "consType": cons_type,
            "consignmentId": consignment_id,
            "pageIndex": page_index,
            "pageSize": page_size,
        }

        response = requests.post(
            url,
            headers=API_CONFIG["headers"],
            json=payload,
            timeout=30,
        )

        if response.status_code != 200:
            return f"查询失败: HTTP {response.status_code}, 错误信息: {response.text}"

        result = response.json()

        data = result.get("data") or {}
        records = data.get("records") or []

        # 若无记录,按需求返回空字段
        if not isinstance(records, list) or len(records) == 0:
            return (
                "\t商品明细信息\n"
                "\t出口商品编码:\n"
                "\t中文品名:"
            )

        # 拼接所有记录(每条记录两行)。如需仅返回第一条,可切片 records[:1]
        lines = ["\t商品明细信息"]
        for item in records:
            sku_code = item.get("skuCode") if isinstance(item, dict) else ""
            sku_name = item.get("skuName") if isinstance(item, dict) else ""
            lines.append(f"\t出口商品编码:{sku_code or ''}")
            lines.append(f"\t中文品名:{sku_name or ''}")

        return "\n".join(lines)

    except requests.exceptions.RequestException as e:
        return f"网络请求失败: {str(e)}"
    except json.JSONDecodeError as e:
        return f"响应解析失败: {str(e)}"
    except Exception as e:
        return f"查询表体明细失败: {str(e)}"


def push_waybill_for_ocr(waybill_id: int, Authorization: str = None) -> str:
    """根据运单ID推送OCR进行识别
    
    Args:
        waybill_id: 运单ID(必填)
        Authorization: 授权令牌,如果提供则使用该值,否则使用 API_CONFIG 中的默认值
    
    Returns:
        推送结果信息
    """
    try:
        url = f"{API_CONFIG['base_url']}/Exp/bus-customer/dataworksNew/vue/push/file"
        
        # 构建请求数据
        data = {
            "id": waybill_id
        }
        
        # 构建 headers,优先使用传入的 Authorization
        headers = dict(API_CONFIG['headers'])
        if Authorization:
            headers['Authorization'] = Authorization
        
        # 发送POST请求
        response = requests.post(
            url,
            headers=headers,
            json=data,
            timeout=30
        )
        
        # 检查响应状态
        if response.status_code != 200:
            return f"❌ 推送失败: HTTP {response.status_code}, 错误信息: {response.text}"
        
        result = response.json()
        
        # 添加调试信息
        print(f"推送OCR识别API响应: {result}")
        
        # 业务状态判定
        if result.get('success') is False:
            error_msg = result.get('message', '未知错误')
            return f"❌ 推送失败: {error_msg}"
        
        # 成功情况
        return f"✅ 运单ID {waybill_id} 已成功推送到OCR识别系统"
            
    except requests.exceptions.RequestException as e:
        return f"❌ 网络请求失败: {str(e)}"
    except json.JSONDecodeError as e:
        return f"❌ 响应解析失败: {str(e)}"
    except Exception as e:
        return f"❌ 推送OCR识别失败: {str(e)}"