Metadata-Version: 2.4
Name: py-chanjet-toolkit
Version: 3.0.1
Summary: 畅捷通 T+ Python 扩展包 / Chanjet T+ Python Extension - T+ 云 API 调用封装 / Chanjet T+ Cloud API client library
Author-email: 郭磊 <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2026 郭磊
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://gitee.com/guolei19850528/py_chanjet_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_chanjet_toolkit
Project-URL: Package, https://pypi.org/project/py-chanjet-toolkit/
Keywords: chanjet,tplus,chanjet-toolkit,tplus-toolkit,畅捷通,畅捷通T+,T+云API,tplus_api,soap,zkhb,enterprise
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Office/Business
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: cache
Requires-Dist: diskcache>=5.0.0; extra == "cache"
Requires-Dist: redis>=5.0.0; extra == "cache"
Provides-Extra: dev
Requires-Dist: ruff>=0.6.0; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.0; extra == "docs"
Requires-Dist: mkdocs-material>=9.0; extra == "docs"
Dynamic: license-file

# py-chanjet-toolkit

[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![PyPI](https://img.shields.io/badge/pypi-py--chanjet--toolkit-blue.svg)](https://pypi.org/project/py-chanjet-toolkit/)
[![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org/)

## 文档语言

- [中文 (README.md)](README.md)
- [English (README.en.md)](README.en.md)

## 介绍

**py-chanjet-toolkit** 是畅捷通 T+ 的 Python 扩展包，封装了畅捷通 T+ 云 API 的各类接口。

本包提供同步客户端 `ZKHBClient` 和异步客户端 `AsyncZKHBClient`，方法名完全一致，支持 `with` / `async with` 上下文管理器，让你极其简单地与畅捷通 T+ ZKHB SOAP Web Service 交互。无需手动拼接 URL，无需手动构建 SOAP XML 负载，支持同步和异步客户端。

### 核心特性

- **双模客户端**：同时提供同步（`ZKHBClient`）与异步（`AsyncZKHBClient`）客户端，方法名完全一致，支持 `with` / `async with` 上下文管理器。
- **ZKHB SOAP Web Service 封装**：基于 httpx + pydantic 实现，支持 SOAP 1.1 和 SOAP 1.2，提供 `GetDataSet` 接口执行 SQL 查询返回 DataSet。
- **同步与异步方法名一致**：异步客户端方法名与同步客户端完全一致。
- **SQL 构建工具**：提供 `build_charge_fee_items_query_sql` 构建收费多表关联查询 SQL。
- **数据过滤工具**：提供 `filter_charge_fee_items_data` 过滤收费数据，排除相同缴费周期且缴费和退费金额相等的记录。
- **基于 httpx**：底层 HTTP 客户端使用 httpx，支持同步与异步请求。

### 参考文档

- [畅捷通 T+](https://www.chanjet.com/)

## 软件架构

```
py_chanjet_toolkit/
├── README.md                   # 项目说明文档（中文）
├── README.en.md                # 项目说明文档（英文）
├── pyproject.toml              # 项目构建配置（PEP 621 / setuptools）
├── LICENSE                     # MIT 许可证
├── uv.lock                     # 依赖锁定文件
├── src/
│   └── py_chanjet_toolkit/     # 源代码包
│       ├── __init__.py         # 包入口
│       ├── py.typed            # PEP 561 类型标记
│       └── tplus/              # 子包，供他人调用
│           ├── __init__.py
│           └── zkhb/
│               ├── __init__.py
│               ├── client.py   # 同步客户端 ZKHBClient 与异步客户端 AsyncZKHBClient
│               └── models.py   # pydantic 响应模型
├── tests/                      # 测试用例
│   └── tplus/
│       └── zkhb/
│           ├── conftest.py     # 公共夹具（客户端、查询条件）
│           └── test_*.py       # 各接口的同步 / 异步测试用例
└── examples/                   # 演示代码
    └── tplus/
        └── zkhb/
            ├── __init__.py
            ├── example_*.py    # 各接口同步示例
            └── example_async_*.py  # 各接口异步示例
```

## 安装教程

推荐使用 [uv](https://github.com/astral-sh/uv) 进行安装：

### 1. 基础安装（推荐 uv）

```bash
uv pip install py_chanjet_toolkit
```

或从本地源码安装（开发模式）：

```bash
uv pip install -e .
```

### 2. 或者使用 pip 安装

```bash
pip install py_chanjet_toolkit
```

或从本地源码安装（开发模式）：

```bash
pip install -e .
```

开发模式安装（含测试依赖）：

```bash
# 使用 uv
uv sync --dev

# 或使用 pip
pip install -e ".[dev]"
```

## 使用说明

### 快速开始

#### ZKHB SOAP Web Service - GetDataSet (同步)

```python
from py_chanjet_toolkit.tplus.zkhb import ZKHBClient, ZKHBClientConfig

# 方式 1: 使用自定义配置
config = ZKHBClientConfig(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
    timeout=30.0,
    soap_version="1.1",  # 或 "1.2"
)

with ZKHBClient(config=config) as client:
    result = client.get_dataset("SELECT * FROM ChargeFee")
    if result.ok and result.data:
        for row in result.data.to_dict_list():
            print(row)
```

#### ZKHB SOAP Web Service - GetDataSet (异步)

```python
import asyncio
from py_chanjet_toolkit.tplus.zkhb import AsyncZKHBClient, ZKHBClientConfig

config = ZKHBClientConfig(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
    timeout=30.0,
    soap_version="1.1",  # 或 "1.2"
)

async def async_example():
    async with AsyncZKHBClient(config=config) as client:
        result = await client.get_dataset("SELECT * FROM ChargeFee")
        if result.ok and result.data:
            for row in result.data.to_dict_list():
                print(row)

asyncio.run(async_example())
```

### 返回结果说明

`get_dataset()` 返回 `ZKHBDataSetResponse` 对象，包含：
- `ok`: bool - 是否成功
- `data`: ZKHBGetDataSetResult - 结果数据（查询失败时为 None）

`ZKHBGetDataSetResult` 提供：
- `to_dict_list()` - 将 DataSet XML 转换为字典列表
- `schema_xml`: str - 表结构定义 XML
- `data_xml`: str - 原始数据 XML

`ZKHBDataSetResponse` 完整响应类：
- `ok`: bool - 是否成功
- `data`: ZKHBGetDataSetResult - 结果数据（查询失败时为 None）

### 创建客户端

```python
from py_chanjet_toolkit.tplus.zkhb import ZKHBClient, AsyncZKHBClient, ZKHBClientConfig

# 同步客户端
client = ZKHBClient(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
)

# 异步客户端
async_client = AsyncZKHBClient(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
)
```

推荐使用上下文管理器，自动管理 HTTP 连接池：

```python
with ZKHBClient(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
) as client:
    # 使用 client 调用接口
    pass

async with AsyncZKHBClient(
    base_url="http://your-server:port",
    endpoint_path="/estate/webService/ForcelandEstateService.asmx",
) as client:
    # 使用 client 调用接口
    pass
```

### ZKHBClientConfig 参数说明

配置类，支持以下参数：

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| base_url | str | 无 | SOAP 服务基础地址（如 `http://your-server:port`），需配置 |
| endpoint_path | str | 无 | 服务端点路径（如 `/estate/webService/ForcelandEstateService.asmx`），需配置 |
| timeout | float | 30.0 | 请求超时时间（秒） |
| verify_ssl | bool | False | 是否验证 SSL 证书 |
| soap_version | str | "1.1" | SOAP 版本，"1.1" 或 "1.2" |
| default_op | str | "GetDataSet" | 默认操作名 |

### SQL 构建工具函数

#### `build_charge_fee_items_query_sql(columns, conditions, order_by)`

生成查询实际支付项目的 SQL 语句，用于物业收费多表关联查询。

**参数：**
- `columns`: str - 额外查询列，添加到默认列前面（默认空）
- `conditions`: str - 查询条件，拼接到 WHERE 后（默认空）
- `order_by`: str - 排序方式（默认 `"order by cfi.ChargeFeeItemID"`）

**返回：**
- `str` - 完整 SQL 语句

**默认查询表关联：**
- `chargeMasterList` (cml) - 收费主列表（主表）
- `EstateDetail` (ed) - 小区详情
- `ChargeFeeItem` (cfi) - 收费项目
- `RoomDetail` (rd) - 房间详情
- `ChargeBillItem` (cbi) - 收费账单项目

**使用示例：**
```python
from py_chanjet_toolkit.tplus.zkhb import build_charge_fee_items_query_sql, ZKHBClient

# 生成查询某小区收费记录的 SQL
sql = build_charge_fee_items_query_sql(
    conditions="and cml.EstateID='E001' and cml.ChargeTime >= '2024-01-01'"
)

with ZKHBClient("http://your-server:port", "/estate/webService/ForcelandEstateService.asmx") as client:
    result = client.get_dataset(sql)
    for row in result.data.to_dict_list():
        print(row)
```

### 数据过滤工具函数

#### `filter_charge_fee_items_data(records)`

过滤收费数据，排除相同缴费周期且缴费和退费金额相等的数据。

**参数：**
- `records`: List[Dict] - 包含 ActualAmount、SDate、EDate 字段的记录列表

**返回：**
- `List[Dict]` - 过滤后的记录列表

**逻辑说明：**
- 按 (SDate, EDate) 缴费周期分组
- 在每个周期内，查找正数（缴费）和负数（退费）且金额绝对值相等的配对
- 将配对的数据全部排除
- 未配对的数据保留

**使用示例：**
```python
from py_chanjet_toolkit.tplus.zkhb import filter_charge_fee_items_data

raw_data = [
    {'ChargeMListID': '1', 'SDate': '2026-03-15', 'EDate': '2026-09-15', 'ActualAmount': '600.00'},
    {'ChargeMListID': '2', 'SDate': '2026-03-15', 'EDate': '2026-09-15', 'ActualAmount': '-600.00'},
    {'ChargeMListID': '3', 'SDate': '2026-03-15', 'EDate': '2026-09-15', 'ActualAmount': '600.00'},
]

filtered = filter_charge_fee_items_data(raw_data)
# 第1条和第2条被排除（同周期正负相等），第3条保留
print(len(filtered))  # 输出 2
```

## 示例代码 (`examples/`)

完整可运行示例位于 `examples/tplus/zkhb/`，覆盖全部接口的同步与异步调用，文件命名规则为 `example_*.py`（同步）与 `example_async_*.py`（异步）。

运行示例前，请复制模板并填写真实配置：

```bash
cp examples/tplus/zkhb/.env.example examples/tplus/zkhb/.env
```

运行示例（以客户端用法为例）：

```bash
python examples/tplus/zkhb/example_client_usage.py
python examples/tplus/zkhb/example_async_client_usage.py
```

公共配置与查询条件集中在示例文件中，统一从 `examples/tplus/zkhb/.env` 读取变量。

### 示例文件列表

| 同步示例 | 异步示例 | 说明 |
|----------|----------|------|
| `example_client_usage.py` | `example_async_client_usage.py` | 客户端用法 |
| `example_sql_build.py` | - | SQL 构建示例 |
| `example_full_workflow.py` | `example_async_full_workflow.py` | 完整工作流（配置加载 + SQL 构建 + 数据过滤 + 调用服务） |

## 测试 (`tests/`)

测试用例位于 `tests/tplus/zkhb/`，基于 pytest + pytest-asyncio，统一从 `tests/tplus/zkhb/.env` 读取配置，公共夹具定义在 `tests/tplus/zkhb/conftest.py`。

运行测试前，请复制模板并填写真实配置：

```bash
cp tests/tplus/zkhb/.env.example tests/tplus/zkhb/.env
```

安装测试依赖并运行：

```bash
uv pip install -e ".[dev]"
pytest tests/tplus/zkhb -q
```

或使用 pip：

```bash
pip install -e ".[dev]"
pytest tests/tplus/zkhb -q
```

### 测试文件列表

- `test_client.py` / `test_async_client.py`：客户端接口
- `test_sql.py`：SQL 构建测试

## 贡献指南

1. Fork 本仓库
2. 新建 `Feat_xxx` 分支
3. 提交代码
4. 新建 Pull Request

## 许可证

本项目采用 [MIT 许可证](LICENSE)。
