客户关系管理(CRM)
Praxis CRM 将联系人、公司、线索、商机、订单和沟通记录保存在同一组织。智能体通过 praxis.crm 操作,人在 Console 查看相同的记录。对象、属性、流水线、关联和自定义对象模型兼容 HubSpot CRM;阶段规则、线索合格、按请求撤销和共享布局是 Praxis 的扩展。行业流程以设置模板装入组织,没有专门的「装模板」接口。
快速开始
1. 让智能体装上行业流程
在 Praxis 智能体(或接入的 Claude Code、Codex、Cursor)里说:
加载 use-crm 技能,在我的组织里装上旅游行业的 CRM 模板。智能体会依次装好自定义对象 → 属性组与属性 → 流水线与阶段规则 → 布局。use-crm 技能附带旅游和工业设备两个模板,源码见示例源码。
安装不会覆盖你已有的设置:定义一致的跳过,定义冲突的停下并告诉你哪里冲突;中途失败可以用同一个模板续装。安装不是跨所有设置的原子事务。
也可以自己用脚本装:用 @deepraxis/sdk 的 new Praxis({ apiKey, baseUrl }) 建客户端,调用 install-template.ts 的 installTemplate(praxis, template, log)。安装器只调用标准的 CRM 方法。
阶段由服务生成 ID。metadata.praxis_template_stage 记着 confirm 这类模板键;业务写入要用返回的流水线和阶段 ID。自定义对象类型是 p_installments(分期)和 p_payables(供应商应付)。
2. 录线索并转成商机
用 praxis.crm.objects.create 建联系人和线索,用 praxis.crm.associations.createDefault 关联,按 new → assigned → attempting 推进。有了可核实的联系方式(如 wechat_id)后,调用 praxis.crm.leads.qualify 把线索转成商机:保留联系人,商机落在需求沟通阶段,引用在响应的 refs 里返回。
3. 推进商机:阶段规则会拦住缺项
填写 destination、travel_date、traveler_count 后推进到 recommend。要进入 confirm,必须同时有 budget 和 chosen_plan;缺一项时服务返回 HTTP 400、类别 VALIDATION_ERROR,errors[].context.properties 列出缺的字段,商机仍停在 recommend,已填的字段也不会被部分保存。补齐后再推进到 confirm、deposit_received。
4. 建订单并核对收款
建订单并关联商机,为订单建分期(如金额 "2000"、状态 pending)。分期改为 received 后,订单的 received_total 自动汇总为 "2000"。订单的 platform_fee 由两个来源属性算出,例如 group_buy_amount "10000"、received_amount "2000" 时为 "8000"。只登记真实收到的钱;CRM 不代收款,也不换算币种。
写操作的响应里有 refs[].viewer_url,打开就是这条记录的页面。在对话或工单里贴这个链接,会显示成引用卡片,点开快速查看。
想先完整演一遍
示例源码里的 acceptance.ts 会把上面四步连起来跑一遍,并写入演示记录。请在一个单独新建的空组织里跑,不要用正式组织:
export PRAXIS_API_URL=https://api.deepraxis.comexport PRAXIS_API_KEY=<这个空组织的 API Key>bun acceptance.ts --fresh-test-org脚本在写入前会检查组织里是否已有记录或自定义对象,有就停下。这只是保险,不能代替你确认 Key 属于那个空组织。
阶段规则
| metadata 字段 | 含义 |
|---|---|
praxis_category | open、won、lost |
praxis_terminal | 字符串 “true” / “false”;终点不能离开 |
praxis_allowed_next | 实际阶段 ID 的 JSON 数组字符串;“null” 表示不限,可进入同流水线未归档阶段 |
praxis_required | 进入阶段前必须具备的属性名 JSON 数组字符串 |
用 praxis.crm.objects.update 在同一请求中提交新属性和目标阶段;必填 bool 必须为字符串 "true","false" 不算满足。商机使用 pipeline / dealstage,线索、订单及自定义对象使用 hs_pipeline / hs_pipeline_stage。明确选择安装的流水线;模板保留系统默认流水线。
旅游订单严格按 TravelX OrderStatus 流转:settled 类别为 won,但仍能进入 archived;archived 和 refunded 才是终点。cancelled 可以重新进入 pending_submit 或 refunding。submitted 必填 dmc_name;pending_trip 必填 dmc_confirmed、balance_received;in_progress 必填 sign_result。供应商应付的「状态」由流水线阶段 hs_pipeline_stage 表示。
被规则拒绝时,根据证据补齐缺项或询问客户;不能删除必填、换流水线或编造值来绕过。use-crm 技能说明如何按 BANT 判断阶段,并把沟通依据写成关联 note。
received_total 为只读汇总:关联的 p_installments 中 status 为 received 的 amount 之和。platform_fee 根据订单两个来源属性计算。模板不执行收款或币种换算;金额用业务币种的十进制字符串。多选属性用 enumeration / checkbox,记录值以分号连接。
要撤销动作,通过带 propertiesWithHistory 的记录读取取回 changeSetId,调用 praxis.crm.changes.revert({ path: { changeSetId } })。后续编辑冲突会返回 409,应先读取现值。撤销不代表删除新建记录,也不是卸载模板。
HubSpot 兼容面
自有 API 为 /crm/v1。使用 HubSpot 官方客户端时,把 base URL 指到 https://api.deepraxis.com/hubspot,认证使用 Praxis key。例如官方 Node 客户端可配置 new Client({ accessToken: process.env.PRAXIS_API_KEY, basePath: "https://api.deepraxis.com/hubspot" });参见 HubSpot 客户端。对象模型参考 HubSpot 自定义对象。
兼容范围限于已实现的 CRM 操作,不代表整个 HubSpot 产品或其付费套餐。线索合格、撤销、布局、规则 metadata、calculation 与 rollup 类型使用 Praxis 自有 SDK。自有面和 HubSpot 兼容面使用同一组织的记录。
限额与错误
| 限额 | 当前值 |
|---|---|
| 请求体 / 单条记录属性 | 分别不超过 256 KiB |
| 批量请求 | 最多 100 条输入 |
| 创建流水线 / 自定义 schema | 最多 100 个阶段 / 1,000 个属性 |
| 搜索分页 | 最多 200 条;用不透明的 paging.next.after 继续 |
| 单请求汇总重算 | 最多 200 次写入 |
| 关联遍历 / 物化读取 | 最多 10,000 条边 / 2 MiB |
| HTTP / 类别 | 下一步 |
|---|---|
400 VALIDATION_ERROR | 检查 errors[].context.properties,补齐有依据的字段、选择允许的阶段或编辑计算字段的来源。LIMIT_EXCEEDED 也映射到此类别,应缩小请求或关联规模。 |
400 BAD_REQUEST | 修正属性请求或游标,不原样重试。 |
| 401 / 403 | 提供目标组织有效的 key,或取得访问权限。 |
404 OBJECT_NOT_FOUND | 重新查询有权限的对象、记录、属性、流水线或阶段。 |
409 CONFLICT | 先读现值,处理唯一值重复或撤销时的后续编辑冲突。 |
示例源码
以下文件与 use-crm 技能中的源码逐字一致,只调用已生成的 CRM SDK 方法。安装器保留服务支持的 calculation、rollup、file 等线字段,尽管生成的 HubSpot 属性类型尚未完整描述这些扩展。
templates/travel.json
{ "name": "travel", "label": "旅游", "objects": [ { "name": "installments", "labels": { "singular": "分期", "plural": "分期" }, "primaryDisplayProperty": "installment_name", "secondaryDisplayProperties": [], "requiredProperties": [ "installment_name" ], "searchableProperties": [ "installment_name" ], "properties": [ { "name": "installment_name", "label": "分期名称", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "amount", "label": "金额", "type": "number", "fieldType": "number", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "due_date", "label": "到期日", "type": "date", "fieldType": "date", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "status", "label": "收款状态", "type": "enumeration", "fieldType": "select", "groupName": "custominformation", "hasUniqueValue": false, "options": [ { "value": "pending", "label": "待收", "displayOrder": 0, "hidden": false }, { "value": "received", "label": "已收", "displayOrder": 1, "hidden": false }, { "value": "waived", "label": "免收", "displayOrder": 2, "hidden": false } ] }, { "name": "payee_kind", "label": "收款方类型", "type": "enumeration", "fieldType": "select", "groupName": "custominformation", "hasUniqueValue": false, "options": [ { "value": "company", "label": "本公司", "displayOrder": 0, "hidden": false }, { "value": "supplier", "label": "供应商", "displayOrder": 1, "hidden": false }, { "value": "dmc_collect", "label": "地接代收", "displayOrder": 2, "hidden": false } ] }, { "name": "payee_name", "label": "收款方名称", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false } ], "associatedObjects": [ "orders" ], "allowsSensitiveProperties": false }, { "name": "payables", "labels": { "singular": "供应商应付", "plural": "供应商应付" }, "primaryDisplayProperty": "supplier_name", "secondaryDisplayProperties": [], "requiredProperties": [ "supplier_name" ], "searchableProperties": [ "supplier_name" ], "properties": [ { "name": "supplier_name", "label": "供应商名称", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "service", "label": "服务内容", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "amount", "label": "应付金额", "type": "number", "fieldType": "number", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "offset_collected", "label": "抵扣的代收", "type": "number", "fieldType": "number", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "settlement", "label": "结算方式", "type": "enumeration", "fieldType": "select", "groupName": "custominformation", "hasUniqueValue": false, "options": [ { "value": "prepaid_offset", "label": "预付抵扣", "displayOrder": 0, "hidden": false }, { "value": "cash", "label": "现金", "displayOrder": 1, "hidden": false } ] }, { "name": "hs_pipeline", "label": "流水线", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false }, { "name": "hs_pipeline_stage", "label": "阶段", "type": "string", "fieldType": "text", "groupName": "custominformation", "hasUniqueValue": false } ], "associatedObjects": [ "orders" ], "allowsSensitiveProperties": false } ], "properties": { "leads": [ { "name": "wechat_id", "label": "微信号", "type": "string", "fieldType": "text", "groupName": "leadsinformation", "hasUniqueValue": false } ], "deals": [ { "name": "destination", "label": "目的地", "type": "string", "fieldType": "text", "groupName": "需求", "hasUniqueValue": false }, { "name": "travel_date", "label": "出行日期", "type": "date", "fieldType": "date", "groupName": "需求", "hasUniqueValue": false }, { "name": "trip_days", "label": "行程天数", "type": "number", "fieldType": "number", "groupName": "需求", "hasUniqueValue": false }, { "name": "traveler_count", "label": "出行人数(如 2 大 1 小)", "type": "string", "fieldType": "text", "groupName": "需求", "hasUniqueValue": false }, { "name": "budget", "label": "预算", "type": "number", "fieldType": "number", "groupName": "需求", "hasUniqueValue": false }, { "name": "decision_note", "label": "决策说明", "type": "string", "fieldType": "text", "groupName": "需求", "hasUniqueValue": false }, { "name": "chosen_plan", "label": "所选方案", "type": "string", "fieldType": "text", "groupName": "需求", "hasUniqueValue": false }, { "name": "lost_reason", "label": "流失原因", "type": "enumeration", "fieldType": "select", "groupName": "需求", "hasUniqueValue": false, "options": [ { "value": "price", "label": "价格", "displayOrder": 0, "hidden": false }, { "value": "plan", "label": "行程方案", "displayOrder": 1, "hidden": false }, { "value": "timing", "label": "时间不合适", "displayOrder": 2, "hidden": false }, { "value": "no_response", "label": "未回应", "displayOrder": 3, "hidden": false }, { "value": "other", "label": "其他", "displayOrder": 4, "hidden": false } ] } ], "orders": [ { "name": "amount", "label": "订单金额", "type": "number", "fieldType": "number", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "trip_start", "label": "出行开始", "type": "date", "fieldType": "date", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "trip_end", "label": "出行结束", "type": "date", "fieldType": "date", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "landing_at", "label": "落地时间", "type": "datetime", "fieldType": "date", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "travelers", "label": "出行人", "type": "string", "fieldType": "text", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "dmc_name", "label": "地接名称", "type": "string", "fieldType": "text", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "dmc_confirmed", "label": "地接已确认", "type": "bool", "fieldType": "booleancheckbox", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "balance_received", "label": "已收尾款", "type": "bool", "fieldType": "booleancheckbox", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "sign_result", "label": "签单结果", "type": "enumeration", "fieldType": "select", "groupName": "ordersinformation", "hasUniqueValue": false, "options": [ { "value": "success", "label": "成功", "displayOrder": 0, "hidden": false }, { "value": "failed", "label": "失败", "displayOrder": 1, "hidden": false } ] }, { "name": "received_total", "label": "已收金额", "type": "rollup", "fieldType": "number", "groupName": "ordersinformation", "hasUniqueValue": false, "rollup": { "association": "p_installments", "property": "amount", "op": "sum", "where": [ { "propertyName": "status", "operator": "EQ", "value": "received" } ] } }, { "name": "group_buy_amount", "label": "团购金额", "type": "number", "fieldType": "number", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "received_amount", "label": "到账金额", "type": "number", "fieldType": "number", "groupName": "ordersinformation", "hasUniqueValue": false }, { "name": "platform_fee", "label": "平台费用", "type": "calculation", "fieldType": "calculation_equation", "groupName": "ordersinformation", "hasUniqueValue": false, "calculationFormula": "max(0, group_buy_amount - received_amount)" } ] }, "pipelines": { "leads": [ { "label": "旅游线索筛选", "displayOrder": 1, "stages": [ { "label": "新线索", "displayOrder": 0, "metadata": { "praxis_template_stage": "new", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"assigned\",\"invalid\"]", "praxis_required": "[]" } }, { "label": "已分配", "displayOrder": 1, "metadata": { "praxis_template_stage": "assigned", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"attempting\",\"invalid\"]", "praxis_required": "[]" } }, { "label": "尝试联系", "displayOrder": 2, "metadata": { "praxis_template_stage": "attempting", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"wechat_added\",\"invalid\"]", "praxis_required": "[]" } }, { "label": "已加微信", "displayOrder": 3, "metadata": { "praxis_template_stage": "wechat_added", "praxis_category": "won", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[\"wechat_id\"]" } }, { "label": "无效", "displayOrder": 4, "metadata": { "praxis_template_stage": "invalid", "praxis_category": "lost", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[]" } } ] } ], "deals": [ { "label": "旅游销售", "displayOrder": 1, "stages": [ { "label": "需求沟通", "displayOrder": 0, "metadata": { "praxis_template_stage": "needs", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"recommend\",\"lost\"]", "praxis_required": "[]", "probability": "0.1" } }, { "label": "方案推荐", "displayOrder": 1, "metadata": { "praxis_template_stage": "recommend", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"needs\",\"confirm\",\"lost\"]", "praxis_required": "[\"destination\",\"travel_date\",\"traveler_count\"]", "probability": "0.3" } }, { "label": "方案确认", "displayOrder": 2, "metadata": { "praxis_template_stage": "confirm", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"recommend\",\"deposit_received\",\"lost\"]", "praxis_required": "[\"budget\",\"chosen_plan\"]", "probability": "0.6" } }, { "label": "已收定金", "displayOrder": 3, "metadata": { "praxis_template_stage": "deposit_received", "praxis_category": "won", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[]", "probability": "1" } }, { "label": "流失", "displayOrder": 4, "metadata": { "praxis_template_stage": "lost", "praxis_category": "lost", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[\"lost_reason\"]", "probability": "0" } } ] } ], "orders": [ { "label": "旅游订单", "displayOrder": 1, "stages": [ { "label": "草稿、跟单中", "displayOrder": 0, "metadata": { "praxis_template_stage": "draft", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"pending_submit\",\"cancelled\",\"refunding\"]", "praxis_required": "[]" } }, { "label": "信息完善、待交单", "displayOrder": 1, "metadata": { "praxis_template_stage": "pending_submit", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"submitted\",\"draft\",\"cancelled\",\"refunding\"]", "praxis_required": "[]" } }, { "label": "已交给地接、待回传", "displayOrder": 2, "metadata": { "praxis_template_stage": "submitted", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"pending_trip\",\"pending_submit\",\"cancelled\",\"refunding\"]", "praxis_required": "[\"dmc_name\"]" } }, { "label": "待出行", "displayOrder": 3, "metadata": { "praxis_template_stage": "pending_trip", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"pending_sign\",\"in_progress\",\"pending_submit\",\"cancelled\",\"refunding\"]", "praxis_required": "[\"dmc_confirmed\",\"balance_received\"]" } }, { "label": "待签单", "displayOrder": 4, "metadata": { "praxis_template_stage": "pending_sign", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"in_progress\",\"sign_failed\"]", "praxis_required": "[]" } }, { "label": "出行中", "displayOrder": 5, "metadata": { "praxis_template_stage": "in_progress", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"pending_settle\",\"refunding\"]", "praxis_required": "[\"sign_result\"]" } }, { "label": "签单失败", "displayOrder": 6, "metadata": { "praxis_template_stage": "sign_failed", "praxis_category": "lost", "praxis_terminal": "false", "praxis_allowed_next": "[\"cancelled\",\"refunding\"]", "praxis_required": "[]" } }, { "label": "待结算", "displayOrder": 7, "metadata": { "praxis_template_stage": "pending_settle", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"settled\"]", "praxis_required": "[]" } }, { "label": "已结算", "displayOrder": 8, "metadata": { "praxis_template_stage": "settled", "praxis_category": "won", "praxis_terminal": "false", "praxis_allowed_next": "[\"archived\"]", "praxis_required": "[]" } }, { "label": "已归档", "displayOrder": 9, "metadata": { "praxis_template_stage": "archived", "praxis_category": "won", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[]" } }, { "label": "已取消", "displayOrder": 10, "metadata": { "praxis_template_stage": "cancelled", "praxis_category": "lost", "praxis_terminal": "false", "praxis_allowed_next": "[\"pending_submit\",\"refunding\"]", "praxis_required": "[]" } }, { "label": "退款中", "displayOrder": 11, "metadata": { "praxis_template_stage": "refunding", "praxis_category": "lost", "praxis_terminal": "false", "praxis_allowed_next": "[\"refunded\"]", "praxis_required": "[]" } }, { "label": "已退款", "displayOrder": 12, "metadata": { "praxis_template_stage": "refunded", "praxis_category": "lost", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[]" } } ] } ], "p_payables": [ { "label": "供应商应付", "displayOrder": 1, "stages": [ { "label": "待对账", "displayOrder": 0, "metadata": { "praxis_template_stage": "pending_reconcile", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"reconciled\"]", "praxis_required": "[]" } }, { "label": "已对账", "displayOrder": 1, "metadata": { "praxis_template_stage": "reconciled", "praxis_category": "open", "praxis_terminal": "false", "praxis_allowed_next": "[\"settled\"]", "praxis_required": "[]" } }, { "label": "已结算", "displayOrder": 2, "metadata": { "praxis_template_stage": "settled", "praxis_category": "won", "praxis_terminal": "true", "praxis_allowed_next": "[]", "praxis_required": "[]" } } ] } ] }, "layouts": { "deals": { "objectType": "deals", "summary": [ "amount" ], "sidebar": [ "dealname", "dealstage", "destination", "travel_date", "traveler_count", "budget", "chosen_plan" ], "sections": [ "group:需求", "activity", "assoc:contacts" ] }, "orders": { "objectType": "orders", "summary": [ "amount", { "property": "received_total", "of": "amount" } ], "sidebar": [ "hs_order_name", "hs_pipeline_stage", "trip_start", "trip_end", "dmc_name", "dmc_confirmed", "balance_received", "sign_result" ], "sections": [ "table:p_installments", "table:p_payables", "activity" ] } }}install-template.ts
import type * as SDK from "@deepraxis/sdk/types";
// Only generated wire types enter this Worker package's compiler; the SDK runtime uses its own DOM config.type Method<D, R> = (...args: {} extends Omit<D, "url"> ? [args?: Omit<D, "url">] : [args: Omit<D, "url">]) => Promise<R>;export interface CrmClient { crm: { schemas: { list: Method<SDK.CrmSchemasListData, SDK.CrmSchemasListResponse>; create: Method<SDK.CrmSchemasCreateData, SDK.CrmSchemasCreateResponse> }; objects: { list: Method<SDK.CrmObjectsListData, SDK.CrmObjectsListResponse>; create: Method<SDK.CrmObjectsCreateData, SDK.CrmObjectsCreateResponse>; retrieve: Method<SDK.CrmObjectsRetrieveData, SDK.CrmObjectsRetrieveResponse>; update: Method<SDK.CrmObjectsUpdateData, SDK.CrmObjectsUpdateResponse> }; properties: { list: Method<SDK.CrmPropertiesListData, SDK.CrmPropertiesListResponse>; create: Method<SDK.CrmPropertiesCreateData, SDK.CrmPropertiesCreateResponse>; groups: { list: Method<SDK.CrmPropertiesGroupsListData, SDK.CrmPropertiesGroupsListResponse>; create: Method<SDK.CrmPropertiesGroupsCreateData, SDK.CrmPropertiesGroupsCreateResponse> } }; pipelines: { list: Method<SDK.CrmPipelinesListData, SDK.CrmPipelinesListResponse>; create: Method<SDK.CrmPipelinesCreateData, SDK.CrmPipelinesCreateResponse>; stages: { update: Method<SDK.CrmPipelinesStagesUpdateData, SDK.CrmPipelinesStagesUpdateResponse> } }; layouts: { retrieve: Method<SDK.CrmLayoutsRetrieveData, SDK.CrmLayoutsRetrieveResponse>; update: Method<SDK.CrmLayoutsUpdateData, SDK.CrmLayoutsUpdateResponse> }; leads: { qualify: Method<SDK.CrmLeadsQualifyData, SDK.CrmLeadsQualifyResponse> }; associations: { createDefault: Method<SDK.CrmAssociationsCreateDefaultData, SDK.CrmAssociationsCreateDefaultResponse> }; };}
/** JSON templates use stable stage keys in metadata; the server assigns actual stage ids. */export interface TemplateProperty { name: string; label: string; type: string; fieldType: string; groupName: string; hasUniqueValue?: boolean; options?: { value: string; label: string; displayOrder: number; hidden: boolean }[]; calculationFormula?: string; rollup?: { association: string; property: string; op: string; where?: unknown[] };}export interface TemplateStage { label: string; displayOrder: number; metadata: Record<string, string> }export interface Template { name: string; label: string; objects: { name: string; labels: { singular: string; plural: string }; primaryDisplayProperty: string; properties: TemplateProperty[]; associatedObjects: string[]; requiredProperties: string[]; searchableProperties: string[]; secondaryDisplayProperties: string[]; allowsSensitiveProperties: boolean }[]; properties: Record<string, TemplateProperty[]>; pipelines: Record<string, { label: string; displayOrder: number; stages: TemplateStage[] }[]>; layouts: Record<string, { objectType: string; summary: (string | { property: string; of: string })[]; sidebar: string[]; sections: string[] }>;}export type Log = (entry: { step: string; request?: unknown; result?: unknown }) => void;type Wire = Record<string, any>;const same = (a: unknown, b: unknown): boolean => { const canonical = (v: any): any => Array.isArray(v) ? v.map(canonical) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map(k => [k, canonical(v[k])])) : v; return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));};const compatible = (actual: Wire, expected: Wire, keys: string[]) => keys.every(k => expected[k] === undefined || same(actual[k], expected[k]));const assert = (ok: unknown, message: string): void => { if (!ok) throw new Error(message); };
/** Installs settings only. Repeating an identical install skips writes; conflicts stop without replacing user settings. */export async function installTemplate(praxis: CrmClient, template: Template, log: Log = () => {}) { async function call<T>(step: string, request: unknown, run: () => Promise<T>): Promise<T> { log({ step, request }); const result = await run(); log({ step, result }); return result; } const schemas = await call("schemas.list", {}, () => praxis.crm.schemas.list()) as unknown as { results: Wire[] }; for (const body of template.objects) { const objectType = body.name.startsWith("p_") ? body.name : `p_${body.name}`; const found = schemas.results.find(s => s.name === objectType); if (found) { assert(compatible(found, body, ["labels", "primaryDisplayProperty", "associatedObjects", "requiredProperties"]), `Schema conflict: ${objectType}`); } else { await call("schemas.create", { body }, () => praxis.crm.schemas.create({ body: body as unknown as Parameters<CrmClient["crm"]["schemas"]["create"]>[0]["body"] })); } } const allProperties = { ...template.properties }; for (const schema of template.objects) allProperties[schema.name.startsWith("p_") ? schema.name : `p_${schema.name}`] = schema.properties; for (const [objectType, definitions] of Object.entries(allProperties)) { const path = { objectType }; const groups = await call("properties.groups.list", { path }, () => praxis.crm.properties.groups.list({ path })) as unknown as { results: Wire[] }; for (const [displayOrder, name] of [...new Set(definitions.map(p => p.groupName))].entries()) { if (!groups.results.some(g => g.name === name)) { const body = { name, label: name, displayOrder }; await call("properties.groups.create", { path, body }, () => praxis.crm.properties.groups.create({ path, body })); } } const existing = await call("properties.list", { path }, () => praxis.crm.properties.list({ path })) as unknown as { results: Wire[] }; for (const body of definitions) { const found = existing.results.find(p => p.name === body.name); if (found) { assert(compatible(found, body, ["label", "type", "fieldType", "groupName", "hasUniqueValue", "options", "rollup", "calculationFormula"]), `Property conflict: ${objectType}.${body.name}`); } else { // L4a's generated HubSpot type omits CRM's file/calculation/rollup extensions; preserve their wire fields. await call("properties.create", { path, body }, () => praxis.crm.properties.create({ path, body: body as unknown as Parameters<CrmClient["crm"]["properties"]["create"]>[0]["body"] })); } } } const pipelines: Record<string, { id: string; stages: Record<string, string> }> = {}; for (const [objectType, definitions] of Object.entries(template.pipelines)) { const path = { objectType }; const existing = await call("pipelines.list", { path }, () => praxis.crm.pipelines.list({ path })) as unknown as { results: Wire[] }; for (const definition of definitions) { const matches = existing.results.filter(p => p.label === definition.label); assert(matches.length <= 1, `Ambiguous pipeline: ${objectType}/${definition.label}`); const body = { ...definition, stages: definition.stages.map(s => ({ ...s, metadata: { ...s.metadata, praxis_allowed_next: "[]", praxis_template_pending: "true" } })) }; const pipeline = matches[0] ?? await call("pipelines.create", { path, body }, () => praxis.crm.pipelines.create({ path, body })) as unknown as Wire; assert(pipeline.displayOrder === definition.displayOrder && pipeline.stages.length === definition.stages.length, `Pipeline conflict: ${objectType}/${definition.label}`); const ids: Record<string, string> = {}; for (const stage of definition.stages) { const key = stage.metadata.praxis_template_stage!; const matches = pipeline.stages.filter((s: Wire) => s.metadata.praxis_template_stage === key); assert(matches.length === 1, `Missing or ambiguous stage: ${objectType}/${key}`); assert(matches[0].label === stage.label && matches[0].displayOrder === stage.displayOrder, `Stage definition conflict: ${objectType}/${key}`); ids[key] = matches[0].id; } for (const stage of definition.stages) { const key = stage.metadata.praxis_template_stage!; const allowed: string[] | null = JSON.parse(stage.metadata.praxis_allowed_next!); const translated = allowed === null ? null : allowed.map(k => { assert(ids[k], `Unknown next stage: ${k}`); return ids[k]!; }); const metadata = { ...stage.metadata, praxis_allowed_next: JSON.stringify(translated), praxis_template_pending: "false" }; const current = pipeline.stages.find((s: Wire) => s.id === ids[key]); if (compatible(current.metadata, metadata, Object.keys(metadata))) continue; assert(current.metadata.praxis_template_pending === "true", `Stage rules conflict: ${objectType}/${key}`); const stagePath = { objectType, pipelineId: pipeline.id, stageId: ids[key]! }; await call("pipelines.stages.update", { path: stagePath, body: { metadata } }, () => praxis.crm.pipelines.stages.update({ path: stagePath, body: { metadata } })); } pipelines[objectType] = { id: pipeline.id, stages: ids }; } } for (const [objectType, body] of Object.entries(template.layouts)) { const path = { objectType }; const current = await call("layouts.retrieve", { path }, () => praxis.crm.layouts.retrieve({ path })); if (same(current, body)) continue; // A template owns the layouts of the objects it configures: the service default or an earlier layout is replaced (the retrieve above is logged). await call("layouts.update", { path, body }, () => praxis.crm.layouts.update({ path, body })); } return pipelines;}acceptance.ts
/** Run only with an API key belonging to a NEW, empty Develop test organization. Never refreshes credentials. */// Load the SDK with its own runtime/compiler settings, outside the Worker's dependency graph.const sdkPackage = "@deepraxis/sdk";const { Praxis, PraxisError } = await import(sdkPackage);import { readFile } from "node:fs/promises";import { installTemplate, type Template, type Log, type CrmClient } from "./install-template";
type Wire = Record<string, any>;const check = (condition: unknown, message: string): void => { if (!condition) throw new Error(message); };export const printStep: Log = entry => console.log(JSON.stringify(entry));
/** Injectable SDK client makes the same scenario runnable against a local HTTP fixture. */export async function runAcceptance(praxis: CrmClient, template: Template, log: Log = printStep) { async function step<T>(name: string, request: unknown, run: () => Promise<T>): Promise<T> { log({ step: name, request }); try { const result = await run(); log({ step: name, result }); return result; } catch (error) { if (error instanceof PraxisError) { const failure = error as Wire; log({ step: name, result: { status: failure.status, requestId: failure.requestId, error: failure.raw } }); } throw error; } } check(template.name === "travel", "This acceptance scenario requires the travel template"); const schemas = await step("fresh organization: schemas", {}, () => praxis.crm.schemas.list()) as unknown as { results: Wire[] }; check(schemas.results.length > 0 && schemas.results.every(s => !s.name.startsWith("p_")), "Expected a new organization without custom objects"); // All reads precede the first write. Do not mutate an organization that already has CRM data. for (const schema of schemas.results) { const args = { path: { objectType: schema.name }, query: { limit: 1 } }; const records = await step(`fresh organization: ${schema.name}`, args, () => praxis.crm.objects.list(args)); check(records.results.length === 0, `Organization is not empty: ${schema.name}`); const archivedArgs = { ...args, query: { limit: 1, archived: true } }; const archived = await step(`fresh organization: archived ${schema.name}`, archivedArgs, () => praxis.crm.objects.list(archivedArgs)); check(archived.results.length === 0, `Organization has archived records: ${schema.name}`); } const pipelines = await installTemplate(praxis, template, log); // An identical second install must not create duplicates or replace existing settings. const again = await installTemplate(praxis, template, entry => { check(!/\.(create|update)$/.test(entry.step), `Second install attempted a write: ${entry.step}`); log(entry); }); check(JSON.stringify(pipelines) === JSON.stringify(again), "Repeated installation changed pipeline ids"); const leads = pipelines.leads!, deals = pipelines.deals!, orders = pipelines.orders!; const create = async (objectType: string, properties: Record<string, string>) => { const args = { path: { objectType }, body: { properties, associations: [] } }; return step(`objects.create ${objectType}`, args, () => praxis.crm.objects.create(args)); }; const update = async (objectType: string, objectId: string, properties: Record<string, string>) => { const args = { path: { objectType, objectId }, body: { properties } }; return step(`objects.update ${objectType}`, args, () => praxis.crm.objects.update(args)); }; const associate = async (objectType: string, objectId: string, toObjectType: string, toObjectId: string) => { const args = { path: { objectType, objectId, toObjectType, toObjectId } }; return step("associations.createDefault", args, () => praxis.crm.associations.createDefault(args)); }; const contact = await create("contacts", { firstname: "Travel acceptance", email: `crm-l4b-${Date.now()}@example.invalid` }); const lead = await create("leads", { hs_lead_name: "Travel template acceptance", hs_pipeline: leads.id, hs_pipeline_stage: leads.stages.new! }); await associate("leads", lead.id, "contacts", contact.id); await update("leads", lead.id, { hs_pipeline_stage: leads.stages.assigned! }); await update("leads", lead.id, { hs_pipeline_stage: leads.stages.attempting!, wechat_id: "test-traveler" }); const qualifyArgs = { path: { leadId: lead.id }, body: { contact: { kind: "keep" as const }, company: { kind: "none" as const }, qualifiedStageId: leads.stages.wechat_added!, deal: { pipelineId: deals.id, stageId: deals.stages.needs!, properties: { dealname: "Travel L4b acceptance", amount: "10000" } } } }; const qualified = await step("leads.qualify", qualifyArgs, () => praxis.crm.leads.qualify(qualifyArgs)) as unknown as Wire; const dealRef = qualified.refs?.find((r: Wire) => r.object === "deals"); check(dealRef?.id && dealRef.viewer_url, "Qualify must return the new deal's reference and viewer_url"); const dealId = dealRef.id as string; await update("deals", dealId, { dealstage: deals.stages.recommend!, destination: "云南", travel_date: "2026-12-01", traveler_count: "2 大 1 小" }); let rejected = false; try { await update("deals", dealId, { dealstage: deals.stages.confirm!, budget: "10000" }); } catch (error) { if (!(error instanceof PraxisError)) throw error; const failure = error as Wire; const raw = failure.raw as Wire; check(failure.status === 400 && raw?.category === "VALIDATION_ERROR", "Expected 400 VALIDATION_ERROR"); check(raw.errors?.some((e: Wire) => e.context?.properties?.includes("chosen_plan")), "Error must name chosen_plan"); rejected = true; } check(rejected, "Missing chosen_plan was accepted"); const beforeArgs = { path: { objectType: "deals", objectId: dealId }, query: { properties: ["dealstage", "budget"] } }; const before = await step("verify rejected transition was atomic", beforeArgs, () => praxis.crm.objects.retrieve(beforeArgs)); check(before.properties.dealstage === deals.stages.recommend! && !before.properties.budget, "Rejected transition persisted partial data"); await update("deals", dealId, { dealstage: deals.stages.confirm!, budget: "10000", chosen_plan: "云南六日家庭游" }); await update("deals", dealId, { dealstage: deals.stages.deposit_received! }); const order = await create("orders", { hs_order_name: "Travel L4b order", hs_pipeline: orders.id, hs_pipeline_stage: orders.stages.draft!, amount: "10000", group_buy_amount: "10000", received_amount: "2000" }); await associate("orders", order.id, "deals", dealId); const installment = await create("p_installments", { installment_name: "定金", amount: "2000", due_date: "2026-11-01", status: "pending", payee_kind: "company", payee_name: "Test company" }); await associate("p_installments", installment.id, "orders", order.id); const getOrder = async (name: string) => { const args = { path: { objectType: "orders", objectId: order.id }, query: { properties: ["received_total", "amount", "platform_fee"] } }; return step(name, args, () => praxis.crm.objects.retrieve(args)); }; const unpaid = await getOrder("verify pending installment excluded"); check(unpaid.properties.received_total === "0", "Pending installment counted as received"); await update("p_installments", installment.id, { status: "received" }); const paid = await getOrder("verify order received_total"); check(paid.properties.received_total === "2000", "Expected received_total=2000"); check(paid.properties.platform_fee === "8000", "Expected platform_fee=8000"); const layoutArgs = { path: { objectType: "orders" } }; const layout = await step("verify order layout", layoutArgs, () => praxis.crm.layouts.retrieve(layoutArgs)); check(layout.sections.includes("table:p_installments"), "Order layout must show installments"); const refs = (order as unknown as Wire).refs; check(refs?.some((r: Wire) => r.object === "orders" && r.id === order.id && r.viewer_url), "Order write did not return viewer_url"); const result = { status: "passed", leadId: lead.id, dealId, orderId: order.id, installmentId: installment.id, received_total: paid.properties.received_total, refs }; log({ step: "acceptance complete", result }); return result;}
if (import.meta.main) { const { PRAXIS_API_URL: baseUrl, PRAXIS_API_KEY: apiKey } = process.env; // The script writes data: it runs only against a non-production API host (the first label ends in "-develop"). const develop = baseUrl !== undefined && new URL(baseUrl).hostname.split(".")[0]!.endsWith("-develop"); if (!develop || !apiKey || !process.argv.includes("--fresh-test-org")) { throw new Error("Set PRAXIS_API_URL to the develop API host, PRAXIS_API_KEY for a NEW empty test organization, and pass --fresh-test-org"); } const template = JSON.parse(await readFile(new URL("./templates/travel.json", import.meta.url), "utf8")) as Template; await runAcceptance(new Praxis({ baseUrl, apiKey, maxRetries: 0, timeoutMs: 30_000 }), template);}下一步
- CRM API 参考:自有接口、HubSpot 兼容面与错误码。
- API Keys:上面的请求和 HubSpot 客户端都用 Praxis key 认证,先在这里创建。
- 智能体:智能体通过
praxis.crm操作这些记录,先了解怎么配置并运行一个智能体。