@steedos-widgets/amis-object 1.2.13 → 1.2.15

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.
@@ -1771,8 +1771,8 @@
1771
1771
  /*
1772
1772
  * @Author: baozhoutao@steedos.com
1773
1773
  * @Date: 2022-11-01 15:51:00
1774
- * @LastEditors: Please set LastEditors
1775
- * @LastEditTime: 2023-04-26 11:52:04
1774
+ * @LastEditors: liaodaxue
1775
+ * @LastEditTime: 2023-06-06 11:12:33
1776
1776
  * @Description:
1777
1777
  */
1778
1778
 
@@ -1855,7 +1855,7 @@
1855
1855
  "isLookup": "${isLookup}",
1856
1856
  "listName": "${listName}"
1857
1857
  },
1858
- "title": "新建 ${uiSchema.label}",
1858
+ "title": "新建 ${uiSchema.label | raw}",
1859
1859
  "body": [
1860
1860
  {
1861
1861
  "type": "service",
@@ -5828,6 +5828,7 @@ else{
5828
5828
  pickerSchema = await getTableSchema$1(tableFields, {
5829
5829
  labelFieldName: refObjectConfig.NAME_FIELD_KEY,
5830
5830
  top: top,
5831
+ isLookup: true,
5831
5832
  ...ctx
5832
5833
  });
5833
5834
 
@@ -5877,6 +5878,10 @@ else{
5877
5878
  };
5878
5879
  }
5879
5880
 
5881
+ if(field.pickerSchema){
5882
+ pickerSchema = Object.assign({}, pickerSchema, field.pickerSchema);
5883
+ }
5884
+
5880
5885
  const data = {
5881
5886
  type: getAmisStaticFieldType('picker', readonly),
5882
5887
  labelField: referenceTo.labelField.name,
@@ -6403,7 +6408,7 @@ else{
6403
6408
  return {
6404
6409
  type: amisFieldType,
6405
6410
  tpl: `
6406
- <% let fileData = data.${steedosField.name}; if (fileData) { %>
6411
+ <% let fileData = data._display.${steedosField.name}; if (fileData) { %>
6407
6412
  <% if(!Array.isArray(fileData)){ fileData = [fileData]} %>
6408
6413
  <% fileData.forEach(function(item) { %>
6409
6414
  <a href='<%= item.url %>' target='_self' class='block'><%= item.name %></a>
@@ -6444,7 +6449,6 @@ else{
6444
6449
  }
6445
6450
  }
6446
6451
  };
6447
-
6448
6452
  if(steedosField.multiple){
6449
6453
  convertData.multiple = true;
6450
6454
  convertData.joinValues = false;
@@ -7167,2204 +7171,2439 @@ else{
7167
7171
  getAmisStaticFieldType: getAmisStaticFieldType
7168
7172
  });
7169
7173
 
7170
- const API_CACHE = 100;
7171
-
7172
- function getReadonlyFormAdaptor(object, fields){
7173
- let scriptStr = '';
7174
- const selectFields = ___default__namespace.filter(fields, function(field){return field.name.indexOf('.') < 0 && ((field.type == 'select' && field.options) || ((field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to))});
7175
- const gridAndObjectFieldsName = ___default__namespace.map(___default__namespace.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type === 'object' || field.type === 'grid')}), 'name');
7176
- ___default__namespace.each(selectFields, function(field){
7177
- if(!___default__namespace.includes(OMIT_FIELDS, field.name)){
7178
- field.name;
7179
- if(field.options){
7180
- const options = JSON.stringify({options: field.options});
7181
- scriptStr = scriptStr + `var ${field.name}Options= (${options}).options;`;
7182
- }else if(field.optionsFunction){
7183
- scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`;
7184
- }else if(field._optionsFunction){
7185
- scriptStr = scriptStr + `var ${field.name}Options = eval(${field._optionsFunction})(api.data);`;
7186
- }
7187
- if(field.multiple){
7188
- scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`;
7189
- }else {
7190
- scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`;
7191
- scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`;
7192
- }
7193
- }
7194
- });
7195
-
7196
- // const refFields = _.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to});
7197
- // _.each(refFields, function(field){
7198
- // if(!_.includes(OMIT_FIELDS, field.name)){
7199
- // const valueField = field.reference_to_field || '_id';
7200
- // scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`
7201
- // if(field.multiple){
7202
- // scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`
7203
- // }else{
7204
- // scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`
7205
- // scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`
7206
- // }
7207
- // }
7208
- // })
7209
-
7210
- return `
7211
- if(payload.data.data.length === 0){
7212
- return {
7213
- status: 2,
7214
- msg: "无法找到记录"
7215
- }
7216
- }
7217
- if(payload.data.data){
7218
- var data = payload.data.data[0];
7219
- var gridAndObjectFieldsName = ${JSON.stringify(gridAndObjectFieldsName)};
7220
- try{
7221
- ${scriptStr}
7222
- ${getScriptForAddUrlPrefixForImgFields(fields)}
7223
- ${getScriptForRewriteValueForFileFields(fields)}
7224
- }catch(e){
7225
- console.error(e)
7226
- }
7227
- // 原始记录
7228
- var record = _.cloneDeep(data);
7229
- try{
7230
- _.each(gridAndObjectFieldsName, function(name){
7231
- data[name] = data._display[name];
7232
- })
7233
- }catch(e){
7234
- console.error(e)
7235
- }
7236
- payload.data = data;
7237
- payload.data.__objectName = "${object.name}";
7238
- payload.data.__record = record;
7239
- window.postMessage(Object.assign({type: "record.loaded"}, {record: record}), "*")
7240
- }
7241
- if(payload.errors){
7242
- payload.status = 2;
7243
- payload.msg = payload.errors[0].message;
7244
- }
7245
- return payload;
7246
- `
7247
- }
7248
-
7249
- async function getReadonlyFormInitApi(object, recordId, fields, options){
7250
- return {
7251
- method: "post",
7252
- url: getApi$2()+"&recordId=${recordId}",
7253
- cache: API_CACHE,
7254
- // requestAdaptor: "console.log('getReadonlyFormInitApi requestAdaptor', api);return api;",
7255
- adaptor: getReadonlyFormAdaptor(object, fields),
7256
- data: await getFindOneQuery$1(object, recordId, fields, options),
7257
- headers: {
7258
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7259
- }
7260
- }
7261
- }
7262
-
7263
7174
  /*
7264
- img/avatar字段值添加URL前缀使其在amis中正常显示图片。
7265
- */
7266
- function getScriptForAddUrlPrefixForImgFields(fields){
7267
- let imgFieldsKeys = [];
7268
- let imgFields = {};
7269
- fields.forEach((item)=>{
7270
- if(___default__namespace.includes(['image','avatar'], item.type)){
7271
- imgFieldsKeys.push(item.name);
7272
- imgFields[item.name] = {
7273
- name: item.name,
7274
- type: item.type,
7275
- multiple: item.multiple
7276
- };
7277
- }
7278
- });
7279
- if(!imgFieldsKeys.length){
7280
- return '';
7175
+ * @Author: baozhoutao@steedos.com
7176
+ * @Date: 2022-08-04 10:42:49
7177
+ * @LastEditors: baozhoutao@steedos.com
7178
+ * @LastEditTime: 2022-08-25 10:28:47
7179
+ * @Description:
7180
+ */
7181
+ var config = {
7182
+ listView: {
7183
+ newRecordMode: 'modal',
7184
+ editRecordMode: 'modal',
7185
+ perPage: 20
7281
7186
  }
7282
- return `
7283
- // image字段值添加URL前缀
7284
- let imgFieldsKeys = ${JSON.stringify(imgFieldsKeys)};
7285
- let imgFields = ${JSON.stringify(imgFields)};
7286
- imgFieldsKeys.forEach((item)=>{
7287
- let imgFieldValue = data[item];
7288
- let imgFieldDisplayValue = data._display && data._display[item];
7289
- if(imgFieldValue && imgFieldValue.length){
7290
- let fieldProps = imgFields[item];
7291
- if(fieldProps.multiple){
7292
- if(imgFieldDisplayValue instanceof Array){
7293
- data[item] = imgFieldDisplayValue.map((i)=>{ return i.url });
7187
+ };
7188
+
7189
+ async function getQuickEditSchema(field, options){
7190
+ const quickEditId = options.objectName + "_" + field.name + "QuickEdit";//定义快速编辑的表单id,用于setvalue传值
7191
+ var quickEditSchema = { body: [], id: quickEditId };
7192
+ if (field.disabled) {
7193
+ quickEditSchema = false;
7194
+ } else {
7195
+ var fieldSchema = await convertSFieldToAmisField(field, false, ___default__namespace.omit(options, 'buttons'));
7196
+ //存在属性上可编辑,实际不可编辑的字段,convertSFieldToAmisField函数可能会返回undefined,如summary
7197
+ if (!!fieldSchema) {
7198
+ quickEditSchema.body.push(fieldSchema);
7199
+ //以下字段使用_display的数据,因此在触发change等事件时对数据_display进行修改,以实现保存前的回显
7200
+ var TempDisplayField = ``;
7201
+ quickEditSchema.body[0].onEvent = {};
7202
+ const quickEditOnEvent = function (displayField) {
7203
+ const EventType = {
7204
+ "actions": [
7205
+ {
7206
+ "actionType": "custom",
7207
+ "script": `
7208
+ var _display = event.data._display;
7209
+ ${displayField}
7210
+ doAction({actionType: 'setValue', "args": {"value": {_display}},componentId: "${quickEditId}"});
7211
+ `
7294
7212
  }
7295
- }else{
7296
- data[item] = imgFieldDisplayValue && imgFieldDisplayValue.url;
7213
+ ]
7214
+ };
7215
+ return EventType;
7216
+ };
7217
+ switch (field.type) {
7218
+ //TODO:amis的picker组件直接点击选项x时不会触发change事件,待处理
7219
+ case "lookup":
7220
+ case "master_detail":
7221
+ if (field.multiple) {
7222
+ TempDisplayField = `
7223
+ _display["${field.name}"] = [];
7224
+ event.data.value.forEach(function(item,index){
7225
+ _display["${field.name}"].push(
7226
+ {
7227
+ "label": event.data.option[index].${quickEditSchema.body[0].labelField},
7228
+ "value": event.data.option[index]._id,
7229
+ "objectName": "${field.reference_to}"
7230
+ }
7231
+ )
7232
+ })
7233
+ `;
7234
+ } else {
7235
+ TempDisplayField = `
7236
+ _display["${field.name}"] = {
7237
+ "label": event.data.option.${quickEditSchema.body[0].labelField},
7238
+ "value": event.data._id,
7239
+ "objectName": "${field.reference_to}"
7240
+ }
7241
+ `;
7242
+ }
7243
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7244
+ break;
7245
+ case "select":
7246
+ TempDisplayField = `
7247
+ _display["${field.name}"] = event.data.selectedItems.label;
7248
+ `;
7249
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7250
+ break;
7251
+ case "percent":
7252
+ TempDisplayField = `
7253
+ _display["${field.name}"] = (event.data.value * 100).toFixed(${field.scale}) + '%';
7254
+ `;
7255
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7256
+ break;
7257
+ case "time":
7258
+ TempDisplayField = `
7259
+ _display["${field.name}"] = moment(event.data.value).utc().format('HH:mm');
7260
+ `;
7261
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7262
+ break;
7263
+ case "date":
7264
+ TempDisplayField = `
7265
+ _display["${field.name}"] = moment(event.data.value).utc().format('YYYY-MM-DD');
7266
+ `;
7267
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7268
+ break;
7269
+ case "datetime":
7270
+ TempDisplayField = `
7271
+ _display["${field.name}"] = moment(event.data.value).format('YYYY-MM-DD HH:mm');
7272
+ `;
7273
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7274
+ break;
7275
+ case "boolean":
7276
+ TempDisplayField = `
7277
+ _display["${field.name}"] = event.data.value?"√":"";
7278
+ `;
7279
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7280
+ break;
7281
+ case "number":
7282
+ case "currency":
7283
+ TempDisplayField = `
7284
+ _display["${field.name}"] = event.data.value?.toFixed(${field.scale});
7285
+ `;
7286
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
7287
+
7288
+ break;
7289
+ case "file":
7290
+ var removeDisplayField = ``;
7291
+ if (field.multiple) {
7292
+ TempDisplayField = `
7293
+ _display["${field.name}"].push({
7294
+ "name": event.data.result.name,
7295
+ "url": event.data.result.url,
7296
+ "type": event.data.item.type,
7297
+ "size": event.data.item.size
7298
+ });
7299
+ `;
7300
+ removeDisplayField = `
7301
+ _.remove(_display["${field.name}"], function(file){return file.url == event.data.item.url});
7302
+ `;
7303
+ } else {
7304
+ TempDisplayField = `
7305
+ _display["${field.name}"] = {
7306
+ "name": event.data.result.name,
7307
+ "url": event.data.result.url,
7308
+ "type": event.data.item.type,
7309
+ "size": event.data.item.size
7310
+ };
7311
+ `;
7312
+ removeDisplayField = `
7313
+ if(_display["${field.name}"].url == event.data.item.url){
7314
+ _display["${field.name}"] = {};
7315
+ }
7316
+ `;
7317
+ }
7318
+ quickEditSchema.body[0].onEvent["success"] = quickEditOnEvent(TempDisplayField);
7319
+ quickEditSchema.body[0].onEvent["remove"] = quickEditOnEvent(removeDisplayField);
7320
+ break;
7321
+ case "avatar":
7322
+ case "image":
7323
+ quickEditSchema.body[0].receiver.adaptor = `
7324
+ const { context } = api.body;
7325
+ var rootUrl = context.rootUrl + "/api/files/${field.type}s/";
7326
+ payload = {
7327
+ status: response.status == 200 ? 0 : response.status,
7328
+ msg: response.statusText,
7329
+ data: {
7330
+ value: rootUrl + payload._id,//为了实现图片crud的回显,需要将value从id改为url,当保存数据数据时,再在发送适配器内重新将id提取出来
7331
+ name: payload.original.name,
7332
+ url: rootUrl + payload._id,
7297
7333
  }
7298
7334
  }
7299
- })
7300
- `
7301
- }
7335
+ return payload;
7336
+ `;
7337
+ break;
7338
+ }
7302
7339
 
7303
- /*
7304
- file字段值重写使其在amis中正常显示附件名、点击附件名下载文件。
7305
- */
7306
- function getScriptForRewriteValueForFileFields(fields){
7307
- let fileFieldsKeys = [];
7308
- let fileFields = {};
7309
- fields.forEach((item)=>{
7310
- if(item.type === 'file'){
7311
- fileFieldsKeys.push(item.name);
7312
- fileFields[item.name] = {
7313
- name: item.name,
7314
- multiple: item.multiple
7315
- };
7340
+ } else {
7341
+ quickEditSchema = false;
7342
+ }
7343
+ //TODO:附件多选时会覆盖老数据,暂时禁用
7344
+ if(field.type == "file" && field.multiple){
7345
+ quickEditSchema = false;
7316
7346
  }
7317
- });
7318
- if(!fileFieldsKeys.length){
7319
- return '';
7320
7347
  }
7321
- return `
7322
- // file字段值重写以便编辑时正常显示附件名、点击附件名正常下载附件
7323
- let fileFieldsKeys = ${JSON.stringify(fileFieldsKeys)};
7324
- let fileFields = ${JSON.stringify(fileFields)};
7325
- fileFieldsKeys.forEach((item)=>{
7326
- let fileFieldValue = data[item];
7327
- let fileFieldDisplayValue = data._display && data._display[item];
7328
- if(fileFieldValue && fileFieldValue.length){
7329
- if(fileFields[item].multiple){
7330
- if(fileFieldDisplayValue instanceof Array){
7331
- data[item] = fileFieldDisplayValue.map((item, index)=>{
7332
- return {
7333
- value: fileFieldValue[index],
7334
- name: item.name,
7335
- url: item.url + "?download=true",
7336
- state: "uploaded"
7348
+ return quickEditSchema;
7349
+ }
7350
+
7351
+ async function getTableColumns$1(fields, options){
7352
+ const columns = [{name: '_index',type: 'text', width: 32, placeholder: ""}];
7353
+ const allowEdit = options.permissions?.allowEdit && options.permissions?.modifyAllRecords && !options.isLookup && options.enable_inline_edit != false;
7354
+ for (const field of fields) {
7355
+ //增加quickEdit属性,实现快速编辑
7356
+ const quickEditSchema = allowEdit ? await getQuickEditSchema(field, options) : allowEdit;
7357
+ if((field.is_name || field.name === options.labelFieldName) && options.objectName === 'cms_files'){
7358
+ const previewFileScript = `
7359
+ var data = event.data;
7360
+ var file_name = data.versions ? data.name : "${field.label}";
7361
+ var file_id = data._id;
7362
+ SteedosUI.previewFile && SteedosUI.previewFile({file_name, file_id});
7363
+ `;
7364
+ columns.push({
7365
+ "type": "button",
7366
+ "label": `<%=data.versions ? data.name : "${field.label}"%>`,
7367
+ "className": "whitespace-nowrap",
7368
+ "level": "link",
7369
+ "quickEdit": quickEditSchema,
7370
+ "onEvent": {
7371
+ "click": {
7372
+ "actions": [
7373
+ {
7374
+ "args": {
7375
+ "api": {
7376
+ "url": "${context.rootUrl}/api/files/files/${versions[0]}?download=true",
7377
+ "method": "get",
7378
+ "headers": {
7379
+ "Authorization": "Bearer ${context.tenantId},${context.authToken}"
7380
+ }
7337
7381
  }
7338
- });
7382
+ },
7383
+ "actionType": "download",
7384
+ "expression": "!!!window?.nw?.require"//浏览器上直接下载
7385
+ },
7386
+ {
7387
+ "args": {},
7388
+ "actionType": "custom",
7389
+ "script": previewFileScript,
7390
+ "expression": "!!window?.nw?.require" //PC客户端预览附件
7339
7391
  }
7340
- }else{
7341
- data[item] = [{
7342
- value: fileFieldValue,
7343
- name: fileFieldDisplayValue.name,
7344
- url: fileFieldDisplayValue.url + "?download=true",
7345
- state: "uploaded"
7346
- }];
7347
- }
7392
+ ]
7393
+ }
7348
7394
  }
7349
- })
7350
- `
7351
- }
7352
-
7353
- async function getEditFormInitApi(object, recordId, fields, options){
7354
- const data = await getFindOneQuery$1(object, recordId, fields);
7355
- data.recordId = "${recordId}";
7356
- data.objectName = "${objectName}";
7357
- data.uiSchema = "${uiSchema}";
7358
- data.global = "${global}";
7359
- data.context = "${context}";
7360
- data.defaultData = "${defaultData}";
7361
- data._master = "${_master}";
7362
-
7363
- return {
7364
- method: "post",
7365
- url: getApi$2() + '&objectName=${objectName}' ,
7366
- // sendOn: "!!this.recordId",
7367
- cache: API_CACHE,
7368
- requestAdaptor: `
7369
- // 所有不想在network请求中发送的数据都应该从data中分离出来,data变量只需要留下query才需要发送出去
7370
- var { recordId, objectName, uiSchema, global, context, ...data} = api.data;
7371
- if(!recordId){
7372
- // 新建则不请求任何数据
7373
- data.query = "{data:" + objectName + "(filters: " + JSON.stringify(["_id", "=", null]) + ", top: 1){_id}}";
7395
+ });
7396
+ }else if(field.type === 'toggle'){
7397
+ columns.push(Object.assign({}, {
7398
+ type: "switch",
7399
+ name: field.name,
7400
+ label: field.label,
7401
+ width: field.width,
7402
+ toggled: field.toggled,
7403
+ className:"whitespace-nowrap"
7404
+ }, field.amis, {name: field.name}));
7405
+ }else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7406
+ columns.push(Object.assign({}, {
7407
+ type: "switch",
7408
+ name: field.name,
7409
+ label: field.label,
7410
+ width: field.width,
7411
+ toggled: field.toggled,
7412
+ quickEdit: quickEditSchema,
7413
+ className:"whitespace-nowrap",
7414
+ ...getAmisFileReadonlySchema(field)
7415
+ }, field.amis, {name: field.name}));
7374
7416
  }
7375
- api.data = data;
7376
- ${options.initApiRequestAdaptor || ''}
7377
- return api;
7378
- `,
7379
- adaptor: `
7380
- const recordId = api.body.recordId;
7381
- let initialValues={};
7382
- if(recordId && payload.data.data){
7383
- var data = payload.data.data[0];
7384
- const dataKeys = _.keys(data);
7385
- const uiSchema = api.body.uiSchema;
7386
- const fieldKeys = uiSchema && _.keys(uiSchema.fields);
7387
-
7388
- if(data){
7389
- ${getScriptForAddUrlPrefixForImgFields(fields)}
7390
- ${getScriptForRewriteValueForFileFields(fields)}
7391
-
7392
- _.each(dataKeys, function(key){
7393
- if(fieldKeys.indexOf(key)<0){
7394
- delete data[key];
7395
- }
7396
- })
7397
-
7398
- //初始化接口返回的字段移除字段值为null的字段
7399
- for (key in data){
7400
- if(data[key] === null){
7401
- delete data[key];
7402
- }
7403
- }
7404
- };
7405
- initialValues = data;
7417
+ else if(field.type === 'select'){
7418
+ const map = getSelectMap(field.options);
7419
+ columns.push(Object.assign({}, {
7420
+ type: "mapping",
7421
+ name: field.name,
7422
+ label: field.label,
7423
+ map: map,
7424
+ sortable: field.sortable,
7425
+ width: field.width,
7426
+ toggled: field.toggled,
7427
+ className:"whitespace-nowrap",
7428
+ quickEdit: quickEditSchema
7429
+ }, field.amis, {name: field.name}));
7406
7430
  }
7407
- else{
7408
- var uiSchema = api.body.uiSchema;
7409
- var defaultData = api.body.defaultData;
7410
- var defaultValues = {};
7411
- _.each(uiSchema?.fields, function(field){
7412
- var value = SteedosUI.getFieldDefaultValue(field, api.body.global);
7413
- if(value){
7414
- defaultValues[field.name] = value;
7415
- }
7416
- });
7417
- if(defaultData && _.isObject(defaultData) && !_.isArray(defaultData)){
7418
- defaultValues = Object.assign({}, defaultValues, defaultData)
7431
+ else {
7432
+ const tpl = await getFieldTpl(field, options);
7433
+ let type = 'text';
7434
+ if(tpl){
7435
+ type = 'tpl';
7436
+ }else if(field.type === 'html'){
7437
+ type = 'markdown';
7438
+ }else if(field.type === 'url' && field.show_as_qr){
7439
+ type = 'qr-code';
7419
7440
  }
7420
- if(uiSchema.form){
7421
- try{
7422
- var objectFormConfig = JSON.parse(uiSchema.form);
7423
- var formInitialValuesFun = objectFormConfig.initialValues;
7424
- if(formInitialValuesFun){
7425
- formInitialValuesFun = new Function("return " + formInitialValuesFun)();
7426
- }
7427
- if(typeof formInitialValuesFun === "function"){
7428
- initialValues = formInitialValuesFun.apply({doc: defaultValues || {} , global: api.body.global, master: api.body._master })
7429
- }
7430
- }
7431
- catch(ex){
7432
- console.warn(ex);
7433
- }
7441
+ let className = "";
7442
+ if(field.type === 'textarea'){
7443
+ className = 'min-w-56';
7434
7444
  }
7435
- if(_.isObject(initialValues)){
7436
- // uiSchema.form.initialValues为函数且执行后为json,则优先取initialValues中的默认值
7437
- initialValues = Object.assign({}, defaultValues, initialValues);
7445
+ if(field.wrap === false){
7446
+ className += " whitespace-nowrap";
7438
7447
  }
7439
- else{
7440
- initialValues = defaultValues;
7448
+ if(!field.hidden && !field.extra){
7449
+ columns.push(Object.assign({}, {
7450
+ name: field.name,
7451
+ label: field.label,
7452
+ sortable: field.sortable,
7453
+ // searchable: field.searchable,
7454
+ width: field.width,
7455
+ type: type,
7456
+ tpl: tpl,
7457
+ toggled: field.toggled,
7458
+ className,
7459
+ quickEdit: quickEditSchema,
7460
+ options: field.type === 'html' ? {html: true} : null
7461
+ // toggled: true
7462
+ }, field.amis, {name: field.name}));
7441
7463
  }
7442
7464
  }
7443
- // data下的变量需要在保存接口(getSaveApi)中被删除。
7444
- payload.data = {
7445
- ...initialValues
7446
- }
7447
- ${options.initApiAdaptor || ''}
7448
- return payload;
7449
- `,
7450
- responseData: {
7451
- initialValues: "$$",
7452
- editFormInited: true
7453
- },
7454
- data: data,
7455
- headers: {
7456
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7457
- }
7458
7465
  }
7466
+ // columns.push(getOperation(fields));
7467
+ if(!___default__namespace.some(columns, { name: options.labelFieldName })){
7468
+ const href = Router$1.getObjectDetailPath({
7469
+ ...options, formFactor: options.formFactor, appId: "${appId}", objectName: options.objectName || "${objectName}", recordId: `\${${options.idFieldName}}`
7470
+ });
7471
+ columns[0].type = "tpl";
7472
+ columns[0].tpl = `<a href="${href}">\${${columns[0].name}}</a>`;
7473
+ }
7474
+ return columns;
7459
7475
  }
7460
7476
 
7477
+ /**
7478
+ * 生成移动端列表每行显示的amis行
7479
+ * @param {*} tpls 要显示的每个字段的tpl
7480
+ * @returns {
7481
+ "type": "wrapper",
7482
+ "body": [{
7483
+ "type": "tpl",
7484
+ "tpl": tpls[index].tpl,
7485
+ "className": "truncate"//左侧样式类
7486
+ },{
7487
+ "type": "tpl",
7488
+ "tpl": tpls[index + 1].tpl,
7489
+ "className": "truncate ml-2 flex flex-shrink-0"//右侧样式类
7490
+ }],
7491
+ "size": "none",
7492
+ "className": "flex items-center justify-between"//每行样式类
7493
+ }
7494
+ */
7495
+ function getMobileLines(tpls){
7496
+ let lines = [];
7497
+ let maxLineCount = 2;
7498
+ let lineChildren = [];
7499
+ let isNewLine = false;
7500
+ let isLeft = true;
7501
+ let lineChildrenClassName = "";
7502
+ let lineClassName = "flex items-center justify-between h-[20px]";
7503
+ tpls.forEach(function(item){
7504
+ if(isNewLine && lines.length < maxLineCount){
7505
+ lines.push({
7506
+ "type": "wrapper",
7507
+ "body": lineChildren,
7508
+ "size": "none",
7509
+ "className": lineClassName
7510
+ });
7511
+ lineChildren = [];
7512
+ }
7513
+ if(isLeft){
7514
+ // 左侧半行
7515
+ lineChildrenClassName = "steedos-listview-item-left truncate";
7516
+ if(item.field.is_wide){
7517
+ // 左侧全行样式可以单独写
7518
+ lineChildrenClassName = "steedos-listview-item-wide truncate";
7519
+ }
7520
+ if(lines.length === 0){
7521
+ // 第一个字段加粗黑色显示
7522
+ lineChildrenClassName += " font-bold text-gray-800";
7523
+ }
7524
+ }
7525
+ else {
7526
+ // 右侧半行
7527
+ lineChildrenClassName = "steedos-listview-item-right truncate ml-2 flex flex-shrink-0";
7528
+ }
7529
+ lineChildren.push({
7530
+ "type": "tpl",
7531
+ "tpl": item.tpl,
7532
+ "className": lineChildrenClassName
7533
+ });
7461
7534
 
7462
- function getSaveApi(object, recordId, fields, options){
7463
- return {
7464
- method: 'post',
7465
- url: getApi$2(),
7466
- data: getSaveQuery(object, recordId),
7467
- requestAdaptor: getSaveRequestAdaptor(fields, options),
7468
- responseData: {
7469
- "recordId": "${record._id}"
7470
- },
7471
- adaptor: `
7472
- if(payload.errors){
7473
- payload.status = 2;
7474
- payload.msg = window.t ? window.t(payload.errors[0].message) : payload.errors[0].message;
7535
+ if(item.field.is_wide){
7536
+ // 宽字段占整行
7537
+ isLeft = true;
7538
+ isNewLine = true;
7475
7539
  }
7476
- ${options.apiAdaptor || ''}
7477
- return payload;
7478
- `,
7479
- headers: {
7480
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7540
+ else {
7541
+ isLeft = !isLeft;
7542
+ isNewLine = isLeft;
7481
7543
  }
7544
+ });
7545
+
7546
+ if(lineChildren.length && lines.length < maxLineCount){
7547
+ lines.push({
7548
+ "type": "wrapper",
7549
+ "body": lineChildren,
7550
+ "size": "none",
7551
+ "className": lineClassName
7552
+ });
7482
7553
  }
7554
+
7555
+ return lines;
7483
7556
  }
7484
7557
 
7485
- function getBatchDelete(objectName){
7486
- return {
7487
- method: 'post',
7488
- url: getApi$2(),
7489
- requestAdaptor: `
7490
- var ids = api.data.ids.split(",");
7491
- var deleteArray = [];
7492
- ids.forEach((id,index)=>{
7493
- deleteArray.push(\`delete__\${index}:${objectName}__delete(id: "\${id}")\`);
7494
- })
7495
- api.data = {query: \`mutation{\${deleteArray.join(',')}}\`};
7496
- return api;
7497
- `,
7498
- data: {
7499
- ids: `\${ids}`
7500
- },
7501
- headers: {
7502
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7558
+ async function getMobileTableColumns(fields, options){
7559
+ const columns = [];
7560
+ let nameField = {};
7561
+ let tpls = [];
7562
+ for (const field of fields) {
7563
+ let tpl = "";
7564
+ if(field.is_name || field.name === options.labelFieldName){
7565
+ nameField = field;
7566
+ options.onlyDisplayLabel = true;
7567
+ tpl = await getFieldTpl(field, options);
7568
+ }
7569
+ else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7570
+ // 图片和附件类型字段暂时显示为附件名称,后续需要再优化
7571
+ tpl = `\${_display.${field.name}.name}`;
7572
+ }
7573
+ else {
7574
+ if(field.type === 'lookup' || field.type === 'master_detail'){
7575
+ options.onlyDisplayLabel = true;
7576
+ }
7577
+ tpl = await getFieldTpl(field, options);
7578
+ }
7579
+ if(!tpl){
7580
+ tpl = `\${${field.name}}`;
7581
+ }
7582
+ if(!field.hidden && !field.extra){
7583
+ tpls.push({ field, tpl });
7503
7584
  }
7504
7585
  }
7505
- }
7586
+ const url = getNameTplUrl(nameField, options);
7506
7587
 
7507
- /*
7508
- * @Author: baozhoutao@steedos.com
7509
- * @Date: 2022-05-26 16:02:08
7510
- * @LastEditors: baozhoutao@steedos.com
7511
- * @LastEditTime: 2023-03-13 16:01:40
7512
- * @Description:
7513
- */
7588
+ const columnLines = getMobileLines(tpls);
7514
7589
 
7515
- const getFieldSchemaArray = (formFields)=>{
7516
- let fieldSchemaArray = [];
7517
- fieldSchemaArray.length = 0;
7518
7590
 
7519
- ___default__namespace.forEach(formFields, (field) => {
7520
- if (!field.group || field.group == 'null' || field.group == '-')
7521
- field.group = '通用';
7522
- const fieldName = field.name;
7523
- let isObjectField = /\w+\.\w+/.test(fieldName);
7524
- if (field.type == 'grid' || field.type == 'object') {
7525
- // field.group = field.label
7526
- field.is_wide = true;
7527
- }
7591
+ let column = {
7592
+ name: nameField.name,
7593
+ label: nameField.label,
7594
+ sortable: nameField.sortable,
7595
+ type: "button",
7596
+ level: "link",
7597
+ actionType: "link",
7598
+ link: url,
7599
+ innerClassName: "steedos-listview-item block text-gray-500",
7600
+ body: {
7601
+ "type": "wrapper",
7602
+ "body": columnLines,
7603
+ "size": "none",
7604
+ "className": "p-1"
7605
+ }
7606
+ };
7528
7607
 
7529
- if (!isObjectField){
7530
- if(!field.hidden){
7531
- fieldSchemaArray.push(Object.assign({name: fieldName}, field, {permission: {allowEdit: true}}));
7532
- }
7608
+ if(options.objectName === 'cms_files'){
7609
+ if(window.Meteor?.isCordova){
7610
+ column = {
7611
+ ...column,
7612
+ actionType: "",
7613
+ link: "",
7614
+ onEvent: {
7615
+ "click": {
7616
+ "actions": [
7617
+ {
7618
+ "script": `
7619
+ let cms_url = "/api/files/files/"+event.data.versions[0]+"?download=true"
7620
+ Steedos.cordovaDownload(encodeURI(Steedos.absoluteUrl(cms_url)), event.data.name);
7621
+ `,
7622
+ "actionType": "custom"
7623
+ }
7624
+ ],
7625
+ "weight": 0
7626
+ }
7627
+ }
7628
+ };
7629
+ }else {
7630
+ column = {
7631
+ ...column,
7632
+ actionType: "",
7633
+ link: "",
7634
+ onEvent: {
7635
+ "click": {
7636
+ "actions": [
7637
+ {
7638
+ "args": {
7639
+ "api": {
7640
+ "url": url,
7641
+ "method": "get",
7642
+ "headers": {
7643
+ "Authorization": "Bearer ${context.tenantId},${context.authToken}"
7644
+ }
7645
+ }
7646
+ },
7647
+ "actionType": "download"
7648
+ }
7649
+ ],
7650
+ "weight": 0
7651
+ }
7652
+ }
7653
+ };
7654
+ }
7655
+
7533
7656
  }
7534
- });
7535
- return fieldSchemaArray;
7536
- };
7537
7657
 
7538
- const getSection = async (formFields, permissionFields, fieldSchemaArray, sectionName, ctx) => {
7539
- const sectionFields = ___default__namespace.filter(fieldSchemaArray, { 'group': sectionName });
7540
- if(sectionFields.length == ___default__namespace.filter(sectionFields, ['hidden', true]).length){
7541
- return ;
7542
- }
7658
+ columns.push(column);
7659
+
7543
7660
 
7544
- const fieldSetBody = [];
7661
+ return columns;
7662
+ }
7545
7663
 
7546
- for (const perField of sectionFields) {
7547
- let field = perField;
7548
- if(perField.type === 'grid'){
7549
- field = await getGridFieldSubFields(perField, formFields);
7550
- // console.log(`perField.type grid ===> field`, field)
7551
- }else if(perField.type === 'object'){
7552
- field = await getObjectFieldSubFields(perField, formFields);
7553
- // console.log(`perField.type object ===> field`, field)
7554
- }
7555
- if(field.name.indexOf(".") < 0){
7556
- ctx.__formFields = formFields;
7557
- const amisField = await convertSFieldToAmisField(field, field.readonly, ctx);
7558
- // console.log(`${field.name} amisField`, field, amisField)
7559
- if(amisField){
7560
- fieldSetBody.push(amisField);
7561
- }
7562
- }
7563
- }
7664
+ function getDefaultParams(options){
7665
+ return {
7666
+ perPage: options.top || options.perPage || config.listView.perPage
7667
+ }
7668
+ }
7564
7669
 
7565
- // fieldSet 已支持显隐控制
7566
- const sectionFieldsVisibleOn = ___default__namespace.map(___default__namespace.compact(___default__namespace.map(fieldSetBody, 'visibleOn')) , (visibleOn)=>{
7567
- return visibleOn;
7568
- });
7569
- const section = {
7570
- "type": "fieldSet",
7571
- "title": sectionName,
7572
- "collapsable": true,
7573
- "body": fieldSetBody,
7574
- };
7575
- if(sectionFieldsVisibleOn.length > 0 && fieldSetBody.length === sectionFieldsVisibleOn.length){
7576
- section.visibleOn = `${sectionFieldsVisibleOn.join(" || ")}`;
7577
- }
7578
- return section
7579
- };
7670
+ function getButtonVisibleOn(button){
7671
+ let visible= button.visible;
7580
7672
 
7581
- const getSections = async (permissionFields, formFields, ctx) => {
7582
- const fieldSchemaArray = getFieldSchemaArray(formFields);
7583
- const _sections = ___default__namespace.groupBy(fieldSchemaArray, 'group');
7584
- const sections = [];
7585
- var sectionHeaderVisibleOn=[];
7586
- for (const key in _sections) {
7587
- const section = await getSection(formFields, permissionFields, fieldSchemaArray, key, ctx);
7588
- if(section.body.length > 0){
7589
- if(section.visibleOn){
7590
- sectionHeaderVisibleOn.push(section.visibleOn);
7591
- }
7592
- sections.push(section);
7673
+ if(button._visible){
7674
+ visible = button._visible;
7593
7675
  }
7594
- }
7595
- /*
7596
- 为了实现只有一个分组时隐藏该分组标题,需要分三种情况(分组如果没有visibleon属性就代表一定显示,有visibleon需要进行判断)
7597
- 1.所有分组中只有一个分组没有visibleon,还需要判断其他有visibleon的分组是否显示,只有其他都不显示时,才需要隐藏标题;反之,有任何一个显示,就不需要隐藏标题
7598
- 2.所有分组都有visibleon
7599
- 2.1 当前分组为隐藏时,标题就设置为隐藏
7600
- 2.2 当前分组为显示时,其他分组只要有一个是显示,就显示该分组标题
7601
- 2.3 当前分组为显示时,其他分组都隐藏,就隐藏该分组标题
7602
- 3.所有分组中有两个以上的分组没有visibleon(这种情况不用处理)
7603
- */
7604
- if(ctx.mode == "edit"){
7605
- if (sections.length - sectionHeaderVisibleOn.length == 1) {
7606
- sections.forEach((section) => {
7607
- section.headingClassName = {
7608
- "hidden": `!(${sectionHeaderVisibleOn.join(" || ") || 'false'})`
7609
- };
7610
- });
7611
- } else if (sections.length == sectionHeaderVisibleOn.length) {
7612
- sections.forEach((section, index) => {
7613
- var tempSectionHeaderVisibleOn = sectionHeaderVisibleOn.slice();
7614
- tempSectionHeaderVisibleOn.splice(index, 1);
7615
- section.headingClassName = {
7616
- "hidden": `!((${tempSectionHeaderVisibleOn.join(" || ") || 'false'}) && ${sectionHeaderVisibleOn[index]})`
7617
- };
7618
- });
7619
- }
7620
- }
7621
-
7622
- return sections;
7623
- };
7624
7676
 
7625
- /*
7626
- * @Author: baozhoutao@steedos.com
7627
- * @Date: 2022-07-07 11:02:29
7628
- * @LastEditors: baozhoutao@steedos.com
7629
- * @LastEditTime: 2023-03-07 17:19:34
7630
- * @Description:
7631
- */
7677
+ if(___default.isBoolean(visible)){
7678
+ visible = visible.toString();
7679
+ }
7632
7680
 
7633
- async function getFormBody(permissionFields, formFields, ctx){
7634
- return await getSections(permissionFields, formFields, ctx);
7681
+ if(visible){
7682
+ // if(visible.indexOf("Meteor.") > 0 || visible.indexOf("Creator.") > 0 || visible.indexOf("Session.") > 0){
7683
+ // console.warn('无效的visible', visible)
7684
+ // return 'false';
7685
+ // }
7686
+ if(visible.trim().startsWith('function')){
7687
+ return `${visible}(objectName, typeof _id === 'undefined' ? null: _id, typeof record === 'undefined' ? (typeof recordPermissions === 'undefined' ? {} : recordPermissions) : record.recordPermissions, data)`
7688
+ }
7689
+ return visible;
7690
+ }
7691
+
7692
+ if(button.type === 'amis_button'){
7693
+ const amisSchema = button.amis_schema;
7694
+ if(amisSchema && amisSchema.body && amisSchema.body.length > 0){
7695
+ const btn1 = amisSchema.body[0];
7696
+ return btn1.visibleOn
7697
+ }
7698
+ }
7635
7699
  }
7636
7700
 
7637
- // lodash的defaultsDeep函数有bug,无法正确合并值为数值的节点,重写修正该函数
7638
- // 源码出处:https://github.com/nodeutils/defaults-deep
7639
- const defaultsDeep = (...args)=>{
7640
- let output = {};
7641
- ___default.toArray(args).reverse().forEach(item=> {
7642
- ___default.mergeWith(output, item, (objectValue, sourceValue) => {
7643
- return ___default.isArray(sourceValue) ? sourceValue : undefined;
7701
+ async function getTableOperation(ctx){
7702
+ const buttons = ctx.buttons;
7703
+ const operationButtons = [];
7704
+ ___default.each(buttons, (button)=>{
7705
+ if(___default.isBoolean(button.visible)){
7706
+ button.visible = button.visible.toString();
7707
+ }
7708
+ // operationButtons.push({
7709
+ // type: 'button',
7710
+ // label: button.label,
7711
+ // visibleOn: button.visible ? `${button.visible}` : (button._visible ? `${button._visible}` : null),
7712
+ // onEvent: {
7713
+ // click: {
7714
+ // actions: []
7715
+ // }
7716
+ // }
7717
+ // })
7718
+
7719
+ operationButtons.push({
7720
+ type: 'steedos-object-button',
7721
+ name: button.name,
7722
+ objectName: button.objectName,
7723
+ visibleOn: getButtonVisibleOn(button),
7724
+ className: 'antd-Button--default'
7644
7725
  });
7645
7726
  });
7646
- return output;
7647
- };
7648
-
7649
- function getBulkActions(objectSchema){
7650
- return [
7651
- {
7652
- "type": "button",
7653
- "level": "danger",
7654
- "label": "批量删除",
7655
- "actionType": "ajax",
7656
- "confirmText": "确定要删除吗",
7657
- "className": "hidden",
7658
- "id": "batchDelete",
7659
- "api": getBatchDelete(objectSchema.name),
7660
- }
7661
- // {
7662
- // "label": "批量修改",
7663
- // "actionType": "dialog",
7664
- // "dialog": {
7665
- // "title": "批量编辑",
7666
- // "name": "sample-bulk-edit",
7667
- // "body": {
7668
- // "type": "form",
7669
- // "api": "https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/sample/bulkUpdate2",
7670
- // "controls": [
7671
- // {
7672
- // "type": "hidden",
7673
- // "name": "ids"
7674
- // },
7675
- // {
7676
- // "type": "text",
7677
- // "name": "name",
7678
- // "label": "Name"
7679
- // }
7680
- // ]
7681
- // }
7682
- // }
7683
- // }
7684
- ]
7727
+ if(operationButtons.length < 1){
7728
+ return ;
7729
+ }
7730
+ return {
7731
+ type: 'operation',
7732
+ label: '操作',
7733
+ fixed: 'right',
7734
+ labelClassName: 'text-center',
7735
+ className: 'text-center steedos-listview-operation w-20',
7736
+ buttons: [
7737
+ {
7738
+ "type": "steedos-dropdown-button",
7739
+ "label": "xxx",
7740
+ "buttons": operationButtons,
7741
+ "placement": "bottomRight",
7742
+ "overlayClassName": "shadow !min-w-[160px]",
7743
+ "trigger": ["click"],
7744
+ "id": "u:c2140a365019",
7745
+ onOpenApi: {
7746
+ url: `\${context.rootUrl}/service/api/@\${objectName}/recordPermissions/\${_id}`,
7747
+ method: "get",
7748
+ data: {
7749
+ $: "$$",
7750
+ objectName: "${objectName}",
7751
+ listViewId: "${listViewId}",
7752
+ appId: "${appId}",
7753
+ formFactor: "${formFactor}",
7754
+ context: `\${context}`
7755
+ },
7756
+ headers: {
7757
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7758
+ },
7759
+ adaptor: `
7760
+ payload = {
7761
+ record: {
7762
+ recordPermissions: payload
7763
+ }
7764
+ };
7765
+ return payload;
7766
+ `,
7767
+ }
7768
+ }
7769
+ ]
7770
+ }
7685
7771
  }
7686
7772
 
7687
- async function getObjectCRUD(objectSchema, fields, options){
7688
- // console.time('getObjectCRUD');
7689
- const { top, perPage, showDisplayAs = false, displayAs, crudClassName = "" } = options;
7690
- const nonpaged = objectSchema.paging && objectSchema.paging.enabled === false;
7691
- const isTreeObject = objectSchema.enable_tree;
7692
- const bulkActions = getBulkActions(objectSchema);
7693
- const bodyProps = {
7694
- // toolbar: getToolbar(),
7695
- // headerToolbar: getObjectHeaderToolbar(objectSchema, options.formFactor, {showDisplayAs}),
7696
- headerToolbarClassName: "px-4 py-2 border-gray-300 bg-gray-100 border-solid border-b",
7697
- footerToolbar: getObjectFooterToolbar(objectSchema, options.formFactor, {
7698
- disableStatistics: options.queryCount === false
7699
- }),
7700
- filter: options.filterVisible !== false && await getObjectFilter(objectSchema, fields, options),
7701
- };
7702
- if(options.formFactor !== 'SMALL' || ["split"].indexOf(options.displayAs) == -1){
7703
- Object.assign(bodyProps, {
7704
- bulkActions: options.bulkActions != false ? bulkActions : false
7705
- });
7773
+ async function getTableSchema$1(fields, options){
7774
+ if(!options){
7775
+ options = {};
7706
7776
  }
7707
- // yml里配置的 不分页和enable_tree:true 优先级最高,组件中输入的top次之。
7708
- options.queryCount = true;
7709
- if(nonpaged || isTreeObject){
7710
- options.top = 50000;
7711
- bodyProps.footerToolbar = [];
7712
- options.queryCount = true; // 禁止翻页的时候, 需要查找总数
7713
- }else if(top){
7714
- bodyProps.footerToolbar = [];
7715
- if(options.isRelated){
7716
- options.queryCount = true;
7717
- }else {
7718
- options.queryCount = false;
7719
- }
7777
+ let columns = [];
7778
+ if(options.formFactor === 'SMALL' || ["split"].indexOf(options.displayAs) > -1){
7779
+ columns = await getMobileTableColumns(fields, options);
7720
7780
  }
7721
- // console.log(`getObjectHeaderToolbar====2===>`, options.filterVisible)
7722
- bodyProps.headerToolbar = getObjectHeaderToolbar(objectSchema, options.formFactor, {
7723
- showDisplayAs,
7724
- hiddenCount: options.queryCount === false,
7725
- headerToolbarItems: options.headerToolbarItems,
7726
- filterVisible: options.filterVisible
7727
- });
7781
+ else {
7782
+ columns = await getTableColumns$1(fields, options);
7783
+ columns.push(await getTableOperation(options));
7784
+ }
7785
+ return {
7786
+ mode: "table",
7787
+ name: "thelist",
7788
+ headerToolbarClassName: "py-2 px-2 border-gray-300 bg-gray-100 border-solid border-b",
7789
+ className: "",
7790
+ draggable: false,
7791
+ defaultParams: getDefaultParams(options),
7792
+ columns: columns,
7793
+ syncLocation: false,
7794
+ keepItemSelectionOnPageChange: true,
7795
+ checkOnItemClick: false,
7796
+ labelTpl: `\${${options.labelFieldName}}`,
7797
+ autoFillHeight: false, // 自动高度效果不理想,先关闭
7798
+ columnsTogglable: false,
7799
+ }
7800
+ }
7728
7801
 
7729
7802
 
7730
- let body = null;
7731
- const id = `listview_${objectSchema.name}`;
7732
- if(options.formFactor === 'SMALL' && false){
7733
- delete bodyProps.bulkActions;
7734
- delete bodyProps.headerToolbar;
7735
- delete bodyProps.footerToolbar;
7736
- const card = await getCardSchema(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: objectSchema.NAME_FIELD_KEY || 'name'}, options, {actions: false}));
7737
- body = Object.assign({}, card , {
7738
- type: 'crud',
7739
- primaryField: '_id',
7740
- id: id,
7741
- name: id,
7742
- keepItemSelectionOnPageChange: false,
7743
- api: await getTableApi(objectSchema, fields, options),
7744
- hiddenOn: options.tableHiddenOn,
7745
- },
7746
- bodyProps
7747
- );
7748
- }else {
7749
- let labelFieldName = objectSchema.NAME_FIELD_KEY || 'name';
7750
- // organizations 对象的历史遗留问题, fullname 被标记为了 名称字段. 在此处特殊处理.
7751
- if(objectSchema.name === 'organizations'){
7752
- labelFieldName = 'name';
7753
- }
7754
- const table = await getTableSchema$1(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: labelFieldName}, options));
7755
- delete table.mode;
7756
7803
 
7757
- body = Object.assign({}, table, {
7758
- type: 'crud',
7759
- primaryField: '_id',
7760
- affixHeader: false,
7761
- id: id,
7762
- name: id,
7763
- keepItemSelectionOnPageChange: true,
7764
- api: await getTableApi(objectSchema, fields, options),
7765
- hiddenOn: options.tableHiddenOn,
7766
- autoFillHeight: options.isRelated ? false : true,
7767
- className: `flex-auto ${crudClassName || ""}`,
7768
- bodyClassName: "bg-white",
7769
- crudClassName: crudClassName,
7770
- },
7771
- bodyProps,
7772
- );
7804
+ /**
7805
+ *
7806
+ * @param {*} mainObject
7807
+ * @param {*} fields
7808
+ * @param {*} options = {filter: listview 过滤条件, ...}
7809
+ * @returns
7810
+ */
7811
+ async function getTableApi(mainObject, fields, options){
7812
+ const searchableFields = [];
7813
+ let { filter, filtersFunction, sort, top, setDataToComponentId = '' } = options;
7814
+
7815
+ if(___default__namespace.isArray(filter)){
7816
+ filter = ___default__namespace.map(filter, function(item){
7817
+ if(item.operation){
7818
+ return [item.field, item.operation, item.value];
7819
+ }else {
7820
+ return item
7821
+ }
7822
+ });
7773
7823
  }
7824
+ if(!filter){
7825
+ filter = [];
7826
+ }
7827
+ let baseFilters = null;
7828
+ if(filter){
7829
+ baseFilters = filter;
7830
+ }
7831
+ ___default__namespace.each(fields,function(field){
7832
+ if(field.searchable){
7833
+ searchableFields.push(field.name);
7834
+ }
7835
+ });
7774
7836
 
7775
- const defaults = options.defaults;
7776
- if (defaults) {
7777
- const listSchema = defaults.listSchema || {};
7778
- body = defaultsDeep({}, listSchema, body);
7779
- const headerSchema = defaults.headerSchema;
7780
- const footerSchema = defaults.footerSchema;
7781
- if (headerSchema || footerSchema) {
7782
- let wrappedBody = [body];
7783
- if (headerSchema) {
7784
- if(___default__default["default"].isArray(headerSchema)){
7785
- wrappedBody = ___default__default["default"].union(headerSchema,wrappedBody);
7786
- }
7787
- else {
7788
- wrappedBody.unshift(headerSchema);
7789
- }
7837
+ const fileFields = {};
7838
+ const fileFieldsKeys = [];
7839
+ // 含有optionsFunction属性, 无reference_to属性的lookup字段
7840
+ const lookupFields = {};
7841
+ fields.forEach((item)=>{
7842
+ if(___default__namespace.includes(['image','avatar','file'], item.type)){
7843
+ fileFieldsKeys.push(item.name);
7844
+ fileFields[item.name] = {
7845
+ name: item.name,
7846
+ type: item.type,
7847
+ multiple: item.multiple
7848
+ };
7790
7849
  }
7791
- if (footerSchema) {
7792
- if(___default__default["default"].isArray(footerSchema)){
7793
- wrappedBody = ___default__default["default"].union(wrappedBody,footerSchema);
7794
- }
7795
- else {
7796
- wrappedBody.push(footerSchema);
7797
- }
7850
+ if(___default__namespace.includes(['lookup'], item.type) && !item.reference_to ){
7851
+ lookupFields[item.name] = item;
7798
7852
  }
7799
- body = wrappedBody;
7800
- }
7853
+ });
7854
+
7855
+ let valueField = mainObject.key_field || '_id';
7856
+ const api = await getApi(mainObject, null, fields, {count: options.queryCount, alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"`});
7857
+
7858
+ if(options.isRelated){
7859
+ api.url += "&recordId=${_master.recordId}";
7801
7860
  }
7802
- // console.timeEnd('getObjectCRUD');
7803
- // TODO: data应该只留loaded,其他属性都改为从上层传递下来
7804
- return {
7805
- type: 'service',
7806
- className: '',
7807
- id: `service_${id}`,
7808
- name: `page`,
7809
- data: {
7810
- objectName: objectSchema.name,
7811
- // _id: null,
7812
- recordPermissions: objectSchema.permissions,
7813
- uiSchema: objectSchema,
7814
- // loaded: false //crud接收适配器中设置为true,否则就是刷新浏览器第一次加载
7815
- },
7816
- body: body
7817
- }
7818
- }
7819
-
7820
- const getGlobalData = (mode)=>{
7821
- const user = getSteedosAuth();
7822
- return {mode: mode, user: user, spaceId: user.spaceId, userId: user.userId}
7823
- };
7824
7861
 
7825
- const getFormFields = (objectSchema, formProps)=>{
7826
- /**
7827
- * fieldsExtend: 重写字段定义
7828
- * fields: 包含的字段
7829
- * excludedFields: 排除的字段
7830
- */
7831
- const { fieldsExtend, fields: includedFields, excludedFields } = formProps;
7832
-
7833
- let fields = {};
7834
- // 以uiSchema fields 为基础, 遍历字段, 并更新字段定义
7835
- ___default__default["default"].forEach(objectSchema.fields, (field, fieldName)=>{
7836
- if(!lodash.has(field, "name")){
7837
- field.name = fieldName;
7862
+ api.data.$term = "$term";
7863
+ api.data.term = "$term";
7864
+ api.data.$self = "$$";
7865
+ api.data.self = "$$";
7866
+ api.data.filter = "$filter";
7867
+ api.data.loaded = "${loaded}";
7868
+ api.data.listViewId = "${listViewId}";
7869
+ api.data.listName = "${listName}";
7870
+ api.requestAdaptor = `
7871
+ // selfData 中的数据由 CRUD 控制. selfData中,只能获取到 CRUD 给定的data. 无法从数据链中获取数据.
7872
+ let selfData = JSON.parse(JSON.stringify(api.data.$self));
7873
+ // 保留一份初始data,以供自定义发送适配器中获取原始数据。
7874
+ const data = _.cloneDeep(api.data);
7875
+ try{
7876
+ // TODO: 不应该直接在这里取localStorage,应该从外面传入
7877
+ const listViewId = api.data.listViewId;
7878
+ const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
7879
+ let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
7880
+ if(localListViewProps){
7881
+ localListViewProps = JSON.parse(localListViewProps);
7882
+ selfData = Object.assign({}, localListViewProps, selfData);
7883
+ if(!api.data.filter){
7884
+ api.data.filter = localListViewProps.filter;
7885
+ }
7886
+ if(!api.data.loaded){
7887
+ // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
7888
+ // 所以会把localSearchableFilter中已经存过的页码覆盖
7889
+ // 如果是第一次加载组件始终让翻页页码从本地存储中取值
7890
+ let formFactor = "${options.formFactor}";
7891
+ // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
7892
+ api.data.pageNo = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
7893
+ }
7894
+ }
7838
7895
  }
7839
- if(fieldsExtend && fieldsExtend[fieldName]){
7840
- fields[field.name] = Object.assign({}, field, fieldsExtend[fieldName], {name: field.name});
7841
- }else {
7842
- fields[field.name] = field;
7896
+ catch(ex){
7897
+ console.error("本地存储中crud参数解析异常:", ex);
7843
7898
  }
7844
- });
7845
-
7846
- if(!___default__default["default"].isEmpty(includedFields) && ___default__default["default"].isArray(includedFields)){
7847
- const includedFieldsMap = {};
7848
- ___default__default["default"].each(includedFields, (fName, index)=>{
7849
- if(fields[fName]){
7850
- includedFieldsMap[fName] = Object.assign({}, fields[fName], {sort_no: index});
7851
- }
7852
- });
7853
- fields = includedFieldsMap;
7854
- }
7855
-
7856
- if(!___default__default["default"].isEmpty(excludedFields) && ___default__default["default"].isArray(excludedFields)){
7857
- ___default__default["default"].each(excludedFields, (fName)=>{
7858
- delete fields[fName];
7859
- });
7860
- }
7899
+ ${baseFilters ? `var systemFilters = ${JSON.stringify(baseFilters)};` : 'var systemFilters = [];'}
7900
+ var _ids = []
7901
+ const filtersFunction = ${filtersFunction};
7902
+ if(filtersFunction){
7903
+ const _filters = filtersFunction(systemFilters, api.data.$self);
7904
+ if(api.data.listName == "recent"){
7905
+ _ids = _filters[2]
7906
+ }
7907
+ if(_filters && _filters.length > 0){
7908
+ if(_.isEmpty(systemFilters)){
7909
+ systemFilters = _filters || [];
7910
+ }else{
7911
+ systemFilters = [systemFilters, 'and', _filters];
7912
+ }
7913
+ }
7914
+ }
7915
+ let userFilters =[];
7916
+
7917
+ if(_.isEmpty(systemFilters)){
7918
+ systemFilters = api.data.filter || [];
7919
+ }else{
7920
+ if(!_.isEmpty(api.data.filter)){
7921
+ systemFilters = [systemFilters, 'and', api.data.filter];
7922
+ }
7923
+ }
7924
+ var pageSize = api.data.pageSize || 10;
7925
+ var pageNo = api.data.pageNo || 1;
7926
+ var skip = (pageNo - 1) * pageSize;
7927
+ var orderBy = api.data.orderBy || '';
7928
+ var orderDir = api.data.orderDir || '';
7929
+ var sort = orderBy + ' ' + orderDir;
7930
+ sort = orderBy ? sort : "${sort || ''}";
7931
+ var allowSearchFields = ${JSON.stringify(searchableFields)};
7932
+ if(api.data.$term){
7933
+ userFilters = [["name", "contains", "'+ api.data.$term +'"]];
7934
+ }else if(selfData.op === 'loadOptions' && selfData.value){
7935
+ userFilters = [["${valueField.name}", "=", selfData.value]];
7936
+ }
7937
+
7938
+ var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
7861
7939
 
7862
- return lodash.sortBy(___default__default["default"].values(fields), "sort_no");
7863
- };
7940
+ if(searchableFilter.length > 0){
7941
+ if(userFilters.length > 0 ){
7942
+ userFilters = [userFilters, 'and', searchableFilter];
7943
+ }else{
7944
+ userFilters = searchableFilter;
7945
+ }
7946
+ }
7864
7947
 
7865
- async function getObjectForm(objectSchema, ctx){
7866
- const { recordId, formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, tabId, appId, defaults } = ctx;
7867
- const fields = ___default__default["default"].values(objectSchema.fields);
7868
- const formFields = getFormFields(objectSchema, ctx);
7869
- const formSchema = defaults && defaults.formSchema || {};
7870
- if(___default__default["default"].has(formSchema, 'className')){
7871
- formSchema.className = 'steedos-amis-form';
7948
+ if(allowSearchFields){
7949
+ allowSearchFields.forEach(function(key){
7950
+ const keyValue = selfData[key];
7951
+ if(_.isString(keyValue)){
7952
+ userFilters.push([key, "contains", keyValue]);
7953
+ }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
7954
+ userFilters.push([key, "=", keyValue]);
7955
+ }
7956
+ })
7872
7957
  }
7873
- const amisSchema = {
7874
- type: 'service',
7875
- className: 'p-0',
7876
- name: `page_edit_${recordId}`,
7877
- api: await getEditFormInitApi(objectSchema, recordId, fields, ctx),
7878
- data:{
7879
- editFormInited: false
7880
- },
7881
- // data: {global: getGlobalData('edit'), recordId: recordId, objectName: objectSchema.name, context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
7882
- initApi: null,
7883
- initFetch: null ,
7884
- body: [defaultsDeep({}, formSchema, {
7885
- type: "form",
7886
- mode: layout,
7887
- data: {
7888
- "&": "${initialValues}"
7889
- },
7890
- labelAlign,
7891
- persistData: false,
7892
- resetAfterSubmit: true,
7893
- preventEnterSubmit: true,
7894
- promptPageLeave: true,
7895
- canAccessSuperData: false,
7896
- name: `form_edit_${recordId}`,
7897
- debug: false,
7898
- title: "",
7899
- submitText: "", // amis 表单不显示提交按钮, 表单提交由项目代码接管
7900
- api: await getSaveApi(objectSchema, recordId, fields, ctx),
7901
- initFetch: recordId != 'new',
7902
- body: await getFormBody(fields, formFields, ctx),
7903
- panelClassName:'m-0 sm:rounded-lg shadow-none border-none',
7904
- bodyClassName: 'p-0',
7905
- className: 'steedos-amis-form',
7906
- hiddenOn: "${editFormInited != true}",
7907
- onEvent: {
7908
- "submitSucc": {
7909
- "weight": 0,
7910
- "actions": [
7911
- {
7912
- "actionType": "broadcast",
7913
- "args": {
7914
- "eventName": `@data.changed.${objectSchema.name}`
7915
- },
7916
- "data": {
7917
- "objectName": `${objectSchema.name}`,
7918
- "displayAs": "${displayAs}"
7958
+
7959
+ if(selfData.__keywords && allowSearchFields){
7960
+ const keywordsFilters = [];
7961
+ allowSearchFields.forEach(function(key, index){
7962
+ const keyValue = selfData.__keywords;
7963
+ if(keyValue){
7964
+ keywordsFilters.push([key, "contains", keyValue]);
7965
+ if(index < allowSearchFields.length - 1){
7966
+ keywordsFilters.push('or');
7919
7967
  }
7920
- },
7921
- {
7922
- "actionType": "broadcast",
7923
- "args": {
7924
- "eventName": "@data.changed.${_master.objectName}"
7925
- },
7926
- "data": {
7927
- "objectName": "${_master.objectName}",
7928
- "_isRelated": "${_isRelated || _master._isRelated}"
7929
- },
7930
- "expression": `\${_master.objectName != '${objectSchema.name}' && _master.objectName}`
7931
- },
7932
- // {
7933
- // "actionType": "custom",
7934
- // "script": "debugger;"
7935
- // },
7936
- // {
7937
- // "args": {},
7938
- // "actionType": "closeDialog"
7939
- // }
7940
- ]
7941
- }
7942
- }
7943
- })]
7968
+ }
7969
+ })
7970
+ userFilters.push(keywordsFilters);
7944
7971
  };
7945
- if(formSchema.id){
7946
- amisSchema.id = `service-${formSchema.id}`;
7972
+
7973
+ let filters = [];
7974
+
7975
+ if(!_.isEmpty(systemFilters)){
7976
+ filters = systemFilters;
7977
+ };
7978
+ if(api.data.$self.additionalFilters){
7979
+ if(_.isString(api.data.$self.additionalFilters)){
7980
+ userFilters.push(eval(api.data.$self.additionalFilters))
7981
+ }else{
7982
+ userFilters.push(api.data.$self.additionalFilters)
7983
+ }
7947
7984
  }
7948
- return amisSchema;
7949
- }
7950
7985
 
7951
- async function getObjectDetail(objectSchema, recordId, ctx){
7952
- const { formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, formInitProps } = ctx;
7953
- const fields = ___default__default["default"].values(objectSchema.fields);
7954
- const formFields = getFormFields(objectSchema, ctx);
7955
- const serviceId = `service_detail_page`;
7956
- return {
7957
- type: 'service',
7958
- name: `page_readonly_${recordId}`,
7959
- id: serviceId,
7960
- data: {global: getGlobalData('read'), context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
7961
- api: await getReadonlyFormInitApi(objectSchema, recordId, fields, formInitProps),
7962
- body: [
7963
- {
7964
- "type": "wrapper", //form 的 hiddenOn 会导致 form onEvent 异常, 使用wrapper包裹一次form,并在wrapper上控制显隐
7965
- hiddenOn: "${recordLoaded != true}",
7966
- "className": "p-0 m-0",
7967
- "body": {
7968
- type: "form",
7969
- mode: layout,
7970
- labelAlign,
7971
- persistData: false,
7972
- promptPageLeave: false,
7973
- name: `form_readonly_${recordId}`,
7974
- debug: false,
7975
- title: "",
7976
- data: {
7977
- "formData": "$$"
7978
- },
7979
- wrapWithPanel: false,
7980
- body: await getFormBody(___default.map(fields, (field)=>{field.readonly = true; return field;}), ___default.map(formFields, (field)=>{field.readonly = true; return field;}), Object.assign({}, ctx, {showSystemFields: true})),
7981
- className: 'steedos-amis-form bg-white',
7982
- actions: [], // 不显示表单默认的提交按钮
7983
- onEvent: {
7984
- [`@data.changed.${objectSchema.name}`]: { // 由于amis service 组件的 onEvent 存在bug ,此处借助form来刷新 上层 service https://github.com/baidu/amis/issues/6294
7985
- "actions": [
7986
- {
7987
- "actionType": "reload",
7988
- "componentId": serviceId,
7989
- "expression": "this.__deletedRecord != true"
7990
- },
7991
- {
7992
- // "args": {
7993
- // "url": "/app/${appId}/${objectName}/grid/${side_listview_id}",
7994
- // "blank": false
7995
- // },
7996
- "actionType": "custom",
7997
- "script": "Steedos.goBack()",
7998
- "expression": "this.__deletedRecord === true"
7999
- }
8000
- ]
8001
- }
8002
- }
8003
- },
8004
- }
8005
- ],
8006
- onEvent: {
8007
- "fetchInited": {
8008
- "weight": 0,
8009
- "actions": [
8010
- {
8011
- actionType: 'broadcast',
8012
- eventName: "recordLoaded",
8013
- args: {
8014
- eventName: "recordLoaded"
8015
- },
8016
- data: {
8017
- objectName: "${event.data.__objectName}",
8018
- record: "${event.data.__record}"
8019
- },
8020
- expression: "${event.data.__response.error != true}"
8021
- },
8022
- {
8023
- "actionType": "setValue",
8024
- "args": {
8025
- value: {
8026
- "recordLoaded": true,
8027
- }
8028
- },
8029
- expression: "${event.data.__response.error != true}"
8030
- }
8031
- ]
8032
- }
7986
+ if(api.data.$self._isRelated){
7987
+ const self = api.data.$self;
7988
+ const relatedKey = self.relatedKey;
7989
+ const refField = self.uiSchema.fields[relatedKey];
7990
+ const masterRecord = self._master.record;
7991
+ const masterObjectName = self._master.objectName;
7992
+ let relatedValue = self._master.recordId;
7993
+ if(refField.reference_to_field && refField.reference_to_field != '_id'){
7994
+ relatedValue = masterRecord[refField.reference_to_field]
7995
+ }
7996
+ let relatedFilters;
7997
+ if (
7998
+ refField._reference_to ||
7999
+ (refField.reference_to && !_.isString(refField.reference_to))
8000
+ ) {
8001
+ relatedFilters = [
8002
+ [relatedKey + "/o", "=", masterObjectName],
8003
+ [relatedKey + "/ids", "=", relatedValue],
8004
+ ];
8005
+ } else {
8006
+ relatedFilters = [relatedKey, "=", relatedValue];
8033
8007
  }
8008
+ userFilters.push(relatedFilters)
8034
8009
  }
8035
- }
8036
8010
 
8037
- /*
8038
- * @Author: baozhoutao@steedos.com
8039
- * @Date: 2022-08-04 10:42:49
8040
- * @LastEditors: baozhoutao@steedos.com
8041
- * @LastEditTime: 2022-08-25 10:28:47
8042
- * @Description:
8043
- */
8044
- var config = {
8045
- listView: {
8046
- newRecordMode: 'modal',
8047
- editRecordMode: 'modal',
8048
- perPage: 20
8011
+ if(!_.isEmpty(userFilters)){
8012
+ if(_.isEmpty(filters)){
8013
+ filters = userFilters;
8014
+ }else{
8015
+ filters = [filters, 'and', userFilters]
8016
+ }
8049
8017
  }
8050
- };
8051
-
8052
- async function getTableColumns$1(fields, options){
8053
- const columns = [{name: '_index',type: 'text', width: 32, placeholder: ""}];
8054
- for (const field of fields) {
8055
- if((field.is_name || field.name === options.labelFieldName) && options.objectName === 'cms_files'){
8056
- const previewFileScript = `
8057
- var data = event.data;
8058
- var file_name = data.versions ? data.name : "${field.label}";
8059
- var file_id = data._id;
8060
- SteedosUI.previewFile && SteedosUI.previewFile({file_name, file_id});
8061
- `;
8062
- columns.push({
8063
- "type": "button",
8064
- "label": `<%=data.versions ? data.name : "${field.label}"%>`,
8065
- "className": "whitespace-nowrap",
8066
- "level": "link",
8067
- "onEvent": {
8068
- "click": {
8069
- "actions": [
8070
- {
8071
- "args": {
8072
- "api": {
8073
- "url": "${context.rootUrl}/api/files/files/${versions[0]}?download=true",
8074
- "method": "get",
8075
- "headers": {
8076
- "Authorization": "Bearer ${context.tenantId},${context.authToken}"
8077
- }
8078
- }
8079
- },
8080
- "actionType": "download",
8081
- "expression": "!!!window?.nw?.require"//浏览器上直接下载
8082
- },
8083
- {
8084
- "args": {},
8085
- "actionType": "custom",
8086
- "script": previewFileScript,
8087
- "expression": "!!window?.nw?.require" //PC客户端预览附件
8088
- }
8089
- ]
8090
- }
8091
- }
8092
- });
8093
- }else if(field.type === 'toggle'){
8094
- columns.push(Object.assign({}, {
8095
- type: "switch",
8096
- name: field.name,
8097
- label: field.label,
8098
- width: field.width,
8099
- toggled: field.toggled,
8100
- disabled: true,
8101
- className:"whitespace-nowrap",
8102
- }, field.amis, {name: field.name}));
8103
- }else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
8104
- columns.push(Object.assign({}, {
8105
- type: "switch",
8106
- name: field.name,
8107
- label: field.label,
8108
- width: field.width,
8109
- toggled: field.toggled,
8110
- disabled: true,
8111
- className:"whitespace-nowrap",
8112
- ...getAmisFileReadonlySchema(field)
8113
- }, field.amis, {name: field.name}));
8018
+ api.data._ids = _ids;
8019
+ api.data = {
8020
+ query: api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim())
8021
+ }
8022
+ ${options.requestAdaptor || ''}
8023
+ return api;
8024
+ `;
8025
+ api.adaptor = `
8026
+ if(api.body.listName == "recent"){
8027
+ payload.data.rows = _.sortBy(payload.data.rows, function(item){
8028
+ return _.indexOf(api.body._ids, item._id)
8029
+ });
8030
+ }
8031
+ const enable_tree = ${mainObject.enable_tree};
8032
+ if(!enable_tree){
8033
+ _.each(payload.data.rows, function(item, index){
8034
+ const {pageNo, pageSize} = api.body;
8035
+ const skip = (pageNo - 1) * pageSize;
8036
+ item._index = skip + index + 1;
8037
+ })
8038
+ }
8039
+ window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8040
+ let fileFields = ${JSON.stringify(fileFields)};
8041
+ let lookupFields = ${JSON.stringify(lookupFields)};
8042
+ _.each(payload.data.rows, function(item, index){
8043
+ _.each(fileFields , (field, key)=>{
8044
+ if(item[key] && item._display && item._display[key]){
8045
+ let value = item._display[key];
8046
+ if(!_.isArray(value)){
8047
+ value = [value]
8048
+ };
8049
+ if(field.type === 'file'){
8050
+ item[key] = value
8051
+ }else{
8052
+ item[key] = _.map(value, 'url')
8053
+ }
8114
8054
  }
8115
- else if(field.type === 'select'){
8116
- const map = getSelectMap(field.options);
8117
- columns.push(Object.assign({}, {
8118
- type: "mapping",
8119
- name: field.name,
8120
- label: field.label,
8121
- map: map,
8122
- sortable: field.sortable,
8123
- width: field.width,
8124
- toggled: field.toggled,
8125
- className:"whitespace-nowrap",
8126
- }, field.amis, {name: field.name}));
8055
+ })
8056
+ _.each(lookupFields , (field, key)=>{
8057
+ if(item[key]){
8058
+ if(field._optionsFunction){
8059
+ const optionsFunction = eval("(" + field._optionsFunction+ ")")(item);
8060
+ item[key + '__label'] = _.map(_.filter(optionsFunction, function(option){return _.includes(item[key], option.value)}), 'label').join(' ');
8061
+ }
8127
8062
  }
8128
- else {
8129
- const tpl = await getFieldTpl(field, options);
8063
+ })
8064
+ })
8065
+
8066
+ if(enable_tree){
8067
+ const records = payload.data.rows || [];
8068
+ const getTreeOptions = SteedosUI.getTreeOptions
8069
+ payload.data.rows = getTreeOptions(records,{"valueField":"_id"});
8070
+ }
8130
8071
 
8131
- let type = 'text';
8132
- if(tpl){
8133
- type = 'tpl';
8134
- }else if(field.type === 'html'){
8135
- type = 'markdown';
8136
- }else if(field.type === 'url' && field.show_as_qr){
8137
- type = 'qr-code';
8138
- }
8139
- let className = "";
8140
- if(field.type === 'textarea'){
8141
- className = 'min-w-56';
8142
- }
8143
- if(field.wrap === false){
8144
- className += " whitespace-nowrap";
8145
- }
8146
- if(!field.hidden && !field.extra){
8147
- columns.push(Object.assign({}, {
8148
- name: field.name,
8149
- label: field.label,
8150
- sortable: field.sortable,
8151
- // searchable: field.searchable,
8152
- width: field.width,
8153
- type: type,
8154
- tpl: tpl,
8155
- toggled: field.toggled,
8156
- className,
8157
- options: field.type === 'html' ? {html: true} : null
8158
- // toggled: true
8159
- }, field.amis, {name: field.name}));
8160
- }
8072
+
8073
+ try{
8074
+ // TODO: 不应该直接在这里取localStorage,应该从外面传入
8075
+ const listViewId = api.body.listViewId;
8076
+ const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
8077
+ /**
8078
+ * localListViewProps规范来自crud请求api中api.data.$self参数值的。
8079
+ * 比如:{"perPage":20,"page":1,"__searchable__name":"7","__searchable__between__n1__c":[null,null],"filter":[["name","contains","a"]]}
8080
+ * __searchable__...:顶部放大镜搜索条件
8081
+ * filter:右侧过滤器
8082
+ * perPage:每页条数
8083
+ * page:当前页码
8084
+ * orderBy:排序字段
8085
+ * orderDir:排序方向
8086
+ */
8087
+ let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
8088
+ let selfData = JSON.parse(JSON.stringify(api.body.$self));
8089
+ if(localListViewProps){
8090
+ localListViewProps = JSON.parse(localListViewProps);
8091
+ selfData = Object.assign({}, localListViewProps, selfData, { filter: api.body.filter });
8092
+ if(!api.body.loaded){
8093
+ // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
8094
+ // 所以会把localSearchableFilter中已经存过的页码覆盖
8095
+ // 如果是第一次加载组件始终让翻页页码从本地存储中取值
8096
+ let formFactor = "${options.formFactor}";
8097
+ // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
8098
+ selfData.page = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
8161
8099
  }
8162
-
8163
- }
8164
- // columns.push(getOperation(fields));
8165
- if(!___default__namespace.some(columns, { name: options.labelFieldName })){
8166
- const href = Router$1.getObjectDetailPath({
8167
- ...options, formFactor: options.formFactor, appId: "${appId}", objectName: options.objectName || "${objectName}", recordId: `\${${options.idFieldName}}`
8168
- });
8169
- columns[0].type = "tpl";
8170
- columns[0].tpl = `<a href="${href}">\${${columns[0].name}}</a>`;
8171
8100
  }
8172
- return columns;
8101
+ delete selfData.context;
8102
+ delete selfData.global;
8103
+ sessionStorage.setItem(listViewPropsStoreKey, JSON.stringify(selfData));
8104
+ // 返回页码到UI界面
8105
+ payload.data.page= selfData.page;
8106
+ }
8107
+ catch(ex){
8108
+ console.error("本地存储中crud参数解析异常:", ex);
8173
8109
  }
8110
+ // 标记加载过,后续优先从本地存储中加载相关参数
8111
+ payload.data.loaded= true;
8174
8112
 
8175
- /**
8176
- * 生成移动端列表每行显示的amis行
8177
- * @param {*} tpls 要显示的每个字段的tpl
8178
- * @returns {
8179
- "type": "wrapper",
8180
- "body": [{
8181
- "type": "tpl",
8182
- "tpl": tpls[index].tpl,
8183
- "className": "truncate"//左侧样式类
8184
- },{
8185
- "type": "tpl",
8186
- "tpl": tpls[index + 1].tpl,
8187
- "className": "truncate ml-2 flex flex-shrink-0"//右侧样式类
8188
- }],
8189
- "size": "none",
8190
- "className": "flex items-center justify-between"//每行样式类
8113
+ const setDataToComponentId = "${setDataToComponentId}";
8114
+ if(setDataToComponentId){
8115
+ SteedosUI.getRef(api.body.$self.$scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8116
+ };
8117
+ ${options.adaptor || ''}
8118
+ return payload;
8119
+ `;
8120
+ return api;
8121
+ }
8122
+
8123
+ async function getApi(object, recordId, fields, options){
8124
+ const data = await getFindQuery(object, recordId, fields, options);
8125
+ return {
8126
+ method: "post",
8127
+ url: getApi$2(), // + "&recordId=${recordId}"
8128
+ data: data,
8129
+ headers: {
8130
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8131
+ }
8191
8132
  }
8192
- */
8193
- function getMobileLines(tpls){
8194
- let lines = [];
8195
- let maxLineCount = 2;
8196
- let lineChildren = [];
8197
- let isNewLine = false;
8198
- let isLeft = true;
8199
- let lineChildrenClassName = "";
8200
- let lineClassName = "flex items-center justify-between h-[20px]";
8201
- tpls.forEach(function(item){
8202
- if(isNewLine && lines.length < maxLineCount){
8203
- lines.push({
8204
- "type": "wrapper",
8205
- "body": lineChildren,
8206
- "size": "none",
8207
- "className": lineClassName
8208
- });
8209
- lineChildren = [];
8133
+ }
8134
+
8135
+ function getRecordPermissionsApi(object, recordId, options){
8136
+ const data = getRecordPermissionsQuery(object, recordId, options);
8137
+ return {
8138
+ method: "post",
8139
+ url: getApi$2(),
8140
+ data: data,
8141
+ headers: {
8142
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8210
8143
  }
8211
- if(isLeft){
8212
- // 左侧半行
8213
- lineChildrenClassName = "steedos-listview-item-left truncate";
8214
- if(item.field.is_wide){
8215
- // 左侧全行样式可以单独写
8216
- lineChildrenClassName = "steedos-listview-item-wide truncate";
8144
+ }
8145
+ }
8146
+
8147
+ const API_CACHE = 100;
8148
+
8149
+ function getReadonlyFormAdaptor(object, fields){
8150
+ let scriptStr = '';
8151
+ const selectFields = ___default__namespace.filter(fields, function(field){return field.name.indexOf('.') < 0 && ((field.type == 'select' && field.options) || ((field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to))});
8152
+ const gridAndObjectFieldsName = ___default__namespace.map(___default__namespace.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type === 'object' || field.type === 'grid')}), 'name');
8153
+ ___default__namespace.each(selectFields, function(field){
8154
+ if(!___default__namespace.includes(OMIT_FIELDS, field.name)){
8155
+ field.name;
8156
+ if(field.options){
8157
+ const options = JSON.stringify({options: field.options});
8158
+ scriptStr = scriptStr + `var ${field.name}Options= (${options}).options;`;
8159
+ }else if(field.optionsFunction){
8160
+ scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`;
8161
+ }else if(field._optionsFunction){
8162
+ scriptStr = scriptStr + `var ${field.name}Options = eval(${field._optionsFunction})(api.data);`;
8217
8163
  }
8218
- if(lines.length === 0){
8219
- // 第一个字段加粗黑色显示
8220
- lineChildrenClassName += " font-bold text-gray-800";
8164
+ if(field.multiple){
8165
+ scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`;
8166
+ }else {
8167
+ scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`;
8168
+ scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`;
8221
8169
  }
8222
8170
  }
8223
- else {
8224
- // 右侧半行
8225
- lineChildrenClassName = "steedos-listview-item-right truncate ml-2 flex flex-shrink-0";
8226
- }
8227
- lineChildren.push({
8228
- "type": "tpl",
8229
- "tpl": item.tpl,
8230
- "className": lineChildrenClassName
8231
- });
8171
+ });
8232
8172
 
8233
- if(item.field.is_wide){
8234
- // 宽字段占整行
8235
- isLeft = true;
8236
- isNewLine = true;
8173
+ // const refFields = _.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to});
8174
+ // _.each(refFields, function(field){
8175
+ // if(!_.includes(OMIT_FIELDS, field.name)){
8176
+ // const valueField = field.reference_to_field || '_id';
8177
+ // scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`
8178
+ // if(field.multiple){
8179
+ // scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`
8180
+ // }else{
8181
+ // scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`
8182
+ // scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`
8183
+ // }
8184
+ // }
8185
+ // })
8186
+
8187
+ return `
8188
+ if(payload.data.data.length === 0){
8189
+ return {
8190
+ status: 2,
8191
+ msg: "无法找到记录"
8192
+ }
8193
+ }
8194
+ if(payload.data.data){
8195
+ var data = payload.data.data[0];
8196
+ var gridAndObjectFieldsName = ${JSON.stringify(gridAndObjectFieldsName)};
8197
+ try{
8198
+ ${scriptStr}
8199
+ ${getScriptForAddUrlPrefixForImgFields(fields)}
8200
+ ${getScriptForRewriteValueForFileFields(fields)}
8201
+ }catch(e){
8202
+ console.error(e)
8203
+ }
8204
+ // 原始记录
8205
+ var record = _.cloneDeep(data);
8206
+ try{
8207
+ _.each(gridAndObjectFieldsName, function(name){
8208
+ data[name] = data._display[name];
8209
+ })
8210
+ }catch(e){
8211
+ console.error(e)
8212
+ }
8213
+ payload.data = data;
8214
+ payload.data.__objectName = "${object.name}";
8215
+ payload.data.__record = record;
8216
+ window.postMessage(Object.assign({type: "record.loaded"}, {record: record}), "*")
8217
+ }
8218
+ if(payload.errors){
8219
+ payload.status = 2;
8220
+ payload.msg = payload.errors[0].message;
8221
+ }
8222
+ return payload;
8223
+ `
8224
+ }
8225
+
8226
+ async function getReadonlyFormInitApi(object, recordId, fields, options){
8227
+ return {
8228
+ method: "post",
8229
+ url: getApi$2()+"&recordId=${recordId}",
8230
+ cache: API_CACHE,
8231
+ // requestAdaptor: "console.log('getReadonlyFormInitApi requestAdaptor', api);return api;",
8232
+ adaptor: getReadonlyFormAdaptor(object, fields),
8233
+ data: await getFindOneQuery$1(object, recordId, fields, options),
8234
+ headers: {
8235
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8237
8236
  }
8238
- else {
8239
- isLeft = !isLeft;
8240
- isNewLine = isLeft;
8237
+ }
8238
+ }
8239
+
8240
+ /*
8241
+ img/avatar字段值添加URL前缀使其在amis中正常显示图片。
8242
+ */
8243
+ function getScriptForAddUrlPrefixForImgFields(fields){
8244
+ let imgFieldsKeys = [];
8245
+ let imgFields = {};
8246
+ fields.forEach((item)=>{
8247
+ if(___default__namespace.includes(['image','avatar'], item.type)){
8248
+ imgFieldsKeys.push(item.name);
8249
+ imgFields[item.name] = {
8250
+ name: item.name,
8251
+ type: item.type,
8252
+ multiple: item.multiple
8253
+ };
8241
8254
  }
8242
8255
  });
8243
-
8244
- if(lineChildren.length && lines.length < maxLineCount){
8245
- lines.push({
8246
- "type": "wrapper",
8247
- "body": lineChildren,
8248
- "size": "none",
8249
- "className": lineClassName
8250
- });
8256
+ if(!imgFieldsKeys.length){
8257
+ return '';
8251
8258
  }
8252
-
8253
- return lines;
8259
+ return `
8260
+ // image字段值添加URL前缀
8261
+ let imgFieldsKeys = ${JSON.stringify(imgFieldsKeys)};
8262
+ let imgFields = ${JSON.stringify(imgFields)};
8263
+ imgFieldsKeys.forEach((item)=>{
8264
+ let imgFieldValue = data[item];
8265
+ let imgFieldDisplayValue = data._display && data._display[item];
8266
+ if(imgFieldValue && imgFieldValue.length){
8267
+ let fieldProps = imgFields[item];
8268
+ if(fieldProps.multiple){
8269
+ if(imgFieldDisplayValue instanceof Array){
8270
+ data[item] = imgFieldDisplayValue.map((i)=>{ return i.url });
8271
+ }
8272
+ }else{
8273
+ data[item] = imgFieldDisplayValue && imgFieldDisplayValue.url;
8274
+ }
8275
+ }
8276
+ })
8277
+ `
8254
8278
  }
8255
8279
 
8256
- async function getMobileTableColumns(fields, options){
8257
- const columns = [];
8258
- let nameField = {};
8259
- let tpls = [];
8260
- for (const field of fields) {
8261
- let tpl = "";
8262
- if(field.is_name || field.name === options.labelFieldName){
8263
- nameField = field;
8264
- options.onlyDisplayLabel = true;
8265
- tpl = await getFieldTpl(field, options);
8266
- }
8267
- else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
8268
- // 图片和附件类型字段暂时显示为附件名称,后续需要再优化
8269
- tpl = `\${_display.${field.name}.name}`;
8270
- }
8271
- else {
8272
- if(field.type === 'lookup' || field.type === 'master_detail'){
8273
- options.onlyDisplayLabel = true;
8274
- }
8275
- tpl = await getFieldTpl(field, options);
8276
- }
8277
- if(!tpl){
8278
- tpl = `\${${field.name}}`;
8280
+ /*
8281
+ file字段值重写使其在amis中正常显示附件名、点击附件名下载文件。
8282
+ */
8283
+ function getScriptForRewriteValueForFileFields(fields){
8284
+ let fileFieldsKeys = [];
8285
+ let fileFields = {};
8286
+ fields.forEach((item)=>{
8287
+ if(item.type === 'file'){
8288
+ fileFieldsKeys.push(item.name);
8289
+ fileFields[item.name] = {
8290
+ name: item.name,
8291
+ multiple: item.multiple
8292
+ };
8279
8293
  }
8280
- if(!field.hidden && !field.extra){
8281
- tpls.push({ field, tpl });
8294
+ });
8295
+ if(!fileFieldsKeys.length){
8296
+ return '';
8297
+ }
8298
+ return `
8299
+ // file字段值重写以便编辑时正常显示附件名、点击附件名正常下载附件
8300
+ let fileFieldsKeys = ${JSON.stringify(fileFieldsKeys)};
8301
+ let fileFields = ${JSON.stringify(fileFields)};
8302
+ fileFieldsKeys.forEach((item)=>{
8303
+ let fileFieldValue = data[item];
8304
+ let fileFieldDisplayValue = data._display && data._display[item];
8305
+ if(fileFieldValue && fileFieldValue.length){
8306
+ if(fileFields[item].multiple){
8307
+ if(fileFieldDisplayValue instanceof Array){
8308
+ data[item] = fileFieldDisplayValue.map((item, index)=>{
8309
+ return {
8310
+ value: fileFieldValue[index],
8311
+ name: item.name,
8312
+ url: item.url + "?download=true",
8313
+ state: "uploaded"
8314
+ }
8315
+ });
8316
+ }
8317
+ }else{
8318
+ data[item] = [{
8319
+ value: fileFieldValue,
8320
+ name: fileFieldDisplayValue.name,
8321
+ url: fileFieldDisplayValue.url + "?download=true",
8322
+ state: "uploaded"
8323
+ }];
8324
+ }
8325
+ }
8326
+ })
8327
+ `
8328
+ }
8329
+
8330
+ async function getEditFormInitApi(object, recordId, fields, options){
8331
+ const data = await getFindOneQuery$1(object, recordId, fields);
8332
+ data.recordId = "${recordId}";
8333
+ data.objectName = "${objectName}";
8334
+ data.uiSchema = "${uiSchema}";
8335
+ data.global = "${global}";
8336
+ data.context = "${context}";
8337
+ data.defaultData = "${defaultData}";
8338
+ data._master = "${_master}";
8339
+
8340
+ return {
8341
+ method: "post",
8342
+ url: getApi$2() + '&objectName=${objectName}' ,
8343
+ // sendOn: "!!this.recordId",
8344
+ cache: API_CACHE,
8345
+ requestAdaptor: `
8346
+ // 所有不想在network请求中发送的数据都应该从data中分离出来,data变量只需要留下query才需要发送出去
8347
+ var { recordId, objectName, uiSchema, global, context, ...data} = api.data;
8348
+ if(!recordId){
8349
+ // 新建则不请求任何数据
8350
+ data.query = "{data:" + objectName + "(filters: " + JSON.stringify(["_id", "=", null]) + ", top: 1){_id}}";
8282
8351
  }
8283
- }
8284
- const url = getNameTplUrl(nameField, options);
8285
-
8286
- const columnLines = getMobileLines(tpls);
8352
+ api.data = data;
8353
+ ${options.initApiRequestAdaptor || ''}
8354
+ return api;
8355
+ `,
8356
+ adaptor: `
8357
+ const recordId = api.body.recordId;
8358
+ let initialValues={};
8359
+ if(recordId && payload.data.data){
8360
+ var data = payload.data.data[0];
8361
+ const dataKeys = _.keys(data);
8362
+ const uiSchema = api.body.uiSchema;
8363
+ const fieldKeys = uiSchema && _.keys(uiSchema.fields);
8287
8364
 
8365
+ if(data){
8366
+ ${getScriptForAddUrlPrefixForImgFields(fields)}
8367
+ ${getScriptForRewriteValueForFileFields(fields)}
8288
8368
 
8289
- let column = {
8290
- name: nameField.name,
8291
- label: nameField.label,
8292
- sortable: nameField.sortable,
8293
- type: "button",
8294
- level: "link",
8295
- actionType: "link",
8296
- link: url,
8297
- innerClassName: "steedos-listview-item block text-gray-500",
8298
- body: {
8299
- "type": "wrapper",
8300
- "body": columnLines,
8301
- "size": "none",
8302
- "className": "p-1"
8303
- }
8304
- };
8305
-
8306
- if(options.objectName === 'cms_files'){
8307
- if(window.Meteor?.isCordova){
8308
- column = {
8309
- ...column,
8310
- actionType: "",
8311
- link: "",
8312
- onEvent: {
8313
- "click": {
8314
- "actions": [
8315
- {
8316
- "script": `
8317
- let cms_url = "/api/files/files/"+event.data.versions[0]+"?download=true"
8318
- Steedos.cordovaDownload(encodeURI(Steedos.absoluteUrl(cms_url)), event.data.name);
8319
- `,
8320
- "actionType": "custom"
8321
- }
8322
- ],
8323
- "weight": 0
8369
+ _.each(dataKeys, function(key){
8370
+ if(fieldKeys.indexOf(key)<0){
8371
+ delete data[key];
8372
+ }
8373
+ })
8374
+
8375
+ //初始化接口返回的字段移除字段值为null的字段
8376
+ for (key in data){
8377
+ if(data[key] === null){
8378
+ delete data[key];
8324
8379
  }
8325
8380
  }
8326
8381
  };
8327
- }else {
8328
- column = {
8329
- ...column,
8330
- actionType: "",
8331
- link: "",
8332
- onEvent: {
8333
- "click": {
8334
- "actions": [
8335
- {
8336
- "args": {
8337
- "api": {
8338
- "url": url,
8339
- "method": "get",
8340
- "headers": {
8341
- "Authorization": "Bearer ${context.tenantId},${context.authToken}"
8342
- }
8343
- }
8344
- },
8345
- "actionType": "download"
8346
- }
8347
- ],
8348
- "weight": 0
8382
+ initialValues = data;
8383
+ }
8384
+ else{
8385
+ var uiSchema = api.body.uiSchema;
8386
+ var defaultData = api.body.defaultData;
8387
+ var defaultValues = {};
8388
+ _.each(uiSchema?.fields, function(field){
8389
+ var value = SteedosUI.getFieldDefaultValue(field, api.body.global);
8390
+ if(value){
8391
+ defaultValues[field.name] = value;
8392
+ }
8393
+ });
8394
+ if(defaultData && _.isObject(defaultData) && !_.isArray(defaultData)){
8395
+ defaultValues = Object.assign({}, defaultValues, defaultData)
8396
+ }
8397
+ if(uiSchema.form){
8398
+ try{
8399
+ var objectFormConfig = JSON.parse(uiSchema.form);
8400
+ var formInitialValuesFun = objectFormConfig.initialValues;
8401
+ if(formInitialValuesFun){
8402
+ formInitialValuesFun = new Function("return " + formInitialValuesFun)();
8403
+ }
8404
+ if(typeof formInitialValuesFun === "function"){
8405
+ initialValues = formInitialValuesFun.apply({doc: defaultValues || {} , global: api.body.global, master: api.body._master })
8349
8406
  }
8350
8407
  }
8351
- };
8408
+ catch(ex){
8409
+ console.warn(ex);
8410
+ }
8411
+ }
8412
+ if(_.isObject(initialValues)){
8413
+ // uiSchema.form.initialValues为函数且执行后为json,则优先取initialValues中的默认值
8414
+ initialValues = Object.assign({}, defaultValues, initialValues);
8415
+ }
8416
+ else{
8417
+ initialValues = defaultValues;
8418
+ }
8419
+ }
8420
+ // data下的变量需要在保存接口(getSaveApi)中被删除。
8421
+ payload.data = {
8422
+ ...initialValues
8423
+ }
8424
+ ${options.initApiAdaptor || ''}
8425
+ return payload;
8426
+ `,
8427
+ responseData: {
8428
+ initialValues: "$$",
8429
+ editFormInited: true
8430
+ },
8431
+ data: data,
8432
+ headers: {
8433
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8352
8434
  }
8353
-
8354
8435
  }
8436
+ }
8355
8437
 
8356
- columns.push(column);
8357
-
8358
8438
 
8359
- return columns;
8439
+ function getSaveApi(object, recordId, fields, options){
8440
+ return {
8441
+ method: 'post',
8442
+ url: getApi$2(),
8443
+ data: getSaveQuery(object, recordId),
8444
+ requestAdaptor: getSaveRequestAdaptor(fields, options),
8445
+ responseData: {
8446
+ "recordId": "${record._id}"
8447
+ },
8448
+ adaptor: `
8449
+ if(payload.errors){
8450
+ payload.status = 2;
8451
+ payload.msg = window.t ? window.t(payload.errors[0].message) : payload.errors[0].message;
8452
+ }
8453
+ ${options.apiAdaptor || ''}
8454
+ return payload;
8455
+ `,
8456
+ headers: {
8457
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8458
+ }
8459
+ }
8360
8460
  }
8361
8461
 
8362
- function getDefaultParams(options){
8462
+ function getBatchDelete(objectName){
8363
8463
  return {
8364
- perPage: options.top || options.perPage || config.listView.perPage
8464
+ method: 'post',
8465
+ url: getApi$2(),
8466
+ requestAdaptor: `
8467
+ var ids = api.data.ids.split(",");
8468
+ var deleteArray = [];
8469
+ ids.forEach((id,index)=>{
8470
+ deleteArray.push(\`delete__\${index}:${objectName}__delete(id: "\${id}")\`);
8471
+ })
8472
+ api.data = {query: \`mutation{\${deleteArray.join(',')}}\`};
8473
+ return api;
8474
+ `,
8475
+ data: {
8476
+ ids: `\${ids}`
8477
+ },
8478
+ headers: {
8479
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8480
+ }
8365
8481
  }
8366
8482
  }
8367
8483
 
8368
- function getButtonVisibleOn(button){
8369
- let visible= button.visible;
8484
+ const DEFAULT_CALENDAR_OPTIONS = {
8485
+ startDateExpr: "start",
8486
+ endDateExpr: "end",
8487
+ allDayExpr: "is_all_day",
8488
+ textExpr: "name"
8489
+ };
8370
8490
 
8371
- if(button._visible){
8372
- visible = button._visible;
8373
- }
8491
+ async function getCalendarApi(mainObject, fields, options) {
8492
+ if (!options) {
8493
+ options = {};
8494
+ }
8495
+ const calendarOptions = options.calendarOptions;
8496
+ const searchableFields = [];
8497
+ let { filter, sort, top, setDataToComponentId = '' } = options;
8374
8498
 
8375
- if(___default.isBoolean(visible)){
8376
- visible = visible.toString();
8377
- }
8499
+ if (!top) {
8500
+ // 日历请求不翻页
8501
+ top = 200;
8502
+ }
8378
8503
 
8379
- if(visible){
8380
- // if(visible.indexOf("Meteor.") > 0 || visible.indexOf("Creator.") > 0 || visible.indexOf("Session.") > 0){
8381
- // console.warn('无效的visible', visible)
8382
- // return 'false';
8383
- // }
8384
- if(visible.trim().startsWith('function')){
8385
- return `${visible}(objectName, typeof _id === 'undefined' ? null: _id, typeof record === 'undefined' ? (typeof recordPermissions === 'undefined' ? {} : recordPermissions) : record.recordPermissions, data)`
8386
- }
8387
- return visible;
8504
+ if (___default__default["default"].isArray(filter)) {
8505
+ filter = ___default__default["default"].map(filter, function (item) {
8506
+ if (item.operation) {
8507
+ return [item.field, item.operation, item.value];
8508
+ } else {
8509
+ return item
8510
+ }
8511
+ });
8512
+ }
8513
+ if (!filter) {
8514
+ filter = [];
8515
+ }
8516
+
8517
+ ___default__default["default"].each(fields, function (field) {
8518
+ if (field.searchable) {
8519
+ searchableFields.push(field.name);
8388
8520
  }
8521
+ });
8522
+
8523
+ const idFieldName = mainObject.idFieldName || "_id";
8524
+ let valueField = mainObject.key_field || '_id';
8525
+ const api = await getApi(mainObject, null, fields, { alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"` });
8526
+ api.data.$term = "$term";
8527
+ api.data.$self = "$$";
8528
+ api.data.filter = "$filter";
8529
+ api.data.pageSize = top || 10;
8530
+ api.requestAdaptor = `
8531
+ let selfData = JSON.parse(JSON.stringify(api.data.$self));
8532
+ var filters = api.data.filter || ${JSON.stringify(filter)} || [];
8533
+ const eventFetchInfo = selfData.fetchInfo;
8534
+ const startDateExpr = "${calendarOptions.startDateExpr}";
8535
+ const endDateExpr = "${calendarOptions.endDateExpr}";
8536
+ const eventDurationFilters = [[endDateExpr, ">=", eventFetchInfo.start], [startDateExpr, "<=", eventFetchInfo.end]];
8537
+ if(_.isEmpty(filters)){
8538
+ filters = eventDurationFilters;
8539
+ }else{
8540
+ filters = [filters, 'and', eventDurationFilters]
8541
+ }
8389
8542
 
8390
- if(button.type === 'amis_button'){
8391
- const amisSchema = button.amis_schema;
8392
- if(amisSchema && amisSchema.body && amisSchema.body.length > 0){
8393
- const btn1 = amisSchema.body[0];
8394
- return btn1.visibleOn
8395
- }
8396
- }
8543
+ if(api.data.$self.additionalFilters){
8544
+ filters.push(api.data.$self.additionalFilters)
8397
8545
  }
8398
8546
 
8399
- async function getTableOperation(ctx){
8400
- const buttons = ctx.buttons;
8401
- const operationButtons = [];
8402
- ___default.each(buttons, (button)=>{
8403
- if(___default.isBoolean(button.visible)){
8404
- button.visible = button.visible.toString();
8405
- }
8406
- // operationButtons.push({
8407
- // type: 'button',
8408
- // label: button.label,
8409
- // visibleOn: button.visible ? `${button.visible}` : (button._visible ? `${button._visible}` : null),
8410
- // onEvent: {
8411
- // click: {
8412
- // actions: []
8413
- // }
8414
- // }
8415
- // })
8547
+ var pageSize = api.data.pageSize || 10;
8548
+ var pageNo = api.data.pageNo || 1;
8549
+ var skip = (pageNo - 1) * pageSize;
8550
+ var orderBy = api.data.orderBy || '';
8551
+ var orderDir = api.data.orderDir || '';
8552
+ var sort = orderBy + ' ' + orderDir;
8553
+ sort = orderBy ? sort : "${sort}";
8554
+ var allowSearchFields = ${JSON.stringify(searchableFields)};
8555
+ if(api.data.$term){
8556
+ filters = [["name", "contains", "'+ api.data.$term +'"]];
8557
+ }else if(selfData.op === 'loadOptions' && selfData.value){
8558
+ filters = [["${valueField.name}", "=", selfData.value]];
8559
+ }
8560
+ var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
8416
8561
 
8417
- operationButtons.push({
8418
- type: 'steedos-object-button',
8419
- name: button.name,
8420
- objectName: button.objectName,
8421
- visibleOn: getButtonVisibleOn(button),
8422
- className: 'antd-Button--default'
8423
- });
8424
- });
8425
- if(operationButtons.length < 1){
8426
- return ;
8427
- }
8428
- return {
8429
- type: 'operation',
8430
- label: '操作',
8431
- fixed: 'right',
8432
- labelClassName: 'text-center',
8433
- className: 'text-center steedos-listview-operation w-20',
8434
- buttons: [
8435
- {
8436
- "type": "steedos-dropdown-button",
8437
- "label": "xxx",
8438
- "buttons": operationButtons,
8439
- "placement": "bottomRight",
8440
- "overlayClassName": "shadow !min-w-[160px]",
8441
- "trigger": ["click"],
8442
- "id": "u:c2140a365019",
8443
- onOpenApi: {
8444
- url: `\${context.rootUrl}/service/api/@\${objectName}/recordPermissions/\${_id}`,
8445
- method: "get",
8446
- data: {
8447
- $: "$$",
8448
- objectName: "${objectName}",
8449
- listViewId: "${listViewId}",
8450
- appId: "${appId}",
8451
- formFactor: "${formFactor}",
8452
- context: `\${context}`
8453
- },
8454
- headers: {
8455
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8456
- },
8457
- adaptor: `
8458
- payload = {
8459
- record: {
8460
- recordPermissions: payload
8461
- }
8462
- };
8463
- return payload;
8464
- `,
8465
- }
8466
- }
8467
- ]
8562
+ if(searchableFilter.length > 0){
8563
+ if(filters.length > 0 ){
8564
+ filters = [filters, 'and', searchableFilter];
8565
+ }else{
8566
+ filters = searchableFilter;
8468
8567
  }
8469
8568
  }
8470
8569
 
8471
- async function getTableSchema$1(fields, options){
8472
- if(!options){
8473
- options = {};
8474
- }
8475
- let columns = [];
8476
- if(options.formFactor === 'SMALL' || ["split"].indexOf(options.displayAs) > -1){
8477
- columns = await getMobileTableColumns(fields, options);
8478
- }
8479
- else {
8480
- columns = await getTableColumns$1(fields, options);
8481
- columns.push(await getTableOperation(options));
8482
- }
8483
- return {
8484
- mode: "table",
8485
- name: "thelist",
8486
- headerToolbarClassName: "py-2 px-2 border-gray-300 bg-gray-100 border-solid border-b",
8487
- className: "",
8488
- draggable: false,
8489
- defaultParams: getDefaultParams(options),
8490
- columns: columns,
8491
- syncLocation: false,
8492
- keepItemSelectionOnPageChange: true,
8493
- checkOnItemClick: false,
8494
- labelTpl: `\${${options.labelFieldName}}`,
8495
- autoFillHeight: false, // 自动高度效果不理想,先关闭
8496
- columnsTogglable: false,
8497
- }
8570
+ if(allowSearchFields){
8571
+ allowSearchFields.forEach(function(key){
8572
+ const keyValue = selfData[key];
8573
+ if(_.isString(keyValue)){
8574
+ filters.push([key, "contains", keyValue]);
8575
+ }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8576
+ filters.push([key, "=", keyValue]);
8577
+ }
8578
+ })
8498
8579
  }
8499
8580
 
8581
+ if(selfData.__keywords && allowSearchFields){
8582
+ const keywordsFilters = [];
8583
+ allowSearchFields.forEach(function(key, index){
8584
+ const keyValue = selfData.__keywords;
8585
+ if(keyValue){
8586
+ keywordsFilters.push([key, "contains", keyValue]);
8587
+ if(index < allowSearchFields.length - 1){
8588
+ keywordsFilters.push('or');
8589
+ }
8590
+ }
8591
+ })
8592
+ filters.push(keywordsFilters);
8593
+ }
8594
+ api.data.query = api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim());
8595
+ delete api.data.$term;
8596
+ delete api.data.filter;
8597
+ delete api.data.pageSize;
8598
+ delete api.data.pageNo;
8599
+ delete api.data.orderBy;
8600
+ delete api.data.orderDir;
8601
+ return api;
8602
+ `;
8603
+ api.adaptor = `
8604
+ window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8605
+ const setDataToComponentId = "${setDataToComponentId}";
8606
+ if(setDataToComponentId){
8607
+ SteedosUI.getRef(api.body.$self.scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8608
+ }
8609
+ const rows = payload.data.rows || [];
8610
+ const selfData = api.data.$self;
8611
+ const events = rows.map(function(n){
8612
+ return {
8613
+ id: n["${idFieldName}"],
8614
+ title: n["${calendarOptions.textExpr}"],
8615
+ start: n["${calendarOptions.startDateExpr}"],
8616
+ end: n["${calendarOptions.endDateExpr}"],
8617
+ allDay: n["${calendarOptions.allDayExpr}"],
8618
+ extendedProps: n
8619
+ }
8620
+ });
8621
+ const successCallback = selfData.successCallback;
8622
+ const failureCallback = selfData.failureCallback;
8623
+ successCallback(events);
8624
+ return payload;
8625
+ `;
8626
+ return api;
8627
+ }
8500
8628
 
8629
+ function getCalendarRecordPermissionsApi(mainObject, recordId) {
8630
+ const api = getRecordPermissionsApi(mainObject, recordId, { alias: 'rows', limit: 1, fields: ["allowEdit"] });
8631
+ api.data.$self = "$$";
8632
+ api.adaptor = `
8633
+ const rows = payload.data.rows || [];
8634
+ const selfData = api.data.$self;
8635
+ const revert = selfData.revert;
8636
+ const recordPermissions = rows[0] && rows[0].recordPermissions;
8637
+ const editable = !!(recordPermissions && recordPermissions.allowEdit);
8638
+ if(!editable){
8639
+ // 没有权限时还原
8640
+ revert && revert();
8641
+ }
8642
+ payload.data.editable = editable;
8643
+ return payload;
8644
+ `;
8645
+ return api;
8646
+ }
8501
8647
 
8502
- /**
8503
- *
8504
- * @param {*} mainObject
8505
- * @param {*} fields
8506
- * @param {*} options = {filter: listview 过滤条件, ...}
8507
- * @returns
8508
- */
8509
- async function getTableApi(mainObject, fields, options){
8510
- const searchableFields = [];
8511
- let { filter, filtersFunction, sort, top, setDataToComponentId = '' } = options;
8648
+ function getCalendarRecordSaveApi(object, calendarOptions) {
8649
+ const formData = {};
8650
+ const idFieldName = object.idFieldName || "_id";
8651
+ formData[idFieldName] = "${event.data.event.id}";
8652
+ const nameFieldKey = object.NAME_FIELD_KEY || "name";
8653
+ formData[nameFieldKey] = "${event.data.event.title}";
8654
+ formData[calendarOptions.startDateExpr] = "${event.data.event.start}";
8655
+ formData[calendarOptions.endDateExpr] = "${event.data.event.end}";
8656
+ formData[calendarOptions.allDayExpr] = "${event.data.event.allDay}";
8657
+ // formData[calendarOptions.textExpr] = "${event.data.event.title}";
8658
+ const apiData = {
8659
+ objectName: "${objectName}",
8660
+ $: formData,
8661
+ $self: "$$"
8662
+ };
8663
+ const saveDataTpl = `
8664
+ const formData = api.data.$;
8665
+ const objectName = api.data.objectName;
8666
+ let query = \`mutation{record: \${objectName}__update(id: "\${formData.${idFieldName}}", doc: {__saveData}){${idFieldName}}}\`;
8667
+ delete formData.${idFieldName};
8668
+ let __saveData = JSON.stringify(JSON.stringify(formData));
8669
+ `;
8670
+ const requestAdaptor = `
8671
+ ${saveDataTpl}
8672
+ api.data.query = query.replace('{__saveData}', __saveData);
8673
+ return api;
8674
+ `;
8512
8675
 
8513
- if(___default__namespace.isArray(filter)){
8514
- filter = ___default__namespace.map(filter, function(item){
8515
- if(item.operation){
8516
- return [item.field, item.operation, item.value];
8517
- }else {
8518
- return item
8519
- }
8520
- });
8521
- }
8522
- if(!filter){
8523
- filter = [];
8676
+ return {
8677
+ method: 'post',
8678
+ url: getApi$2(),
8679
+ data: apiData,
8680
+ requestAdaptor: requestAdaptor,
8681
+ adaptor: `
8682
+ if(payload.errors){
8683
+ payload.status = 2;
8684
+ payload.msg = payload.errors[0].message;
8685
+ const revert = api.data.$self.event.data.revert;
8686
+ revert && revert();
8524
8687
  }
8525
- let baseFilters = null;
8526
- if(filter){
8527
- baseFilters = filter;
8688
+ return payload;
8689
+ `,
8690
+ headers: {
8691
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8528
8692
  }
8529
- ___default__namespace.each(fields,function(field){
8530
- if(field.searchable){
8531
- searchableFields.push(field.name);
8532
- }
8533
- });
8693
+ };
8694
+ }
8534
8695
 
8535
- const fileFields = {};
8536
- const fileFieldsKeys = [];
8537
- // 含有optionsFunction属性, 无reference_to属性的lookup字段
8538
- const lookupFields = {};
8539
- fields.forEach((item)=>{
8540
- if(___default__namespace.includes(['image','avatar','file'], item.type)){
8541
- fileFieldsKeys.push(item.name);
8542
- fileFields[item.name] = {
8543
- name: item.name,
8544
- type: item.type,
8545
- multiple: item.multiple
8546
- };
8547
- }
8548
- if(___default__namespace.includes(['lookup'], item.type) && !item.reference_to ){
8549
- lookupFields[item.name] = item;
8550
- }
8551
- });
8696
+ /**
8697
+ * 列表视图Calendar amisSchema
8698
+ * @param {*} objectSchema 对象UISchema
8699
+ * @returns amisSchema
8700
+ */
8701
+ async function getObjectCalendar(objectSchema, calendarOptions, options) {
8702
+ const permissions = objectSchema.permissions;
8703
+ if (!options) {
8704
+ options = {};
8705
+ }
8552
8706
 
8553
- let valueField = mainObject.key_field || '_id';
8554
- const api = await getApi(mainObject, null, fields, {count: options.queryCount, alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"`});
8707
+ calendarOptions = Object.assign({}, DEFAULT_CALENDAR_OPTIONS, ___default.omitBy(calendarOptions, ___default.isNil));
8555
8708
 
8556
- if(options.isRelated){
8557
- api.url += "&recordId=${_master.recordId}";
8709
+ const titleFields = calendarOptions.title || [
8710
+ calendarOptions.startDateExpr,
8711
+ calendarOptions.endDateExpr,
8712
+ calendarOptions.allDayExpr,
8713
+ calendarOptions.textExpr
8714
+ ];
8715
+ let fields = [];
8716
+ ___default.each(titleFields, function (n) {
8717
+ if (objectSchema.fields[n]) {
8718
+ fields.push(objectSchema.fields[n]);
8558
8719
  }
8720
+ });
8559
8721
 
8560
- api.data.$term = "$term";
8561
- api.data.term = "$term";
8562
- api.data.$self = "$$";
8563
- api.data.self = "$$";
8564
- api.data.filter = "$filter";
8565
- api.data.loaded = "${loaded}";
8566
- api.data.listViewId = "${listViewId}";
8567
- api.data.listName = "${listName}";
8568
- api.requestAdaptor = `
8569
- // selfData 中的数据由 CRUD 控制. selfData中,只能获取到 CRUD 给定的data. 无法从数据链中获取数据.
8570
- let selfData = JSON.parse(JSON.stringify(api.data.$self));
8571
- // 保留一份初始data,以供自定义发送适配器中获取原始数据。
8572
- const data = _.cloneDeep(api.data);
8573
- try{
8574
- // TODO: 不应该直接在这里取localStorage,应该从外面传入
8575
- const listViewId = api.data.listViewId;
8576
- const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
8577
- let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
8578
- if(localListViewProps){
8579
- localListViewProps = JSON.parse(localListViewProps);
8580
- selfData = Object.assign({}, localListViewProps, selfData);
8581
- if(!api.data.filter){
8582
- api.data.filter = localListViewProps.filter;
8583
- }
8584
- if(!api.data.loaded){
8585
- // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
8586
- // 所以会把localSearchableFilter中已经存过的页码覆盖
8587
- // 如果是第一次加载组件始终让翻页页码从本地存储中取值
8588
- let formFactor = "${options.formFactor}";
8589
- // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
8590
- api.data.pageNo = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
8591
- }
8592
- }
8593
- }
8594
- catch(ex){
8595
- console.error("本地存储中crud参数解析异常:", ex);
8596
- }
8597
- ${baseFilters ? `var systemFilters = ${JSON.stringify(baseFilters)};` : 'var systemFilters = [];'}
8598
- var _ids = []
8599
- const filtersFunction = ${filtersFunction};
8600
- if(filtersFunction){
8601
- const _filters = filtersFunction(systemFilters, api.data.$self);
8602
- if(api.data.listName == "recent"){
8603
- _ids = _filters[2]
8604
- }
8605
- if(_filters && _filters.length > 0){
8606
- if(_.isEmpty(systemFilters)){
8607
- systemFilters = _filters || [];
8608
- }else{
8609
- systemFilters = [systemFilters, 'and', _filters];
8610
- }
8611
- }
8612
- }
8613
- let userFilters =[];
8614
-
8615
- if(_.isEmpty(systemFilters)){
8616
- systemFilters = api.data.filter || [];
8617
- }else{
8618
- if(!_.isEmpty(api.data.filter)){
8619
- systemFilters = [systemFilters, 'and', api.data.filter];
8620
- }
8722
+ if (objectSchema.fields[calendarOptions.allDayExpr]) {
8723
+ fields.push(objectSchema.fields[calendarOptions.allDayExpr]);
8724
+ }
8725
+
8726
+ let sort = options.sort;
8727
+ if (!sort) {
8728
+ const sortField = options.sortField;
8729
+ const sortOrder = options.sortOrder;
8730
+ if (sortField) {
8731
+ let sortStr = sortField + ' ' + sortOrder || 'asc';
8732
+ sort = sortStr;
8621
8733
  }
8622
- var pageSize = api.data.pageSize || 10;
8623
- var pageNo = api.data.pageNo || 1;
8624
- var skip = (pageNo - 1) * pageSize;
8625
- var orderBy = api.data.orderBy || '';
8626
- var orderDir = api.data.orderDir || '';
8627
- var sort = orderBy + ' ' + orderDir;
8628
- sort = orderBy ? sort : "${sort || ''}";
8629
- var allowSearchFields = ${JSON.stringify(searchableFields)};
8630
- if(api.data.$term){
8631
- userFilters = [["name", "contains", "'+ api.data.$term +'"]];
8632
- }else if(selfData.op === 'loadOptions' && selfData.value){
8633
- userFilters = [["${valueField.name}", "=", selfData.value]];
8734
+ }
8735
+ let initialView = calendarOptions.currentView;
8736
+ if (initialView) {
8737
+ // day, week, month, agenda
8738
+ switch (initialView) {
8739
+ case "day":
8740
+ initialView = "timeGridDay";
8741
+ break;
8742
+ case "week":
8743
+ initialView = "timeGridWeek";
8744
+ break;
8745
+ case "month":
8746
+ initialView = "dayGridMonth";
8747
+ break;
8748
+ case "agenda":
8749
+ initialView = "listWeek";
8750
+ break;
8634
8751
  }
8635
-
8636
- var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
8752
+ }
8753
+ else {
8754
+ initialView = "timeGridWeek";
8755
+ }
8637
8756
 
8638
- if(searchableFilter.length > 0){
8639
- if(userFilters.length > 0 ){
8640
- userFilters = [userFilters, 'and', searchableFilter];
8641
- }else{
8642
- userFilters = searchableFilter;
8643
- }
8644
- }
8757
+ options.calendarOptions = calendarOptions;
8758
+ const api = await getCalendarApi(objectSchema, fields, options);
8645
8759
 
8646
- if(allowSearchFields){
8647
- allowSearchFields.forEach(function(key){
8648
- const keyValue = selfData[key];
8649
- if(_.isString(keyValue)){
8650
- userFilters.push([key, "contains", keyValue]);
8651
- }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8652
- userFilters.push([key, "=", keyValue]);
8653
- }
8654
- })
8655
- }
8760
+ const onGetEventsScript = `
8761
+ const api = ${JSON.stringify(api)};
8762
+ event.data.calendarOptions = ${JSON.stringify(calendarOptions)};
8763
+ doAction({
8764
+ "actionType": 'ajax',
8765
+ "args": {
8766
+ "api": api
8767
+ },
8768
+ });
8769
+ `;
8656
8770
 
8657
- if(selfData.__keywords && allowSearchFields){
8658
- const keywordsFilters = [];
8659
- allowSearchFields.forEach(function(key, index){
8660
- const keyValue = selfData.__keywords;
8661
- if(keyValue){
8662
- keywordsFilters.push([key, "contains", keyValue]);
8663
- if(index < allowSearchFields.length - 1){
8664
- keywordsFilters.push('or');
8771
+ const onSelectScript = `
8772
+ const data = event.data;
8773
+ const doc = {};
8774
+ doc["${calendarOptions.startDateExpr}"] = data.start;
8775
+ doc["${calendarOptions.endDateExpr}"] = data.end;
8776
+ doc["${calendarOptions.allDayExpr}"] = data.allDay;
8777
+ doc["${calendarOptions.textExpr}"] = data.title;
8778
+ // ObjectForm会认作用域下的变量值
8779
+ // TODO: 待组件支持initValues属性后应该改掉,不应该通过data直接传值
8780
+ // TODO: 全天事件属性传入doc了但是没有生效,需要手动在ObjectForm中勾选全天事件
8781
+ const title = "新建 ${objectSchema.label}";
8782
+ doAction(
8783
+ {
8784
+ "actionType": "dialog",
8785
+ "dialog": {
8786
+ "type": "dialog",
8787
+ "title": title,
8788
+ "body": [
8789
+ {
8790
+ "type": "steedos-object-form",
8791
+ "objectApiName": "\${objectName}",
8792
+ "mode": "edit",
8793
+ "defaultData": doc,
8794
+ "onEvent": {
8795
+ "submitSucc": {
8796
+ "weight": 0,
8797
+ "actions": [
8798
+ {
8799
+ "actionType": "custom",
8800
+ "script": "event.data.view?.calendar.refetchEvents();"
8665
8801
  }
8802
+ ]
8666
8803
  }
8667
- })
8668
- userFilters.push(keywordsFilters);
8669
- };
8804
+ }
8805
+ }
8806
+ ],
8807
+ "closeOnEsc": false,
8808
+ "closeOnOutside": false,
8809
+ "showCloseButton": true,
8810
+ "size": "lg"
8811
+ }
8812
+ });
8813
+ `;
8814
+
8815
+ const onEventClickScript = `
8816
+ const data = event.data;
8817
+ const eventData = data.event;
8818
+ const appId = data.appId;
8819
+ const objectName = data.objectName;
8820
+ const eventId = data.event && data.event.id;
8821
+ doAction({
8822
+ "actionType": "dialog",
8823
+ "dialog": {
8824
+ "type": "dialog",
8825
+ "title": "",
8826
+ "body": [
8827
+ {
8828
+ "type": "steedos-record-detail",
8829
+ "objectApiName": "\${objectName}",
8830
+ "recordId": data.event && data.event.id
8831
+ }
8832
+ ],
8833
+ "closeOnEsc": false,
8834
+ "closeOnOutside": false,
8835
+ "showCloseButton": true,
8836
+ "size": "lg",
8837
+ "actions": []
8838
+ }
8839
+ });
8840
+ `;
8670
8841
 
8671
- let filters = [];
8842
+ const recordId = "${event.id}";
8843
+ const recordPermissionsApi = getCalendarRecordPermissionsApi(objectSchema, recordId);
8844
+ const recordSaveApi = getCalendarRecordSaveApi(objectSchema, calendarOptions);
8672
8845
 
8673
- if(!_.isEmpty(systemFilters)){
8674
- filters = systemFilters;
8675
- };
8676
- if(api.data.$self.additionalFilters){
8677
- if(_.isString(api.data.$self.additionalFilters)){
8678
- userFilters.push(eval(api.data.$self.additionalFilters))
8679
- }else{
8680
- userFilters.push(api.data.$self.additionalFilters)
8681
- }
8682
- }
8846
+ const businessHours = {
8847
+ daysOfWeek: [1, 2, 3, 4, 5],
8848
+ startTime: '08:00',
8849
+ endTime: '18:00',
8850
+ };
8851
+ if (!___default.isEmpty(calendarOptions.startDayHour)) {
8852
+ businessHours.startTime = `${calendarOptions.startDayHour}:00`;
8853
+ }
8854
+ if (!___default.isEmpty(calendarOptions.endDayHour)) {
8855
+ businessHours.endTime = `${calendarOptions.endDayHour}:00`;
8856
+ }
8683
8857
 
8684
- if(api.data.$self._isRelated){
8685
- const self = api.data.$self;
8686
- const relatedKey = self.relatedKey;
8687
- const refField = self.uiSchema.fields[relatedKey];
8688
- const masterRecord = self._master.record;
8689
- const masterObjectName = self._master.objectName;
8690
- let relatedValue = self._master.recordId;
8691
- if(refField.reference_to_field && refField.reference_to_field != '_id'){
8692
- relatedValue = masterRecord[refField.reference_to_field]
8858
+ const onEvent = {
8859
+ "getEvents": {
8860
+ "weight": 0,
8861
+ "actions": [
8862
+ {
8863
+ "componentId": "",
8864
+ "args": {
8865
+ },
8866
+ "actionType": "custom",
8867
+ "script": onGetEventsScript
8693
8868
  }
8694
- let relatedFilters;
8695
- if (
8696
- refField._reference_to ||
8697
- (refField.reference_to && !_.isString(refField.reference_to))
8698
- ) {
8699
- relatedFilters = [
8700
- [relatedKey + "/o", "=", masterObjectName],
8701
- [relatedKey + "/ids", "=", relatedValue],
8702
- ];
8703
- } else {
8704
- relatedFilters = [relatedKey, "=", relatedValue];
8869
+ ]
8870
+ },
8871
+ "select": {
8872
+ "weight": 0,
8873
+ "actions": [
8874
+ {
8875
+ "componentId": "",
8876
+ "args": {
8877
+ },
8878
+ "actionType": "custom",
8879
+ "script": onSelectScript
8705
8880
  }
8706
- userFilters.push(relatedFilters)
8707
- }
8708
-
8709
- if(!_.isEmpty(userFilters)){
8710
- if(_.isEmpty(filters)){
8711
- filters = userFilters;
8712
- }else{
8713
- filters = [filters, 'and', userFilters]
8881
+ ]
8882
+ },
8883
+ "eventClick": {
8884
+ "weight": 0,
8885
+ "actions": [
8886
+ {
8887
+ "componentId": "",
8888
+ "args": {
8889
+ },
8890
+ "actionType": "custom",
8891
+ "script": onEventClickScript
8714
8892
  }
8715
- }
8716
- api.data._ids = _ids;
8717
- api.data = {
8718
- query: api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim())
8719
- }
8720
- ${options.requestAdaptor || ''}
8721
- return api;
8722
- `;
8723
- api.adaptor = `
8724
- if(api.body.listName == "recent"){
8725
- payload.data.rows = _.sortBy(payload.data.rows, function(item){
8726
- return _.indexOf(api.body._ids, item._id)
8727
- });
8728
- }
8729
- const enable_tree = ${mainObject.enable_tree};
8730
- if(!enable_tree){
8731
- _.each(payload.data.rows, function(item, index){
8732
- const {pageNo, pageSize} = api.body;
8733
- const skip = (pageNo - 1) * pageSize;
8734
- item._index = skip + index + 1;
8735
- })
8736
- }
8737
- window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8738
- let fileFields = ${JSON.stringify(fileFields)};
8739
- let lookupFields = ${JSON.stringify(lookupFields)};
8740
- _.each(payload.data.rows, function(item, index){
8741
- _.each(fileFields , (field, key)=>{
8742
- if(item[key] && item._display && item._display[key]){
8743
- let value = item._display[key];
8744
- if(!_.isArray(value)){
8745
- value = [value]
8746
- };
8747
- if(field.type === 'file'){
8748
- item[key] = value
8749
- }else{
8750
- item[key] = _.map(value, 'url')
8751
- }
8893
+ ]
8894
+ },
8895
+ "eventAdd": {
8896
+ "weight": 0,
8897
+ "actions": [
8898
+ {
8899
+ "componentId": "",
8900
+ "args": {
8901
+ },
8902
+ "actionType": "custom",
8903
+ "script": "console.log('eventAdd'); console.log(event);"
8752
8904
  }
8753
- })
8754
- _.each(lookupFields , (field, key)=>{
8755
- if(item[key]){
8756
- if(field._optionsFunction){
8757
- const optionsFunction = eval("(" + field._optionsFunction+ ")")(item);
8758
- item[key + '__label'] = _.map(_.filter(optionsFunction, function(option){return _.includes(item[key], option.value)}), 'label').join(' ');
8905
+ ]
8906
+ },
8907
+ "eventChange": {
8908
+ "weight": 0,
8909
+ "actions": [
8910
+ {
8911
+ "actionType": 'ajax',
8912
+ "args": {
8913
+ "api": recordPermissionsApi
8914
+ }
8915
+ },
8916
+ {
8917
+ "actionType": "toast",
8918
+ "expression": "!event.data.editable",
8919
+ "args": {
8920
+ "msgType": "error",
8921
+ "msg": "您没有编辑该记录的权限!",
8922
+ "position": "top-center"
8923
+ }
8924
+ },
8925
+ {
8926
+ "actionType": 'ajax',
8927
+ "expression": "event.data.editable",
8928
+ "args": {
8929
+ "api": recordSaveApi,
8930
+ "messages": {
8931
+ "success": objectSchema.label + "修改成功",
8932
+ "failed": objectSchema.label + "修改失败!"
8759
8933
  }
8934
+ }
8760
8935
  }
8761
- })
8762
- })
8763
-
8764
- if(enable_tree){
8765
- const records = payload.data.rows || [];
8766
- const getTreeOptions = SteedosUI.getTreeOptions
8767
- payload.data.rows = getTreeOptions(records,{"valueField":"_id"});
8768
- }
8769
-
8770
-
8771
- try{
8772
- // TODO: 不应该直接在这里取localStorage,应该从外面传入
8773
- const listViewId = api.body.listViewId;
8774
- const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
8775
- /**
8776
- * localListViewProps规范来自crud请求api中api.data.$self参数值的。
8777
- * 比如:{"perPage":20,"page":1,"__searchable__name":"7","__searchable__between__n1__c":[null,null],"filter":[["name","contains","a"]]}
8778
- * __searchable__...:顶部放大镜搜索条件
8779
- * filter:右侧过滤器
8780
- * perPage:每页条数
8781
- * page:当前页码
8782
- * orderBy:排序字段
8783
- * orderDir:排序方向
8784
- */
8785
- let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
8786
- let selfData = JSON.parse(JSON.stringify(api.body.$self));
8787
- if(localListViewProps){
8788
- localListViewProps = JSON.parse(localListViewProps);
8789
- selfData = Object.assign({}, localListViewProps, selfData, { filter: api.body.filter });
8790
- if(!api.body.loaded){
8791
- // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
8792
- // 所以会把localSearchableFilter中已经存过的页码覆盖
8793
- // 如果是第一次加载组件始终让翻页页码从本地存储中取值
8794
- let formFactor = "${options.formFactor}";
8795
- // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
8796
- selfData.page = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
8797
- }
8798
- }
8799
- delete selfData.context;
8800
- delete selfData.global;
8801
- sessionStorage.setItem(listViewPropsStoreKey, JSON.stringify(selfData));
8802
- // 返回页码到UI界面
8803
- payload.data.page= selfData.page;
8804
- }
8805
- catch(ex){
8806
- console.error("本地存储中crud参数解析异常:", ex);
8807
- }
8808
- // 标记加载过,后续优先从本地存储中加载相关参数
8809
- payload.data.loaded= true;
8810
-
8811
- const setDataToComponentId = "${setDataToComponentId}";
8812
- if(setDataToComponentId){
8813
- SteedosUI.getRef(api.body.$self.$scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8814
- };
8815
- ${options.adaptor || ''}
8816
- return payload;
8817
- `;
8818
- return api;
8819
- }
8820
-
8821
- async function getApi(object, recordId, fields, options){
8822
- const data = await getFindQuery(object, recordId, fields, options);
8823
- return {
8824
- method: "post",
8825
- url: getApi$2(), // + "&recordId=${recordId}"
8826
- data: data,
8827
- headers: {
8828
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8936
+ ]
8937
+ },
8938
+ "eventRemove": {
8939
+ "weight": 0,
8940
+ "actions": [
8941
+ {
8942
+ "componentId": "",
8943
+ "args": {
8944
+ },
8945
+ "actionType": "custom",
8946
+ "script": "console.log('eventRemove'); console.log(event);"
8829
8947
  }
8830
- }
8831
- }
8832
-
8833
- function getRecordPermissionsApi(object, recordId, options){
8834
- const data = getRecordPermissionsQuery(object, recordId, options);
8835
- return {
8836
- method: "post",
8837
- url: getApi$2(),
8838
- data: data,
8839
- headers: {
8840
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8948
+ ]
8949
+ },
8950
+ "eventsSet": {
8951
+ "weight": 0,
8952
+ "actions": [
8953
+ {
8954
+ "componentId": "",
8955
+ "args": {
8956
+ },
8957
+ "actionType": "custom",
8958
+ "script": "console.log('eventsSet'); console.log(event);"
8841
8959
  }
8960
+ ]
8842
8961
  }
8843
- }
8844
-
8845
- const DEFAULT_CALENDAR_OPTIONS = {
8846
- startDateExpr: "start",
8847
- endDateExpr: "end",
8848
- allDayExpr: "is_all_day",
8849
- textExpr: "name"
8850
- };
8851
-
8852
- async function getCalendarApi(mainObject, fields, options) {
8853
- if (!options) {
8854
- options = {};
8855
- }
8856
- const calendarOptions = options.calendarOptions;
8857
- const searchableFields = [];
8858
- let { filter, sort, top, setDataToComponentId = '' } = options;
8962
+ };
8859
8963
 
8860
- if (!top) {
8861
- // 日历请求不翻页
8862
- top = 200;
8863
- }
8964
+ Object.assign(onEvent, options.onEvent);
8864
8965
 
8865
- if (___default__default["default"].isArray(filter)) {
8866
- filter = ___default__default["default"].map(filter, function (item) {
8867
- if (item.operation) {
8868
- return [item.field, item.operation, item.value];
8869
- } else {
8870
- return item
8966
+ const config = options.config || {};
8967
+ if(config.eventContent && typeof config.eventContent === "string"){
8968
+ const hasReturn = /\breturn\b/.test(config.eventContent);
8969
+ if(hasReturn){
8970
+ try {
8971
+ // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8972
+ let fn = new Function("arg", config.eventContent);
8973
+ config.eventContent = fn;
8974
+ } catch (e) {
8975
+ console.warn(e);
8871
8976
  }
8872
- });
8873
- }
8874
- if (!filter) {
8875
- filter = [];
8876
- }
8877
-
8878
- ___default__default["default"].each(fields, function (field) {
8879
- if (field.searchable) {
8880
- searchableFields.push(field.name);
8881
8977
  }
8882
- });
8883
-
8884
- const idFieldName = mainObject.idFieldName || "_id";
8885
- let valueField = mainObject.key_field || '_id';
8886
- const api = await getApi(mainObject, null, fields, { alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"` });
8887
- api.data.$term = "$term";
8888
- api.data.$self = "$$";
8889
- api.data.filter = "$filter";
8890
- api.data.pageSize = top || 10;
8891
- api.requestAdaptor = `
8892
- let selfData = JSON.parse(JSON.stringify(api.data.$self));
8893
- var filters = api.data.filter || ${JSON.stringify(filter)} || [];
8894
- const eventFetchInfo = selfData.fetchInfo;
8895
- const startDateExpr = "${calendarOptions.startDateExpr}";
8896
- const endDateExpr = "${calendarOptions.endDateExpr}";
8897
- const eventDurationFilters = [[endDateExpr, ">=", eventFetchInfo.start], [startDateExpr, "<=", eventFetchInfo.end]];
8898
- if(_.isEmpty(filters)){
8899
- filters = eventDurationFilters;
8900
- }else{
8901
- filters = [filters, 'and', eventDurationFilters]
8902
- }
8903
-
8904
- if(api.data.$self.additionalFilters){
8905
- filters.push(api.data.$self.additionalFilters)
8906
- }
8907
-
8908
- var pageSize = api.data.pageSize || 10;
8909
- var pageNo = api.data.pageNo || 1;
8910
- var skip = (pageNo - 1) * pageSize;
8911
- var orderBy = api.data.orderBy || '';
8912
- var orderDir = api.data.orderDir || '';
8913
- var sort = orderBy + ' ' + orderDir;
8914
- sort = orderBy ? sort : "${sort}";
8915
- var allowSearchFields = ${JSON.stringify(searchableFields)};
8916
- if(api.data.$term){
8917
- filters = [["name", "contains", "'+ api.data.$term +'"]];
8918
- }else if(selfData.op === 'loadOptions' && selfData.value){
8919
- filters = [["${valueField.name}", "=", selfData.value]];
8920
- }
8921
- var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
8978
+ }
8922
8979
 
8923
- if(searchableFilter.length > 0){
8924
- if(filters.length > 0 ){
8925
- filters = [filters, 'and', searchableFilter];
8926
- }else{
8927
- filters = searchableFilter;
8980
+ if(config.noEventsContent && typeof config.noEventsContent === "string"){
8981
+ const hasReturn = /\breturn\b/.test(config.noEventsContent);
8982
+ if(hasReturn){
8983
+ try {
8984
+ // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8985
+ let fn = new Function("arg", config.noEventsContent);
8986
+ config.noEventsContent = fn;
8987
+ } catch (e) {
8988
+ console.warn(e);
8989
+ }
8928
8990
  }
8929
- }
8930
-
8931
- if(allowSearchFields){
8932
- allowSearchFields.forEach(function(key){
8933
- const keyValue = selfData[key];
8934
- if(_.isString(keyValue)){
8935
- filters.push([key, "contains", keyValue]);
8936
- }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8937
- filters.push([key, "=", keyValue]);
8938
- }
8939
- })
8940
- }
8941
-
8942
- if(selfData.__keywords && allowSearchFields){
8943
- const keywordsFilters = [];
8944
- allowSearchFields.forEach(function(key, index){
8945
- const keyValue = selfData.__keywords;
8946
- if(keyValue){
8947
- keywordsFilters.push([key, "contains", keyValue]);
8948
- if(index < allowSearchFields.length - 1){
8949
- keywordsFilters.push('or');
8950
- }
8951
- }
8952
- })
8953
- filters.push(keywordsFilters);
8954
- }
8955
- api.data.query = api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim());
8956
- delete api.data.$term;
8957
- delete api.data.filter;
8958
- delete api.data.pageSize;
8959
- delete api.data.pageNo;
8960
- delete api.data.orderBy;
8961
- delete api.data.orderDir;
8962
- return api;
8963
- `;
8964
- api.adaptor = `
8965
- window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8966
- const setDataToComponentId = "${setDataToComponentId}";
8967
- if(setDataToComponentId){
8968
- SteedosUI.getRef(api.body.$self.scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8969
- }
8970
- const rows = payload.data.rows || [];
8971
- const selfData = api.data.$self;
8972
- const events = rows.map(function(n){
8973
- return {
8974
- id: n["${idFieldName}"],
8975
- title: n["${calendarOptions.textExpr}"],
8976
- start: n["${calendarOptions.startDateExpr}"],
8977
- end: n["${calendarOptions.endDateExpr}"],
8978
- allDay: n["${calendarOptions.allDayExpr}"],
8979
- extendedProps: n
8980
8991
  }
8981
- });
8982
- const successCallback = selfData.successCallback;
8983
- const failureCallback = selfData.failureCallback;
8984
- successCallback(events);
8985
- return payload;
8986
- `;
8987
- return api;
8988
- }
8989
8992
 
8990
- function getCalendarRecordPermissionsApi(mainObject, recordId) {
8991
- const api = getRecordPermissionsApi(mainObject, recordId, { alias: 'rows', limit: 1, fields: ["allowEdit"] });
8992
- api.data.$self = "$$";
8993
- api.adaptor = `
8994
- const rows = payload.data.rows || [];
8995
- const selfData = api.data.$self;
8996
- const revert = selfData.revert;
8997
- const recordPermissions = rows[0] && rows[0].recordPermissions;
8998
- const editable = !!(recordPermissions && recordPermissions.allowEdit);
8999
- if(!editable){
9000
- // 没有权限时还原
9001
- revert && revert();
9002
- }
9003
- payload.data.editable = editable;
9004
- return payload;
9005
- `;
9006
- return api;
9007
- }
9008
-
9009
- function getCalendarRecordSaveApi(object, calendarOptions) {
9010
- const formData = {};
9011
- const idFieldName = object.idFieldName || "_id";
9012
- formData[idFieldName] = "${event.data.event.id}";
9013
- const nameFieldKey = object.NAME_FIELD_KEY || "name";
9014
- formData[nameFieldKey] = "${event.data.event.title}";
9015
- formData[calendarOptions.startDateExpr] = "${event.data.event.start}";
9016
- formData[calendarOptions.endDateExpr] = "${event.data.event.end}";
9017
- formData[calendarOptions.allDayExpr] = "${event.data.event.allDay}";
9018
- // formData[calendarOptions.textExpr] = "${event.data.event.title}";
9019
- const apiData = {
9020
- objectName: "${objectName}",
9021
- $: formData,
9022
- $self: "$$"
9023
- };
9024
- const saveDataTpl = `
9025
- const formData = api.data.$;
9026
- const objectName = api.data.objectName;
9027
- let query = \`mutation{record: \${objectName}__update(id: "\${formData.${idFieldName}}", doc: {__saveData}){${idFieldName}}}\`;
9028
- delete formData.${idFieldName};
9029
- let __saveData = JSON.stringify(JSON.stringify(formData));
9030
- `;
9031
- const requestAdaptor = `
9032
- ${saveDataTpl}
9033
- api.data.query = query.replace('{__saveData}', __saveData);
9034
- return api;
9035
- `;
9036
-
9037
- return {
9038
- method: 'post',
9039
- url: getApi$2(),
9040
- data: apiData,
9041
- requestAdaptor: requestAdaptor,
9042
- adaptor: `
9043
- if(payload.errors){
9044
- payload.status = 2;
9045
- payload.msg = payload.errors[0].message;
9046
- const revert = api.data.$self.event.data.revert;
9047
- revert && revert();
9048
- }
9049
- return payload;
9050
- `,
9051
- headers: {
9052
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
9053
- }
8993
+ const amisSchema = {
8994
+ "type": "steedos-fullcalendar",
8995
+ "label": "",
8996
+ "name": "fullcalendar",
8997
+ "placeholder":"${additionalFilters}",//用于触发reload
8998
+ "editable": permissions.allowEdit,
8999
+ "selectable": permissions.allowCreate,
9000
+ "selectMirror": permissions.allowCreate,
9001
+ "initialView": initialView,
9002
+ "businessHours": businessHours,
9003
+ ...config,
9004
+ "onEvent": onEvent
9054
9005
  };
9006
+ return amisSchema;
9055
9007
  }
9056
9008
 
9057
- /**
9058
- * 列表视图Calendar amisSchema
9059
- * @param {*} objectSchema 对象UISchema
9060
- * @returns amisSchema
9009
+ /*
9010
+ * @Author: baozhoutao@steedos.com
9011
+ * @Date: 2022-05-26 16:02:08
9012
+ * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
9013
+ * @LastEditTime: 2023-06-04 15:49:23
9014
+ * @Description:
9061
9015
  */
9062
- async function getObjectCalendar(objectSchema, calendarOptions, options) {
9063
- const permissions = objectSchema.permissions;
9064
- if (!options) {
9065
- options = {};
9066
- }
9067
9016
 
9068
- calendarOptions = Object.assign({}, DEFAULT_CALENDAR_OPTIONS, ___default.omitBy(calendarOptions, ___default.isNil));
9017
+ const getFieldSchemaArray = (formFields) => {
9018
+ let fieldSchemaArray = [];
9019
+ fieldSchemaArray.length = 0;
9069
9020
 
9070
- const titleFields = calendarOptions.title || [
9071
- calendarOptions.startDateExpr,
9072
- calendarOptions.endDateExpr,
9073
- calendarOptions.allDayExpr,
9074
- calendarOptions.textExpr
9075
- ];
9076
- let fields = [];
9077
- ___default.each(titleFields, function (n) {
9078
- if (objectSchema.fields[n]) {
9079
- fields.push(objectSchema.fields[n]);
9021
+ ___default__namespace.forEach(formFields, (field) => {
9022
+ if (!field.group || field.group == 'null' || field.group == '-')
9023
+ field.group = '通用';
9024
+ const fieldName = field.name;
9025
+ let isObjectField = /\w+\.\w+/.test(fieldName);
9026
+ if (field.type == 'grid' || field.type == 'object') {
9027
+ // field.group = field.label
9028
+ field.is_wide = true;
9029
+ }
9030
+
9031
+ if (!isObjectField) {
9032
+ if (!field.hidden) {
9033
+ fieldSchemaArray.push(Object.assign({ name: fieldName }, field, { permission: { allowEdit: true } }));
9034
+ }
9080
9035
  }
9081
9036
  });
9037
+ return fieldSchemaArray;
9038
+ };
9082
9039
 
9083
- if (objectSchema.fields[calendarOptions.allDayExpr]) {
9084
- fields.push(objectSchema.fields[calendarOptions.allDayExpr]);
9040
+ const getSection = async (formFields, permissionFields, fieldSchemaArray, sectionName, ctx) => {
9041
+ if (!ctx) {
9042
+ ctx = {};
9043
+ }
9044
+ const sectionFields = ___default__namespace.filter(fieldSchemaArray, { 'group': sectionName });
9045
+ if (sectionFields.length == ___default__namespace.filter(sectionFields, ['hidden', true]).length) {
9046
+ return;
9085
9047
  }
9086
9048
 
9087
- let sort = options.sort;
9088
- if (!sort) {
9089
- const sortField = options.sortField;
9090
- const sortOrder = options.sortOrder;
9091
- if (sortField) {
9092
- let sortStr = sortField + ' ' + sortOrder || 'asc';
9093
- sort = sortStr;
9049
+ const fieldSetBody = [];
9050
+
9051
+ for (const perField of sectionFields) {
9052
+ let field = perField;
9053
+ if (perField.type === 'grid') {
9054
+ field = await getGridFieldSubFields(perField, formFields);
9055
+ // console.log(`perField.type grid ===> field`, field)
9056
+ } else if (perField.type === 'object') {
9057
+ field = await getObjectFieldSubFields(perField, formFields);
9058
+ // console.log(`perField.type object ===> field`, field)
9059
+ }
9060
+ if (field.name.indexOf(".") < 0) {
9061
+ ctx.__formFields = formFields;
9062
+ const amisField = await convertSFieldToAmisField(field, field.readonly, ctx);
9063
+ // console.log(`${field.name} amisField`, field, amisField)
9064
+ if (amisField) {
9065
+ fieldSetBody.push(amisField);
9066
+ }
9094
9067
  }
9095
9068
  }
9096
- let initialView = calendarOptions.currentView;
9097
- if (initialView) {
9098
- // day, week, month, agenda
9099
- switch (initialView) {
9100
- case "day":
9101
- initialView = "timeGridDay";
9102
- break;
9103
- case "week":
9104
- initialView = "timeGridWeek";
9105
- break;
9106
- case "month":
9107
- initialView = "dayGridMonth";
9108
- break;
9109
- case "agenda":
9110
- initialView = "listWeek";
9111
- break;
9069
+
9070
+ // fieldSet 已支持显隐控制
9071
+ const sectionFieldsVisibleOn = ___default__namespace.map(___default__namespace.compact(___default__namespace.map(fieldSetBody, 'visibleOn')), (visibleOn) => {
9072
+ return visibleOn;
9073
+ });
9074
+
9075
+ let section = {
9076
+ "type": "fieldSet",
9077
+ "title": sectionName,
9078
+ "collapsable": true,
9079
+ "body": fieldSetBody,
9080
+ };
9081
+
9082
+ if (ctx.enableTabs) {
9083
+ section = {
9084
+ "title": sectionName,
9085
+ "body": fieldSetBody,
9086
+ };
9087
+ }
9088
+
9089
+ if (sectionFieldsVisibleOn.length > 0 && fieldSetBody.length === sectionFieldsVisibleOn.length) {
9090
+ section.visibleOn = `${sectionFieldsVisibleOn.join(" || ")}`;
9091
+ }
9092
+ return section
9093
+ };
9094
+
9095
+ const getSections = async (permissionFields, formFields, ctx) => {
9096
+ if (!ctx) {
9097
+ ctx = {};
9098
+ }
9099
+ const fieldSchemaArray = getFieldSchemaArray(formFields);
9100
+ const _sections = ___default__namespace.groupBy(fieldSchemaArray, 'group');
9101
+ const sections = [];
9102
+ var sectionVisibleOns = [];
9103
+ for (const key in _sections) {
9104
+ const section = await getSection(formFields, permissionFields, fieldSchemaArray, key, ctx);
9105
+ if (section.body.length > 0) {
9106
+ if (section.visibleOn) {
9107
+ sectionVisibleOns.push(section.visibleOn);
9108
+ }
9109
+ else {
9110
+ sectionVisibleOns.push("true");
9111
+ }
9112
+ sections.push(section);
9112
9113
  }
9113
9114
  }
9114
- else {
9115
- initialView = "timeGridWeek";
9115
+ /*
9116
+ 为了实现只有一个分组时隐藏该分组标题,需要分三种情况(分组如果没有visibleon属性就代表一定显示,有visibleon需要进行判断)
9117
+ 1 当前分组为隐藏时,标题就设置为隐藏
9118
+ 2 当前分组为显示时,其他分组只要有一个是显示,就显示该分组标题
9119
+ 3 当前分组为显示时,其他分组都隐藏,就隐藏该分组标题
9120
+ */
9121
+ sections.forEach((section, index) => {
9122
+ var tempSectionVisibleOns = sectionVisibleOns.slice();
9123
+ tempSectionVisibleOns.splice(index, 1);
9124
+ section.headingClassName = {
9125
+ "hidden": `!((${tempSectionVisibleOns.join(" || ") || 'false'}) && ${sectionVisibleOns[index]})`
9126
+ };
9127
+ });
9128
+
9129
+ if (ctx.enableTabs) {
9130
+ // TODO: 以下sectionHeaderVisibleOn代码逻辑是为实现只有一个选项卡时给选项卡添加sectionHeaderVisibleOn样式类来把选项卡顶部卡头隐藏
9131
+ // 但是 amis filter过滤器有两个bug造成此功能不好实现:
9132
+ // 1.filter过滤器只支持对象数组,并不支持boolean或字符串数组,见: https://github.com/baidu/amis/issues/7078
9133
+ // 2.filter过滤器的返回结果无法进一步获取最终过滤后的数组长度,见:https://github.com/baidu/amis/issues/7077
9134
+ // let sectionHeaderVisibleOn = "false";
9135
+ // if(sectionVisibleOns.length){
9136
+ // sectionHeaderVisibleOn = "[" + sectionVisibleOns.join(",") + "]" + "|filter:equals:true.length > 1";
9137
+ // }
9138
+ // console.log("===sectionHeaderVisibleOn===", sectionHeaderVisibleOn);
9139
+ // sectionHeaderVisibleOn = "[true]|filter:equals:true.length > 1";
9140
+ // sectionHeaderVisibleOn = "false";
9141
+ // sectionHeaderVisibleOn = "[1,1,1]|filter:equals:1.length > 1";
9142
+ return [
9143
+ {
9144
+ "type": "tabs",
9145
+ // "className": {
9146
+ // "hiddenFormTabs": `!(${sectionHeaderVisibleOn})`
9147
+ // },
9148
+ "tabs": sections,
9149
+ "tabsMode": ctx.tabsMode
9150
+ }
9151
+ ]
9116
9152
  }
9117
9153
 
9118
- options.calendarOptions = calendarOptions;
9119
- const api = await getCalendarApi(objectSchema, fields, options);
9154
+ return sections;
9155
+ };
9120
9156
 
9121
- const onGetEventsScript = `
9122
- const api = ${JSON.stringify(api)};
9123
- event.data.calendarOptions = ${JSON.stringify(calendarOptions)};
9124
- doAction({
9125
- "actionType": 'ajax',
9126
- "args": {
9127
- "api": api
9128
- },
9129
- });
9130
- `;
9157
+ /*
9158
+ * @Author: baozhoutao@steedos.com
9159
+ * @Date: 2022-07-07 11:02:29
9160
+ * @LastEditors: baozhoutao@steedos.com
9161
+ * @LastEditTime: 2023-03-07 17:19:34
9162
+ * @Description:
9163
+ */
9131
9164
 
9132
- const onSelectScript = `
9133
- const data = event.data;
9134
- const doc = {};
9135
- doc["${calendarOptions.startDateExpr}"] = data.start;
9136
- doc["${calendarOptions.endDateExpr}"] = data.end;
9137
- doc["${calendarOptions.allDayExpr}"] = data.allDay;
9138
- doc["${calendarOptions.textExpr}"] = data.title;
9139
- // ObjectForm会认作用域下的变量值
9140
- // TODO: 待组件支持initValues属性后应该改掉,不应该通过data直接传值
9141
- // TODO: 全天事件属性传入doc了但是没有生效,需要手动在ObjectForm中勾选全天事件
9142
- const title = "新建 ${objectSchema.label}";
9143
- doAction(
9144
- {
9145
- "actionType": "dialog",
9146
- "dialog": {
9147
- "type": "dialog",
9148
- "title": title,
9149
- "body": [
9150
- {
9151
- "type": "steedos-object-form",
9152
- "objectApiName": "\${objectName}",
9153
- "mode": "edit",
9154
- "defaultData": doc,
9155
- "onEvent": {
9156
- "submitSucc": {
9157
- "weight": 0,
9158
- "actions": [
9159
- {
9160
- "actionType": "custom",
9161
- "script": "event.data.view?.calendar.refetchEvents();"
9162
- }
9163
- ]
9164
- }
9165
- }
9166
- }
9167
- ],
9168
- "closeOnEsc": false,
9169
- "closeOnOutside": false,
9170
- "showCloseButton": true,
9171
- "size": "lg"
9165
+ async function getFormBody(permissionFields, formFields, ctx){
9166
+ return await getSections(permissionFields, formFields, ctx);
9167
+ }
9168
+
9169
+ // lodash的defaultsDeep函数有bug,无法正确合并值为数值的节点,重写修正该函数
9170
+ // 源码出处:https://github.com/nodeutils/defaults-deep
9171
+ const defaultsDeep = (...args)=>{
9172
+ let output = {};
9173
+ ___default.toArray(args).reverse().forEach(item=> {
9174
+ ___default.mergeWith(output, item, (objectValue, sourceValue) => {
9175
+ return ___default.isArray(sourceValue) ? sourceValue : undefined;
9176
+ });
9177
+ });
9178
+ return output;
9179
+ };
9180
+
9181
+ function getBulkActions(objectSchema){
9182
+ return [
9183
+ {
9184
+ "type": "button",
9185
+ "level": "danger",
9186
+ "label": "批量删除",
9187
+ "actionType": "ajax",
9188
+ "confirmText": "确定要删除吗",
9189
+ "className": "hidden",
9190
+ "id": "batchDelete",
9191
+ "api": getBatchDelete(objectSchema.name),
9192
+ }
9193
+ // {
9194
+ // "label": "批量修改",
9195
+ // "actionType": "dialog",
9196
+ // "dialog": {
9197
+ // "title": "批量编辑",
9198
+ // "name": "sample-bulk-edit",
9199
+ // "body": {
9200
+ // "type": "form",
9201
+ // "api": "https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/sample/bulkUpdate2",
9202
+ // "controls": [
9203
+ // {
9204
+ // "type": "hidden",
9205
+ // "name": "ids"
9206
+ // },
9207
+ // {
9208
+ // "type": "text",
9209
+ // "name": "name",
9210
+ // "label": "Name"
9211
+ // }
9212
+ // ]
9213
+ // }
9214
+ // }
9215
+ // }
9216
+ ]
9217
+ }
9218
+
9219
+ async function getObjectCRUD(objectSchema, fields, options){
9220
+ // console.time('getObjectCRUD');
9221
+ const { top, perPage, showDisplayAs = false, displayAs, crudClassName = "" } = options;
9222
+ const nonpaged = objectSchema.paging && objectSchema.paging.enabled === false;
9223
+ const isTreeObject = objectSchema.enable_tree;
9224
+ const bulkActions = getBulkActions(objectSchema);
9225
+ const bodyProps = {
9226
+ // toolbar: getToolbar(),
9227
+ // headerToolbar: getObjectHeaderToolbar(objectSchema, options.formFactor, {showDisplayAs}),
9228
+ headerToolbarClassName: "px-4 py-2 border-gray-300 bg-gray-100 border-solid border-b",
9229
+ footerToolbar: getObjectFooterToolbar(objectSchema, options.formFactor, {
9230
+ disableStatistics: options.queryCount === false
9231
+ }),
9232
+ filter: options.filterVisible !== false && await getObjectFilter(objectSchema, fields, options),
9233
+ };
9234
+ if(options.formFactor !== 'SMALL' || ["split"].indexOf(options.displayAs) == -1){
9235
+ Object.assign(bodyProps, {
9236
+ bulkActions: options.bulkActions != false ? bulkActions : false
9237
+ });
9172
9238
  }
9173
- });
9174
- `;
9175
-
9176
- const onEventClickScript = `
9177
- const data = event.data;
9178
- const eventData = data.event;
9179
- const appId = data.appId;
9180
- const objectName = data.objectName;
9181
- const eventId = data.event && data.event.id;
9182
- doAction({
9183
- "actionType": "dialog",
9184
- "dialog": {
9185
- "type": "dialog",
9186
- "title": "",
9187
- "body": [
9188
- {
9189
- "type": "steedos-record-detail",
9190
- "objectApiName": "\${objectName}",
9191
- "recordId": data.event && data.event.id
9239
+ // yml里配置的 不分页和enable_tree:true 优先级最高,组件中输入的top次之。
9240
+ options.queryCount = true;
9241
+ if(nonpaged || isTreeObject){
9242
+ options.top = 5000;
9243
+ bodyProps.footerToolbar = [];
9244
+ options.queryCount = true; // 禁止翻页的时候, 需要查找总数
9245
+ }else if(top){
9246
+ bodyProps.footerToolbar = [];
9247
+ if(options.isRelated){
9248
+ options.queryCount = true;
9249
+ }else {
9250
+ options.queryCount = false;
9192
9251
  }
9193
- ],
9194
- "closeOnEsc": false,
9195
- "closeOnOutside": false,
9196
- "showCloseButton": true,
9197
- "size": "lg",
9198
- "actions": []
9199
- }
9200
- });
9201
- `;
9202
-
9203
- const recordId = "${event.id}";
9204
- const recordPermissionsApi = getCalendarRecordPermissionsApi(objectSchema, recordId);
9205
- const recordSaveApi = getCalendarRecordSaveApi(objectSchema, calendarOptions);
9252
+ }
9253
+ // console.log(`getObjectHeaderToolbar====2===>`, options.filterVisible)
9254
+ bodyProps.headerToolbar = getObjectHeaderToolbar(objectSchema, options.formFactor, {
9255
+ showDisplayAs,
9256
+ hiddenCount: options.queryCount === false,
9257
+ headerToolbarItems: options.headerToolbarItems,
9258
+ filterVisible: options.filterVisible
9259
+ });
9206
9260
 
9207
- const businessHours = {
9208
- daysOfWeek: [1, 2, 3, 4, 5],
9209
- startTime: '08:00',
9210
- endTime: '18:00',
9211
- };
9212
- if (!___default.isEmpty(calendarOptions.startDayHour)) {
9213
- businessHours.startTime = `${calendarOptions.startDayHour}:00`;
9214
- }
9215
- if (!___default.isEmpty(calendarOptions.endDayHour)) {
9216
- businessHours.endTime = `${calendarOptions.endDayHour}:00`;
9217
- }
9218
9261
 
9219
- const onEvent = {
9220
- "getEvents": {
9221
- "weight": 0,
9222
- "actions": [
9223
- {
9224
- "componentId": "",
9225
- "args": {
9226
- },
9227
- "actionType": "custom",
9228
- "script": onGetEventsScript
9229
- }
9230
- ]
9231
- },
9232
- "select": {
9233
- "weight": 0,
9234
- "actions": [
9235
- {
9236
- "componentId": "",
9237
- "args": {
9238
- },
9239
- "actionType": "custom",
9240
- "script": onSelectScript
9262
+ let body = null;
9263
+ const id = `listview_${objectSchema.name}`;
9264
+ if(options.formFactor === 'SMALL' && false){
9265
+ delete bodyProps.bulkActions;
9266
+ delete bodyProps.headerToolbar;
9267
+ delete bodyProps.footerToolbar;
9268
+ const card = await getCardSchema(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: objectSchema.NAME_FIELD_KEY || 'name'}, options, {actions: false}));
9269
+ body = Object.assign({}, card , {
9270
+ type: 'crud',
9271
+ primaryField: '_id',
9272
+ id: id,
9273
+ name: id,
9274
+ keepItemSelectionOnPageChange: false,
9275
+ api: await getTableApi(objectSchema, fields, options),
9276
+ hiddenOn: options.tableHiddenOn,
9277
+ },
9278
+ bodyProps
9279
+ );
9280
+ }else {
9281
+ let labelFieldName = objectSchema.NAME_FIELD_KEY || 'name';
9282
+ // organizations 对象的历史遗留问题, fullname 被标记为了 名称字段. 在此处特殊处理.
9283
+ if(objectSchema.name === 'organizations'){
9284
+ labelFieldName = 'name';
9285
+ }
9286
+ const table = await getTableSchema$1(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: labelFieldName, permissions:objectSchema.permissions,enable_inline_edit:objectSchema.enable_inline_edit}, options));
9287
+ delete table.mode;
9288
+ //image与avatar需要在提交修改时特别处理
9289
+ const imageNames = ___default__default["default"].compact(___default__default["default"].map(___default__default["default"].filter(fields, (field) => ["image","avatar"].includes(field.type)), 'name'));
9290
+ const quickSaveApiRequestAdaptor = `
9291
+ var graphqlOrder = "";
9292
+ var imageNames = ${JSON.stringify(imageNames)};
9293
+ api.data.rowsDiff.forEach(function (item, index) {
9294
+ for(key in item){
9295
+ if(_.includes(imageNames, key)){
9296
+ if(typeof item[key] == "string"){
9297
+ const match = item[key].match(/\\/([^\\/]+)$/);
9298
+ item[key] = match && match.length > 1?match[1]:"";
9299
+ }else{
9300
+ item[key] = _.map(item[key], function(ele){
9301
+ const match = ele.match(/\\/([^\\/]+)$/);
9302
+ return match && match.length > 1?match[1]:"";
9303
+ })
9304
+ }
9241
9305
  }
9242
- ]
9243
- },
9244
- "eventClick": {
9245
- "weight": 0,
9246
- "actions": [
9247
- {
9248
- "componentId": "",
9249
- "args": {
9250
- },
9251
- "actionType": "custom",
9252
- "script": onEventClickScript
9306
+ }
9307
+ const itemOrder = 'update' + index + ':' + api.data.objectName + '__update(id:"' + item._id + '", doc:' + JSON.stringify(JSON.stringify(_.omit(item, '_id'))) + ') {_id}';
9308
+ graphqlOrder += itemOrder;
9309
+ })
9310
+ graphqlOrder = 'mutation {' + graphqlOrder + '}';
9311
+ return {
9312
+ ...api,
9313
+ data: {
9314
+ query: graphqlOrder
9253
9315
  }
9254
- ]
9255
- },
9256
- "eventAdd": {
9257
- "weight": 0,
9258
- "actions": [
9259
- {
9260
- "componentId": "",
9261
- "args": {
9316
+ }
9317
+ `;
9318
+
9319
+ body = Object.assign({}, table, {
9320
+ type: 'crud',
9321
+ primaryField: '_id',
9322
+ affixHeader: false,
9323
+ id: id,
9324
+ name: id,
9325
+ keepItemSelectionOnPageChange: true,
9326
+ api: await getTableApi(objectSchema, fields, options),
9327
+ hiddenOn: options.tableHiddenOn,
9328
+ autoFillHeight: options.isRelated ? false : true,
9329
+ className: `flex-auto ${crudClassName || ""}`,
9330
+ bodyClassName: "bg-white",
9331
+ crudClassName: crudClassName,
9332
+ quickSaveApi: {
9333
+ url: `\${context.rootUrl}/graphql`,
9334
+ method: "post",
9335
+ dataType: "json",
9336
+ headers: {
9337
+ Authorization: "Bearer ${context.tenantId},${context.authToken}",
9262
9338
  },
9263
- "actionType": "custom",
9264
- "script": "console.log('eventAdd'); console.log(event);"
9265
- }
9266
- ]
9267
- },
9268
- "eventChange": {
9269
- "weight": 0,
9270
- "actions": [
9271
- {
9272
- "actionType": 'ajax',
9273
- "args": {
9274
- "api": recordPermissionsApi
9275
- }
9339
+ requestAdaptor: quickSaveApiRequestAdaptor,
9276
9340
  },
9277
- {
9278
- "actionType": "toast",
9279
- "expression": "!event.data.editable",
9280
- "args": {
9281
- "msgType": "error",
9282
- "msg": "您没有编辑该记录的权限!",
9283
- "position": "top-center"
9341
+ rowClassNameExpr: options.rowClassNameExpr
9342
+ },
9343
+ bodyProps,
9344
+ );
9345
+ }
9346
+
9347
+ const defaults = options.defaults;
9348
+ if (defaults) {
9349
+ const listSchema = defaults.listSchema || {};
9350
+ body = defaultsDeep({}, listSchema, body);
9351
+ const headerSchema = defaults.headerSchema;
9352
+ const footerSchema = defaults.footerSchema;
9353
+ if (headerSchema || footerSchema) {
9354
+ let wrappedBody = [body];
9355
+ if (headerSchema) {
9356
+ if(___default__default["default"].isArray(headerSchema)){
9357
+ wrappedBody = ___default__default["default"].union(headerSchema,wrappedBody);
9284
9358
  }
9285
- },
9286
- {
9287
- "actionType": 'ajax',
9288
- "expression": "event.data.editable",
9289
- "args": {
9290
- "api": recordSaveApi,
9291
- "messages": {
9292
- "success": objectSchema.label + "修改成功",
9293
- "failed": objectSchema.label + "修改失败!"
9294
- }
9359
+ else {
9360
+ wrappedBody.unshift(headerSchema);
9295
9361
  }
9296
9362
  }
9297
- ]
9298
- },
9299
- "eventRemove": {
9300
- "weight": 0,
9301
- "actions": [
9302
- {
9303
- "componentId": "",
9304
- "args": {
9305
- },
9306
- "actionType": "custom",
9307
- "script": "console.log('eventRemove'); console.log(event);"
9308
- }
9309
- ]
9310
- },
9311
- "eventsSet": {
9312
- "weight": 0,
9313
- "actions": [
9314
- {
9315
- "componentId": "",
9316
- "args": {
9317
- },
9318
- "actionType": "custom",
9319
- "script": "console.log('eventsSet'); console.log(event);"
9363
+ if (footerSchema) {
9364
+ if(___default__default["default"].isArray(footerSchema)){
9365
+ wrappedBody = ___default__default["default"].union(wrappedBody,footerSchema);
9366
+ }
9367
+ else {
9368
+ wrappedBody.push(footerSchema);
9369
+ }
9320
9370
  }
9321
- ]
9371
+ body = wrappedBody;
9372
+ }
9373
+ }
9374
+ // console.timeEnd('getObjectCRUD');
9375
+ // TODO: data应该只留loaded,其他属性都改为从上层传递下来
9376
+ return {
9377
+ type: 'service',
9378
+ className: '',
9379
+ id: `service_${id}`,
9380
+ name: `page`,
9381
+ data: {
9382
+ objectName: objectSchema.name,
9383
+ // _id: null,
9384
+ recordPermissions: objectSchema.permissions,
9385
+ uiSchema: objectSchema,
9386
+ // loaded: false //crud接收适配器中设置为true,否则就是刷新浏览器第一次加载
9387
+ },
9388
+ body: body
9322
9389
  }
9323
- };
9390
+ }
9324
9391
 
9325
- Object.assign(onEvent, options.onEvent);
9392
+ const getGlobalData = (mode)=>{
9393
+ const user = getSteedosAuth();
9394
+ return {mode: mode, user: user, spaceId: user.spaceId, userId: user.userId}
9395
+ };
9326
9396
 
9327
- const config = options.config || {};
9328
- if(config.eventContent && typeof config.eventContent === "string"){
9329
- const hasReturn = /\breturn\b/.test(config.eventContent);
9330
- if(hasReturn){
9331
- try {
9332
- // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
9333
- let fn = new Function("arg", config.eventContent);
9334
- config.eventContent = fn;
9335
- } catch (e) {
9336
- console.warn(e);
9337
- }
9397
+ const getFormFields = (objectSchema, formProps)=>{
9398
+ /**
9399
+ * fieldsExtend: 重写字段定义
9400
+ * fields: 包含的字段
9401
+ * excludedFields: 排除的字段
9402
+ */
9403
+ const { fieldsExtend, fields: includedFields, excludedFields } = formProps;
9404
+
9405
+ let fields = {};
9406
+ // 以uiSchema fields 为基础, 遍历字段, 并更新字段定义
9407
+ ___default__default["default"].forEach(objectSchema.fields, (field, fieldName)=>{
9408
+ if(!lodash.has(field, "name")){
9409
+ field.name = fieldName;
9338
9410
  }
9339
- }
9411
+ if(fieldsExtend && fieldsExtend[fieldName]){
9412
+ fields[field.name] = Object.assign({}, field, fieldsExtend[fieldName], {name: field.name});
9413
+ }else {
9414
+ fields[field.name] = field;
9415
+ }
9416
+ });
9340
9417
 
9341
- if(config.noEventsContent && typeof config.noEventsContent === "string"){
9342
- const hasReturn = /\breturn\b/.test(config.noEventsContent);
9343
- if(hasReturn){
9344
- try {
9345
- // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
9346
- let fn = new Function("arg", config.noEventsContent);
9347
- config.noEventsContent = fn;
9348
- } catch (e) {
9349
- console.warn(e);
9418
+ if(!___default__default["default"].isEmpty(includedFields) && ___default__default["default"].isArray(includedFields)){
9419
+ const includedFieldsMap = {};
9420
+ ___default__default["default"].each(includedFields, (fName, index)=>{
9421
+ if(fields[fName]){
9422
+ includedFieldsMap[fName] = Object.assign({}, fields[fName], {sort_no: index});
9350
9423
  }
9351
- }
9424
+ });
9425
+ fields = includedFieldsMap;
9352
9426
  }
9353
9427
 
9354
- const amisSchema = {
9355
- "type": "steedos-fullcalendar",
9356
- "label": "",
9357
- "name": "fullcalendar",
9358
- "placeholder":"${additionalFilters}",//用于触发reload
9359
- "editable": permissions.allowEdit,
9360
- "selectable": permissions.allowCreate,
9361
- "selectMirror": permissions.allowCreate,
9362
- "initialView": initialView,
9363
- "businessHours": businessHours,
9364
- ...config,
9365
- "onEvent": onEvent
9366
- };
9367
- return amisSchema;
9428
+ if(!___default__default["default"].isEmpty(excludedFields) && ___default__default["default"].isArray(excludedFields)){
9429
+ ___default__default["default"].each(excludedFields, (fName)=>{
9430
+ delete fields[fName];
9431
+ });
9432
+ }
9433
+
9434
+ return lodash.sortBy(___default__default["default"].values(fields), "sort_no");
9435
+ };
9436
+
9437
+ async function getObjectForm(objectSchema, ctx){
9438
+ const { recordId, formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, tabId, appId, defaults } = ctx;
9439
+ const fields = ___default__default["default"].values(objectSchema.fields);
9440
+ const formFields = getFormFields(objectSchema, ctx);
9441
+ const formSchema = defaults && defaults.formSchema || {};
9442
+ if(___default__default["default"].has(formSchema, 'className')){
9443
+ formSchema.className = 'steedos-amis-form';
9444
+ }
9445
+ const amisSchema = {
9446
+ type: 'service',
9447
+ className: 'p-0',
9448
+ name: `page_edit_${recordId}`,
9449
+ api: await getEditFormInitApi(objectSchema, recordId, fields, ctx),
9450
+ data:{
9451
+ editFormInited: false
9452
+ },
9453
+ // data: {global: getGlobalData('edit'), recordId: recordId, objectName: objectSchema.name, context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
9454
+ initApi: null,
9455
+ initFetch: null ,
9456
+ body: [defaultsDeep({}, formSchema, {
9457
+ type: "form",
9458
+ mode: layout,
9459
+ data: {
9460
+ "&": "${initialValues}"
9461
+ },
9462
+ labelAlign,
9463
+ persistData: false,
9464
+ resetAfterSubmit: true,
9465
+ preventEnterSubmit: true,
9466
+ promptPageLeave: true,
9467
+ canAccessSuperData: false,
9468
+ name: `form_edit_${recordId}`,
9469
+ debug: false,
9470
+ title: "",
9471
+ submitText: "", // amis 表单不显示提交按钮, 表单提交由项目代码接管
9472
+ api: await getSaveApi(objectSchema, recordId, fields, ctx),
9473
+ initFetch: recordId != 'new',
9474
+ body: await getFormBody(fields, formFields, ctx),
9475
+ panelClassName:'m-0 sm:rounded-lg shadow-none border-none',
9476
+ bodyClassName: 'p-0',
9477
+ className: 'steedos-amis-form',
9478
+ hiddenOn: "${editFormInited != true}",
9479
+ onEvent: {
9480
+ "submitSucc": {
9481
+ "weight": 0,
9482
+ "actions": [
9483
+ {
9484
+ "actionType": "broadcast",
9485
+ "args": {
9486
+ "eventName": `@data.changed.${objectSchema.name}`
9487
+ },
9488
+ "data": {
9489
+ "objectName": `${objectSchema.name}`,
9490
+ "displayAs": "${displayAs}"
9491
+ }
9492
+ },
9493
+ {
9494
+ "actionType": "broadcast",
9495
+ "args": {
9496
+ "eventName": "@data.changed.${_master.objectName}"
9497
+ },
9498
+ "data": {
9499
+ "objectName": "${_master.objectName}",
9500
+ "_isRelated": "${_isRelated || _master._isRelated}"
9501
+ },
9502
+ "expression": `\${_master.objectName != '${objectSchema.name}' && _master.objectName}`
9503
+ },
9504
+ // {
9505
+ // "actionType": "custom",
9506
+ // "script": "debugger;"
9507
+ // },
9508
+ // {
9509
+ // "args": {},
9510
+ // "actionType": "closeDialog"
9511
+ // }
9512
+ ]
9513
+ }
9514
+ }
9515
+ })]
9516
+ };
9517
+ if(formSchema.id){
9518
+ amisSchema.id = `service-${formSchema.id}`;
9519
+ }
9520
+ return amisSchema;
9521
+ }
9522
+
9523
+ async function getObjectDetail(objectSchema, recordId, ctx){
9524
+ const { formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, formInitProps } = ctx;
9525
+ const fields = ___default__default["default"].values(objectSchema.fields);
9526
+ const formFields = getFormFields(objectSchema, ctx);
9527
+ const serviceId = `service_detail_page`;
9528
+ return {
9529
+ type: 'service',
9530
+ name: `page_readonly_${recordId}`,
9531
+ id: serviceId,
9532
+ data: {global: getGlobalData('read'), context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
9533
+ api: await getReadonlyFormInitApi(objectSchema, recordId, fields, formInitProps),
9534
+ body: [
9535
+ {
9536
+ "type": "wrapper", //form 的 hiddenOn 会导致 form onEvent 异常, 使用wrapper包裹一次form,并在wrapper上控制显隐
9537
+ hiddenOn: "${recordLoaded != true}",
9538
+ "className": "p-0 m-0",
9539
+ "body": {
9540
+ type: "form",
9541
+ mode: layout,
9542
+ labelAlign,
9543
+ persistData: false,
9544
+ promptPageLeave: false,
9545
+ name: `form_readonly_${recordId}`,
9546
+ debug: false,
9547
+ title: "",
9548
+ data: {
9549
+ "formData": "$$"
9550
+ },
9551
+ wrapWithPanel: false,
9552
+ body: await getFormBody(___default.map(fields, (field)=>{field.readonly = true; return field;}), ___default.map(formFields, (field)=>{field.readonly = true; return field;}), Object.assign({}, ctx, {showSystemFields: true})),
9553
+ className: 'steedos-amis-form bg-white',
9554
+ actions: [], // 不显示表单默认的提交按钮
9555
+ onEvent: {
9556
+ [`@data.changed.${objectSchema.name}`]: { // 由于amis service 组件的 onEvent 存在bug ,此处借助form来刷新 上层 service https://github.com/baidu/amis/issues/6294
9557
+ "actions": [
9558
+ {
9559
+ "actionType": "reload",
9560
+ "componentId": serviceId,
9561
+ "expression": "this.__deletedRecord != true"
9562
+ },
9563
+ {
9564
+ // "args": {
9565
+ // "url": "/app/${appId}/${objectName}/grid/${side_listview_id}",
9566
+ // "blank": false
9567
+ // },
9568
+ "actionType": "custom",
9569
+ "script": "Steedos.goBack()",
9570
+ "expression": "this.__deletedRecord === true"
9571
+ }
9572
+ ]
9573
+ }
9574
+ }
9575
+ },
9576
+ }
9577
+ ],
9578
+ onEvent: {
9579
+ "fetchInited": {
9580
+ "weight": 0,
9581
+ "actions": [
9582
+ {
9583
+ actionType: 'broadcast',
9584
+ eventName: "recordLoaded",
9585
+ args: {
9586
+ eventName: "recordLoaded"
9587
+ },
9588
+ data: {
9589
+ objectName: "${event.data.__objectName}",
9590
+ record: "${event.data.__record}"
9591
+ },
9592
+ expression: "${event.data.__response.error != true}"
9593
+ },
9594
+ {
9595
+ "actionType": "setValue",
9596
+ "args": {
9597
+ value: {
9598
+ "recordLoaded": true,
9599
+ }
9600
+ },
9601
+ expression: "${event.data.__response.error != true}"
9602
+ }
9603
+ ]
9604
+ }
9605
+ }
9606
+ }
9368
9607
  }
9369
9608
 
9370
9609
  /*
@@ -9786,8 +10025,8 @@ else{
9786
10025
  /*
9787
10026
  * @Author: baozhoutao@steedos.com
9788
10027
  * @Date: 2022-07-05 15:55:39
9789
- * @LastEditors: baozhoutao@steedos.com
9790
- * @LastEditTime: 2023-04-28 11:11:29
10028
+ * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
10029
+ * @LastEditTime: 2023-06-04 17:36:49
9791
10030
  * @Description:
9792
10031
  */
9793
10032
 
@@ -10118,7 +10357,8 @@ else{
10118
10357
  "requestAdaptor": listView.requestAdaptor,
10119
10358
  "adaptor": listView.adaptor,
10120
10359
  "headerToolbarItems": ctx.headerToolbarItems,
10121
- "filterVisible": ctx.filterVisible
10360
+ "filterVisible": ctx.filterVisible,
10361
+ "rowClassNameExpr": ctx.rowClassNameExpr
10122
10362
  };
10123
10363
  return {
10124
10364
  uiSchema,
@@ -13708,11 +13948,11 @@ else{
13708
13948
  };
13709
13949
 
13710
13950
  var AmisObjectForm = function (props) { return __awaiter(void 0, void 0, void 0, function () {
13711
- var $schema, recordId, defaultData, mode, layout, labelAlign, appId, fieldsExtend, _a, excludedFields, _b, fields, _c, className, initApiRequestAdaptor, initApiAdaptor, apiRequestAdaptor, apiAdaptor, objectApiName, schemaKeys, formSchema, defaults, options, globalData, amisSchema, uiSchema, schema, schema, formData;
13951
+ var $schema, recordId, defaultData, mode, layout, labelAlign, appId, fieldsExtend, _a, excludedFields, _b, fields, _c, className, initApiRequestAdaptor, initApiAdaptor, apiRequestAdaptor, apiAdaptor, enableTabs, tabsMode, objectApiName, schemaKeys, formSchema, defaults, options, globalData, amisSchema, uiSchema, schema, schema, formData;
13712
13952
  return __generator(this, function (_d) {
13713
13953
  switch (_d.label) {
13714
13954
  case 0:
13715
- $schema = props.$schema, recordId = props.recordId, defaultData = props.defaultData, mode = props.mode, layout = props.layout, labelAlign = props.labelAlign, appId = props.appId, fieldsExtend = props.fieldsExtend, _a = props.excludedFields, excludedFields = _a === void 0 ? null : _a, _b = props.fields, fields = _b === void 0 ? null : _b, _c = props.className, className = _c === void 0 ? "" : _c, initApiRequestAdaptor = props.initApiRequestAdaptor, initApiAdaptor = props.initApiAdaptor, apiRequestAdaptor = props.apiRequestAdaptor, apiAdaptor = props.apiAdaptor;
13955
+ $schema = props.$schema, recordId = props.recordId, defaultData = props.defaultData, mode = props.mode, layout = props.layout, labelAlign = props.labelAlign, appId = props.appId, fieldsExtend = props.fieldsExtend, _a = props.excludedFields, excludedFields = _a === void 0 ? null : _a, _b = props.fields, fields = _b === void 0 ? null : _b, _c = props.className, className = _c === void 0 ? "" : _c, initApiRequestAdaptor = props.initApiRequestAdaptor, initApiAdaptor = props.initApiAdaptor, apiRequestAdaptor = props.apiRequestAdaptor, apiAdaptor = props.apiAdaptor, enableTabs = props.enableTabs, tabsMode = props.tabsMode;
13716
13956
  objectApiName = props.objectApiName || "space_users";
13717
13957
  schemaKeys = ___default.difference(___default.keys($schema), ["type", "mode", "layout", "defaultData"]);
13718
13958
  formSchema = ___default.pick(props, schemaKeys);
@@ -13742,7 +13982,9 @@ else{
13742
13982
  initApiRequestAdaptor: initApiRequestAdaptor,
13743
13983
  initApiAdaptor: initApiAdaptor,
13744
13984
  apiRequestAdaptor: apiRequestAdaptor,
13745
- apiAdaptor: apiAdaptor
13985
+ apiAdaptor: apiAdaptor,
13986
+ enableTabs: enableTabs,
13987
+ tabsMode: tabsMode
13746
13988
  }))];
13747
13989
  case 1:
13748
13990
  schema = _d.sent();
@@ -13780,14 +14022,14 @@ else{
13780
14022
  }); };
13781
14023
 
13782
14024
  var AmisObjectListView = function (props) { return __awaiter(void 0, void 0, void 0, function () {
13783
- var $schema, top, perPage, _a, showHeader, data, defaultData, _b, className, crudClassName, _c, showDisplayAs, sideSchema, _e, filterVisible, headerToolbarItems, headerSchema, ctx, listName, defaults, objectApiName, displayAs, formFactor, isMobile, uiSchema, listView, schemaKeys, listSchema, setDataToComponentId, amisSchemaData, listViewId, listViewSchemaProps, serviceData;
14025
+ var $schema, top, perPage, _a, showHeader, data, defaultData, _b, className, crudClassName, _c, showDisplayAs, sideSchema, _e, filterVisible, headerToolbarItems, rowClassNameExpr, headerSchema, ctx, listName, defaults, objectApiName, displayAs, formFactor, isMobile, uiSchema, listView, schemaKeys, listSchema, setDataToComponentId, amisSchemaData, listViewId, listViewSchemaProps, serviceData;
13784
14026
  var _f;
13785
14027
  return __generator(this, function (_g) {
13786
14028
  switch (_g.label) {
13787
14029
  case 0:
13788
14030
  // console.time('AmisObjectListView')
13789
14031
  console.log("AmisObjectListView props", props);
13790
- $schema = props.$schema, top = props.top, perPage = props.perPage, _a = props.showHeader, showHeader = _a === void 0 ? true : _a, data = props.data, defaultData = props.defaultData, _b = props.className, className = _b === void 0 ? "" : _b, crudClassName = props.crudClassName, _c = props.showDisplayAs, showDisplayAs = _c === void 0 ? false : _c, sideSchema = props.sideSchema, props.columnsTogglable, _e = props.filterVisible, filterVisible = _e === void 0 ? true : _e, headerToolbarItems = props.headerToolbarItems;
14032
+ $schema = props.$schema, top = props.top, perPage = props.perPage, _a = props.showHeader, showHeader = _a === void 0 ? true : _a, data = props.data, defaultData = props.defaultData, _b = props.className, className = _b === void 0 ? "" : _b, crudClassName = props.crudClassName, _c = props.showDisplayAs, showDisplayAs = _c === void 0 ? false : _c, sideSchema = props.sideSchema, props.columnsTogglable, _e = props.filterVisible, filterVisible = _e === void 0 ? true : _e, headerToolbarItems = props.headerToolbarItems, rowClassNameExpr = props.rowClassNameExpr;
13791
14033
  headerSchema = props.headerSchema;
13792
14034
  ctx = props.ctx;
13793
14035
  listName = (defaultData === null || defaultData === void 0 ? void 0 : defaultData.listName) || (data === null || data === void 0 ? void 0 : data.listName) || (props === null || props === void 0 ? void 0 : props.listName);
@@ -13868,7 +14110,7 @@ else{
13868
14110
  }
13869
14111
  amisSchemaData = Object.assign({}, data, defaultData);
13870
14112
  listViewId = (ctx === null || ctx === void 0 ? void 0 : ctx.listViewId) || amisSchemaData.listViewId;
13871
- listViewSchemaProps = __assign$2(__assign$2({ top: top, perPage: perPage, showHeader: showHeader, defaults: defaults }, ctx), { listViewId: listViewId, setDataToComponentId: setDataToComponentId, filterVisible: filterVisible, showDisplayAs: showDisplayAs, displayAs: displayAs, headerToolbarItems: headerToolbarItems });
14113
+ listViewSchemaProps = __assign$2(__assign$2({ top: top, perPage: perPage, showHeader: showHeader, defaults: defaults }, ctx), { listViewId: listViewId, setDataToComponentId: setDataToComponentId, filterVisible: filterVisible, showDisplayAs: showDisplayAs, displayAs: displayAs, headerToolbarItems: headerToolbarItems, rowClassNameExpr: rowClassNameExpr });
13872
14114
  if (!headerSchema) {
13873
14115
  headerSchema = getObjectListHeader$1(uiSchema, listName, ctx);
13874
14116
  }