CRM
Praxis CRM keeps contacts, companies, leads, deals, orders and their activity in one organization. Agents work through praxis.crm; people see the same records in Console. Objects, properties, pipelines, associations and custom schemas follow HubSpot CRM. Stage rules, lead qualification, change-set reversal and shared layouts extend that model. Industry processes are installed as settings, with no dedicated template-install endpoint.
When to use it
Contacts, leads, deals and orders shaped like HubSpot.
Use it when
- A sales pipeline, lead qualification, orders and payments.
Not for, use instead
- End users who sign in →
customer - Generic data →
database
How it behaves
- Use the stage ids the service returns;
crm.leads.qualifyturns a lead into a deal.
Combines with
- Records link from tickets.
Entry: praxis.crm.* · docs developers/crm/index
Quickstart
1. Have an agent install the industry flow
In a Praxis agent (or a connected Claude Code, Codex or Cursor), say:
Load the use-crm skill and install the travel CRM template in my organization.The agent installs custom objects → property groups and properties → pipelines and stage rules → layouts. The use-crm skill ships two templates, travel and industrial equipment; the sources are under Example sources.
Installing never overwrites your existing settings: identical definitions are skipped, a conflicting definition stops the install and says where it conflicts, and a failed install can resume with the same template. The install is not one atomic transaction across all settings.
You can also install with a script: create a client with new Praxis({ apiKey, baseUrl }) from @deepraxis/sdk and call installTemplate(praxis, template, log) from install-template.ts. The installer calls only standard CRM methods.
The service generates stage IDs. metadata.praxis_template_stage keeps template keys such as confirm; business writes must use the returned pipeline and stage IDs. The custom object types are p_installments (installments) and p_payables (supplier payables).
2. Capture a lead and turn it into a deal
Create a contact and a lead with praxis.crm.objects.create, associate them with praxis.crm.associations.createDefault, and move the lead through new → assigned → attempting. Once you have a verifiable contact detail (such as wechat_id), call praxis.crm.leads.qualify to turn the lead into a deal: the contact is kept, the deal lands in the needs-discussion stage, and its references come back in the response refs.
3. Advance the deal: stage rules stop missing fields
Fill in destination, travel_date and traveler_count, then advance to recommend. Entering confirm needs both budget and chosen_plan. With one missing, the service returns HTTP 400 with category VALIDATION_ERROR, errors[].context.properties names the missing field, the deal stays in recommend, and nothing is partially saved. Fill in the rest, then advance to confirm and deposit_received.
4. Create an order and reconcile receipts
Create an order associated with the deal and add an installment to it (for example amount "2000", status pending). When the installment changes to received, the order’s received_total rolls up to "2000". The order’s platform_fee is computed from two source properties: with group_buy_amount "10000" and received_amount "2000" it is "8000". Record only money actually received; the CRM does not collect payments or convert currencies.
Write responses carry refs[].viewer_url, the record’s own page. Paste that link into a conversation or ticket and it renders as a reference card that opens a quick view.
Run the whole flow first
acceptance.ts under Example sources runs the four steps end to end and writes demo records. Run it in a separate, newly created, empty organization, never in your real one:
export PRAXIS_API_URL=https://api.deepraxis.comexport PRAXIS_API_KEY=<that empty organization's API key>bun acceptance.ts --fresh-test-orgBefore writing, the script checks whether the organization already has records or custom objects, and stops if it does. That is a safeguard; it does not replace your own check that the key belongs to the empty organization.
Stage rules
| Metadata key | Meaning |
|---|---|
praxis_category | open, won or lost |
praxis_terminal | String "true" or "false"; terminal stages cannot be left |
praxis_allowed_next | JSON array string of actual stage ids; "null" permits any non-archived stage in the pipeline |
praxis_required | JSON array string of properties required before entry |
Send new property values and the target stage in one praxis.crm.objects.update request. A required bool must be the string "true", not "false". Deals use pipeline / dealstage; leads, orders and custom objects use hs_pipeline / hs_pipeline_stage. Choose the installed pipeline explicitly; installation keeps seeded defaults.
Travel order transitions copy TravelX OrderStatus. Settled is won but can still advance to archived; archived and refunded are terminal. Cancelled can reopen at pending_submit or enter refunding. Submitted requires dmc_name; pending_trip requires dmc_confirmed and balance_received; in_progress requires sign_result. Payables “status” is its pipeline stage, stored in hs_pipeline_stage.
When a rule rejects an edit, fill the named fields from evidence or ask the customer. Do not remove requirements, change pipelines or invent values to bypass it. The use-crm skill explains BANT decisions and recording the supporting conversation as an associated note.
received_total is a read-only filtered sum of associated p_installments amounts whose status is received. platform_fee is calculated from the order’s two source properties. Templates do not collect payments or convert currencies; amounts are decimal strings in your business currency. Multi-select properties use enumeration / checkbox, with semicolon-separated values.
To undo an action, retrieve the affected properties with propertiesWithHistory, keep the changeSetId, and call praxis.crm.changes.revert({ path: { changeSetId } }). A later conflicting edit causes 409; read the current values before deciding what to do. Reversal is not a deletion of created records or a template uninstall.
HubSpot compatibility
The native API is /crm/v1. For an official HubSpot client, point its base URL at https://api.deepraxis.com/hubspot and authenticate with a Praxis key. For example, the official Node client accepts new Client({ accessToken: process.env.PRAXIS_API_KEY, basePath: "https://api.deepraxis.com/hubspot" }); see HubSpot’s client. Object definitions follow the HubSpot custom object model.
Compatibility is limited to the implemented CRM operations, not the entire HubSpot product or its billing tiers. Use the native SDK for Praxis extensions: qualification, reversal, layouts, rule metadata, calculation and rollup types. The native and HubSpot faces use the same organization records.
Limits and errors
| Limit | Current value |
|---|---|
| Request body / stored record properties | 256 KiB each |
| Batch request | At most 100 inputs |
| Pipeline / custom schema creation | At most 100 stages / 1,000 properties |
| Search page | At most 200 records; follow the opaque paging.next.after cursor |
| Per-request rollup recomputations | At most 200 writes |
| Association traversal / materialized read | At most 10,000 edges / 2 MiB |
| HTTP / category | Recovery |
|---|---|
400 VALIDATION_ERROR | Read errors[].context.properties; supply missing evidence, choose an allowed transition, or edit computed-field inputs. LIMIT_EXCEEDED also maps here: reduce the request or relationship fanout. |
400 BAD_REQUEST | Correct malformed properties or cursor; do not retry unchanged. |
| 401 / 403 | Provide a valid key for the intended organization or obtain access. |
404 OBJECT_NOT_FOUND | Rediscover an accessible object type, record, property, pipeline or stage. |
409 CONFLICT | Re-read unique values or later edits before resolving duplicates or reversal conflicts. |
Example sources
These sources match the built-in use-crm skill byte for byte. They call only generated CRM SDK methods; the installer keeps the service’s calculation, rollup and file wire fields even where the generated HubSpot property types omit those extensions.
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);}Next steps
- CRM API reference: the native operations, the HubSpot-compatible surface and error codes.
- API keys: the requests above and the HubSpot client both authenticate with a Praxis key; create one first.
- Agents: agents act on these records through
praxis.crm; start with how to configure and run one.