File size: 15,373 Bytes
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
e14c2fd
1f123e1
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
1f123e1
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// ---------------------------------------------------------------------------
// settings / DatabasePermsPane.tsx β€” ONE DATABASE'S RULE, given the whole pane.
// (wave 40, owner instruction 7 Β· W40-T14.)
//
// ⭐ WHY IT EXISTS, IN THE OWNER'S OWN WORDS: *"Manage user, Access section: show
// only the Database, with just a checkbox and an Edit button (put the Metrics
// field toggle under there). Edit opens the whole database's Fields and Filters
// to toggle, with a Back button to return."*
//
// ⚠ THE PARENTHESIS IN THAT QUOTE IS SUPERSEDED, AND ONLY THE PARENTHESIS. Owner instruction 13
// (W40-T16) folded the Metrics toggle one level further in: it is no longer a box "under there"
// but one CHECKBOX PER METRIC inside this pane's Hide-fields list. The room, the Back button and
// the Fields/Filters pairing are instruction 7's and are unchanged. Read the quote as the reason
// this file exists, never as a description of the controls it draws today.
//
// What it replaces is a single-row INLINE ACCORDION. That shape was right when
// the list was two databases and the panels were the only thing under them; it
// is wrong now, because a filter builder and a field list opened inside a row of
// a list of every database the tenant has are two menus that failed to close.
// A rule about one database gets a room, and the room says which database.
//
// β›” IT OWNS NO STATE AND WRITES NOTHING. Every value comes from the caller's
// DRAFT and every change goes back out as a callback, exactly as
// `ModulePermsList` does β€” `PermsEditor` holds the draft, the confirm and the
// PUT. This component is a layout and a set of handlers, so the account page
// keeps one source of truth for what is about to be saved.
//
// β›”β›” THE `lockedKey` / `hideableKeys` PAIR BELOW IS LOAD-BEARING AND ITS
// FAILURE IS SILENT. Drop either and one click on "Hide all" hides the database's
// own identity column: a record whose faithful enforcement is a table of blank
// rows, which the server's PUT validation ACCEPTS because the identity column is
// a perfectly known field key. Both halves ship together or the pane is a defect.
// ---------------------------------------------------------------------------

import { FilterBuilderPanel, FieldsHidePanel } from "../filter-kit";
import type { FilterTree } from "../customer-grid/types";
import type { MetricsCensus, PermsModule, PermsRecord } from "./permsModel";
import { filterOf, hiddenSetFor, hideAllKeys, identityKey, showAllKeys } from "./permsModel";
import "./perms.css";

export interface DatabasePermsPaneProps {
  /** The database being edited: its label titles the pane, its fields feed both panels. */
  module: PermsModule;
  /**
   * ⚠ THE WHOLE DRAFT, keyed by module, NOT this module's entry. `filterOf` and `hiddenSetFor`
   * are where "an absent filter is an empty tree" and "absent hidden fields is an empty set" are
   * spelled, once; taking a bare entry would make this file spell them a second time, and two
   * spellings of one default are what those helpers exist to prevent.
   */
  entries: PermsRecord;
  /** Return to the account page. The SAME function the account page's Escape handler calls. */
  onBack: () => void;
  onFilter: (next: FilterTree | null) => void;
  onToggleHidden: (fieldKey: string) => void;
  onSetHidden: (keys: string[]) => void;
  /*
   * ⭐⭐ W40-T16 (OWNER INSTRUCTION 13) β€” `onMetrics` IS GONE FROM THIS PANE, AND SO IS THE BOX
   * IT DREW. Owner, verbatim: *"Fold 'Metrics fields (lookback measures over this database)' into
   * the 'Hide fields' checkboxes, one row per metric, named 'Metric - Revenue', 'Metric - Order'
   * and so on, so a user can check the ones the permissioning is limited to."*
   *
   * β›” A DELETION RATHER THAN A HIDE, because the control it replaces answered a COARSER
   * question. One box said "this account may build measures over this database, or may not";
   * the Hide-fields list below now carries one checkbox per bound measure, so the same admin
   * decides WHICH ones. Leaving the blanket box beside them would put two controls on one screen
   * that can contradict each other, and the record has no way to express the contradiction.
   *
   * ⚠ THE CAPABILITY ITSELF IS UNTOUCHED. `PermsEntry.metrics` still rides the wire, still parses
   * (`parseEntry`) and is still emitted (`toPutBody`), because a record written before this
   * ticket may carry an explicit revocation. What honours it here is `hiddenSetFor` below, on the
   * READ side: a blanket `metrics: false` paints every metric row as hidden without rewriting
   * anybody's stored rule. See the note at that call.
   */
  /** People this tenant can name in a `user` condition. Absent β‡’ the panel says so. */
  userOptions?: string[];
  /**
   * ⭐⭐ W46-T34 β€” THE METRIC CENSUS FOR *THIS* DATABASE, as `routes_admin::get_perms` ships it
   * under `metrics_by_module[key]`. The server half landed first and nothing read it; this prop
   * is the reader ([[a-built-validated-wall-can-have-no-caller]]).
   *
   * β›” `status` IS THREE ANSWERS, NOT TWO, AND THAT DISTINCTION IS THE WHOLE TICKET. `none` means
   * asked and answered β€” this database genuinely binds no measure. `unavailable` means the offer
   * could not be made at all (a warming mirror, say) and `reason` states why. Rendering the
   * second as the first is exactly the conflation the server half was written to end, so the two
   * branches below never share a sentence.
   */
  metrics?: MetricsCensus;
}

/**
 * β›”β›” `MetricsCensus` MOVED TO `permsModel.ts` AND IS RE-EXPORTED HERE β€” AND THE DIRECTION IS A
 * HARNESS CONSTRAINT, NOT A TIDY-UP. The first draft declared it in THIS file with a note saying
 * the eventual parser should import it from here. Measured, that import is not free:
 * `verify_login.py` compiles `permsModel.ts` with a bare `npx tsc` and **no `--jsx`**, so a
 * type-only `import ... from "./DatabasePermsPane"` raises `TS6142` inside that gate's own
 * compilation. A `.tsx` importing a `.ts` costs nothing; the reverse does. The shape therefore
 * lives beside the parser that produces it, and there is still exactly ONE definition.
 *
 * ⚠ THE RE-EXPORT IS NOT DECORATION. It keeps this module's public surface exactly as W46-T34
 * shipped it, so any importer that already reads the name from here β€” a test, a future pane β€”
 * does not have to move in the same change.
 */
export type { MetricsCensus } from "./permsModel";

export function DatabasePermsPane({
  module,
  entries,
  onBack,
  onFilter,
  onToggleHidden,
  onSetHidden,
  userOptions,
  metrics,
}: DatabasePermsPaneProps) {
  /**
   * β›”β›” THE FALLBACK ANSWERS ONLY THE QUESTION IT CAN ANSWER, AND SILENCE IS THE THIRD ANSWER.
   * Until `parsePermsPayload` carries `metrics_by_module` (out of this ticket's fence), no census
   * reaches this pane, so the count is derived from the metric pseudo-fields already in
   * `module.fields`. That derivation is TRUE when measures exist and a LIE when none appear:
   * `routes_admin` builds the field list and the census from the same `_metric_catalogue` call,
   * so a database whose offer failed ships zero metric fields β€” indistinguishable here from one
   * that genuinely binds none. Saying "this database has no measures" off that would re-create
   * the exact conflation W46-T34's server half exists to end, so the empty case renders NOTHING
   * and waits for the census. A missing sentence is recoverable; a confident wrong one is not.
   */
  const derived = module.fields.filter((f) => f.isMetric).length;
  const census: MetricsCensus | null =
    metrics ?? (derived > 0 ? { count: derived, status: "ok" } : null);

  return (
    <div className="set-dbperm">
      <div className="set-dbperm-head">
        {/* β›” ONE WORD, AND THE SHORTNESS IS FORCED RATHER THAN CHOSEN. The account's own exit,
            "Back to accounts", is rendered by `PermsEditor` DIRECTLY ABOVE this pane and stays
            there while the room is open. Spelling this one "Back to account" would put two
            controls one letter apart on one screen, going to different places, which is a worse
            room than either label is a good one. Position already says where this one goes: it
            sits on the database title's line, so it leaves the database. `DESIGN.md` Β§4 asks for
            the shorter label wherever the longer one is narration, and here it also happens to
            be the only unambiguous one. */}
        <button type="button" className="set-secondary set-dbperm-back" onClick={onBack}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false">
            <path
              d="M9.5 4 5.5 8l4 4"
              stroke="currentColor"
              strokeWidth={1.3}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          Back
        </button>
        {/* The pane says which database it is about. Without it every one of these rooms looks
            identical, and the reader's only clue is what they clicked a scroll ago. */}
        <h4 className="set-h4 set-dbperm-title">{module.label}</h4>
      </div>

      {/* THE KIT'S OWN PANELS (contract C-KIT), not lookalikes: the same two the grid toolbar
          mounts, so an admin writes a condition with the control they already know and there is
          one condition grammar in the product rather than two that drift within a wave.
          They STACK here rather than sitting side by side: the pane is theirs alone now, and a
          filter and a field list read as two decisions taken in order, not one wide row. */}
      <div className="set-dbperm-panels">
        <div className="cg-pop set-perm-pop">
          <FilterBuilderPanel
            database={null}
            fields={module.fields}
            filters={filterOf(entries, module.key)}
            onChange={onFilter}
            userOptions={userOptions}
          />
        </div>
        <div className="cg-pop set-perm-pop">
          {/* ⭐⭐ W46-T34 β€” THE METRICS GROUP, STATED FOR THIS DATABASE AND NOT FOR ANY OTHER.
              It sits INSIDE the hide-fields pop rather than above the pair, because the rows it
              heads are that panel's own checkboxes ("Metric - Sales", "Metric - Orders"): a
              census floating above both panels would read as a fact about the filter builder too.
              β›” THREE BRANCHES, NEVER TWO. `ok` counts what is offered; `none` says the database
              binds no measure; `unavailable` says the offer could not be made and prints the
              server's own reason. The second and third share no wording on purpose β€” "there are
              none" and "I cannot say" are different answers, and merging them is the defect this
              ticket's server half was written to fix.
              ⚠ CLASSES ONLY, AND ONLY EXISTING ONES. `perms.css` and `index.css` are out of this
              ticket's fence, so a minted class would render unstyled: `.set-perm-group` is the
              muted group label instruction 8 already established, `.pg-empty` the empty-state
              sentence `ModulePermsList` already uses for the same job one level up. */}
          {census && (
            <p className="set-perm-group">
              {census.status === "ok"
                ? `Metrics: ${census.count} ${census.count === 1 ? "measure" : "measures"}`
                : "Metrics"}
            </p>
          )}
          {census && census.status === "none" && (
            <p className="pg-empty">This database has no measures.</p>
          )}
          {census && census.status === "unavailable" && (
            <p className="pg-empty">
              {census.reason
                ? `Measures could not be listed: ${census.reason}`
                : "Measures could not be listed, so this database's metrics are unknown."}
            </p>
          )}
          {/* ⭐⭐ W40-T16 β€” THIS LIST IS WHERE THE METRICS RULE NOW LIVES. `module.fields` carries
              C3's `measure_`-namespaced pseudo-fields, `permsModel::parseField` marks each one,
              and the panel draws it as an ordinary checkbox named "Metric - Revenue". Checking it
              puts that field's key into `hiddenFields` through the same `onToggle` every other
              row uses, so there is no second write path for a metric and no second record shape.
              β›” `hiddenSetFor`, NOT `hiddenSet`, AND THE DIFFERENCE IS THE MIGRATION. A record
              written before this ticket can carry a blanket `metrics: false` (W38-T19's box), and
              the control that wrote it is gone from this pane. The union paints every metric row
              as hidden for such a record, so the old revocation is HONOURED on screen rather than
              silently reading as a grant. It is a read-side union on purpose: folding it into
              `hiddenFields` would edit somebody's stored rule as a side effect of opening a page. */}
          <FieldsHidePanel
            fields={module.fields}
            hidden={hiddenSetFor(entries, module.key, module.fields)}
            onToggle={onToggleHidden}
            /* ⭐⭐ W40-T17 (OWNER INSTRUCTION 15) β€” THE ONE PROP THAT MAKES THIS MOUNT DIFFER
               FROM THE GRID'S. Owner, verbatim: *"stop displaying 'Shared with me' / 'Shared
               with everyone' fields under Hide Fields - permission on pre-set Fields only."*
               `false` drops both sections AND swaps the membership rule for AM-2's
               `metric || !custom`, so this list is the database's own columns plus its bound
               measures and nothing else.
               β›” IT IS PASSED HERE AND NOWHERE ELSE. `customer-grid/Toolbar.tsx` mounts the same
               panel and passes no `sharedSections`, so the grid keeps all three sections exactly
               as the 2026-08-21 hotfix left them. That is the whole reason this is a prop rather
               than a deletion: the two surfaces are supposed to differ now. */
            sharedSections={false}
            // β›”β›” BOTH HALVES OF THE TRAP, and neither is decoration. `lockedKey` disables the
            // identity column's own checkbox; `hideableKeys` is what keeps "Hide all" from
            // including it anyway. One without the other still ships blank rows.
            lockedKey={identityKey(module.fields)}
            /* ⭐⭐ W40-T17 β€” THE BULK ACTIONS REACH EXACTLY WHAT THIS ROOM LISTS, and the
               narrowing above is what owes them the change: a list showing four rows whose
               "Show all" clears hidden state for seven fields would WIDEN a permission through
               a control that never displayed the columns it just revealed. `showAllKeys`
               subtracts the governed keys instead of emptying the record; `hideAllKeys` adds
               them without disturbing what the record hides elsewhere. Both strip the identity
               key, so the trap above stays closed from this side too. */
            onHideAll={() => onSetHidden(hideAllKeys(entries, module.key, module.fields))}
            onShowAll={() => onSetHidden(showAllKeys(entries, module.key, module.fields))}
          />
        </div>
      </div>
    </div>
  );
}