@anzusystems/common-admin 2.0.0-rc.28 → 2.0.0-rc.29

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.
Files changed (41) hide show
  1. package/dist/domains/dam/api/damAssetApi.d.ts +12 -1
  2. package/dist/domains/dam/api/damAssetApi.js +151 -95
  3. package/dist/domains/dam/api/damAssetApi.js.map +1 -1
  4. package/dist/domains/dam/api/damMetadataOnServer.d.ts +35 -0
  5. package/dist/domains/dam/api/damMetadataOnServer.js +28 -0
  6. package/dist/domains/dam/api/damMetadataOnServer.js.map +1 -0
  7. package/dist/domains/dam/assetDetail/components/AssetDetailSidebarMetadata.vue.js +26 -25
  8. package/dist/domains/dam/assetDetail/components/AssetDetailSidebarMetadata.vue.js.map +1 -1
  9. package/dist/domains/dam/assetDetail/store/assetDetailStore.js +40 -39
  10. package/dist/domains/dam/assetDetail/store/assetDetailStore.js.map +1 -1
  11. package/dist/domains/dam/cropper/components/ACropper.vue.d.ts +1 -1
  12. package/dist/domains/dam/cropper/components/ACropper.vue.js +153 -136
  13. package/dist/domains/dam/cropper/components/ACropper.vue.js.map +1 -1
  14. package/dist/domains/dam/imageWidget/components/AImageMediaWidget.vue.d.ts +1 -1
  15. package/dist/domains/dam/imageWidget/components/AImagePublicInput.vue.d.ts +1 -1
  16. package/dist/domains/dam/imageWidget/components/AImageWidget.vue.d.ts +1 -1
  17. package/dist/domains/dam/imageWidget/components/AImageWidgetMultiple.vue.d.ts +1 -1
  18. package/dist/domains/dam/imageWidget/components/ImageMediaWidgetInner.vue.d.ts +1 -1
  19. package/dist/domains/dam/imageWidget/components/ImageWidgetInner.vue.d.ts +1 -1
  20. package/dist/domains/dam/imageWidget/components/ImageWidgetMultipleInner.vue.d.ts +1 -1
  21. package/dist/domains/dam/uploadQueue/components/UploadQueueDialog.vue.js +106 -106
  22. package/dist/domains/dam/uploadQueue/components/UploadQueueDialog.vue.js.map +1 -1
  23. package/dist/domains/dam/uploadQueue/components/UploadQueueDialogSingle.vue.js +13 -13
  24. package/dist/domains/dam/uploadQueue/components/UploadQueueDialogSingle.vue.js.map +1 -1
  25. package/dist/domains/dam/uploadQueue/settlement/uploadSettle.js +115 -114
  26. package/dist/domains/dam/uploadQueue/settlement/uploadSettle.js.map +1 -1
  27. package/dist/domains/dam/uploadQueue/store/uploadQueuesStore.js +147 -143
  28. package/dist/domains/dam/uploadQueue/store/uploadQueuesStore.js.map +1 -1
  29. package/dist/domains/filters/components/FiltersSelected.vue.js +5 -5
  30. package/dist/domains/filters/components/FiltersSelected.vue.js.map +1 -1
  31. package/dist/domains/filters/composables/filterFactory.js +41 -38
  32. package/dist/domains/filters/composables/filterFactory.js.map +1 -1
  33. package/dist/domains/remoteAutocomplete/components/AFormRemoteAutocomplete.vue.js +46 -38
  34. package/dist/domains/remoteAutocomplete/components/AFormRemoteAutocomplete.vue.js.map +1 -1
  35. package/dist/domains/system/composables/alerts.js +8 -2
  36. package/dist/domains/system/composables/alerts.js.map +1 -1
  37. package/dist/domains/system/systemBar/utils/appReload.d.ts +9 -1
  38. package/dist/domains/system/systemBar/utils/appReload.js +3 -3
  39. package/dist/domains/system/systemBar/utils/appReload.js.map +1 -1
  40. package/dist/lib.d.ts +2 -2
  41. package/package.json +2 -2
@@ -2,6 +2,7 @@ import { AxiosInstance } from 'axios';
2
2
  import { DocId, IntegerId } from '../../../shared/types/common';
3
3
  import { AssetDetailItemDto, AssetSearchListItemDto, DamAssetTypeType } from '../types/Asset';
4
4
  import { UploadQueueItem } from '../types/UploadQueue';
5
+ import { DamMetadataOnServer } from './damMetadataOnServer';
5
6
  import { DamMediaFromDam } from '../types/MediaAware';
6
7
  export declare const ENTITY = "asset";
7
8
  export interface AssetMetadataBulkItem {
@@ -35,6 +36,9 @@ export declare const fetchAssetByFileId: (client: () => AxiosInstance, endPoint:
35
36
  /**
36
37
  * Saves the metadata of the queue items. Sources are sent only where `extSystem` has them
37
38
  * for the item's asset type in DAM configuration `configName`.
39
+ * Every item is sent, so the answer holds each asset. Of an item whose metadata the DAM sent before,
40
+ * only the fields changed since go, and changed custom data rebased onto the assets read right before
41
+ * (`damMetadataOnServer`). Ten items per request. A failed request stops the later ones.
38
42
  */
39
43
  export declare const bulkUpdateAssetsMetadata: (client: () => AxiosInstance, endPoint: string, items: UploadQueueItem[], mainFileSingleUseOverride: boolean | undefined, extSystem: IntegerId, configName: string) => Promise<AssetMetadataBulkItem[]>;
40
44
  export declare const fetchAssetListByIds: (client: () => AxiosInstance, endPoint: string, ids: DocId[], licenceId: number) => Promise<AssetDetailItemDto[]>;
@@ -48,7 +52,14 @@ export declare const hasMetadataToSave: (item: UploadQueueItem) => item is Uploa
48
52
  * configuration `configName`. A field refused for several assets is listed once.
49
53
  */
50
54
  export declare const showMetadataSaveError: (error: unknown, extSystem: IntegerId, configName: string) => void;
51
- export declare const updateAssetMetadata: (client: () => AxiosInstance, endPoint: string, asset: AssetDetailItemDto, extSystem: IntegerId, mainFileSingleUse: boolean | null, configName: string) => Promise<void>;
55
+ /**
56
+ * Saves the asset detail form `asset`. Callers name the fields of a refusal through `showMetadataSaveError`.
57
+ * Sources are sent only where `extSystem` has them for the asset type in DAM configuration `configName`.
58
+ * With `known`, what the DAM had when the form was read or last saved, only the fields changed against it go,
59
+ * and changed custom data rebased onto the asset read right before. Without it the form is sent whole.
60
+ * Resolves to what the DAM has after the save as far as the form knows, the form's next `known`.
61
+ */
62
+ export declare const updateAssetMetadata: (client: () => AxiosInstance, endPoint: string, asset: AssetDetailItemDto, extSystem: IntegerId, mainFileSingleUse: boolean | null, configName: string, known?: DamMetadataOnServer) => Promise<DamMetadataOnServer>;
52
63
  export declare const updateAssetAuthors: (client: () => AxiosInstance, endPoint: string, asset: AssetDetailItemDto, extSystem: IntegerId, configName: string) => Promise<void>;
53
64
  export type IdsGroupedByLicences = Map<IntegerId, DocId[]>;
54
65
  export type AssetAuthorsItems = AssetAuthorsItem[];
@@ -1,75 +1,82 @@
1
1
  import e from "axios";
2
2
  import { UploadQueueItemType as t } from "../types/UploadQueue.js";
3
3
  import "../../../shared/statusCodes.js";
4
- import { isNull as n, isUndefined as r } from "../../../shared/utils/common.js";
5
- import { AnzuApiValidationError as i, isAnzuApiValidationError as a } from "../../../shared/error/AnzuApiValidationError.js";
6
- import { useAlerts as o } from "../../system/composables/alerts.js";
7
- import { SYSTEM_CORE_DAM as s } from "./damConstants.js";
8
- import { DAM_END_POINT_CMS_ASSET as c } from "./damEndPoints.js";
9
- import { useDamConfigState as l } from "../config/composables/damConfigState.js";
10
- import { useApiFetchList as u } from "../../api/composables/useApiFetchList.js";
11
- import { useApiCommand as d, useApiRequest as f } from "../../api/composables/useApiRequest.js";
12
- import { useApiFetchItems as p } from "../../api/composables/useApiFetchItems.js";
13
- import { commonT as m } from "../../../plugins/i18n.js";
14
- import { customDataFormElementName as h } from "../../customDataForm/utils/customDataFormElementName.js";
15
- import { isDamSourceEnabled as g } from "../author/composables/damSourceConfig.js";
4
+ import { cloneDeep as n, isNull as r, isUndefined as i } from "../../../shared/utils/common.js";
5
+ import { customDataOf as a, metadataOfAsset as o, metadataOnServer as s, rebaseCustomData as c, sameMetadataValue as l, setMetadataOnServer as u } from "./damMetadataOnServer.js";
6
+ import { AnzuApiValidationError as d, isAnzuApiValidationError as f } from "../../../shared/error/AnzuApiValidationError.js";
7
+ import { useAlerts as p } from "../../system/composables/alerts.js";
8
+ import { SYSTEM_CORE_DAM as m } from "./damConstants.js";
9
+ import { DAM_END_POINT_CMS_ASSET as h } from "./damEndPoints.js";
10
+ import { useDamConfigState as g } from "../config/composables/damConfigState.js";
11
+ import { useApiFetchList as _ } from "../../api/composables/useApiFetchList.js";
12
+ import { useApiCommand as v, useApiRequest as y } from "../../api/composables/useApiRequest.js";
13
+ import { useApiFetchItems as b } from "../../api/composables/useApiFetchItems.js";
14
+ import { commonT as x } from "../../../plugins/i18n.js";
15
+ import { customDataFormElementName as S } from "../../customDataForm/utils/customDataFormElementName.js";
16
+ import { isDamSourceEnabled as C } from "../author/composables/damSourceConfig.js";
16
17
  // src/domains/dam/api/damAssetApi.ts
17
- var _ = 10, v = "asset", y = 50, b = (e, t, n) => u({
18
+ var w = 10, T = "asset", E = 50, D = (e, t, n) => _({
18
19
  client: e,
19
- system: s,
20
- entity: v,
20
+ system: m,
21
+ entity: T,
21
22
  urlTemplate: t + "/licence/:licenceId",
22
23
  urlParams: { licenceId: n }
23
- }), x = (e, t) => u({
24
+ }), O = (e, t) => _({
24
25
  client: e,
25
- system: s,
26
- entity: v,
26
+ system: m,
27
+ entity: T,
27
28
  urlTemplate: t + "/licence"
28
- }), S = (e, t, n, r = {}) => {
29
- let { execute: i } = f({
29
+ }), k = (e, t, n, r = {}) => {
30
+ let { execute: i } = y({
30
31
  client: e,
31
32
  method: "GET",
32
- system: s,
33
- entity: v,
33
+ system: m,
34
+ entity: T,
34
35
  urlTemplate: t + "/:id"
35
36
  });
36
37
  return i({
37
38
  urlParams: { id: n },
38
39
  report: r.report
39
40
  });
40
- }, C = (e, t, n = c) => {
41
- let { execute: r } = f({
41
+ }, A = (e, t, n = h) => {
42
+ let { execute: r } = y({
42
43
  client: e,
43
44
  method: "GET",
44
- system: s,
45
- entity: v,
45
+ system: m,
46
+ entity: T,
46
47
  urlTemplate: n + "/:id"
47
48
  });
48
49
  return r({ urlParams: { id: t } });
49
- }, w = (e, t, n) => {
50
- let { execute: r } = f({
50
+ }, j = (e, t, n) => {
51
+ let { execute: r } = y({
51
52
  client: e,
52
53
  method: "GET",
53
- system: s,
54
- entity: v,
54
+ system: m,
55
+ entity: T,
55
56
  urlTemplate: t + "/asset-file/:id"
56
57
  });
57
58
  return r({ urlParams: { id: n } });
58
- }, T = async (e, t, n, r, i, a) => {
59
- let o = n.filter(N), { execute: s } = k(e, t);
60
- return (await M(s, I(o, r, i, a), o.map((e) => e.assetType))).flat();
59
+ }, M = async (e, t, n, r, i, a) => {
60
+ let o = q(n.filter(B), r, i, a), { execute: c } = I(e, t), l = [];
61
+ for (let n = 0; n < o.length; n += w) {
62
+ let r = o.slice(n, n + w);
63
+ await J(e, t, r);
64
+ let [i] = await z(c, r.map(({ body: e }) => e), r.map(({ item: e }) => e.assetType));
65
+ r.forEach(({ item: e, body: t, typed: n }) => u(e, G(s(e) ?? n, n, t))), l.push(...i ?? []);
66
+ }
67
+ return l;
61
68
  };
62
- async function E(e, t, n, r) {
69
+ async function N(e, t, n, r) {
63
70
  if (n.length === 0) return Promise.resolve([]);
64
- let i = Math.ceil(n.length / y), a = [];
71
+ let i = Math.ceil(n.length / E), a = [];
65
72
  for (let o = 0; o < i; o++) {
66
- let i = o * y, s = n.slice(i, i + y), c = await e().get(t + `/licence/${r}/ids/${s.join(",")}`);
73
+ let i = o * E, s = n.slice(i, i + E), c = await e().get(t + `/licence/${r}/ids/${s.join(",")}`);
67
74
  a.push(c);
68
75
  }
69
76
  return a;
70
77
  }
71
- var D = (e, t, n, r) => new Promise((i, a) => {
72
- E(e, t, n, r).then((e) => {
78
+ var P = (e, t, n, r) => new Promise((i, a) => {
79
+ N(e, t, n, r).then((e) => {
73
80
  if (n.length === 0) return i([]);
74
81
  if (e.length === 0) a(e);
75
82
  else if (e.every((e) => e.status === 200)) {
@@ -84,103 +91,152 @@ var D = (e, t, n, r) => new Promise((i, a) => {
84
91
  }).catch((e) => {
85
92
  a(e);
86
93
  });
87
- }), O = (e, t) => ({
94
+ }), F = (e, t) => ({
88
95
  client: e,
89
96
  method: "PATCH",
90
- system: s,
91
- entity: v,
97
+ system: m,
98
+ entity: T,
92
99
  urlTemplate: t + "/metadata-bulk-update",
93
100
  options: { validateStatus: (e) => e === 200 }
94
- }), k = (e, t) => p({
95
- ...O(e, t),
101
+ }), I = (e, t) => b({
102
+ ...F(e, t),
96
103
  shape: "array"
97
- }), A = (e, t) => d(O(e, t)), j = class extends i {
104
+ }), L = (e, t) => v(F(e, t)), R = class extends d {
98
105
  requestFields;
99
106
  assetTypes;
100
107
  constructor(e, t) {
101
- super(e, s, v, e), this.requestFields = Object.entries(e.response.data.fields).map(([e, t]) => ({
108
+ super(e, m, T, e), this.requestFields = Object.entries(e.response.data.fields).map(([e, t]) => ({
102
109
  field: e,
103
110
  errors: t
104
111
  })), this.assetTypes = t;
105
112
  }
106
- }, M = async (t, n, r) => {
113
+ }, z = async (t, n, r) => {
107
114
  let i = [];
108
- for (let o = 0; o < n.length; o += _) try {
109
- i.push(await t({ body: n.slice(o, o + _) }));
115
+ for (let a = 0; a < n.length; a += w) try {
116
+ i.push(await t({ body: n.slice(a, a + w) }));
110
117
  } catch (t) {
111
- throw a(t) && e.isAxiosError(t.cause) ? new j(t.cause, r.slice(o, o + _)) : t;
118
+ throw f(t) && e.isAxiosError(t.cause) ? new R(t.cause, r.slice(a, a + w)) : t;
112
119
  }
113
120
  return i;
114
- }, N = (e) => !n(e.assetId) && e.canEditMetadata;
115
- function P(e, t, n, r, i) {
116
- return g(e, t, i) ? {
121
+ }, B = (e) => !r(e.assetId) && e.canEditMetadata;
122
+ function V(e, t, n, r, i) {
123
+ return C(e, t, i) ? {
117
124
  authors: n,
118
125
  sources: r
119
126
  } : { authors: n };
120
127
  }
121
- function F(e, n) {
128
+ function H(e, n) {
122
129
  return e.type === t.Asset ? {} : { mainFileSingleUse: n ?? e.mainFileSingleUse ?? !1 };
123
130
  }
124
- function I(e, t, n, r) {
125
- let i = [];
126
- return e.forEach((e) => {
127
- N(e) && i.push({
128
- id: e.assetId,
129
- keywords: e.keywords,
130
- ...P(e.assetType, n, e.authors, e.sources, r),
131
+ var U = (e, t) => (e ?? !1) === (t ?? !1);
132
+ function W(e, t, n, r, i, a, o, s) {
133
+ let c = V(t, o, n.authors, n.sources, s);
134
+ if (!r) return {
135
+ body: {
136
+ id: e,
137
+ keywords: n.keywords,
138
+ ...c,
131
139
  described: !0,
132
- customData: e.customData,
133
- ...F(e, t)
134
- });
135
- }), i;
140
+ customData: n.customData,
141
+ ...i
142
+ },
143
+ base: void 0
144
+ };
145
+ let u = {
146
+ id: e,
147
+ described: !0
148
+ };
149
+ return l(n.keywords, r.keywords) || (u.keywords = n.keywords), l(n.authors, r.authors) || (u.authors = n.authors), "sources" in c && !l(n.sources, r.sources) && (u.sources = n.sources), "mainFileSingleUse" in i && (a || !U(i.mainFileSingleUse, r.mainFileSingleUse)) && (u.mainFileSingleUse = i.mainFileSingleUse), l(n.customData, r.customData) ? {
150
+ body: u,
151
+ base: void 0
152
+ } : (u.customData = n.customData, {
153
+ body: u,
154
+ base: r.customData
155
+ });
136
156
  }
137
- var { showErrorsDefault: L, showUnknownError: R, showApiValidationError: z } = o(), B = (e, t, n, i) => {
157
+ var G = (e, t, n) => ({
158
+ keywords: n.keywords ?? e.keywords,
159
+ authors: n.authors ?? e.authors,
160
+ sources: n.sources ?? e.sources,
161
+ customData: i(n.customData) ? e.customData : t.customData,
162
+ mainFileSingleUse: i(n.mainFileSingleUse) ? e.mainFileSingleUse : n.mainFileSingleUse
163
+ }), K = (e) => n({
164
+ keywords: e.keywords ?? [],
165
+ authors: e.authors ?? [],
166
+ sources: e.sources ?? [],
167
+ customData: a(e.customData),
168
+ mainFileSingleUse: e.mainFileSingleUse
169
+ });
170
+ function q(e, t, n, r) {
171
+ return e.map((e) => {
172
+ let a = K(e), o = s(e), c = H(e, t), { body: l, base: u } = W(e.assetId, e.assetType, a, o, c, !i(t), n, r);
173
+ return {
174
+ item: e,
175
+ body: l,
176
+ typed: a,
177
+ base: u
178
+ };
179
+ });
180
+ }
181
+ var J = async (e, t, n) => {
182
+ let r = n.filter(({ base: e }) => !i(e));
183
+ if (r.length === 0) return;
184
+ let o = /* @__PURE__ */ new Map();
185
+ r.forEach(({ item: e }) => o.set(e.licenceId, [...o.get(e.licenceId) ?? [], e.assetId]));
186
+ let s = /* @__PURE__ */ new Map();
187
+ for (let [n, r] of o) for (let i of await P(e, t, r, n)) s.set(i.id, i);
188
+ r.forEach(({ item: e, body: t, typed: n, base: r }) => {
189
+ let o = s.get(e.assetId);
190
+ o && !i(r) && (t.customData = c(n.customData, r, a(o.metadata.customData)));
191
+ });
192
+ }, { showErrorsDefault: Y, showUnknownError: X, showApiValidationError: Z } = p(), Q = (e, t, n, r) => {
138
193
  let a = e.match(/^\[(\d+)\]\.(.+)$/), o = a ? a[2] : e;
139
- if (o === "keywords") return m("common.damImage.asset.model.keywords");
140
- if (o === "authors") return m("common.damImage.asset.model.authors");
141
- if (o === "sources") return m("common.damImage.asset.model.sources");
194
+ if (o === "keywords") return x("common.damImage.asset.model.keywords");
195
+ if (o === "authors") return x("common.damImage.asset.model.authors");
196
+ if (o === "sources") return x("common.damImage.asset.model.sources");
142
197
  let s = o.split(".").at(-1), c = a ? t[Number(a[1])] : void 0;
143
- if (o.startsWith("customData.") && !r(c)) {
144
- let { getDamConfigAssetCustomFormElements: e } = l(void 0, i), t = e(n)?.[c].find((e) => e.property === s);
145
- if (t) return h(t);
198
+ if (o.startsWith("customData.") && !i(c)) {
199
+ let { getDamConfigAssetCustomFormElements: e } = g(void 0, r), t = e(n)?.[c].find((e) => e.property === s);
200
+ if (t) return S(t);
146
201
  }
147
202
  return s;
148
- }, V = (e, t, n) => {
149
- if (e instanceof j) {
203
+ }, $ = (e, t, n) => {
204
+ if (e instanceof R) {
150
205
  let r = /* @__PURE__ */ new Map();
151
206
  for (let { field: i, errors: a } of e.requestFields) {
152
- let o = B(i, e.assetTypes, t, n);
207
+ let o = Q(i, e.assetTypes, t, n);
153
208
  r.set(o, /* @__PURE__ */ new Set([...r.get(o) ?? [], ...a]));
154
209
  }
155
- z(Array.from(r, ([e, t]) => ({
210
+ Z(Array.from(r, ([e, t]) => ({
156
211
  field: e,
157
212
  errors: [...t]
158
213
  })), -1, !0);
159
- } else L(e) || R();
160
- }, H = async (e, t, n, r, i, a) => {
161
- let o = {
162
- id: n.id,
163
- keywords: n.keywords,
164
- ...P(n.attributes.assetType, r, n.authors, n.sources, a),
165
- described: !0,
166
- customData: n.metadata.customData,
167
- mainFileSingleUse: i
168
- }, { execute: s } = A(e, t);
169
- await M(s, [o], [n.attributes.assetType]);
170
- }, U = async (e, t, n, r, i) => {
214
+ } else Y(e) || X();
215
+ }, ee = async (e, t, r, s, l, u, d) => {
216
+ let f = n({
217
+ ...o(r),
218
+ mainFileSingleUse: l
219
+ }), { body: p, base: m } = W(r.id, r.attributes.assetType, f, d, { mainFileSingleUse: l }, !1, s, u);
220
+ if (!i(m)) {
221
+ let n = await k(e, t, r.id);
222
+ p.customData = c(f.customData, m, a(n.metadata.customData));
223
+ }
224
+ let { execute: h } = L(e, t);
225
+ return await z(h, [p], [r.attributes.assetType]), G(d ?? f, f, p);
226
+ }, te = async (e, t, n, r, i) => {
171
227
  let a = {
172
228
  id: n.id,
173
- ...P(n.attributes.assetType, r, n.authors, n.sources, i),
229
+ ...V(n.attributes.assetType, r, n.authors, n.sources, i),
174
230
  described: !0
175
- }, { execute: o } = A(e, t);
176
- await M(o, [a], [n.attributes.assetType]);
177
- }, W = async (e, t, n, r, i, a) => {
178
- let { execute: o } = A(e, t);
179
- await M(o, i.map((e) => ({
231
+ }, { execute: o } = L(e, t);
232
+ await z(o, [a], [n.attributes.assetType]);
233
+ }, ne = async (e, t, n, r, i, a) => {
234
+ let { execute: o } = L(e, t);
235
+ await z(o, i.map((e) => ({
180
236
  id: e.id,
181
- ...P(n, r, e.authors, e.sources ?? [], a)
237
+ ...V(n, r, e.authors, e.sources ?? [], a)
182
238
  })), []);
183
239
  };
184
- export { v as ENTITY, W as bulkUpdateAssetsAuthors, T as bulkUpdateAssetsMetadata, S as fetchAsset, C as fetchAssetAsCmsMedia, w as fetchAssetByFileId, D as fetchAssetListByIds, N as hasMetadataToSave, V as showMetadataSaveError, U as updateAssetAuthors, H as updateAssetMetadata, b as useFetchAssetList, x as useFetchAssetListByLicences };
240
+ export { T as ENTITY, ne as bulkUpdateAssetsAuthors, M as bulkUpdateAssetsMetadata, k as fetchAsset, A as fetchAssetAsCmsMedia, j as fetchAssetByFileId, P as fetchAssetListByIds, B as hasMetadataToSave, $ as showMetadataSaveError, te as updateAssetAuthors, ee as updateAssetMetadata, D as useFetchAssetList, O as useFetchAssetListByLicences };
185
241
 
186
242
  //# sourceMappingURL=damAssetApi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"damAssetApi.js","names":["axios","UploadQueueItemType","isNull","isUndefined","AnzuApiValidationError","isAnzuApiValidationError","useAlerts","SYSTEM_CORE_DAM","DAM_END_POINT_CMS_ASSET","useDamConfigState","useApiFetchList","useApiCommand","useApiRequest","useApiFetchItems","commonT","customDataFormElementName","isDamSourceEnabled","BULK_METADATA_LIMIT","ENTITY","FETCH_BY_IDS_MAX_LIMIT","useFetchAssetList","client","endPoint","licenceId","useFetchAssetListByLicences","fetchAsset","id","options","execute","fetchAssetAsCmsMedia","fetchAssetByFileId","assetFileId","bulkUpdateAssetsMetadata","items","mainFileSingleUseOverride","extSystem","configName","sent","hasMetadataToSave","useMetadataBulkUpdate","saveMetadataInBatches","listItemsToMetadataBulkItems","item","fetchAssetListByIdsSequence","ids","totalCalls","responses","i","offset","reduced","res","fetchAssetListByIds","resolve","reject","final","list","err","metadataBulkUpdate","status","useMetadataBulkCommand","AssetMetadataValidationError","axiosError","assetTypes","field","errors","bodies","answers","error","creditFields","assetType","authors","sources","singleUseField","override","dtoItems","showErrorsDefault","showUnknownError","showApiValidationError","metadataFieldName","key","indexed","path","property","getDamConfigAssetCustomFormElements","found","element","showMetadataSaveError","named","name","updateAssetMetadata","asset","mainFileSingleUse","data","updateAssetAuthors","bulkUpdateAssetsAuthors"],"sources":["../../../../src/domains/dam/api/damAssetApi.ts"],"sourcesContent":["import axios, { type AxiosError, type AxiosInstance } from 'axios'\nimport type { DocId, IntegerId } from '@/shared/types/common'\nimport type { AssetDetailItemDto, AssetSearchListItemDto, DamAssetTypeType } from '@/domains/dam/types/Asset'\nimport { type UploadQueueItem, UploadQueueItemType } from '@/domains/dam/types/UploadQueue'\nimport { HTTP_STATUS_OK } from '@/shared/statusCodes'\nimport { isNull, isUndefined } from '@/shared/utils/common'\nimport {\n AnzuApiValidationError,\n type AnzuApiValidationResponseData,\n isAnzuApiValidationError,\n type ValidationError,\n} from '@/shared/error/AnzuApiValidationError'\nimport { useAlerts } from '@/domains/system/composables/alerts'\nimport { SYSTEM_CORE_DAM } from '@/domains/dam/api/damConstants'\nimport { DAM_END_POINT_CMS_ASSET } from '@/domains/dam/api/damEndPoints'\nimport { useDamConfigState } from '@/domains/dam/config/composables/damConfigState'\nimport { useApiFetchList } from '@/domains/api/composables/useApiFetchList'\nimport { useApiCommand, useApiRequest } from '@/domains/api/composables/useApiRequest'\nimport { useApiFetchItems } from '@/domains/api/composables/useApiFetchItems'\nimport type { DamMediaFromDam } from '@/domains/dam/types/MediaAware'\nimport { commonT } from '@/plugins/i18n'\nimport { customDataFormElementName } from '@/domains/customDataForm/utils/customDataFormElementName'\nimport { isDamSourceEnabled } from '@/domains/dam/author/composables/damSourceConfig'\n\nconst BULK_METADATA_LIMIT = 10\nexport const ENTITY = 'asset'\nconst FETCH_BY_IDS_MAX_LIMIT = 50\n\nexport interface AssetMetadataBulkItem {\n id: DocId\n keywords: DocId[]\n authors: DocId[]\n sources?: DocId[]\n described: boolean\n customData: AssetCustomData\n // Left out for a copy, which keeps the flag of the asset it was copied from.\n mainFileSingleUse?: boolean | null\n mainFileInternal: boolean | null\n mainFileOverrideInternal: boolean | null\n}\n\n// What a save sends. Whether the main file is internal is set in the DAM itself.\n// A save from here leaves those two fields unchanged and reads them from the answer.\ntype AssetMetadataBulkItemBody = Omit<AssetMetadataBulkItem, 'mainFileInternal' | 'mainFileOverrideInternal'>\n\nexport declare type AssetCustomData = Record<string, any>\n\nexport const useFetchAssetList = (client: () => AxiosInstance, endPoint: string, licenceId: IntegerId) =>\n useApiFetchList<AssetSearchListItemDto>({\n client,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/licence/:licenceId',\n urlParams: { licenceId },\n })\n\n/**\n * Assets of several licences in one search, the licences in the filter `licences`. DAM requires them to share an ext\n * system (LicenceCollectionSingleExtSystem). Not every endpoint has it: the UGC proxy of core-dam lists only one licence.\n */\nexport const useFetchAssetListByLicences = (client: () => AxiosInstance, endPoint: string) =>\n useApiFetchList<AssetSearchListItemDto>({\n client,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n // No '/search' here: useApiFetchList appends it for an elastic filter config.\n urlTemplate: endPoint + '/licence',\n })\n\n/**\n * `options.report: false` keeps a failure of this read out of the api error logger.\n * Used by the upload queue, which polls the same asset repeatedly and reports only the first failure of a streak.\n */\nexport const fetchAsset = (\n client: () => AxiosInstance,\n endPoint: string,\n id: DocId,\n options: { report?: boolean } = {}\n) => {\n const { execute } = useApiRequest<AssetDetailItemDto, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/:id',\n })\n\n return execute({ urlParams: { id }, report: options.report })\n}\n\n/** `endPoint`: as configured (`endPointCmsAsset`). Defaults to `/adm/v1/cms/asset`. */\nexport const fetchAssetAsCmsMedia = <T extends DamMediaFromDam>(\n client: () => AxiosInstance,\n id: DocId,\n endPoint: string = DAM_END_POINT_CMS_ASSET\n) => {\n const { execute } = useApiRequest<T, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/:id',\n })\n\n return execute({ urlParams: { id } })\n}\n\nexport const fetchAssetByFileId = (client: () => AxiosInstance, endPoint: string, assetFileId: DocId) => {\n const { execute } = useApiRequest<AssetDetailItemDto, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/asset-file/:id',\n })\n\n return execute({ urlParams: { id: assetFileId } })\n}\n\n/**\n * Saves the metadata of the queue items. Sources are sent only where `extSystem` has them\n * for the item's asset type in DAM configuration `configName`.\n */\nexport const bulkUpdateAssetsMetadata = async (\n client: () => AxiosInstance,\n endPoint: string,\n items: UploadQueueItem[],\n mainFileSingleUseOverride: boolean | undefined,\n extSystem: IntegerId,\n configName: string\n) => {\n const sent = items.filter(hasMetadataToSave)\n const { execute } = useMetadataBulkUpdate<AssetMetadataBulkItemBody>(client, endPoint)\n const answers = await saveMetadataInBatches(\n execute,\n listItemsToMetadataBulkItems(sent, mainFileSingleUseOverride, extSystem, configName),\n sent.map((item) => item.assetType)\n )\n\n return answers.flat()\n}\n\nasync function fetchAssetListByIdsSequence(\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) {\n if (ids.length === 0) return Promise.resolve([])\n const totalCalls = Math.ceil(ids.length / FETCH_BY_IDS_MAX_LIMIT)\n const responses = []\n\n for (let i = 0; i < totalCalls; i++) {\n const offset = i * FETCH_BY_IDS_MAX_LIMIT\n const reduced = ids.slice(offset, offset + FETCH_BY_IDS_MAX_LIMIT)\n const res = await client().get(endPoint + `/licence/${licenceId}/ids/${reduced.join(',')}`)\n responses.push(res)\n }\n return responses\n}\n\nexport const fetchAssetListByIds: (\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) => Promise<AssetDetailItemDto[]> = (\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) => {\n return new Promise((resolve, reject) => {\n fetchAssetListByIdsSequence(client, endPoint, ids, licenceId)\n .then((responses) => {\n if (ids.length === 0) {\n return resolve([])\n } else if (responses.length === 0) {\n reject(responses)\n } else if (\n responses.every((res) => {\n return res.status === HTTP_STATUS_OK\n })\n ) {\n const final = []\n for (let i = 0; i < responses.length; i++) {\n const list = responses[i]!.data?.data\n // Reject instead of treating it as \"none exist\": the upload queue counts the assets missing from an answer.\n if (!Array.isArray(list)) return reject(responses)\n final.push(...list)\n }\n resolve(final as AssetDetailItemDto[])\n } else {\n reject(responses)\n }\n })\n .catch((err) => {\n //\n reject(err)\n })\n })\n}\n\n// Only a 200 is a save: any other answer is a save that failed, as before.\nconst metadataBulkUpdate = (client: () => AxiosInstance, endPoint: string) => ({\n client,\n method: 'PATCH' as const,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/metadata-bulk-update',\n options: { validateStatus: (status: number) => status === HTTP_STATUS_OK },\n})\n\n// For callers that build on the answer. It must be the list of saved assets.\nconst useMetadataBulkUpdate = <B>(client: () => AxiosInstance, endPoint: string) =>\n useApiFetchItems<AssetMetadataBulkItem, B[]>({ ...metadataBulkUpdate(client, endPoint), shape: 'array' })\n\n// For a caller that reads nothing of the answer.\nconst useMetadataBulkCommand = <B>(client: () => AxiosInstance, endPoint: string) =>\n useApiCommand<B[]>(metadataBulkUpdate(client, endPoint))\n\n/**\n * A metadata save refused by validation. `fields` are as the helpers build them.\n * `requestFields` keep the request keys, such as `[0].customData.title`.\n * The index is the asset's position in its batch, not a screen row.\n * `assetTypes` are the types of that batch's assets, in order. A custom field is named by the form of its asset's type.\n */\nclass AssetMetadataValidationError extends AnzuApiValidationError {\n requestFields: ValidationError[]\n assetTypes: Array<DamAssetTypeType | undefined>\n\n constructor(axiosError: AxiosError<AnzuApiValidationResponseData>, assetTypes: Array<DamAssetTypeType | undefined>) {\n super(axiosError, SYSTEM_CORE_DAM, ENTITY, axiosError)\n this.requestFields = Object.entries(axiosError.response!.data.fields).map(([field, errors]) => ({ field, errors }))\n this.assetTypes = assetTypes\n }\n}\n\n/**\n * Ten at a time, sequentially. The server saves a batch whole or not at all.\n * A failing batch stops the later ones, earlier ones stay saved, and saving again is safe.\n */\nconst saveMetadataInBatches = async <B, R>(\n execute: (params: { body: B[] }) => Promise<R>,\n bodies: B[],\n assetTypes: Array<DamAssetTypeType | undefined>\n) => {\n const answers: R[] = []\n for (let offset = 0; offset < bodies.length; offset += BULK_METADATA_LIMIT) {\n try {\n answers.push(await execute({ body: bodies.slice(offset, offset + BULK_METADATA_LIMIT) }))\n } catch (error) {\n // The helper builds the validation error from the axios error and keeps it as the cause.\n if (isAnzuApiValidationError(error) && axios.isAxiosError(error.cause)) {\n throw new AssetMetadataValidationError(error.cause, assetTypes.slice(offset, offset + BULK_METADATA_LIMIT))\n }\n throw error\n }\n }\n\n return answers\n}\n\n/** Items the bulk save sends: those with an asset whose metadata the user may edit. */\nexport const hasMetadataToSave = (item: UploadQueueItem): item is UploadQueueItem & { assetId: DocId } =>\n !isNull(item.assetId) && item.canEditMetadata\n\n/** Authors, and the sources where the ext system has them for the asset type. */\nfunction creditFields(\n assetType: DamAssetTypeType,\n extSystem: IntegerId,\n authors: DocId[],\n sources: DocId[],\n configName: string\n): Pick<AssetMetadataBulkItem, 'authors' | 'sources'> {\n return isDamSourceEnabled(assetType, extSystem, configName) ? { authors, sources } : { authors }\n}\n\n/**\n * The single use flag a row saves. A copy into the upload licence (a row of an asset) keeps the flag of the asset it\n * was copied from, so it sends none, also under a mass override; its switch is not offered.\n */\nfunction singleUseField(\n item: UploadQueueItem,\n override: boolean | undefined\n): Pick<AssetMetadataBulkItem, 'mainFileSingleUse'> {\n if (item.type === UploadQueueItemType.Asset) return {}\n // Never null. A row whose switch is not known yet is saved as off, which is how the DAM treats null.\n return { mainFileSingleUse: override ?? item.mainFileSingleUse ?? false }\n}\n\nfunction listItemsToMetadataBulkItems(\n items: UploadQueueItem[],\n mainFileSingleUseOverride: boolean | undefined,\n extSystem: IntegerId,\n configName: string\n) {\n const dtoItems: AssetMetadataBulkItemBody[] = []\n items.forEach((item) => {\n if (hasMetadataToSave(item)) {\n dtoItems.push({\n id: item.assetId,\n keywords: item.keywords,\n ...creditFields(item.assetType, extSystem, item.authors, item.sources, configName),\n described: true,\n customData: item.customData,\n ...singleUseField(item, mainFileSingleUseOverride),\n })\n }\n })\n\n return dtoItems\n}\n\nconst { showErrorsDefault, showUnknownError, showApiValidationError } = useAlerts()\n\n/** A field of a refused metadata save, named as the forms name it. */\nconst metadataFieldName = (\n key: string,\n assetTypes: Array<DamAssetTypeType | undefined>,\n extSystem: IntegerId,\n configName: string\n) => {\n const indexed = key.match(/^\\[(\\d+)\\]\\.(.+)$/)\n const path = indexed ? indexed[2]! : key\n if (path === 'keywords') return commonT('common.damImage.asset.model.keywords')\n if (path === 'authors') return commonT('common.damImage.asset.model.authors')\n if (path === 'sources') return commonT('common.damImage.asset.model.sources')\n const property = path.split('.').at(-1)!\n const assetType = indexed ? assetTypes[Number(indexed[1])] : undefined\n if (path.startsWith('customData.') && !isUndefined(assetType)) {\n const { getDamConfigAssetCustomFormElements } = useDamConfigState(undefined, configName)\n const found = getDamConfigAssetCustomFormElements(extSystem)?.[assetType].find(\n (element) => element.property === property\n )\n if (found) return customDataFormElementName(found)\n }\n\n return property\n}\n\n/**\n * The single place that tells the user about a failed metadata save, by kind of failure.\n * A validation refusal names its fields as the `extSystem` forms do in DAM\n * configuration `configName`. A field refused for several assets is listed once.\n */\nexport const showMetadataSaveError = (error: unknown, extSystem: IntegerId, configName: string) => {\n if (error instanceof AssetMetadataValidationError) {\n const named = new Map<string, Set<string>>()\n for (const { field, errors } of error.requestFields) {\n const name = metadataFieldName(field, error.assetTypes, extSystem, configName)\n named.set(name, new Set([...(named.get(name) ?? []), ...errors]))\n }\n showApiValidationError(\n Array.from(named, ([field, errors]) => ({ field, errors: [...errors] })),\n -1,\n true\n )\n return\n }\n if (!showErrorsDefault(error)) showUnknownError()\n}\n\n// Callers name the fields of a refusal through `showMetadataSaveError`.\n// Sources are sent only where `extSystem` has them for the asset type in DAM configuration `configName`.\nexport const updateAssetMetadata = async (\n client: () => AxiosInstance,\n endPoint: string,\n asset: AssetDetailItemDto,\n extSystem: IntegerId,\n mainFileSingleUse: boolean | null,\n configName: string\n) => {\n const data: AssetMetadataBulkItemBody = {\n id: asset.id,\n keywords: asset.keywords,\n ...creditFields(asset.attributes.assetType, extSystem, asset.authors, asset.sources, configName),\n described: true,\n customData: asset.metadata.customData,\n mainFileSingleUse: mainFileSingleUse,\n }\n\n const { execute } = useMetadataBulkCommand<AssetMetadataBulkItemBody>(client, endPoint)\n await saveMetadataInBatches(execute, [data], [asset.attributes.assetType])\n}\n\n// Callers name the fields of a refusal through `showMetadataSaveError`.\n// Writes the asset's authors, and its sources where `extSystem` has them in DAM configuration `configName`.\nexport const updateAssetAuthors = async (\n client: () => AxiosInstance,\n endPoint: string,\n asset: AssetDetailItemDto,\n extSystem: IntegerId,\n configName: string\n) => {\n const data: Partial<AssetMetadataBulkItem> = {\n id: asset.id,\n ...creditFields(asset.attributes.assetType, extSystem, asset.authors, asset.sources, configName),\n described: true,\n }\n\n const { execute } = useMetadataBulkCommand<Partial<AssetMetadataBulkItem>>(client, endPoint)\n await saveMetadataInBatches(execute, [data], [asset.attributes.assetType])\n}\n\nexport type IdsGroupedByLicences = Map<IntegerId, DocId[]>\n\nexport type AssetAuthorsItems = AssetAuthorsItem[]\nexport interface AssetAuthorsItem {\n id: DocId\n authors: DocId[]\n sources?: DocId[]\n}\n\n/** Writes authors of assets of `assetType`, and their sources where `extSystem` has them in DAM configuration `configName`. */\nexport const bulkUpdateAssetsAuthors = async (\n client: () => AxiosInstance,\n endPoint: string,\n assetType: DamAssetTypeType,\n extSystem: IntegerId,\n items: AssetAuthorsItems,\n configName: string\n) => {\n const { execute } = useMetadataBulkCommand<Pick<AssetMetadataBulkItem, 'id' | 'authors' | 'sources'>>(\n client,\n endPoint\n )\n const dtoItems = items.map((item) => ({\n id: item.id,\n ...creditFields(assetType, extSystem, item.authors, item.sources ?? [], configName),\n }))\n await saveMetadataInBatches(execute, dtoItems, [])\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,IAAMiB,IAAsB,IACfC,IAAS,SAChBC,IAAyB,IAqBlBC,KAAqBC,GAA6BC,GAAkBC,MAC/Eb,EAAwC;CACtCW;CACA,QAAQd;CACR,QAAQW;CACR,aAAaI,IAAW;CACxB,WAAW,EAAEC,aAAU;AACzB,CAAC,GAMUC,KAA+BH,GAA6BC,MACvEZ,EAAwC;CACtCW;CACA,QAAQd;CACR,QAAQW;CAER,aAAaI,IAAW;AAC1B,CAAC,GAMUG,KACXJ,GACAC,GACAI,GACAC,IAAgC,CAAC,MAC9B;CACH,IAAM,EAAEC,eAAYhB,EAAw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AAO,QAAQ,CAAC,GAAGC,CAAM;EAAE,EAAE,GACvE,IACA,EACF;CAEF,OACKW,EAAkBR,CAAK,KAAGS,EAAiB;AAClD,GAIaa,IAAsB,OACjCpE,GACAC,GACAoE,GACAvD,GACAwD,GACAvD,MACG;CACH,IAAMwD,IAAkC;EACtC,IAAIF,EAAM;EACV,UAAUA,EAAM;EAChB,GAAGtB,EAAasB,EAAM,WAAW,WAAWvD,GAAWuD,EAAM,SAASA,EAAM,SAAStD,CAAU;EAC/F,WAAW;EACX,YAAYsD,EAAM,SAAS;EACRC;CACrB,GAEM,EAAE/D,eAAY+B,EAAkDtC,GAAQC,CAAQ;CACtF,MAAMkB,EAAsBZ,GAAS,CAACgE,CAAI,GAAG,CAACF,EAAM,WAAW,SAAS,CAAC;AAC3E,GAIaG,IAAqB,OAChCxE,GACAC,GACAoE,GACAvD,GACAC,MACG;CACH,IAAMwD,IAAuC;EAC3C,IAAIF,EAAM;EACV,GAAGtB,EAAasB,EAAM,WAAW,WAAWvD,GAAWuD,EAAM,SAASA,EAAM,SAAStD,CAAU;EAC/F,WAAW;CACb,GAEM,EAAER,eAAY+B,EAAuDtC,GAAQC,CAAQ;CAC3F,MAAMkB,EAAsBZ,GAAS,CAACgE,CAAI,GAAG,CAACF,EAAM,WAAW,SAAS,CAAC;AAC3E,GAYaI,IAA0B,OACrCzE,GACAC,GACA+C,GACAlC,GACAF,GACAG,MACG;CACH,IAAM,EAAER,eAAY+B,EAClBtC,GACAC,CACF;CAKA,MAAMkB,EAAsBZ,GAJXK,EAAM,KAAKS,OAAU;EACpC,IAAIA,EAAK;EACT,GAAG0B,EAAaC,GAAWlC,GAAWO,EAAK,SAASA,EAAK,WAAW,CAAC,GAAGN,CAAU;CACpF,EACqC,GAAU,CAAC,CAAC;AACnD"}
1
+ {"version":3,"file":"damAssetApi.js","names":["axios","UploadQueueItemType","cloneDeep","isNull","isUndefined","customDataOf","metadataOfAsset","metadataOnServer","rebaseCustomData","sameMetadataValue","setMetadataOnServer","AnzuApiValidationError","isAnzuApiValidationError","useAlerts","SYSTEM_CORE_DAM","DAM_END_POINT_CMS_ASSET","useDamConfigState","useApiFetchList","useApiCommand","useApiRequest","useApiFetchItems","commonT","customDataFormElementName","isDamSourceEnabled","BULK_METADATA_LIMIT","ENTITY","FETCH_BY_IDS_MAX_LIMIT","useFetchAssetList","client","endPoint","licenceId","useFetchAssetListByLicences","fetchAsset","id","options","execute","fetchAssetAsCmsMedia","fetchAssetByFileId","assetFileId","bulkUpdateAssetsMetadata","items","mainFileSingleUseOverride","extSystem","configName","saves","listItemsToMetadataBulkItems","hasMetadataToSave","useMetadataBulkUpdate","answers","offset","batch","rebaseOntoFreshRead","answer","saveMetadataInBatches","body","item","typed","metadataAfterSave","fetchAssetListByIdsSequence","ids","totalCalls","responses","i","reduced","res","fetchAssetListByIds","resolve","reject","final","list","err","metadataBulkUpdate","status","useMetadataBulkCommand","AssetMetadataValidationError","axiosError","assetTypes","field","errors","bodies","error","creditFields","assetType","authors","sources","singleUseField","override","sameSingleUse","one","other","metadataBody","known","singleUse","singleUseForced","credit","before","typedOfRow","base","rebased","byLicence","fresh","asset","showErrorsDefault","showUnknownError","showApiValidationError","metadataFieldName","key","indexed","path","property","getDamConfigAssetCustomFormElements","found","element","showMetadataSaveError","named","name","updateAssetMetadata","mainFileSingleUse","updateAssetAuthors","data","bulkUpdateAssetsAuthors"],"sources":["../../../../src/domains/dam/api/damAssetApi.ts"],"sourcesContent":["import axios, { type AxiosError, type AxiosInstance } from 'axios'\nimport type { DocId, IntegerId } from '@/shared/types/common'\nimport type { AssetDetailItemDto, AssetSearchListItemDto, DamAssetTypeType } from '@/domains/dam/types/Asset'\nimport { type UploadQueueItem, UploadQueueItemType } from '@/domains/dam/types/UploadQueue'\nimport { HTTP_STATUS_OK } from '@/shared/statusCodes'\nimport { cloneDeep, isNull, isUndefined } from '@/shared/utils/common'\nimport {\n customDataOf,\n type DamMetadataOnServer,\n metadataOfAsset,\n metadataOnServer,\n rebaseCustomData,\n sameMetadataValue,\n setMetadataOnServer,\n} from '@/domains/dam/api/damMetadataOnServer'\nimport {\n AnzuApiValidationError,\n type AnzuApiValidationResponseData,\n isAnzuApiValidationError,\n type ValidationError,\n} from '@/shared/error/AnzuApiValidationError'\nimport { useAlerts } from '@/domains/system/composables/alerts'\nimport { SYSTEM_CORE_DAM } from '@/domains/dam/api/damConstants'\nimport { DAM_END_POINT_CMS_ASSET } from '@/domains/dam/api/damEndPoints'\nimport { useDamConfigState } from '@/domains/dam/config/composables/damConfigState'\nimport { useApiFetchList } from '@/domains/api/composables/useApiFetchList'\nimport { useApiCommand, useApiRequest } from '@/domains/api/composables/useApiRequest'\nimport { useApiFetchItems } from '@/domains/api/composables/useApiFetchItems'\nimport type { DamMediaFromDam } from '@/domains/dam/types/MediaAware'\nimport { commonT } from '@/plugins/i18n'\nimport { customDataFormElementName } from '@/domains/customDataForm/utils/customDataFormElementName'\nimport { isDamSourceEnabled } from '@/domains/dam/author/composables/damSourceConfig'\n\nconst BULK_METADATA_LIMIT = 10\nexport const ENTITY = 'asset'\nconst FETCH_BY_IDS_MAX_LIMIT = 50\n\nexport interface AssetMetadataBulkItem {\n id: DocId\n keywords: DocId[]\n authors: DocId[]\n sources?: DocId[]\n described: boolean\n customData: AssetCustomData\n // Left out for a copy, which keeps the flag of the asset it was copied from.\n mainFileSingleUse?: boolean | null\n mainFileInternal: boolean | null\n mainFileOverrideInternal: boolean | null\n}\n\n// What a save sends. Whether the main file is internal is set in the DAM itself.\n// A save from here leaves those two fields unchanged and reads them from the answer.\n// A field left out is one the save does not change: the DAM keeps it as it is.\ntype AssetMetadataBulkItemBody = Pick<AssetMetadataBulkItem, 'id' | 'described'> &\n Partial<Pick<AssetMetadataBulkItem, 'keywords' | 'authors' | 'sources' | 'customData' | 'mainFileSingleUse'>>\n\nexport declare type AssetCustomData = Record<string, any>\n\nexport const useFetchAssetList = (client: () => AxiosInstance, endPoint: string, licenceId: IntegerId) =>\n useApiFetchList<AssetSearchListItemDto>({\n client,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/licence/:licenceId',\n urlParams: { licenceId },\n })\n\n/**\n * Assets of several licences in one search, the licences in the filter `licences`. DAM requires them to share an ext\n * system (LicenceCollectionSingleExtSystem). Not every endpoint has it: the UGC proxy of core-dam lists only one licence.\n */\nexport const useFetchAssetListByLicences = (client: () => AxiosInstance, endPoint: string) =>\n useApiFetchList<AssetSearchListItemDto>({\n client,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n // No '/search' here: useApiFetchList appends it for an elastic filter config.\n urlTemplate: endPoint + '/licence',\n })\n\n/**\n * `options.report: false` keeps a failure of this read out of the api error logger.\n * Used by the upload queue, which polls the same asset repeatedly and reports only the first failure of a streak.\n */\nexport const fetchAsset = (\n client: () => AxiosInstance,\n endPoint: string,\n id: DocId,\n options: { report?: boolean } = {}\n) => {\n const { execute } = useApiRequest<AssetDetailItemDto, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/:id',\n })\n\n return execute({ urlParams: { id }, report: options.report })\n}\n\n/** `endPoint`: as configured (`endPointCmsAsset`). Defaults to `/adm/v1/cms/asset`. */\nexport const fetchAssetAsCmsMedia = <T extends DamMediaFromDam>(\n client: () => AxiosInstance,\n id: DocId,\n endPoint: string = DAM_END_POINT_CMS_ASSET\n) => {\n const { execute } = useApiRequest<T, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/:id',\n })\n\n return execute({ urlParams: { id } })\n}\n\nexport const fetchAssetByFileId = (client: () => AxiosInstance, endPoint: string, assetFileId: DocId) => {\n const { execute } = useApiRequest<AssetDetailItemDto, null>({\n client,\n method: 'GET',\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/asset-file/:id',\n })\n\n return execute({ urlParams: { id: assetFileId } })\n}\n\n/**\n * Saves the metadata of the queue items. Sources are sent only where `extSystem` has them\n * for the item's asset type in DAM configuration `configName`.\n * Every item is sent, so the answer holds each asset. Of an item whose metadata the DAM sent before,\n * only the fields changed since go, and changed custom data rebased onto the assets read right before\n * (`damMetadataOnServer`). Ten items per request. A failed request stops the later ones.\n */\nexport const bulkUpdateAssetsMetadata = async (\n client: () => AxiosInstance,\n endPoint: string,\n items: UploadQueueItem[],\n mainFileSingleUseOverride: boolean | undefined,\n extSystem: IntegerId,\n configName: string\n) => {\n const saves = listItemsToMetadataBulkItems(\n items.filter(hasMetadataToSave),\n mainFileSingleUseOverride,\n extSystem,\n configName\n )\n const { execute } = useMetadataBulkUpdate<AssetMetadataBulkItemBody>(client, endPoint)\n const answers: AssetMetadataBulkItem[] = []\n for (let offset = 0; offset < saves.length; offset += BULK_METADATA_LIMIT) {\n const batch = saves.slice(offset, offset + BULK_METADATA_LIMIT)\n await rebaseOntoFreshRead(client, endPoint, batch)\n const [answer] = await saveMetadataInBatches(\n execute,\n batch.map(({ body }) => body),\n batch.map(({ item }) => item.assetType)\n )\n // Onto what the row knows now, not when the save began: a save in the asset detail may have\n // written its read into the row meanwhile, and going back to the older state sent its values again.\n batch.forEach(({ item, body, typed }) =>\n setMetadataOnServer(item, metadataAfterSave(metadataOnServer(item) ?? typed, typed, body))\n )\n answers.push(...(answer ?? []))\n }\n\n return answers\n}\n\nasync function fetchAssetListByIdsSequence(\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) {\n if (ids.length === 0) return Promise.resolve([])\n const totalCalls = Math.ceil(ids.length / FETCH_BY_IDS_MAX_LIMIT)\n const responses = []\n\n for (let i = 0; i < totalCalls; i++) {\n const offset = i * FETCH_BY_IDS_MAX_LIMIT\n const reduced = ids.slice(offset, offset + FETCH_BY_IDS_MAX_LIMIT)\n const res = await client().get(endPoint + `/licence/${licenceId}/ids/${reduced.join(',')}`)\n responses.push(res)\n }\n return responses\n}\n\nexport const fetchAssetListByIds: (\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) => Promise<AssetDetailItemDto[]> = (\n client: () => AxiosInstance,\n endPoint: string,\n ids: DocId[],\n licenceId: number\n) => {\n return new Promise((resolve, reject) => {\n fetchAssetListByIdsSequence(client, endPoint, ids, licenceId)\n .then((responses) => {\n if (ids.length === 0) {\n return resolve([])\n } else if (responses.length === 0) {\n reject(responses)\n } else if (\n responses.every((res) => {\n return res.status === HTTP_STATUS_OK\n })\n ) {\n const final = []\n for (let i = 0; i < responses.length; i++) {\n const list = responses[i]!.data?.data\n // Reject instead of treating it as \"none exist\": the upload queue counts the assets missing from an answer.\n if (!Array.isArray(list)) return reject(responses)\n final.push(...list)\n }\n resolve(final as AssetDetailItemDto[])\n } else {\n reject(responses)\n }\n })\n .catch((err) => {\n //\n reject(err)\n })\n })\n}\n\n// Only a 200 is a save: any other answer is a save that failed, as before.\nconst metadataBulkUpdate = (client: () => AxiosInstance, endPoint: string) => ({\n client,\n method: 'PATCH' as const,\n system: SYSTEM_CORE_DAM,\n entity: ENTITY,\n urlTemplate: endPoint + '/metadata-bulk-update',\n options: { validateStatus: (status: number) => status === HTTP_STATUS_OK },\n})\n\n// For callers that build on the answer. It must be the list of saved assets.\nconst useMetadataBulkUpdate = <B>(client: () => AxiosInstance, endPoint: string) =>\n useApiFetchItems<AssetMetadataBulkItem, B[]>({ ...metadataBulkUpdate(client, endPoint), shape: 'array' })\n\n// For a caller that reads nothing of the answer.\nconst useMetadataBulkCommand = <B>(client: () => AxiosInstance, endPoint: string) =>\n useApiCommand<B[]>(metadataBulkUpdate(client, endPoint))\n\n/**\n * A metadata save refused by validation. `fields` are as the helpers build them.\n * `requestFields` keep the request keys, such as `[0].customData.title`.\n * The index is the asset's position in its batch, not a screen row.\n * `assetTypes` are the types of that batch's assets, in order. A custom field is named by the form of its asset's type.\n */\nclass AssetMetadataValidationError extends AnzuApiValidationError {\n requestFields: ValidationError[]\n assetTypes: Array<DamAssetTypeType | undefined>\n\n constructor(axiosError: AxiosError<AnzuApiValidationResponseData>, assetTypes: Array<DamAssetTypeType | undefined>) {\n super(axiosError, SYSTEM_CORE_DAM, ENTITY, axiosError)\n this.requestFields = Object.entries(axiosError.response!.data.fields).map(([field, errors]) => ({ field, errors }))\n this.assetTypes = assetTypes\n }\n}\n\n/**\n * Ten at a time, sequentially. The server saves a batch whole or not at all.\n * A failing batch stops the later ones, earlier ones stay saved, and saving again is safe.\n */\nconst saveMetadataInBatches = async <B, R>(\n execute: (params: { body: B[] }) => Promise<R>,\n bodies: B[],\n assetTypes: Array<DamAssetTypeType | undefined>\n) => {\n const answers: R[] = []\n for (let offset = 0; offset < bodies.length; offset += BULK_METADATA_LIMIT) {\n try {\n answers.push(await execute({ body: bodies.slice(offset, offset + BULK_METADATA_LIMIT) }))\n } catch (error) {\n // The helper builds the validation error from the axios error and keeps it as the cause.\n if (isAnzuApiValidationError(error) && axios.isAxiosError(error.cause)) {\n throw new AssetMetadataValidationError(error.cause, assetTypes.slice(offset, offset + BULK_METADATA_LIMIT))\n }\n throw error\n }\n }\n\n return answers\n}\n\n/** Items the bulk save sends: those with an asset whose metadata the user may edit. */\nexport const hasMetadataToSave = (item: UploadQueueItem): item is UploadQueueItem & { assetId: DocId } =>\n !isNull(item.assetId) && item.canEditMetadata\n\n/** Authors, and the sources where the ext system has them for the asset type. */\nfunction creditFields(\n assetType: DamAssetTypeType,\n extSystem: IntegerId,\n authors: DocId[],\n sources: DocId[],\n configName: string\n): Pick<AssetMetadataBulkItem, 'authors' | 'sources'> {\n return isDamSourceEnabled(assetType, extSystem, configName) ? { authors, sources } : { authors }\n}\n\n/**\n * The single use flag a row saves. A copy into the upload licence (a row of an asset) keeps the flag of the asset it\n * was copied from, so it sends none, also under a mass override; its switch is not offered.\n */\nfunction singleUseField(\n item: UploadQueueItem,\n override: boolean | undefined\n): Pick<AssetMetadataBulkItem, 'mainFileSingleUse'> {\n if (item.type === UploadQueueItemType.Asset) return {}\n // Never null. A row whose switch is not known yet is saved as off, which is how the DAM treats null.\n return { mainFileSingleUse: override ?? item.mainFileSingleUse ?? false }\n}\n\n// The DAM treats a single use flag that is not set as off.\nconst sameSingleUse = (one: boolean | null | undefined, other: boolean | null | undefined) =>\n (one ?? false) === (other ?? false)\n\n/**\n * The body of one asset's save: all of `typed` without `known`, otherwise the fields that differ from it.\n * `base`: the custom data the changes were made against, for rebasing them onto a fresh read before sending.\n */\nfunction metadataBody(\n id: DocId,\n assetType: DamAssetTypeType,\n typed: DamMetadataOnServer,\n known: DamMetadataOnServer | undefined,\n singleUse: Pick<AssetMetadataBulkItem, 'mainFileSingleUse'>,\n singleUseForced: boolean,\n extSystem: IntegerId,\n configName: string\n) {\n const credit = creditFields(assetType, extSystem, typed.authors, typed.sources, configName)\n if (!known) {\n const body: AssetMetadataBulkItemBody = {\n id,\n keywords: typed.keywords,\n ...credit,\n described: true,\n customData: typed.customData,\n ...singleUse,\n }\n return { body, base: undefined }\n }\n const body: AssetMetadataBulkItemBody = { id, described: true }\n if (!sameMetadataValue(typed.keywords, known.keywords)) body.keywords = typed.keywords\n if (!sameMetadataValue(typed.authors, known.authors)) body.authors = typed.authors\n if ('sources' in credit && !sameMetadataValue(typed.sources, known.sources)) body.sources = typed.sources\n if (\n 'mainFileSingleUse' in singleUse &&\n (singleUseForced || !sameSingleUse(singleUse.mainFileSingleUse, known.mainFileSingleUse))\n ) {\n body.mainFileSingleUse = singleUse.mainFileSingleUse\n }\n if (sameMetadataValue(typed.customData, known.customData)) return { body, base: undefined }\n body.customData = typed.customData\n\n return { body, base: known.customData }\n}\n\n/**\n * What the DAM has after a save that sent `body`, as far as the form or row knows: `before` with the sent fields.\n * Custom data are what the form or row held, which is what its next changes are made against.\n * The DAM also has the other editors' keys the save took, and the next rebase takes them again.\n */\nconst metadataAfterSave = (\n before: DamMetadataOnServer,\n typed: DamMetadataOnServer,\n body: AssetMetadataBulkItemBody\n): DamMetadataOnServer => ({\n keywords: body.keywords ?? before.keywords,\n authors: body.authors ?? before.authors,\n sources: body.sources ?? before.sources,\n customData: isUndefined(body.customData) ? before.customData : typed.customData,\n mainFileSingleUse: isUndefined(body.mainFileSingleUse) ? before.mainFileSingleUse : body.mainFileSingleUse,\n})\n\nconst typedOfRow = (item: UploadQueueItem): DamMetadataOnServer =>\n cloneDeep({\n keywords: item.keywords ?? [],\n authors: item.authors ?? [],\n sources: item.sources ?? [],\n customData: customDataOf(item.customData),\n mainFileSingleUse: item.mainFileSingleUse,\n })\n\nfunction listItemsToMetadataBulkItems(\n items: Array<UploadQueueItem & { assetId: DocId }>,\n mainFileSingleUseOverride: boolean | undefined,\n extSystem: IntegerId,\n configName: string\n) {\n return items.map((item) => {\n // Copied when the save starts: the row can be edited while its request waits for earlier ones.\n const typed = typedOfRow(item)\n const known = metadataOnServer(item)\n const singleUse = singleUseField(item, mainFileSingleUseOverride)\n const { body, base } = metadataBody(\n item.assetId,\n item.assetType,\n typed,\n known,\n singleUse,\n !isUndefined(mainFileSingleUseOverride),\n extSystem,\n configName\n )\n\n return { item, body, typed, base }\n })\n}\n\n/*\n * Rebases the changed custom data of a request onto the assets read right before it, one read per licence.\n * An asset the read does not find is sent as it is, and the DAM answers for it.\n */\nconst rebaseOntoFreshRead = async (\n client: () => AxiosInstance,\n endPoint: string,\n batch: ReturnType<typeof listItemsToMetadataBulkItems>\n) => {\n const rebased = batch.filter(({ base }) => !isUndefined(base))\n if (rebased.length === 0) return\n const byLicence = new Map<IntegerId, DocId[]>()\n rebased.forEach(({ item }) => byLicence.set(item.licenceId, [...(byLicence.get(item.licenceId) ?? []), item.assetId]))\n const fresh = new Map<DocId, AssetDetailItemDto>()\n for (const [licenceId, ids] of byLicence) {\n for (const asset of await fetchAssetListByIds(client, endPoint, ids, licenceId)) fresh.set(asset.id, asset)\n }\n rebased.forEach(({ item, body, typed, base }) => {\n const asset = fresh.get(item.assetId)\n if (!asset || isUndefined(base)) return\n body.customData = rebaseCustomData(typed.customData, base, customDataOf(asset.metadata.customData))\n })\n}\n\nconst { showErrorsDefault, showUnknownError, showApiValidationError } = useAlerts()\n\n/** A field of a refused metadata save, named as the forms name it. */\nconst metadataFieldName = (\n key: string,\n assetTypes: Array<DamAssetTypeType | undefined>,\n extSystem: IntegerId,\n configName: string\n) => {\n const indexed = key.match(/^\\[(\\d+)\\]\\.(.+)$/)\n const path = indexed ? indexed[2]! : key\n if (path === 'keywords') return commonT('common.damImage.asset.model.keywords')\n if (path === 'authors') return commonT('common.damImage.asset.model.authors')\n if (path === 'sources') return commonT('common.damImage.asset.model.sources')\n const property = path.split('.').at(-1)!\n const assetType = indexed ? assetTypes[Number(indexed[1])] : undefined\n if (path.startsWith('customData.') && !isUndefined(assetType)) {\n const { getDamConfigAssetCustomFormElements } = useDamConfigState(undefined, configName)\n const found = getDamConfigAssetCustomFormElements(extSystem)?.[assetType].find(\n (element) => element.property === property\n )\n if (found) return customDataFormElementName(found)\n }\n\n return property\n}\n\n/**\n * The single place that tells the user about a failed metadata save, by kind of failure.\n * A validation refusal names its fields as the `extSystem` forms do in DAM\n * configuration `configName`. A field refused for several assets is listed once.\n */\nexport const showMetadataSaveError = (error: unknown, extSystem: IntegerId, configName: string) => {\n if (error instanceof AssetMetadataValidationError) {\n const named = new Map<string, Set<string>>()\n for (const { field, errors } of error.requestFields) {\n const name = metadataFieldName(field, error.assetTypes, extSystem, configName)\n named.set(name, new Set([...(named.get(name) ?? []), ...errors]))\n }\n showApiValidationError(\n Array.from(named, ([field, errors]) => ({ field, errors: [...errors] })),\n -1,\n true\n )\n return\n }\n if (!showErrorsDefault(error)) showUnknownError()\n}\n\n/**\n * Saves the asset detail form `asset`. Callers name the fields of a refusal through `showMetadataSaveError`.\n * Sources are sent only where `extSystem` has them for the asset type in DAM configuration `configName`.\n * With `known`, what the DAM had when the form was read or last saved, only the fields changed against it go,\n * and changed custom data rebased onto the asset read right before. Without it the form is sent whole.\n * Resolves to what the DAM has after the save as far as the form knows, the form's next `known`.\n */\nexport const updateAssetMetadata = async (\n client: () => AxiosInstance,\n endPoint: string,\n asset: AssetDetailItemDto,\n extSystem: IntegerId,\n mainFileSingleUse: boolean | null,\n configName: string,\n known?: DamMetadataOnServer\n) => {\n const typed = cloneDeep({ ...metadataOfAsset(asset), mainFileSingleUse })\n const { body, base } = metadataBody(\n asset.id,\n asset.attributes.assetType,\n typed,\n known,\n { mainFileSingleUse },\n false,\n extSystem,\n configName\n )\n if (!isUndefined(base)) {\n const fresh = await fetchAsset(client, endPoint, asset.id)\n body.customData = rebaseCustomData(typed.customData, base, customDataOf(fresh.metadata.customData))\n }\n\n const { execute } = useMetadataBulkCommand<AssetMetadataBulkItemBody>(client, endPoint)\n await saveMetadataInBatches(execute, [body], [asset.attributes.assetType])\n\n return metadataAfterSave(known ?? typed, typed, body)\n}\n\n// Callers name the fields of a refusal through `showMetadataSaveError`.\n// Writes the asset's authors, and its sources where `extSystem` has them in DAM configuration `configName`.\nexport const updateAssetAuthors = async (\n client: () => AxiosInstance,\n endPoint: string,\n asset: AssetDetailItemDto,\n extSystem: IntegerId,\n configName: string\n) => {\n const data: Partial<AssetMetadataBulkItem> = {\n id: asset.id,\n ...creditFields(asset.attributes.assetType, extSystem, asset.authors, asset.sources, configName),\n described: true,\n }\n\n const { execute } = useMetadataBulkCommand<Partial<AssetMetadataBulkItem>>(client, endPoint)\n await saveMetadataInBatches(execute, [data], [asset.attributes.assetType])\n}\n\nexport type IdsGroupedByLicences = Map<IntegerId, DocId[]>\n\nexport type AssetAuthorsItems = AssetAuthorsItem[]\nexport interface AssetAuthorsItem {\n id: DocId\n authors: DocId[]\n sources?: DocId[]\n}\n\n/** Writes authors of assets of `assetType`, and their sources where `extSystem` has them in DAM configuration `configName`. */\nexport const bulkUpdateAssetsAuthors = async (\n client: () => AxiosInstance,\n endPoint: string,\n assetType: DamAssetTypeType,\n extSystem: IntegerId,\n items: AssetAuthorsItems,\n configName: string\n) => {\n const { execute } = useMetadataBulkCommand<Pick<AssetMetadataBulkItem, 'id' | 'authors' | 'sources'>>(\n client,\n endPoint\n )\n const dtoItems = items.map((item) => ({\n id: item.id,\n ...creditFields(assetType, extSystem, item.authors, item.sources ?? [], configName),\n }))\n await saveMetadataInBatches(execute, dtoItems, [])\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,IAAMwB,IAAsB,IACfC,IAAS,SAChBC,IAAyB,IAuBlBC,KAAqBC,GAA6BC,GAAkBC,MAC/Eb,EAAwC;CACtCW;CACA,QAAQd;CACR,QAAQW;CACR,aAAaI,IAAW;CACxB,WAAW,EAAEC,aAAU;AACzB,CAAC,GAMUC,KAA+BH,GAA6BC,MACvEZ,EAAwC;CACtCW;CACA,QAAQd;CACR,QAAQW;CAER,aAAaI,IAAW;AAC1B,CAAC,GAMUG,KACXJ,GACAC,GACAI,GACAC,IAAgC,CAAC,MAC9B;CACH,IAAM,EAAEC,eAAYhB,EAAwC;EAC1DS;EACA,QAAQ;EACR,QAAQd;EACR,QAAQW;EACR,aAAaI,IAAW;CAC1B,CAAC;CAED,OAAOM,EAAQ;EAAE,WAAW,EAAEF,MAAG;EAAG,QAAQC,EAAQ;CAAO,CAAC;AAC9D,GAGaE,KACXR,GACAK,GACAJ,IAAmBd,MAChB;CACH,IAAM,EAAEoB,eAAYhB,EAAuB;EACzCS;EACA,QAAQ;EACR,QAAQd;EACR,QAAQW;EACR,aAAaI,IAAW;CAC1B,CAAC;CAED,OAAOM,EAAQ,EAAE,WAAW,EAAEF,MAAG,EAAE,CAAC;AACtC,GAEaI,KAAsBT,GAA6BC,GAAkBS,MAAuB;CACvG,IAAM,EAAEH,eAAYhB,EAAwC;EAC1DS;EACA,QAAQ;EACR,QAAQd;EACR,QAAQW;EACR,aAAaI,IAAW;CAC1B,CAAC;CAED,OAAOM,EAAQ,EAAE,WAAW,EAAE,IAAIG,EAAY,EAAE,CAAC;AACnD,GASaC,IAA2B,OACtCX,GACAC,GACAW,GACAC,GACAC,GACAC,MACG;CACH,IAAMC,IAAQC,EACZL,EAAM,OAAOM,CAAiB,GAC9BL,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AAM,EAAEjE,eAAYsC,EAAkD7C,GAAQC,CAAQ;CAGtF,OAFA,MAAMwB,EAAsBlB,GAAS,CAACmB,CAAI,GAAG,CAAC+C,EAAM,WAAW,SAAS,CAAC,GAElE5C,EAAkBkC,KAASnC,GAAOA,GAAOF,CAAI;AACtD,GAIagE,KAAqB,OAChC1F,GACAC,GACAwE,GACA3D,GACAC,MACG;CACH,IAAM4E,IAAuC;EAC3C,IAAIlB,EAAM;EACV,GAAGpB,EAAaoB,EAAM,WAAW,WAAW3D,GAAW2D,EAAM,SAASA,EAAM,SAAS1D,CAAU;EAC/F,WAAW;CACb,GAEM,EAAER,eAAYsC,EAAuD7C,GAAQC,CAAQ;CAC3F,MAAMwB,EAAsBlB,GAAS,CAACoF,CAAI,GAAG,CAAClB,EAAM,WAAW,SAAS,CAAC;AAC3E,GAYamB,KAA0B,OACrC5F,GACAC,GACAqD,GACAxC,GACAF,GACAG,MACG;CACH,IAAM,EAAER,eAAYsC,EAClB7C,GACAC,CACF;CAKA,MAAMwB,EAAsBlB,GAJXK,EAAM,KAAKe,OAAU;EACpC,IAAIA,EAAK;EACT,GAAG0B,EAAaC,GAAWxC,GAAWa,EAAK,SAASA,EAAK,WAAW,CAAC,GAAGZ,CAAU;CACpF,EACqC,GAAU,CAAC,CAAC;AACnD"}
@@ -0,0 +1,35 @@
1
+ import { DocId } from '../../../shared/types/common';
2
+ import { AssetCustomData, AssetDetailItemDto } from '../types/Asset';
3
+ /**
4
+ * The metadata a save of a queue row or of the asset detail edits, as the DAM had them when last read or saved.
5
+ * The DAM keeps a field a save leaves out, but deletes a custom field left out of the custom data. So a save
6
+ * sends only the fields changed against this, and changed custom data rebased onto the asset read right before.
7
+ * Sending the rest as loaded would put back or delete what another editor saved meanwhile.
8
+ */
9
+ export interface DamMetadataOnServer {
10
+ keywords: DocId[];
11
+ authors: DocId[];
12
+ sources: DocId[];
13
+ customData: AssetCustomData;
14
+ mainFileSingleUse: boolean | null;
15
+ }
16
+ export declare const metadataOnServer: (of: object) => DamMetadataOnServer | undefined;
17
+ export declare const setMetadataOnServer: (of: object, metadata: DamMetadataOnServer) => void;
18
+ export declare const forgetMetadataOnServer: (of: object) => void;
19
+ export declare const customDataOf: (value: unknown) => AssetCustomData;
20
+ export declare const metadataOfAsset: (asset: Partial<Pick<AssetDetailItemDto, "keywords" | "authors" | "sources" | "mainFileSingleUse">> & {
21
+ metadata?: {
22
+ customData?: unknown;
23
+ };
24
+ }) => DamMetadataOnServer;
25
+ /**
26
+ * Equality as the DAM sees it: lists by values in order, objects by keys.
27
+ * A key with no value equals a missing key, as it is not sent.
28
+ */
29
+ export declare const sameMetadataValue: (one: unknown, other: unknown) => boolean;
30
+ /**
31
+ * Custom data `mine` rebased onto `theirs`: keys `mine` changed against `base` keep its value, all other keys take
32
+ * the value of `theirs`, which can be another editor's. A key without a value is left out.
33
+ * A key both changed keeps `mine`: the later save wins.
34
+ */
35
+ export declare const rebaseCustomData: (mine: AssetCustomData, base: AssetCustomData, theirs: AssetCustomData) => AssetCustomData;
@@ -0,0 +1,28 @@
1
+ import { toRaw as e } from "vue";
2
+ import { cloneDeep as t, isArray as n, isObject as r, isUndefined as i } from "../../../shared/utils/common.js";
3
+ // src/domains/dam/api/damMetadataOnServer.ts
4
+ var a = /* @__PURE__ */ new WeakMap(), o = (t) => a.get(e(t)), s = (n, r) => {
5
+ a.set(e(n), t(r));
6
+ }, c = (e) => r(e) && !n(e) ? e : {}, l = (e) => ({
7
+ keywords: e.keywords ?? [],
8
+ authors: e.authors ?? [],
9
+ sources: e.sources ?? [],
10
+ customData: c(e.metadata?.customData),
11
+ mainFileSingleUse: e.mainFileSingleUse ?? null
12
+ }), u = (e, t) => {
13
+ if (e === t) return !0;
14
+ if (n(e) || n(t)) return n(e) && n(t) && e.length === t.length && e.every((e, n) => u(e, t[n]));
15
+ if (!r(e) || !r(t)) return !1;
16
+ let i = e, a = t;
17
+ return [.../* @__PURE__ */ new Set([...Object.keys(i), ...Object.keys(a)])].every((e) => u(i[e], a[e]));
18
+ }, d = (e, t, n) => {
19
+ let r = {};
20
+ for (let a of /* @__PURE__ */ new Set([...Object.keys(e ?? {}), ...Object.keys(n)])) {
21
+ let o = u(e?.[a], t[a]) ? n[a] : e?.[a];
22
+ i(o) || (r[a] = o);
23
+ }
24
+ return r;
25
+ };
26
+ export { c as customDataOf, l as metadataOfAsset, o as metadataOnServer, d as rebaseCustomData, u as sameMetadataValue, s as setMetadataOnServer };
27
+
28
+ //# sourceMappingURL=damMetadataOnServer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"damMetadataOnServer.js","names":["toRaw","cloneDeep","isArray","isObject","isUndefined","known","metadataOnServer","of","setMetadataOnServer","metadata","customDataOf","value","metadataOfAsset","asset","sameMetadataValue","one","other","index","a","b","key","rebaseCustomData","mine","base","theirs","rebased"],"sources":["../../../../src/domains/dam/api/damMetadataOnServer.ts"],"sourcesContent":["import { toRaw } from 'vue'\nimport type { DocId } from '@/shared/types/common'\nimport type { AssetCustomData, AssetDetailItemDto } from '@/domains/dam/types/Asset'\nimport { cloneDeep, isArray, isObject, isUndefined } from '@/shared/utils/common'\n\n/**\n * The metadata a save of a queue row or of the asset detail edits, as the DAM had them when last read or saved.\n * The DAM keeps a field a save leaves out, but deletes a custom field left out of the custom data. So a save\n * sends only the fields changed against this, and changed custom data rebased onto the asset read right before.\n * Sending the rest as loaded would put back or delete what another editor saved meanwhile.\n */\nexport interface DamMetadataOnServer {\n keywords: DocId[]\n authors: DocId[]\n sources: DocId[]\n customData: AssetCustomData\n mainFileSingleUse: boolean | null\n}\n\n// Keyed by the queue row or the asset object of the detail. Unknown for one never read here: that one is sent whole.\nconst known = new WeakMap<object, DamMetadataOnServer>()\n\nexport const metadataOnServer = (of: object) => known.get(toRaw(of))\n\nexport const setMetadataOnServer = (of: object, metadata: DamMetadataOnServer) => {\n known.set(toRaw(of), cloneDeep(metadata))\n}\n\nexport const forgetMetadataOnServer = (of: object) => {\n known.delete(toRaw(of))\n}\n\n// The DAM writes empty custom data as an empty list.\nexport const customDataOf = (value: unknown): AssetCustomData => (isObject(value) && !isArray(value) ? value : {})\n\n// Missing parts read as empty: a host may hand over a shortened asset.\nexport const metadataOfAsset = (\n asset: Partial<Pick<AssetDetailItemDto, 'keywords' | 'authors' | 'sources' | 'mainFileSingleUse'>> & {\n metadata?: { customData?: unknown }\n }\n): DamMetadataOnServer => ({\n keywords: asset.keywords ?? [],\n authors: asset.authors ?? [],\n sources: asset.sources ?? [],\n customData: customDataOf(asset.metadata?.customData),\n mainFileSingleUse: asset.mainFileSingleUse ?? null,\n})\n\n/**\n * Equality as the DAM sees it: lists by values in order, objects by keys.\n * A key with no value equals a missing key, as it is not sent.\n */\nexport const sameMetadataValue = (one: unknown, other: unknown): boolean => {\n if (one === other) return true\n if (isArray(one) || isArray(other)) {\n return (\n isArray(one) &&\n isArray(other) &&\n one.length === other.length &&\n one.every((value, index) => sameMetadataValue(value, other[index]))\n )\n }\n if (!isObject(one) || !isObject(other)) return false\n const a = one as Record<string, unknown>\n const b = other as Record<string, unknown>\n\n return [...new Set([...Object.keys(a), ...Object.keys(b)])].every((key) => sameMetadataValue(a[key], b[key]))\n}\n\n/**\n * Custom data `mine` rebased onto `theirs`: keys `mine` changed against `base` keep its value, all other keys take\n * the value of `theirs`, which can be another editor's. A key without a value is left out.\n * A key both changed keeps `mine`: the later save wins.\n */\nexport const rebaseCustomData = (\n mine: AssetCustomData,\n base: AssetCustomData,\n theirs: AssetCustomData\n): AssetCustomData => {\n const rebased: AssetCustomData = {}\n for (const key of new Set([...Object.keys(mine ?? {}), ...Object.keys(theirs)])) {\n const value = sameMetadataValue(mine?.[key], base[key]) ? theirs[key] : mine?.[key]\n if (!isUndefined(value)) rebased[key] = value\n }\n\n return rebased\n}\n"],"mappings":";;;AAoBA,IAAMK,oBAAQ,IAAI,QAAqC,GAE1CC,KAAoBC,MAAeF,EAAM,IAAIL,EAAMO,CAAE,CAAC,GAEtDC,KAAuBD,GAAYE,MAAkC;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