diff --git a/.changeset/2804-contract-form-change.md b/.changeset/2804-contract-form-change.md
new file mode 100644
index 000000000..8f659dda8
--- /dev/null
+++ b/.changeset/2804-contract-form-change.md
@@ -0,0 +1,8 @@
+---
+"hotcrm": minor
+---
+
+Clause-②: no
+Metadata-protocol: none
+
+**Sales: contract forms, an order contract that follows its order, and Change on an activated contract (#2804).** Every contract now has a **Contract Form**: **Order Contract**, **Framework Contract** or **Other**. It sits beside **Contract Type**, which is unchanged. **Draft Contract** on an order makes an order contract that names the order as its **Source Order**; its value is the order's total, tax included, it is read-only on the form, and while the contract is a draft a change to the order's amount changes the contract's value too. A contract you create by hand is a framework contract (value typed, may carry many orders) or Other (no amount needed, such as an NDA; the value starts at 0); you choose while it is a draft. Once a contract is activated, its **Contract Value**, **End Date** and **Payment Terms** are read-only on the form and change only through the new **Change** button: it asks for a reason and the signed amendment, and saves nothing without both. On a framework contract Change may set a new value; on an order contract it offers no value, only **Update from Order**, which takes the order's current amount. A new end date and new payment terms are optional on both. The contract stays Activated, so renewal reminders and expiry go on as before; Change creates no change order, does not touch the order and does not re-plan payments. History is now kept on the value, the start and end dates, the payment terms and the change reason, so the record's History shows each change before and after, who made it and when. If an order's amount changes after its contract is activated, the contract shows **Differs from the Order Amount**. A direct edit of those three fields on an activated contract, through the form or the API, is now refused and names the field (it used to refuse only an earlier end date). Contracts that already exist take a form on their next save: one drafted by Draft Contract and named by its order is an order contract, one with no value is Other, the rest are framework contracts; values are not changed. After upgrading, an administrator runs `pnpm exec objectstack migrate summary-nulls --apply --yes` (the platform's step that computes **Order Amount** on existing contracts), then `pnpm exec tsx scripts/backfill-contract-form.ts --apply`, which gives every existing contract its form at once and prints the order contracts whose value differs from their order, for the business to check; neither step changes a value. Labels, buttons and messages are in English, Chinese, Spanish and Japanese, and the Contracts manual and in-app help describe the rules.
diff --git a/README.md b/README.md
index 8729316fd..fc37f3c85 100644
--- a/README.md
+++ b/README.md
@@ -107,7 +107,7 @@ Open and sign in as `admin@objectos.ai` / `adm
The definition is the app. Objects and fields, rules, screens, flows, permissions and translations are typed metadata under `src/`: change a field there and the table, the API and the screens follow, with no second application to keep in step. An AI coding agent such as Claude Code writes that change in your copy of the repository, and `pnpm validate` checks it against the platform's schema before it ships.
-Today the definition holds **38 business objects**, **54 actions**, **53 flows**, **7 dashboards**, **11 datasets** and **18 positions**, in **4 languages** (en, zh-CN, es-ES, ja-JP).
+Today the definition holds **38 business objects**, **56 actions**, **53 flows**, **7 dashboards**, **11 datasets** and **18 positions**, in **4 languages** (en, zh-CN, es-ES, ja-JP).
HotCRM is built on [ObjectStack](https://github.com/objectstack-ai/objectstack), the open-source platform that runs one business definition as the database, the API, the screens and the agent tools at once. [Customize and extend](https://hotcrm.com/docs/developers/customize-and-extend) walks through a change.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 647c07a27..663dc8f93 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -107,7 +107,7 @@ pnpm dev
定义就是应用。对象和字段、规则、界面、流程、权限和翻译都是 `src/` 下的类型化元数据:在那里改一个字段,数据表、API 和界面随之一起变,没有第二套应用需要同步。像 Claude Code 这样的 AI 编程智能体在你的仓库副本里写下这次改动,`pnpm validate` 在发布前按平台的 schema 检查它。
-目前这份定义包含 **38 个业务对象**、**54 个动作**、**53 个流程**、**7 个仪表盘**、**11 个数据集**和 **18 个岗位**,支持 **4 种语言**(en、zh-CN、es-ES、ja-JP)。
+目前这份定义包含 **38 个业务对象**、**56 个动作**、**53 个流程**、**7 个仪表盘**、**11 个数据集**和 **18 个岗位**,支持 **4 种语言**(en、zh-CN、es-ES、ja-JP)。
HotCRM 构建在 [ObjectStack](https://github.com/objectstack-ai/objectstack) 之上:这个开源平台把一份业务定义同时运行为数据库、API、界面和智能体工具。[定制与扩展](https://hotcrm.com/zh-Hans/docs/developers/customize-and-extend) 演示了一次改动的全过程。
diff --git a/content/docs/(product)/sales/contracts.mdx b/content/docs/(product)/sales/contracts.mdx
index 6dd08d888..9f0ca0883 100644
--- a/content/docs/(product)/sales/contracts.mdx
+++ b/content/docs/(product)/sales/contracts.mdx
@@ -19,6 +19,34 @@ A **contract** is the legal agreement between your company and a customer — wh
Activation is the key transition — it triggers the account to be promoted to *Customer*.
+## The contract form: order, framework or other
+
+Every contract has a **Contract Form**, which decides where its value comes from. It sits beside the contract type and does not replace it: the type says *what* is agreed (a subscription, a service, an NDA), the form says what the contract is *for*.
+
+| Form | How it is made | Its value |
+| --- | --- | --- |
+| **Order Contract** | **Draft Contract** on an order — never by hand | The order's total, tax included. Read-only on the form |
+| **Framework Contract** | By hand — the default for a new contract | Typed by hand. It may carry many orders |
+| **Other** | By hand | No amount needed, such as an NDA. The value is 0 unless you type one |
+
+You choose **Framework Contract** or **Other** while the contract is a draft; once it leaves Draft, the form is fixed. An order contract stays an order contract, and its **Source Order** names the order it was drafted from.
+
+**An order contract follows its order while it is a draft.** Its **Order Amount** and its **Contract Value** are the order's total: change the order (or the quote it came from), and the draft contract's value changes with it. Nobody types the value of an order contract.
+
+**Once the contract is activated, its value stays as signed.** If the order's amount changes afterwards, the contract shows **Differs from the Order Amount**, and its value does not move until someone runs **Change** with **Update from Order** (below).
+
+Contracts that existed before contract forms took one by this rule, the first time each was saved after the upgrade: a contract drafted by **Draft Contract** and named by its order is an order contract; a contract with no value is **Other**; every other contract is a framework contract. An order contract whose value already differed from its order was left as it was, showing **Differs from the Order Amount**, for the business to check.
+
+## Changing an activated contract
+
+On an **Activated** contract, the **Contract Value**, the **End Date** and the **Payment Terms** are read-only on the form. They change only through **Change**, on the contract's header:
+
+- Give a **Change Reason** and upload the **Signed Amendment** the customer signed. Change without both does not save.
+- A framework (or other) contract may be given a **New Contract Value**. An order contract is offered no value at all: tick **Update from Order** to take the order's current amount.
+- A **New End Date** and **New Payment Terms** are optional. A field left empty keeps its value. When the new end date takes the term out of step with **Contract Term (Months)**, the term is counted again from the dates.
+
+The contract stays **Activated**, so renewal reminders and the expiration sweep go on as before. Change creates no change order, does not change the order, and does not re-plan the payments. The contract's **History** shows each value before and after, who changed it and when, and the **Last Change** section shows the latest reason and amendment.
+
## The 6 contract types
| Type | Use for |
@@ -32,18 +60,19 @@ Activation is the key transition — it triggers the account to be promoted to *
## What a contract record stores
-A contract record declares its fields in **six groups**. The contract form shows a curated subset of them across its tabs, so read this as the full inventory of what a contract carries rather than a screen-by-screen map:
+A contract record declares its fields in **seven groups**. The contract form shows a curated subset of them across its tabs, so read this as the full inventory of what a contract carries rather than a screen-by-screen map:
| Group | What's in it |
| --- | --- |
-| **Contract Information** | Contract Name, Contract Number *(auto-numbered `CTR-0001`)*, Contract Type, Contract Document, Description |
+| **Contract Information** | Contract Name, Contract Form, Source Order, Contract Number *(auto-numbered `CTR-0001`)*, Contract Type, Contract Document, Description |
| **Parties** | Contract Owner, Account, Primary Contact, Related Opportunity — the contact and opportunity pickers are scoped to the account you pick first |
| **Terms & Dates** | Contract Term (Months), Start Date, End Date, Special Terms |
-| **Contract Value** | Contract Value, Billing Frequency, Payment Terms, Billing Address |
+| **Contract Value** | Contract Value, Order Amount and Differs from the Order Amount *(order contracts)*, Billing Frequency, Payment Terms, Billing Address |
| **Status & Approval** | Status, Signed Date, Signed By, Signed Copy |
| **Renewal** | Auto Renewal, Renewal Notice (Days) |
+| **Last Change** | Change Reason, Signed Amendment — written by **Change** |
-Contract Name, Account, Primary Contact, Contract Term, Start Date, End Date, Contract Value and Status are all **required** — a contract cannot be saved without them.
+Contract Name, Contract Form, Account, Primary Contact, Contract Term, Start Date, End Date, Contract Value and Status are all **required** — a contract cannot be saved without them. Contract Value starts at 0, so an Other contract needs no amount typed.
## The contract's name and number
@@ -149,15 +178,16 @@ Terminating a contract is a status change to *Terminated*, and two things about
**And it is final.** An edit that moves a terminated contract to any other status is refused, and the contract stays *Terminated* — see *The status progression is a gate* below; a replacement is a new contract. The rest of the contract stays editable: a change to its notes, its terms or its primary contact saves as long as the status is left as it is.
-**Status** is one of the two fields Contract keeps history on, so the audit log does record who moved it and when.
+**Status** is one of the fields Contract keeps history on, so the audit log does record who moved it and when. The others are the owner, the start and end dates, the value, the payment terms and the change reason.
## Built-in rules
-Five rules reject a save outright:
+Six rules reject a save outright:
- **End date must be after start date** — a validation rule on the object.
- **The term must match the dates** — the contract hook counts the months between **Start Date** and **End Date** and rejects anything more than **one month** away from **Contract Term (Months)**: *"Contract term (12 months) does not match date range (6 months from … to …)."* Term and dates move together, or the save bounces.
-- **An activated contract's end date cannot be pulled in** — once the contract is *Activated*, an edit that moves **End Date** earlier is refused (*"Cannot shrink end_date … after activation"*). Pushing it out is fine; shortening a live agreement is a termination or an amendment, not an edit.
+- **An activated contract changes only through Change** — once the contract is *Activated*, an edit to **Contract Value**, **End Date** or **Payment Terms** is refused, naming the field (*"An activated contract's End Date changes only through Change, with a reason and the signed amendment."*). See *Changing an activated contract* above.
+- **An order contract's value is its order's** — typing **Contract Value** on an order contract is refused, whatever its status.
- **Activated requires a signed copy** — a save that moves a contract to *Activated*, or creates one already *Activated*, without a **Signed Copy** is refused on that field; see *Printing a contract and the signed copy* above.
- **The status progression is a gate.** The route is *Draft* → *In Approval* → *Activated* → *Expired* or *Terminated*, with *In Approval* able to go back to *Draft*, *Terminated* reachable from all three live statuses, and *Expired* and *Terminated* both final: a renewal is a new contract, never a revived one. A status change off that route — *Draft* straight to *Activated*, *Activated* back to *Draft*, or reviving an *Expired* or *Terminated* contract — is refused on **Status** with *"This status change is not allowed. A contract moves Draft → In Approval → Activated → Expired; In Approval can go back to Draft, and Draft, In Approval or Activated can be Terminated. Expired and Terminated are final: a renewal is a new contract."*, and the contract keeps its status, whether the change comes from the Edit form or the REST API (`400 VALIDATION_FAILED`). Only a change of the status is judged: any other edit saves on any contract, an expired or terminated one included. A contract *created* directly as *Activated* or *Expired* is not checked by this rule, which is the same import path that skips the activation writes described above; one created *Activated* still needs its **Signed Copy**.
diff --git a/content/docs/(product)/sales/contracts.zh-Hans.mdx b/content/docs/(product)/sales/contracts.zh-Hans.mdx
index b4764cd54..fa01686cc 100644
--- a/content/docs/(product)/sales/contracts.zh-Hans.mdx
+++ b/content/docs/(product)/sales/contracts.zh-Hans.mdx
@@ -19,6 +19,34 @@ description: 与客户签署的协议——条款、价值、续约,以及自
激活是关键转换——它会触发账户被提升为 *Customer*。
+## 合同形式:订单合同、框架合同或其他 [#the-contract-form-order-framework-or-other]
+
+每份合同都有一个**合同形式**,它决定合同金额从哪里来。它与合同类型并列,不取代合同类型:类型说的是约定了*什么*(订阅、服务、保密协议),形式说的是这份合同*用来做什么*。
+
+| 形式 | 怎么产生 | 合同金额 |
+| --- | --- | --- |
+| **订单合同** | 在订单上点**起草合同**——不能手工创建 | 订单的含税总额。表单上只读 |
+| **框架合同** | 手工创建——新建合同的默认形式 | 手工填写。可以挂多张订单 |
+| **其他** | 手工创建 | 不需要金额,例如保密协议。不填时金额为 0 |
+
+合同还是草稿时,你可以在**框架合同**和**其他**之间选择;离开草稿后形式就固定了。订单合同始终是订单合同,它的**来源订单**记着起草它的那张订单。
+
+**订单合同在草稿期间跟随订单。** 它的**订单金额**和**合同金额**就是订单的总额:修改订单(或订单来源的报价),草稿合同的金额随之变化。订单合同的金额没有人手工填写。
+
+**合同激活后,金额保持签署时的数字。** 之后订单金额再变,合同上会显示**与订单金额不一致**,金额本身不动,直到有人用**变更**并选择**按订单更新**(见下文)。
+
+升级之前已有的合同,在升级后第一次保存时按这条规则取得形式:由**起草合同**生成、且被其订单关联的合同是订单合同;没有金额的合同是**其他**;其余合同都是框架合同。金额已经与订单不一致的订单合同保持原样,显示**与订单金额不一致**,留给业务人员核对。
+
+## 变更已激活的合同 [#changing-an-activated-contract]
+
+**已激活**的合同上,**合同金额**、**结束日期**和**付款条款**在表单上只读,只能通过合同页头的**变更**修改:
+
+- 填写**变更原因**,并上传客户签署的**签署的变更协议**。两样缺一,变更存不下来。
+- 框架合同(或其他)可以填写**新合同金额**。订单合同不提供金额输入:勾选**按订单更新**,取订单的当前金额。
+- **新结束日期**和**新付款条款**可填可不填,留空的项保持不变。新结束日期让期限与**合同期限(月)**对不上时,期限会按日期重新计算。
+
+合同保持**已激活**,所以续约提醒和到期扫描照常进行。变更不会生成变更单,不会修改订单,也不会重新规划回款。合同的**历史**里能看到每个值改前改后、谁改的、何时改的;**最近一次变更**一节显示最近一次的原因和变更协议。
+
## 6 种合同类型
| 类型 | 用于 |
@@ -32,18 +60,19 @@ description: 与客户签署的协议——条款、价值、续约,以及自
## 合同记录存储的内容
-合同记录把自己的字段声明为 **6 个区块**。合同表单只把其中一部分挑进各个标签页,所以下表是一份合同携带的字段全集,而不是逐屏对照表:
+合同记录把自己的字段声明为 **7 个区块**。合同表单只把其中一部分挑进各个标签页,所以下表是一份合同携带的字段全集,而不是逐屏对照表:
| 区块 | 其中内容 |
| --- | --- |
-| **合同信息** | 合同名称、合同编号 *(自动编号 `CTR-0001`)*、合同类型、合同文档、描述 |
+| **合同信息** | 合同名称、合同形式、来源订单、合同编号 *(自动编号 `CTR-0001`)*、合同类型、合同文档、描述 |
| **签约方** | 合同负责人、所属客户、主要联系人、关联商机——联系人和商机的选择器都按你先选定的客户过滤 |
| **条款与日期** | 合同期限(月)、开始日期、结束日期、特殊条款 |
-| **合同金额** | 合同金额、计费周期、付款条款、账单地址 |
+| **合同金额** | 合同金额、订单金额与“与订单金额不一致”*(订单合同)*、计费周期、付款条款、账单地址 |
| **状态与审批** | 状态、签署日期、签署人、签署副本 |
| **续约** | 自动续约、续约通知(天) |
+| **最近一次变更** | 变更原因、签署的变更协议——由**变更**写入 |
-合同名称、所属客户、主要联系人、合同期限、开始日期、结束日期、合同金额和状态都是**必填**的——缺一项合同就存不下来。
+合同名称、合同形式、所属客户、主要联系人、合同期限、开始日期、结束日期、合同金额和状态都是**必填**的——缺一项合同就存不下来。合同金额默认为 0,所以“其他”合同不必填写金额。
## 合同名称与合同编号 [#the-contracts-name-and-number]
@@ -149,15 +178,16 @@ description: 与客户签署的协议——条款、价值、续约,以及自
**而且它是最终状态。** 把一份已终止的合同改成任何其他状态的编辑都会被拒绝,合同保持 *Terminated*——见下文*状态推进是一道闸门*;替换它的是一份新合同。合同的其余部分照样可以编辑:只要状态保持不变,改它的备注、条款或主要联系人都能保存。
-**状态**是合同上两个记录变更历史的字段之一,所以审计日志确实记下了谁在何时改的。
+**状态**是合同上记录变更历史的字段之一,所以审计日志确实记下了谁在何时改的。其余的是负责人、开始和结束日期、合同金额、付款条款和变更原因。
## 内置规则
-有五条规则会直接拒绝保存:
+有六条规则会直接拒绝保存:
- **结束日期必须晚于开始日期**——对象上的一条校验规则。
- **期限必须与日期区间对得上**——合同 hook 会算**开始日期**到**结束日期**之间有多少个月,与**合同期限(月)**相差超过 **1 个月**就拒绝:*"Contract term (12 months) does not match date range (6 months from … to …)."* 改期限就要一起改日期,否则存不下去。
-- **已激活的合同,结束日期不能往前改**——合同一旦是「已激活」,把**结束日期**改早的编辑会被拒绝(*"Cannot shrink end_date … after activation"*)。往后延没问题;把一份生效中的协议提前收尾,那是终止或修订,不是编辑。
+- **已激活的合同只能通过变更修改**——合同一旦是「已激活」,修改**合同金额**、**结束日期**或**付款条款**的编辑会被拒绝,并点出字段名(*“已激活合同的结束日期只能通过“变更”修改,并需填写原因、上传签署的变更协议。”*)。见上文*变更已激活的合同*。
+- **订单合同的金额就是订单金额**——无论什么状态,在订单合同上填写**合同金额**都会被拒绝。
- **「已激活」需要签署副本**——把合同改为「已激活」、或新建时就是「已激活」的保存,如果没有**签署副本**,会在该字段上被拒绝;见上文*打印合同与签署副本*。
- **状态推进是一道闸门。** 路线是「草稿」→「审批中」→「已激活」→「已过期」或「已终止」;「审批中」可以退回「草稿」,三种在途状态都能直接走到「已终止」,而「已过期」与「已终止」都是最终状态:续约是一份新合同,绝不是把旧合同救活。偏离这条路线的状态变更——「草稿」直接跳「已激活」、「已激活」退回「草稿」,或者把「已过期」「已终止」的合同救活——会在**状态**上被拒绝,提示 *“不允许这样更改状态。合同按 草稿 → 审批中 → 已激活 → 已过期 推进;审批中可以退回草稿,草稿、审批中或已激活的合同可以改为已终止。已过期和已终止是最终状态:续约是一份新合同。”*,合同保持原来的状态,无论变更来自编辑表单还是 REST API(`400 VALIDATION_FAILED`)。受检查的只有状态的变更:其他任何编辑在任何合同上都能保存,已过期或已终止的也一样。而**新建**时就直接是「已激活」或「已过期」的合同不受这条规则检查,正是上文那条会跳过激活写入的导入路径;新建时就是「已激活」的合同仍然需要它的**签署副本**。
diff --git a/content/docs/(product)/sales/contracts.zh-Hant.mdx b/content/docs/(product)/sales/contracts.zh-Hant.mdx
index 874023ddb..3e1caa979 100644
--- a/content/docs/(product)/sales/contracts.zh-Hant.mdx
+++ b/content/docs/(product)/sales/contracts.zh-Hant.mdx
@@ -21,6 +21,34 @@ description: 與客戶簽署的協議——條款、價值、續約,以及自
啟用是關鍵轉換——它會觸發帳戶被提升為 *Customer*。
+## 合約形式:訂單合約、框架合約或其他 [#the-contract-form-order-framework-or-other]
+
+每份合約都有一個**合約形式**,它決定合約金額從哪裡來。它與合約類型並列,不取代合約類型:類型說的是約定了*什麼*(訂閱、服務、保密協議),形式說的是這份合約*用來做什麼*。
+
+| 形式 | 怎麼產生 | 合約金額 |
+| --- | --- | --- |
+| **訂單合約** | 在訂單上點**起草合約**——不能手工建立 | 訂單的含稅總額。表單上唯讀 |
+| **框架合約** | 手工建立——新建合約的預設形式 | 手工填寫。可以掛多張訂單 |
+| **其他** | 手工建立 | 不需要金額,例如保密協議。不填時金額為 0 |
+
+合約還是草稿時,你可以在**框架合約**和**其他**之間選擇;離開草稿後形式就固定了。訂單合約始終是訂單合約,它的**來源訂單**記著起草它的那張訂單。
+
+**訂單合約在草稿期間跟隨訂單。** 它的**訂單金額**和**合約金額**就是訂單的總額:修改訂單(或訂單來源的報價),草稿合約的金額隨之變化。訂單合約的金額沒有人手工填寫。
+
+**合約啟用後,金額保持簽署時的數字。** 之後訂單金額再變,合約上會顯示**與訂單金額不一致**,金額本身不動,直到有人用**變更**並選擇**按訂單更新**(見下文)。
+
+升級之前已有的合約,在升級後第一次儲存時按這條規則取得形式:由**起草合約**產生、且被其訂單關聯的合約是訂單合約;沒有金額的合約是**其他**;其餘合約都是框架合約。金額已經與訂單不一致的訂單合約保持原樣,顯示**與訂單金額不一致**,留給業務人員核對。
+
+## 變更已啟用的合約 [#changing-an-activated-contract]
+
+**已啟用**的合約上,**合約金額**、**結束日期**和**付款條款**在表單上唯讀,只能透過合約頁首的**變更**修改:
+
+- 填寫**變更原因**,並上傳客戶簽署的**簽署的變更協議**。兩樣缺一,變更存不下來。
+- 框架合約(或其他)可以填寫**新合約金額**。訂單合約不提供金額輸入:勾選**按訂單更新**,取訂單的目前金額。
+- **新結束日期**和**新付款條款**可填可不填,留空的項保持不變。新結束日期讓期限與**合約期限(月)**對不上時,期限會按日期重新計算。
+
+合約保持**已啟用**,所以續約提醒和到期掃描照常進行。變更不會產生變更單,不會修改訂單,也不會重新規劃回款。合約的**歷史**裡能看到每個值改前改後、誰改的、何時改的;**最近一次變更**一節顯示最近一次的原因和變更協議。
+
## 6 種合約類型
| 類型 | 用於 |
@@ -34,18 +62,19 @@ description: 與客戶簽署的協議——條款、價值、續約,以及自
## 合約記錄儲存的內容
-合約記錄把自己的欄位宣告為 **6 個區塊**。合約表單只把其中一部分挑進各個標籤頁,所以下表是一份合約攜帶的欄位全集,而不是逐屏對照表:
+合約記錄把自己的欄位宣告為 **7 個區塊**。合約表單只把其中一部分挑進各個標籤頁,所以下表是一份合約攜帶的欄位全集,而不是逐屏對照表:
| 區塊 | 其中內容 |
| --- | --- |
-| **合約資訊** | 合約名稱、合約編號 *(自動編號 `CTR-0001`)*、合約類型、合約文件、描述 |
+| **合約資訊** | 合約名稱、合約形式、來源訂單、合約編號 *(自動編號 `CTR-0001`)*、合約類型、合約文件、描述 |
| **簽約方** | 合約負責人、所屬客戶、主要聯絡人、關聯商機——聯絡人和商機的選擇器都按你先選定的客戶過濾 |
| **條款與日期** | 合約期限(月)、開始日期、結束日期、特殊條款 |
-| **合約金額** | 合約金額、計費週期、付款條款、帳單地址 |
+| **合約金額** | 合約金額、訂單金額與「與訂單金額不一致」*(訂單合約)*、計費週期、付款條款、帳單地址 |
| **狀態與審批** | 狀態、簽署日期、簽署人、簽署副本 |
| **續約** | 自動續約、續約通知(天) |
+| **最近一次變更** | 變更原因、簽署的變更協議——由**變更**寫入 |
-合約名稱、所屬客戶、主要聯絡人、合約期限、開始日期、結束日期、合約金額和狀態都是**必填**的——缺一項合約就存不下來。
+合約名稱、合約形式、所屬客戶、主要聯絡人、合約期限、開始日期、結束日期、合約金額和狀態都是**必填**的——缺一項合約就存不下來。合約金額預設為 0,所以「其他」合約不必填寫金額。
## 合約名稱與合約編號 [#the-contracts-name-and-number]
@@ -151,15 +180,16 @@ description: 與客戶簽署的協議——條款、價值、續約,以及自
**而且它是最終狀態。** 把一份已終止的合約改成任何其他狀態的編輯都會被拒絕,合約保持 *Terminated*——見下文*狀態推進是一道閘門*;替換它的是一份新合約。合約的其餘部分照樣可以編輯:只要狀態保持不變,改它的備註、條款或主要聯絡人都能儲存。
-**狀態**是合約上兩個記錄變更歷史的欄位之一,所以審計日誌確實記下了誰在何時改的。
+**狀態**是合約上記錄變更歷史的欄位之一,所以審計日誌確實記下了誰在何時改的。其餘的是負責人、開始和結束日期、合約金額、付款條款和變更原因。
## 內建規則
-有五條規則會直接拒絕儲存:
+有六條規則會直接拒絕儲存:
- **結束日期必須晚於開始日期**——物件上的一條驗證規則。
- **期限必須與日期區間對得上**——合約 hook 會算**開始日期**到**結束日期**之間有多少個月,與**合約期限(月)**相差超過 **1 個月**就拒絕:*"Contract term (12 months) does not match date range (6 months from … to …)."* 改期限就要一起改日期,否則存不下去。
-- **已啟用的合約,結束日期不能往前改**——合約一旦是「已啟用」,把**結束日期**改早的編輯會被拒絕(*"Cannot shrink end_date … after activation"*)。往後延沒問題;把一份生效中的協議提前收尾,那是終止或修訂,不是編輯。
+- **已啟用的合約只能透過變更修改**——合約一旦是「已啟用」,修改**合約金額**、**結束日期**或**付款條款**的編輯會被拒絕,並點出欄位名。見上文*變更已啟用的合約*。
+- **訂單合約的金額就是訂單金額**——無論什麼狀態,在訂單合約上填寫**合約金額**都會被拒絕。
- **「已啟用」需要簽署副本**——把合約改為「已啟用」、或新建時就是「已啟用」的儲存,如果沒有**簽署副本**,會在該欄位上被拒絕;見上文*列印合約與簽署副本*。
- **狀態推進是一道閘門。** 路線是「草稿」→「審批中」→「已啟用」→「已過期」或「已終止」;「審批中」可以退回「草稿」,三種在途狀態都能直接走到「已終止」,而「已過期」與「已終止」都是最終狀態:續約是一份新合約,絕不是把舊合約救活。偏離這條路線的狀態變更——「草稿」直接跳「已啟用」、「已啟用」退回「草稿」,或者把「已過期」「已終止」的合約救活——會在**狀態**上被拒絕,提示訊息說明允許的路線,並指出「已過期」與「已終止」是最終狀態、續約是一份新合約;合約保持原來的狀態,無論變更來自編輯表單還是 REST API(`400 VALIDATION_FAILED`)。受檢查的只有狀態的變更:其他任何編輯在任何合約上都能儲存,已過期或已終止的也一樣。而**新建**時就直接是「已啟用」或「已過期」的合約不受這條規則檢查,正是上文那條會跳過啟用寫入的匯入路徑;新建時就是「已啟用」的合約仍然需要它的**簽署副本**。
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 9d4527fba..0bc11e9b1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -19,8 +19,8 @@ loader registers:
```text
HotCRM v6.6.0
-Data: 38 Objects 626 Fields
-UI: 6 Apps 32 Views 4 Pages 7 Dashboards 10 Reports 54 Actions
+Data: 38 Objects 636 Fields
+UI: 6 Apps 32 Views 4 Pages 7 Dashboards 10 Reports 56 Actions
Logic: 53 Flows
Security: 18 Positions 13 Permissions
```
@@ -31,7 +31,7 @@ Validation command:
pnpm validate
```
-> **`54 Actions` is the REGISTRATION count, not a count of distinct action
+> **`56 Actions` is the REGISTRATION count, not a count of distinct action
> definitions.** One action bound to five objects registers five times, so the
> source tree's `*.actions.ts` files and this figure answer different
> questions. The registration count is the calibre this repo states to readers
diff --git a/scripts/backfill-contract-form.ts b/scripts/backfill-contract-form.ts
new file mode 100644
index 000000000..7eab79cf4
--- /dev/null
+++ b/scripts/backfill-contract-form.ts
@@ -0,0 +1,194 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+//
+// One-time contract forms (#2804): give every contract saved before contracts
+// had a form one, and list the order contracts whose value differs from their
+// order, for the business to check.
+//
+// pnpm exec tsx scripts/backfill-contract-form.ts --url https:// --email --password
+// pnpm exec tsx scripts/backfill-contract-form.ts ... --apply # without this it only reports
+//
+// From #2804 every contract has a Contract Form (`crm_contract.contract_form`):
+// Order Contract, Framework Contract or Other. The rule that gives an older
+// contract its form is the maintainer's (ruling 2026-11-26, item 7) and lives
+// in ONE place, the contract hook (`contract_form_and_change`,
+// `src/sales/objects/contract.hook.ts`), which applies it to a contract with
+// no form on that contract's next write:
+//
+// 1. drafted by Draft Contract (it carries the drafted mark) and named by
+// an order ⇒ Order Contract, that order its Source Order;
+// 2. no amount ⇒ Other;
+// 3. every other contract ⇒ Framework Contract.
+//
+// Run the platform's own step first, `pnpm exec objectstack migrate
+// summary-nulls --apply --yes`, which computes Order Amount on the contracts
+// that predate it; without it the order contracts cannot be compared, and the
+// script says so and exits non-zero. The order of the two does not matter
+// for the values: neither corrects one.
+//
+// So this script decides nothing itself. It writes each contract with no form
+// once, as the administrator signed in, one PATCH carrying `contract_form:
+// null` (no choice: the hook applies the rule and writes the form), and reads
+// the forms back. The contract's other fields, its value and status included,
+// are left as they are: an order contract whose value already differs from
+// its order is NOT corrected (item 7). Those are listed at the end, from the
+// stored Contract Value and Order Amount; the app shows each of them
+// "Differs from the Order Amount" too.
+//
+// Safe by construction:
+// • report-only unless `--apply` is passed: it then lists the contracts
+// without a form, and the difference list as it stands;
+// • rerunnable: a contract that has a form is never written, so a second
+// pass over a converged org writes nothing.
+//
+// ⛔ Run against your own org only. The HotCRM maintainers never run it
+// against a hosted org: the hosted tenants' owner decides when and whether
+// it runs there.
+
+type Json = Record;
+
+const DEFAULT_URL = 'http://localhost:4001';
+
+/** `--flag value` / `--flag=value`, else the env var, else the fallback. */
+function arg(name: string, envName: string, fallback: string): string {
+ const argv = process.argv.slice(2);
+ const eq = argv.find((a) => a.startsWith(`--${name}=`));
+ if (eq) return eq.slice(name.length + 3);
+ const i = argv.indexOf(`--${name}`);
+ if (i !== -1 && argv[i + 1]) return argv[i + 1];
+ return process.env[envName]?.trim() || fallback;
+}
+
+const APPLY = process.argv.slice(2).includes('--apply');
+
+class Api {
+ private cookie = '';
+ constructor(private readonly base: URL) {}
+
+ private async call(method: string, path: string, body?: Json): Promise<{ status: number; json: Json }> {
+ const res = await fetch(new URL(path, this.base), {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: this.base.origin,
+ ...(this.cookie ? { Cookie: this.cookie } : {}),
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const setCookie = res.headers.getSetCookie?.() ?? [];
+ if (setCookie.length) this.cookie = setCookie.map((c) => c.split(';')[0]).join('; ');
+ const text = await res.text();
+ let json: Json = {};
+ try { json = text ? JSON.parse(text) : {}; } catch { json = { raw: text }; }
+ return { status: res.status, json };
+ }
+
+ private static message(json: Json): string {
+ return String(json?.error?.message ?? json?.error ?? json?.message ?? JSON.stringify(json));
+ }
+
+ async signIn(email: string, password: string): Promise {
+ const { status, json } = await this.call('POST', '/api/v1/auth/sign-in/email', { email, password });
+ if (status !== 200 || !json?.user?.id) {
+ throw new Error(`sign-in failed for ${email} (${status}: ${json?.message ?? json?.code ?? 'unknown'})`);
+ }
+ return json.user as Json;
+ }
+
+ /**
+ * Every row of `object`, paged. The body is the shape the installed query
+ * schema accepts: `sort` as `[{ field, order }]` and no `filters` key at all
+ * (#1999). `test/backfill-query-bodies.test.ts` keeps it there.
+ */
+ async all(object: string, fields: string[]): Promise {
+ const out: Json[] = [];
+ for (let skip = 0; ; ) {
+ const { status, json } = await this.call('POST', `/api/v1/data/${object}/query`, {
+ fields, sort: [{ field: 'id', order: 'asc' }], skip, top: 200,
+ });
+ if (status < 200 || status >= 300) throw new Error(`query ${object} → ${status}: ${Api.message(json)}`);
+ const rows = (json.records ?? []) as Json[];
+ out.push(...rows);
+ if (rows.length < 200) return out;
+ skip += rows.length;
+ }
+ }
+
+ async patch(object: string, id: string, body: Json): Promise {
+ const { status, json } = await this.call('PATCH', `/api/v1/data/${object}/${id}`, body);
+ if (status < 200 || status >= 300) throw new Error(`PATCH ${object}/${id} → ${status}: ${Api.message(json)}`);
+ }
+}
+
+/** A lookup value as the query door returns it: the id, or an expanded row. */
+const text = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
+const blank = (v: unknown): boolean => text(v) === '';
+const money = (v: unknown): number => (v === null || v === undefined || v === '' ? 0 : Number(v));
+
+async function main(): Promise {
+ const url = arg('url', 'HOTCRM_URL', DEFAULT_URL);
+ const email = arg('email', 'HOTCRM_ADMIN_EMAIL', 'admin@objectos.ai');
+ const password = arg('password', 'HOTCRM_ADMIN_PASSWORD', 'admin123');
+
+ const api = new Api(new URL(url));
+ const me = await api.signIn(email, password);
+ console.log(`Signed in as ${me.email ?? me.id} at ${url}`);
+ console.log(APPLY ? 'Mode: APPLY (records will be written)' : 'Mode: REPORT ONLY (pass --apply to write)');
+
+ const FIELDS = ['id', 'contract_number', 'name', 'contract_form', 'contract_value', 'order_amount'];
+ const contracts = await api.all('crm_contract', FIELDS);
+ const formless = contracts.filter((c) => blank(c.contract_form));
+ console.log(`\ncrm_contract: ${contracts.length} row(s), ${formless.length} without a form.`);
+ for (const c of formless) console.log(` ${c.contract_number ?? c.id} "${text(c.name)}"`);
+
+ let failed = 0;
+ let after = contracts;
+ if (APPLY && formless.length > 0) {
+ for (const c of formless) {
+ try {
+ await api.patch('crm_contract', String(c.id), { contract_form: null });
+ } catch (err) {
+ failed++;
+ console.log(` ${c.contract_number ?? c.id}: ${(err as Error).message}`);
+ }
+ }
+ // Read back rather than trusting the PATCH answers.
+ after = await api.all('crm_contract', FIELDS);
+ const left = after.filter((c) => blank(c.contract_form));
+ const byForm = new Map();
+ for (const c of after) {
+ if (formless.some((f) => f.id === c.id) && !blank(c.contract_form)) {
+ byForm.set(text(c.contract_form), (byForm.get(text(c.contract_form)) ?? 0) + 1);
+ }
+ }
+ console.log(` Formed ${formless.length - left.length}/${formless.length}: ${[...byForm].map(([f, n]) => `${f} ${n}`).join(', ') || 'none'}; ${left.length} still without a form.`);
+ if (left.length > 0) failed++;
+ } else if (!APPLY && formless.length > 0) {
+ console.log('\nReport only. Re-run with --apply to write.');
+ }
+
+ // The difference list (item 7): order contracts whose value is not their
+ // order's amount, for the business to check. Nothing here corrects them.
+ // An Order Amount still NULL has not been computed for a contract that
+ // predates the field: the platform's own step fills it, and until then the
+ // contract cannot be compared.
+ const orders = after.filter((c) => c.contract_form === 'order');
+ const uncounted = orders.filter((c) => c.order_amount === null || c.order_amount === undefined);
+ const differing = orders.filter((c) => !uncounted.includes(c) && money(c.contract_value) !== money(c.order_amount));
+ if (uncounted.length > 0) {
+ console.log(`\n${uncounted.length} order contract(s) have no Order Amount yet: run \`pnpm exec objectstack migrate summary-nulls --apply --yes\`, then this script again, to compare them.`);
+ failed++;
+ }
+ console.log(`\nOrder contracts whose value differs from the order amount: ${differing.length}.`);
+ for (const c of differing) {
+ console.log(` ${c.contract_number ?? c.id} "${text(c.name)}": contract ${money(c.contract_value)}, order ${money(c.order_amount)}`);
+ }
+ if (failed > 0) process.exitCode = 1;
+}
+
+main().catch((err) => {
+ console.error(`\nBackfill failed: ${(err as Error).message}`);
+ process.exitCode = 1;
+});
+
+// A module, not a global script: the other backfills declare the same names.
+export {};
diff --git a/src/docs/crm_sales_contracts.md b/src/docs/crm_sales_contracts.md
index f747796c5..f56dcda55 100644
--- a/src/docs/crm_sales_contracts.md
+++ b/src/docs/crm_sales_contracts.md
@@ -68,6 +68,28 @@ before, and an import or an integration still saves its other changes. The
**Edit** form asks for the **Signed Copy** before it saves any change to such a
contract, so upload the copy first.
+## Order contracts, framework contracts and other
+
+A contract's **Contract Form** says where its value comes from. **Draft
+Contract** on an order makes an **order contract**: its value is the order's
+total, tax included, and while the contract is a draft it follows the order —
+change the order and the contract's value changes with it. Nobody types an
+order contract's value. A contract you create by hand is a **framework
+contract** (its value typed, and it may carry many orders) or **Other** (no
+amount, such as an NDA); you choose while it is a draft.
+
+Once an order contract is activated, its value stays as signed. If the order
+changes afterwards, the contract shows **Differs from the Order Amount**.
+
+## Changing an activated contract
+
+An activated contract's **Contract Value**, **End Date** and **Payment Terms**
+change only through **Change**: give the reason and upload the signed
+amendment, or nothing is saved. On an order contract, **Update from Order**
+takes the order's current amount; no value is typed. The contract stays
+activated, and its history keeps every value before and after, with who
+changed it and when.
+
## Renewals and expiration are watched for you
Two automatic jobs make sure a contract never lapses unnoticed, on a deployment
diff --git a/src/docs/crm_sales_contracts.zh.md b/src/docs/crm_sales_contracts.zh.md
index 7a672eab9..0fb6212dc 100644
--- a/src/docs/crm_sales_contracts.zh.md
+++ b/src/docs/crm_sales_contracts.zh.md
@@ -39,6 +39,22 @@ stateDiagram-v2
**合同必须有签署副本才能激活。** 在上传文件之前,把合同改为**已激活**的那次保存会被拒绝,并指明**签署副本**;已激活合同上的这个文件也不能删除。在这条规则之前就已激活的合同照常到期或终止,导入或集成对它的其他修改也照常保存;但**编辑**表单在保存任何修改之前会先要求**签署副本**,所以请先上传副本。
+## 订单合同、框架合同和其他
+
+合同的**合同形式**说明金额从哪里来。在订单上点**起草合同**生成的是**订单合同**:
+金额就是订单的含税总额,草稿期间跟随订单——改订单,合同金额随之变化。订单合同的
+金额没有人手工填写。手工创建的合同是**框架合同**(金额手工填写,可挂多张订单)
+或**其他**(没有金额,例如保密协议),在草稿期间选择。
+
+订单合同激活后,金额保持签署时的数字。之后订单再变,合同上会显示**与订单金额
+不一致**。
+
+## 变更已激活的合同
+
+已激活合同的**合同金额**、**结束日期**和**付款条款**只能通过**变更**修改:填写
+原因并上传签署的变更协议,否则存不下来。订单合同上用**按订单更新**取订单的当前
+金额,不填写金额。合同保持已激活,它的历史记下每个值改前改后、谁改的、何时改的。
+
## 续约和到期由系统替你盯着
在开启了计划任务的部署上,两个自动任务确保合同不会在无人察觉时失效。默认安装启动时这两个任务都未绑定:不会创建续约任务、通知或商机,已过结束日期的已激活合同会一直保持已激活,直到有人修改它。
diff --git a/src/docs/crm_sales_orders.md b/src/docs/crm_sales_orders.md
index 223c367d7..842953c06 100644
--- a/src/docs/crm_sales_orders.md
+++ b/src/docs/crm_sales_orders.md
@@ -64,6 +64,12 @@ its term, dates and type before you activate it. The order then names the
contract under **Contract**, and you get a **Contract drafted** notice with a
link to it.
+The drafted contract is an **order contract** naming this order as its
+**Source Order**. Its value is the order's total and is never typed: while the
+contract is a draft, a change to the order's amount changes the contract's
+value too. Once the contract is activated it keeps the signed value; see
+[Contracts](./crm_sales_contracts.md).
+
**Draft Contract** is offered only while the order names no contract: an order
placed under a framework contract names that one. A **Cancelled** order is not
offered it, and nothing is drafted for one. The order needs a **Contact**,
diff --git a/src/docs/crm_sales_orders.zh.md b/src/docs/crm_sales_orders.zh.md
index ff9b4dac0..63da97fcf 100644
--- a/src/docs/crm_sales_orders.zh.md
+++ b/src/docs/crm_sales_orders.zh.md
@@ -27,6 +27,8 @@ description: 录入订单与订单行、合计如何随订单行变化、确认
订阅或项目通常需要合同,产品销售通常不需要。在订单上点 **起草合同** 即可起草:一份 **草稿** 合同,合同类型为 *订阅合同*,期限 12 个月、从今天起算,金额为订单的总金额,名称与订单相同,带着订单的所属客户、联系人、关联商机、负责人和付款条款。激活之前请补全期限、日期和类型。随后订单的 **关联合同** 会指向这份合同,你也会收到一条带链接的 **合同已起草** 通知。
+起草出的合同是**订单合同**,它的**来源订单**就是这张订单。合同金额就是订单总额,不手工填写:合同还是草稿时,订单金额一变,合同金额也跟着变。合同激活后保持签署时的金额;见[合同](./crm_sales_contracts.md)。
+
只有当订单还没有关联合同时才会提供 **起草合同**:挂在框架合同下的订单已经指向那份合同。**已取消** 的订单不提供 **起草合同**,也不会为它起草任何东西。订单需要填写 **联系人**,因为合同必须有主要联系人;没有联系人时不会起草任何东西。销售代表也可以运行它,尽管销售代表不能亲手新建合同。
## 合计随订单行变化
diff --git a/src/sales/actions/contract.actions.ts b/src/sales/actions/contract.actions.ts
index 63f029dff..8084829e8 100644
--- a/src/sales/actions/contract.actions.ts
+++ b/src/sales/actions/contract.actions.ts
@@ -55,3 +55,74 @@ export const PrintContractAction: Action = {
locations: ['record_header', 'list_item'],
refreshAfter: true,
};
+
+/**
+ * Change — the one way an activated contract's value, end date and payment
+ * terms change (hotcrm#2804, maintainer ruling 2026-11-26).
+ *
+ * Two actions, one per kind of contract, because the ruling gives them
+ * different inputs: a framework contract (and an Other one) may be given a
+ * new value; an order contract is offered no value at all, only Update from
+ * Order, which takes the order's amount. Both ask for the reason and the
+ * signed amendment, and may give a new end date and new payment terms; an
+ * input left empty keeps the field as it is.
+ *
+ * A declarative update (`operation: 'update'`, the dialog's `params`), so it
+ * writes AS THE CALLER: the contract's own grants judge it, as Edit would. It
+ * cannot write the three fields itself — on an activated contract
+ * `readonlyWhen` drops every caller's write to them — so it writes the reason,
+ * the amendment and the `change_new_*` inputs, and
+ * `contract_form_and_change` (`../objects/contract.hook.ts`) refuses a
+ * change without a reason or a newly signed amendment, moves each input
+ * onto its field, and clears the inputs, in the same write. The field history
+ * keeps every value before and after, who and when. The status stays
+ * Activated, so the renewal and expiry sweeps go on reading the contract;
+ * no change order is created, the order is not changed and the payment plan
+ * is not re-planned.
+ *
+ * `visible`: activated contracts of the action's kind, for a person who may
+ * edit contracts. Every predicate is total: a page's first render holds no
+ * status, which offers nothing.
+ */
+export const ChangeContractAction: Action = {
+ name: 'change_contract',
+ label: 'Change',
+ objectName: 'crm_contract',
+ icon: 'file-diff',
+ operation: 'update',
+ locations: ['record_header'],
+ visible: P`has(record.status) && record.status == "activated"
+ && !(has(record.contract_form) && record.contract_form == "order") && current_user.can("crm_contract", "edit")`,
+ description: 'Changes the contract value, the end date or the payment terms of this activated contract. Leave a field empty to keep it.',
+ params: [
+ { field: 'change_reason', required: true },
+ { field: 'change_amendment', required: true },
+ { field: 'change_new_value' },
+ { field: 'change_new_end_date' },
+ { field: 'change_new_payment_terms' },
+ ],
+ successMessage: 'Contract {{ record.name }} changed.',
+ refreshAfter: true,
+};
+
+/** Change on an order contract: as `ChangeContractAction`, with Update from Order in place of a value. */
+export const ChangeOrderContractAction: Action = {
+ name: 'change_order_contract',
+ label: 'Change',
+ objectName: 'crm_contract',
+ icon: 'file-diff',
+ operation: 'update',
+ locations: ['record_header'],
+ visible: P`has(record.status) && record.status == "activated"
+ && has(record.contract_form) && record.contract_form == "order" && current_user.can("crm_contract", "edit")`,
+ description: "Changes the end date or the payment terms of this activated order contract, or takes the order's current amount. Leave a field empty to keep it.",
+ params: [
+ { field: 'change_reason', required: true },
+ { field: 'change_amendment', required: true },
+ { field: 'change_from_order' },
+ { field: 'change_new_end_date' },
+ { field: 'change_new_payment_terms' },
+ ],
+ successMessage: 'Contract {{ record.name }} changed.',
+ refreshAfter: true,
+};
diff --git a/src/sales/actions/index.ts b/src/sales/actions/index.ts
index cf7e6d8cb..8f625ccb3 100644
--- a/src/sales/actions/index.ts
+++ b/src/sales/actions/index.ts
@@ -30,7 +30,8 @@ export { CloneOpportunityAction, MassUpdateStageAction, GenerateQuoteAction } fr
// its `patch` as the caller.
export { CompleteTaskAction } from './task.actions';
// Print Contract (#2317): an `api` action on the print service's door.
-export { PrintContractAction } from './contract.actions';
+// Change (#2804): declarative updates the contract hook applies.
+export { PrintContractAction, ChangeContractAction, ChangeOrderContractAction } from './contract.actions';
// Draft Contract (#2558): the order's contract, drafted on demand by a flow.
// Confirm / Complete / Cancel Order (#2716): declarative updates of the status.
export {
diff --git a/src/sales/flows/sales-order-draft-contract.flow.ts b/src/sales/flows/sales-order-draft-contract.flow.ts
index 7fa21f82f..778983d52 100644
--- a/src/sales/flows/sales-order-draft-contract.flow.ts
+++ b/src/sales/flows/sales-order-draft-contract.flow.ts
@@ -59,7 +59,7 @@ type Flow = Automation.Flow;
export const SalesOrderDraftContractFlow: Flow = {
name: 'sales_order_draft_contract',
label: 'Draft Contract from Order',
- description: "Draft the order's contract — a 12-month subscription at the order's total, for an administrator to complete — and name it on the order.",
+ description: "Draft the order's contract — an order contract at the order's total, a 12-month subscription for an administrator to complete — and name it on the order.",
type: 'screen',
status: 'active',
runAs: 'user',
@@ -150,7 +150,8 @@ export const SalesOrderDraftContractFlow: Flow = {
* link to it. See `SalesOrderDraftContractFlow` for why it is a flow of its
* own and why the link is here.
*
- * The contract is the shared draft (`./_contract-draft.ts`): its value is the
+ * The contract is the shared draft (`./_contract-draft.ts`), as an order
+ * contract naming this order (`DRAFT` below): its value is the
* order's STORED total, read here by id; its description names the order by
* number and name, TEXT in the organization's language (#2535), translated at
* `flows.sales_order_draft_contract_write.records..fields.description`.
@@ -169,13 +170,35 @@ export const SalesOrderDraftContractFlow: Flow = {
* the order it read a moment before. A second set of the same conditions here
* would be a copy to keep in step, guarding a door nothing else opens.
*/
-const DRAFT = contractDraftGraph({
+const SHARED_DRAFT = contractDraftGraph({
root: 'vars.orderRow',
value: 'has(vars.orderRow.total_price) && vars.orderRow.total_price != null ? double(vars.orderRow.total_price) : 0.0',
description: tmpl`Drafted from order {{ order }}`,
name: 'vars.contractName',
}, { from: 'label_order', to: 'link_order', firstEdge: 2, outputVariable: 'contract' });
+/**
+ * The order's draft is an ORDER CONTRACT (hotcrm#2804): its form says so and
+ * it names the order it came from, so its value follows that order while it
+ * is a draft (`contract_form_and_change`, `../objects/contract.hook.ts`). Added
+ * here, onto the shared draft's inserts, and not in `./_contract-draft.ts`:
+ * the accepted quote's automatic draft builds the same inserts and has no
+ * order to name, so it stays a framework contract, the form's default. Both
+ * keys ride the elevated insert: a person may write neither.
+ */
+const DRAFT = {
+ ...SHARED_DRAFT,
+ nodes: SHARED_DRAFT.nodes.map((node) => node.type === 'create_record'
+ ? {
+ ...node,
+ config: {
+ ...node.config,
+ fields: { ...(node.config as { fields: Record }).fields, contract_form: 'order', crm_sales_order: cel`orderId` },
+ },
+ }
+ : node),
+};
+
export const SalesOrderDraftContractWriteFlow: Flow = {
name: 'sales_order_draft_contract_write',
label: 'Draft Contract from Order (write)',
diff --git a/src/sales/objects/contract.hook.ts b/src/sales/objects/contract.hook.ts
index 5d10b6eff..40d8e26e3 100644
--- a/src/sales/objects/contract.hook.ts
+++ b/src/sales/objects/contract.hook.ts
@@ -6,8 +6,9 @@ import type { HookApi } from './_hook-api';
/**
* Contract lifecycle hook.
*
+ * - The contract's form, its order contract's value and Change
+ * (`contract_form_and_change`, hotcrm#2804).
* - Validates `end_date` ≈ `start_date + contract_term_months`.
- * - Rejects shrinking `end_date` after activation.
* - On a write that files the signed copy (`signed_copy`): fills
* `signed_date` when it is empty (#2317).
* - On `activated`: stamps `signed_date` (if missing) on the activating write
@@ -20,23 +21,291 @@ import type { HookApi } from './_hook-api';
// available at runtime (cf. opportunity.hook.ts). Module-level copies were
// dead code that invited silent divergence.
+/**
+ * The contract's form, an order contract's value, and Change (hotcrm#2804,
+ * maintainer ruling 2026-11-26). Runs before `contract_validation`, so the
+ * term check judges the dates a Change leaves behind.
+ *
+ * **Form.** A person picks Framework or Other while the contract is a draft;
+ * Order is made by Draft Contract alone, whose insert is elevated. So a
+ * person who writes Order, or moves an order contract to another form, or
+ * changes the form of a contract that is no longer a draft, is refused.
+ * `readonlyWhen` on `contract_form` keeps the form read-only in those states
+ * and would drop the write in silence; the refusal says why.
+ *
+ * **Backfill (ruling item 7).** A contract saved before the form existed
+ * takes it on its next write, by the rule as written: drafted by the draft
+ * action (it carries the drafted mark, `automation_key`, and an order names
+ * it) ⇒ Order, with that order as its source; no amount ⇒ Other; the rest ⇒
+ * Framework. Its value is left alone: an order contract whose value already
+ * differs from its order shows Differs from the Order Amount, and
+ * `scripts/backfill-contract-form.ts` lists them, but nothing corrects them.
+ *
+ * **An order contract's value.** While the contract is a draft it follows its
+ * order: when the platform rewrites `order_amount` (the order's total,
+ * summed; a system write after any order under the contract changes), the
+ * value takes it. A person never types it; their direct write is refused.
+ * Once activated it stays as signed: a later order change shows Differs from
+ * the Order Amount, and Change with Update from Order takes the new amount.
+ *
+ * **Change.** On an activated contract the value, the end date and the
+ * payment terms are locked (`readonlyWhen`, every caller). A person's direct
+ * write to one is refused here, by name. Change (`../actions/contract.actions.ts`)
+ * writes, as the person, a reason, the signed amendment and the
+ * `change_new_*` inputs; this hook requires the reason and a NEW amendment,
+ * moves each input given onto its field, takes the order's amount on Update
+ * from Order (an order contract is offered no amount), re-counts the term's
+ * months when the new end date leaves them out of step, and clears the
+ * inputs. The fields' history records each value before and after, who and
+ * when. A value written here is derived, not the caller's, so the lock keeps
+ * it. The status stays Activated.
+ */
+const contractFormAndChange: Hook = {
+ name: 'contract_form_and_change',
+ object: 'crm_contract',
+ events: ['beforeInsert', 'beforeUpdate'],
+ priority: 150,
+ description: "Hold the contract's form, keep a draft order contract's value on its order, and apply a Change to an activated contract.",
+ refusals: {
+ FORBIDDEN: {
+ message: 'An order contract is drafted from its order with Draft Contract. Choose Framework Contract or Other.',
+ status: 403,
+ },
+ RECORD_LOCKED: {
+ message: "An order contract's value is its order's amount: change the order, and a draft contract follows it.",
+ status: 409,
+ reasons: {
+ form: { message: "A contract's form is chosen while it is a draft, and an order contract stays an order contract." },
+ contract_value: { message: "An activated contract's Contract Value changes only through Change, with a reason and the signed amendment." },
+ end_date: { message: "An activated contract's End Date changes only through Change, with a reason and the signed amendment." },
+ payment_terms: { message: "An activated contract's Payment Terms change only through Change, with a reason and the signed amendment." },
+ },
+ },
+ VALIDATION_FAILED: {
+ message: 'A change needs a reason and the newly signed amendment.',
+ status: 400,
+ reasons: {
+ not_activated: { message: 'Change applies to an activated contract. A draft contract is edited directly.' },
+ order_value: { message: "An order contract's value is not typed in a change: choose Update from Order to take the order's amount." },
+ },
+ },
+ },
+ handler: async (ctx: HookContext) => {
+ // The refusal envelope (#1075). Mirrored from `src/sales/objects/_refusal.ts` because a
+ // lowered body has no module scope and `extractHookBody` THROWS on an
+ // import; `test/refusal-envelope.test.ts` pins every copy against it.
+ function refuse(
+ message: string,
+ code: string,
+ status: number,
+ userMessage: string = message,
+ ): Error {
+ const err = new Error(message) as Error & {
+ code: string;
+ status: number;
+ userMessage: string;
+ };
+ err.code = code;
+ err.status = status;
+ err.userMessage = userMessage;
+ return err;
+ }
+ // Empty: absent, null, or a blank string. A file value is an id or an
+ // object; either is a value.
+ function blank(v: unknown): boolean {
+ return v === undefined || v === null || (typeof v === 'string' && v.trim() === '');
+ }
+ // Two stored values are the same value: blanks are one value, numbers by
+ // number (a currency may arrive as a string), dates by their day, files
+ // by their serialized form.
+ function same(a: unknown, b: unknown): boolean {
+ if (blank(a) && blank(b)) return true;
+ if (blank(a) || blank(b)) return false;
+ if (typeof a === 'number' || typeof b === 'number') return Number(a) === Number(b);
+ if (typeof a === 'string' && typeof b === 'string') return a.slice(0, 10) === b.slice(0, 10) || a === b;
+ return JSON.stringify(a) === JSON.stringify(b);
+ }
+ // As `contract_validation` counts them: whole months on the UTC calendar.
+ function monthsBetween(startISO: string, endISO: string): number {
+ const s = new Date(startISO);
+ const e = new Date(endISO);
+ return (
+ (e.getUTCFullYear() - s.getUTCFullYear()) * 12 +
+ (e.getUTCMonth() - s.getUTCMonth()) +
+ (e.getUTCDate() >= s.getUTCDate() ? 0 : -1)
+ );
+ }
+
+ const { event, input, previous } = ctx;
+ // A person, not an automation: the drafting flows and the platform's own
+ // roll-up write as the system.
+ const person = Boolean(ctx.user?.id) && !ctx.session?.isSystem;
+
+ if (event === 'beforeInsert') {
+ if (person && input.contract_form === 'order') {
+ throw refuse(
+ 'An order contract is drafted from its order with Draft Contract. Choose Framework Contract or Other.',
+ 'FORBIDDEN',
+ 403,
+ );
+ }
+ return;
+ }
+
+ const prev = previous ?? {};
+ let form = typeof prev.contract_form === 'string' ? prev.contract_form : '';
+ let backfilled = false;
+
+ // ── Backfill: a contract saved before the form existed (ruling item 7).
+ // The rule decides, whatever form the write carries.
+ if (form === '') {
+ let derived = 'framework';
+ let sourceOrder = '';
+ const api = ctx.api as HookApi | undefined;
+ const id = typeof input.id === 'string' ? input.id : (typeof prev.id === 'string' ? prev.id : '');
+ if (api && id && !blank(prev.automation_key)) {
+ const orders = await api.object('crm_sales_order').find({
+ where: { crm_contract: id }, fields: ['id', 'created_at'], top: 50,
+ });
+ // The earliest order naming it: the one whose Draft Contract drafted it.
+ const first = orders
+ .filter((o) => typeof o.id === 'string')
+ .sort((a, b) => String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')))[0];
+ if (first) {
+ derived = 'order';
+ sourceOrder = String(first.id);
+ }
+ }
+ if (derived !== 'order') {
+ const value = 'contract_value' in input ? input.contract_value : prev.contract_value;
+ if (blank(value) || Number(value) === 0) derived = 'other';
+ }
+ input.contract_form = derived;
+ if (sourceOrder) input.crm_sales_order = sourceOrder;
+ form = derived;
+ backfilled = true;
+ }
+
+ const status = typeof prev.status === 'string' ? prev.status : '';
+
+ // ── The form.
+ if (person && !backfilled && 'contract_form' in input && !same(input.contract_form, form)) {
+ if (input.contract_form === 'order') {
+ throw refuse(
+ 'An order contract is drafted from its order with Draft Contract. Choose Framework Contract or Other.',
+ 'FORBIDDEN',
+ 403,
+ );
+ }
+ if (form === 'order' || status !== 'draft') {
+ throw Object.assign(refuse(
+ "A contract's form is chosen while it is a draft, and an order contract stays an order contract.",
+ 'RECORD_LOCKED',
+ 409,
+ ), { reason: 'form' });
+ }
+ }
+
+ // ── A person's direct write to a locked field. Each by its label (#2338
+ // item 12; `test/refusal-labels.test.ts`).
+ if (person && status === 'activated') {
+ const LOCKED: Array<[string, string]> = [
+ ['contract_value', "An activated contract's Contract Value changes only through Change, with a reason and the signed amendment."],
+ ['end_date', "An activated contract's End Date changes only through Change, with a reason and the signed amendment."],
+ ['payment_terms', "An activated contract's Payment Terms change only through Change, with a reason and the signed amendment."],
+ ];
+ for (const [field, sentence] of LOCKED) {
+ if (field in input && !same(input[field], prev[field])) {
+ throw Object.assign(refuse(sentence, 'RECORD_LOCKED', 409), { reason: field });
+ }
+ }
+ }
+ if (person && form === 'order' && 'contract_value' in input && !same(input.contract_value, prev.contract_value)) {
+ throw refuse(
+ "An order contract's value is its order's amount: change the order, and a draft contract follows it.",
+ 'RECORD_LOCKED',
+ 409,
+ );
+ }
+
+ // ── A draft order contract follows its order. Only the platform's own
+ // roll-up write carries `order_amount` this far: a person's copy of a
+ // summary field is held back from hooks and dropped. A CHANGE of the
+ // amount, from one the contract already held: not the write that
+ // backfills the form, and not the first value the platform materialises
+ // on a contract that predates the field (`os migrate summary-nulls`,
+ // NULL → the order's total). Neither may correct an old value (ruling
+ // item 7); the next change of the order does. A new contract is born
+ // holding 0 (its orders are named after it), so its first order counts.
+ if (ctx.session?.isSystem && !backfilled && form === 'order' && status === 'draft' && 'order_amount' in input
+ && typeof prev.order_amount === 'number' && !same(input.order_amount, prev.order_amount)) {
+ input.contract_value = blank(input.order_amount) ? 0 : Number(input.order_amount);
+ }
+
+ // ── Change.
+ const staged = !blank(input.change_new_value) || !blank(input.change_new_end_date)
+ || !blank(input.change_new_payment_terms) || input.change_from_order === true;
+ const recorded = ('change_reason' in input && !same(input.change_reason, prev.change_reason))
+ || ('change_amendment' in input && !same(input.change_amendment, prev.change_amendment));
+ if (!staged && !recorded) return;
+
+ if (status !== 'activated' || ('status' in input && input.status !== 'activated')) {
+ throw Object.assign(refuse(
+ 'Change applies to an activated contract. A draft contract is edited directly.',
+ 'VALIDATION_FAILED',
+ 400,
+ ), { reason: 'not_activated' });
+ }
+ if (blank(input.change_reason) || blank(input.change_amendment) || same(input.change_amendment, prev.change_amendment)) {
+ throw refuse('A change needs a reason and the newly signed amendment.', 'VALIDATION_FAILED', 400);
+ }
+ if (form === 'order' && !blank(input.change_new_value)) {
+ throw Object.assign(refuse(
+ "An order contract's value is not typed in a change: choose Update from Order to take the order's amount.",
+ 'VALIDATION_FAILED',
+ 400,
+ ), { reason: 'order_value' });
+ }
+
+ if (form === 'order') {
+ if (input.change_from_order === true) {
+ input.contract_value = blank(prev.order_amount) ? 0 : Number(prev.order_amount);
+ }
+ } else if (!blank(input.change_new_value)) {
+ input.contract_value = Number(input.change_new_value);
+ }
+ if (!blank(input.change_new_end_date)) {
+ const end = String(input.change_new_end_date).slice(0, 10);
+ input.end_date = end;
+ const start = typeof prev.start_date === 'string' ? prev.start_date : '';
+ const term = typeof prev.contract_term_months === 'number' ? prev.contract_term_months : 0;
+ if (start && end > start) {
+ const calc = monthsBetween(start, end);
+ if (!term || Math.abs(calc - term) > 1) input.contract_term_months = Math.max(1, calc);
+ }
+ }
+ if (!blank(input.change_new_payment_terms)) {
+ input.payment_terms = input.change_new_payment_terms;
+ }
+ input.change_new_value = null;
+ input.change_new_end_date = null;
+ input.change_new_payment_terms = null;
+ input.change_from_order = false;
+ },
+};
+
const contractValidation: Hook = {
name: 'contract_validation',
object: 'crm_contract',
events: ['beforeInsert', 'beforeUpdate'],
priority: 200,
- description: 'Enforce contract term math and prevent shrinking end_date once activated.',
+ description: 'Enforce contract term math.',
refusals: {
VALIDATION_FAILED: {
message: 'Contract term ({{term}} months) does not match date range ({{calc}} months from {{start}} to {{end}}).',
status: 400,
params: ['term', 'calc', 'start', 'end'],
},
- RECORD_LOCKED: {
- message: "An activated contract's End Date cannot move earlier ({{from}} → {{to}}). Use a termination/amendment workflow instead.",
- status: 409,
- params: ['from', 'to'],
- },
},
handler: async (ctx: HookContext) => {
// The refusal envelope (#1075). Mirrored from `src/sales/objects/_refusal.ts` because a
@@ -58,7 +327,7 @@ const contractValidation: Hook = {
err.userMessage = userMessage;
return err;
}
- const { event, input, previous } = ctx;
+ const { input, previous } = ctx;
// Both operands are stored `YYYY-MM-DD` values, which the date-only parse
// anchors at UTC MIDNIGHT — so they are read here on the calendar they were
@@ -97,21 +366,9 @@ const contractValidation: Hook = {
}
}
- if (event === 'beforeUpdate' && previous?.status === 'activated') {
- if (
- typeof input.end_date === 'string' &&
- typeof previous.end_date === 'string' &&
- input.end_date < previous.end_date
- ) {
- throw Object.assign(refuse(
- // The field by its label, never its API name (#2338 item 12);
- // `test/refusal-labels.test.ts` reads the label off `crm_contract`.
- `An activated contract's End Date cannot move earlier (${previous.end_date as string} → ${input.end_date}). Use a termination/amendment workflow instead.`,
- 'RECORD_LOCKED',
- 409,
- ), { params: { from: previous.end_date as string, to: input.end_date } });
- }
- }
+ // An activated contract's End Date no longer has a rule of its own here:
+ // it changes only through Change, which may move it either way
+ // (`contract_form_and_change`, which runs first, hotcrm#2804).
},
};
@@ -195,4 +452,4 @@ const contractActivation: Hook = {
},
};
-export default [contractValidation, contractSignedCopyDate, contractSignedDateStamp, contractActivation];
+export default [contractFormAndChange, contractValidation, contractSignedCopyDate, contractSignedDateStamp, contractActivation];
diff --git a/src/sales/objects/contract.object.ts b/src/sales/objects/contract.object.ts
index 983bc8f95..a0dfc1078 100644
--- a/src/sales/objects/contract.object.ts
+++ b/src/sales/objects/contract.object.ts
@@ -1,7 +1,7 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { ObjectSchema, Field } from '@objectstack/spec/data';
-import { P } from '@objectstack/spec';
+import { P, F } from '@objectstack/spec';
/**
* How far ahead, in days, the daily `contract_renewal` sweep looks for
@@ -60,6 +60,9 @@ export const Contract = ObjectSchema.create({
{ key: 'value', label: 'Contract Value', icon: 'dollar-sign' },
{ key: 'status', label: 'Status & Approval', icon: 'check-circle' },
{ key: 'renewal', label: 'Renewal', icon: 'refresh-ccw', collapse: 'collapsed' },
+ // The last Change on an activated contract (hotcrm#2804): its reason and
+ // its signed amendment. Every earlier one is in the field history.
+ { key: 'change', label: 'Last Change', icon: 'file-diff', collapse: 'collapsed' },
],
fields: {
@@ -102,6 +105,60 @@ export const Contract = ObjectSchema.create({
maxLength: 255,
}),
+ // The contract's FORM (hotcrm#2804, maintainer ruling 2026-11-26): what
+ // the contract is FOR, which decides where its value comes from. Distinct
+ // from `contract_type` below, which says what is agreed (subscription,
+ // service, NDA …) and stays as it is.
+ //
+ // - `order`: drafted from one order by Draft Contract
+ // (`../flows/sales-order-draft-contract.flow.ts`), which names that
+ // order in `crm_sales_order`. Its value IS the order's amount: while
+ // the contract is a draft it follows the order, and it is never typed.
+ // - `framework`: created by hand, may carry many orders, its value typed
+ // by hand. The default for a contract a person creates.
+ // - `other`: carries no amount (an NDA, say); the value is not required.
+ //
+ // A person chooses between Framework and Other while the contract is a
+ // draft. Order is not offered (the option shows only on a contract that
+ // already is one), and `contract_form_and_change` (`./contract.hook.ts`)
+ // refuses a person who writes it, or who moves an order contract to
+ // another form. `readonlyWhen` makes the field read-only on the form once
+ // either holds. A contract saved before this field existed takes its
+ // form by the backfill rule the next time it is written (the hook), and
+ // `scripts/backfill-contract-form.ts` writes each one once.
+ //
+ // `required` WITHOUT `storage: { notNull: true }`, as `name` above and for
+ // the same reason (AGENTS.md Metadata semantics rule 11): contracts saved
+ // before this field have none, and a NOT NULL column cannot be added to
+ // the installed table.
+ contract_form: Field.select({
+ label: 'Contract Form',
+ group: 'basic',
+ required: true,
+ options: [
+ {
+ label: 'Order Contract', value: 'order',
+ visibleWhen: P`has(record.contract_form) && record.contract_form == "order"`,
+ },
+ { label: 'Framework Contract', value: 'framework', default: true },
+ { label: 'Other', value: 'other' },
+ ],
+ readonlyWhen: P`(has(record.contract_form) && record.contract_form == "order") || (has(record.status) && record.status != "draft")`,
+ description: 'Order Contract: drafted from an order, its value is the order amount. Framework Contract: its value is typed, and it may carry many orders. Other: no amount, such as an NDA.',
+ }),
+
+ // The order an order contract was drafted from (hotcrm#2804). Written by
+ // Draft Contract's elevated insert and, for a contract that predates the
+ // field, by the backfill rule in `contract.hook.ts`; `readonly`, so no
+ // person sets it. An order still names its contract in its own
+ // `crm_contract`; this is the other direction, for the contract alone.
+ crm_sales_order: Field.lookup('crm_sales_order', {
+ label: 'Source Order',
+ group: 'basic',
+ readonly: true,
+ description: 'The order this contract was drafted from.',
+ }),
+
// Relationships — the master the OWD derives from. Authored as
// master-detail so the master is not decided by declaration order against
// the required `crm_contact` lookup below (objectstack#14747).
@@ -171,12 +228,23 @@ export const Contract = ObjectSchema.create({
// (measured on 18.3.0: a printed contract started "Yesterday"). `short`
// reads "Sep 14, '26", as the quote's dates do (#2370 row 9,
// docs/developers/number-formats.md).
+ //
+ // The term's dates, the value and the payment terms keep their history
+ // (hotcrm#2804): the record's History shows each change before and after,
+ // who made it and when. On an activated contract the end date, the value
+ // and the payment terms change only through Change
+ // (`../actions/contract.actions.ts`): `readonlyWhen` holds them read-only
+ // on the form and drops a direct write from any caller, and
+ // `contract_form_and_change` refuses a person's direct write by name and
+ // writes the values a Change carries. The start date is not one of the
+ // three: the ruling names the end date.
start_date: Field.date({
label: 'Start Date',
group: 'terms',
format: 'short',
required: true,
storage: { notNull: true },
+ trackHistory: true,
}),
end_date: Field.date({
@@ -185,15 +253,74 @@ export const Contract = ObjectSchema.create({
format: 'short',
required: true,
storage: { notNull: true },
+ trackHistory: true,
+ readonlyWhen: P`has(record.status) && record.status == "activated"`,
}),
// Financial
+ //
+ // An order contract's value is its order's amount (hotcrm#2804): never
+ // typed, so read-only on the form whatever the status, and written by
+ // `contract_form_and_change` from `order_amount` while the contract is a
+ // draft, and by a Change's "Update from Order" once it is activated.
+ //
+ // An Other contract carries no amount, and nobody has to type one: the
+ // value defaults to 0, the backfill rule's "no amount". It stays
+ // `required` + NOT NULL rather than `requiredWhen` (Other exempt): the
+ // platform refuses `requiredWhen` beside `storage.notNull` (ADR-0113),
+ // and the installed column is NOT NULL.
contract_value: Field.currency({
label: 'Contract Value',
group: 'value',
min: 0,
required: true,
+ defaultValue: 0,
storage: { notNull: true },
+ trackHistory: true,
+ readonlyWhen: P`(has(record.contract_form) && record.contract_form == "order") || (has(record.status) && record.status == "activated")`,
+ }),
+
+ // The amounts of the orders placed under this contract (hotcrm#2804):
+ // `total_price`, the order's tax-inclusive total (subtotal less discount,
+ // plus tax and shipping; `sales_order.hook.ts`). On an order contract
+ // that is its one order. The platform keeps it, rewriting it whenever an
+ // order under the contract changes, and that rewrite is what lets a
+ // draft order contract follow its order (`contract_form_and_change`).
+ // Shown on an order contract only: a framework contract's quota is sub 4
+ // of hotcrm#2803, not this field.
+ order_amount: Field.summary({
+ label: 'Order Amount',
+ group: 'value',
+ scale: 2,
+ readonly: true,
+ visibleWhen: P`has(record.contract_form) && record.contract_form == "order"`,
+ description: "The order's total, tax included.",
+ summaryOperations: {
+ object: 'crm_sales_order',
+ field: 'total_price',
+ function: 'sum',
+ relationshipField: 'crm_contract',
+ },
+ }),
+
+ // The sign the ruling asks for (hotcrm#2804): an order contract whose
+ // value no longer equals its order's amount — the order changed after the
+ // contract was activated, or the contract predates the rule (item 7: such
+ // contracts are listed, not corrected). A sign, never a block (AGENTS.md
+ // rule 8). Empty, not "No", when the two agree or on another form, so the
+ // record page folds it away.
+ order_amount_differs: Field.formula({
+ label: 'Differs from the Order Amount',
+ group: 'value',
+ returnType: 'boolean',
+ // Judged only once the order amount is known: a contract that predates
+ // the field holds NULL there until the roll-up is materialised.
+ expression: F`has(record.contract_form) && record.contract_form == "order"
+ && has(record.order_amount) && record.order_amount != null
+ && double(record.order_amount)
+ != (has(record.contract_value) && record.contract_value != null ? double(record.contract_value) : 0.0)
+ ? true : null`,
+ description: "The contract value no longer equals the order's amount. Change, with Update from Order, takes the order's amount.",
}),
billing_frequency: Field.select({
@@ -217,6 +344,10 @@ export const Contract = ObjectSchema.create({
// list's `net_30` option default applies only when the quote itself
// carried no term, which is the intended fall-through, not a gap.
picklist: 'payment_terms',
+ // Changed only through Change once activated (hotcrm#2804; see the
+ // dates above).
+ trackHistory: true,
+ readonlyWhen: P`has(record.status) && record.status == "activated"`,
}),
// Renewal
@@ -328,6 +459,70 @@ export const Contract = ObjectSchema.create({
maxLength: 100,
}),
+ // ─── Change (hotcrm#2804) ─────────────────────────────────────────────
+ // An activated contract changes its value, end date and payment terms
+ // only through Change (`../actions/contract.actions.ts`), with a reason
+ // and the signed amendment. The status stays Activated, so renewal and
+ // expiry go on as before; no change order is created, the order is not
+ // changed and the payment plan is not re-planned.
+ //
+ // The reason and the amendment are what Change records: the last one
+ // here, every one in the field history with who and when. Neither is on
+ // the edit form (`../views/contract.view.ts`); a write that carries them
+ // IS a change, and `contract_form_and_change` holds it to the rules.
+ change_reason: Field.textarea({
+ label: 'Change Reason',
+ group: 'change',
+ maxLength: 2000,
+ trackHistory: true,
+ description: 'Why the contract was last changed. Written by Change.',
+ }),
+
+ change_amendment: Field.file({
+ label: 'Signed Amendment',
+ group: 'change',
+ trackHistory: true,
+ description: 'The amendment the customer signed for the last change. Written by Change.',
+ }),
+
+ // What one Change asks for: the dialog's inputs, which the hook moves
+ // onto the three locked fields and then clears, in the same write.
+ // `readonlyWhen` drops a CALLER's write to a locked field, so a Change
+ // cannot write them itself; a value the hook derives is not a caller's
+ // write and is kept (the platform's sanctioned path for a conditionally
+ // locked field). `hidden`: they hold nothing between Changes.
+ change_new_value: Field.currency({
+ label: 'New Contract Value',
+ group: 'change',
+ min: 0,
+ hidden: true,
+ description: 'Leave empty to keep the contract value.',
+ }),
+
+ change_new_end_date: Field.date({
+ label: 'New End Date',
+ group: 'change',
+ format: 'short',
+ hidden: true,
+ description: 'Leave empty to keep the end date.',
+ }),
+
+ change_new_payment_terms: Field.select({
+ label: 'New Payment Terms',
+ group: 'change',
+ picklist: 'payment_terms',
+ hidden: true,
+ description: 'Leave empty to keep the payment terms.',
+ }),
+
+ change_from_order: Field.boolean({
+ label: 'Update from Order',
+ group: 'change',
+ defaultValue: false,
+ hidden: true,
+ description: "Take the order's current amount as the contract value.",
+ }),
+
// Billing Address
billing_address: Field.address({
label: 'Billing Address',
diff --git a/src/sales/translations/en/objects.commerce.ts b/src/sales/translations/en/objects.commerce.ts
index 2169f1d4a..798e474b3 100644
--- a/src/sales/translations/en/objects.commerce.ts
+++ b/src/sales/translations/en/objects.commerce.ts
@@ -69,10 +69,28 @@ export const commerce: Record = {
description: { label: 'Description' },
automation_key: { label: 'Automation Key', help: 'Which automation drafted this contract. Written by that automation; never edit.' },
billing_address: { label: 'Billing Address' },
+ // The contract's form, an order contract's amount and Change (#2804).
+ contract_form: {
+ label: 'Contract Form',
+ help: 'Order Contract: drafted from an order, its value is the order amount. Framework Contract: its value is typed, and it may carry many orders. Other: no amount, such as an NDA.',
+ options: { order: 'Order Contract', framework: 'Framework Contract', other: 'Other' },
+ },
+ crm_sales_order: { label: 'Source Order', help: 'The order this contract was drafted from.' },
+ order_amount: { label: 'Order Amount', help: 'The order\'s total, tax included.' },
+ order_amount_differs: { label: 'Differs from the Order Amount', help: 'The contract value no longer equals the order\'s amount. Change, with Update from Order, takes the order\'s amount.' },
+ change_reason: { label: 'Change Reason', help: 'Why the contract was last changed. Written by Change.' },
+ change_amendment: { label: 'Signed Amendment', help: 'The amendment the customer signed for the last change. Written by Change.' },
+ change_new_value: { label: 'New Contract Value', help: 'Leave empty to keep the contract value.' },
+ change_new_end_date: { label: 'New End Date', help: 'Leave empty to keep the end date.' },
+ change_new_payment_terms: { label: 'New Payment Terms', help: 'Leave empty to keep the payment terms.' },
+ change_from_order: { label: 'Update from Order', help: 'Take the order\'s current amount as the contract value.' },
},
// Print Contract (#2317).
_actions: {
print_contract: { label: 'Print Contract', successMessage: 'Contract PDF attached to the contract.' },
+ // Change (#2804): one action per kind of contract.
+ change_contract: { label: 'Change', description: 'Changes the contract value, the end date or the payment terms of this activated contract. Leave a field empty to keep it.', successMessage: 'Contract {{ record.name }} changed.' },
+ change_order_contract: { label: 'Change', description: 'Changes the end date or the payment terms of this activated order contract, or takes the order\'s current amount. Leave a field empty to keep it.', successMessage: 'Contract {{ record.name }} changed.' },
},
_views: {
all_contracts: { label: 'All Contracts' },
@@ -87,6 +105,7 @@ export const commerce: Record = {
value: { label: 'Contract Value' },
status: { label: 'Status & Approval' },
renewal: { label: 'Renewal' },
+ change: { label: 'Last Change' },
// Form section names on contract.view.ts (#1100). `contract_terms`,
// not `terms` — `terms` is already the fieldGroup key for "Terms & Dates".
contract_terms: { label: 'Terms' },
diff --git a/src/sales/translations/es-ES/hooks.ts b/src/sales/translations/es-ES/hooks.ts
index fe808dfd7..7020fd8d3 100644
--- a/src/sales/translations/es-ES/hooks.ts
+++ b/src/sales/translations/es-ES/hooks.ts
@@ -78,14 +78,35 @@ export const hooks: NonNullable = {
},
},
},
+ // The contract's form, an order contract's value and Change (#2804).
+ contract_form_and_change: {
+ refusals: {
+ FORBIDDEN: {
+ message: 'Un contrato de pedido se redacta desde su pedido con Redactar contrato. Elija Contrato Marco u Otro.',
+ },
+ RECORD_LOCKED: {
+ message: 'El valor de un contrato de pedido es el importe de su pedido: cambie el pedido, y un contrato en borrador lo sigue.',
+ reasons: {
+ form: { message: 'La forma de un contrato se elige mientras es un borrador, y un contrato de pedido sigue siéndolo.' },
+ contract_value: { message: 'El Valor del Contrato de un contrato activado solo cambia con Cambiar, con un motivo y la enmienda firmada.' },
+ end_date: { message: 'La Fecha de Fin de un contrato activado solo cambia con Cambiar, con un motivo y la enmienda firmada.' },
+ payment_terms: { message: 'Las Condiciones de Pago de un contrato activado solo cambian con Cambiar, con un motivo y la enmienda firmada.' },
+ },
+ },
+ VALIDATION_FAILED: {
+ message: 'Un cambio necesita un motivo y la enmienda recién firmada.',
+ reasons: {
+ not_activated: { message: 'Cambiar se aplica a un contrato activado. Un contrato en borrador se edita directamente.' },
+ order_value: { message: 'En un cambio no se escribe el valor de un contrato de pedido: elija Actualizar desde el Pedido para tomar el importe del pedido.' },
+ },
+ },
+ },
+ },
contract_validation: {
refusals: {
VALIDATION_FAILED: {
message: 'La duración del contrato ({{term}} meses) no coincide con el rango de fechas ({{calc}} meses del {{start}} al {{end}}).',
},
- RECORD_LOCKED: {
- message: 'La Fecha de Fin de un contrato activado no puede adelantarse ({{from}} → {{to}}). Use un proceso de rescisión o enmienda.',
- },
},
},
event_do_not_call_guard: {
diff --git a/src/sales/translations/es-ES/objects.commerce.ts b/src/sales/translations/es-ES/objects.commerce.ts
index ec300229b..1fa5006e0 100644
--- a/src/sales/translations/es-ES/objects.commerce.ts
+++ b/src/sales/translations/es-ES/objects.commerce.ts
@@ -77,10 +77,28 @@ export const commerce: Record = {
description: { label: 'Descripción' },
automation_key: { label: 'Clave de Automatización', help: 'La automatización que redactó este contrato. La escribe esa automatización; no la edite.' },
billing_address: { label: 'Dirección de Facturación' },
+ // The contract's form, an order contract's amount and Change (#2804).
+ contract_form: {
+ label: 'Forma del Contrato',
+ help: 'Contrato de Pedido: redactado desde un pedido, su valor es el importe del pedido. Contrato Marco: su valor se escribe a mano y puede cubrir varios pedidos. Otro: sin importe, como un NDA.',
+ options: { order: 'Contrato de Pedido', framework: 'Contrato Marco', other: 'Otro' },
+ },
+ crm_sales_order: { label: 'Pedido de Origen', help: 'El pedido desde el que se redactó este contrato.' },
+ order_amount: { label: 'Importe del Pedido', help: 'El total del pedido, impuestos incluidos.' },
+ order_amount_differs: { label: 'Difiere del Importe del Pedido', help: 'El valor del contrato ya no es igual al importe del pedido. Cambiar, con Actualizar desde el Pedido, toma el importe del pedido.' },
+ change_reason: { label: 'Motivo del Cambio', help: 'Por qué se cambió el contrato la última vez. Lo escribe Cambiar.' },
+ change_amendment: { label: 'Enmienda Firmada', help: 'La enmienda que el cliente firmó para el último cambio. La escribe Cambiar.' },
+ change_new_value: { label: 'Nuevo Valor del Contrato', help: 'Déjelo vacío para conservar el valor del contrato.' },
+ change_new_end_date: { label: 'Nueva Fecha de Fin', help: 'Déjela vacía para conservar la fecha de fin.' },
+ change_new_payment_terms: { label: 'Nuevas Condiciones de Pago', help: 'Déjelas vacías para conservar las condiciones de pago.' },
+ change_from_order: { label: 'Actualizar desde el Pedido', help: 'Toma el importe actual del pedido como valor del contrato.' },
},
// Print Contract (#2317).
_actions: {
print_contract: { label: 'Imprimir Contrato', successMessage: 'PDF del contrato adjuntado al contrato.' },
+ // Change (#2804): one action per kind of contract.
+ change_contract: { label: 'Cambiar', description: 'Cambia el valor, la fecha de fin o las condiciones de pago de este contrato activado. Deje un campo vacío para conservarlo.', successMessage: 'Contrato {{ record.name }} cambiado.' },
+ change_order_contract: { label: 'Cambiar', description: 'Cambia la fecha de fin o las condiciones de pago de este contrato de pedido activado, o toma el importe actual del pedido. Deje un campo vacío para conservarlo.', successMessage: 'Contrato {{ record.name }} cambiado.' },
},
_views: {
all_contracts: { label: 'Todos los Contratos' },
@@ -95,6 +113,7 @@ export const commerce: Record = {
value: { label: 'Valor del Contrato' },
status: { label: 'Estado y Aprobación' },
renewal: { label: 'Renovación' },
+ change: { label: 'Último Cambio' },
// Nombres de sección del formulario en contract.view.ts (#1100)
contract_terms: { label: 'Términos' },
signing_and_documents: { label: 'Firma y Documentos' },
diff --git a/src/sales/translations/ja-JP/hooks.ts b/src/sales/translations/ja-JP/hooks.ts
index 22ed9ef89..6c1abb6af 100644
--- a/src/sales/translations/ja-JP/hooks.ts
+++ b/src/sales/translations/ja-JP/hooks.ts
@@ -78,14 +78,35 @@ export const hooks: NonNullable = {
},
},
},
+ // The contract's form, an order contract's value and Change (#2804).
+ contract_form_and_change: {
+ refusals: {
+ FORBIDDEN: {
+ message: '受注契約は受注の「契約を作成」からのみ作成されます。基本契約またはその他を選択してください。',
+ },
+ RECORD_LOCKED: {
+ message: '受注契約の金額は受注金額です。受注を変更してください。下書きの契約はそれに従います。',
+ reasons: {
+ form: { message: '契約形態は下書きの間に選択します。受注契約は受注契約のままです。' },
+ contract_value: { message: '有効化済みの契約の契約金額は、理由と署名済みの変更契約書を添えて「変更」でのみ変更できます。' },
+ end_date: { message: '有効化済みの契約の終了日は、理由と署名済みの変更契約書を添えて「変更」でのみ変更できます。' },
+ payment_terms: { message: '有効化済みの契約の支払条件は、理由と署名済みの変更契約書を添えて「変更」でのみ変更できます。' },
+ },
+ },
+ VALIDATION_FAILED: {
+ message: '変更には理由と、新たに署名された変更契約書が必要です。',
+ reasons: {
+ not_activated: { message: '「変更」は有効化済みの契約に使います。下書きの契約は直接編集してください。' },
+ order_value: { message: '受注契約の変更では金額を入力しません。「受注から更新」を選んで受注金額を取り込んでください。' },
+ },
+ },
+ },
+ },
contract_validation: {
refusals: {
VALIDATION_FAILED: {
message: '契約期間({{term}}か月)が日付範囲({{start}}から{{end}}まで{{calc}}か月)と一致しません。',
},
- RECORD_LOCKED: {
- message: '有効な契約の終了日は前倒しできません({{from}} → {{to}})。解約または変更の手続きを使用してください。',
- },
},
},
event_do_not_call_guard: {
diff --git a/src/sales/translations/ja-JP/objects.commerce.ts b/src/sales/translations/ja-JP/objects.commerce.ts
index e7e2cff42..ddd91e4c0 100644
--- a/src/sales/translations/ja-JP/objects.commerce.ts
+++ b/src/sales/translations/ja-JP/objects.commerce.ts
@@ -76,10 +76,28 @@ export const commerce: Record = {
description: { label: '説明' },
automation_key: { label: '自動化キー', help: 'この契約を起草した自動化。その自動化が書き込みます。編集しないでください。' },
billing_address: { label: '請求先住所' },
+ // The contract's form, an order contract's amount and Change (#2804).
+ contract_form: {
+ label: '契約形態',
+ help: '受注契約:受注から作成され、金額は受注金額です。基本契約:金額は手入力で、複数の受注を紐付けられます。その他:NDA など金額のない契約です。',
+ options: { order: '受注契約', framework: '基本契約', other: 'その他' },
+ },
+ crm_sales_order: { label: '元の受注', help: 'この契約の作成元となった受注です。' },
+ order_amount: { label: '受注金額', help: '受注の税込合計です。' },
+ order_amount_differs: { label: '受注金額と不一致', help: '契約金額が受注金額と一致しなくなっています。「変更」で「受注から更新」を選ぶと受注金額を取り込みます。' },
+ change_reason: { label: '変更理由', help: '契約を最後に変更した理由です。「変更」が書き込みます。' },
+ change_amendment: { label: '署名済み変更契約書', help: '最後の変更について顧客が署名した変更契約書です。「変更」が書き込みます。' },
+ change_new_value: { label: '新しい契約金額', help: '空欄のままにすると契約金額は変わりません。' },
+ change_new_end_date: { label: '新しい終了日', help: '空欄のままにすると終了日は変わりません。' },
+ change_new_payment_terms: { label: '新しい支払条件', help: '空欄のままにすると支払条件は変わりません。' },
+ change_from_order: { label: '受注から更新', help: '受注の現在の金額を契約金額にします。' },
},
// Print Contract (#2317).
_actions: {
print_contract: { label: '契約書を印刷', successMessage: '契約書の PDF を添付しました。' },
+ // Change (#2804): one action per kind of contract.
+ change_contract: { label: '変更', description: '有効化済みのこの契約の金額、終了日、支払条件を変更します。空欄の項目は変わりません。', successMessage: '契約 {{ record.name }} を変更しました。' },
+ change_order_contract: { label: '変更', description: '有効化済みのこの受注契約の終了日や支払条件を変更するか、受注の現在の金額を取り込みます。空欄の項目は変わりません。', successMessage: '契約 {{ record.name }} を変更しました。' },
},
_views: {
all_contracts: { label: '全契約' },
@@ -94,6 +112,7 @@ export const commerce: Record = {
value: { label: '契約金額' },
status: { label: 'ステータス・承認' },
renewal: { label: '更新' },
+ change: { label: '直近の変更' },
// contract.view.ts のフォームセクション名 (#1100)
contract_terms: { label: '契約条件' },
signing_and_documents: { label: '署名と書類' },
diff --git a/src/sales/translations/zh-CN/hooks.ts b/src/sales/translations/zh-CN/hooks.ts
index f78f0e682..c6b5681d7 100644
--- a/src/sales/translations/zh-CN/hooks.ts
+++ b/src/sales/translations/zh-CN/hooks.ts
@@ -78,14 +78,35 @@ export const hooks: NonNullable = {
},
},
},
+ // The contract's form, an order contract's value and Change (#2804).
+ contract_form_and_change: {
+ refusals: {
+ FORBIDDEN: {
+ message: '订单合同只能在订单上用“起草合同”生成。请选择框架合同或其他。',
+ },
+ RECORD_LOCKED: {
+ message: '订单合同的金额就是订单金额:请修改订单,草稿合同会随之更新。',
+ reasons: {
+ form: { message: '合同形式只能在草稿时选择,订单合同始终是订单合同。' },
+ contract_value: { message: '已激活合同的合同金额只能通过“变更”修改,并需填写原因、上传签署的变更协议。' },
+ end_date: { message: '已激活合同的结束日期只能通过“变更”修改,并需填写原因、上传签署的变更协议。' },
+ payment_terms: { message: '已激活合同的付款条款只能通过“变更”修改,并需填写原因、上传签署的变更协议。' },
+ },
+ },
+ VALIDATION_FAILED: {
+ message: '变更需要填写原因,并上传新签署的变更协议。',
+ reasons: {
+ not_activated: { message: '“变更”只适用于已激活的合同。草稿合同请直接编辑。' },
+ order_value: { message: '订单合同的变更不填写金额:选择“按订单更新”以取订单金额。' },
+ },
+ },
+ },
+ },
contract_validation: {
refusals: {
VALIDATION_FAILED: {
message: '合同期限({{term}} 个月)与日期范围不符(从 {{start}} 到 {{end}} 为 {{calc}} 个月)。',
},
- RECORD_LOCKED: {
- message: '已激活合同的结束日期不能提前({{from}} → {{to}})。请改用终止或变更流程。',
- },
},
},
event_do_not_call_guard: {
diff --git a/src/sales/translations/zh-CN/objects.commerce.ts b/src/sales/translations/zh-CN/objects.commerce.ts
index c9fe6e000..5e26666da 100644
--- a/src/sales/translations/zh-CN/objects.commerce.ts
+++ b/src/sales/translations/zh-CN/objects.commerce.ts
@@ -75,10 +75,28 @@ export const commerce: Record = {
document_url: { label: '合同文档' },
special_terms: { label: '特殊条款' },
billing_address: { label: '账单地址' },
+ // The contract's form, an order contract's amount and Change (#2804).
+ contract_form: {
+ label: '合同形式',
+ help: '订单合同:由订单起草,金额就是订单金额。框架合同:金额手工填写,可挂多张订单。其他:没有金额,例如保密协议。',
+ options: { order: '订单合同', framework: '框架合同', other: '其他' },
+ },
+ crm_sales_order: { label: '来源订单', help: '起草这份合同的订单。' },
+ order_amount: { label: '订单金额', help: '订单的含税总额。' },
+ order_amount_differs: { label: '与订单金额不一致', help: '合同金额已不等于订单金额。用“变更”并选择“按订单更新”,可取订单的当前金额。' },
+ change_reason: { label: '变更原因', help: '合同最近一次变更的原因。由“变更”写入。' },
+ change_amendment: { label: '签署的变更协议', help: '客户为最近一次变更签署的补充协议。由“变更”写入。' },
+ change_new_value: { label: '新合同金额', help: '留空则保持合同金额不变。' },
+ change_new_end_date: { label: '新结束日期', help: '留空则保持结束日期不变。' },
+ change_new_payment_terms: { label: '新付款条款', help: '留空则保持付款条款不变。' },
+ change_from_order: { label: '按订单更新', help: '把订单的当前金额作为合同金额。' },
},
// Print Contract (#2317).
_actions: {
print_contract: { label: '打印合同', successMessage: '合同 PDF 已归档到附件。' },
+ // Change (#2804): one action per kind of contract.
+ change_contract: { label: '变更', description: '变更这份已激活合同的金额、结束日期或付款条款。留空的项保持不变。', successMessage: '合同 {{ record.name }} 已变更。' },
+ change_order_contract: { label: '变更', description: '变更这份已激活订单合同的结束日期或付款条款,或取订单的当前金额。留空的项保持不变。', successMessage: '合同 {{ record.name }} 已变更。' },
},
_views: {
all_contracts: { label: '全部合同' },
@@ -93,6 +111,7 @@ export const commerce: Record = {
value: { label: '合同金额' },
status: { label: '状态与审批' },
renewal: { label: '续约' },
+ change: { label: '最近一次变更' },
// contract.view.ts 表单区块名称 (#1100)
contract_terms: { label: '条款' },
signing_and_documents: { label: '签署与文件' },
diff --git a/src/sales/views/contract.view.ts b/src/sales/views/contract.view.ts
index 313a277ac..6fb51c83c 100644
--- a/src/sales/views/contract.view.ts
+++ b/src/sales/views/contract.view.ts
@@ -111,8 +111,10 @@ export const ContractViews = defineView({
name: 'parties',
label: 'Parties',
columns: 3,
- // The name first: a new contract asks for it (hotcrm#2746).
- fields: ['name', 'contract_number', 'crm_account', 'crm_contact', 'crm_opportunity', 'owner_id', 'status'],
+ // The name first: a new contract asks for it (hotcrm#2746). The form
+ // next (hotcrm#2804): a person creating a contract chooses Framework
+ // or Other, and it decides whether the value is required.
+ fields: ['name', 'contract_form', 'contract_number', 'crm_account', 'crm_contact', 'crm_opportunity', 'owner_id', 'status'],
},
{
// Named `contract_terms`, not `terms` — `terms` is already a distinct
diff --git a/test/backfill-contract-form.test.ts b/test/backfill-contract-form.test.ts
new file mode 100644
index 000000000..9543c81db
--- /dev/null
+++ b/test/backfill-contract-form.test.ts
@@ -0,0 +1,81 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { REPO_ROOT } from './helpers/repo-root';
+
+type Rec = Record;
+
+/**
+ * `scripts/backfill-contract-form.ts` (hotcrm#2804) writes each contract an
+ * upgraded database holds without a form, once, carrying no choice: the rule
+ * that picks the form is the contract hook's (`contract_form_and_change`,
+ * pinned on a booted stack by `contract-form-change.test.ts`). It never writes
+ * a contract that has a form, never writes a value, and lists the order
+ * contracts whose value differs from their order.
+ *
+ * Run as an operator runs it, with `--apply`, against a stubbed REST door; the
+ * stub stands in for the hook by giving each written row a form.
+ */
+
+const ROWS: Rec[] = [
+ { id: 'c1', contract_number: 'CTR-0001', name: 'Old one', contract_form: null, contract_value: 5_000, order_amount: 0 },
+ { id: 'c2', contract_number: 'CTR-0002', name: 'Differs', contract_form: 'order', contract_value: 1_100, order_amount: 1_300 },
+ { id: 'c3', contract_number: 'CTR-0003', name: 'Agrees', contract_form: 'order', contract_value: 900, order_amount: 900 },
+ { id: 'c4', contract_number: 'CTR-0004', name: 'Framework', contract_form: 'framework', contract_value: 2_000, order_amount: 0 },
+];
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('scripts/backfill-contract-form.ts --apply', () => {
+ it('writes each contract without a form once, with no choice, and lists the order contracts that differ', async () => {
+ const rows = structuredClone(ROWS);
+ const patches: Array<{ id: string; body: Rec }> = [];
+ const reply = (status: number, json: unknown) => ({
+ status, headers: { getSetCookie: (): string[] => [] }, text: async () => JSON.stringify(json),
+ });
+ const stub = vi.fn(async (input: string | URL, init?: { method?: string; body?: unknown }) => {
+ const { pathname } = new URL(String(input));
+ if (pathname === '/api/v1/auth/sign-in/email') return reply(200, { user: { id: 'admin', email: 'admin@hotcrm.test' } });
+ if (pathname === '/api/v1/data/crm_contract/query' && init?.method === 'POST') return reply(200, { records: rows });
+ const patch = /^\/api\/v1\/data\/crm_contract\/([^/]+)$/.exec(pathname);
+ if (patch && init?.method === 'PATCH') {
+ patches.push({ id: patch[1]!, body: JSON.parse(String(init.body)) as Rec });
+ rows.find((c) => c.id === patch[1])!.contract_form = 'framework'; // the hook's rule
+ return reply(200, { record: { id: patch[1] } });
+ }
+ return reply(404, { error: `no route for ${init?.method} ${pathname}` });
+ });
+ vi.stubGlobal('fetch', stub);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const failed = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const argv = process.argv;
+ const exitCode = process.exitCode;
+ process.argv = [argv[0]!, 'backfill-contract-form-probe', '--apply'];
+ try {
+ await import(pathToFileURL(join(REPO_ROOT, 'scripts', 'backfill-contract-form.ts')).href);
+ let seen = -1;
+ for (let turn = 0; turn < 200 && seen !== stub.mock.calls.length; turn++) {
+ seen = stub.mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ expect(process.exitCode ?? 0, 'the script reported a failure').toBe(0);
+ } finally {
+ process.argv = argv;
+ process.exitCode = exitCode;
+ }
+
+ expect(failed).not.toHaveBeenCalled();
+ expect(patches).toEqual([{ id: 'c1', body: { contract_form: null } }]);
+ const printed = log.mock.calls.map((c) => String(c[0])).join('\n');
+ expect(printed).toContain('differs from the order amount: 1.');
+ expect(printed).toContain('CTR-0002 "Differs": contract 1100, order 1300');
+ expect(printed).not.toContain('CTR-0003 "Agrees":');
+ expect(printed).not.toContain('no Order Amount yet');
+ });
+});
diff --git a/test/contract-form-change.test.ts b/test/contract-form-change.test.ts
new file mode 100644
index 000000000..15e4086e6
--- /dev/null
+++ b/test/contract-form-change.test.ts
@@ -0,0 +1,353 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import { describe, it, expect, beforeAll, vi } from 'vitest';
+import type { VerifyStack } from '@objectstack/verify';
+import { ExpressionEngine } from '@objectstack/formula';
+import { ChangeContractAction, ChangeOrderContractAction } from '../src/sales/actions/contract.actions';
+import { DraftContractAction } from '../src/sales/actions/sales_order.actions';
+import { Contract } from '../src/sales/objects/contract.object';
+import { ContractViews } from '../src/sales/views/contract.view';
+import {
+ hotcrmStack, signUpPerson, committedFile, systemUpdate, type Person,
+} from './helpers/verify-stack';
+
+type Rec = Record;
+
+/**
+ * The contract's form, an order contract's value and Change (hotcrm#2804, hook
+ * `contract_form_and_change`,
+ * maintainer ruling 2026-11-26), against a booted stack.
+ *
+ * 1. Draft Contract on an order drafts an ORDER contract naming its order,
+ * at the order's tax-inclusive total; a person cannot type its value, and
+ * while it is a draft it follows the order.
+ * 2. Once activated the value, the end date and the payment terms are locked:
+ * a direct write is refused by name, the order's later change only shows
+ * Differs from the Order Amount, and Change — with a reason and a newly
+ * signed amendment — is the one way to move them, recorded in the history.
+ * 3. On an order contract Change offers no value, only Update from Order; a
+ * framework contract may be given a new value. The status stays Activated.
+ * 4. A contract saved before the form existed takes its form by the backfill
+ * rule on its next write, and keeps its value.
+ */
+
+let verify: VerifyStack;
+let manager: Person;
+let rep: Person;
+beforeAll(async () => {
+ verify = await hotcrmStack();
+ manager = await signUpPerson(verify, 'manager@contract-form-change.test', {
+ name: 'Form Manager', positions: ['crm_sales_manager'], permissionSets: ['sales_manager'],
+ });
+ rep = await signUpPerson(verify, 'rep@contract-form-change.test', {
+ name: 'Form Rep', positions: ['crm_sales_rep'], permissionSets: ['sales_rep'],
+ });
+}, 120_000);
+
+const as = (who: Person) => ({ as: who.token });
+const stored = async (object: string, id: string): Promise => (await verify.rows(object, { id }))[0]!;
+const refusal = (p: Promise): Promise => p.then(() => null, (e: Rec) => e);
+/** The ADR-0112 envelope: code and status, never the throw alone. */
+const expectRefused = (err: Rec | null, code: string, status: number) => {
+ expect(err, `the write was accepted; expected ${code}`).toBeTruthy();
+ expect(err!.code).toBe(code);
+ expect(err!.status ?? err!.statusCode).toBe(status);
+};
+
+let k = 0;
+/** An account and contact of the rep's. */
+const parties = async (): Promise<{ account: string; contact: string }> => {
+ const [account] = await verify.seed('crm_account', [{ name: `Form Co ${++k}`, type: 'prospect', owner_id: rep.id }]);
+ const [contact] = await verify.seed('crm_contact', [{
+ first_name: 'Fay', last_name: `Form ${k}`, email: `fay${k}@contract-form-change.test`, crm_account: account!.id, owner_id: rep.id,
+ }]);
+ return { account: String(account!.id), contact: String(contact!.id) };
+};
+
+/** A draft order of the rep's: subtotal 1 000, tax 100 → total 1 100. */
+const draftOrder = async (): Promise => {
+ const { account, contact } = await parties();
+ return (await verify.hooks.run('crm_sales_order', 'insert', {
+ name: `Form order ${k}`, crm_account: account, crm_contact: contact, subtotal: 1_000, tax: 100,
+ }, as(rep))) as Rec;
+};
+
+/** Draft Contract on `orderId`, as the rep, through the flow door the action uses; the drafted contract. */
+const draftFrom = async (orderId: string): Promise => {
+ await verify.flows.run(DraftContractAction.target as string, { recordId: orderId, objectName: 'crm_sales_order' }, as(rep));
+ const order = await stored('crm_sales_order', orderId);
+ expect(order.crm_contract, 'Draft Contract named no contract on the order').toBeTruthy();
+ return stored('crm_contract', String(order.crm_contract));
+};
+
+/** Take `id` from draft to activated, as the manager, with the signed copy. */
+const activate = async (id: string): Promise => {
+ await verify.hooks.run('crm_contract', 'update', { id, status: 'in_approval' }, as(manager));
+ await verify.hooks.run('crm_contract', 'update', {
+ id, status: 'activated', signed_copy: await committedFile(verify, manager.id),
+ }, as(manager));
+ expect((await stored('crm_contract', id)).status).toBe('activated');
+};
+
+/** A framework contract, activated, at 12 000 over 2026. */
+const activeFramework = async (): Promise => {
+ const { account, contact } = await parties();
+ const [c] = await verify.seed('crm_contract', [{
+ name: `Framework ${k}`, crm_account: account, crm_contact: contact, contract_form: 'framework', contract_value: 12_000,
+ start_date: '2026-01-01', end_date: '2027-01-01', contract_term_months: 12, payment_terms: 'net_30',
+ status: 'activated', owner_id: manager.id, signed_copy: await committedFile(verify, manager.id),
+ }]);
+ return c!;
+};
+
+/** Run Change on `id` as the manager, through the action door the console posts to. */
+const change = (action: string, id: string, params: Rec) =>
+ verify.actions.run('crm_contract', action, { as: manager.token, recordId: id, params });
+
+/** Each field's latest tracked change on `id`: { old, new } from the history. */
+const lastTracked = async (id: string, field: string): Promise<{ old: unknown; new: unknown } | undefined> => {
+ const entries = (await verify.rows('sys_activity', { object_name: 'crm_contract', record_id: id }))
+ .map((r: Rec) => ({ at: String(r.timestamp), meta: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata }))
+ .filter((e) => e.meta?.new && field in e.meta.new)
+ .sort((x, y) => y.at.localeCompare(x.at));
+ const top = entries[0];
+ return top ? { old: top.meta.old?.[field], new: top.meta.new[field] } : undefined;
+};
+
+describe('Draft Contract drafts an order contract (hotcrm#2804 item 2)', () => {
+ let order: Rec;
+ let contract: Rec;
+ beforeAll(async () => {
+ order = await draftOrder();
+ contract = await draftFrom(String(order.id));
+ }, 60_000);
+
+ it('is an order contract naming its order, at the order\'s tax-inclusive total', async () => {
+ expect(Number(order.total_price)).toBe(1_100);
+ expect(contract.contract_form).toBe('order');
+ expect(contract.crm_sales_order).toBe(order.id);
+ expect(Number(contract.contract_value)).toBe(1_100);
+ await vi.waitFor(async () => expect(Number((await stored('crm_contract', contract.id)).order_amount)).toBe(1_100),
+ { timeout: 10_000, interval: 50 });
+ });
+
+ it('refuses a person who types its value, and keeps the value', async () => {
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', { id: contract.id, contract_value: 5 }, as(manager))), 'RECORD_LOCKED', 409);
+ expect(Number((await stored('crm_contract', contract.id)).contract_value)).toBe(1_100);
+ });
+
+ it('follows the order while it is a draft', async () => {
+ await verify.hooks.run('crm_sales_order', 'update', { id: order.id, tax: 250 }, as(rep));
+ await vi.waitFor(async () => {
+ const c = await stored('crm_contract', contract.id);
+ expect(Number(c.order_amount)).toBe(1_250);
+ expect(Number(c.contract_value)).toBe(1_250);
+ }, { timeout: 10_000, interval: 50 });
+ });
+
+ it('refuses a person who makes an order contract by hand, or moves one to another form', async () => {
+ const { account, contact } = await parties();
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'insert', {
+ name: 'By hand', crm_account: account, crm_contact: contact, contract_form: 'order', contract_value: 1,
+ start_date: '2026-01-01', end_date: '2027-01-01', contract_term_months: 12,
+ }, as(manager))), 'FORBIDDEN', 403);
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', { id: contract.id, contract_form: 'framework' }, as(manager))), 'RECORD_LOCKED', 409);
+ expect((await stored('crm_contract', contract.id)).contract_form).toBe('order');
+ });
+});
+
+describe('contract_form_and_change — an activated order contract: locked, a sign when the order moves, Change from the order (items 2, 5)', () => {
+ let order: Rec;
+ let contract: Rec;
+ beforeAll(async () => {
+ order = await draftOrder();
+ contract = await draftFrom(String(order.id));
+ await activate(String(contract.id));
+ // The order's amount changes after activation.
+ await verify.hooks.run('crm_sales_order', 'update', { id: order.id, tax: 300 }, as(rep));
+ await vi.waitFor(async () => expect(Number((await stored('crm_contract', contract.id)).order_amount)).toBe(1_300),
+ { timeout: 10_000, interval: 50 });
+ }, 90_000);
+
+ it('keeps the signed value when the order changes, and says it differs', async () => {
+ const c = await stored('crm_contract', contract.id);
+ expect(Number(c.contract_value)).toBe(1_100);
+ const differs = ExpressionEngine.evaluate((Contract.fields.order_amount_differs as Rec).expression, { record: c } as never);
+ expect(differs).toMatchObject({ ok: true, value: true });
+ const agrees = ExpressionEngine.evaluate((Contract.fields.order_amount_differs as Rec).expression, { record: { ...c, contract_value: 1_300 } } as never);
+ expect(agrees).toMatchObject({ ok: true, value: null });
+ });
+
+ it('refuses a direct write to the end date or the payment terms, by name', async () => {
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', { id: contract.id, end_date: '2030-01-01' }, as(manager))), 'RECORD_LOCKED', 409);
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', { id: contract.id, payment_terms: 'net_60' }, as(manager))), 'RECORD_LOCKED', 409);
+ });
+
+ it('refuses a change without the signed amendment, at the dialog\'s door and at the record, and changes nothing', async () => {
+ // The action door holds the param contract: a required param missing.
+ const door = await refusal(change('change_order_contract', contract.id, { change_reason: 'New price list', change_from_order: true }));
+ expectRefused(door, 'VALIDATION_ERROR', 400);
+ expect(String(door!.message ?? '')).toMatch(/amendment/i);
+ // A write past the dialog meets the hook.
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', {
+ id: contract.id, change_reason: 'New price list', change_from_order: true,
+ }, as(manager))), 'VALIDATION_FAILED', 400);
+ expect(Number((await stored('crm_contract', contract.id)).contract_value)).toBe(1_100);
+ });
+
+ it('refuses a typed value on an order contract', async () => {
+ // Not one of the order contract's params at all …
+ expectRefused(await refusal(change('change_order_contract', contract.id, {
+ change_reason: 'Typed', change_amendment: await committedFile(verify, manager.id), change_new_value: 9,
+ })), 'VALIDATION_ERROR', 400);
+ // … and refused on the record when written past the dialog.
+ const err = await refusal(verify.hooks.run('crm_contract', 'update', {
+ id: contract.id, change_reason: 'Typed', change_amendment: await committedFile(verify, manager.id), change_new_value: 9,
+ }, as(manager)));
+ expectRefused(err, 'VALIDATION_FAILED', 400);
+ expect(Number((await stored('crm_contract', contract.id)).contract_value)).toBe(1_100);
+ });
+
+ it('takes the order\'s amount on Update from Order, stays Activated, and records before and after', async () => {
+ await change('change_order_contract', contract.id, {
+ change_reason: 'Order re-quoted', change_amendment: await committedFile(verify, manager.id), change_from_order: true,
+ });
+ const c = await stored('crm_contract', contract.id);
+ expect(Number(c.contract_value)).toBe(1_300);
+ expect(c.status).toBe('activated');
+ expect(c.change_reason).toBe('Order re-quoted');
+ expect(c.change_from_order ?? false).toBe(false);
+ const tracked = await lastTracked(contract.id, 'contract_value');
+ expect(tracked && Number(tracked.old)).toBe(1_100);
+ expect(tracked && Number(tracked.new)).toBe(1_300);
+ });
+});
+
+describe('Change on a framework contract (item 5)', () => {
+ it('moves the value, the end date and the payment terms, re-counts the term, and clears its inputs', async () => {
+ const c = await activeFramework();
+ await change('change_contract', c.id, {
+ change_reason: 'Scope extended', change_amendment: await committedFile(verify, manager.id),
+ change_new_value: 18_000, change_new_end_date: '2027-07-01', change_new_payment_terms: 'net_60',
+ });
+ const row = await stored('crm_contract', c.id);
+ expect(Number(row.contract_value)).toBe(18_000);
+ expect(row.end_date).toBe('2027-07-01');
+ expect(row.payment_terms).toBe('net_60');
+ expect(row.contract_term_months).toBe(18);
+ expect(row.status).toBe('activated');
+ expect(row.change_new_value ?? null).toBeNull();
+ expect(row.change_new_end_date ?? null).toBeNull();
+ expect(row.change_new_payment_terms ?? null).toBeNull();
+ expect((await lastTracked(c.id, 'end_date'))?.old).toBe('2027-01-01');
+ });
+
+ it('refuses a change without a reason', async () => {
+ const c = await activeFramework();
+ expectRefused(await refusal(change('change_contract', c.id, {
+ change_amendment: await committedFile(verify, manager.id), change_new_value: 1,
+ })), 'VALIDATION_ERROR', 400);
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', {
+ id: c.id, change_amendment: await committedFile(verify, manager.id), change_new_value: 1,
+ }, as(manager))), 'VALIDATION_FAILED', 400);
+ expect(Number((await stored('crm_contract', c.id)).contract_value)).toBe(12_000);
+ });
+
+ it('refuses Change on a contract that is not activated', async () => {
+ const c = await activeFramework();
+ await systemUpdate(verify, 'crm_contract', { id: c.id, status: 'terminated' });
+ expectRefused(await refusal(verify.hooks.run('crm_contract', 'update', {
+ id: c.id, change_reason: 'Late', change_amendment: await committedFile(verify, manager.id), change_new_value: 1,
+ }, as(manager))), 'VALIDATION_FAILED', 400);
+ });
+});
+
+describe('the backfill rule (item 7)', () => {
+ /** A contract as it was before the form: no form at all. */
+ const formless = async (doc: Rec, own?: { account: string; contact: string }): Promise => {
+ const { account, contact } = own ?? await parties();
+ const [c] = await verify.seed('crm_contract', [{
+ name: `Old ${k}`, crm_account: account, crm_contact: contact, contract_value: 5_000,
+ start_date: '2026-01-01', end_date: '2027-01-01', contract_term_months: 12, status: 'draft', ...doc,
+ }]);
+ const ql = verify.kernel.getService('objectql');
+ await (ql.getDriverForObject('crm_contract') as Rec).update('crm_contract', c!.id, { contract_form: null });
+ expect((await stored('crm_contract', c!.id)).contract_form ?? null, 'the fixture still has a form').toBeNull();
+ return c!;
+ };
+
+ it('drafted and named by an order ⇒ order contract with that order, its value kept', async () => {
+ const order = await draftOrder();
+ const c = await formless({ automation_key: 'quote_acceptance', contract_value: 999 },
+ { account: String(order.crm_account), contact: String(order.crm_contact) });
+ // Linking the order rolls its amount onto the contract: that system write
+ // is the contract's first, and backfills the form without correcting the
+ // value.
+ await systemUpdate(verify, 'crm_sales_order', { id: order.id, crm_contract: c.id });
+ await verify.hooks.run('crm_contract', 'update', { id: c.id, description: 'Touched.' }, as(manager));
+ const row = await stored('crm_contract', c.id);
+ expect(row.contract_form).toBe('order');
+ expect(row.crm_sales_order).toBe(order.id);
+ expect(Number(row.contract_value)).toBe(999);
+ });
+
+ it('does not correct an old draft order contract when its Order Amount is first computed', async () => {
+ const order = await draftOrder();
+ const c = await draftFrom(String(order.id));
+ // As a contract that predates the roll-up: no Order Amount yet, and a
+ // value that differs from its order.
+ const ql = verify.kernel.getService('objectql');
+ await (ql.getDriverForObject('crm_contract') as Rec).update('crm_contract', c.id, { order_amount: null, contract_value: 500 });
+ // The platform materialises it (`os migrate summary-nulls`), as the system.
+ await systemUpdate(verify, 'crm_contract', { id: c.id, order_amount: 1_100 });
+ const row = await stored('crm_contract', c.id);
+ expect(Number(row.order_amount)).toBe(1_100);
+ expect(Number(row.contract_value)).toBe(500);
+ });
+
+ it('no amount ⇒ other; the rest ⇒ framework', async () => {
+ const none = await formless({ contract_value: 0 });
+ const some = await formless({});
+ for (const c of [none, some]) await systemUpdate(verify, 'crm_contract', { id: c.id, description: 'Touched.' });
+ expect((await stored('crm_contract', none.id)).contract_form).toBe('other');
+ expect((await stored('crm_contract', some.id)).contract_form).toBe('framework');
+ });
+});
+
+describe('the metadata', () => {
+ const offered = (action: Rec, record: Rec): boolean => {
+ const result = ExpressionEngine.evaluate(action.visible as never, {
+ record, user: { id: manager.id, positions: ['crm_sales_manager'] },
+ permissions: { crm_contract: { allowRead: true, allowEdit: true } } as never,
+ } as never);
+ expect(result.ok, JSON.stringify(result)).toBe(true);
+ return (result as Rec).value === true;
+ };
+
+ it('offers each Change on activated contracts of its kind only', () => {
+ const order = { status: 'activated', contract_form: 'order' };
+ const framework = { status: 'activated', contract_form: 'framework' };
+ expect([offered(ChangeOrderContractAction, order), offered(ChangeContractAction, order)]).toEqual([true, false]);
+ expect([offered(ChangeOrderContractAction, framework), offered(ChangeContractAction, framework)]).toEqual([false, true]);
+ expect(offered(ChangeContractAction, { status: 'draft', contract_form: 'framework' })).toBe(false);
+ expect(offered(ChangeContractAction, {})).toBe(false);
+ });
+
+ it('gives the order contract no value input, only Update from Order', () => {
+ const names = (a: Rec) => (a.params as Rec[]).map((p) => p.field);
+ expect(names(ChangeOrderContractAction)).toContain('change_from_order');
+ expect(names(ChangeOrderContractAction)).not.toContain('change_new_value');
+ expect(names(ChangeContractAction)).toContain('change_new_value');
+ for (const a of [ChangeContractAction, ChangeOrderContractAction]) {
+ expect((a.params as Rec[]).filter((p) => p.required).map((p) => p.field)).toEqual(['change_reason', 'change_amendment']);
+ }
+ });
+
+ it('keeps the history the ruling names, and asks for the form on the edit form', () => {
+ for (const f of ['contract_value', 'start_date', 'end_date', 'payment_terms', 'change_reason']) {
+ expect((Contract.fields as Rec)[f].trackHistory, f).toBe(true);
+ }
+ const fields = (ContractViews.form!.sections as Rec[]).flatMap((s) => s.fields as string[]);
+ expect(fields).toContain('contract_form');
+ });
+});
diff --git a/test/hooks-runtime-service.test.ts b/test/hooks-runtime-service.test.ts
index 315c7c2cd..84378fbb9 100644
--- a/test/hooks-runtime-service.test.ts
+++ b/test/hooks-runtime-service.test.ts
@@ -323,18 +323,22 @@ describe('contract_validation', () => {
await expect(managerContract({ start_date: '2026-01-01', end_date: '2026-12-15', contract_term_months: 12 })).resolves.toBeTruthy();
});
- it('refuses to move End Date earlier after activation, naming the field by its label', async () => {
- // Shrunk within the term's one-month tolerance, so the shrink rule is the
- // one that answers.
+ // An activated contract's End Date moves only through Change (#2804): the
+ // earlier shrink-only rule is gone, and a direct edit in either direction is
+ // refused by contract_form_and_change, naming the field.
+ it('refuses moving End Date earlier after activation, naming the field by its label', async () => {
const contract = await contractOf({ status: 'activated', start_date: '2026-01-01', end_date: '2027-01-01', contract_term_months: 12 });
- await expect(verify.hooks.run('crm_contract', 'update', { id: contract.id, end_date: '2026-12-15' }, as(manager)))
- .rejects.toThrow(/End Date cannot move earlier/);
+ const err = await verify.hooks.run('crm_contract', 'update', { id: contract.id, end_date: '2026-12-15' }, as(manager)).catch((e) => e);
+ expect([err?.code, err?.status ?? err?.statusCode]).toEqual(['RECORD_LOCKED', 409]);
+ expect(String(err?.message)).toMatch(/End Date changes only through Change/);
+ expect((await stored('crm_contract', contract.id)).end_date).toBe('2027-01-01');
});
- it('allows extending end_date after activation', async () => {
+ it('refuses extending end_date directly after activation too', async () => {
const contract = await contractOf({ status: 'activated', start_date: '2026-01-01', end_date: '2027-01-01', contract_term_months: 12 });
- await verify.hooks.run('crm_contract', 'update', { id: contract.id, end_date: '2028-01-01', contract_term_months: 24 }, as(manager));
- expect((await stored('crm_contract', contract.id)).end_date).toBe('2028-01-01');
+ const err = await verify.hooks.run('crm_contract', 'update', { id: contract.id, end_date: '2028-01-01', contract_term_months: 24 }, as(manager)).catch((e) => e);
+ expect([err?.code, err?.status ?? err?.statusCode]).toEqual(['RECORD_LOCKED', 409]);
+ expect((await stored('crm_contract', contract.id)).end_date).toBe('2027-01-01');
});
it('allows shrinking end_date while still a draft', async () => {
diff --git a/test/refusal-envelope.test.ts b/test/refusal-envelope.test.ts
index 0067400b5..a55dc17c9 100644
--- a/test/refusal-envelope.test.ts
+++ b/test/refusal-envelope.test.ts
@@ -200,11 +200,17 @@ describe('every refusal names a code the platform will echo (#1075)', () => {
// 98 until hotcrm#2755 added `invoice_plan_step_guard`'s refusal of an
// invoice naming another account's billing milestone; 99 until hotcrm#2761
// added `expense_report_rules`' two refusals of deleting an approved or a
- // paid report, administrators included.
+ // paid report, administrators included; 101 until hotcrm#2804 moved the
+ // contract's end-date refusal out of `contract_validation` (one less) and
+ // added `contract_form_and_change`'s eight (an order contract by hand on
+ // insert and on update, the form's lock, the activated contract's locked
+ // field, an order contract's value, Change on a contract that is not
+ // activated, Change without its reason or amendment, a typed value on an
+ // order contract).
// The number is hand-maintained on purpose: a new refusal has to be a
// deliberate edit here, so a guard that quietly stopped being swept cannot
// hide behind a count that follows it.
- expect(sites).toHaveLength(101);
+ expect(sites).toHaveLength(108);
});
it('uses only members of the platform ErrorCode enum', () => {
diff --git a/test/refusal-labels.test.ts b/test/refusal-labels.test.ts
index 14b4db338..83a248f79 100644
--- a/test/refusal-labels.test.ts
+++ b/test/refusal-labels.test.ts
@@ -78,8 +78,11 @@ describe('freeze refusals use the labels the user sees (#2338 item 12)', () => {
for (const [value, label] of statuses) expect(label, value).toBe(optionLabel(Quote, 'status', value));
});
- it('contract_validation: the end date', () => {
- expect(lowered('contract_validation')).toContain(`contract's ${fieldLabel(Contract, 'end_date')} cannot move earlier`);
+ it('contract_form_and_change: the three fields an activated contract changes only through Change (#2804)', () => {
+ const source = lowered('contract_form_and_change');
+ for (const field of ['contract_value', 'end_date', 'payment_terms']) {
+ expect(source, field).toContain(`An activated contract's ${fieldLabel(Contract, field)} change`);
+ }
});
});
diff --git a/test/runtime-coverage.test.ts b/test/runtime-coverage.test.ts
index 5ad44c1b6..1a1bbfafd 100644
--- a/test/runtime-coverage.test.ts
+++ b/test/runtime-coverage.test.ts
@@ -69,6 +69,10 @@ const RUNTIME_TEST_FILES = [
// #2317 — filing a contract's signed copy dates the signature
// (`contract_signed_copy_date`), beside the two signed-copy gates it serves.
'contract-signed-copy.test.ts',
+ // #2804 — the contract form and Change (`contract_form_and_change`): the
+ // order contract's draft follow, the person locks, both Change actions and
+ // the backfill rule, driven on the booted app.
+ 'contract-form-change.test.ts',
// #592 — the activity model's own runtime file: both `crm_event` hooks, the
// parity check that keeps the duplicated bubble body from drifting, and the
// readonly-strip regression proof against a real engine.
diff --git a/test/sales-order-draft-contract.test.ts b/test/sales-order-draft-contract.test.ts
index 78aa19e3f..11debe491 100644
--- a/test/sales-order-draft-contract.test.ts
+++ b/test/sales-order-draft-contract.test.ts
@@ -205,7 +205,11 @@ describe('the same contract the automatic draft drafts', () => {
.filter((node) => node.type === 'create_record' && node.config.objectName === 'crm_contract')
.map((node) => [node.id, Object.keys(node.config.fields).sort()]));
expect(Object.keys(drafts(QuoteAcceptedContractDraftFlow))).toEqual(CONTRACT_DRAFT_NODE_IDS);
- expect(drafts(SalesOrderDraftContractWriteFlow)).toEqual(drafts(QuoteAcceptedContractDraftFlow));
+ // The order's draft adds two keys of its own (hotcrm#2804): it is an order
+ // contract, naming the order it came from. The quote's draft has no order.
+ const fromQuote = drafts(QuoteAcceptedContractDraftFlow);
+ expect(drafts(SalesOrderDraftContractWriteFlow)).toEqual(Object.fromEntries(Object.entries(fromQuote)
+ .map(([id, keys]) => [id, [...(keys as string[]), 'contract_form', 'crm_sales_order'].sort()])));
});
});