Skip to content

feat(o2c): Prepare Billing reduces the order's automatic full-amount step (#2934) - #2938

Merged
objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/issue-2934-billing-reduces-auto-step
Dec 4, 2026
Merged

objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/issue-2934-billing-reduces-auto-step

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2934

Clause-②: no
Metadata-protocol: none
Metadata-impact: maintainer — a hook changed (a new afterDelete hook, billing_step_give_back, on crm_billing_milestone) and an existing action (Prepare Billing) now changes and deletes the order's generated plan step. No permission set, sharing rule, field or object is added, removed or renamed. AGENTS.md puts "a hook changed" in the maintainer class until the reviewer says otherwise; the reviewer may downgrade it to reviewer (a flow-like data change that does not change who sees what).

维护者速读

  • 用户能看到什么变化:按工时计费的订单上,项目经理每次「准备开票」后,订单确认时自动生成的那条全额回款计划会扣减本次开票金额(扣到零即删除),订单不再常亮「回款计划与订单金额不符」,预期回款不再重复计算。
  • 为什么做:落实您在开票第二步那张合并请求上对第一问选 B(倾向 B-1)的裁决,修正订单与回款里回款计划长期失真的问题。
  • 出错会怎样:受影响的是有项目开票的订单的回款计划金额;如果扣减有误,销售可以直接改回那条计划的金额,删除开票计划也会把金额还回去,可以撤回。升级前已经开过票的订单不会被自动修正,仍会显示不符。
  • 要你做什么:确认三个默认处理(已有回款或发票指向的自动计划不动、有多条自动计划不动、升级前的老订单不回填)是否可以接受。

What changes

  • Prepare Billing (src/psa/actions/billing.actions.ts), in the same ctx.api.transaction as the run: after the stamps and their count check, the order's generated step (origin = order_confirmation) is reduced by the amount billed and deleted when it reaches zero. Payment Plan Differs then reads true only when the plan really differs. The action's result gains order_step ({ id, amount, deleted }, or null when nothing was reduced).
  • Concurrency. The reduction is a compare-and-set, like the stamps: a predicate write (multi: true) on { id, planned_amount: <amount read> } whose answered row count must be 1. Another writer between the read and the write makes it 0, and the run throws CONFLICT and rolls back (step, stamps and all), the existing 409 the person retries. Measured: the engine's predicate update and delete answer the row count through the sandbox facade.
  • Decisions (stated, not guessed):
    • A run billing more than the generated step still holds: the step is deleted and the whole bill is kept. The threshold is the generated step's own amount, which is below the order's total when a rep split the plan, so on a split plan this happens before the order's total is reached. The plan then grows by the excess and the order shows Payment Plan Differs, which is true.
    • Generated step with money received on it, or an invoice naming it (the hidden crm_invoice.crm_billing_milestone column): left as it is. Someone is working that plan.
    • Several generated steps (only an import or the API can make a second one): all left as they are.
    • Contract-only project: contracts have no generated step; nothing else changes.
  • Deleting a billing step gives its amount back (billing_step_give_back, src/o2c/objects/billing_milestone.hook.ts, afterDelete, runAs: 'system'). Why: deleting a billing step clears its rows (objectstack#34899), so the next run bills them again and reduces the step again. Without the give-back the same rows would be taken off twice. Same conditions as the reduction; the generated step never grows past the order's Total Price, so a billing step written before this change (which took nothing) gives nothing back. When the generated step is gone, nothing is recreated: the plan reads short until the next run bills the rows again, which restores it.
  • What the give-back does not guarantee (stated plainly):
    • It runs after the delete has committed, outside the delete's transaction. It cannot hold the delete back.
    • Its write is a compare-and-set, up to three attempts. After the third miss it gives up, logs a warning (ctx.log.warn, naming the order, the step and the amount), and the generated step stays short of the amount until a person corrects it.
    • It does not record what each billing run actually took off the generated step. It gives back the deleted step's Planned Amount and relies on the Total Price cap for steps that took less or nothing (a step billed before this change, or a run that found the generated step not clean).
  • Rule 11, the sanctioned way: src/sales/objects/_hook-api.ts declares HookCompareAndSetOptions (where names the id, multi: true) as an update overload answering the row count (measured: 1 when the compare held, 0 when another writer moved the row). It carries the reason and the roster of its one caller. No guard in test/ reads hook write options, so that comment and the hook's comment are the record. HookLogContext types ctx.log; the build grants the lowered body log (measured: ["api.read","api.write","log"]).
  • Readers checked. planned_amount/plan_differs on the order (sales-order.extension.ts, a summary and a formula, no code change); the amount-follow flow edges e6/e7 (sales-order-amount-plan-step.flow.ts) still follow only a lone non-billing step: after a reduction the order has several steps and is left alone, and after the generated step is deleted a lone billing step still takes e7. The confirmation flow creates a step only when there is none. The cancel-trim flow is unaffected. open_amount drives the Overdue view (a reduced step is open less, which is correct). The contract's planned summary sees the same steps. No dataset or dashboard reads these fields. The project's Billed / Not Yet Billed (Project Delivery phase 3, step 3b: billed and not yet billed on the project, in the project financials and on the dashboard; manual and docs #2622) is not touched.
  • Manuals and docs: crm_psa_billing (en, zh), crm_o2c_collection_plan (en, zh), the docs site's Time and Expenses and Collection Plan pages (en, zh-Hans, zh-Hant) and psa-module-plan.md. The "tracked in Order to Cash: Prepare Billing reduces the order's automatic full-amount payment plan step, so Payment Plan Differs stays truthful #2934" wording is replaced by the new behaviour.
  • Changeset .changeset/2934-billing-reduces-auto-step.md (minor), including the upgrade note.

Tests

test/psa-prepare-billing-order-step.test.ts (19 cases, on the booted app through the action door), with exact figures:

  • 10,000 order: 300 then 150 billed → generated step 9,700 then 9,550; order Planned 10,000, plan_differs empty; open across the plan = 10,000.
  • 300 order billed 300 → generated step deleted, plan = 300, no flag. 400 order billed 450 → deleted, plan 450, flag true.
  • Received 1,000 on the generated step → untouched (10,000 + 300 = 10,300, flag true). Invoice naming it → untouched. Two generated steps (500, 10,000) → untouched.
  • Another writer moves the step to 9,000 at the compare-and-set → 409 CONFLICT, no billing step, no stamp, step still 10,000; the retry gives 9,700.
  • Contract project → order_step null, contract steps unchanged.
  • Give-back on a split plan (generated step 6,000 + a 4,000 step by hand): billing 300 → 5,700; delete → exactly 6,000 (the 10,000 cap not reached); billing again → 5,700, plan 10,000, no flag.
  • Delete the 300 billing step → generated step back to 10,000; billing again → 9,700, plan 10,000, no flag. A billing step from before this change (generated step at 10,000) → deleting it leaves 10,000.
  • Generated step already deleted (300 order billed 300): deleting the billing step recreates nothing (no steps, no flag); billing again → billing 300, plan 300.
  • Generated step with 1,000 received after the run: deleting the billing step gives nothing back (9,700 stays; plan 9,700 against 10,000, flag true).
  • Retry: another writer moves the generated step to 9,600 then 9,500 → the third attempt writes 9,500 + 300 = 9,800. Three misses (9,600, 9,500, 9,400) → the delete stands and the step keeps 9,400; the shipped (lowered) body run in the platform's sandbox logs exactly one warning: [hook 'billing_step_give_back'] billing_step_give_back: the generated plan step kept changing; its amount was not given back with { order, step, amount: 300 }. (The booted handle runs handlers in-process, whose context has no ctx.log, so the warning is read off the shipped body; runShippedHook gained an optional host logger.)
  • Total raised from 10,000 to 12,000 after a reduction: the follow flow leaves both steps (9,700 + 300), plan 10,000 against 12,000, flag true.
  • Cancel-trim with billing steps: with 100 received on the 300 billing step → the generated 9,700 is deleted, the billing step lowered to 100, no flag; with nothing received → both steps deleted (the give-back included), the trim run completed.

test/runtime-coverage.test.ts: the new file joins RUNTIME_TEST_FILES, so the new hook is named in a runtime test.

Ablation (red without the change)
  • The reduction disabled (if (false && orderId)): 5 of 10 red (the 9,700/9,550 case, exactly-zero, beyond-the-order, the CONFLICT case, the give-back case); restored, 10/10.
  • Only the give-back hook unregistered: 1 red, expected 9700 to be 10000; restored, 10/10.
  • After review (19 cases): the Total Price cap replaced by the ceiling (round2(ceiling)): 2 red, the split plan (expected 10000 to be 6000) and the two-miss retry (expected 10000 to be 9800). The row-count check removed (return after the first write whatever it answered): 3 red, the two-miss retry (expected 9600 to be 9800), three misses (expected 9600 to be 9400) and the shipped-body warning case. Restored, 19/19.

Acceptance notes

  • Pre-existing, not changed here: when the cancel-trim flow deletes a billing step that billed time, its rows are cleared as on any delete of a billing step (objectstack#34899), so they would be billable again on the cancelled order's project. Read from the documented clear-on-delete, not measured on the cancel path here.
  • Upgrade: billing steps written before this release did not reduce the generated step, so an order billed before the upgrade keeps showing Payment Plan Differs until a person lowers its generated step. No backfill here. The changeset says so, and the question is in the report.
  • When the order's total changes after a reduction (generated step + billing steps), the amount-follow flow leaves the plan alone (several steps, as before) and the order shows Payment Plan Differs until the rep adjusts the generated step. Making that flow re-derive the generated step is not in this card.

Verification

Booted `objectstack dev` (port 4001), Wayne Operations Module Rollout (seeded T&M) linked to a new 10,000 order confirmed Draft→Confirmed, a consultant's timesheet submitted and approved through the approval, Prepare Billing twice

en:

confirmed    {"total":10000,"planned":10000,"plan_differs":null,"steps":[["order_confirmation",10000,10000]],"open_sum":10000}
prepare 2026-11-02 200 … "amount":1360 … "order_step":{"amount":8640,"deleted":false}
after run 1  {"total":10000,"planned":10000,"plan_differs":null,"steps":[["billing",1360,1360],["order_confirmation",8640,8640]],"open_sum":10000}
prepare 2026-11-09 200 … "amount":680 … "order_step":{"amount":7960,"deleted":false}
after run 2  {"total":10000,"planned":10000,"plan_differs":null,"steps":[["billing",1360,1360],["order_confirmation",7960,7960],["billing",680,680]],"open_sum":10000}

zh-CN (accept-language: zh-CN, a second order): the same figures (8,640 then 7,960, Planned 10,000, plan_differs empty, open 10,000); a third run answered 400 截至 2026-11-23,没有尚未开票的已批准可计费工时或费用。 and changed nothing. The zh-CN label of the flag is 回款计划与订单金额不符.

Two-minute check: npx vitest run test/psa-prepare-billing-order-step.test.ts, which should show 19 passed.

Read first: src/psa/actions/billing.actions.ts (the reduction block after the count check), src/o2c/objects/billing_milestone.hook.ts (the give-back cap and compare-and-set), test/psa-prepare-billing-order-step.test.ts (the CONFLICT case).

Gates on head 91aa8d3: pnpm validate / typecheck / lint (os lint --strict) / hygiene exit 0; full suite as 8 shards exit 0 (745 / 848 / 847 / 870 / 832 / 957 / 773 / 1200 passed).

🤖 Generated with Claude Code

https://claude.ai/code/session_017xRBcUpajguxop2zMyDN9K

…step (#2934)

Ruling Q1 = B on #2933, variant B-1. Each Prepare Billing run, in its own
transaction, takes what it billed off the order's one clean generated step
(origin order_confirmation, nothing received on it, no invoice naming it)
and deletes it at zero, so the plan still adds up to the order and Payment
Plan Differs reads true only when the plan really differs. The write is a
compare-and-set on the amount read; a writer in between refuses the run
with CONFLICT and rolls it back.

Billing past the order's amount deletes the step and keeps the whole bill,
so the order shows Payment Plan Differs for the excess. A step with money
or an invoice against it, or an order with several generated steps, is
left as it is. A deleted billing step gives its amount back to the
generated step while it exists (billing_step_give_back), never past the
order's total, so rows billed again are not taken off twice.

Manuals (en, zh), the docs site and the plan replace the "tracked in
#2934" wording; a changeset.

Claude-Session: https://claude.ai/code/session_017xRBcUpajguxop2zMyDN9K
@vercel

vercel Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
hotcrm Ignored Ignored Dec 4, 2026 2:08am UTC

Request Review

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:hotcrm@sunhaolin · sunhaolin · session_017xRBcUpajguxop2zMyDN9K

CI on 6174e80 (2026-12-03T13:47Z): 18 checks green. Check Changeset run 47116555691 was cancelled, not failed: it was the only run, and it stopped at start. The PR carries .changeset/2934-billing-reduces-auto-step.md. The relay cannot re-run a cancelled changeset-check.yml run, and no empty push is allowed. The check re-runs with the next real push (review follow-ups); if none is needed, the maintainer can re-run it from the Actions tab before merging.

The independent review is pending: the reviewer is out of quota until 12-06 (UTC). The maintainer is choosing between waiting and a substitute reviewer.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:hotcrm@sunhaolin · sunhaolin · session_017xRBcUpajguxop2zMyDN9K

Independent read-only review · head 6174e80 · 2026-12-04T01:13Z · reviewer: Opus, substituting for Fable (Fable quota exhausted until 12-06; the maintainer chose 「#2938 选b」) · maintainer-class, stays draft

  1. 结论:有条件通过。
  2. 依据:开票扣减在本次运行的事务里、出账计数检查之后,按 id+读到金额的条件写入(multi:true);已在 19.0.0-next.3 objectql 源码核对,条件写入返回受影响行数,落空即 CONFLICT 整体回滚。10 个用例覆盖扣减、扣到零、超额、有回款、有发票、多条生成计划、并发冲突、合同项目、退还;与 e6/e7 和取消修剪流程最终结果不冲突。
  3. 风险:① 删除开票计划后的退还不在删除的事务里(平台先提交删除再触发 afterDelete),退还出错或三次条件写入都落空会静默放弃,自动计划永久少一笔、订单误报「不符」,只能人工改回;② 退还不记当初实际扣了多少,只靠「不超过订单总额」兜底,拆分过的订单单删不重开会偏差;③ 规则 11:hook 用 as unknown as 绕过 HookUpdateOptions,没在 _hook-api.ts 专门放开并登记;④ 文档说「开票超过订单金额」才删除,实际门槛是自动计划自身金额;⑤ 测试空白:退还用例被上限掩盖、没测到 hook 侧行数判断,未覆盖自动计划已删/已有回款时退还、三次重试、取消修剪、扣减后改总额;⑥ Check Changeset 为 cancelled,需重跑。
  4. 类别:维护者类(同意)——新增以系统身份运行的 afterDelete hook,开票会自动修改/删除订单回款计划。

待维护者裁决

  1. 老订单回填:A 不回填,变更说明提示销售手调;B 一次性脚本(分不清是否已手调,可能扣两次);C 流程重算(只在总额变化时触发)。Prepare Billing 12-02 才上线,受影响极少。建议 A。
  2. 自动计划已有回款/发票:A 不动;B 照扣但不低于已回款(退还也须对称)。建议本 PR 选 A,先记录每次实际扣减额后再考虑 B。
  3. 多条生成计划:只来自导入或 API。A 都不动;B 扣最新一条。建议 A。
  4. 扣减后订单总额变化:A 保持,靠「不符」提示;B 另开卡让 e6 按「总额 − 其他计划」重算——改逐笔加减为按结果推算,可根治风险①②,甚至可去掉退还 hook,下限不低于 0、不低于已回款。建议本 PR 选 A,同时开 B 卡,把「推算替代增减」写进卡里。

Seat: items ③–⑤ go back to the dev now. A push also re-runs ⑥. Risks ①② will be stated in the PR body; with Q4=B, the root fix goes to a follow-up card.

Evidence: billing.actions.ts:157-177; pin objectql index.js:26073, 26601, 36937-36960, 36999-37011; billing_milestone.hook.ts:57-69; _hook-api.ts:145-162; test/psa-prepare-billing-order-step.test.ts:184, 221-241; crm_psa_billing.md:80.

…2934)

Independent review of #2938 at 6174e80, items 3 to 5 and 1-2 wording:

- Rule 11: the give-back's compare-and-set is typed, not cast. The hook API
  declares HookCompareAndSetOptions (where names the id, multi: true; the
  measured answer is the row count) as an update overload, with its reason
  and its one rostered caller; no guard in test/ reads hook write options,
  so the two comments are the record.
- After three missed compare-and-sets the hook logs a warning through
  ctx.log (the build grants log to the lowered body, measured: api.read,
  api.write, log); HookLogContext types it.
- Docs, manuals and changeset: the generated step is deleted when a run
  bills more than it still holds, which on a split plan comes before the
  order's total. The changeset states that the give-back runs after the
  delete commits, gives up after three misses, and does not record what
  each run took, relying on the Total Price cap.
- Tests with exact figures: give-back on a split plan (5,700 back to 6,000,
  the cap not reached); generated step already deleted; generated step
  with money received; two misses then 9,500 + 300 = 9,800; three misses
  leave 9,400 and the shipped body logs one warning; total raised after a
  reduction; cancelled with and without money on the billing step.
  runShippedHook takes an optional host logger.

Claude-Session: https://claude.ai/code/session_017xRBcUpajguxop2zMyDN9K
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:hotcrm@sunhaolin · sunhaolin · session_017xRBcUpajguxop2zMyDN9K

Head update: 91aa8d3, review items fixed, CI all green (2026-12-04T02:20Z)

  • ③ The as unknown as cast is gone. _hook-api.ts declares HookCompareAndSetOptions (returns the row count) and HookLogContext, each with its reason, measurement and callers.
  • ④ The deletion threshold now reads "more than the generated step still holds" in every manual, docs page, comment and the changeset.
  • ①② The PR body and changeset now state the after-commit give-back, the three-attempt limit and the reliance on the Total Price cap. An exhausted retry now logs a warning (ctx.log.warn) instead of returning silently.
  • ⑤ The test file has 19 cases (was 10), with new ones for: split plan, generated step already deleted, money received, 2 and 3 misses with the shipped-body warning, cancel-trim, and a total change after a reduction. Ablations: removing the cap turns 2 cases red; removing the row-count check turns 3 red.
  • ⑥ Check Changeset re-ran with the push. All 20 checks on 91aa8d3 finished green, and the PR is mergeable. The full suite passed locally in 8 shards.

Stays draft for the maintainer's merge; the 4 rulings above are pending.

@objectstack-fleet objectstack-fleet Bot added the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Dec 4, 2026
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:hotcrm@sunhaolin · sunhaolin · session_017xRBcUpajguxop2zMyDN9K

Maintainer's rulings and merge word in chat, verbatim: 「2938 你帮我合并。4 个问题:1A 2A 3A 4A+开卡」 · recorded 2026-12-04T08:55Z

All 22 checks on 91aa8d3 are green and the PR is mergeable. On the maintainer's word: readying and queueing for merge.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review December 4, 2026 08:56
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Dec 4, 2026
Merged via the queue into main with commit 3377e24 Dec 4, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Order to Cash: Prepare Billing reduces the order's automatic full-amount payment plan step, so Payment Plan Differs stays truthful

2 participants