Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/30184-requiredwhen-transition-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/core': patch
'@object-ui/components': patch
---

fix(ui): the record Edit form judges a field's `requiredWhen` as the engine does, a transition gate against the stored record, so a record already inside the gate without the value saves an unrelated edit

Clause-②: yes (widening)
Metadata-protocol: none

This widens the public surface of `@object-ui/core`: the new export `requiredWhenRestsOnStoredRecord` and the new `requiredWhenAtRest` field in the return type of `resolveFieldRuleState`.

- **`@object-ui/components` form renderer:** on an Edit form (`previousValues` set), a field's `requiredWhen` is required only when the stored record complied with it. A stored record that already violates it (the predicate holds over the stored record and its value is missing, as with a contract activated before its signed-copy rule existed) is not blocked any more: it saves an edit that leaves the field empty, as the engine and REST `PATCH` already accept. This follows `Field.requiredWhen`: the write is refused only when the merged record violates the requirement AND the pre-write record complied. Still refused: the edit that moves a record into the gate without the value, and clearing the value of a record that held it. A Create form enforces as before. The "Required to run" note under an empty field (the update-action heads-up) is no longer shown for such a stored record, because the engine judges the action's write against the same stored record.
- **`@object-ui/core`:** `resolveFieldRuleState` takes `statics.name` (the field's name) and returns `requiredWhenAtRest`. With `previous` and `statics.name` given, a stored record already violating `requiredWhen` resolves `required: false` and `requiredWhenAtRest: true`. A caller that passes no `name` keeps the plain verdict. New export `requiredWhenRestsOnStoredRecord(pred, name, stored, scope?)`, the stored-record check alone. A predicate that cannot be evaluated over the stored record counts it as compliant, as on the server.
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,25 @@ describe('form renderer — fields an update action would require (objectstack#2
expect(noteOnIssuedOn()).toBeNull();
});

it('notes nothing when the stored row already lacks the value inside the gate (objectstack#30184)', async () => {
// A paid invoice from before the rule: `issued_on` is missing while the
// rule already holds. The engine judges every write, an action's included,
// against that stored row, under which the field rests, so neither Save
// nor the action is refused for it, and the form says neither.
const onSubmit = vi.fn();
const { getObjectSchema } = renderInvoiceForm({
record: { ...DRAFT, status: 'paid' },
onSubmit,
});
await waitFor(() => expect(getObjectSchema).toHaveBeenCalled());
await new Promise((r) => setTimeout(r, 20));
expect(noteOnIssuedOn()).toBeNull();
expect(issuedOnInput().getAttribute('aria-required')).toBeNull();

fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
});

it('names every action that would require the field, one line each', async () => {
renderInvoiceForm({
actions: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,70 @@ describe('form renderer — `requiredWhen` at SUBMIT time (objectui#4161)', () =
expect(screen.queryByText(/is required/i)).toBeNull();
});
});

/**
* objectstack#30184 — on an EDIT form `requiredWhen` is a TRANSITION GATE, as
* the engine judges it (`Field.requiredWhen`: refused only when the merged
* record violates the rule AND the stored row complied). The reported case: a
* contract activated before its signed-copy rule existed must still save an
* unrelated edit, while activating a contract without the copy stays refused.
*/
describe('form renderer — `requiredWhen` judged against the stored row on EDIT (objectstack#30184)', () => {
const CONTRACT_FIELDS = [
{ name: 'status', label: 'Status', type: 'input' },
{ name: 'end_date', label: 'End Date', type: 'input' },
{ name: 'signed_copy', label: 'Signed Copy', type: 'input', requiredWhen: "record.status == 'activated'" },
];
const signedCopy = () => screen.getByLabelText(/signed copy/i);

it('saves an unrelated edit to a record already in the gate without the value', async () => {
const stored = { status: 'activated', end_date: '2026-12-31', signed_copy: null };
const onSubmit = vi.fn().mockResolvedValue(undefined);
renderForm(CONTRACT_FIELDS, stored, onSubmit, { previousValues: stored });

expect(signedCopy()).not.toHaveAttribute('aria-required');
fireEvent.change(screen.getByLabelText(/end date/i), { target: { value: '2027-06-30' } });
submit();

await waitFor(() => expect(onSubmit).toHaveBeenCalled());
expect(onSubmit.mock.calls[0][0]).toMatchObject({ status: 'activated', end_date: '2027-06-30' });
expect(screen.queryByText(/is required/i)).toBeNull();
});

it('still refuses the edit that moves a record INTO the gate without the value', async () => {
const stored = { status: 'draft', end_date: '2026-12-31', signed_copy: null };
const onSubmit = vi.fn().mockResolvedValue(undefined);
renderForm(CONTRACT_FIELDS, stored, onSubmit, { previousValues: stored });

fireEvent.change(screen.getByLabelText(/status/i), { target: { value: 'activated' } });
await waitFor(() => expect(signedCopy()).toHaveAttribute('aria-required', 'true'));
submit();

await waitFor(() => expect(screen.getByText(/signed copy is required/i)).toBeInTheDocument());
expect(onSubmit).not.toHaveBeenCalled();
});

it('still refuses clearing the value of a record that held it', async () => {
const stored = { status: 'activated', end_date: '2026-12-31', signed_copy: 'copy.pdf' };
const onSubmit = vi.fn().mockResolvedValue(undefined);
renderForm(CONTRACT_FIELDS, stored, onSubmit, { previousValues: stored });

expect(signedCopy()).toHaveAttribute('aria-required', 'true');
fireEvent.change(signedCopy(), { target: { value: '' } });
submit();

await waitFor(() => expect(screen.getByText(/signed copy is required/i)).toBeInTheDocument());
expect(onSubmit).not.toHaveBeenCalled();
});

it('still enforces on a CREATE form (no stored row)', async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
renderForm(CONTRACT_FIELDS, { status: 'activated', end_date: '', signed_copy: '' }, onSubmit);

expect(signedCopy()).toHaveAttribute('aria-required', 'true');
submit();

await waitFor(() => expect(screen.getByText(/signed copy is required/i)).toBeInTheDocument());
expect(onSubmit).not.toHaveBeenCalled();
});
});
12 changes: 11 additions & 1 deletion ui/packages/components/src/renderers/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2298,6 +2298,8 @@ ComponentRegistry.register('form',
required: !!f.required,
readonly: (f as any).readonly === true,
serverOwnedValue: isServerOwnedValue(f, isCreateForm),
// The render path's required verdict, so the cleanup agrees with it.
name,
},
previousRecord,
predicateScope,
Expand Down Expand Up @@ -3460,6 +3462,10 @@ ComponentRegistry.register('form',
// live record, which used to re-require it here with nothing the user
// could type to unblock the submit (#4085).
serverOwnedValue: serverOwned,
// On an EDIT form `requiredWhen` is judged as the engine judges it, a
// transition gate against the stored row (`previousRecord`): a row
// already missing the value rests under the rule (objectstack#30184).
name,
},
previousRecord,
// The host shell's predicate scope — `current_user` and friends (#6010).
Expand Down Expand Up @@ -4062,9 +4068,13 @@ ComponentRegistry.register('form',
// action leaves (`actionOutcomes`). Not while it is required
// already (the asterisk says so), nor on a control the person
// cannot fill. Faults answer `false` and stay quiet: the live
// evaluation above already reported a broken rule.
// evaluation above already reported a broken rule. Nor when the
// stored row already violates the rule: an action's write is
// judged against that same stored row, and it rests under the
// rule whatever the patch writes (objectstack#30184).
requiredWhen != null &&
!required &&
!ruleState.requiredWhenAtRest &&
!readonly &&
!fieldDisabled &&
actionOutcomes.length > 0 &&
Expand Down
64 changes: 63 additions & 1 deletion ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ExpressionEngine } from '@objectstack/formula';
import { evalFieldPredicate, resolveFieldRuleState } from '../fieldRules';
import { evalFieldPredicate, requiredWhenRestsOnStoredRecord, resolveFieldRuleState } from '../fieldRules';

/** Run `fn` with `console.warn` muted (the loud fail-open of #5149 is pinned
* in its own describe below; these legacy value-contract tests only care about
Expand Down Expand Up @@ -413,6 +413,7 @@ describe('fault directions — what a BROKEN rule decides (objectui#8069)', () =
readonlyWhen: expect.any(String),
requiredWhen: expect.any(String),
},
requiredWhenAtRest: false,
});
});
});
Expand Down Expand Up @@ -555,3 +556,64 @@ describe('blank predicate — declared but empty (objectui#8069)', () => {
expect(msg).toContain('[blank]');
});
});

/**
* objectstack#30184 — `requiredWhen` is a TRANSITION GATE on an update, judged
* the way objectql's `evaluateValidationRules` judges it: refused only when the
* merged record violates the rule AND the stored row complied.
*/
describe('resolveFieldRuleState — `requiredWhen` as a transition gate (objectstack#30184)', () => {
const RULE = { requiredWhen: "record.status == 'activated'" };
const LEGACY = { status: 'activated', end_date: '2026-12-31', signed_copy: null };

it('an already-activated stored row with no value rests: not required, at rest', () => {
const st = resolveFieldRuleState(RULE, { ...LEGACY, end_date: '2027-01-31' }, { name: 'signed_copy' }, LEGACY);
expect(st.required).toBe(false);
expect(st.requiredWhenAtRest).toBe(true);
});

it('the write that moves a stored row INTO the gate is still required', () => {
const stored = { status: 'draft', signed_copy: null };
const st = resolveFieldRuleState(RULE, { ...stored, status: 'activated' }, { name: 'signed_copy' }, stored);
expect(st.required).toBe(true);
expect(st.requiredWhenAtRest).toBe(false);
});

it('a stored row that complied stays required, so clearing its value is refused', () => {
const stored = { status: 'activated', signed_copy: 'copy.pdf' };
const st = resolveFieldRuleState(RULE, { ...stored, signed_copy: null }, { name: 'signed_copy' }, stored);
expect(st.required).toBe(true);
expect(st.requiredWhenAtRest).toBe(false);
});

it('an insert (no stored row) is required whenever the predicate holds', () => {
const st = resolveFieldRuleState(RULE, { status: 'activated', signed_copy: null }, { name: 'signed_copy' });
expect(st.required).toBe(true);
expect(st.requiredWhenAtRest).toBe(false);
});

it('without `statics.name` the plain verdict is kept', () => {
const st = resolveFieldRuleState(RULE, LEGACY, {}, LEGACY);
expect(st.required).toBe(true);
expect(st.requiredWhenAtRest).toBe(false);
});

it('a static `required: true` is never relaxed by the stored row', () => {
const st = resolveFieldRuleState(RULE, LEGACY, { required: true, name: 'signed_copy' }, LEGACY);
expect(st.required).toBe(true);
});

it('a predicate that cannot be evaluated over the stored row treats it as COMPLIANT', () => {
// A field selection on a string faults, so no violation is proven and
// the rule keeps enforcing, as the engine does.
const pred = "record.status == 'activated' && record.flag.x == 1";
expect(muted(() => requiredWhenRestsOnStoredRecord(pred, 'signed_copy', { status: 'activated', flag: 'not-a-map', signed_copy: null }))).toBe(false);
expect(requiredWhenRestsOnStoredRecord("record.status == 'activated'", 'signed_copy', undefined)).toBe(false);
});

it('a stored value that is present is not at rest', () => {
expect(
requiredWhenRestsOnStoredRecord("record.status == 'activated'", 'signed_copy', { status: 'activated', signed_copy: 'copy.pdf' }),
).toBe(false);
});
});
95 changes: 81 additions & 14 deletions ui/packages/core/src/evaluator/fieldRules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ import type { Expression } from '@objectstack/spec';

import { isBlankPredicateText } from './declaredPredicate.js';
import { isUnevaluablePredicate, UNEVALUABLE_PREDICATE_REASON } from './unevaluablePredicate.js';
import { isMissingForRequired } from '../validation/required-presence.js';

/** A field-rule predicate as authored in metadata. */
export type FieldRulePredicate = string | { dialect?: string; source: string };
Expand Down Expand Up @@ -430,12 +431,32 @@ export interface FieldRuleFaults {
* unblock it. See `isServerOwnedValue` in `../validation/server-owned-value.js`
* for who computes the fact and why the mode is the caller's to state.
*
* ## `requiredWhen` is a TRANSITION GATE on an update, as the engine judges it
*
* `@objectstack/spec` `Field.requiredWhen`: "the write is refused only when the
* merged record violates the requirement AND the pre-write record complied"
* (ADR-0113 non-regression). objectql's `evaluateValidationRules` implements
* exactly that, and it is the contract this client side is bound to. So on an
* UPDATE — `previous` given, and `statics.name` saying which of its columns is
* this field's stored value — a stored row that ALREADY violates the rule (the
* predicate holds over it and its value is missing) is at rest: no write that
* leaves the field empty is refused by this rule, so `required` is `false` and
* `requiredWhenAtRest` is `true`. See {@link requiredWhenRestsOnStoredRecord}.
*
* A row that complied is judged as before, so the write that moves it INTO the
* gate and the write that clears a stored value are both still required. An
* INSERT has no `previous` and complies vacuously, as on the server. A caller
* that passes no `statics.name` keeps the plain verdict.
*
* @param fieldContext Optional locator for failure warnings — e.g.
* `"field 'amount'"`. The warning then reads
* `visibleWhen of field 'amount' …`; without it, the rule
* kind alone is reported.
* @returns The three verdicts, plus `faults` — see {@link FieldRuleFaults} for
* what a submit path reads from it and what it leaves out.
* what a submit path reads from it and what it leaves out — and
* `requiredWhenAtRest`, true when the stored row already violates
* `requiredWhen` (see above), for a caller that judges another write
* against the same stored row.
*/
export function resolveFieldRuleState(
rules: {
Expand All @@ -444,11 +465,17 @@ export function resolveFieldRuleState(
requiredWhen?: FieldRulePredicate;
},
record: Record<string, unknown>,
statics: { required?: boolean; readonly?: boolean; serverOwnedValue?: boolean },
statics: { required?: boolean; readonly?: boolean; serverOwnedValue?: boolean; name?: string },
previous?: Record<string, unknown>,
scope?: Record<string, unknown>,
fieldContext?: string,
): { visible: boolean; readonly: boolean; required: boolean; faults: FieldRuleFaults } {
): {
visible: boolean;
readonly: boolean;
required: boolean;
faults: FieldRuleFaults;
requiredWhenAtRest: boolean;
} {
const faults: FieldRuleFaults = {};
// `onFault` fires beside the built-in warning, not instead of it (`warn`
// stays on), so recording the report costs no diagnostic and no second
Expand Down Expand Up @@ -490,20 +517,60 @@ export function resolveFieldRuleState(
// render. A broken `requiredWhen` still warns wherever it decides something
// — the same object's EDIT form, and any create form where the field is not
// server-owned.
const requiredByRule =
statics.serverOwnedValue !== true &&
statics.required !== true &&
rules.requiredWhen != null &&
evalFieldPredicate(
rules.requiredWhen,
record,
REQUIRED_WHEN_FAULTED,
previous,
scope,
diag('requiredWhen'),
);
// Asked only when the rule would require the field: the stored row's verdict
// can only relax a TRUE one (the transition-gate section above).
const requiredWhenAtRest =
requiredByRule &&
statics.name !== undefined &&
requiredWhenRestsOnStoredRecord(rules.requiredWhen, statics.name, previous, scope);
const required =
statics.serverOwnedValue === true
? false
: statics.required === true ||
(rules.requiredWhen != null
? evalFieldPredicate(
rules.requiredWhen,
record,
REQUIRED_WHEN_FAULTED,
previous,
scope,
diag('requiredWhen'),
)
: REQUIRED_WHEN_ABSENT);
(rules.requiredWhen != null ? requiredByRule && !requiredWhenAtRest : REQUIRED_WHEN_ABSENT);

return { visible, readonly, required, faults };
return { visible, readonly, required, faults, requiredWhenAtRest };
}

/**
* Does the STORED row already violate this field's `requiredWhen` — the
* predicate holds over it and the field's stored value is missing?
*
* The pre-state half of the engine's transition gate (objectql
* `evaluateValidationRules`, ADR-0113 non-regression): a write is refused only
* when the merged record violates the rule and the stored row complied, so a
* row this answers `true` for rests under the rule whatever the write leaves
* in the field. Judged over the stored row alone, bound as both `record` and
* `previous`, as the engine binds it.
*
* `false` without a stored row (an insert complies vacuously) and `false` when
* the predicate cannot be evaluated over it: the engine then treats the stored
* row as COMPLIANT, so enforcement stays on unless a violation is proven. The
* fault is not reported here; the live evaluation of the same rule reports it.
*
* "Missing" is {@link isMissingForRequired}, the same answer the client's
* required check gives, so a value this calls present is never one that check
* would refuse.
*/
export function requiredWhenRestsOnStoredRecord(
pred: FieldRulePredicate | undefined | null,
name: string,
stored: Record<string, unknown> | undefined,
scope?: Record<string, unknown>,
): boolean {
if (pred == null || stored == null) return false;
if (!isMissingForRequired(stored[name])) return false;
return evalFieldPredicate(pred, stored, false, stored, scope, { warn: false });
}
Loading