feat: 同步 LightCore 应用后台 CLI

This commit is contained in:
2026-11-20 04:02:32 +08:00
parent 3eb720cfbd
commit c19c26ec2c
12 changed files with 5477 additions and 45 deletions
+15 -5
View File
@@ -1,6 +1,6 @@
# LightCore CLI
LightCore CLI 提供 System、Media 和其他 LightCore 应用的后台命令。
LightCore CLI 提供 System、Media、Fangyus、恒德、GYSmart 和 Shop 的后台命令。
## 安装
@@ -13,6 +13,8 @@ lightcore --help
从已克隆的源码安装时,在仓库根目录运行 `python -m pip install .`。
更新到同一版本号的较新提交时,可在安装命令中加 `--force-reinstall`。
## 登录与会话
独立安装时,CLI 将各应用的会话存到用户目录下的 `.lightcore/lightcore-api/<应用>/.env`。例如 System 使用 `system/.env`,Media 使用 `media/.env`。从 LightCore 或相邻的 plan 工作区执行时,CLI 使用 LightCore 下的 `.work/lightcore-api/<应用>/.env`。可在应用名后传 `--env-file` 指定会话文件,登录和后续命令使用同一路径。
@@ -75,15 +77,23 @@ lightcore media contents save --body-file .work/content.json
lightcore media videos download --video-id 58 --file-id 123 --output .work/参考图.png
```
## 通用 HTTP
## Fangyus、恒德、GYSmart 和 Shop
其他应用可通过 `lightcore api` 调用。按应用契约填写后台相对路径和 JSON。不同应用使用各自会话。
使用各应用后台账号登录。要同时操作不同部署,为每个目标指定独立的 `--env-file`。离线查看命令用法、请求形状和示例无需登录。
```text
lightcore api login --app gysmart
lightcore api request --app gysmart --path /product/getList --body-file .work/products-query.json
lightcore fangyus --env-file .work/fangyus-local.env login --base-url http://localhost:8888
lightcore fangyus --env-file .work/fangyus-local.env article create --body-file .work/article.json --dry-run
lightcore hengde --help
lightcore gysmart email save-config --schema
lightcore shop crm catalog product apply --schema
lightcore shop file upload --file .work/product.png --body-file .work/upload.json
```
Shop 提供展厅、公共文件、抖音生活服务、内容及渠道、CRM 和商城。Plan 与 Apply 的请求形状分别通过各自的 `--schema` 查看。请求超时后先用原 `requestId` 查回执,或凭请求号核对操作结果。商城视觉包还需要当前源码构建的根 `light` 和宿主机 Chromium,可用 `--renderer` 指定 `light` 路径。
也可使用 `lightcore api` 按应用契约调用后台相对路径。
从当前工作目录接收 `responseFile` 摘要时,读取 CLI 返回的完整响应文件以获取截断部分。
## 测试
+36
View File
@@ -0,0 +1,36 @@
"""Named commands for the individual application admin APIs."""
from . import fangyus_routes, gysmart_routes, hengde_routes, shop_routes
from .system_commands import add_operation
APPLICATIONS = {
"fangyus": ("Fangyus 后台操作", fangyus_routes.ROUTES),
"hengde": ("恒德后台操作", hengde_routes.ROUTES),
"gysmart": ("GYSmart 后台操作", gysmart_routes.ROUTES),
"shop": ("Shop 业务管理", shop_routes.ROUTES),
}
def add_commands(commands, app):
login = commands.add_parser("login", help="交互登录并保存本机会话")
login.add_argument("--base-url", help="目标后端地址")
login.set_defaults(handler=lambda client, args: client.login(args.base_url, isolate_target=True), endpoint="/auth/login")
if app != "gysmart":
for name, description, handler in (
("refresh", "刷新本机会话", lambda client, _: client.refresh()),
("logout", "退出并清理本机 Token", lambda client, _: client.logout()),
):
auth = commands.add_parser(name, help=description)
auth.set_defaults(handler=handler, endpoint=f"/auth/{name}")
subcommands = {(): commands}
for group, operations in APPLICATIONS[app][1].items():
path = tuple(group.split())
for index, part in enumerate(path, start=1):
prefix = path[:index]
if prefix not in subcommands:
section = subcommands[prefix[:-1]].add_parser(part, help=f"{part} 管理")
subcommands[prefix] = section.add_subparsers(required=True)
actions = subcommands[path]
for action, (route, schema, mode) in operations.items():
add_operation(actions, None, action, route, route, None, mode, schema=schema)
+4 -1
View File
@@ -3,7 +3,7 @@ from pathlib import Path
import subprocess
import sys
from . import api, media, media_commands, system_commands
from . import api, application_commands, media, media_commands, system_commands
from .system_client import SystemClient
from .transport import Client, ClientError, compact
@@ -56,6 +56,9 @@ def parser():
media_commands.add_commands(commands, media.add_file_commands(commands))
system = apps.add_parser("system", help="System 后台操作")
system_commands.add_commands(app_options(system, "system"))
for name, (description, _) in application_commands.APPLICATIONS.items():
app = apps.add_parser(name, help=description)
application_commands.add_commands(app_options(app, name), name)
return root
+344
View File
@@ -0,0 +1,344 @@
"""Named fangyus admin API operations and request schemas."""
ROUTES = {
'account': {
'create': (
'/account/create',
{'properties': {'displayName': {'maxLength': 50, 'type': 'string'},
'password': {'minLength': 8, 'type': 'string'},
'username': {'maxLength': 50, 'minLength': 3, 'type': 'string'}},
'required': ['username', 'password', 'displayName'],
'type': 'object'},
None,
),
'delete': (
'/account/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/account/getList',
{'properties': {'keyword': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'role': {'type': 'string'},
'status': {'type': 'string'}},
'required': ['pageNo', 'pageSize'],
'type': 'object'},
None,
),
'reset-password': (
'/account/resetPassword',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'password': {'minLength': 8, 'type': 'string'}},
'required': ['id', 'password'],
'type': 'object'},
None,
),
'update-status': (
'/account/updateStatus',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'status': {'enum': ['enabled', 'disabled'], 'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'article': {
'create': (
'/article/create',
{'properties': {'author': {'type': 'string'},
'category': {'type': 'string'},
'contentHtml': {'maxLength': 2097152, 'type': 'string'},
'description': {'type': 'string'},
'dryRun': {'type': 'boolean'},
'keywords': {'items': {'type': 'string'}, 'type': 'array'},
'seoTitle': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'},
'title': {'maxLength': 160, 'type': 'string'}},
'required': ['category', 'title', 'contentHtml'],
'type': 'object'},
None,
),
'delete': (
'/article/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get': (
'/article/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/article/getList',
{'properties': {'category': {'type': 'string'},
'keyword': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/article/save',
{'properties': {'author': {'maxLength': 64, 'type': 'string'},
'category': {'enum': ['firm_news', 'industry_news', 'case_study',
'legal_education', 'professional_view'],
'type': 'string'},
'contentHtml': {'type': 'string'},
'description': {'maxLength': 320, 'type': 'string'},
'heroImage': {'type': 'string'},
'id': {'type': 'integer'},
'keywords': {'items': {'type': 'string'}, 'type': 'array'},
'seoTitle': {'maxLength': 160, 'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'},
'title': {'maxLength': 160, 'type': 'string'}},
'required': ['category', 'title', 'status'],
'type': 'object'},
None,
),
'update-status': (
'/article/updateStatus',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'auth': {
'change-password': (
'/auth/changePassword',
{'properties': {'newPassword': {'minLength': 8, 'type': 'string'},
'oldPassword': {'type': 'string'}},
'required': ['oldPassword', 'newPassword'],
'type': 'object'},
None,
),
'info': (
'/auth/info',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'update-profile': (
'/auth/updateProfile',
{'properties': {'displayName': {'maxLength': 50, 'type': 'string'}},
'required': ['displayName'],
'type': 'object'},
None,
),
},
'consultation': {
'delete': (
'/consultation/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get': (
'/consultation/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/consultation/getList',
{'properties': {'keyword': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'practiceArea': {'type': 'string'},
'status': {'type': 'string'}},
'required': ['pageNo', 'pageSize'],
'type': 'object'},
None,
),
'update-remark': (
'/consultation/updateRemark',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'remark': {'maxLength': 500, 'type': 'string'}},
'required': ['id'],
'type': 'object'},
None,
),
'update-status': (
'/consultation/updateStatus',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'remark': {'maxLength': 500, 'type': 'string'},
'status': {'enum': ['new', 'contacted', 'invalid', 'closed'],
'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'lawyer': {
'delete': (
'/lawyer/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get': (
'/lawyer/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/lawyer/getList',
{'properties': {'practiceAreaId': {'type': 'integer'}, 'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/lawyer/save',
{'properties': {'biographyHtml': {'type': 'string'},
'education': {'items': {'type': 'string'}, 'type': 'array'},
'email': {'maxLength': 160, 'type': 'string'},
'id': {'type': 'integer'},
'introduction': {'maxLength': 500, 'type': 'string'},
'languages': {'items': {'type': 'string'}, 'type': 'array'},
'name': {'maxLength': 80, 'type': 'string'},
'photo': {'type': 'string'},
'position': {'maxLength': 120, 'type': 'string'},
'practiceAreaIds': {'items': {'type': 'integer'}, 'type': 'array'},
'representativeMatters': {'items': {'type': 'string'}, 'type': 'array'},
'seoTitle': {'maxLength': 160, 'type': 'string'},
'slug': {'maxLength': 160, 'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'}},
'required': ['slug', 'name', 'status'],
'type': 'object'},
None,
),
},
'page': {
'delete': (
'/page/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get': (
'/page/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/page/getList',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'save': (
'/page/save',
{'properties': {'contentHtml': {'type': 'string'},
'heroImage': {'type': 'string'},
'id': {'type': 'integer'},
'key': {'maxLength': 80, 'type': 'string'},
'seoDescription': {'maxLength': 320, 'type': 'string'},
'seoTitle': {'maxLength': 160, 'type': 'string'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'},
'subtitle': {'maxLength': 240, 'type': 'string'},
'title': {'maxLength': 160, 'type': 'string'}},
'required': ['key', 'title', 'status'],
'type': 'object'},
None,
),
},
'practice-area': {
'delete': (
'/practiceArea/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get': (
'/practiceArea/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/practiceArea/getList',
{'properties': {'status': {'type': 'string'}}, 'required': [], 'type': 'object'},
None,
),
'save': (
'/practiceArea/save',
{'properties': {'contentHtml': {'type': 'string'},
'heroImage': {'type': 'string'},
'icon': {'maxLength': 64, 'type': 'string'},
'id': {'type': 'integer'},
'name': {'maxLength': 120, 'type': 'string'},
'seoTitle': {'maxLength': 160, 'type': 'string'},
'slug': {'maxLength': 160, 'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'enum': ['draft', 'published', 'archived'], 'type': 'string'},
'summary': {'maxLength': 500, 'type': 'string'}},
'required': ['slug', 'name', 'status'],
'type': 'object'},
None,
),
},
'site': {
'get': (
'/site/get',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'save': (
'/site/save',
{'properties': {'address': {'maxLength': 320, 'type': 'string'},
'businessHours': {'maxLength': 120, 'type': 'string'},
'email': {'maxLength': 160, 'type': 'string'},
'firmName': {'maxLength': 160, 'type': 'string'},
'heroImage': {'type': 'string'},
'icpNumber': {'maxLength': 80, 'type': 'string'},
'introduction': {'type': 'string'},
'logo': {'type': 'string'},
'phone': {'maxLength': 40, 'type': 'string'},
'publicSecurityNumber': {'maxLength': 80, 'type': 'string'},
'seoDescription': {'maxLength': 320, 'type': 'string'},
'shortName': {'maxLength': 80, 'type': 'string'},
'slogan': {'maxLength': 200, 'type': 'string'},
'wechatQrCode': {'type': 'string'}},
'required': ['firmName', 'shortName'],
'type': 'object'},
None,
),
},
'storage': {
'download-from-url': (
'/storage/downloadFromUrl',
{'properties': {'url': {'maxLength': 2048, 'type': 'string'}},
'required': ['url'],
'type': 'object'},
None,
),
'get-config': (
'/storage/getConfig',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'register-external-image': (
'/storage/registerExternalImage',
{'properties': {'url': {'maxLength': 2048, 'type': 'string'}},
'required': ['url'],
'type': 'object'},
None,
),
'save-config': (
'/storage/saveConfig',
{'properties': {'bucket': {'maxLength': 120, 'type': 'string'},
'clientSecret': {'maxLength': 255, 'type': 'string'}},
'required': ['bucket'],
'type': 'object'},
None,
),
'upload-image': (
'/storage/uploadImage',
{'properties': {'file': {'format': 'binary', 'type': 'string'}},
'required': ['file'],
'type': 'object'},
'upload',
),
},
}
+525
View File
@@ -0,0 +1,525 @@
"""Named gysmart admin API operations and request schemas."""
ROUTES = {
'admin': {
'disable': (
'/admin/disable',
{'properties': {'id': {'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/admin/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/admin/save',
{'properties': {'displayName': {'type': 'string'},
'id': {'type': 'integer'},
'password': {'type': 'string'},
'role': {'type': 'string'},
'username': {'type': 'string'}},
'required': ['username', 'displayName', 'role'],
'type': 'object'},
None,
),
},
'agent-credential': {
'disable': (
'/agentCredential/disable',
{'properties': {'id': {'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/agentCredential/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/agentCredential/save',
{'properties': {'active': {'type': 'boolean'},
'id': {'type': 'integer'},
'name': {'type': 'string'},
'scopes': {'items': {'type': 'string'}, 'type': 'array'},
'token': {'type': 'string'}},
'required': ['name'],
'type': 'object'},
'private-output',
),
},
'agent-draft': {
'approve': (
'/agentDraft/approve',
{'properties': {'id': {'type': 'integer'}, 'version': {'type': 'integer'}},
'required': ['id'],
'type': 'object'},
None,
),
'list': (
'/agentDraft/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'reject': (
'/agentDraft/reject',
{'properties': {'id': {'type': 'integer'}, 'version': {'type': 'integer'}},
'required': ['id'],
'type': 'object'},
None,
),
'save': (
'/agentDraft/save',
{'properties': {'baseVersion': {'type': 'integer'},
'entityId': {'type': 'integer'},
'entityType': {'type': 'string'},
'idempotencyKey': {'type': 'string'},
'operation': {'type': 'string'},
'payload': {}},
'required': ['entityType', 'operation', 'idempotencyKey'],
'type': 'object'},
None,
),
},
'audit': {
'list': (
'/audit/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
},
'auth': {
'change-password': (
'/auth/changePassword',
{'properties': {'newPassword': {'minLength': 8, 'type': 'string'},
'oldPassword': {'type': 'string'}},
'required': ['oldPassword', 'newPassword'],
'type': 'object'},
None,
),
},
'category': {
'list': (
'/category/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/category/save',
{'properties': {'id': {'type': 'integer'},
'image': {'type': 'string'},
'names': {'additionalProperties': {'type': 'string'}, 'type': 'object'},
'parentId': {'type': 'integer'},
'published': {'type': 'boolean'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
},
'content': {
'list': (
'/content/getList',
{'properties': {'kind': {'type': 'string'},
'language': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'publish': (
'/content/publish',
{'properties': {'id': {'type': 'integer'}, 'version': {'type': 'integer'}},
'required': ['id'],
'type': 'object'},
None,
),
'save': (
'/content/save',
{'properties': {'bodyHtml': {'type': 'string'},
'id': {'type': 'integer'},
'kind': {'type': 'string'},
'language': {'type': 'string'},
'pageId': {'type': 'integer'},
'seoDescription': {'type': 'string'},
'slug': {'type': 'string'},
'title': {'type': 'string'},
'version': {'type': 'integer'}},
'required': ['slug', 'kind', 'language', 'title'],
'type': 'object'},
None,
),
},
'coupon': {
'list': (
'/coupon/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/coupon/save',
{'properties': {'active': {'type': 'boolean'},
'code': {'type': 'string'},
'discountType': {'type': 'string'},
'endsAt': {'format': 'date-time', 'type': 'string'},
'id': {'type': 'integer'},
'minSubtotal': {'type': 'integer'},
'startsAt': {'format': 'date-time', 'type': 'string'},
'usageLimit': {'type': 'integer'},
'usedCount': {'type': 'integer'},
'value': {'type': 'integer'}},
'required': ['code', 'discountType'],
'type': 'object'},
None,
),
},
'dashboard': {
'get-stats': (
'/dashboard/getStats',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
},
'email': {
'get-provider-status': (
'/email/getProviderStatus',
{'properties': {'id': {'type': 'string'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/email/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'retry': (
'/email/retry',
{'properties': {'id': {'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'save-config': (
'/email/saveConfig',
{'properties': {'apiKey': {'maxLength': 4096, 'type': 'string'}},
'required': ['apiKey'],
'type': 'object'},
None,
),
'send-test': (
'/email/sendTest',
{'properties': {'idempotencyKey': {'type': 'string'},
'to': {'format': 'email', 'type': 'string'}},
'required': ['to', 'idempotencyKey'],
'type': 'object'},
None,
),
},
'exchange-rate': {
'list': (
'/exchangeRate/getList',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'save': (
'/exchangeRate/save',
{'properties': {'currency': {'type': 'string'},
'enabled': {'type': 'boolean'},
'expectedVersion': {'type': 'integer'},
'unitsPerUsd': {'type': 'string'}},
'required': ['currency'],
'type': 'object'},
None,
),
},
'fulfillment': {
'list': (
'/fulfillment/getList',
{'properties': {'orderId': {'type': 'integer'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/fulfillment/save',
{'properties': {'carrier': {'type': 'string'},
'deliveredAt': {'format': 'date-time', 'type': 'string'},
'id': {'type': 'integer'},
'orderId': {'type': 'integer'},
'shippedAt': {'format': 'date-time', 'type': 'string'},
'status': {'type': 'string'},
'trackingNumber': {'type': 'string'}},
'required': ['orderId', 'status'],
'type': 'object'},
None,
),
},
'inquiry': {
'list': (
'/inquiry/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'update-status': (
'/inquiry/updateStatus',
{'properties': {'id': {'type': 'integer'}, 'status': {'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'order': {
'list': (
'/order/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'update-status': (
'/order/updateStatus',
{'properties': {'id': {'type': 'integer'}, 'status': {'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'product': {
'adjust-inventory': (
'/product/adjustInventory',
{'properties': {'adjustments': {'items': {'properties': {'expectedVersion': {'type': 'integer'},
'mode': {'type': 'string'},
'quantity': {'type': 'integer'},
'skuId': {'type': 'integer'}},
'required': [],
'type': 'object'},
'type': 'array'},
'idempotencyKey': {'type': 'string'},
'productId': {'type': 'integer'},
'reason': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
'archive': (
'/product/archive',
{'properties': {'expectedVersion': {'type': 'integer'},
'id': {'type': 'integer'},
'language': {'type': 'string'}},
'required': ['id', 'expectedVersion'],
'type': 'object'},
None,
),
'get': (
'/product/getDetail',
{'properties': {'id': {'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'get-inventory-ledger': (
'/product/getInventoryLedger',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'productId': {'type': 'integer'}},
'required': ['productId'],
'type': 'object'},
None,
),
'list': (
'/product/getList',
{'properties': {'categoryId': {'type': 'integer'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'query': {'type': 'string'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
'publish': (
'/product/publish',
{'properties': {'expectedVersion': {'type': 'integer'},
'id': {'type': 'integer'},
'language': {'type': 'string'}},
'required': ['id', 'expectedVersion'],
'type': 'object'},
None,
),
'save': (
'/product/save',
{'properties': {'categoryId': {'type': 'integer'},
'expectedVersion': {'type': 'integer'},
'id': {'type': 'integer'},
'images': {'items': {'properties': {'alt': {'additionalProperties': {'type': 'string'},
'type': 'object'},
'file': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'productType': {'type': 'string'},
'purchaseMode': {'type': 'string'},
'shippingCountries': {'items': {'type': 'string'}, 'type': 'array'},
'skus': {'items': {'properties': {'active': {'type': 'boolean'},
'code': {'type': 'string'},
'combination': {'additionalProperties': {'type': 'string'},
'type': 'object'},
'id': {'type': 'integer'},
'image': {'type': 'string'},
'imageAlt': {'additionalProperties': {'type': 'string'},
'type': 'object'},
'initialStock': {'type': 'integer'},
'usdPriceMinor': {'type': 'integer'},
'weightGrams': {'type': 'integer'}},
'required': [],
'type': 'object'},
'type': 'array'},
'slug': {'type': 'string'},
'specifications': {'items': {'properties': {'id': {'type': 'string'},
'names': {'additionalProperties': {'type': 'string'},
'type': 'object'},
'values': {'items': {'properties': {'id': {'type': 'string'},
'names': {'additionalProperties': {'type': 'string'},
'type': 'object'}},
'required': [],
'type': 'object'},
'type': 'array'}},
'required': [],
'type': 'object'},
'type': 'array'},
'translations': {'items': {'properties': {'description': {'type': 'string'},
'language': {'type': 'string'},
'name': {'type': 'string'},
'seoDescription': {'type': 'string'},
'subtitle': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'}},
'required': [],
'type': 'object'},
None,
),
'unpublish-language': (
'/product/unpublishLanguage',
{'properties': {'expectedVersion': {'type': 'integer'},
'id': {'type': 'integer'},
'language': {'type': 'string'}},
'required': ['id', 'expectedVersion'],
'type': 'object'},
None,
),
},
'refund': {
'list': (
'/refund/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'request': (
'/refund/request',
{'properties': {'amountMinor': {'type': 'integer'},
'idempotencyKey': {'type': 'string'},
'orderId': {'type': 'integer'},
'reason': {'type': 'string'}},
'required': ['orderId', 'amountMinor', 'reason'],
'type': 'object'},
None,
),
},
'shipping-rule': {
'list': (
'/shippingRule/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/shippingRule/save',
{'properties': {'active': {'type': 'boolean'},
'amountMinor': {'type': 'integer'},
'countryCode': {'type': 'string'},
'etaDays': {'type': 'integer'},
'freeOverMinor': {'type': 'integer'},
'id': {'type': 'integer'},
'name': {'type': 'string'}},
'required': ['countryCode', 'name'],
'type': 'object'},
None,
),
},
'storage': {
'get-config': (
'/storage/getConfig',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'register-external': (
'/storage/registerExternal',
{'properties': {'url': {'type': 'string'}}, 'required': ['url'], 'type': 'object'},
None,
),
'save-config': (
'/storage/saveConfig',
{'properties': {'bucket': {'type': 'string'}, 'clientSecret': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
'upload-image': (
'/storage/uploadImage',
{'properties': {'file': {'format': 'binary', 'type': 'string'}},
'required': ['file'],
'type': 'object'},
'upload',
),
},
'tax-rule': {
'list': (
'/taxRule/getList',
{'properties': {'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'}},
'required': [],
'type': 'object'},
None,
),
'save': (
'/taxRule/save',
{'properties': {'active': {'type': 'boolean'},
'countryCode': {'type': 'string'},
'id': {'type': 'integer'},
'inclusive': {'type': 'boolean'},
'rateBps': {'type': 'integer'}},
'required': ['countryCode'],
'type': 'object'},
None,
),
},
}
+511
View File
@@ -0,0 +1,511 @@
"""Named hengde admin API operations and request schemas."""
ROUTES = {
'account': {
'create': (
'/account/create',
{'properties': {'displayName': {'maxLength': 50, 'type': 'string'},
'password': {'minLength': 8, 'type': 'string'},
'username': {'maxLength': 50, 'minLength': 3, 'type': 'string'}},
'required': ['username', 'password', 'displayName'],
'type': 'object'},
None,
),
'delete': (
'/account/delete',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}}, 'required': ['id'], 'type': 'object'},
None,
),
'list': (
'/account/getList',
{'properties': {'keyword': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'role': {'type': 'string'},
'status': {'type': 'string'}},
'required': ['pageNo', 'pageSize'],
'type': 'object'},
None,
),
'reset-password': (
'/account/resetPassword',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'password': {'minLength': 8, 'type': 'string'}},
'required': ['id', 'password'],
'type': 'object'},
None,
),
'update-status': (
'/account/updateStatus',
{'properties': {'id': {'minimum': 1, 'type': 'integer'},
'status': {'enum': ['enabled', 'disabled'], 'type': 'string'}},
'required': ['id', 'status'],
'type': 'object'},
None,
),
},
'auth': {
'change-password': (
'/auth/changePassword',
{'properties': {'newPassword': {'minLength': 8, 'type': 'string'},
'oldPassword': {'type': 'string'}},
'required': ['oldPassword', 'newPassword'],
'type': 'object'},
None,
),
'info': (
'/auth/info',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'update-profile': (
'/auth/updateProfile',
{'properties': {'displayName': {'maxLength': 50, 'type': 'string'}},
'required': ['displayName'],
'type': 'object'},
None,
),
},
'category': {
'get': (
'/category/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}, 'locale': {'type': 'string'}},
'required': ['id', 'locale'],
'type': 'object'},
None,
),
'list': (
'/category/getList',
{'properties': {'keyword': {'type': 'string'},
'locale': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['locale', 'pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/category/save',
{'properties': {'data': {'properties': {'description': {'type': 'string'},
'image': {'type': 'string'},
'label': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'parentId': {'type': 'integer'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'certification': {
'get': (
'/certification/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}, 'locale': {'type': 'string'}},
'required': ['id', 'locale'],
'type': 'object'},
None,
),
'list': (
'/certification/getList',
{'properties': {'keyword': {'type': 'string'},
'locale': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['locale', 'pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/certification/save',
{'properties': {'data': {'properties': {'authority': {'type': 'string'},
'image': {'type': 'string'},
'scope': {'type': 'string'},
'seoDescription': {'type': 'string'},
'seoTitle': {'type': 'string'},
'summary': {'type': 'string'},
'title': {'type': 'string'},
'validity': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'download': {
'get': (
'/download/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}, 'locale': {'type': 'string'}},
'required': ['id', 'locale'],
'type': 'object'},
None,
),
'list': (
'/download/getList',
{'properties': {'keyword': {'type': 'string'},
'locale': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['locale', 'pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/download/save',
{'properties': {'data': {'properties': {'category': {'type': 'string'},
'documentLocale': {'type': 'string'},
'file': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'home': {
'get': (
'/home/get',
{'properties': {'key': {'type': 'string'}, 'locale': {'type': 'string'}},
'required': ['locale'],
'type': 'object'},
None,
),
'save': (
'/home/save',
{'properties': {'data': {'properties': {'copy': {'properties': {'aModelThatFitsYourProject': {'type': 'string'},
'aboutHengde': {'type': 'string'},
'cleaningMonitoringMaintenance': {'type': 'string'},
'cleaningThatFitsTheSite': {'type': 'string'},
'efficientCleaningConfidentOperation': {'type': 'string'},
'equipmentAndServicesPlannedAroundTheNeedsOf': {'type': 'string'},
'featuredSolutions': {'type': 'string'},
'flexibleCooperation': {'type': 'string'},
'hengdeSolutions': {'type': 'string'},
'illustrativeSolarCleaningScene': {'type': 'string'},
'imageAiGeneratedSceneIllustration': {'type': 'string'},
'intelligentCleaning': {'type': 'string'},
'iotRemoteManagement': {'type': 'string'},
'licensedElectricalServices': {'type': 'string'},
'lifecycleOMSupport': {'type': 'string'},
'nextSlide': {'type': 'string'},
'ourSolutions': {'type': 'string'},
'pauseSlides': {'type': 'string'},
'previousSlide': {'type': 'string'},
'projectApplications': {'type': 'string'},
'qualityIntegrity': {'type': 'string'},
'rootedInQingyuanFocusedOnEnergy': {'type': 'string'}},
'required': [],
'type': 'object'},
'heroSlides': {'items': {'properties': {'cta': {'type': 'string'},
'image': {'type': 'string'},
'path': {'type': 'string'},
'subtitle': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'statistics': {'items': {'properties': {'label': {'type': 'string'},
'value': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'page': {
'get': (
'/page/get',
{'properties': {'key': {'type': 'string'}, 'locale': {'type': 'string'}},
'required': ['locale'],
'type': 'object'},
None,
),
'save': (
'/page/save',
{'properties': {'data': {'properties': {'cooperationModes': {'items': {'properties': {'description': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'copy': {'properties': {'acrossPlantTypesCleaningConditions': {'type': 'string'},
'askAboutQualifications': {'type': 'string'},
'bladesPulleysAndCablesAreInspectedAndReplaced': {'type': 'string'},
'businessPhone': {'type': 'string'},
'callUs': {'type': 'string'},
'capabilities': {'type': 'string'},
'chineseDocument': {'type': 'string'},
'chooseACooperationModelForPlantConditionsInvestment': {'type': 'string'},
'companyProductDocuments': {'type': 'string'},
'dataLedAssessmentAgreedTerms': {'type': 'string'},
'discussASimilarProject': {'type': 'string'},
'discussCooperation': {'type': 'string'},
'downloadDocument': {'type': 'string'},
'downloadTheChineseCompanyProfileAndRobotLeaflet': {'type': 'string'},
'email': {'type': 'string'},
'emailUs': {'type': 'string'},
'equipmentForSiteConditions': {'type': 'string'},
'equipmentOwnershipTermCleaningFrequencyResponseRequirementsAnd': {'type': 'string'},
'equipmentTechnologySiteServices': {'type': 'string'},
'established': {'type': 'string'},
'followHengdeIntelligentCleaningRobotsOnWechat': {'type': 'string'},
'gradeIiiInstallationRepairAndTestingPermitsSupport': {'type': 'string'},
'guangdongHengde': {'type': 'string'},
'hengdeOfficialWechatAccountQrCode': {'type': 'string'},
'illustrativeSolarCleaningScene': {'type': 'string'},
'imageAiGeneratedSceneIllustration': {'type': 'string'},
'investmentServicesForYourProject': {'type': 'string'},
'issuer': {'type': 'string'},
'lanInternetHybridAndTimerDeploymentsSupportCleaning': {'type': 'string'},
'modularMaintenance': {'type': 'string'},
'moreProjectApplications': {'type': 'string'},
'officeAddress': {'type': 'string'},
'onSiteApplications': {'type': 'string'},
'openCertificateImage': {'type': 'string'},
'ourServicesCoverElectricalEquipmentUpTo10': {'type': 'string'},
'productionAddress': {'type': 'string'},
'professionalPowerOM': {'type': 'string'},
'projectApplications': {'type': 'string'},
'projectBasedCooperation': {'type': 'string'},
'projectEnquiries': {'type': 'string'},
'projectPhotographsAndDescriptionsAreDrawnFromHengde': {'type': 'string'},
'providePlantInformationAndHistoricalGenerationDataFor': {'type': 'string'},
'qualifications': {'type': 'string'},
'qualityIntegrity': {'type': 'string'},
'remoteOnSiteControl': {'type': 'string'},
'scope': {'type': 'string'},
'selectTractionPortableOrSpecializedCleaningSystemsFor': {'type': 'string'},
'shareThePlantLocationCapacityModuleLayoutAnd': {'type': 'string'},
'startWithAProjectDiscussion': {'type': 'string'},
'validity': {'type': 'string'},
'viewQualification': {'type': 'string'},
'viewQualifications': {'type': 'string'},
'wechat': {'type': 'string'}},
'required': [],
'type': 'object'},
'description': {'type': 'string'},
'faqItems': {'items': {'properties': {'answer': {'type': 'string'},
'question': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'intro': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'key': {'type': 'string'},
'locale': {'type': 'string'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'product': {
'get': (
'/product/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}, 'locale': {'type': 'string'}},
'required': ['id', 'locale'],
'type': 'object'},
None,
),
'list': (
'/product/getList',
{'properties': {'keyword': {'type': 'string'},
'locale': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['locale', 'pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/product/save',
{'properties': {'categoryIds': {'items': {'type': 'integer'}, 'type': 'array'},
'data': {'properties': {'bullets': {'items': {'type': 'string'},
'type': 'array'},
'description': {'type': 'string'},
'featured': {'type': 'boolean'},
'gallery': {'type': 'string'},
'image': {'type': 'string'},
'seoDescription': {'type': 'string'},
'seoTitle': {'type': 'string'},
'specs': {'items': {'properties': {'label': {'type': 'string'},
'value': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'summary': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'project': {
'get': (
'/project/detail',
{'properties': {'id': {'minimum': 1, 'type': 'integer'}, 'locale': {'type': 'string'}},
'required': ['id', 'locale'],
'type': 'object'},
None,
),
'list': (
'/project/getList',
{'properties': {'keyword': {'type': 'string'},
'locale': {'type': 'string'},
'pageNo': {'default': 1, 'minimum': 1, 'type': 'integer'},
'pageSize': {'default': 20, 'maximum': 100, 'minimum': 1, 'type': 'integer'},
'status': {'type': 'string'}},
'required': ['locale', 'pageNo', 'pageSize'],
'type': 'object'},
None,
),
'save': (
'/project/save',
{'properties': {'data': {'properties': {'body': {'items': {'type': 'string'}, 'type': 'array'},
'facts': {'items': {'properties': {'label': {'type': 'string'},
'value': {'type': 'string'}},
'required': [],
'type': 'object'},
'type': 'array'},
'image': {'type': 'string'},
'location': {'type': 'string'},
'seoDescription': {'type': 'string'},
'seoTitle': {'type': 'string'},
'summary': {'type': 'string'},
'title': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'slug': {'type': 'string'},
'sortOrder': {'type': 'integer'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'site': {
'get': (
'/site/get',
{'properties': {'key': {'type': 'string'}, 'locale': {'type': 'string'}},
'required': ['locale'],
'type': 'object'},
None,
),
'save': (
'/site/save',
{'properties': {'data': {'properties': {'address': {'type': 'string'},
'advantagesGallery': {'type': 'string'},
'brandName': {'type': 'string'},
'companyName': {'type': 'string'},
'contact': {'type': 'string'},
'description': {'type': 'string'},
'email': {'type': 'string'},
'footerBrandDescription': {'type': 'string'},
'footerDescription': {'type': 'string'},
'footerEyebrow': {'type': 'string'},
'footerTitle': {'type': 'string'},
'illustration': {'type': 'string'},
'internationalName': {'type': 'string'},
'introduction': {'type': 'string'},
'legalOwner': {'type': 'string'},
'logo': {'type': 'string'},
'mobile': {'type': 'string'},
'pageHeroImage': {'type': 'string'},
'phone': {'type': 'string'},
'productionAddress': {'type': 'string'},
'projectKey': {'type': 'string'},
'projectName': {'type': 'string'},
'title': {'type': 'string'},
'wechatQrCode': {'type': 'string'}},
'required': [],
'type': 'object'},
'id': {'type': 'integer'},
'locale': {'type': 'string'},
'status': {'type': 'string'}},
'required': [],
'type': 'object'},
None,
),
},
'storage': {
'download-from-url': (
'/storage/downloadFromUrl',
{'properties': {'url': {'maxLength': 2048, 'type': 'string'}},
'required': ['url'],
'type': 'object'},
None,
),
'get-config': (
'/storage/getConfig',
{'properties': {}, 'required': [], 'type': 'object'},
None,
),
'register-external-image': (
'/storage/registerExternalImage',
{'properties': {'url': {'maxLength': 2048, 'type': 'string'}},
'required': ['url'],
'type': 'object'},
None,
),
'save-config': (
'/storage/saveConfig',
{'properties': {'bucket': {'maxLength': 120, 'type': 'string'},
'clientSecret': {'maxLength': 255, 'type': 'string'}},
'required': ['bucket'],
'type': 'object'},
None,
),
'upload-file': (
'/storage/uploadFile',
{'properties': {'file': {'format': 'binary', 'type': 'string'}},
'required': ['file'],
'type': 'object'},
'upload',
),
'upload-image': (
'/storage/uploadImage',
{'properties': {'file': {'format': 'binary', 'type': 'string'}},
'required': ['file'],
'type': 'object'},
'upload',
),
},
}
File diff suppressed because it is too large Load Diff
+73
View File
@@ -0,0 +1,73 @@
"""Render prepared Shop documents using the host's Chromium runner."""
import json
import os
from pathlib import Path
import shutil
import subprocess
from .transport import ClientError, compact
def response_data(client, route, body):
response = client.exchange(route, compact(body).encode("utf-8"))
if not client.success(response):
failure = response.get("json") or {}
raise ClientError(failure.get("msg") or "商城视觉请求失败。",
**{key: response[key] for key in ("httpStatus", "code", "traceId")})
return response["json"].get("data"), response["traceId"]
def local_binary(args):
if args.renderer:
return str(args.renderer.resolve(strict=True))
filename = "light.exe" if os.name == "nt" else "light"
for parent in (Path.cwd(), *Path.cwd().parents):
candidate = parent / "backend" / filename
if (parent / "backend" / "go.mod").is_file() and candidate.is_file():
return str(candidate)
binary = shutil.which(filename)
if not binary:
raise ClientError("请通过 --renderer 指定当前后端源码构建的 light 可执行文件。")
return binary
def render(client, args, body):
binary = local_binary(args)
output = args.output
if not output.is_absolute() or output.exists() or output.is_symlink():
raise ClientError("--output-dir 必须是尚不存在的本地绝对路径。")
prepared, trace_id = response_data(client, args.endpoint, body)
if not isinstance(prepared, dict) or not all(isinstance(prepared.get(key), dict)
for key in ("render", "metadata", "snapshot")):
raise ClientError("商城视觉输入响应无效。", traceId=trace_id)
dataset = "deal" if "/dealAgent/" in args.endpoint else "product"
request = {"render": prepared["render"], dataset: prepared["metadata"]}
with subprocess.Popen(
[binary, "render-shop-visual", "--output-dir", str(output)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
) as child:
try:
child.stdin.write((compact(request) + "\n").encode("utf-8"))
child.stdin.flush()
ready = child.stdout.readline(4096)
if not ready or json.loads(ready) != {"rendered": True}:
raise ClientError("本地 Chromium 渲染失败,请核对 Chromium、平台及输出目录。", traceId=trace_id)
current, _ = response_data(client, args.endpoint.rsplit("/", 1)[0] + "/validateRenderInput", prepared["snapshot"])
if current is not True:
raise ClientError("视觉快照复核未通过。", traceId=trace_id)
result, _ = child.communicate(b'{"commit":true}\n', timeout=120)
if child.returncode != 0:
raise ClientError("商城视觉包写入失败。", traceId=trace_id)
return {"ok": True, "traceId": trace_id, "body": json.loads(result)}
except (OSError, ValueError, subprocess.TimeoutExpired):
raise ClientError("本地商城视觉渲染或输出失败。", traceId=trace_id) from None
finally:
if child.poll() is None:
if not child.stdin.closed:
child.stdin.close()
try:
child.wait(timeout=5)
except subprocess.TimeoutExpired:
child.kill()
child.wait()
+76 -18
View File
@@ -7,16 +7,22 @@ import re
import subprocess
from .api import format_response
from .shop_visual import render
from .system_client import LOGIN_PATH, LOGOUT_PATH
from .system_routes import GROUPS
from .system_schema import REQUESTS
from .transport import ClientError, MultipartBody, compact, private_output, reject_constant
PRIVATE_INPUT_FIELDS = {"accessKey", "accessKeyId", "accessKeySecret", "secretKey", "oldPassword", "newPassword"}
PRIVATE_INPUT_FIELDS = {
"accessKey", "accessKeyId", "accessKeySecret", "apiKey", "clientSecret", "secretKey",
"password", "oldPassword", "newPassword", "token",
}
def example_value(name, field):
if "type" not in field:
return {}
if "const" in field:
return field["const"]
if "default" in field:
@@ -28,11 +34,13 @@ def example_value(name, field):
if field["type"] == "array":
return [example_value(name, field["items"])]
if field["type"] == "object":
return {key: example_value(key, spec) for key, spec in field["properties"].items()}
return {key: example_value(key, spec) for key, spec in field.get("properties", {}).items()}
if field["type"] == "integer":
return 600 if name == "ttl" else field.get("minimum", 1)
if field["type"] == "boolean":
return True
if field["type"] == "number":
return field.get("minimum", 0.0)
examples = {"uuid": "0198d956-1111-4444-8888-111111111111", "uri": "https://example.com/",
"email": "admin@example.com", "binary": "example.png"}
if field.get("format") in examples:
@@ -60,14 +68,28 @@ def request_body(args):
if flags:
raise ClientError("--body-file 与字段参数只能选择一种。")
try:
body = json.loads(args.body_file.read_text(encoding="utf-8-sig"), parse_constant=reject_constant)
with args.body_file.open("rb") as stream:
raw = stream.read((8 << 20) + 1)
if len(raw) > 8 << 20:
raise ClientError("请求文件不能超过 8 MiB。")
body = json.loads(raw.decode("utf-8-sig"), parse_constant=reject_constant,
object_pairs_hook=unique_fields)
except ValueError:
raise ClientError("请求正文必须是有效 JSON 对象。") from None
raise ClientError("请求正文必须是有效且无重复字段的 JSON 对象。") from None
if not isinstance(body, dict):
raise ClientError("请求正文必须是 JSON 对象。")
return body
def unique_fields(pairs):
fields = {}
for key, value in pairs:
if key in fields:
raise ValueError("duplicate JSON field")
fields[key] = value
return fields
def save_private_json(args, data, details):
target = args.output.absolute()
try:
@@ -82,60 +104,94 @@ def call(client, args):
if args.output is not None and (args.output.exists() or args.output.is_symlink()):
raise ClientError("目标文件已存在,拒绝覆盖。")
body = request_body(args)
if getattr(args, "dry_run", False):
body["dryRun"] = True
client.remember_secrets(body)
payload = (MultipartBody(args.file, body) if args.mode == "upload" else compact(body).encode("utf-8"))
response = client.exchange(args.endpoint, payload, output=args.output if args.mode == "zip" else None)
if client.app == "shop" and args.endpoint in (
"/general/agentPublicFile/importFile", "/content/workspaceAgent/importAttachment",
) and isinstance(body.get("url"), str):
client.secrets.append(body["url"])
if args.mode == "render":
return render(client, args, body)
if args.mode == "metadata-upload":
payload = MultipartBody(args.file, {"metadata": compact(body)}, reject_symlink=True)
elif args.mode == "upload":
payload = MultipartBody(args.file, body, reject_symlink=client.app == "shop")
else:
payload = compact(body).encode("utf-8")
try:
response = client.exchange(args.endpoint, payload, output=args.output if args.mode in ("zip", "download") else None)
except ClientError as error:
if "结果未知" in str(error):
meta = body.get("meta")
request_id = body.get("requestId") or (meta.get("requestId") if isinstance(meta, dict) else None)
if request_id:
error.details["requestId"] = request_id
if body.get("idempotencyKey"):
error.details["idempotencyKey"] = body["idempotencyKey"]
raise
if response.get("downloaded"):
return response
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
if args.mode in ("zip", "private-output"):
if args.mode in ("zip", "download", "private-output"):
if not client.success(response):
message = (response["json"] or {}).get("msg") if isinstance(response["json"], dict) else None
raise ClientError(message or "System 请求失败。", **details)
if args.mode == "zip":
raise ClientError("System 响应未包含证书 ZIP。", **details)
raise ClientError(message or "请求失败。", **details)
if args.mode in ("zip", "download"):
raise ClientError("响应未包含可下载文件。", **details)
data = response["json"].get("data")
if not isinstance(data, dict) or not data:
raise ClientError("System 响应未包含所需数据。", **details)
raise ClientError("响应未包含所需数据。", **details)
return save_private_json(args, data, details)
if args.endpoint == "/user/updatePassword" and client.success(response):
data = response["json"].get("data")
if not isinstance(data, dict) or data.get("success") is not True:
message = (data or {}).get("message") if isinstance(data, dict) else None
raise ClientError(message or "System 密码修改失败。", **details)
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / "system", args.max_chars)
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / client.app, args.max_chars)
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None):
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None, *, schema=None):
command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False)
if schema is None:
request = REQUESTS[request_type] if request_type else {"properties": {}, "required": []}
schema = {"type": "object", **request}
private_input = bool(PRIVATE_INPUT_FIELDS.intersection(schema["properties"]))
inputs = command.add_mutually_exclusive_group(required=private_input)
inputs.add_argument("--schema", action=ShowRequest, nargs=0, help="离线查看请求字段、类型和约束")
inputs.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例请求")
if mode == "upload":
if mode in ("upload", "metadata-upload"):
command.add_argument("--file", type=Path, required=True, help="上传的本机文件")
else:
if mode != "upload" or schema["properties"].keys() - {"file"}:
label = "本机私有 JSON 输入文件" if private_input else "UTF-8 JSON 请求文件"
inputs.add_argument("--body-file", type=Path, help=label)
if mode in ("zip", "private-output"):
if mode in ("zip", "download", "private-output"):
command.add_argument("--output", type=Path, required=True, help="私有输出路径,拒绝覆盖")
if mode == "render":
command.add_argument("--output-dir", dest="output", type=Path, required=True, help="私有视觉包输出目录")
command.add_argument("--renderer", type=Path, help="本地 light 可执行文件路径")
fields = []
if not private_input:
for field, spec in schema["properties"].items():
value_type = spec["type"]
value_type = spec.get("type")
if isinstance(value_type, list):
value_type = value_type[0]
if field == "file" or value_type not in ("string", "integer", "boolean"):
repeated = value_type == "array"
if repeated:
value_type = spec.get("items", {}).get("type")
if field in ("file", "dryRun") or value_type not in ("string", "integer", "number", "boolean"):
continue
flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field)
label = f"JSON 字段 {field}"
if field in schema["required"] and "default" not in spec:
label += ",必填"
options = {"dest": field, "help": label}
if repeated:
options.update(action="append", help=f"{label},可重复指定")
if value_type == "integer":
options["type"] = int
if value_type == "number":
options["type"] = float
if value_type == "boolean":
options.update(type=parse_bool, metavar="true|false")
if "enum" in spec:
@@ -146,6 +202,8 @@ def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=N
fields.append(field)
command.set_defaults(handler=call, endpoint=f"{prefix}/{endpoint}" if prefix else endpoint,
mode=mode, request_schema=schema, output=None, body_file=None, fields=fields)
if "dryRun" in schema["properties"]:
command.add_argument("--dry-run", action="store_true", help="只预检输入与状态")
def parse_bool(value):
+36 -18
View File
@@ -2,6 +2,7 @@
import contextlib
import errno
import getpass
from hashlib import sha256
from http.client import IncompleteRead
import ipaddress
import json
@@ -9,6 +10,7 @@ import mimetypes
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import tempfile
@@ -20,7 +22,7 @@ from uuid import uuid4
DEFAULT_BASE_URL = 'https://api.zhecent.com'
DEFAULT_BASE_URLS = {'shop': DEFAULT_BASE_URL, 'media': DEFAULT_BASE_URL,
'gysmart': 'https://am.gysmart.shop'}
'gysmart': 'https://am.gysmart.shop', 'fangyus': '', 'hengde': ''}
APP_KEY = 'LIGHTCORE_API_APP'
KEYS = ('LIGHTCORE_API_BASE_URL', 'LIGHTCORE_ACCESS_TOKEN', 'LIGHTCORE_REFRESH_TOKEN',
'LIGHTCORE_ACCESS_TOKEN_EXPIRES_AT', 'LIGHTCORE_REFRESH_TOKEN_EXPIRES_AT')
@@ -163,13 +165,14 @@ def reject_constant(_):
class MultipartBody:
"""可重复打开的有长度流;仅认证失效允许一次重发。"""
def __init__(self, file, fields):
self.file = Path(file).resolve()
def __init__(self, file, fields, *, reject_symlink=False):
self.file = Path(file).absolute() if reject_symlink else Path(file).resolve()
self.reject_symlink = reject_symlink
if not isinstance(fields, dict) or any(not isinstance(k, str) or not isinstance(v, (str, int, float, bool)) for k, v in fields.items()):
raise ClientError('上传表单必须是 JSON 对象,字段值为字符串、数字或布尔值。')
if not self.file.is_file():
raise ClientError('上传文件不存在。')
self.stat = self.file.stat()
self.stat = self.file.lstat() if self.reject_symlink else self.file.stat()
if not stat.S_ISREG(self.stat.st_mode):
raise ClientError('上传路径必须是普通文件。')
boundary = 'lightcore-' + uuid4().hex
self.content_type = 'multipart/form-data; boundary=' + boundary
parts = []
@@ -187,11 +190,13 @@ class MultipartBody:
self.size = len(self.prefix) + self.stat.st_size + len(self.suffix)
def __iter__(self):
current = self.file.stat()
if (current.st_size, current.st_mtime_ns) != (self.stat.st_size, self.stat.st_mtime_ns):
with self.file.open('rb') as stream:
current = os.fstat(stream.fileno())
if (not os.path.samestat(current, self.stat)
or current.st_size != self.stat.st_size or current.st_mtime_ns != self.stat.st_mtime_ns
or self.reject_symlink and self.file.is_symlink()):
raise ClientError('上传文件已变化,未继续发送。')
yield self.prefix
with self.file.open('rb') as stream:
while chunk := stream.read(1024 * 1024):
yield chunk
yield self.suffix
@@ -203,7 +208,7 @@ class Client:
def __init__(self, app, env_file, timeout=30):
self.app = app
self.timeout = timeout
self.refreshable = self.app in ('shop', 'media')
self.refreshable = self.app in ('shop', 'media', 'fangyus', 'hengde')
self.auth_fields = {key: field for key, field in AUTH_FIELDS.items()
if self.refreshable or key in (KEYS[1], KEYS[3])}
self.admin_path = admin_path(app)
@@ -250,7 +255,10 @@ class Client:
def configured_base(self, settings, explicit=None):
candidates = (explicit, os.environ.get(KEYS[0]), settings.get(KEYS[0]))
return base_url(next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app]), self.app)
address = next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app])
if not address:
raise ClientError('首次登录请通过 --base-url 指定目标后端地址。')
return base_url(address, self.app)
def read_session(self):
if not self.env.is_file():
@@ -284,16 +292,19 @@ class Client:
details = {'httpStatus': response.status, 'code': 200,
'traceId': response.headers.get('X-Request-ID')}
target = Path(output).absolute()
digest = sha256()
try:
size = 0
with private_output(target) as stream:
while chunk := response.read(1024 * 1024):
stream.write(chunk)
digest.update(chunk)
size += len(chunk)
expected = response.headers.get('Content-Length')
if expected is not None and size != int(expected):
raise ClientError('下载长度不完整,未保存目标文件。', **details)
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target), 'bytes': size}
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target),
'bytes': size, 'sha256': digest.hexdigest()}
except (OSError, ValueError, IncompleteRead, subprocess.SubprocessError) as error:
raise ClientError('下载未完成或目标文件已存在;未覆盖目标文件。', **details) from error
@@ -306,21 +317,23 @@ class Client:
headers['Content-Type'] = payload.content_type
headers['Content-Length'] = str(payload.size)
request = Request(base + self.admin_path + path, data=payload, headers=headers, method=method)
trace_id = None
try:
try:
response = self.http.open(request, timeout=self.timeout)
except HTTPError as error:
response = error
with response:
trace_id = response.headers.get('X-Request-ID')
if (output is not None and 200 <= response.status < 300
and response.headers.get('Content-Disposition', '').lower().startswith('attachment')
and (self.app != 'system' or response.headers.get_content_type() == 'application/zip')):
return self.save_download(response, output)
raw = response.read().decode(response.headers.get_content_charset() or 'utf-8')
trace_id = response.headers.get('X-Request-ID')
status = response.status
except (URLError, OSError, TimeoutError, IncompleteRead, ValueError):
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。') from None
details = {'traceId': trace_id} if trace_id else {}
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。', **details) from None
parsed = None
try:
parsed = json.loads(raw)
@@ -397,14 +410,18 @@ class Client:
except (OSError, subprocess.SubprocessError, ClientError) as error:
raise ClientError('服务端已退出,但清理本机会话失败。', **details) from error
def login_base(self, explicit_base):
def login_base(self, explicit_base, isolate_target=False):
previous = self.read_settings()
if previous.get(APP_KEY) not in (None, self.app) or (previous.get(APP_KEY) is None and any(previous.get(k) for k in KEYS[1:])):
raise ClientError('目标文件已有其他或未标明应用的会话,拒绝覆盖,请使用独立会话文件。')
return self.configured_base(previous, explicit_base)
base = self.configured_base(previous, explicit_base)
if (isolate_target and previous.get(KEYS[0]) and previous.get(KEYS[1])
and base_url(previous[KEYS[0]], self.app) != base):
raise ClientError('会话文件属于其他目标后端,请通过 --env-file 指定独立文件。')
return base
def login(self, explicit_base=None):
base = self.login_base(explicit_base)
def login(self, explicit_base=None, *, isolate_target=False):
base = self.login_base(explicit_base, isolate_target)
account_field = 'identifier' if self.app == 'shop' else 'username'
while True:
identifier = input('后台账号或登录手机号: ')
@@ -421,6 +438,7 @@ class Client:
break
session = self.auth_session(base, response)
with session_lock(self.env, self.timeout):
self.login_base(base, isolate_target)
self.write_session(session)
return {'ok': True, 'traceId': response['traceId'], 'message': '登录成功,会话已保存在本机。'}
+241
View File
@@ -0,0 +1,241 @@
content attachment-download
content attachment-get
content attachment-import
content attachment-list
content attachment-set-validity
content attachment-update
content attachment-upload
content cms article-apply
content cms article-archive
content cms article-check
content cms article-get
content cms article-list
content cms article-plan
content cms article-publish
content cms article-restore-apply
content cms article-restore-plan
content cms article-revision-get
content cms article-revision-list
content cms article-withdraw
content cms attachment-copy
content cms case-apply
content cms case-archive
content cms case-check
content cms case-get
content cms case-list
content cms case-plan
content cms case-publish
content cms case-restore-apply
content cms case-restore-plan
content cms case-revision-get
content cms case-revision-list
content cms case-withdraw
content cms category-create
content cms category-delete
content cms category-get
content cms category-list
content cms category-update
content cms category-update-status
content context-get
content document-export
content document-get
content document-list
content document-restore-apply
content document-restore-plan
content document-review
content document-review-check
content document-review-get
content document-revision-get
content document-revision-list
content document-save
content document-set-validity
content fact-get
content fact-list
content fact-restore-apply
content fact-restore-plan
content fact-revision-get
content fact-revision-list
content fact-save
content fact-set-validity
content operation-get
content operation-list
content review-rule-get
content review-rule-list
content review-rule-restore-apply
content review-rule-restore-plan
content review-rule-revision-get
content review-rule-revision-list
content review-rule-save
content review-rule-set-validity
content run-finish
content run-get
content run-list
content run-start
content source-get
content source-list
content source-restore-apply
content source-restore-plan
content source-revision-get
content source-revision-list
content source-save
content source-set-validity
content website article-apply
content website article-archive
content website article-check
content website article-get
content website article-list
content website article-plan
content website article-publish
content website article-withdraw
content website attachment-copy
content website category-create
content website category-delete
content website category-get
content website category-list
content website category-update
content website category-update-status
content website restore-apply
content website restore-plan
content website revision-get
content website revision-list
content workspace-create
content workspace-get
content workspace-list
content workspace-restore-apply
content workspace-restore-plan
content workspace-revision-get
content workspace-revision-list
content workspace-set-validity
content workspace-update
crm artifact get
crm artifact list
crm catalog brand create
crm catalog brand delete
crm catalog brand delete-preview
crm catalog brand get
crm catalog brand list
crm catalog brand update
crm catalog brand update-status
crm catalog category create
crm catalog category delete
crm catalog category delete-preview
crm catalog category get
crm catalog category list
crm catalog category tree
crm catalog category update
crm catalog category update-status
crm catalog operation get
crm catalog operation list
crm catalog product apply
crm catalog product delete
crm catalog product delete-preview
crm catalog product get
crm catalog product list
crm catalog product plan
crm catalog product update-status
crm catalog quotation-category create
crm catalog quotation-category delete
crm catalog quotation-category delete-preview
crm catalog quotation-category get
crm catalog quotation-category list
crm catalog quotation-category update
crm catalog quotation-category update-status
crm customer get
crm customer list
crm fund-ledger account get
crm fund-ledger account list
crm fund-ledger balance-check
crm fund-ledger daily-summary
crm fund-ledger overview
crm fund-ledger record get
crm fund-ledger record list
crm project file download
crm project file get
crm project file list
crm project get
crm project list
douyin-local-life validate
file convert-pdf-to-images
file download
file get
file image variant
file import
file list
file operation get
file operation list
file purpose get
file purpose list
file rename
file upload
mall brand-create
mall brand-delete
mall brand-get
mall brand-list
mall brand-update
mall brand-update-status
mall category-create
mall category-delete
mall category-get
mall category-list
mall category-tree
mall category-update
mall category-update-status
mall deal-apply
mall deal-check
mall deal-get
mall deal-list
mall deal-operation-get
mall deal-operation-list
mall deal-plan
mall deal-publish-apply
mall deal-publish-plan
mall deal-render
mall deal-status-apply
mall deal-status-plan
mall deal-version-get
mall deal-version-list
mall operation-get
mall operation-list
mall product-ai-apply
mall product-ai-plan
mall product-ai-version-diff
mall product-ai-version-get
mall product-ai-version-list
mall product-apply
mall product-audit
mall product-check
mall product-context-apply
mall product-context-get
mall product-context-plan
mall product-context-revision-diff
mall product-context-revision-get
mall product-context-revision-list
mall product-get
mall product-inventory-apply
mall product-inventory-get
mall product-inventory-ledger-list
mall product-inventory-plan
mall product-list
mall product-plan
mall product-render
mall product-restore-apply
mall product-restore-plan
mall product-revision-diff
mall product-revision-get
mall product-revision-list
mall product-sort-apply
mall product-sort-list
mall product-sort-plan
mall product-status-apply
mall product-status-plan
mall shipping-template-list
mall supplier-create
mall supplier-delete
mall supplier-get
mall supplier-list
mall supplier-update
showroom create
showroom get
showroom list
showroom update
showroom update-status
+245
View File
@@ -0,0 +1,245 @@
import argparse
from contextlib import redirect_stdout
from hashlib import sha256
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import Thread
import time
import unittest
from unittest.mock import Mock, patch
from lightcore_cli.application_commands import APPLICATIONS
from lightcore_cli.cli import main, parser
from lightcore_cli.shop_visual import render
from lightcore_cli.transport import ClientError
BACKEND = Path(__file__).resolve().parents[1] / "../../backend"
class ApplicationRouteTests(unittest.TestCase):
def test_registered_routes_and_offline_schemas(self):
cli = parser()
for app, (_, groups) in APPLICATIONS.items():
controllers = BACKEND / "application" / app / "interfaces/admin/controllers"
registered = set()
for file in controllers.glob("*.go"):
if file.stem.endswith("_test"):
continue
source = file.read_text(encoding="utf-8")
registered.update(re.findall(r'\.Handle\("POST",\s*"([^"]+)"', source))
base = re.search(r'\bbase\s*:=\s*"([^"]+)"', source)
if base:
registered.update(base[1] + suffix for suffix in re.findall(r'\.Handle\("POST",\s*base\s*\+\s*"([^"]+)"', source))
if file.name == "product.go" and app == "shop":
registered.update(re.findall(r'\{"(/mall/product/[^" ]+)", t\.', source))
commands = set()
for group, operations in groups.items():
for name, (path, _, _) in operations.items():
with self.subTest(app=app, group=group, command=name):
for flag in ("--schema", "--example"):
output = io.StringIO()
with redirect_stdout(output), self.assertRaises(SystemExit) as error:
cli.parse_args([app, *group.split(), name, flag])
self.assertEqual(error.exception.code, 0)
body = json.loads(output.getvalue())
if flag == "--schema":
self.assertEqual(body["type"], "object")
commands.add(path)
if app == "shop":
if controllers.is_dir():
self.assertEqual(commands - registered, set())
old_leaves = Path(__file__).with_name("shop_command_inventory.txt")
self.assertEqual(
{f"{group} {name}" for group, operations in groups.items() for name in operations},
set(old_leaves.read_text(encoding="utf-8").splitlines()),
)
else:
commands.add(cli.parse_args([app, "login"]).endpoint)
if app != "gysmart":
commands.update(cli.parse_args([app, action]).endpoint for action in ("refresh", "logout"))
if controllers.is_dir():
self.assertEqual(commands, registered)
class AdminHTTP(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, data, *, code=200, message="", attachment=False):
raw = data if attachment else json.dumps({"code": code, "msg": message, "data": data}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream" if attachment else "application/json")
self.send_header("Content-Length", str(len(raw)))
self.send_header("X-Request-ID", "test-trace")
if attachment:
self.send_header("Content-Disposition", "attachment; filename=private.bin")
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
raw = self.rfile.read(int(self.headers["Content-Length"]))
token = self.headers.get("Authorization")
multipart = self.headers.get_content_type() == "multipart/form-data"
data = raw if multipart else json.loads(raw)
self.server.requests.append((self.path, token, data))
app = self.path.split("/")[2]
if self.path.endswith(("/auth/login", "/auth/refresh")):
expires = int(time.time()) + 600
auth = {"accessToken": f"synthetic-{app}-token", "accessTokenExpiresAt": expires}
if app != "gysmart":
auth.update(refreshToken=f"synthetic-{app}-refresh", refreshTokenExpiresAt=expires)
return self.reply(auth)
if token != f"Bearer synthetic-{app}-token":
return self.reply(None, code=1001)
if self.path.endswith("/downloadAttachment"):
if data.get("workspaceKey") != "allowed":
return self.reply(None, code=403, message="scope denied")
return self.reply(b"private test data", attachment=True)
if self.path.endswith("/article/create") and data.get("title") == "duplicate":
return self.reply(None, code=400, message="同标题文章已存在")
if self.path.endswith("/workspaceAgent/saveFact"):
self.close_connection = True
return
if self.path.endswith("/getProviderStatus"):
return self.reply({"lastEvent": "delivered"})
self.reply({"received": True})
class ApplicationHTTPTests(unittest.TestCase):
def setUp(self):
directory = TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.folder = Path(directory.name)
self.server = self.start_server()
def start_server(self):
server = ThreadingHTTPServer(("127.0.0.1", 0), AdminHTTP)
server.requests = []
server.address = f"http://127.0.0.1:{server.server_port}"
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
Thread(target=server.serve_forever, daemon=True).start()
return server
def call(self, app, *args, session=None):
with redirect_stdout(io.StringIO()) as stream, patch.dict("os.environ", {"LIGHTCORE_API_BASE_URL": ""}):
status = main([app, "--env-file", str(session or self.folder / f"{app}.env"), *args])
self.assertNotIn("synthetic-", stream.getvalue())
return status, json.loads(stream.getvalue())
def login(self, app, server=None, session=None):
with patch("builtins.input", return_value="tester"), patch("getpass.getpass", return_value="test-password"):
return self.call(app, "login", "--base-url", (server or self.server).address, session=session)
def test_app_and_target_sessions_are_isolated(self):
self.assertEqual(self.login("fangyus")[0], 0)
self.assertEqual(self.login("hengde")[0], 0)
self.assertEqual(self.login("gysmart")[0], 0)
self.assertEqual(self.call("hengde", "refresh")[0], 0)
self.assertEqual(self.server.requests[-1][2], {"refreshToken": "synthetic-hengde-refresh"})
before = len(self.server.requests)
self.assertEqual(self.call("hengde", "refresh", session=self.folder / "fangyus.env")[0], 1)
self.assertEqual(len(self.server.requests), before)
other = self.start_server()
self.assertEqual(self.login("fangyus", other)[0], 1)
self.assertEqual(other.requests, [])
self.assertEqual(self.login("fangyus", other, self.folder / "fangyus-other.env")[0], 0)
self.assertEqual(self.call("gysmart", "email", "get-provider-status", "--id", "email-1")[1]["body"]["data"],
{"lastEvent": "delivered"})
self.assertEqual(self.call("hengde", "logout")[0], 0)
self.assertEqual(self.call("hengde", "refresh")[0], 1)
def test_fangyus_preflight_and_business_error(self):
self.assertEqual(self.login("fangyus")[0], 0)
body = self.folder / "article.json"
body.write_text('{"category":"news","title":"duplicate","contentHtml":"<p>Example</p>"}', encoding="utf-8")
code, result = self.call("fangyus", "article", "create", "--body-file", str(body), "--dry-run")
self.assertEqual(code, 1)
self.assertEqual(result["traceId"], "test-trace")
self.assertEqual(result["body"]["msg"], "同标题文章已存在")
self.assertTrue(self.server.requests[-1][2]["dryRun"])
before = len(self.server.requests)
body.write_text('{"title":"first","title":"second"}', encoding="utf-8")
self.assertEqual(self.call("fangyus", "article", "create", "--body-file", str(body))[0], 1)
self.assertEqual(len(self.server.requests), before)
def test_shop_plan_apply_defaults_and_private_file(self):
self.assertEqual(self.login("shop")[0], 0)
self.assertEqual(self.server.requests[-1][2]["identifier"], "tester")
self.assertEqual(self.call("shop", "douyin-local-life", "validate")[0], 0)
self.assertEqual(self.server.requests[-1][2], {"profile": "official"})
body = self.folder / "request.json"
for action, fields in (
("product-plan", {"manifest": {"productId": 27, "expectedRevision": 4}}),
("product-apply", {"manifest": {"productId": 27, "expectedRevision": 4}, "planHash": "a" * 64,
"requestId": "0198d956-1111-4444-8888-111111111111"}),
):
body.write_text(json.dumps(fields), encoding="utf-8")
self.assertEqual(self.call("shop", "mall", action, "--body-file", str(body))[0], 0)
self.assertEqual(self.server.requests[-1][2], fields)
target = self.folder / "file.bin"
args = ("content", "attachment-download", "--attachment-key", "fixture", "--output", str(target))
self.assertEqual(self.call("shop", *args, "--workspace-key", "denied")[0], 1)
self.assertFalse(target.exists())
code, result = self.call("shop", *args, "--workspace-key", "allowed")
self.assertEqual(code, 0)
self.assertEqual(result["sha256"], sha256(b"private test data").hexdigest())
self.assertEqual(target.read_bytes(), b"private test data")
self.assertEqual(self.call("shop", *args, "--workspace-key", "allowed")[0], 1)
def test_shop_upload_and_unknown_result(self):
self.assertEqual(self.login("shop")[0], 0)
file = self.folder / "fixture.png"
file.write_bytes(b"fixture image")
body = self.folder / "request.json"
body.write_text('{"purpose":"mall/product/image","requestId":"upload-id"}', encoding="utf-8")
self.assertEqual(self.call("shop", "file", "upload", "--file", str(file), "--body-file", str(body))[0], 0)
self.assertIn(b"name=\"requestId\"\r\n\r\nupload-id", self.server.requests[-1][2])
self.assertIn(b"fixture image", self.server.requests[-1][2])
body.write_text('{"meta":{"requestId":"fact-write-id"}}', encoding="utf-8")
code, result = self.call("shop", "content", "fact-save", "--body-file", str(body))
self.assertEqual(code, 1)
self.assertEqual(result["requestId"], "fact-write-id")
class ShopRenderProtocolTests(unittest.TestCase):
def test_commit_requires_current_snapshot(self):
prepare = {"render": {"HTML": "<html/>"}, "metadata": {}, "snapshot": {"id": 5}}
for current in (False, True):
with self.subTest(current=current), TemporaryDirectory() as directory:
result = {"httpStatus": 200, "code": 200, "traceId": "render-test"}
client = Mock()
client.success.return_value = True
client.exchange.side_effect = [{**result, "json": {"data": prepare}}, {**result, "json": {"data": current}}]
child = Mock()
child.stdin = io.BytesIO()
child.stdout = io.BytesIO(b'{"rendered":true}\n')
child.returncode = 0
child.poll.return_value = None if not current else 0
child.communicate.return_value = (b'{"productId":5}', b"")
args = argparse.Namespace(output=Path(directory) / "bundle", endpoint="/mall/productAgent/getRenderInput")
with patch("lightcore_cli.shop_visual.local_binary", return_value="light"), patch(
"lightcore_cli.shop_visual.subprocess.Popen", return_value=Mock(**{
"__enter__": Mock(return_value=child), "__exit__": Mock(return_value=False)
})
):
if current:
self.assertEqual(render(client, args, {"id": 5})["body"], {"productId": 5})
child.communicate.assert_called_once_with(b'{"commit":true}\n', timeout=120)
else:
with self.assertRaisesRegex(ClientError, "快照复核未通过"):
render(client, args, {"id": 5})
child.communicate.assert_not_called()
self.assertTrue(child.stdin.closed)
self.assertEqual(client.exchange.call_args.args,
("/mall/productAgent/validateRenderInput", b'{"id":5}'))
self.assertFalse(args.output.exists())
if __name__ == "__main__":
unittest.main()