Skip to content

Commit 1aac465

Browse files
fix(plugin-form): judge the wizard final-submit gate on computed formula values (#35348)
Fixes #35189 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:向导表单(以及简单表单的移动端分步模式)最终提交前的必填检查,现在先按对象的公式字段重新计算记录,再判断字段的 `visibleWhen`,与普通表单的做法一致。 - 为什么改:之前用的是上次读取时的旧公式值。改动让字段移出条件后,向导仍要求填写服务端并不要求的字段;移入条件后,又放过了服务端会拒收的提交。 - 风险与回滚:只改了 `WizardForm.tsx` 的最终提交检查,不改 spec、服务端和 i18n。回滚就是 revert 这个 PR。 - 先看:`ui/packages/plugin-form/src/WizardForm.tsx`(`gateFinalSubmit` 中的 `ruleRecord` 与 `formulaPlan`)、`ui/packages/plugin-form/src/__tests__/wizardFormulaGate-35189.test.tsx`、`.changeset/35189-wizard-gate-formula.md`。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/plugin-form/src/__tests__/wizardFormulaGate-35189.test.tsx`,预期 5 passed;把 `WizardForm.tsx` 换回 main 的版本后再跑,预期 3 failed / 2 passed。 - 需要你做的:无,席位落地。 ## What changes - `WizardForm` plans the object's `formula` fields once, from the object schema it already reads (`planObjectFormulas` from `@object-ui/core`, for the acting user of the predicate scope). No second schema read and no new export. - `gateFinalSubmit` judges `resolveFieldRuleState` and the view-level `visibleOn` on `formulaPlan.compute(record)`: the value a read of the written record would serve, as `form.tsx` and `FormPage.tsx` do (ADR-0113, formula paragraph). Emptiness is still read off the written record. - A `visibleWhen` that reads a formula the form cannot compute (`plan.unservableReadsOf`) is dropped in the gate, the same way the step form's `withoutUnservableVisibleWhen` drops it. The field counts as shown, keeps `required` and raises no fault. - Unchanged, as dispatched: if there is no `getObjectSchema`, or the schema read fails, there is no plan, and the gate judges the record as it holds it. ## Tests New `wizardFormulaGate-35189.test.tsx`: an edit wizard with a required field on a skipped step, whose `visibleWhen` reads a formula. - An edit moves the formula out of the condition: the save goes through. - An edit moves the formula into the condition: the save is refused, and the wizard marks and opens the step that holds the field. - The `visibleWhen` reads an unservable formula (through a lookup): the field counts as shown and required, so the save is refused. - Two controls read the same condition straight off a stored column. They pass before and after the fix. <details><summary>Red on main, green with the fix</summary> - Fix applied: `VERDICT command-exit 0`, Tests 5 passed (5). - `WizardForm.tsx` taken from main (planObjectFormulas count 0): `VERDICT command-exit 1`, Tests 3 failed / 2 passed (5). The three formula legs are red and both controls are green. The fixed file was restored with a matching blob hash. </details> <details><summary>Package suite and type-check (tree f2cc860)</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-form/`: `VERDICT command-exit 0`, Test Files 238 passed (238), Tests 2678 passed / 1 skipped. - `pnpm --filter @object-ui/plugin-form type-check`: `VERDICT command-exit 0`. The test program lists the new test file. </details> ## Acceptance notes - Explicit data-source prop with no renderer context (not filed, reach not measured). The step form plans its formulas from the `SchemaRendererProvider` context only (`useObjectFormulaPlan` in `form.tsx`), but `WizardForm` also accepts an explicit `dataSource` prop. A host that passes only the prop now gets a final gate that computes formulas and a step form that judges the stale value. After an edit that moves a required field into its condition, the gate refuses and opens a step whose form hides the field. Before this PR, the server refused that save with a 400 that named the same hidden field. Hosts that mount the renderer context (the Console) do not hit this. I did not reproduce it through a public entry point. - The residual where a missing or failed schema read gives no plan is unchanged. ## Verification <details><summary>Derived gate families (dispatch-gates, 3 paths)</summary> - 38 derived commands. 37 exited 0 on the first pass. `pnpm --dir ui exec vitest run scripts/` was killed by the container's out-of-memory killer and was re-run under the verify lock with two workers: `VERDICT command-exit 0`, 171 files passed / 2 skipped. - `--ran` reconciliation: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` (merges cleanly with origin/main e4bfa33, 0 PR heads overlap). - Every other family is left to this PR's CI check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CajiB6BSQKWowy6YLB)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8f49499 commit 1aac465

3 files changed

Lines changed: 215 additions & 4 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
---
4+
5+
fix(plugin-form): the wizard's final-submit gate judges a `visibleWhen` that reads a formula on the computed value
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`WizardForm` re-checks every declared field when it submits, including the fields on steps the user skipped. The simple form's mobile stepper submits through the same check. That check now computes the object's `formula` fields over the record being written before it judges field rules, the same way the form renderer does (`planObjectFormulas`, ADR-0113). Before, it used the formula value from the last read. So after an edit that moved a required field out of its `visibleWhen`, the wizard still demanded the field even though the server does not require it. After an edit that moved the field into its `visibleWhen`, the wizard sent the save without the field and the server refused it.
11+
12+
The `visibleWhen` of a field that reads a formula the form cannot compute is handled as the step forms handle it: the field counts as shown and keeps its `required` flag. The plan is built from the object schema the wizard already reads. When that read fails, or no data source is given, the gate judges the record as it holds it, as before.

‎ui/packages/plugin-form/src/WizardForm.tsx‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
evalFieldPredicate,
2323
isMissingForRequired,
2424
isServerOwnedValue,
25+
planObjectFormulas,
2526
requiredWhenRestsOnStoredRecord,
2627
} from '@object-ui/core';
2728
import { createSafeTranslation, useLocalization } from '@object-ui/i18n';
@@ -800,6 +801,20 @@ export const WizardForm: React.FC<WizardFormProps> = ({
800801
*/
801802
const predicateScope = usePredicateScope();
802803

804+
/**
805+
* The object's `formula` fields, planned from the schema this wizard already
806+
* read, for the acting user of the predicate scope (ADR-0113, formula
807+
* paragraph). The final gate judges field rules on `plan.compute(record)`,
808+
* the value a read of the written record would serve, as the form renderer
809+
* does (`objectFormulas.ts`): never on the formula value last read.
810+
* `undefined` when the object declares no formula, or its schema read
811+
* failed or was never made, and the gate then judges the record as held.
812+
*/
813+
const formulaPlan = useMemo(
814+
() => planObjectFormulas(objectSchema?.fields, predicateScope),
815+
[objectSchema, predicateScope],
816+
);
817+
803818
// Current section fields
804819
const currentSectionFields = useMemo(() => {
805820
if (currentStep >= 0 && currentStep < totalSteps) {
@@ -868,17 +883,28 @@ export const WizardForm: React.FC<WizardFormProps> = ({
868883
): { missing: Map<number, string[]>; faultedVisibleWhen: Map<number, string[]> } => {
869884
const out = new Map<number, string[]>();
870885
const faultedVisibleWhen = new Map<number, string[]>();
886+
// The record the rules are judged on: the object's formulas computed over
887+
// it (see `formulaPlan`). Emptiness is still read off `record`, the values
888+
// that are written.
889+
const ruleRecord = formulaPlan ? formulaPlan.compute(record) : record;
871890
schema.sections.forEach((section, index) => {
872891
for (const field of buildSectionFields(section)) {
873892
const name = field?.name;
874893
if (!name || (field as any).hidden === true) continue;
894+
// A `visibleWhen` reading a formula the form cannot compute is dropped,
895+
// as the step form that draws the field drops it: shown, keeping its
896+
// `required`, and no fault (`withoutUnservableVisibleWhen`).
897+
const visibleWhen =
898+
formulaPlan && formulaPlan.unservableReadsOf((field as any).visibleWhen).length > 0
899+
? undefined
900+
: (field as any).visibleWhen;
875901
const state = resolveFieldRuleState(
876902
{
877-
visibleWhen: (field as any).visibleWhen,
903+
visibleWhen,
878904
readonlyWhen: (field as any).readonlyWhen,
879905
requiredWhen: (field as any).requiredWhen,
880906
},
881-
record,
907+
ruleRecord,
882908
{
883909
required: !!field.required,
884910
readonly: (field as any).readonly === true,
@@ -913,7 +939,7 @@ export const WizardForm: React.FC<WizardFormProps> = ({
913939
// receives the ADR-0089 canonical view-level `visibleWhen` spelling.
914940
const viewVisible =
915941
(field as any).visibleOn == null ||
916-
evalFieldPredicate((field as any).visibleOn, record, true, undefined, predicateScope, {
942+
evalFieldPredicate((field as any).visibleOn, ruleRecord, true, undefined, predicateScope, {
917943
context: `visibleOn of field '${name}'`,
918944
});
919945
// A hidden or read-only field is not the user's to fill in.
@@ -938,7 +964,7 @@ export const WizardForm: React.FC<WizardFormProps> = ({
938964
});
939965
return { missing: out, faultedVisibleWhen };
940966
},
941-
[schema.sections, buildSectionFields, isCreateWizard, isEditWizard, persistedRecord, predicateScope],
967+
[schema.sections, buildSectionFields, isCreateWizard, isEditWizard, persistedRecord, predicateScope, formulaPlan],
942968
);
943969

944970
// Handle step data collection (merge partial data into formData)
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#35189 — `WizardForm`'s final-submit gate (`gateFinalSubmit`)
11+
* judges a `visibleWhen` that reads a `formula` field on the value the written
12+
* record would serve, as the form renderer does since objectstack#35033
13+
* (`planObjectFormulas`, ADR-0113's formula paragraph).
14+
*
15+
* The gate re-checks every declared field at the final submit, including the
16+
* ones on a step the user skipped and never mounted. It judged them on the
17+
* record as last read, so a formula's stale stored value decided whether a
18+
* required field was demanded: after an edit that moved the formula out of
19+
* the field's condition the gate demanded a field the server does not require,
20+
* and after an edit that moved it in the gate let the save go without a field
21+
* the server does require. The same gate serves a simple form's mobile stepper.
22+
*
23+
* Every case edits step 1, skips straight past the step holding the gated
24+
* field, and presses Update, so only the cross-step gate has an opinion. The
25+
* observable is whether `dataSource.update` was called. The CONTROL cases read
26+
* the same condition straight off a stored column, with no formula in between:
27+
* they pass before and after the fix.
28+
*/
29+
30+
import React from 'react';
31+
import { describe, it, expect, vi, afterEach } from 'vitest';
32+
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
33+
import { registerAllFields } from '@object-ui/fields';
34+
import { SchemaRendererProvider } from '@object-ui/react';
35+
import { WizardForm } from '../WizardForm';
36+
37+
registerAllFields();
38+
39+
afterEach(() => {
40+
cleanup();
41+
vi.restoreAllMocks();
42+
});
43+
44+
/** The ticket object: `escalated` is a formula over `status`. */
45+
function ticketSchema(reasonVisibleWhen: string) {
46+
return {
47+
name: 'ticket',
48+
fields: {
49+
subject: { type: 'text', label: 'Subject' },
50+
status: { type: 'text', label: 'Status' },
51+
account: { type: 'lookup', label: 'Account', reference: 'account' },
52+
escalated: { type: 'formula', label: 'Escalated', expression: "record.status == 'escalated'" },
53+
// Unservable on the form: it reads through a reference.
54+
vip: { type: 'formula', label: 'VIP', expression: "record.account.tier == 'gold'" },
55+
escalation_reason: {
56+
type: 'text',
57+
label: 'Escalation Reason',
58+
required: true,
59+
visibleWhen: reasonVisibleWhen,
60+
},
61+
notes: { type: 'text', label: 'Notes' },
62+
},
63+
};
64+
}
65+
66+
const fill = (name: string, value: string) => {
67+
const input = document.body.querySelector<HTMLInputElement>(`[data-field="${name}"] input`);
68+
if (!input) throw new Error(`field not rendered: ${name}`);
69+
fireEvent.change(input, { target: { value } });
70+
};
71+
72+
const stepIndicator = (index: number) =>
73+
document.body.querySelectorAll<HTMLButtonElement>('nav[aria-label="Progress"] button')[index];
74+
75+
function editWizard(reasonVisibleWhen: string, stored: Record<string, unknown>) {
76+
const dataSource = {
77+
getObjectSchema: vi.fn().mockResolvedValue(ticketSchema(reasonVisibleWhen)),
78+
findOne: vi.fn().mockResolvedValue({ id: 't1', subject: 'Outage', notes: '', escalation_reason: null, ...stored }),
79+
create: vi.fn(),
80+
update: vi.fn(async (_o: string, _id: string, d: any) => ({ id: 't1', ...stored, ...d })),
81+
};
82+
// Mounted as a host mounts it: the data source in the renderer context too,
83+
// so the step forms compute the same formulas the final gate does.
84+
render(
85+
<SchemaRendererProvider dataSource={dataSource as any}>
86+
<WizardForm
87+
schema={{
88+
type: 'object-form',
89+
formType: 'wizard',
90+
objectName: 'ticket',
91+
mode: 'edit',
92+
recordId: 't1',
93+
allowSkip: true,
94+
sections: [
95+
{ name: 's1', label: 'Step 1', fields: ['subject', 'status'] },
96+
{ name: 's2', label: 'Step 2', fields: ['escalation_reason'] },
97+
{ name: 's3', label: 'Step 3', fields: ['notes'] },
98+
],
99+
} as any}
100+
dataSource={dataSource as any}
101+
/>
102+
</SchemaRendererProvider>,
103+
);
104+
return dataSource;
105+
}
106+
107+
/** Edit step 1 as asked, jump past step 2 to step 3, and press Update. */
108+
async function editAndSubmit(step1: Record<string, string>) {
109+
await waitFor(() => {
110+
const el = document.body.querySelector<HTMLInputElement>('[data-field="subject"] input');
111+
if (!el || el.value !== 'Outage') throw new Error('record not on screen yet');
112+
});
113+
for (const [name, value] of Object.entries(step1)) fill(name, value);
114+
fireEvent.click(stepIndicator(2));
115+
await waitFor(() => expect(document.body.querySelector('[data-field="notes"]')).toBeTruthy());
116+
fill('notes', 'followed up');
117+
expect(document.body.querySelector('[data-field="escalation_reason"]')).toBeNull();
118+
fireEvent.click(screen.getByRole('button', { name: /Update/i }));
119+
}
120+
121+
async function expectSaved(dataSource: { update: ReturnType<typeof vi.fn> }) {
122+
await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1));
123+
}
124+
125+
/**
126+
* Refused: the gate marks the step holding the field, the wizard lands there
127+
* and draws the field, and nothing is sent.
128+
*/
129+
async function expectRefused(dataSource: { update: ReturnType<typeof vi.fn> }) {
130+
await waitFor(() =>
131+
expect(document.body.querySelector('[data-testid="wizard-step:s2"]')?.getAttribute('data-error')).toBe('true'),
132+
);
133+
await waitFor(() => expect(document.body.querySelector('[data-field="escalation_reason"]')).toBeTruthy());
134+
expect(dataSource.update).not.toHaveBeenCalled();
135+
}
136+
137+
const BY_FORMULA = 'record.escalated == true';
138+
const BY_COLUMN = "record.status == 'escalated'";
139+
140+
describe('WizardForm final gate — a visibleWhen reading a formula is judged on the computed value (objectstack#35189)', () => {
141+
it('an edit that moves the formula OUT of the condition saves without the hidden required field', async () => {
142+
const dataSource = editWizard(BY_FORMULA, { status: 'escalated', escalated: true });
143+
await editAndSubmit({ status: 'open' });
144+
await expectSaved(dataSource);
145+
expect(dataSource.update.mock.calls[0][2]).toMatchObject({ status: 'open', notes: 'followed up' });
146+
});
147+
148+
it('an edit that moves the formula INTO the condition demands the required field', async () => {
149+
const dataSource = editWizard(BY_FORMULA, { status: 'open', escalated: false });
150+
await editAndSubmit({ status: 'escalated' });
151+
await expectRefused(dataSource);
152+
});
153+
154+
it('a visibleWhen reading a formula the form cannot compute keeps the field shown and required, as the step form draws it', async () => {
155+
const dataSource = editWizard('record.vip == true', { status: 'open', vip: false, account: 'a1' });
156+
await editAndSubmit({ status: 'pending' });
157+
await expectRefused(dataSource);
158+
});
159+
});
160+
161+
describe('#35189 CONTROLS — no formula in between: these pass before and after the fix', () => {
162+
it('a stored column moved out of the condition saves', async () => {
163+
const dataSource = editWizard(BY_COLUMN, { status: 'escalated', escalated: true });
164+
await editAndSubmit({ status: 'open' });
165+
await expectSaved(dataSource);
166+
});
167+
168+
it('a stored column moved into the condition is refused', async () => {
169+
const dataSource = editWizard(BY_COLUMN, { status: 'open', escalated: false });
170+
await editAndSubmit({ status: 'escalated' });
171+
await expectRefused(dataSource);
172+
});
173+
});

0 commit comments

Comments
 (0)