@sankhyalabs/sankhyablocks 2.9.0 → 2.10.0

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.
@@ -241,6 +241,13 @@ class DataUnitFetcher {
241
241
  type
242
242
  expression
243
243
  }
244
+ },
245
+ children{
246
+ name
247
+ links{
248
+ source
249
+ target
250
+ }
244
251
  }
245
252
  children{
246
253
  name
@@ -251,9 +258,9 @@ class DataUnitFetcher {
251
258
  }
252
259
  }
253
260
  }`);
254
- this.templateByQuery.set("fetchData", ConfigStorage.dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!]) {
261
+ this.templateByQuery.set("fetchData", ConfigStorage.dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
255
262
  $queryAlias$: fetchDataUnit(name: $dataunit){
256
- data(limit: $limit offset: $offset filters: $filters sort: $sort){
263
+ data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId){
257
264
  limit
258
265
  offset
259
266
  total
@@ -290,8 +297,8 @@ class DataUnitFetcher {
290
297
  }
291
298
  }`);
292
299
  }
293
- getDataUnit(entityName, resourceID) {
294
- const dataUnit = new core.DataUnit(`dd://${entityName}/${resourceID}`);
300
+ getDataUnit(entityName, resourceID, parentDataUnit) {
301
+ const dataUnit = parentDataUnit != undefined ? parentDataUnit.getChildDataunit(`dd://${entityName}/${resourceID}`) : new core.DataUnit(`dd://${entityName}/${resourceID}`);
295
302
  dataUnit.metadataLoader = (dataUnit) => this.loadMetadata(dataUnit);
296
303
  dataUnit.dataLoader = (dataUnit, request) => this.loadData(dataUnit, request);
297
304
  dataUnit.saveLoader = (dataUnit, changes) => this.saveData(dataUnit, changes);
@@ -354,6 +361,7 @@ class DataUnitFetcher {
354
361
  const variables = { dataunit: dataUnit.name, sort, filters };
355
362
  variables.limit = limit;
356
363
  variables.offset = offset;
364
+ variables.parentRecordId = request.parentRecordId;
357
365
  if (!core.StringUtils.isEmpty(quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.term)) {
358
366
  if (variables.filter === undefined) {
359
367
  variables.filter = [];
@@ -421,6 +429,9 @@ class DataUnitFetcher {
421
429
  if (change.sourceId) {
422
430
  reqChange.sourceId = change.sourceId;
423
431
  }
432
+ if (record.__parent__record__id__) {
433
+ reqChange.parentRecordId = record.__parent__record__id__;
434
+ }
424
435
  return reqChange;
425
436
  });
426
437
  return new Promise((resolve, reject) => {
@@ -918,13 +929,13 @@ const SnkApplication = class {
918
929
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache
919
930
  * passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
920
931
  */
921
- async createDataunit(entityName, dataUnitName) {
932
+ async createDataunit(entityName, dataUnitName, parentDataUnit) {
922
933
  return new Promise((resolve, reject) => {
923
934
  const duPromisses = this.getDuPromissesStack(dataUnitName);
924
935
  const waitingDu = duPromisses.length > 0;
925
936
  duPromisses.push(new PendingPromise(resolve, reject));
926
937
  if (!waitingDu) {
927
- const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID);
938
+ const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID, parentDataUnit);
928
939
  dataUnit.loadMetadata().then(() => {
929
940
  if (dataUnitName) {
930
941
  this._duCache.set(dataUnitName, dataUnit);
@@ -943,14 +954,14 @@ const SnkApplication = class {
943
954
  /**
944
955
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
945
956
  */
946
- async getDataUnit(entityName, dataUnitName) {
957
+ async getDataUnit(entityName, dataUnitName, parentDataUnit) {
947
958
  return new Promise((resolve, reject) => {
948
959
  const dataUnit = this._duCache.get(dataUnitName);
949
960
  if (dataUnit) {
950
961
  resolve(dataUnit);
951
962
  }
952
963
  else {
953
- this.createDataunit(entityName, dataUnitName).then(dataUnit => {
964
+ this.createDataunit(entityName, dataUnitName, parentDataUnit).then(dataUnit => {
954
965
  resolve(dataUnit);
955
966
  }).catch(reason => reject(reason));
956
967
  }
@@ -12,10 +12,10 @@ const snkDataUnitCss = ".sc-snk-data-unit-h{display:flex;flex-direction:column;h
12
12
  const SnkDataUnit = class {
13
13
  constructor(hostRef) {
14
14
  index.registerInstance(this, hostRef);
15
- this.dataStateChange = index.createEvent(this, "dataStateChange", 7);
16
- this.dataUnitReady = index.createEvent(this, "dataUnitReady", 7);
17
- this.insertionMode = index.createEvent(this, "insertionMode", 7);
18
- this.cancelEdition = index.createEvent(this, "cancelEdition", 7);
15
+ this.dataStateChange = index.createEvent(this, "dataStateChange", 3);
16
+ this.dataUnitReady = index.createEvent(this, "dataUnitReady", 3);
17
+ this.insertionMode = index.createEvent(this, "insertionMode", 3);
18
+ this.cancelEdition = index.createEvent(this, "cancelEdition", 3);
19
19
  this._onDataUnitResolve = [];
20
20
  /**
21
21
  * Determina quantas linhas são retornadas por página.
@@ -29,12 +29,13 @@ const SnkDataUnit = class {
29
29
  copyMode: false,
30
30
  isDirty: this.dataUnit.isDirty(),
31
31
  hasDirtyRecords: this.dataUnit.hasDirtyRecords(),
32
- selectedRecords: this.dataUnit.getSelectedRecords()
32
+ selectedRecords: this.dataUnit.getSelectedRecords(),
33
+ selectedRecord: this.dataUnit.getSelectedRecord()
33
34
  };
34
- this.dataUnit.records.forEach(r => {
35
- if (r.__record__id__.startsWith('NEW_')) {
35
+ this.dataUnit.records.forEach(record => {
36
+ if (record.__record__id__.startsWith('NEW_')) {
36
37
  duState.insertionMode = true;
37
- duState.copyMode || (duState.copyMode = r['__record__source__id__'] != undefined);
38
+ duState.copyMode || (duState.copyMode = record['__record__source__id__'] != undefined);
38
39
  }
39
40
  });
40
41
  this.dataState = duState;
@@ -88,6 +89,7 @@ const SnkDataUnit = class {
88
89
  }
89
90
  }
90
91
  observeDataUnit() {
92
+ this.handlerLinkFields();
91
93
  this.dataUnitReady.emit(this.dataUnit);
92
94
  }
93
95
  /**
@@ -233,11 +235,21 @@ const SnkDataUnit = class {
233
235
  }
234
236
  return SnkMessageBuilder.OperationMap.CLEAN;
235
237
  }
238
+ async getDataUnitParentOrChild() {
239
+ var _a;
240
+ const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
241
+ if (this._parentSnkDataUnit) {
242
+ this._parentDataUnit = await ((_a = this._parentSnkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
243
+ return await this._application.getDataUnit(this.entityName, undefined, this._parentDataUnit);
244
+ }
245
+ else {
246
+ return await this._application.getDataUnit(this.entityName, cacheName);
247
+ }
248
+ }
236
249
  async loadDataUnit() {
237
250
  if (!this.dataUnit) {
238
251
  if (this._application && this.entityName) {
239
- const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
240
- this.dataUnit = await this._application.getDataUnit(this.entityName, cacheName);
252
+ this.dataUnit = await this.getDataUnitParentOrChild();
241
253
  this.dataUnit.pageSize = this.pageSize;
242
254
  this.dataUnit.unsubscribe(this._dataUnitObserver);
243
255
  this.dataUnit.addInterceptor(this);
@@ -249,12 +261,39 @@ const SnkDataUnit = class {
249
261
  }
250
262
  }
251
263
  }
264
+ getParentSnkDataUnit() {
265
+ let currentElement = this.element;
266
+ while (currentElement.parentNode) {
267
+ if (currentElement.parentNode.nodeName === 'SNK-DATA-UNIT') {
268
+ return currentElement.parentNode;
269
+ }
270
+ currentElement = currentElement.parentNode;
271
+ }
272
+ return;
273
+ }
274
+ handlerLinkFields() {
275
+ var _a, _b;
276
+ const metadata = Object.assign({}, this.dataUnit.metadata);
277
+ if (!this._parentDataUnit)
278
+ return;
279
+ const child = this._parentDataUnit.getChildInfo(this.entityName);
280
+ if (!child)
281
+ return;
282
+ const fieldsLink = (_a = child === null || child === void 0 ? void 0 : child.links) === null || _a === void 0 ? void 0 : _a.map(link => link.target);
283
+ (_b = metadata === null || metadata === void 0 ? void 0 : metadata.fields) === null || _b === void 0 ? void 0 : _b.forEach(field => {
284
+ if (fieldsLink === null || fieldsLink === void 0 ? void 0 : fieldsLink.includes(field.name)) {
285
+ field.visible = false;
286
+ }
287
+ });
288
+ this.dataUnit.metadata = metadata;
289
+ }
252
290
  //---------------------------------------------
253
291
  // Lifecycle web component
254
292
  //---------------------------------------------
255
293
  componentWillLoad() {
256
294
  this._application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
257
295
  this._application.getAllAccess().then(access => this._permissions = access);
296
+ this._parentSnkDataUnit = this.getParentSnkDataUnit();
258
297
  }
259
298
  componentDidLoad() {
260
299
  this.loadDataUnit();
@@ -270,13 +270,13 @@ export class SnkApplication {
270
270
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache
271
271
  * passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
272
272
  */
273
- async createDataunit(entityName, dataUnitName) {
273
+ async createDataunit(entityName, dataUnitName, parentDataUnit) {
274
274
  return new Promise((resolve, reject) => {
275
275
  const duPromisses = this.getDuPromissesStack(dataUnitName);
276
276
  const waitingDu = duPromisses.length > 0;
277
277
  duPromisses.push(new PendingPromise(resolve, reject));
278
278
  if (!waitingDu) {
279
- const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID);
279
+ const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID, parentDataUnit);
280
280
  dataUnit.loadMetadata().then(() => {
281
281
  if (dataUnitName) {
282
282
  this._duCache.set(dataUnitName, dataUnit);
@@ -295,14 +295,14 @@ export class SnkApplication {
295
295
  /**
296
296
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
297
297
  */
298
- async getDataUnit(entityName, dataUnitName) {
298
+ async getDataUnit(entityName, dataUnitName, parentDataUnit) {
299
299
  return new Promise((resolve, reject) => {
300
300
  const dataUnit = this._duCache.get(dataUnitName);
301
301
  if (dataUnit) {
302
302
  resolve(dataUnit);
303
303
  }
304
304
  else {
305
- this.createDataunit(entityName, dataUnitName).then(dataUnit => {
305
+ this.createDataunit(entityName, dataUnitName, parentDataUnit).then(dataUnit => {
306
306
  resolve(dataUnit);
307
307
  }).catch(reason => reject(reason));
308
308
  }
@@ -1075,13 +1075,16 @@ export class SnkApplication {
1075
1075
  },
1076
1076
  "createDataunit": {
1077
1077
  "complexType": {
1078
- "signature": "(entityName: string, dataUnitName?: string) => Promise<DataUnit>",
1078
+ "signature": "(entityName: string, dataUnitName?: string, parentDataUnit?: DataUnit) => Promise<DataUnit>",
1079
1079
  "parameters": [{
1080
1080
  "tags": [],
1081
1081
  "text": ""
1082
1082
  }, {
1083
1083
  "tags": [],
1084
1084
  "text": ""
1085
+ }, {
1086
+ "tags": [],
1087
+ "text": ""
1085
1088
  }],
1086
1089
  "references": {
1087
1090
  "Promise": {
@@ -1101,13 +1104,16 @@ export class SnkApplication {
1101
1104
  },
1102
1105
  "getDataUnit": {
1103
1106
  "complexType": {
1104
- "signature": "(entityName: string, dataUnitName: string) => Promise<DataUnit>",
1107
+ "signature": "(entityName: string, dataUnitName: string, parentDataUnit?: DataUnit) => Promise<DataUnit>",
1105
1108
  "parameters": [{
1106
1109
  "tags": [],
1107
1110
  "text": ""
1108
1111
  }, {
1109
1112
  "tags": [],
1110
1113
  "text": ""
1114
+ }, {
1115
+ "tags": [],
1116
+ "text": ""
1111
1117
  }],
1112
1118
  "references": {
1113
1119
  "Promise": {
@@ -17,12 +17,13 @@ export class SnkDataUnit {
17
17
  copyMode: false,
18
18
  isDirty: this.dataUnit.isDirty(),
19
19
  hasDirtyRecords: this.dataUnit.hasDirtyRecords(),
20
- selectedRecords: this.dataUnit.getSelectedRecords()
20
+ selectedRecords: this.dataUnit.getSelectedRecords(),
21
+ selectedRecord: this.dataUnit.getSelectedRecord()
21
22
  };
22
- this.dataUnit.records.forEach(r => {
23
- if (r.__record__id__.startsWith('NEW_')) {
23
+ this.dataUnit.records.forEach(record => {
24
+ if (record.__record__id__.startsWith('NEW_')) {
24
25
  duState.insertionMode = true;
25
- duState.copyMode || (duState.copyMode = r['__record__source__id__'] != undefined);
26
+ duState.copyMode || (duState.copyMode = record['__record__source__id__'] != undefined);
26
27
  }
27
28
  });
28
29
  this.dataState = duState;
@@ -76,6 +77,7 @@ export class SnkDataUnit {
76
77
  }
77
78
  }
78
79
  observeDataUnit() {
80
+ this.handlerLinkFields();
79
81
  this.dataUnitReady.emit(this.dataUnit);
80
82
  }
81
83
  /**
@@ -221,11 +223,21 @@ export class SnkDataUnit {
221
223
  }
222
224
  return OperationMap.CLEAN;
223
225
  }
226
+ async getDataUnitParentOrChild() {
227
+ var _a;
228
+ const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
229
+ if (this._parentSnkDataUnit) {
230
+ this._parentDataUnit = await ((_a = this._parentSnkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
231
+ return await this._application.getDataUnit(this.entityName, undefined, this._parentDataUnit);
232
+ }
233
+ else {
234
+ return await this._application.getDataUnit(this.entityName, cacheName);
235
+ }
236
+ }
224
237
  async loadDataUnit() {
225
238
  if (!this.dataUnit) {
226
239
  if (this._application && this.entityName) {
227
- const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
228
- this.dataUnit = await this._application.getDataUnit(this.entityName, cacheName);
240
+ this.dataUnit = await this.getDataUnitParentOrChild();
229
241
  this.dataUnit.pageSize = this.pageSize;
230
242
  this.dataUnit.unsubscribe(this._dataUnitObserver);
231
243
  this.dataUnit.addInterceptor(this);
@@ -237,12 +249,39 @@ export class SnkDataUnit {
237
249
  }
238
250
  }
239
251
  }
252
+ getParentSnkDataUnit() {
253
+ let currentElement = this.element;
254
+ while (currentElement.parentNode) {
255
+ if (currentElement.parentNode.nodeName === 'SNK-DATA-UNIT') {
256
+ return currentElement.parentNode;
257
+ }
258
+ currentElement = currentElement.parentNode;
259
+ }
260
+ return;
261
+ }
262
+ handlerLinkFields() {
263
+ var _a, _b;
264
+ const metadata = Object.assign({}, this.dataUnit.metadata);
265
+ if (!this._parentDataUnit)
266
+ return;
267
+ const child = this._parentDataUnit.getChildInfo(this.entityName);
268
+ if (!child)
269
+ return;
270
+ const fieldsLink = (_a = child === null || child === void 0 ? void 0 : child.links) === null || _a === void 0 ? void 0 : _a.map(link => link.target);
271
+ (_b = metadata === null || metadata === void 0 ? void 0 : metadata.fields) === null || _b === void 0 ? void 0 : _b.forEach(field => {
272
+ if (fieldsLink === null || fieldsLink === void 0 ? void 0 : fieldsLink.includes(field.name)) {
273
+ field.visible = false;
274
+ }
275
+ });
276
+ this.dataUnit.metadata = metadata;
277
+ }
240
278
  //---------------------------------------------
241
279
  // Lifecycle web component
242
280
  //---------------------------------------------
243
281
  componentWillLoad() {
244
282
  this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
245
283
  this._application.getAllAccess().then(access => this._permissions = access);
284
+ this._parentSnkDataUnit = this.getParentSnkDataUnit();
246
285
  }
247
286
  componentDidLoad() {
248
287
  this.loadDataUnit();
@@ -404,7 +443,7 @@ export class SnkDataUnit {
404
443
  return [{
405
444
  "method": "dataStateChange",
406
445
  "name": "dataStateChange",
407
- "bubbles": true,
446
+ "bubbles": false,
408
447
  "cancelable": true,
409
448
  "composed": true,
410
449
  "docs": {
@@ -423,7 +462,7 @@ export class SnkDataUnit {
423
462
  }, {
424
463
  "method": "dataUnitReady",
425
464
  "name": "dataUnitReady",
426
- "bubbles": true,
465
+ "bubbles": false,
427
466
  "cancelable": true,
428
467
  "composed": true,
429
468
  "docs": {
@@ -443,7 +482,7 @@ export class SnkDataUnit {
443
482
  }, {
444
483
  "method": "insertionMode",
445
484
  "name": "insertionMode",
446
- "bubbles": true,
485
+ "bubbles": false,
447
486
  "cancelable": true,
448
487
  "composed": true,
449
488
  "docs": {
@@ -458,7 +497,7 @@ export class SnkDataUnit {
458
497
  }, {
459
498
  "method": "cancelEdition",
460
499
  "name": "cancelEdition",
461
- "bubbles": true,
500
+ "bubbles": false,
462
501
  "cancelable": true,
463
502
  "composed": true,
464
503
  "docs": {
@@ -31,6 +31,13 @@ export default class DataUnitFetcher {
31
31
  type
32
32
  expression
33
33
  }
34
+ },
35
+ children{
36
+ name
37
+ links{
38
+ source
39
+ target
40
+ }
34
41
  }
35
42
  children{
36
43
  name
@@ -41,9 +48,9 @@ export default class DataUnitFetcher {
41
48
  }
42
49
  }
43
50
  }`);
44
- this.templateByQuery.set("fetchData", gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!]) {
51
+ this.templateByQuery.set("fetchData", gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
45
52
  $queryAlias$: fetchDataUnit(name: $dataunit){
46
- data(limit: $limit offset: $offset filters: $filters sort: $sort){
53
+ data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId){
47
54
  limit
48
55
  offset
49
56
  total
@@ -80,8 +87,8 @@ export default class DataUnitFetcher {
80
87
  }
81
88
  }`);
82
89
  }
83
- getDataUnit(entityName, resourceID) {
84
- const dataUnit = new DataUnit(`dd://${entityName}/${resourceID}`);
90
+ getDataUnit(entityName, resourceID, parentDataUnit) {
91
+ const dataUnit = parentDataUnit != undefined ? parentDataUnit.getChildDataunit(`dd://${entityName}/${resourceID}`) : new DataUnit(`dd://${entityName}/${resourceID}`);
85
92
  dataUnit.metadataLoader = (dataUnit) => this.loadMetadata(dataUnit);
86
93
  dataUnit.dataLoader = (dataUnit, request) => this.loadData(dataUnit, request);
87
94
  dataUnit.saveLoader = (dataUnit, changes) => this.saveData(dataUnit, changes);
@@ -144,6 +151,7 @@ export default class DataUnitFetcher {
144
151
  const variables = { dataunit: dataUnit.name, sort, filters };
145
152
  variables.limit = limit;
146
153
  variables.offset = offset;
154
+ variables.parentRecordId = request.parentRecordId;
147
155
  if (!StringUtils.isEmpty(quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.term)) {
148
156
  if (variables.filter === undefined) {
149
157
  variables.filter = [];
@@ -211,6 +219,9 @@ export default class DataUnitFetcher {
211
219
  if (change.sourceId) {
212
220
  reqChange.sourceId = change.sourceId;
213
221
  }
222
+ if (record.__parent__record__id__) {
223
+ reqChange.parentRecordId = record.__parent__record__id__;
224
+ }
214
225
  return reqChange;
215
226
  });
216
227
  return new Promise((resolve, reject) => {
@@ -238,6 +238,13 @@ class DataUnitFetcher {
238
238
  type
239
239
  expression
240
240
  }
241
+ },
242
+ children{
243
+ name
244
+ links{
245
+ source
246
+ target
247
+ }
241
248
  }
242
249
  children{
243
250
  name
@@ -248,9 +255,9 @@ class DataUnitFetcher {
248
255
  }
249
256
  }
250
257
  }`);
251
- this.templateByQuery.set("fetchData", dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!]) {
258
+ this.templateByQuery.set("fetchData", dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
252
259
  $queryAlias$: fetchDataUnit(name: $dataunit){
253
- data(limit: $limit offset: $offset filters: $filters sort: $sort){
260
+ data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId){
254
261
  limit
255
262
  offset
256
263
  total
@@ -287,8 +294,8 @@ class DataUnitFetcher {
287
294
  }
288
295
  }`);
289
296
  }
290
- getDataUnit(entityName, resourceID) {
291
- const dataUnit = new DataUnit(`dd://${entityName}/${resourceID}`);
297
+ getDataUnit(entityName, resourceID, parentDataUnit) {
298
+ const dataUnit = parentDataUnit != undefined ? parentDataUnit.getChildDataunit(`dd://${entityName}/${resourceID}`) : new DataUnit(`dd://${entityName}/${resourceID}`);
292
299
  dataUnit.metadataLoader = (dataUnit) => this.loadMetadata(dataUnit);
293
300
  dataUnit.dataLoader = (dataUnit, request) => this.loadData(dataUnit, request);
294
301
  dataUnit.saveLoader = (dataUnit, changes) => this.saveData(dataUnit, changes);
@@ -351,6 +358,7 @@ class DataUnitFetcher {
351
358
  const variables = { dataunit: dataUnit.name, sort, filters };
352
359
  variables.limit = limit;
353
360
  variables.offset = offset;
361
+ variables.parentRecordId = request.parentRecordId;
354
362
  if (!StringUtils.isEmpty(quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.term)) {
355
363
  if (variables.filter === undefined) {
356
364
  variables.filter = [];
@@ -418,6 +426,9 @@ class DataUnitFetcher {
418
426
  if (change.sourceId) {
419
427
  reqChange.sourceId = change.sourceId;
420
428
  }
429
+ if (record.__parent__record__id__) {
430
+ reqChange.parentRecordId = record.__parent__record__id__;
431
+ }
421
432
  return reqChange;
422
433
  });
423
434
  return new Promise((resolve, reject) => {
@@ -916,13 +927,13 @@ const SnkApplication = /*@__PURE__*/ proxyCustomElement(class extends HTMLElemen
916
927
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache
917
928
  * passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
918
929
  */
919
- async createDataunit(entityName, dataUnitName) {
930
+ async createDataunit(entityName, dataUnitName, parentDataUnit) {
920
931
  return new Promise((resolve, reject) => {
921
932
  const duPromisses = this.getDuPromissesStack(dataUnitName);
922
933
  const waitingDu = duPromisses.length > 0;
923
934
  duPromisses.push(new PendingPromise(resolve, reject));
924
935
  if (!waitingDu) {
925
- const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID);
936
+ const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID, parentDataUnit);
926
937
  dataUnit.loadMetadata().then(() => {
927
938
  if (dataUnitName) {
928
939
  this._duCache.set(dataUnitName, dataUnit);
@@ -941,14 +952,14 @@ const SnkApplication = /*@__PURE__*/ proxyCustomElement(class extends HTMLElemen
941
952
  /**
942
953
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
943
954
  */
944
- async getDataUnit(entityName, dataUnitName) {
955
+ async getDataUnit(entityName, dataUnitName, parentDataUnit) {
945
956
  return new Promise((resolve, reject) => {
946
957
  const dataUnit = this._duCache.get(dataUnitName);
947
958
  if (dataUnit) {
948
959
  resolve(dataUnit);
949
960
  }
950
961
  else {
951
- this.createDataunit(entityName, dataUnitName).then(dataUnit => {
962
+ this.createDataunit(entityName, dataUnitName, parentDataUnit).then(dataUnit => {
952
963
  resolve(dataUnit);
953
964
  }).catch(reason => reject(reason));
954
965
  }
@@ -9,10 +9,10 @@ const SnkDataUnit$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement
9
9
  constructor() {
10
10
  super();
11
11
  this.__registerHost();
12
- this.dataStateChange = createEvent(this, "dataStateChange", 7);
13
- this.dataUnitReady = createEvent(this, "dataUnitReady", 7);
14
- this.insertionMode = createEvent(this, "insertionMode", 7);
15
- this.cancelEdition = createEvent(this, "cancelEdition", 7);
12
+ this.dataStateChange = createEvent(this, "dataStateChange", 3);
13
+ this.dataUnitReady = createEvent(this, "dataUnitReady", 3);
14
+ this.insertionMode = createEvent(this, "insertionMode", 3);
15
+ this.cancelEdition = createEvent(this, "cancelEdition", 3);
16
16
  this._onDataUnitResolve = [];
17
17
  /**
18
18
  * Determina quantas linhas são retornadas por página.
@@ -26,12 +26,13 @@ const SnkDataUnit$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement
26
26
  copyMode: false,
27
27
  isDirty: this.dataUnit.isDirty(),
28
28
  hasDirtyRecords: this.dataUnit.hasDirtyRecords(),
29
- selectedRecords: this.dataUnit.getSelectedRecords()
29
+ selectedRecords: this.dataUnit.getSelectedRecords(),
30
+ selectedRecord: this.dataUnit.getSelectedRecord()
30
31
  };
31
- this.dataUnit.records.forEach(r => {
32
- if (r.__record__id__.startsWith('NEW_')) {
32
+ this.dataUnit.records.forEach(record => {
33
+ if (record.__record__id__.startsWith('NEW_')) {
33
34
  duState.insertionMode = true;
34
- duState.copyMode || (duState.copyMode = r['__record__source__id__'] != undefined);
35
+ duState.copyMode || (duState.copyMode = record['__record__source__id__'] != undefined);
35
36
  }
36
37
  });
37
38
  this.dataState = duState;
@@ -85,6 +86,7 @@ const SnkDataUnit$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement
85
86
  }
86
87
  }
87
88
  observeDataUnit() {
89
+ this.handlerLinkFields();
88
90
  this.dataUnitReady.emit(this.dataUnit);
89
91
  }
90
92
  /**
@@ -230,11 +232,21 @@ const SnkDataUnit$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement
230
232
  }
231
233
  return OperationMap.CLEAN;
232
234
  }
235
+ async getDataUnitParentOrChild() {
236
+ var _a;
237
+ const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
238
+ if (this._parentSnkDataUnit) {
239
+ this._parentDataUnit = await ((_a = this._parentSnkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
240
+ return await this._application.getDataUnit(this.entityName, undefined, this._parentDataUnit);
241
+ }
242
+ else {
243
+ return await this._application.getDataUnit(this.entityName, cacheName);
244
+ }
245
+ }
233
246
  async loadDataUnit() {
234
247
  if (!this.dataUnit) {
235
248
  if (this._application && this.entityName) {
236
- const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
237
- this.dataUnit = await this._application.getDataUnit(this.entityName, cacheName);
249
+ this.dataUnit = await this.getDataUnitParentOrChild();
238
250
  this.dataUnit.pageSize = this.pageSize;
239
251
  this.dataUnit.unsubscribe(this._dataUnitObserver);
240
252
  this.dataUnit.addInterceptor(this);
@@ -246,12 +258,39 @@ const SnkDataUnit$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement
246
258
  }
247
259
  }
248
260
  }
261
+ getParentSnkDataUnit() {
262
+ let currentElement = this.element;
263
+ while (currentElement.parentNode) {
264
+ if (currentElement.parentNode.nodeName === 'SNK-DATA-UNIT') {
265
+ return currentElement.parentNode;
266
+ }
267
+ currentElement = currentElement.parentNode;
268
+ }
269
+ return;
270
+ }
271
+ handlerLinkFields() {
272
+ var _a, _b;
273
+ const metadata = Object.assign({}, this.dataUnit.metadata);
274
+ if (!this._parentDataUnit)
275
+ return;
276
+ const child = this._parentDataUnit.getChildInfo(this.entityName);
277
+ if (!child)
278
+ return;
279
+ const fieldsLink = (_a = child === null || child === void 0 ? void 0 : child.links) === null || _a === void 0 ? void 0 : _a.map(link => link.target);
280
+ (_b = metadata === null || metadata === void 0 ? void 0 : metadata.fields) === null || _b === void 0 ? void 0 : _b.forEach(field => {
281
+ if (fieldsLink === null || fieldsLink === void 0 ? void 0 : fieldsLink.includes(field.name)) {
282
+ field.visible = false;
283
+ }
284
+ });
285
+ this.dataUnit.metadata = metadata;
286
+ }
249
287
  //---------------------------------------------
250
288
  // Lifecycle web component
251
289
  //---------------------------------------------
252
290
  componentWillLoad() {
253
291
  this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
254
292
  this._application.getAllAccess().then(access => this._permissions = access);
293
+ this._parentSnkDataUnit = this.getParentSnkDataUnit();
255
294
  }
256
295
  componentDidLoad() {
257
296
  this.loadDataUnit();
@@ -237,6 +237,13 @@ class DataUnitFetcher {
237
237
  type
238
238
  expression
239
239
  }
240
+ },
241
+ children{
242
+ name
243
+ links{
244
+ source
245
+ target
246
+ }
240
247
  }
241
248
  children{
242
249
  name
@@ -247,9 +254,9 @@ class DataUnitFetcher {
247
254
  }
248
255
  }
249
256
  }`);
250
- this.templateByQuery.set("fetchData", dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!]) {
257
+ this.templateByQuery.set("fetchData", dist.gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
251
258
  $queryAlias$: fetchDataUnit(name: $dataunit){
252
- data(limit: $limit offset: $offset filters: $filters sort: $sort){
259
+ data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId){
253
260
  limit
254
261
  offset
255
262
  total
@@ -286,8 +293,8 @@ class DataUnitFetcher {
286
293
  }
287
294
  }`);
288
295
  }
289
- getDataUnit(entityName, resourceID) {
290
- const dataUnit = new DataUnit(`dd://${entityName}/${resourceID}`);
296
+ getDataUnit(entityName, resourceID, parentDataUnit) {
297
+ const dataUnit = parentDataUnit != undefined ? parentDataUnit.getChildDataunit(`dd://${entityName}/${resourceID}`) : new DataUnit(`dd://${entityName}/${resourceID}`);
291
298
  dataUnit.metadataLoader = (dataUnit) => this.loadMetadata(dataUnit);
292
299
  dataUnit.dataLoader = (dataUnit, request) => this.loadData(dataUnit, request);
293
300
  dataUnit.saveLoader = (dataUnit, changes) => this.saveData(dataUnit, changes);
@@ -350,6 +357,7 @@ class DataUnitFetcher {
350
357
  const variables = { dataunit: dataUnit.name, sort, filters };
351
358
  variables.limit = limit;
352
359
  variables.offset = offset;
360
+ variables.parentRecordId = request.parentRecordId;
353
361
  if (!StringUtils.isEmpty(quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.term)) {
354
362
  if (variables.filter === undefined) {
355
363
  variables.filter = [];
@@ -417,6 +425,9 @@ class DataUnitFetcher {
417
425
  if (change.sourceId) {
418
426
  reqChange.sourceId = change.sourceId;
419
427
  }
428
+ if (record.__parent__record__id__) {
429
+ reqChange.parentRecordId = record.__parent__record__id__;
430
+ }
420
431
  return reqChange;
421
432
  });
422
433
  return new Promise((resolve, reject) => {
@@ -914,13 +925,13 @@ const SnkApplication = class {
914
925
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache
915
926
  * passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
916
927
  */
917
- async createDataunit(entityName, dataUnitName) {
928
+ async createDataunit(entityName, dataUnitName, parentDataUnit) {
918
929
  return new Promise((resolve, reject) => {
919
930
  const duPromisses = this.getDuPromissesStack(dataUnitName);
920
931
  const waitingDu = duPromisses.length > 0;
921
932
  duPromisses.push(new PendingPromise(resolve, reject));
922
933
  if (!waitingDu) {
923
- const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID);
934
+ const dataUnit = this.dataUnitFetcher.getDataUnit(entityName, this.resourceID, parentDataUnit);
924
935
  dataUnit.loadMetadata().then(() => {
925
936
  if (dataUnitName) {
926
937
  this._duCache.set(dataUnitName, dataUnit);
@@ -939,14 +950,14 @@ const SnkApplication = class {
939
950
  /**
940
951
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
941
952
  */
942
- async getDataUnit(entityName, dataUnitName) {
953
+ async getDataUnit(entityName, dataUnitName, parentDataUnit) {
943
954
  return new Promise((resolve, reject) => {
944
955
  const dataUnit = this._duCache.get(dataUnitName);
945
956
  if (dataUnit) {
946
957
  resolve(dataUnit);
947
958
  }
948
959
  else {
949
- this.createDataunit(entityName, dataUnitName).then(dataUnit => {
960
+ this.createDataunit(entityName, dataUnitName, parentDataUnit).then(dataUnit => {
950
961
  resolve(dataUnit);
951
962
  }).catch(reason => reject(reason));
952
963
  }
@@ -8,10 +8,10 @@ const snkDataUnitCss = ".sc-snk-data-unit-h{display:flex;flex-direction:column;h
8
8
  const SnkDataUnit = class {
9
9
  constructor(hostRef) {
10
10
  registerInstance(this, hostRef);
11
- this.dataStateChange = createEvent(this, "dataStateChange", 7);
12
- this.dataUnitReady = createEvent(this, "dataUnitReady", 7);
13
- this.insertionMode = createEvent(this, "insertionMode", 7);
14
- this.cancelEdition = createEvent(this, "cancelEdition", 7);
11
+ this.dataStateChange = createEvent(this, "dataStateChange", 3);
12
+ this.dataUnitReady = createEvent(this, "dataUnitReady", 3);
13
+ this.insertionMode = createEvent(this, "insertionMode", 3);
14
+ this.cancelEdition = createEvent(this, "cancelEdition", 3);
15
15
  this._onDataUnitResolve = [];
16
16
  /**
17
17
  * Determina quantas linhas são retornadas por página.
@@ -25,12 +25,13 @@ const SnkDataUnit = class {
25
25
  copyMode: false,
26
26
  isDirty: this.dataUnit.isDirty(),
27
27
  hasDirtyRecords: this.dataUnit.hasDirtyRecords(),
28
- selectedRecords: this.dataUnit.getSelectedRecords()
28
+ selectedRecords: this.dataUnit.getSelectedRecords(),
29
+ selectedRecord: this.dataUnit.getSelectedRecord()
29
30
  };
30
- this.dataUnit.records.forEach(r => {
31
- if (r.__record__id__.startsWith('NEW_')) {
31
+ this.dataUnit.records.forEach(record => {
32
+ if (record.__record__id__.startsWith('NEW_')) {
32
33
  duState.insertionMode = true;
33
- duState.copyMode || (duState.copyMode = r['__record__source__id__'] != undefined);
34
+ duState.copyMode || (duState.copyMode = record['__record__source__id__'] != undefined);
34
35
  }
35
36
  });
36
37
  this.dataState = duState;
@@ -84,6 +85,7 @@ const SnkDataUnit = class {
84
85
  }
85
86
  }
86
87
  observeDataUnit() {
88
+ this.handlerLinkFields();
87
89
  this.dataUnitReady.emit(this.dataUnit);
88
90
  }
89
91
  /**
@@ -229,11 +231,21 @@ const SnkDataUnit = class {
229
231
  }
230
232
  return OperationMap.CLEAN;
231
233
  }
234
+ async getDataUnitParentOrChild() {
235
+ var _a;
236
+ const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
237
+ if (this._parentSnkDataUnit) {
238
+ this._parentDataUnit = await ((_a = this._parentSnkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
239
+ return await this._application.getDataUnit(this.entityName, undefined, this._parentDataUnit);
240
+ }
241
+ else {
242
+ return await this._application.getDataUnit(this.entityName, cacheName);
243
+ }
244
+ }
232
245
  async loadDataUnit() {
233
246
  if (!this.dataUnit) {
234
247
  if (this._application && this.entityName) {
235
- const cacheName = this.dataUnitName ? this.dataUnitName : this.entityName;
236
- this.dataUnit = await this._application.getDataUnit(this.entityName, cacheName);
248
+ this.dataUnit = await this.getDataUnitParentOrChild();
237
249
  this.dataUnit.pageSize = this.pageSize;
238
250
  this.dataUnit.unsubscribe(this._dataUnitObserver);
239
251
  this.dataUnit.addInterceptor(this);
@@ -245,12 +257,39 @@ const SnkDataUnit = class {
245
257
  }
246
258
  }
247
259
  }
260
+ getParentSnkDataUnit() {
261
+ let currentElement = this.element;
262
+ while (currentElement.parentNode) {
263
+ if (currentElement.parentNode.nodeName === 'SNK-DATA-UNIT') {
264
+ return currentElement.parentNode;
265
+ }
266
+ currentElement = currentElement.parentNode;
267
+ }
268
+ return;
269
+ }
270
+ handlerLinkFields() {
271
+ var _a, _b;
272
+ const metadata = Object.assign({}, this.dataUnit.metadata);
273
+ if (!this._parentDataUnit)
274
+ return;
275
+ const child = this._parentDataUnit.getChildInfo(this.entityName);
276
+ if (!child)
277
+ return;
278
+ const fieldsLink = (_a = child === null || child === void 0 ? void 0 : child.links) === null || _a === void 0 ? void 0 : _a.map(link => link.target);
279
+ (_b = metadata === null || metadata === void 0 ? void 0 : metadata.fields) === null || _b === void 0 ? void 0 : _b.forEach(field => {
280
+ if (fieldsLink === null || fieldsLink === void 0 ? void 0 : fieldsLink.includes(field.name)) {
281
+ field.visible = false;
282
+ }
283
+ });
284
+ this.dataUnit.metadata = metadata;
285
+ }
248
286
  //---------------------------------------------
249
287
  // Lifecycle web component
250
288
  //---------------------------------------------
251
289
  componentWillLoad() {
252
290
  this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
253
291
  this._application.getAllAccess().then(access => this._permissions = access);
292
+ this._parentSnkDataUnit = this.getParentSnkDataUnit();
254
293
  }
255
294
  componentDidLoad() {
256
295
  this.loadDataUnit();
@@ -0,0 +1,90 @@
1
+ import{r as t,c as e,h as s,g as i}from"./p-a77dd79a.js";import{WaitingChangeException as r,WarningException as n,ErrorException as a,ObjectUtils as o,DataType as c,DataUnit as h,StringUtils as u,ChangeOperation as l,DateUtils as d,DependencyType as p,ElementIDUtils as m,ApplicationContext as f,ErrorTracking as y}from"@sankhyalabs/core";import{d as g,D as w,R as v,U as I,F as $,G as _,C as P}from"./p-93d8ea09.js";import{ApplicationUtils as S}from"@sankhyalabs/ezui/dist/collection/utils";import{S as D}from"./p-f624979d.js";import"./p-112455b1.js";class C{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const e=t.reason;e instanceof r||(e?this.processException(e):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t.errorCode+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t.errorCode+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t)),t instanceof r||t instanceof n?this._app.alert(t.title,t.message):t instanceof a?this._app.error(t.title,t.message):this._app.isDebugMode().then((e=>{if(e)if(t instanceof Error)this._app.error(t.name,t.message);else{const e=(null==t?void 0:t.title)||"Erro detectado",s="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(e,s)}}))}}class A{constructor(){this._defaultPageSize=100,this._templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this._templateByQuery.set("search",g.gql`query($entityName: String! $argument: String $criteria: InputSearchCriteria $options: InputSearchOptions) {
2
+ $queryAlias$: search(entityName: $entityName argument: $argument criteria: $criteria options: $options){
3
+ value
4
+ label
5
+ }
6
+ }`)}loadSearchOptions(t,e,s,i){const r=(null==e?void 0:e.trim())||void 0;return e=isNaN(Number(r))&&r?`%${r}`:r,new Promise(((r,n)=>{w.get().callGraphQL({values:{argument:e,entityName:t,criteria:s,options:i},query:this._templateByQuery.get("search")}).then((t=>{r(t)})).catch((t=>{n(t)}))}))}loadAdvancedSearch(t,e,s,i){const r={query:{$:null==s?void 0:s.expression}};(null==s?void 0:s.params.length)>0&&(r.params={param:s.params.map((t=>{let e=t.value,s=t.dataType;return s===c.OBJECT?(e=e.value,s="S"):s=function(t){switch(t){case c.NUMBER:return"I";case c.DATE:return"D";default:return"S"}}(t.dataType),{$:e,type:s}}))});const n={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:{entityName:t,compacted:!1,ignoreEntityCriteria:!1,limit:this._defaultPageSize,query:{$:e},orderByDesc:!1,externalCriteria:r,localEntityName:null==i?void 0:i.rootEntity},clientEventList:{clientEvent:[]}}};return new Promise(((t,e)=>{w.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(n)).then((e=>t(e))).catch((t=>e(t)))}))}}function T(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(T=function(){return t})()}const N=E;function E(t,e){const s=T();return(E=function(t){return s[t-=392]})(t,e)}!function(){const t=E,e=T();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const q=N(396);class b{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchTotals",g.gql`query($filters: [InputFilter!] $name: String!) {
7
+ $queryAlias$: fetchTotals(name: $name, filters: $filters ){
8
+ name
9
+ value
10
+ }
11
+ }`)}async getTotals(t,e,s){let i={name:`totals://${t}/${e}`,filters:s};return w.get().callGraphQL({values:i,query:this.templateByQuery.get("fetchTotals")})}fetchTotals(t,e,s=[]){return new Promise(((i,r)=>{this.getTotals(t,e,s).then((t=>{if(t.length>0){const e=new Map;t.forEach((t=>{e.set(t.name,parseFloat(t.value))})),i(e)}else r("Não foi possível recuperar os totalizadores")})).catch((t=>{r(t)}))}))}}class U{constructor(){this.templateByQuery=new Map,this._loadDataTimeout={},this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",g.gql`query($name: String!) {
12
+ $queryAlias$: fetchDataUnit(name: $name){
13
+ name
14
+ fields{
15
+ name
16
+ defaultValue
17
+ label
18
+ visible
19
+ readOnly
20
+ required
21
+ dataType
22
+ userInterface
23
+ calculated
24
+ group
25
+ properties{
26
+ name
27
+ value
28
+ }
29
+ dependencies{
30
+ masterFields
31
+ type
32
+ expression
33
+ }
34
+ },
35
+ children{
36
+ name
37
+ links{
38
+ source
39
+ target
40
+ }
41
+ }
42
+ children{
43
+ name
44
+ links{
45
+ source
46
+ target
47
+ }
48
+ }
49
+ }
50
+ }`),this.templateByQuery.set("fetchData",g.gql`query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
51
+ $queryAlias$: fetchDataUnit(name: $dataunit){
52
+ data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId){
53
+ limit
54
+ offset
55
+ total
56
+ hasMore
57
+ records{
58
+ id
59
+ fields {
60
+ name
61
+ value
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }`),this.templateByQuery.set("saveData",g.gql`mutation($changes: [InputBatchChange!]!) {
67
+ $queryAlias$: batchOperationDataUnit(changes: $changes){
68
+ oldId
69
+ id
70
+ fields {
71
+ name
72
+ value
73
+ }
74
+ }
75
+ }`),this.templateByQuery.set("fetchDataRecord",g.gql`query($dataunit: String! $recordID: [String!]) {
76
+ $queryAlias$: fetchDataUnit(name: $dataunit){
77
+ record(id: $recordID){
78
+ id
79
+ fields {
80
+ name
81
+ value
82
+ }
83
+ }
84
+ }
85
+ }`)}getDataUnit(t,e,s){const i=null!=s?s.getChildDataunit(`dd://${t}/${e}`):new h(`dd://${t}/${e}`);return i.metadataLoader=t=>this.loadMetadata(t),i.dataLoader=(t,e)=>this.loadData(t,e),i.saveLoader=(t,e)=>this.saveData(t,e),i.removeLoader=(t,e)=>this.removeRecords(t,e),i.recordLoader=(t,e)=>this.loadRecord(t,e),i}loadMetadata(t){return new Promise(((e,s)=>{w.get().callGraphQL({values:{name:t.name},query:this.templateByQuery.get("fetchDataUnit")}).then((t=>{var s;const i={name:t.name,label:t.name,children:[...t.children],fields:[]};null===(s=t.fields)||void 0===s||s.forEach((t=>{let e;Array.isArray(t.properties)&&(e={},t.calculated&&(e.gridHeaderTooltip="Campos calculados não podem ser ordenados"),t.properties.forEach((t=>e[t.name]=t.value))),i.fields.push(Object.assign(Object.assign({},t),{properties:e}))})),e(i)})).catch((t=>{s(t)}))}))}loadData(t,e){const s=t.name;return this._loadDataTimeout[s]&&(clearTimeout(this._loadDataTimeout[s]),delete this._loadDataTimeout[s]),new Promise(((i,r)=>{this._loadDataTimeout[s]=setTimeout((()=>{delete this._loadDataTimeout[s],this.doLoadData(t,e).then((t=>i(t))).catch((t=>r(t)))}),200)}))}doLoadData(t,e){return new Promise(((s,i)=>{var r;const{sort:n,filters:a,limit:o,offset:h,quickFilter:l}=e,d={dataunit:t.name,sort:n,filters:a};if(d.limit=o,d.offset=h,d.parentRecordId=e.parentRecordId,!u.isEmpty(null==l?void 0:l.term)){void 0===d.filter&&(d.filter=[]);const t={name:"__QUICK_FILTER__",expression:"__QUICK_FILTER__",params:[{name:"term",dataType:c.TEXT,value:l.term}]};(null===(r=null==l?void 0:l.fields)||void 0===r?void 0:r.length)>0&&t.params.push({name:"fields",dataType:c.OBJECT,value:l.fields}),d.filter.push(t)}w.get().callGraphQL({values:d,query:this.templateByQuery.get("fetchData")}).then((e=>{const{limit:i,offset:r,total:n,hasMore:a,records:o}=e.data;let c;i&&(c={firstRecord:0==n?0:r+1,lastRecord:r+Math.min(o.length,i),total:n,currentPage:r/i,hasMore:a});const h=[];o.forEach((e=>{const s={__record__id__:e.id};e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),h.push(s)})),s({paginationInfo:c,records:h})})).catch((t=>{i(t)}))}))}saveData(t,e){const s=e.map((e=>{const{dataUnit:s,record:i,updatingFields:r,operation:n}=e;let a;r&&(a=Object.entries(r).map((([e,s])=>{const i=t.getField(e);return{fieldName:e,dataType:i?i.dataType:c.TEXT,value:t.valueToString(e,s)}})));const o={dataUnit:s,fields:a,operation:n,recordId:i.__record__id__};return e.sourceId&&(o.sourceId=e.sourceId),i.__parent__record__id__&&(o.parentRecordId=i.__parent__record__id__),o}));return new Promise(((e,i)=>{w.get().callGraphQL({values:{changes:s},query:this.templateByQuery.get("saveData")}).then((s=>{const i=[];null==s||s.forEach((e=>{const s={__record__id__:e.id};e.oldId&&(s.__old__id__=e.oldId),e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),i.push(s)})),e(i)})).catch((t=>{i(t)}))}))}removeRecords(t,e){const s=e.map((e=>({dataUnit:t.name,operation:l.DELETE,recordId:e})));return new Promise(((t,i)=>{w.get().callGraphQL({values:{changes:s},query:this.templateByQuery.get("saveData")}).then((()=>{t(e)})).catch((t=>{i(t)}))}))}loadRecord(t,e){return new Promise(((s,i)=>{w.get().callGraphQL({values:{recordID:e,dataunit:t.name},query:this.templateByQuery.get("fetchDataRecord")}).then((e=>{const i=[];e.record.forEach((e=>{const s={__record__id__:e.id};e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),i.push(s)})),s(i)})).catch((t=>{i(t)}))}))}}var O;class F{static openAppActivity(t,e){var s;null===(s=window.workspace)||void 0===s||s.openAppActivity(t,e)}}F.resourceID=null===(O=window.workspace)||void 0===O?void 0:O.resourceID;class R{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",g.gql`query($name: String!) {
86
+ $queryAlias$: fetchResource(name: $name){
87
+ name
88
+ resource
89
+ }
90
+ }`)}async getParam(t){const e=`param://application?params=${t}`;return w.get().callGraphQL({values:{name:e},query:this.templateByQuery.get("fetchParam")})}async asString(t){const e=await this.getParam(t);return this.getValue(e)}async asInteger(t){const e=await this.getParam(t);return parseInt(this.getValue(e))}async asFloat(t){const e=await this.getParam(t);return parseFloat(this.getValue(e))}async asBoolean(t){const e=await this.getParam(t);return this.getValue(e).includes('"S"')}async asDate(t){const e=await this.getParam(t);return d.strToDate(this.getValue(e))}async getBatchParams(t){const e=await this.getParam(t.join(",")),s={};return e.forEach((t=>s[t.name]=t.resource)),s}getValue(t={}){return Array.isArray(t)&&t.length>0&&(t=t[0]),u.isEmpty(t.resource)?"":t.resource}}const L=k;function k(t,e){const s=j();return(k=function(t){return s[t-=378]})(t,e)}function j(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(j=function(){return t})()}!function(){const t=k,e=j();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;e.push(e.shift())}catch(t){e.push(e.shift())}}();class M{[L(397)](t){const e=L;if(typeof(t=utxt(t[e(390)]))==e(392)&&(t=JSON[e(400)](t)),null==t)throw Error(e(395));const s=new x("S"===t[e(402)]||!0===t[e(402)]);return Array[e(394)](t[e(391)])&&t[e(391)][e(385)]((t=>s.putAccess(t[e(382)],String(t.status)==e(398)))),s}}class x{constructor(t){const e=L;this.isSup=t,this[e(384)]={}}[L(378)](t,e){this[L(384)][t]=e}[L(393)](t){const e=L;if(this[e(402)])return!0;let s=!0;return this[e(384)][e(380)](t)&&(s=this.actions[t]),s}isUserSup(){return this.isSup}}class B extends v{getData(t){const e=`cfg://auth/${t}`;return new Promise(((t,s)=>{this.loadResource(e).then((e=>{let s=o.stringToObject(e);s&&"object"==typeof s&&t(s)})).catch((t=>{s(t)}))}))}}var z;function G(t){if(null==t)return t;if(t instanceof Date)return t.toISOString();if("object"==typeof t){if(t instanceof Array)return t.map((t=>G(t)));{const e=Object.assign({},t);return Object.keys(t).forEach((s=>{t[s]?e[s]=G(t[s]):delete e[s]})),e}}return t}!function(t){t.INSERT="I",t.UPDATE="A",t.REMOVE="E",t.SHOW="C",t.CONFIG="F",t.CONFIG_NUMBER="N",t.CLONE="D",t.CONFIG_GRID="G"}(z||(z={}));class J extends v{saveConfig(t,e,s){const i=t.map((t=>{const{id:e,value:s,fixed:i,visible:r}=t,n={id:e};return s&&(n.value=G(s)),i&&(n.fixed=i),r&&(n.visible=!0),n}));return this.saveResource(i,`cfg://filter/FilterBarState:${e}/${s}`)}getConfig(t,e){return new Promise(((s,i)=>{this.loadResource(`cfg://filter/FilterBarState:${t}/${e}`).then((t=>{let e;t&&(e=JSON.parse(t).items),s(e||[])})).catch((t=>{i(t)}))}))}}class H extends v{getDefaultValues(t){return new Promise(((e,s)=>{this.loadResource(`cfg://defaultValues/${t}`).then((t=>{let s;t&&(s=JSON.parse(t)),e(s)})).catch((t=>{s(t)}))}))}}const V=class{constructor(s){t(this,s),this.applicationLoaded=e(this,"applicationLoaded",7),this.applicationLoading=e(this,"applicationLoading",7),this._authPromises=[],this._duCache=new Map,this._duPromises=new Map,this._requestListener=new W}get parameters(){return this._parameters||(this._parameters=new R),this._parameters}get resourceID(){return this._resourceID||(this._resourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||F.resourceID||"unknown.resource.id"),this._resourceID}get auth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,e)=>{const s=this._authPromises.length>0;this._authPromises.push(new Z(t,e)),s||this.authFetcher.getData(this.resourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}async isUserSup(){return new Promise(((t,e)=>{this.auth.then((s=>{this.getAuthList(s).then((e=>{t(e.isSup)})).catch((t=>e(t)))}))}))}async hasAccess(t){return new Promise(((e,s)=>{this.auth.then((i=>{this.getAuthList(i).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>s(t)))}))}))}async getAllAccess(){return new Promise(((t,e)=>{this.auth.then((s=>{this.getAuthList(s).then((e=>{const s={};s.isSup=e.isSup,Object.entries(z).forEach((t=>{s[t[0]]=e.actions[t[1]]||!1})),t(s)})).catch((t=>e(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,e="full",s=!0){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=e,this._popUp.useHeader=s,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const e=t.split(",");return new Promise(((t,s)=>{this.getAttributeFromHTMLWrapper("opc0009").then((i=>{"1"===i?t(!0):Promise.all(e.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((e=>{t(e.includes("1"))})).catch((t=>{s(t)}))})).catch((t=>{s(t)}))}))}async getConfig(t){let e={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,s)=>{w.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(e)).then((e=>{var s;return t(null===(s=e.config)||void 0===s?void 0:s.data)})).catch((t=>s(t)))}))}async saveConfig(t,e){let s={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:e}}};return new Promise(((t,e)=>{w.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(s)).then((e=>t(e))).catch((t=>e(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,e){F.openAppActivity(t,e)}getDuPromissesStack(t){let e;return t&&(e=this._duPromises.get(t),e||(e=[],this._duPromises.set(t,e))),e||[]}async createDataunit(t,e,s){return new Promise(((i,r)=>{const n=this.getDuPromissesStack(e),a=n.length>0;if(n.push(new Z(i,r)),!a){const i=this.dataUnitFetcher.getDataUnit(t,this.resourceID,s);i.loadMetadata().then((()=>{for(e&&this._duCache.set(e,i);n.length>0;)n.pop().resolve(i)})).catch((t=>{for(;n.length>0;)n.pop().reject(t)}))}}))}async getDataUnit(t,e,s){return new Promise(((i,r)=>{const n=this._duCache.get(e);n?i(n):this.createDataunit(t,e,s).then((t=>{i(t)})).catch((t=>r(t)))}))}async getResourceID(){return Promise.resolve(this.resourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,e,s,i){return S.alert(t,e,s,i)}async error(t,e,s,i){return S.error(t,e,s,i)}async success(t,e,s,i){return S.success(t,e,s,i)}async message(t,e,s,i){return S.message(t,e,s,i)}async confirm(t,e,s,i,r){return S.confirm(t,e,s,i,r)}async info(t,e){return S.info(t,e)}async loadFormConfig(t){return this.formConfigFetcher.loadFormConfig(t,this.resourceID)}async loadGridConfig(t){return this.gridConfigFetcher.getConfig(t,this.resourceID)}async fetchUserAvailableConfigs(t){return this.formConfigFetcher.fetchUserAvailableConfigs(t,this.resourceID)}async fetchLegacyConfig(t){return this.formConfigFetcher.fetchLegacyConfig(t,this.resourceID)}async fetchDefaultConfig(t){return this.formConfigFetcher.fetchDefaultConfig(t,this.resourceID)}async loadTotals(t,e,s){return this.totalsFetcher.fetchTotals(t,e,s)}async saveGridConfig(t){return this.gridConfigFetcher.saveConfig(t,this.resourceID)}async getFilterBarConfig(t){return new Promise(((e,s)=>{this.configName===t&&this._filterBarConfig?e(this._filterBarConfig):this.configName===t&&null!=this._filterConfigPromise?Promise.all([this._filterConfigPromise]).then((t=>e(t[0]))).catch((t=>s(t[0]))):this.filterBarConfigFetcher.getConfig(this.resourceID,t).then((t=>e(t))).catch((t=>s(t)))}))}async saveFilterBarConfig(t,e){return this.filterBarConfigFetcher.saveConfig(t,this.resourceID,e)}async saveFormConfig(t,e){return this.formConfigFetcher.saveConfig(t,e,this.resourceID)}async getDefaultValues(){return this.defaultValuesFetcher.getDefaultValues(this.resourceID)}async getDefaultValue(t){return this._defaultValues&&this._defaultValues[t]}async getAuthList(t){return await(new M).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new U),this._dataUnitFetcher}get formConfigFetcher(){return this._formConfigFetcher||(this._formConfigFetcher=new $),this._formConfigFetcher}get gridConfigFetcher(){return this._gridConfigFetcher||(this._gridConfigFetcher=new _),this._gridConfigFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new b),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new A),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new B),this._authFetcher}get filterBarConfigFetcher(){return this._filterBarConfigFetcher||(this._filterBarConfigFetcher=new J),this._filterBarConfigFetcher}get defaultValuesFetcher(){return this._defaultValuesFetcher||(this._defaultValuesFetcher=new H),this._defaultValuesFetcher}async executeSearch(t,e,s){const i=null==s?void 0:s.getField(e);if(i){const{mode:e,argument:r}=t,{ENTITYNAME:n,CODEFIELD:a,DESCRIPTIONFIELD:o,ROOTENTITY:h,DESCRIPTIONENTITY:u}=i.properties,l=i.dependencies;let d;const m={rootEntity:h,descriptionFieldName:o,codeFieldName:a,showInactives:!1};return null==l||l.filter((t=>{var e;return null===(e=t.masterFields)||void 0===e?void 0:e.every((t=>{var e;return null===(e=s.getField(t))||void 0===e?void 0:e.visible}))})).forEach((t=>{var e;t.type===p.SEARCHING&&(null===(e=t.masterFields)||void 0===e?void 0:e.length)>0&&(d={expression:t.expression,params:t.masterFields.map((t=>{const e=s.getField(t),i=(null==e?void 0:e.dataType)||c.TEXT,r=s.getFieldValue(t);if(null==r)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${e.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${e.label} para executar a pesquisa.`);return{name:t,value:r,dataType:i}}))})})),this.executePreparedSearch(e,r,{entity:n,entityDescription:u,criteria:d,searchOptions:m})}}async executePreparedSearch(t,e,s){const{entity:i,entityDescription:r,criteria:n,searchOptions:a}=s;return"ADVANCED"===t?new Promise((t=>{const s=document.createElement("snk-pesquisa");s[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${i}`,s.argument=e,s.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(i,t,n,a),s.selectItem=e=>{t(e),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(s)})):this.pesquisaFetcher.loadSearchOptions(i,e,n,a)}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(this._resourceID)}clearContent(t){t&&Array.from(t.children).forEach((e=>{t.removeChild(e)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}componentWillLoad(){this._errorHandler=new C(this),this.messagesBuilder=new D,f.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),f.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,e,s)=>this.executeSearch(t,e,s))),f.setContextValue("__EZUI__GRID_LICENSE__",q),this.configName&&(this._filterConfigPromise=new Promise(((t,e)=>{this.filterBarConfigFetcher.getConfig(this.resourceID,this.configName).then((e=>{this._filterBarConfig=e,t(e)})).catch((t=>e(t)))}))),y.init(),P.get(),this.getDefaultValues().then((t=>{this._defaultValues=t}))}connectedCallback(){f.setContextValue("__SNK__APPLICATION__",this),w.addRequestListener(this._requestListener)}disconnectedCallback(){w.removeRequestListener(this._requestListener)}componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{this.applicationLoaded.emit(!0)})),m.addIDInfo(this._element,`resource_${this._resourceID}`)}render(){return s("div",null,s("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),s("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),s("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return i(this)}};class W{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){var e;if(1==(null===(e=null==t?void 0:t.requestBody)||void 0===e?void 0:e.length)){const{name:e}=t.requestBody[0].variables;if(e){const t=e.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class Z{constructor(t,e){this.resolve=t,this.reject=e}}V.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{V as snk_application}
@@ -0,0 +1 @@
1
+ import{r as t,c as i,h as s,g as e,H as a}from"./p-a77dd79a.js";import{Action as n,ApplicationContext as h}from"@sankhyalabs/core";import{ApplicationUtils as o,DialogType as r}from"@sankhyalabs/ezui/dist/collection/utils";import{O as l}from"./p-f624979d.js";const c=class{constructor(s){t(this,s),this.dataStateChange=i(this,"dataStateChange",3),this.dataUnitReady=i(this,"dataUnitReady",3),this.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this.pageSize=150,this._dataUnitObserver=t=>{const i={insertionMode:!1,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:!1,isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:this.dataUnit.getSelectedRecords(),selectedRecord:this.dataUnit.getSelectedRecord()};if(this.dataUnit.records.forEach((t=>{t.__record__id__.startsWith("NEW_")&&(i.insertionMode=!0,i.copyMode||(i.copyMode=null!=t.__record__source__id__))})),this.dataState=i,t.type===n.DATA_SAVED){const i=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0]);null!=i&&this.showSuccessMessage(i)}if(t.type!==n.RECORDS_ADDED&&t.type!==n.RECORDS_COPIED||this.insertionMode.emit(),t.type===n.EDITION_CANCELED){this.cancelEdition.emit();const t=this.getMessage("snkDataUnit.cancelInfo");null!=t&&this.showSuccessMessage(t)}if(t.type===n.RECORDS_REMOVED){const i=this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]);null!=i&&this.showSuccessMessage(i)}this._application.messagesBuilder.currentOperation=this.getMessageOperation()}}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,i){i!=t&&(this.dataUnit=void 0,this.dataUnitName=t,this.loadDataUnit())}observeEntityName(t,i){i!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,i){i!=t&&this.dataStateChange.emit(t)}observeDataUnit(){this.handlerLinkFields(),this.dataUnitReady.emit(this.dataUnit)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async interceptAction(t){return new Promise((i=>{switch(t.type){case n.RECORDS_ADDED:this.isAllowed("INSERT")?i(t):o.info(this.getMessage("snkDataUnit.forbiddenInsert"));break;case n.RECORDS_COPIED:this.isAllowed("CLONE")?i(t):o.info(this.getMessage("snkDataUnit.forbiddenClone"));break;case n.DATA_CHANGED:case n.CHANGING_DATA:this.isAllowed("UPDATE")?i(t):(this.dataUnit.cancelEdition(),o.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")));break;case n.SAVING_DATA:if(this.beforeSave){const s=this.beforeSave(this.dataUnit);s instanceof Promise?s.then((s=>i(s?t:void 0))):i(s?t:void 0)}else i(t);break;case n.DATA_SAVED:this.afterSave?this.afterSave(this.dataUnit):i(t);break;case n.EDITION_CANCELED:if(this.dataState.hasDirtyRecords){const s=this.getMessage("snkDataUnit.cancelConfirmation");if(null==s)i(t);else{const e=this.getMessage("snkDataUnit.cancelConfirmationTitle");o.confirm(e,s).then((s=>i(s?t:void 0)))}}else i(t);break;case n.REMOVING_RECORDS:if(this.isAllowed("REMOVE")){const s=this.getMessage("snkDataUnit.removeConfirmation");if(null==s)i(t);else{const e={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm.cancel"),labelConfirm:this.getMessage("snkDataUnit.confirm.delete"),btnConfirmDanger:!1},a=this.getMessage("snkDataUnit.removeConfirmationTitle");o.confirm(a,s,null,r.WARN,e).then((s=>i(s?t:void 0)))}}else o.info(this.getMessage("snkDataUnit.forbiddenRemove"));break;default:i(t)}}))}showSuccessMessage(t){o.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}getMessage(t,i){return i||(i=this.getMessageParams()),this._application.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecords?this.dataState.selectedRecords[0]:void 0}getMessageOperation(){return this.dataState.copyMode?l.CLONE:this.dataState.insertionMode?l.INSERT:this.dataState.isDirty?l.UPDATE:l.CLEAN}async getDataUnitParentOrChild(){var t;const i=this.dataUnitName?this.dataUnitName:this.entityName;return this._parentSnkDataUnit?(this._parentDataUnit=await(null===(t=this._parentSnkDataUnit)||void 0===t?void 0:t.getDataUnit()),await this._application.getDataUnit(this.entityName,void 0,this._parentDataUnit)):await this._application.getDataUnit(this.entityName,i)}async loadDataUnit(){if(!this.dataUnit&&this._application&&this.entityName){let t;for(this.dataUnit=await this.getDataUnitParentOrChild(),this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver);t=this._onDataUnitResolve.pop();)t(this.dataUnit)}}getParentSnkDataUnit(){let t=this.element;for(;t.parentNode;){if("SNK-DATA-UNIT"===t.parentNode.nodeName)return t.parentNode;t=t.parentNode}}handlerLinkFields(){var t,i;const s=Object.assign({},this.dataUnit.metadata);if(!this._parentDataUnit)return;const e=this._parentDataUnit.getChildInfo(this.entityName);if(!e)return;const a=null===(t=null==e?void 0:e.links)||void 0===t?void 0:t.map((t=>t.target));null===(i=null==s?void 0:s.fields)||void 0===i||i.forEach((t=>{(null==a?void 0:a.includes(t.name))&&(t.visible=!1)})),this.dataUnit.metadata=s}componentWillLoad(){this._application=h.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess().then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit()}componentDidLoad(){this.loadDataUnit()}render(){return s(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"]}}};c.style=".sc-snk-data-unit-h{display:flex;flex-direction:column;height:100%}";export{c as snk_data_unit}
@@ -1 +1 @@
1
- import{p as e,b as t}from"./p-a77dd79a.js";(()=>{const t=import.meta.url,a={};return""!==t&&(a.resourcesUrl=new URL(".",t).href),e(a)})().then((e=>t([["p-57895452",[[1,"teste-pesquisa"]]],["p-3480f2fa",[[2,"snk-data-unit",{dataState:[1040],dataUnitName:[1,"data-unit-name"],entityName:[1,"entity-name"],pageSize:[2,"page-size"],dataUnit:[1040],beforeSave:[16],afterSave:[16],getDataUnit:[64]}]]],["p-d7ae56ce",[[0,"snk-filter-binary-select",{value:[1544],config:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-91c23d20",[[0,"snk-filter-multi-select",{value:[1544],config:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-1ccaea51",[[0,"snk-filter-number",{config:[16],value:[2],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-12ebe36a",[[0,"snk-filter-period",{config:[16],value:[8],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-ab4ff312",[[0,"snk-filter-personalized",{config:[16],value:[1040],fix:[16],unfix:[16],show:[64]}]]],["p-e075dba7",[[0,"snk-filter-search",{config:[16],value:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-df5d94c6",[[0,"snk-filter-text",{config:[16],value:[1]},[[0,"ezChange","ezChangeListener"]]]]],["p-187b0d06",[[2,"snk-pesquisa",{searchLoader:[16],selectItem:[16],argument:[1025],_itemList:[32],_startLoading:[32]}]]],["p-3cb9f3ad",[[2,"snk-config-options",{fieldConfig:[16],idConfig:[513,"id-config"],dataUnit:[16],_defaultType:[32]}]]],["p-82e20fc0",[[6,"snk-tab-config",{selectedIndex:[1538,"selected-index"],selectedTab:[1537,"selected-tab"],tabs:[1],_processedTabs:[32],_activeEditText:[32],_activeEditTextIndex:[32],_actionsHide:[32],_actionsShow:[32]}]]],["p-d3e402d3",[[0,"snk-filter-detail",{config:[1040],getMessage:[16],show:[64]}]]],["p-9d474bc0",[[6,"snk-grid",{configName:[1,"config-name"],actionsList:[16],taskbarManager:[16],statusResolver:[16],multipleSelection:[4,"multiple-selection"],enableDataExporter:[4,"enable-data-exporter"],_dataUnit:[32],_dataState:[32],_gridConfig:[32],_popUpGridConfig:[32],showConfig:[64],hideConfig:[64],setConfig:[64]}],[2,"snk-configurator",{configName:[1,"config-name"],viewMode:[1,"view-mode"],_opened:[32],_permissions:[32],open:[64],close:[64]}],[2,"snk-field-config",{isConfigActive:[16],fieldConfig:[16],modeInsertion:[516,"mode-insertion"],dataUnit:[16]}]]],["p-4ca32c86",[[2,"snk-form-config",{dataUnit:[16],formConfig:[16],configName:[513,"config-name"],_formConfigOptions:[32],_fieldConfigSelected:[32],_layoutFormConfig:[32],_fieldsAvailable:[32],_formConfig:[32],_formConfigChanged:[32],_optionFormConfigSelected:[32],_optionFormConfigChanged:[32],_tempGroups:[32]}]]],["p-97347faf",[[0,"snk-exporter-email-sender",{getMessage:[16],_config:[32],_opened:[32],_currentStep:[32],open:[64],close:[64]}]]],["p-fc77347c",[[2,"snk-filter-bar",{dataUnit:[1040],configName:[1,"config-name"],filterConfig:[1040],allowDefault:[32],scrollerLocked:[32]},[[0,"filterChange","filterChangeListener"]]],[2,"snk-grid-config",{selectedIndex:[1026,"selected-index"],application:[16],columns:[1040],config:[1040],saveConfig:[64]}],[6,"snk-taskbar",{configName:[1,"config-name"],buttons:[1],customButtons:[16],actionsList:[16],primaryButton:[1,"primary-button"],disabledButtons:[16],dataUnit:[16],_permissions:[32]}],[0,"snk-filter-item",{config:[1040],getMessage:[16],detailIsVisible:[32],showUp:[64],hideDetail:[64]},[[2,"click","clickListener"],[2,"mousedown","mouseDownListener"],[0,"filterChange","filterChangeListener"]]],[4,"snk-filter-list",{label:[1],iconName:[1,"icon-name"],items:[16],getMessage:[16],emptyText:[1,"empty-text"],findFilterText:[1,"find-filter-text"],buttonClass:[1,"button-class"],_filterArgument:[32],_showAll:[32],hideDetail:[64]},[[2,"keydown","keyDownHandler"]]],[0,"snk-filter-modal",{getMessage:[16],items:[1040],modalTitle:[1,"modal-title"],modalSubTitle:[1,"modal-sub-title"],cancelButtonLabel:[1,"cancel-button-label"],okButtonLabel:[1,"ok-button-label"],infoText:[1,"info-text"],useSearch:[4,"use-search"],processModalAction:[16],_filterArgument:[32]}],[1,"snk-select-box",{selectedOption:[1,"selected-option"]}],[2,"snk-data-exporter",{provider:[16],_showDropdown:[32],_releasedToExport:[32]}]]],["p-6617d349",[[2,"snk-form",{configName:[1,"config-name"],recordsValidator:[16],actionsList:[16],taskbarManager:[16],_dataUnit:[32],_dataState:[32],_editionFormConfig:[32],_insertionFormConfig:[32],_showFormConfig:[32],showConfig:[64],hideConfig:[64]}]]],["p-13116d05",[[6,"snk-crud",{configName:[1025,"config-name"],actionsList:[16],taskbarManager:[16],recordsValidator:[16],statusResolver:[16],multipleSelection:[4,"multiple-selection"],enableDataExporter:[4,"enable-data-exporter"],_dataUnit:[32],_dataState:[32],_viewMode:[32],goToView:[64]}]]],["p-1faef46c",[[2,"snk-application",{messagesBuilder:[1040],configName:[1,"config-name"],isUserSup:[64],hasAccess:[64],getAllAccess:[64],getStringParam:[64],getIntParam:[64],getFloatParam:[64],getBooleanParam:[64],getDateParam:[64],showPopUp:[64],showModal:[64],closeModal:[64],closePopUp:[64],temOpcional:[64],getConfig:[64],saveConfig:[64],getAttributeFromHTMLWrapper:[64],openApp:[64],createDataunit:[64],getDataUnit:[64],getResourceID:[64],getUserID:[64],alert:[64],error:[64],success:[64],message:[64],confirm:[64],info:[64],loadFormConfig:[64],loadGridConfig:[64],fetchUserAvailableConfigs:[64],fetchLegacyConfig:[64],fetchDefaultConfig:[64],loadTotals:[64],saveGridConfig:[64],getFilterBarConfig:[64],saveFilterBarConfig:[64],saveFormConfig:[64],getDefaultValues:[64],getDefaultValue:[64],executeSearch:[64],executePreparedSearch:[64],isDebugMode:[64],getAppLabel:[64]}]]]],e)));
1
+ import{p as e,b as t}from"./p-a77dd79a.js";(()=>{const t=import.meta.url,a={};return""!==t&&(a.resourcesUrl=new URL(".",t).href),e(a)})().then((e=>t([["p-57895452",[[1,"teste-pesquisa"]]],["p-c32cfc29",[[2,"snk-data-unit",{dataState:[1040],dataUnitName:[1,"data-unit-name"],entityName:[1,"entity-name"],pageSize:[2,"page-size"],dataUnit:[1040],beforeSave:[16],afterSave:[16],getDataUnit:[64]}]]],["p-d7ae56ce",[[0,"snk-filter-binary-select",{value:[1544],config:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-91c23d20",[[0,"snk-filter-multi-select",{value:[1544],config:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-1ccaea51",[[0,"snk-filter-number",{config:[16],value:[2],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-12ebe36a",[[0,"snk-filter-period",{config:[16],value:[8],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-ab4ff312",[[0,"snk-filter-personalized",{config:[16],value:[1040],fix:[16],unfix:[16],show:[64]}]]],["p-e075dba7",[[0,"snk-filter-search",{config:[16],value:[16],show:[64]},[[0,"ezChange","ezChangeListener"]]]]],["p-df5d94c6",[[0,"snk-filter-text",{config:[16],value:[1]},[[0,"ezChange","ezChangeListener"]]]]],["p-187b0d06",[[2,"snk-pesquisa",{searchLoader:[16],selectItem:[16],argument:[1025],_itemList:[32],_startLoading:[32]}]]],["p-3cb9f3ad",[[2,"snk-config-options",{fieldConfig:[16],idConfig:[513,"id-config"],dataUnit:[16],_defaultType:[32]}]]],["p-82e20fc0",[[6,"snk-tab-config",{selectedIndex:[1538,"selected-index"],selectedTab:[1537,"selected-tab"],tabs:[1],_processedTabs:[32],_activeEditText:[32],_activeEditTextIndex:[32],_actionsHide:[32],_actionsShow:[32]}]]],["p-d3e402d3",[[0,"snk-filter-detail",{config:[1040],getMessage:[16],show:[64]}]]],["p-9d474bc0",[[6,"snk-grid",{configName:[1,"config-name"],actionsList:[16],taskbarManager:[16],statusResolver:[16],multipleSelection:[4,"multiple-selection"],enableDataExporter:[4,"enable-data-exporter"],_dataUnit:[32],_dataState:[32],_gridConfig:[32],_popUpGridConfig:[32],showConfig:[64],hideConfig:[64],setConfig:[64]}],[2,"snk-configurator",{configName:[1,"config-name"],viewMode:[1,"view-mode"],_opened:[32],_permissions:[32],open:[64],close:[64]}],[2,"snk-field-config",{isConfigActive:[16],fieldConfig:[16],modeInsertion:[516,"mode-insertion"],dataUnit:[16]}]]],["p-4ca32c86",[[2,"snk-form-config",{dataUnit:[16],formConfig:[16],configName:[513,"config-name"],_formConfigOptions:[32],_fieldConfigSelected:[32],_layoutFormConfig:[32],_fieldsAvailable:[32],_formConfig:[32],_formConfigChanged:[32],_optionFormConfigSelected:[32],_optionFormConfigChanged:[32],_tempGroups:[32]}]]],["p-97347faf",[[0,"snk-exporter-email-sender",{getMessage:[16],_config:[32],_opened:[32],_currentStep:[32],open:[64],close:[64]}]]],["p-fc77347c",[[2,"snk-filter-bar",{dataUnit:[1040],configName:[1,"config-name"],filterConfig:[1040],allowDefault:[32],scrollerLocked:[32]},[[0,"filterChange","filterChangeListener"]]],[2,"snk-grid-config",{selectedIndex:[1026,"selected-index"],application:[16],columns:[1040],config:[1040],saveConfig:[64]}],[6,"snk-taskbar",{configName:[1,"config-name"],buttons:[1],customButtons:[16],actionsList:[16],primaryButton:[1,"primary-button"],disabledButtons:[16],dataUnit:[16],_permissions:[32]}],[0,"snk-filter-item",{config:[1040],getMessage:[16],detailIsVisible:[32],showUp:[64],hideDetail:[64]},[[2,"click","clickListener"],[2,"mousedown","mouseDownListener"],[0,"filterChange","filterChangeListener"]]],[4,"snk-filter-list",{label:[1],iconName:[1,"icon-name"],items:[16],getMessage:[16],emptyText:[1,"empty-text"],findFilterText:[1,"find-filter-text"],buttonClass:[1,"button-class"],_filterArgument:[32],_showAll:[32],hideDetail:[64]},[[2,"keydown","keyDownHandler"]]],[0,"snk-filter-modal",{getMessage:[16],items:[1040],modalTitle:[1,"modal-title"],modalSubTitle:[1,"modal-sub-title"],cancelButtonLabel:[1,"cancel-button-label"],okButtonLabel:[1,"ok-button-label"],infoText:[1,"info-text"],useSearch:[4,"use-search"],processModalAction:[16],_filterArgument:[32]}],[1,"snk-select-box",{selectedOption:[1,"selected-option"]}],[2,"snk-data-exporter",{provider:[16],_showDropdown:[32],_releasedToExport:[32]}]]],["p-6617d349",[[2,"snk-form",{configName:[1,"config-name"],recordsValidator:[16],actionsList:[16],taskbarManager:[16],_dataUnit:[32],_dataState:[32],_editionFormConfig:[32],_insertionFormConfig:[32],_showFormConfig:[32],showConfig:[64],hideConfig:[64]}]]],["p-13116d05",[[6,"snk-crud",{configName:[1025,"config-name"],actionsList:[16],taskbarManager:[16],recordsValidator:[16],statusResolver:[16],multipleSelection:[4,"multiple-selection"],enableDataExporter:[4,"enable-data-exporter"],_dataUnit:[32],_dataState:[32],_viewMode:[32],goToView:[64]}]]],["p-b84c7c61",[[2,"snk-application",{messagesBuilder:[1040],configName:[1,"config-name"],isUserSup:[64],hasAccess:[64],getAllAccess:[64],getStringParam:[64],getIntParam:[64],getFloatParam:[64],getBooleanParam:[64],getDateParam:[64],showPopUp:[64],showModal:[64],closeModal:[64],closePopUp:[64],temOpcional:[64],getConfig:[64],saveConfig:[64],getAttributeFromHTMLWrapper:[64],openApp:[64],createDataunit:[64],getDataUnit:[64],getResourceID:[64],getUserID:[64],alert:[64],error:[64],success:[64],message:[64],confirm:[64],info:[64],loadFormConfig:[64],loadGridConfig:[64],fetchUserAvailableConfigs:[64],fetchLegacyConfig:[64],fetchDefaultConfig:[64],loadTotals:[64],saveGridConfig:[64],getFilterBarConfig:[64],saveFilterBarConfig:[64],saveFormConfig:[64],getDefaultValues:[64],getDefaultValue:[64],executeSearch:[64],executePreparedSearch:[64],isDebugMode:[64],getAppLabel:[64]}]]]],e)));
@@ -125,11 +125,11 @@ export declare class SnkApplication {
125
125
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache
126
126
  * passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
127
127
  */
128
- createDataunit(entityName: string, dataUnitName?: string): Promise<DataUnit>;
128
+ createDataunit(entityName: string, dataUnitName?: string, parentDataUnit?: DataUnit): Promise<DataUnit>;
129
129
  /**
130
130
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
131
131
  */
132
- getDataUnit(entityName: string, dataUnitName: string): Promise<DataUnit>;
132
+ getDataUnit(entityName: string, dataUnitName: string, parentDataUnit?: DataUnit): Promise<DataUnit>;
133
133
  /**
134
134
  * Obtém o resourceID da tela em questão.
135
135
  */
@@ -5,6 +5,8 @@ export declare class SnkDataUnit implements DUActionInterceptor {
5
5
  _onDataUnitResolve: Array<(dataUnit: DataUnit) => void>;
6
6
  _application: SnkApplication;
7
7
  _permissions: any;
8
+ _parentSnkDataUnit: HTMLSnkDataUnitElement;
9
+ _parentDataUnit: DataUnit;
8
10
  element: HTMLSnkDataUnitElement;
9
11
  /**
10
12
  * Controla o estado atual dos dados.
@@ -74,7 +76,10 @@ export declare class SnkDataUnit implements DUActionInterceptor {
74
76
  private getMessage;
75
77
  private getMessageParams;
76
78
  private getMessageOperation;
79
+ private getDataUnitParentOrChild;
77
80
  loadDataUnit(): Promise<void>;
81
+ private getParentSnkDataUnit;
82
+ private handlerLinkFields;
78
83
  componentWillLoad(): void;
79
84
  componentDidLoad(): void;
80
85
  render(): any;
@@ -87,4 +92,5 @@ export interface DataState {
87
92
  hasNext: boolean;
88
93
  hasPrevious: boolean;
89
94
  selectedRecords: Array<Record>;
95
+ selectedRecord: Record;
90
96
  }
@@ -52,7 +52,7 @@ export namespace Components {
52
52
  /**
53
53
  * Cria o DataUnit a partir do nome da entidade. É possível armazená-lo no cache passando o dataUnitName, assim, se mais de uma chamada for feita, o mesmo DataUnit será usado.
54
54
  */
55
- "createDataunit": (entityName: string, dataUnitName?: string) => Promise<DataUnit>;
55
+ "createDataunit": (entityName: string, dataUnitName?: string, parentDataUnit?: DataUnit) => Promise<DataUnit>;
56
56
  /**
57
57
  * Exibe o diálogo de erro de acordo com os parâmetros passados.
58
58
  */
@@ -100,7 +100,7 @@ export namespace Components {
100
100
  /**
101
101
  * Obtem um DataUnit do cache ou cria um caso ainda não tenha sido criado.
102
102
  */
103
- "getDataUnit": (entityName: string, dataUnitName: string) => Promise<DataUnit>;
103
+ "getDataUnit": (entityName: string, dataUnitName: string, parentDataUnit?: DataUnit) => Promise<DataUnit>;
104
104
  /**
105
105
  * Obtém o valor de um parâmetro do tipo data.
106
106
  */
@@ -4,7 +4,7 @@ export default class DataUnitFetcher {
4
4
  private _loadDataTimeout;
5
5
  constructor();
6
6
  private buldTemplates;
7
- getDataUnit(entityName: string, resourceID: string): DataUnit;
7
+ getDataUnit(entityName: string, resourceID: string, parentDataUnit?: DataUnit): DataUnit;
8
8
  private loadMetadata;
9
9
  private loadData;
10
10
  private doLoadData;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sankhyalabs/sankhyablocks",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Stencil Component Starter",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.js",
@@ -1,83 +0,0 @@
1
- import{r as t,c as e,h as s,g as i}from"./p-a77dd79a.js";import{WaitingChangeException as r,WarningException as n,ErrorException as a,ObjectUtils as o,DataType as c,DataUnit as h,StringUtils as u,ChangeOperation as l,DateUtils as d,DependencyType as p,ElementIDUtils as m,ApplicationContext as f,ErrorTracking as y}from"@sankhyalabs/core";import{d as g,D as w,R as v,U as I,F as _,G as P,C as $}from"./p-93d8ea09.js";import{ApplicationUtils as D}from"@sankhyalabs/ezui/dist/collection/utils";import{S}from"./p-f624979d.js";import"./p-112455b1.js";class C{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const e=t.reason;e instanceof r||(e?this.processException(e):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t.errorCode+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t.errorCode+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t)),t instanceof r||t instanceof n?this._app.alert(t.title,t.message):t instanceof a?this._app.error(t.title,t.message):this._app.isDebugMode().then((e=>{if(e)if(t instanceof Error)this._app.error(t.name,t.message);else{const e=(null==t?void 0:t.title)||"Erro detectado",s="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(e,s)}}))}}class A{constructor(){this._defaultPageSize=100,this._templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this._templateByQuery.set("search",g.gql`query($entityName: String! $argument: String $criteria: InputSearchCriteria $options: InputSearchOptions) {
2
- $queryAlias$: search(entityName: $entityName argument: $argument criteria: $criteria options: $options){
3
- value
4
- label
5
- }
6
- }`)}loadSearchOptions(t,e,s,i){const r=(null==e?void 0:e.trim())||void 0;return e=isNaN(Number(r))&&r?`%${r}`:r,new Promise(((r,n)=>{w.get().callGraphQL({values:{argument:e,entityName:t,criteria:s,options:i},query:this._templateByQuery.get("search")}).then((t=>{r(t)})).catch((t=>{n(t)}))}))}loadAdvancedSearch(t,e,s,i){const r={query:{$:null==s?void 0:s.expression}};(null==s?void 0:s.params.length)>0&&(r.params={param:s.params.map((t=>{let e=t.value,s=t.dataType;return s===c.OBJECT?(e=e.value,s="S"):s=function(t){switch(t){case c.NUMBER:return"I";case c.DATE:return"D";default:return"S"}}(t.dataType),{$:e,type:s}}))});const n={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:{entityName:t,compacted:!1,ignoreEntityCriteria:!1,limit:this._defaultPageSize,query:{$:e},orderByDesc:!1,externalCriteria:r,localEntityName:null==i?void 0:i.rootEntity},clientEventList:{clientEvent:[]}}};return new Promise(((t,e)=>{w.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(n)).then((e=>t(e))).catch((t=>e(t)))}))}}function T(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(T=function(){return t})()}const N=E;function E(t,e){const s=T();return(E=function(t){return s[t-=392]})(t,e)}!function(){const t=E,e=T();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const q=N(396);class b{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchTotals",g.gql`query($filters: [InputFilter!] $name: String!) {
7
- $queryAlias$: fetchTotals(name: $name, filters: $filters ){
8
- name
9
- value
10
- }
11
- }`)}async getTotals(t,e,s){let i={name:`totals://${t}/${e}`,filters:s};return w.get().callGraphQL({values:i,query:this.templateByQuery.get("fetchTotals")})}fetchTotals(t,e,s=[]){return new Promise(((i,r)=>{this.getTotals(t,e,s).then((t=>{if(t.length>0){const e=new Map;t.forEach((t=>{e.set(t.name,parseFloat(t.value))})),i(e)}else r("Não foi possível recuperar os totalizadores")})).catch((t=>{r(t)}))}))}}class U{constructor(){this.templateByQuery=new Map,this._loadDataTimeout={},this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",g.gql`query($name: String!) {
12
- $queryAlias$: fetchDataUnit(name: $name){
13
- name
14
- fields{
15
- name
16
- defaultValue
17
- label
18
- visible
19
- readOnly
20
- required
21
- dataType
22
- userInterface
23
- calculated
24
- group
25
- properties{
26
- name
27
- value
28
- }
29
- dependencies{
30
- masterFields
31
- type
32
- expression
33
- }
34
- }
35
- children{
36
- name
37
- links{
38
- source
39
- target
40
- }
41
- }
42
- }
43
- }`),this.templateByQuery.set("fetchData",g.gql`query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!]) {
44
- $queryAlias$: fetchDataUnit(name: $dataunit){
45
- data(limit: $limit offset: $offset filters: $filters sort: $sort){
46
- limit
47
- offset
48
- total
49
- hasMore
50
- records{
51
- id
52
- fields {
53
- name
54
- value
55
- }
56
- }
57
- }
58
- }
59
- }`),this.templateByQuery.set("saveData",g.gql`mutation($changes: [InputBatchChange!]!) {
60
- $queryAlias$: batchOperationDataUnit(changes: $changes){
61
- oldId
62
- id
63
- fields {
64
- name
65
- value
66
- }
67
- }
68
- }`),this.templateByQuery.set("fetchDataRecord",g.gql`query($dataunit: String! $recordID: [String!]) {
69
- $queryAlias$: fetchDataUnit(name: $dataunit){
70
- record(id: $recordID){
71
- id
72
- fields {
73
- name
74
- value
75
- }
76
- }
77
- }
78
- }`)}getDataUnit(t,e){const s=new h(`dd://${t}/${e}`);return s.metadataLoader=t=>this.loadMetadata(t),s.dataLoader=(t,e)=>this.loadData(t,e),s.saveLoader=(t,e)=>this.saveData(t,e),s.removeLoader=(t,e)=>this.removeRecords(t,e),s.recordLoader=(t,e)=>this.loadRecord(t,e),s}loadMetadata(t){return new Promise(((e,s)=>{w.get().callGraphQL({values:{name:t.name},query:this.templateByQuery.get("fetchDataUnit")}).then((t=>{var s;const i={name:t.name,label:t.name,children:[...t.children],fields:[]};null===(s=t.fields)||void 0===s||s.forEach((t=>{let e;Array.isArray(t.properties)&&(e={},t.calculated&&(e.gridHeaderTooltip="Campos calculados não podem ser ordenados"),t.properties.forEach((t=>e[t.name]=t.value))),i.fields.push(Object.assign(Object.assign({},t),{properties:e}))})),e(i)})).catch((t=>{s(t)}))}))}loadData(t,e){const s=t.name;return this._loadDataTimeout[s]&&(clearTimeout(this._loadDataTimeout[s]),delete this._loadDataTimeout[s]),new Promise(((i,r)=>{this._loadDataTimeout[s]=setTimeout((()=>{delete this._loadDataTimeout[s],this.doLoadData(t,e).then((t=>i(t))).catch((t=>r(t)))}),200)}))}doLoadData(t,e){return new Promise(((s,i)=>{var r;const{sort:n,filters:a,limit:o,offset:h,quickFilter:l}=e,d={dataunit:t.name,sort:n,filters:a};if(d.limit=o,d.offset=h,!u.isEmpty(null==l?void 0:l.term)){void 0===d.filter&&(d.filter=[]);const t={name:"__QUICK_FILTER__",expression:"__QUICK_FILTER__",params:[{name:"term",dataType:c.TEXT,value:l.term}]};(null===(r=null==l?void 0:l.fields)||void 0===r?void 0:r.length)>0&&t.params.push({name:"fields",dataType:c.OBJECT,value:l.fields}),d.filter.push(t)}w.get().callGraphQL({values:d,query:this.templateByQuery.get("fetchData")}).then((e=>{const{limit:i,offset:r,total:n,hasMore:a,records:o}=e.data;let c;i&&(c={firstRecord:0==n?0:r+1,lastRecord:r+Math.min(o.length,i),total:n,currentPage:r/i,hasMore:a});const h=[];o.forEach((e=>{const s={__record__id__:e.id};e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),h.push(s)})),s({paginationInfo:c,records:h})})).catch((t=>{i(t)}))}))}saveData(t,e){const s=e.map((e=>{const{dataUnit:s,record:i,updatingFields:r,operation:n}=e;let a;r&&(a=Object.entries(r).map((([e,s])=>{const i=t.getField(e);return{fieldName:e,dataType:i?i.dataType:c.TEXT,value:t.valueToString(e,s)}})));const o={dataUnit:s,fields:a,operation:n,recordId:i.__record__id__};return e.sourceId&&(o.sourceId=e.sourceId),o}));return new Promise(((e,i)=>{w.get().callGraphQL({values:{changes:s},query:this.templateByQuery.get("saveData")}).then((s=>{const i=[];null==s||s.forEach((e=>{const s={__record__id__:e.id};e.oldId&&(s.__old__id__=e.oldId),e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),i.push(s)})),e(i)})).catch((t=>{i(t)}))}))}removeRecords(t,e){const s=e.map((e=>({dataUnit:t.name,operation:l.DELETE,recordId:e})));return new Promise(((t,i)=>{w.get().callGraphQL({values:{changes:s},query:this.templateByQuery.get("saveData")}).then((()=>{t(e)})).catch((t=>{i(t)}))}))}loadRecord(t,e){return new Promise(((s,i)=>{w.get().callGraphQL({values:{recordID:e,dataunit:t.name},query:this.templateByQuery.get("fetchDataRecord")}).then((e=>{const i=[];e.record.forEach((e=>{const s={__record__id__:e.id};e.fields.forEach((({name:e,value:i})=>{s[e]=t.valueFromString(e,i)})),i.push(s)})),s(i)})).catch((t=>{i(t)}))}))}}var O;class F{static openAppActivity(t,e){var s;null===(s=window.workspace)||void 0===s||s.openAppActivity(t,e)}}F.resourceID=null===(O=window.workspace)||void 0===O?void 0:O.resourceID;class L{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",g.gql`query($name: String!) {
79
- $queryAlias$: fetchResource(name: $name){
80
- name
81
- resource
82
- }
83
- }`)}async getParam(t){const e=`param://application?params=${t}`;return w.get().callGraphQL({values:{name:e},query:this.templateByQuery.get("fetchParam")})}async asString(t){const e=await this.getParam(t);return this.getValue(e)}async asInteger(t){const e=await this.getParam(t);return parseInt(this.getValue(e))}async asFloat(t){const e=await this.getParam(t);return parseFloat(this.getValue(e))}async asBoolean(t){const e=await this.getParam(t);return this.getValue(e).includes('"S"')}async asDate(t){const e=await this.getParam(t);return d.strToDate(this.getValue(e))}async getBatchParams(t){const e=await this.getParam(t.join(",")),s={};return e.forEach((t=>s[t.name]=t.resource)),s}getValue(t={}){return Array.isArray(t)&&t.length>0&&(t=t[0]),u.isEmpty(t.resource)?"":t.resource}}const R=j;function j(t,e){const s=k();return(j=function(t){return s[t-=378]})(t,e)}function k(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(k=function(){return t})()}!function(){const t=j,e=k();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;e.push(e.shift())}catch(t){e.push(e.shift())}}();class M{[R(397)](t){const e=R;if(typeof(t=utxt(t[e(390)]))==e(392)&&(t=JSON[e(400)](t)),null==t)throw Error(e(395));const s=new x("S"===t[e(402)]||!0===t[e(402)]);return Array[e(394)](t[e(391)])&&t[e(391)][e(385)]((t=>s.putAccess(t[e(382)],String(t.status)==e(398)))),s}}class x{constructor(t){const e=R;this.isSup=t,this[e(384)]={}}[R(378)](t,e){this[R(384)][t]=e}[R(393)](t){const e=R;if(this[e(402)])return!0;let s=!0;return this[e(384)][e(380)](t)&&(s=this.actions[t]),s}isUserSup(){return this.isSup}}class B extends v{getData(t){const e=`cfg://auth/${t}`;return new Promise(((t,s)=>{this.loadResource(e).then((e=>{let s=o.stringToObject(e);s&&"object"==typeof s&&t(s)})).catch((t=>{s(t)}))}))}}var z;function G(t){if(null==t)return t;if(t instanceof Date)return t.toISOString();if("object"==typeof t){if(t instanceof Array)return t.map((t=>G(t)));{const e=Object.assign({},t);return Object.keys(t).forEach((s=>{t[s]?e[s]=G(t[s]):delete e[s]})),e}}return t}!function(t){t.INSERT="I",t.UPDATE="A",t.REMOVE="E",t.SHOW="C",t.CONFIG="F",t.CONFIG_NUMBER="N",t.CLONE="D",t.CONFIG_GRID="G"}(z||(z={}));class J extends v{saveConfig(t,e,s){const i=t.map((t=>{const{id:e,value:s,fixed:i,visible:r}=t,n={id:e};return s&&(n.value=G(s)),i&&(n.fixed=i),r&&(n.visible=!0),n}));return this.saveResource(i,`cfg://filter/FilterBarState:${e}/${s}`)}getConfig(t,e){return new Promise(((s,i)=>{this.loadResource(`cfg://filter/FilterBarState:${t}/${e}`).then((t=>{let e;t&&(e=JSON.parse(t).items),s(e||[])})).catch((t=>{i(t)}))}))}}class H extends v{getDefaultValues(t){return new Promise(((e,s)=>{this.loadResource(`cfg://defaultValues/${t}`).then((t=>{let s;t&&(s=JSON.parse(t)),e(s)})).catch((t=>{s(t)}))}))}}const V=class{constructor(s){t(this,s),this.applicationLoaded=e(this,"applicationLoaded",7),this.applicationLoading=e(this,"applicationLoading",7),this._authPromises=[],this._duCache=new Map,this._duPromises=new Map,this._requestListener=new W}get parameters(){return this._parameters||(this._parameters=new L),this._parameters}get resourceID(){return this._resourceID||(this._resourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||F.resourceID||"unknown.resource.id"),this._resourceID}get auth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,e)=>{const s=this._authPromises.length>0;this._authPromises.push(new Z(t,e)),s||this.authFetcher.getData(this.resourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}async isUserSup(){return new Promise(((t,e)=>{this.auth.then((s=>{this.getAuthList(s).then((e=>{t(e.isSup)})).catch((t=>e(t)))}))}))}async hasAccess(t){return new Promise(((e,s)=>{this.auth.then((i=>{this.getAuthList(i).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>s(t)))}))}))}async getAllAccess(){return new Promise(((t,e)=>{this.auth.then((s=>{this.getAuthList(s).then((e=>{const s={};s.isSup=e.isSup,Object.entries(z).forEach((t=>{s[t[0]]=e.actions[t[1]]||!1})),t(s)})).catch((t=>e(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,e="full",s=!0){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=e,this._popUp.useHeader=s,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const e=t.split(",");return new Promise(((t,s)=>{this.getAttributeFromHTMLWrapper("opc0009").then((i=>{"1"===i?t(!0):Promise.all(e.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((e=>{t(e.includes("1"))})).catch((t=>{s(t)}))})).catch((t=>{s(t)}))}))}async getConfig(t){let e={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,s)=>{w.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(e)).then((e=>{var s;return t(null===(s=e.config)||void 0===s?void 0:s.data)})).catch((t=>s(t)))}))}async saveConfig(t,e){let s={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:e}}};return new Promise(((t,e)=>{w.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(s)).then((e=>t(e))).catch((t=>e(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,e){F.openAppActivity(t,e)}getDuPromissesStack(t){let e;return t&&(e=this._duPromises.get(t),e||(e=[],this._duPromises.set(t,e))),e||[]}async createDataunit(t,e){return new Promise(((s,i)=>{const r=this.getDuPromissesStack(e),n=r.length>0;if(r.push(new Z(s,i)),!n){const s=this.dataUnitFetcher.getDataUnit(t,this.resourceID);s.loadMetadata().then((()=>{for(e&&this._duCache.set(e,s);r.length>0;)r.pop().resolve(s)})).catch((t=>{for(;r.length>0;)r.pop().reject(t)}))}}))}async getDataUnit(t,e){return new Promise(((s,i)=>{const r=this._duCache.get(e);r?s(r):this.createDataunit(t,e).then((t=>{s(t)})).catch((t=>i(t)))}))}async getResourceID(){return Promise.resolve(this.resourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,e,s,i){return D.alert(t,e,s,i)}async error(t,e,s,i){return D.error(t,e,s,i)}async success(t,e,s,i){return D.success(t,e,s,i)}async message(t,e,s,i){return D.message(t,e,s,i)}async confirm(t,e,s,i,r){return D.confirm(t,e,s,i,r)}async info(t,e){return D.info(t,e)}async loadFormConfig(t){return this.formConfigFetcher.loadFormConfig(t,this.resourceID)}async loadGridConfig(t){return this.gridConfigFetcher.getConfig(t,this.resourceID)}async fetchUserAvailableConfigs(t){return this.formConfigFetcher.fetchUserAvailableConfigs(t,this.resourceID)}async fetchLegacyConfig(t){return this.formConfigFetcher.fetchLegacyConfig(t,this.resourceID)}async fetchDefaultConfig(t){return this.formConfigFetcher.fetchDefaultConfig(t,this.resourceID)}async loadTotals(t,e,s){return this.totalsFetcher.fetchTotals(t,e,s)}async saveGridConfig(t){return this.gridConfigFetcher.saveConfig(t,this.resourceID)}async getFilterBarConfig(t){return new Promise(((e,s)=>{this.configName===t&&this._filterBarConfig?e(this._filterBarConfig):this.configName===t&&null!=this._filterConfigPromise?Promise.all([this._filterConfigPromise]).then((t=>e(t[0]))).catch((t=>s(t[0]))):this.filterBarConfigFetcher.getConfig(this.resourceID,t).then((t=>e(t))).catch((t=>s(t)))}))}async saveFilterBarConfig(t,e){return this.filterBarConfigFetcher.saveConfig(t,this.resourceID,e)}async saveFormConfig(t,e){return this.formConfigFetcher.saveConfig(t,e,this.resourceID)}async getDefaultValues(){return this.defaultValuesFetcher.getDefaultValues(this.resourceID)}async getDefaultValue(t){return this._defaultValues&&this._defaultValues[t]}async getAuthList(t){return await(new M).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new U),this._dataUnitFetcher}get formConfigFetcher(){return this._formConfigFetcher||(this._formConfigFetcher=new _),this._formConfigFetcher}get gridConfigFetcher(){return this._gridConfigFetcher||(this._gridConfigFetcher=new P),this._gridConfigFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new b),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new A),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new B),this._authFetcher}get filterBarConfigFetcher(){return this._filterBarConfigFetcher||(this._filterBarConfigFetcher=new J),this._filterBarConfigFetcher}get defaultValuesFetcher(){return this._defaultValuesFetcher||(this._defaultValuesFetcher=new H),this._defaultValuesFetcher}async executeSearch(t,e,s){const i=null==s?void 0:s.getField(e);if(i){const{mode:e,argument:r}=t,{ENTITYNAME:n,CODEFIELD:a,DESCRIPTIONFIELD:o,ROOTENTITY:h,DESCRIPTIONENTITY:u}=i.properties,l=i.dependencies;let d;const m={rootEntity:h,descriptionFieldName:o,codeFieldName:a,showInactives:!1};return null==l||l.filter((t=>{var e;return null===(e=t.masterFields)||void 0===e?void 0:e.every((t=>{var e;return null===(e=s.getField(t))||void 0===e?void 0:e.visible}))})).forEach((t=>{var e;t.type===p.SEARCHING&&(null===(e=t.masterFields)||void 0===e?void 0:e.length)>0&&(d={expression:t.expression,params:t.masterFields.map((t=>{const e=s.getField(t),i=(null==e?void 0:e.dataType)||c.TEXT,r=s.getFieldValue(t);if(null==r)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${e.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${e.label} para executar a pesquisa.`);return{name:t,value:r,dataType:i}}))})})),this.executePreparedSearch(e,r,{entity:n,entityDescription:u,criteria:d,searchOptions:m})}}async executePreparedSearch(t,e,s){const{entity:i,entityDescription:r,criteria:n,searchOptions:a}=s;return"ADVANCED"===t?new Promise((t=>{const s=document.createElement("snk-pesquisa");s[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${i}`,s.argument=e,s.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(i,t,n,a),s.selectItem=e=>{t(e),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(s)})):this.pesquisaFetcher.loadSearchOptions(i,e,n,a)}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(this._resourceID)}clearContent(t){t&&Array.from(t.children).forEach((e=>{t.removeChild(e)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}componentWillLoad(){this._errorHandler=new C(this),this.messagesBuilder=new S,f.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),f.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,e,s)=>this.executeSearch(t,e,s))),f.setContextValue("__EZUI__GRID_LICENSE__",q),this.configName&&(this._filterConfigPromise=new Promise(((t,e)=>{this.filterBarConfigFetcher.getConfig(this.resourceID,this.configName).then((e=>{this._filterBarConfig=e,t(e)})).catch((t=>e(t)))}))),y.init(),$.get(),this.getDefaultValues().then((t=>{this._defaultValues=t}))}connectedCallback(){f.setContextValue("__SNK__APPLICATION__",this),w.addRequestListener(this._requestListener)}disconnectedCallback(){w.removeRequestListener(this._requestListener)}componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{this.applicationLoaded.emit(!0)})),m.addIDInfo(this._element,`resource_${this._resourceID}`)}render(){return s("div",null,s("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),s("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),s("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return i(this)}};class W{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){var e;if(1==(null===(e=null==t?void 0:t.requestBody)||void 0===e?void 0:e.length)){const{name:e}=t.requestBody[0].variables;if(e){const t=e.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class Z{constructor(t,e){this.resolve=t,this.reject=e}}V.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{V as snk_application}
@@ -1 +0,0 @@
1
- import{r as t,c as s,h as i,g as e,H as a}from"./p-a77dd79a.js";import{Action as n,ApplicationContext as h}from"@sankhyalabs/core";import{ApplicationUtils as o,DialogType as r}from"@sankhyalabs/ezui/dist/collection/utils";import{O as c}from"./p-f624979d.js";const l=class{constructor(i){t(this,i),this.dataStateChange=s(this,"dataStateChange",7),this.dataUnitReady=s(this,"dataUnitReady",7),this.insertionMode=s(this,"insertionMode",7),this.cancelEdition=s(this,"cancelEdition",7),this._onDataUnitResolve=[],this.pageSize=150,this._dataUnitObserver=t=>{const s={insertionMode:!1,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:!1,isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:this.dataUnit.getSelectedRecords()};if(this.dataUnit.records.forEach((t=>{t.__record__id__.startsWith("NEW_")&&(s.insertionMode=!0,s.copyMode||(s.copyMode=null!=t.__record__source__id__))})),this.dataState=s,t.type===n.DATA_SAVED){const s=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0]);null!=s&&this.showSuccessMessage(s)}if(t.type!==n.RECORDS_ADDED&&t.type!==n.RECORDS_COPIED||this.insertionMode.emit(),t.type===n.EDITION_CANCELED){this.cancelEdition.emit();const t=this.getMessage("snkDataUnit.cancelInfo");null!=t&&this.showSuccessMessage(t)}if(t.type===n.RECORDS_REMOVED){const s=this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]);null!=s&&this.showSuccessMessage(s)}this._application.messagesBuilder.currentOperation=this.getMessageOperation()}}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,s){s!=t&&(this.dataUnit=void 0,this.dataUnitName=t,this.loadDataUnit())}observeEntityName(t,s){s!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,s){s!=t&&this.dataStateChange.emit(t)}observeDataUnit(){this.dataUnitReady.emit(this.dataUnit)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async interceptAction(t){return new Promise((s=>{switch(t.type){case n.RECORDS_ADDED:this.isAllowed("INSERT")?s(t):o.info(this.getMessage("snkDataUnit.forbiddenInsert"));break;case n.RECORDS_COPIED:this.isAllowed("CLONE")?s(t):o.info(this.getMessage("snkDataUnit.forbiddenClone"));break;case n.DATA_CHANGED:case n.CHANGING_DATA:this.isAllowed("UPDATE")?s(t):(this.dataUnit.cancelEdition(),o.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")));break;case n.SAVING_DATA:if(this.beforeSave){const i=this.beforeSave(this.dataUnit);i instanceof Promise?i.then((i=>s(i?t:void 0))):s(i?t:void 0)}else s(t);break;case n.DATA_SAVED:this.afterSave?this.afterSave(this.dataUnit):s(t);break;case n.EDITION_CANCELED:if(this.dataState.hasDirtyRecords){const i=this.getMessage("snkDataUnit.cancelConfirmation");if(null==i)s(t);else{const e=this.getMessage("snkDataUnit.cancelConfirmationTitle");o.confirm(e,i).then((i=>s(i?t:void 0)))}}else s(t);break;case n.REMOVING_RECORDS:if(this.isAllowed("REMOVE")){const i=this.getMessage("snkDataUnit.removeConfirmation");if(null==i)s(t);else{const e={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm.cancel"),labelConfirm:this.getMessage("snkDataUnit.confirm.delete"),btnConfirmDanger:!1},a=this.getMessage("snkDataUnit.removeConfirmationTitle");o.confirm(a,i,null,r.WARN,e).then((i=>s(i?t:void 0)))}}else o.info(this.getMessage("snkDataUnit.forbiddenRemove"));break;default:s(t)}}))}showSuccessMessage(t){o.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}getMessage(t,s){return s||(s=this.getMessageParams()),this._application.messagesBuilder.getMessage(t,s)}getMessageParams(){return this.dataState.selectedRecords?this.dataState.selectedRecords[0]:void 0}getMessageOperation(){return this.dataState.copyMode?c.CLONE:this.dataState.insertionMode?c.INSERT:this.dataState.isDirty?c.UPDATE:c.CLEAN}async loadDataUnit(){if(!this.dataUnit&&this._application&&this.entityName){const t=this.dataUnitName?this.dataUnitName:this.entityName;let s;for(this.dataUnit=await this._application.getDataUnit(this.entityName,t),this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver);s=this._onDataUnitResolve.pop();)s(this.dataUnit)}}componentWillLoad(){this._application=h.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess().then((t=>this._permissions=t))}componentDidLoad(){this.loadDataUnit()}render(){return i(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"]}}};l.style=".sc-snk-data-unit-h{display:flex;flex-direction:column;height:100%}";export{l as snk_data_unit}