@masterteam/components 0.0.290 → 0.0.292

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@ import * as i1 from '@angular/forms';
6
6
  import { ControlContainer, NgControl, FormsModule, Validators } from '@angular/forms';
7
7
  import * as i2 from '@jsverse/transloco';
8
8
  import { TranslocoService, TranslocoModule, TranslocoPipe } from '@jsverse/transloco';
9
- import { startWith, finalize, catchError, of, take, expand, EMPTY, reduce, map } from 'rxjs';
9
+ import { startWith, finalize, catchError, of, take, map, throwError, expand, EMPTY, reduce } from 'rxjs';
10
10
  import { Tooltip } from '@masterteam/components/tooltip';
11
11
  import { Icon } from '@masterteam/icons';
12
12
  import { SelectField } from '@masterteam/components/select-field';
@@ -20,7 +20,7 @@ import { newFieldId } from '@masterteam/components';
20
20
  import { Skeleton } from 'primeng/skeleton';
21
21
  import { Message } from 'primeng/message';
22
22
  import { ModalService } from '@masterteam/components/modal';
23
- import { serializeEntityRawValue } from '@masterteam/components/entities';
23
+ import { readEntityValueColor, serializeEntityRawValue } from '@masterteam/components/entities';
24
24
  import * as i2$1 from 'primeng/inputtext';
25
25
  import { InputTextModule } from 'primeng/inputtext';
26
26
 
@@ -778,6 +778,29 @@ const ACCESS_ALIASES = {
778
778
  const ROW_ID_KEY = '__rowId';
779
779
  const ROW_ENTITY_ID_KEY = '__entityId';
780
780
  const ROW_VALUES_KEY = '__values';
781
+ const ROW_PREFILL_KEY = '__prefill';
782
+ /**
783
+ * View types whose form control binds the resolved object rather than the
784
+ * stored scalar, so the edit dialog has to be pre-filled from the rendered
785
+ * `value` of the cell and not its `raw`. Mirrors `resolveLoadedFieldValue`
786
+ * in `@masterteam/forms/client-form`, which makes the same exception for
787
+ * these two at the top level of a form — a user picker renders from the
788
+ * object and would otherwise display a bare id.
789
+ */
790
+ const OBJECT_VALUED_VIEW_TYPES = new Set(['User', 'MultiUser']);
791
+ /**
792
+ * Stable sort by the payload's `order`, falling back to array position when it
793
+ * is absent. Used to flatten a process form into reading order: `order` on a
794
+ * form field is *section-relative*, so every section restarts at 0 and the
795
+ * numbers only mean anything within their own section.
796
+ */
797
+ function sortByOrder(items) {
798
+ return items
799
+ .map((item, index) => ({ item, index }))
800
+ .sort((a, b) => (a.item.order ?? a.index) - (b.item.order ?? b.index) ||
801
+ a.index - b.index)
802
+ .map(({ item }) => item);
803
+ }
781
804
  class EntityListField {
782
805
  // Inputs
783
806
  label = input('', ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
@@ -912,10 +935,15 @@ class EntityListField {
912
935
  // Keep the backend-rendered cells for untouched columns so resolved
913
936
  // labels (users, lookups, statuses) are not replaced by raw ids.
914
937
  const baseValues = base[ROW_VALUES_KEY] ?? {};
938
+ const basePrefill = base[ROW_PREFILL_KEY] ??
939
+ baseValues;
915
940
  const next = {
916
941
  ...base,
917
942
  [ROW_ID_KEY]: row.rowId,
918
943
  [ROW_VALUES_KEY]: { ...baseValues, ...changed },
944
+ // Re-opening the dialog must still show what the controls bind, so
945
+ // the resolved values survive a pending edit.
946
+ [ROW_PREFILL_KEY]: { ...basePrefill, ...changed },
919
947
  };
920
948
  for (const column of this.columns()) {
921
949
  const key = column.propertyKey ?? column.key;
@@ -1108,7 +1136,11 @@ class EntityListField {
1108
1136
  this.setRowDraft(rowId, values, parsed.display);
1109
1137
  this.pendingRows.set([
1110
1138
  ...this.pendingRows(),
1111
- { rowId, entityId: 0, values: this.toSubmitValues(values) },
1139
+ {
1140
+ rowId,
1141
+ entityId: 0,
1142
+ values: this.toSubmitValues(values, parsed.submit),
1143
+ },
1112
1144
  ]);
1113
1145
  this.emitValue();
1114
1146
  });
@@ -1122,6 +1154,10 @@ class EntityListField {
1122
1154
  const entityId = Number(row[ROW_ENTITY_ID_KEY]) || 0;
1123
1155
  const rowId = String(row[ROW_ID_KEY] ?? '');
1124
1156
  const initialValues = row[ROW_VALUES_KEY] ?? {};
1157
+ // The form is filled with the shapes its controls bind; the diff still
1158
+ // runs against `initialValues`, the stored scalars.
1159
+ const prefillValues = row[ROW_PREFILL_KEY] ??
1160
+ initialValues;
1125
1161
  const ref = this.modal.openModal(component, 'dialog', {
1126
1162
  header: this.transloco.translate('components.entityListField.edit'),
1127
1163
  styleClass: '!w-[48rem] max-w-[96vw]',
@@ -1132,7 +1168,7 @@ class EntityListField {
1132
1168
  levelDataId: this.levelDataId(),
1133
1169
  writeFields: this.writeFields(),
1134
1170
  lookups: this.lookups(),
1135
- initialValues,
1171
+ initialValues: prefillValues,
1136
1172
  isEdit: true,
1137
1173
  },
1138
1174
  });
@@ -1155,7 +1191,7 @@ class EntityListField {
1155
1191
  * (keys outside `readFields`) are left untouched by the backend.
1156
1192
  */
1157
1193
  applyExistingRowEdit(entityId, fallbackRowId, initialValues, parsed) {
1158
- const changed = this.diffValues(initialValues, parsed.values);
1194
+ const changed = this.diffValues(initialValues, parsed.values, parsed.submit);
1159
1195
  const current = this.pendingRows();
1160
1196
  const existing = current.find((row) => row.entityId === entityId);
1161
1197
  const rowId = existing?.rowId || (fallbackRowId ? fallbackRowId : `entity-${entityId}`);
@@ -1173,7 +1209,7 @@ class EntityListField {
1173
1209
  const next = {
1174
1210
  rowId,
1175
1211
  entityId,
1176
- values: this.toSubmitValues(merged),
1212
+ values: this.toSubmitValues(merged, parsed.submit),
1177
1213
  };
1178
1214
  this.pendingRows.set(existing
1179
1215
  ? current.map((row) => (row.entityId === entityId ? next : row))
@@ -1184,7 +1220,7 @@ class EntityListField {
1184
1220
  const values = this.dropEmptyValues(parsed.values);
1185
1221
  this.setRowDraft(rowId, values, parsed.display);
1186
1222
  this.pendingRows.set(this.pendingRows().map((row) => row.rowId === rowId
1187
- ? { ...row, values: this.toSubmitValues(values) }
1223
+ ? { ...row, values: this.toSubmitValues(values, parsed.submit) }
1188
1224
  : row));
1189
1225
  }
1190
1226
  /**
@@ -1223,9 +1259,10 @@ class EntityListField {
1223
1259
  return {
1224
1260
  values: values,
1225
1261
  display: payload['display'] ?? {},
1262
+ submit: payload['submit'] ?? {},
1226
1263
  };
1227
1264
  }
1228
- return { values: payload, display: {} };
1265
+ return { values: payload, display: {}, submit: {} };
1229
1266
  }
1230
1267
  nextRowId() {
1231
1268
  const used = new Set(this.pendingRows().map((row) => row.rowId));
@@ -1252,6 +1289,9 @@ class EntityListField {
1252
1289
  [ROW_ID_KEY]: rowId,
1253
1290
  [ROW_ENTITY_ID_KEY]: entityId,
1254
1291
  [ROW_VALUES_KEY]: values,
1292
+ // A drafted row is built from control values already, so there is
1293
+ // nothing to resolve — the two maps are the same.
1294
+ [ROW_PREFILL_KEY]: values,
1255
1295
  };
1256
1296
  for (const column of this.columns()) {
1257
1297
  // Form values are keyed by catalog property key (e.g. "task_name"),
@@ -1339,14 +1379,24 @@ class EntityListField {
1339
1379
  this.onModelChange(next);
1340
1380
  this.onTouched();
1341
1381
  }
1342
- /** `values[]` entries, restricted to `writeFields` when configured. */
1343
- toSubmitValues(values) {
1382
+ /**
1383
+ * `values[]` entries, restricted to `writeFields` when configured.
1384
+ *
1385
+ * `submitShaped` carries the dialog-normalized counterpart of `values`,
1386
+ * keyed the same way, and is preferred per key. The control value a rich
1387
+ * field holds is not the scalar the backend stores — a user picker holds
1388
+ * the whole search result, a date picker a `Date` — and only the dialog
1389
+ * knows the target module's view types, so it does that reduction. Without
1390
+ * it we would stringify the control value as-is and the row would carry a
1391
+ * JSON user object where a bare id belongs.
1392
+ */
1393
+ toSubmitValues(values, submitShaped = {}) {
1344
1394
  const allowed = new Set(this.writeFields());
1345
1395
  return Object.entries(values)
1346
1396
  .filter(([propertyKey]) => allowed.size === 0 || allowed.has(propertyKey))
1347
1397
  .map(([propertyKey, value]) => ({
1348
1398
  propertyKey,
1349
- rawValue: this.toRawValue(value),
1399
+ rawValue: this.toRawValue(propertyKey in submitShaped ? submitShaped[propertyKey] : value),
1350
1400
  }));
1351
1401
  }
1352
1402
  /** Backend `rawValue` is a serialized scalar; objects/arrays go as JSON. */
@@ -1381,14 +1431,21 @@ class EntityListField {
1381
1431
  * Keys the user actually changed. A key that was empty before and is still
1382
1432
  * empty is skipped (the dialog simply could not pre-fill it); a key that had
1383
1433
  * a value and is now empty is kept so the backend clears it.
1434
+ *
1435
+ * `initial` holds stored scalars (a `User` column pre-fills as a bare id)
1436
+ * while `next` holds control values (the whole picker result), so the two
1437
+ * are only comparable once reduced — hence comparing `submitShaped`.
1438
+ * Comparing the rich value directly marked every rich-valued column as
1439
+ * changed even when untouched, and the partial update then rewrote it.
1384
1440
  */
1385
- diffValues(initial, next) {
1441
+ diffValues(initial, next, submitShaped = {}) {
1386
1442
  const changed = {};
1387
1443
  for (const [key, value] of Object.entries(next)) {
1388
1444
  const before = initial[key];
1445
+ const comparable = key in submitShaped ? submitShaped[key] : value;
1389
1446
  if (this.isEmptyValue(value) && this.isEmptyValue(before))
1390
1447
  continue;
1391
- if (this.isSameValue(before, value))
1448
+ if (this.isSameValue(before, comparable))
1392
1449
  continue;
1393
1450
  changed[key] = value;
1394
1451
  }
@@ -1414,15 +1471,42 @@ class EntityListField {
1414
1471
  fetchDraftColumns(levelId, moduleId, propertyKeys) {
1415
1472
  this.loading.set(true);
1416
1473
  const ctx = this.context();
1417
- this.fetchSubscription = this.http
1474
+ const properties$ = this.http
1418
1475
  .get('fetch/catalog', {
1419
1476
  params: { contextKey: `level:${levelId}/module:${moduleId}` },
1477
+ // A 404 here is the expected unmapped Write-only case handled below,
1478
+ // and every other failure is already surfaced inline by `errorMessage`.
1479
+ // Without this the host's message interceptor toasts the 404 too — it
1480
+ // only honours `noMessage`, and `fetch/catalog` is not a silent
1481
+ // endpoint the way `fetch/query` is.
1482
+ headers: { noMessage: 'true' },
1420
1483
  ...(ctx ? { context: ctx } : {}),
1421
1484
  })
1485
+ .pipe(map((response) => response.data.properties), catchError((error) => {
1486
+ if (this.accessMode() !== 'Write' || error.status !== 404) {
1487
+ return throwError(() => error);
1488
+ }
1489
+ // Write-only EntityLists may intentionally use a target module that
1490
+ // is not mapped to the owning level. Fetch catalog represents a
1491
+ // browsable level/module context and rejects that pair; the runtime
1492
+ // Create form remains the authorized source for its field metadata.
1493
+ return this.http
1494
+ .post('process-form-load', {
1495
+ moduleKey: 'ModuleData',
1496
+ operationKey: 'Create',
1497
+ moduleId,
1498
+ levelId,
1499
+ }, {
1500
+ headers: { noMessage: 'true' },
1501
+ ...(ctx ? { context: ctx } : {}),
1502
+ })
1503
+ .pipe(map((response) => this.mapProcessFormProperties(response)));
1504
+ }));
1505
+ this.fetchSubscription = properties$
1422
1506
  .pipe(takeUntilDestroyed(this.destroyRef), finalize(() => this.loading.set(false)))
1423
1507
  .subscribe({
1424
- next: (response) => {
1425
- const properties = response.data.properties.filter((property) => propertyKeys.includes(property.key) ||
1508
+ next: (catalogProperties) => {
1509
+ const properties = catalogProperties.filter((property) => propertyKeys.includes(property.key) ||
1426
1510
  propertyKeys.includes(property.normalizedKey));
1427
1511
  this.applyResponse({
1428
1512
  catalog: { properties },
@@ -1442,6 +1526,37 @@ class EntityListField {
1442
1526
  error: () => this.errorMessage.set(this.transloco.translate('components.entityListField.loadFailed')),
1443
1527
  });
1444
1528
  }
1529
+ /**
1530
+ * Project a Create form into the catalog shape the column builder expects.
1531
+ * Sections and their fields are flattened into reading order and renumbered
1532
+ * from there — a field's own `order` is section-relative, so carrying it over
1533
+ * as the column order interleaves the sections once `applyResponse` sorts.
1534
+ */
1535
+ mapProcessFormProperties(response) {
1536
+ const sections = sortByOrder(response.data?.formConfiguration?.sections ?? []);
1537
+ return sections
1538
+ .flatMap((section) => sortByOrder(section.fields ?? []))
1539
+ .map((field, index) => {
1540
+ const metadata = field.propertyMetadata;
1541
+ const key = metadata?.key || field.propertyKey;
1542
+ if (!metadata?.viewType || !key)
1543
+ return null;
1544
+ const name = metadata.name;
1545
+ const label = typeof name === 'string'
1546
+ ? name
1547
+ : name?.display || name?.en || name?.ar || key;
1548
+ return {
1549
+ id: metadata.propertyId ?? 0,
1550
+ key,
1551
+ normalizedKey: metadata.normalizedKey || key,
1552
+ label,
1553
+ viewType: metadata.viewType,
1554
+ configuration: metadata.configuration ?? null,
1555
+ order: index,
1556
+ };
1557
+ })
1558
+ .filter((property) => property !== null);
1559
+ }
1445
1560
  fetchRows(levelId, levelDataId, moduleId, propertyKeys) {
1446
1561
  this.loading.set(true);
1447
1562
  this.errorMessage.set(null);
@@ -1509,6 +1624,7 @@ class EntityListField {
1509
1624
  }
1510
1625
  const rows = (response.records ?? []).map((record) => {
1511
1626
  const values = {};
1627
+ const prefill = {};
1512
1628
  const row = {
1513
1629
  Id: record.id,
1514
1630
  [ROW_ID_KEY]: `entity-${record.id}`,
@@ -1520,11 +1636,17 @@ class EntityListField {
1520
1636
  const propertyKey = property?.key ?? column.key;
1521
1637
  const cell = record.values?.[propertyKey];
1522
1638
  row[column.key] = this.toEntityData(column, cell, property, record.id);
1523
- // Keep the machine-readable value so the edit dialog can pre-fill and
1524
- // partial updates can be diffed against it.
1639
+ // Keep the machine-readable value as the baseline a partial update is
1640
+ // diffed against — it is the shape the row submits.
1525
1641
  values[propertyKey] = cell?.raw ?? cell?.value ?? null;
1642
+ // What the edit dialog patches into its form, which is not always the
1643
+ // same thing: see OBJECT_VALUED_VIEW_TYPES.
1644
+ prefill[propertyKey] = OBJECT_VALUED_VIEW_TYPES.has(column.viewType ?? '')
1645
+ ? (cell?.value ?? cell?.raw ?? null)
1646
+ : values[propertyKey];
1526
1647
  }
1527
1648
  row[ROW_VALUES_KEY] = values;
1649
+ row[ROW_PREFILL_KEY] = prefill;
1528
1650
  return row;
1529
1651
  });
1530
1652
  this.rows.set(rows);
@@ -1537,6 +1659,7 @@ class EntityListField {
1537
1659
  normalizedKey: property?.normalizedKey ?? column.key,
1538
1660
  name: column.label ?? property?.label ?? column.key,
1539
1661
  rawValue: serializeEntityRawValue(cell?.raw),
1662
+ color: readEntityValueColor(cell?.color),
1540
1663
  value: (cell?.value ?? ''),
1541
1664
  viewType: (column.viewType ?? 'Text'),
1542
1665
  type: property?.source,