Metadata-Version: 2.4
Name: wecom-smartsheet
Version: 0.2.2
Summary: WeCom SmartSheet Python SDK with full CRUD operations support
Author: WeCom SmartSheet SDK Contributors
License: MIT
Project-URL: Homepage, https://github.com/yourusername/wecom-smartsheet
Project-URL: Documentation, https://github.com/yourusername/wecom-smartsheet#readme
Project-URL: Repository, https://github.com/yourusername/wecom-smartsheet
Project-URL: Bug Tracker, https://github.com/yourusername/wecom-smartsheet/issues
Keywords: wecom,wechat,smartsheet,enterprise,api,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# WeCom SmartSheet Python SDK

[![PyPI version](https://badge.fury.io/py/wecom-smartsheet.svg)](https://badge.fury.io/py/wecom-smartsheet)
[![Python Version](https://img.shields.io/pypi/pyversions/wecom-smartsheet.svg)](https://pypi.org/project/wecom-smartsheet/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

企业微信智能表格 Python SDK，提供完整的 CRUD 操作支持。

---

## ✨ 功能特性

- ✅ **完整的 CRUD 操作** - 读取、新增、更新、删除记录（支持单条/批量）
- ✅ **自动 Token 管理** - 自动获取、缓存和刷新 access_token
- ✅ **灵活的数据导出** - 支持 JSON 和 CSV 格式导出
- ✅ **命令行工具** - 提供 CLI 工具快速操作
- ✅ **零依赖** - 仅使用 Python 标准库

---

## 📦 安装

```bash
pip install wecom-smartsheet
```

**系统要求：** Python >= 3.10

---

## 🚀 快速开始

### 1️⃣ 获取配置参数

在使用前，你需要从企业微信管理后台获取以下参数：

| 参数 | 说明 | 获取位置 |
|------|------|----------|
| `corpid` | 企业 ID | 企业微信管理后台 → 我的企业 → 企业信息 |
| `corpsecret` | 应用密钥 | 企业微信管理后台 → 应用管理 → 自建应用 → Secret |
| `docid` | 文档 ID | 智能表格文档 URL 中的文档标识 |
| `sheet_id` | 工作表 ID | 智能表格中的工作表标识 |

### 2️⃣ 初始化客户端

```python
from wecom_smartsheet import WeComSmartSheetClient

client = WeComSmartSheetClient(
    corpid="your_corpid",        # 替换为你的企业 ID
    corpsecret="your_corpsecret"  # 替换为你的应用密钥
)
```

### 3️⃣ 基本操作

#### 📖 读取记录

```python
# 读取所有记录
records = client.fetch_records(
    docid="your_docid",
    sheet_id="your_sheet_id"
)

print(f"共读取 {len(records)} 条记录")
```

#### ➕ 新增记录

```python
# 新增单条记录
result = client.add_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    records={
        "values": {
            "字段1": [{"text": "值1", "type": "text"}],
            "字段2": [{"text": "值2", "type": "text"}]
        }
    }
)

print(f"新增成功，记录 ID: {result['record_ids'][0]}")
```

#### ✏️ 更新记录

```python
# 更新记录
result = client.update_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    records={
        "record_id": "rec123",  # 要更新的记录 ID
        "values": {
            "字段1": [{"text": "新值", "type": "text"}]
        }
    }
)

print("更新成功")
```

#### 🗑️ 删除记录

```python
# 删除记录
result = client.delete_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    record_ids="rec123"  # 要删除的记录 ID
)

print("删除成功")
```

---

## 💡 完整示例

```python
from wecom_smartsheet import WeComSmartSheetClient, WeComAPIError

# 初始化客户端
client = WeComSmartSheetClient(
    corpid="your_corpid",
    corpsecret="your_corpsecret"
)

try:
    # 1. 新增记录
    add_result = client.add_records(
        docid="your_docid",
        sheet_id="your_sheet_id",
        records={"values": {"姓名": [{"text": "张三", "type": "text"}]}}
    )
    new_record_id = add_result["record_ids"][0]
    print(f"✓ 新增成功: {new_record_id}")

    # 2. 读取记录
    records = client.fetch_records(
        docid="your_docid",
        sheet_id="your_sheet_id"
    )
    print(f"✓ 读取成功: 共 {len(records)} 条记录")

    # 3. 更新记录
    client.update_records(
        docid="your_docid",
        sheet_id="your_sheet_id",
        records={
            "record_id": new_record_id,
            "values": {"姓名": [{"text": "李四", "type": "text"}]}
        }
    )
    print("✓ 更新成功")

    # 4. 删除记录
    client.delete_records(
        docid="your_docid",
        sheet_id="your_sheet_id",
        record_ids=new_record_id
    )
    print("✓ 删除成功")

except ValueError as e:
    print(f"✗ 参数错误: {e}")
except WeComAPIError as e:
    print(f"✗ API 错误: {e}")
```

---

## 📚 高级用法

### 批量操作

```python
# 批量新增
result = client.add_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    records=[
        {"values": {"姓名": [{"text": "张三", "type": "text"}]}},
        {"values": {"姓名": [{"text": "李四", "type": "text"}]}},
        {"values": {"姓名": [{"text": "王五", "type": "text"}]}}
    ]
)

# 批量更新
result = client.update_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    records=[
        {"record_id": "rec1", "values": {"状态": [{"text": "已完成", "type": "text"}]}},
        {"record_id": "rec2", "values": {"状态": [{"text": "进行中", "type": "text"}]}}
    ]
)

# 批量删除
result = client.delete_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    record_ids=["rec1", "rec2", "rec3"]
)
```

### 数据导出

```python
# 导出为 JSON
client.fetch_records_to_json(
    docid="your_docid",
    sheet_id="your_sheet_id",
    output_path="output.json"
)

# 导出为 CSV（支持 Excel 打开）
client.fetch_records_to_csv(
    docid="your_docid",
    sheet_id="your_sheet_id",
    output_path="output.csv"
)
```

### 分页和过滤

```python
# 分页控制
records = client.fetch_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    page_size=100,        # 每页记录数
    max_pages=10,         # 最大页数
    pause_seconds=0.1     # 页面间暂停时间
)

# 使用视图过滤
records = client.fetch_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    view_id="your_view_id"  # 使用特定视图
)

# 扁平化数据格式
records = client.fetch_records(
    docid="your_docid",
    sheet_id="your_sheet_id",
    transform="flat"  # 将嵌套结构展平
)
```

---

## 🔧 API 参考

### `WeComSmartSheetClient`

#### 初始化

```python
client = WeComSmartSheetClient(
    corpid: str,           # 企业 ID
    corpsecret: str,       # 应用密钥
    timeout: int = 20      # 请求超时时间（秒）
)
```

#### 方法

| 方法 | 说明 | 返回值 |
|------|------|--------|
| `fetch_records()` | 读取记录 | `list[dict]` |
| `add_records()` | 新增记录 | `dict` (包含 record_ids) |
| `update_records()` | 更新记录 | `dict` |
| `delete_records()` | 删除记录 | `dict` |
| `fetch_records_to_json()` | 导出为 JSON | `None` |
| `fetch_records_to_csv()` | 导出为 CSV | `None` |

### 异常处理

```python
from wecom_smartsheet import WeComAPIError

try:
    result = client.add_records(...)
except ValueError as e:
    # 参数验证错误
    print(f"参数错误: {e}")
except WeComAPIError as e:
    # API 调用错误
    print(f"API 错误: {e}")
```

---

## 🖥️ 命令行工具

安装后可以使用 `wecom-smartsheet-fetch` 命令：

```bash
wecom-smartsheet-fetch --help
```

---

## 📝 更新日志

### v0.2.0 (2026-03-03)
- ✨ 新增 `add_records()` 方法（新增记录）
- ✨ 新增 `update_records()` 方法（更新记录）
- ✨ 新增 `delete_records()` 方法（删除记录）
- 📝 添加完整的使用示例和文档
- ✅ 23 个新增测试，测试覆盖率 100%

### v0.1.0 (2026-02-13)
- 🎉 初始版本
- ✨ 实现 `fetch_records()` 方法（读取记录）
- ✨ 支持 JSON 和 CSV 导出
- ✨ 提供命令行工具

---

## 🤝 贡献

欢迎提交 Issue 和 Pull Request！

---

## 📄 许可证

MIT License - 详见 [LICENSE](LICENSE) 文件

---

## 🔗 相关链接

- [PyPI 项目页面](https://pypi.org/project/wecom-smartsheet/)
- [企业微信开发文档](https://developer.work.weixin.qq.com/)
- [智能表格 API 文档](https://developer.work.weixin.qq.com/document/path/97465)

---

## ❓ 常见问题

### Q: 如何获取 docid 和 sheet_id？

A: 打开智能表格，查看浏览器地址栏的 URL，格式类似：
```
https://doc.weixin.qq.com/sheet/xxxxx?scode=xxxxx&tab=xxxxx
```
其中 `xxxxx` 部分就是 docid 和 sheet_id。

### Q: 字段值的格式是什么？

A: 企业微信智能表格的字段值需要使用特定的 JSON 格式：
```python
{"字段名": [{"text": "值", "type": "text"}]}
```

### Q: 支持哪些 Python 版本？

A: 支持 Python 3.10 及以上版本。

### Q: 有使用限制吗？

A: 请遵守企业微信 API 的调用频率限制，建议在批量操作时适当添加延迟。

---

**如有问题或建议，欢迎提交 Issue！** 🚀
