@steedos-widgets/amis-lib 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.
package/dist/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _$1 from 'lodash';
2
- import ___default, { isEmpty, isArray, each, find, endsWith, cloneDeep, forEach, includes, get, toArray, mergeWith, map, isBoolean, omitBy, isNil, isString, union, has, slice, defaultsDeep as defaultsDeep$1, isObject as isObject$1, filter, startsWith } from 'lodash';
2
+ import ___default, { isEmpty, isArray, each, find, endsWith, cloneDeep, forEach, includes, get, isBoolean, omitBy, isNil, toArray, mergeWith, map, isString, union, has, slice, defaultsDeep as defaultsDeep$1, isObject as isObject$1, filter, startsWith } from 'lodash';
3
3
  import { Router as Router$1, getSteedosAuth as getSteedosAuth$1, lookupToAmis as lookupToAmis$1, fetchAPI as fetchAPI$1 } from '@steedos-widgets/amis-lib';
4
4
  import isPlainObject from 'lodash/isPlainObject';
5
5
 
@@ -1386,8 +1386,8 @@ const parseSingleExpression = function (func, formData, dataPath, global, userSe
1386
1386
  /*
1387
1387
  * @Author: baozhoutao@steedos.com
1388
1388
  * @Date: 2022-11-01 15:51:00
1389
- * @LastEditors: Please set LastEditors
1390
- * @LastEditTime: 2023-04-26 11:52:04
1389
+ * @LastEditors: liaodaxue
1390
+ * @LastEditTime: 2023-06-06 11:12:33
1391
1391
  * @Description:
1392
1392
  */
1393
1393
 
@@ -1470,7 +1470,7 @@ const getSchema$4 = async (uiSchema, ctx) => {
1470
1470
  "isLookup": "${isLookup}",
1471
1471
  "listName": "${listName}"
1472
1472
  },
1473
- "title": "新建 ${uiSchema.label}",
1473
+ "title": "新建 ${uiSchema.label | raw}",
1474
1474
  "body": [
1475
1475
  {
1476
1476
  "type": "service",
@@ -5443,6 +5443,7 @@ async function lookupToAmisPicker(field, readonly, ctx){
5443
5443
  pickerSchema = await getTableSchema$1(tableFields, {
5444
5444
  labelFieldName: refObjectConfig.NAME_FIELD_KEY,
5445
5445
  top: top,
5446
+ isLookup: true,
5446
5447
  ...ctx
5447
5448
  });
5448
5449
 
@@ -5492,6 +5493,10 @@ async function lookupToAmisPicker(field, readonly, ctx){
5492
5493
  };
5493
5494
  }
5494
5495
 
5496
+ if(field.pickerSchema){
5497
+ pickerSchema = Object.assign({}, pickerSchema, field.pickerSchema);
5498
+ }
5499
+
5495
5500
  const data = {
5496
5501
  type: getAmisStaticFieldType('picker', readonly),
5497
5502
  labelField: referenceTo.labelField.name,
@@ -6018,7 +6023,7 @@ const getAmisFileReadonlySchema = (steedosField)=>{
6018
6023
  return {
6019
6024
  type: amisFieldType,
6020
6025
  tpl: `
6021
- <% let fileData = data.${steedosField.name}; if (fileData) { %>
6026
+ <% let fileData = data._display.${steedosField.name}; if (fileData) { %>
6022
6027
  <% if(!Array.isArray(fileData)){ fileData = [fileData]} %>
6023
6028
  <% fileData.forEach(function(item) { %>
6024
6029
  <a href='<%= item.url %>' target='_self' class='block'><%= item.name %></a>
@@ -6059,7 +6064,6 @@ const getAmisFileEditSchema = (steedosField)=>{
6059
6064
  }
6060
6065
  }
6061
6066
  };
6062
-
6063
6067
  if(steedosField.multiple){
6064
6068
  convertData.multiple = true;
6065
6069
  convertData.joinValues = false;
@@ -6782,2204 +6786,2439 @@ var index = /*#__PURE__*/Object.freeze({
6782
6786
  getAmisStaticFieldType: getAmisStaticFieldType
6783
6787
  });
6784
6788
 
6785
- const API_CACHE = 100;
6789
+ /*
6790
+ * @Author: baozhoutao@steedos.com
6791
+ * @Date: 2022-08-04 10:42:49
6792
+ * @LastEditors: baozhoutao@steedos.com
6793
+ * @LastEditTime: 2022-08-25 10:28:47
6794
+ * @Description:
6795
+ */
6796
+ var config = {
6797
+ listView: {
6798
+ newRecordMode: 'modal',
6799
+ editRecordMode: 'modal',
6800
+ perPage: 20
6801
+ }
6802
+ };
6786
6803
 
6787
- function getReadonlyFormAdaptor(object, fields){
6788
- let scriptStr = '';
6789
- const selectFields = _$1.filter(fields, function(field){return field.name.indexOf('.') < 0 && ((field.type == 'select' && field.options) || ((field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to))});
6790
- const gridAndObjectFieldsName = _$1.map(_$1.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type === 'object' || field.type === 'grid')}), 'name');
6791
- _$1.each(selectFields, function(field){
6792
- if(!_$1.includes(OMIT_FIELDS, field.name)){
6793
- field.name;
6794
- if(field.options){
6795
- const options = JSON.stringify({options: field.options});
6796
- scriptStr = scriptStr + `var ${field.name}Options= (${options}).options;`;
6797
- }else if(field.optionsFunction){
6798
- scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`;
6799
- }else if(field._optionsFunction){
6800
- scriptStr = scriptStr + `var ${field.name}Options = eval(${field._optionsFunction})(api.data);`;
6801
- }
6802
- if(field.multiple){
6803
- scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`;
6804
- }else {
6805
- scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`;
6806
- scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`;
6804
+ async function getQuickEditSchema(field, options){
6805
+ const quickEditId = options.objectName + "_" + field.name + "QuickEdit";//定义快速编辑的表单id,用于setvalue传值
6806
+ var quickEditSchema = { body: [], id: quickEditId };
6807
+ if (field.disabled) {
6808
+ quickEditSchema = false;
6809
+ } else {
6810
+ var fieldSchema = await convertSFieldToAmisField(field, false, _$1.omit(options, 'buttons'));
6811
+ //存在属性上可编辑,实际不可编辑的字段,convertSFieldToAmisField函数可能会返回undefined,如summary
6812
+ if (!!fieldSchema) {
6813
+ quickEditSchema.body.push(fieldSchema);
6814
+ //以下字段使用_display的数据,因此在触发change等事件时对数据_display进行修改,以实现保存前的回显
6815
+ var TempDisplayField = ``;
6816
+ quickEditSchema.body[0].onEvent = {};
6817
+ const quickEditOnEvent = function (displayField) {
6818
+ const EventType = {
6819
+ "actions": [
6820
+ {
6821
+ "actionType": "custom",
6822
+ "script": `
6823
+ var _display = event.data._display;
6824
+ ${displayField}
6825
+ doAction({actionType: 'setValue', "args": {"value": {_display}},componentId: "${quickEditId}"});
6826
+ `
6827
+ }
6828
+ ]
6829
+ };
6830
+ return EventType;
6831
+ };
6832
+ switch (field.type) {
6833
+ //TODO:amis的picker组件直接点击选项x时不会触发change事件,待处理
6834
+ case "lookup":
6835
+ case "master_detail":
6836
+ if (field.multiple) {
6837
+ TempDisplayField = `
6838
+ _display["${field.name}"] = [];
6839
+ event.data.value.forEach(function(item,index){
6840
+ _display["${field.name}"].push(
6841
+ {
6842
+ "label": event.data.option[index].${quickEditSchema.body[0].labelField},
6843
+ "value": event.data.option[index]._id,
6844
+ "objectName": "${field.reference_to}"
6845
+ }
6846
+ )
6847
+ })
6848
+ `;
6849
+ } else {
6850
+ TempDisplayField = `
6851
+ _display["${field.name}"] = {
6852
+ "label": event.data.option.${quickEditSchema.body[0].labelField},
6853
+ "value": event.data._id,
6854
+ "objectName": "${field.reference_to}"
6855
+ }
6856
+ `;
6857
+ }
6858
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6859
+ break;
6860
+ case "select":
6861
+ TempDisplayField = `
6862
+ _display["${field.name}"] = event.data.selectedItems.label;
6863
+ `;
6864
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6865
+ break;
6866
+ case "percent":
6867
+ TempDisplayField = `
6868
+ _display["${field.name}"] = (event.data.value * 100).toFixed(${field.scale}) + '%';
6869
+ `;
6870
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6871
+ break;
6872
+ case "time":
6873
+ TempDisplayField = `
6874
+ _display["${field.name}"] = moment(event.data.value).utc().format('HH:mm');
6875
+ `;
6876
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6877
+ break;
6878
+ case "date":
6879
+ TempDisplayField = `
6880
+ _display["${field.name}"] = moment(event.data.value).utc().format('YYYY-MM-DD');
6881
+ `;
6882
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6883
+ break;
6884
+ case "datetime":
6885
+ TempDisplayField = `
6886
+ _display["${field.name}"] = moment(event.data.value).format('YYYY-MM-DD HH:mm');
6887
+ `;
6888
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6889
+ break;
6890
+ case "boolean":
6891
+ TempDisplayField = `
6892
+ _display["${field.name}"] = event.data.value?"√":"";
6893
+ `;
6894
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6895
+ break;
6896
+ case "number":
6897
+ case "currency":
6898
+ TempDisplayField = `
6899
+ _display["${field.name}"] = event.data.value?.toFixed(${field.scale});
6900
+ `;
6901
+ quickEditSchema.body[0].onEvent["change"] = quickEditOnEvent(TempDisplayField);
6902
+
6903
+ break;
6904
+ case "file":
6905
+ var removeDisplayField = ``;
6906
+ if (field.multiple) {
6907
+ TempDisplayField = `
6908
+ _display["${field.name}"].push({
6909
+ "name": event.data.result.name,
6910
+ "url": event.data.result.url,
6911
+ "type": event.data.item.type,
6912
+ "size": event.data.item.size
6913
+ });
6914
+ `;
6915
+ removeDisplayField = `
6916
+ _.remove(_display["${field.name}"], function(file){return file.url == event.data.item.url});
6917
+ `;
6918
+ } else {
6919
+ TempDisplayField = `
6920
+ _display["${field.name}"] = {
6921
+ "name": event.data.result.name,
6922
+ "url": event.data.result.url,
6923
+ "type": event.data.item.type,
6924
+ "size": event.data.item.size
6925
+ };
6926
+ `;
6927
+ removeDisplayField = `
6928
+ if(_display["${field.name}"].url == event.data.item.url){
6929
+ _display["${field.name}"] = {};
6930
+ }
6931
+ `;
6932
+ }
6933
+ quickEditSchema.body[0].onEvent["success"] = quickEditOnEvent(TempDisplayField);
6934
+ quickEditSchema.body[0].onEvent["remove"] = quickEditOnEvent(removeDisplayField);
6935
+ break;
6936
+ case "avatar":
6937
+ case "image":
6938
+ quickEditSchema.body[0].receiver.adaptor = `
6939
+ const { context } = api.body;
6940
+ var rootUrl = context.rootUrl + "/api/files/${field.type}s/";
6941
+ payload = {
6942
+ status: response.status == 200 ? 0 : response.status,
6943
+ msg: response.statusText,
6944
+ data: {
6945
+ value: rootUrl + payload._id,//为了实现图片crud的回显,需要将value从id改为url,当保存数据数据时,再在发送适配器内重新将id提取出来
6946
+ name: payload.original.name,
6947
+ url: rootUrl + payload._id,
6948
+ }
6949
+ }
6950
+ return payload;
6951
+ `;
6952
+ break;
6807
6953
  }
6808
- }
6809
- });
6810
-
6811
- // const refFields = _.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to});
6812
- // _.each(refFields, function(field){
6813
- // if(!_.includes(OMIT_FIELDS, field.name)){
6814
- // const valueField = field.reference_to_field || '_id';
6815
- // scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`
6816
- // if(field.multiple){
6817
- // scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`
6818
- // }else{
6819
- // scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`
6820
- // scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`
6821
- // }
6822
- // }
6823
- // })
6824
6954
 
6825
- return `
6826
- if(payload.data.data.length === 0){
6827
- return {
6828
- status: 2,
6829
- msg: "无法找到记录"
6830
- }
6831
- }
6832
- if(payload.data.data){
6833
- var data = payload.data.data[0];
6834
- var gridAndObjectFieldsName = ${JSON.stringify(gridAndObjectFieldsName)};
6835
- try{
6836
- ${scriptStr}
6837
- ${getScriptForAddUrlPrefixForImgFields(fields)}
6838
- ${getScriptForRewriteValueForFileFields(fields)}
6839
- }catch(e){
6840
- console.error(e)
6955
+ } else {
6956
+ quickEditSchema = false;
6841
6957
  }
6842
- // 原始记录
6843
- var record = _.cloneDeep(data);
6844
- try{
6845
- _.each(gridAndObjectFieldsName, function(name){
6846
- data[name] = data._display[name];
6847
- })
6848
- }catch(e){
6849
- console.error(e)
6958
+ //TODO:附件多选时会覆盖老数据,暂时禁用
6959
+ if(field.type == "file" && field.multiple){
6960
+ quickEditSchema = false;
6850
6961
  }
6851
- payload.data = data;
6852
- payload.data.__objectName = "${object.name}";
6853
- payload.data.__record = record;
6854
- window.postMessage(Object.assign({type: "record.loaded"}, {record: record}), "*")
6855
6962
  }
6856
- if(payload.errors){
6857
- payload.status = 2;
6858
- payload.msg = payload.errors[0].message;
6859
- }
6860
- return payload;
6861
- `
6963
+ return quickEditSchema;
6862
6964
  }
6863
6965
 
6864
- async function getReadonlyFormInitApi(object, recordId, fields, options){
6865
- return {
6866
- method: "post",
6867
- url: getApi$2()+"&recordId=${recordId}",
6868
- cache: API_CACHE,
6869
- // requestAdaptor: "console.log('getReadonlyFormInitApi requestAdaptor', api);return api;",
6870
- adaptor: getReadonlyFormAdaptor(object, fields),
6871
- data: await getFindOneQuery$1(object, recordId, fields, options),
6872
- headers: {
6873
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
6966
+ async function getTableColumns(fields, options){
6967
+ const columns = [{name: '_index',type: 'text', width: 32, placeholder: ""}];
6968
+ const allowEdit = options.permissions?.allowEdit && options.permissions?.modifyAllRecords && !options.isLookup && options.enable_inline_edit != false;
6969
+ for (const field of fields) {
6970
+ //增加quickEdit属性,实现快速编辑
6971
+ const quickEditSchema = allowEdit ? await getQuickEditSchema(field, options) : allowEdit;
6972
+ if((field.is_name || field.name === options.labelFieldName) && options.objectName === 'cms_files'){
6973
+ const previewFileScript = `
6974
+ var data = event.data;
6975
+ var file_name = data.versions ? data.name : "${field.label}";
6976
+ var file_id = data._id;
6977
+ SteedosUI.previewFile && SteedosUI.previewFile({file_name, file_id});
6978
+ `;
6979
+ columns.push({
6980
+ "type": "button",
6981
+ "label": `<%=data.versions ? data.name : "${field.label}"%>`,
6982
+ "className": "whitespace-nowrap",
6983
+ "level": "link",
6984
+ "quickEdit": quickEditSchema,
6985
+ "onEvent": {
6986
+ "click": {
6987
+ "actions": [
6988
+ {
6989
+ "args": {
6990
+ "api": {
6991
+ "url": "${context.rootUrl}/api/files/files/${versions[0]}?download=true",
6992
+ "method": "get",
6993
+ "headers": {
6994
+ "Authorization": "Bearer ${context.tenantId},${context.authToken}"
6995
+ }
6996
+ }
6997
+ },
6998
+ "actionType": "download",
6999
+ "expression": "!!!window?.nw?.require"//浏览器上直接下载
7000
+ },
7001
+ {
7002
+ "args": {},
7003
+ "actionType": "custom",
7004
+ "script": previewFileScript,
7005
+ "expression": "!!window?.nw?.require" //PC客户端预览附件
7006
+ }
7007
+ ]
7008
+ }
7009
+ }
7010
+ });
7011
+ }else if(field.type === 'toggle'){
7012
+ columns.push(Object.assign({}, {
7013
+ type: "switch",
7014
+ name: field.name,
7015
+ label: field.label,
7016
+ width: field.width,
7017
+ toggled: field.toggled,
7018
+ className:"whitespace-nowrap"
7019
+ }, field.amis, {name: field.name}));
7020
+ }else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7021
+ columns.push(Object.assign({}, {
7022
+ type: "switch",
7023
+ name: field.name,
7024
+ label: field.label,
7025
+ width: field.width,
7026
+ toggled: field.toggled,
7027
+ quickEdit: quickEditSchema,
7028
+ className:"whitespace-nowrap",
7029
+ ...getAmisFileReadonlySchema(field)
7030
+ }, field.amis, {name: field.name}));
7031
+ }
7032
+ else if(field.type === 'select'){
7033
+ const map = getSelectMap(field.options);
7034
+ columns.push(Object.assign({}, {
7035
+ type: "mapping",
7036
+ name: field.name,
7037
+ label: field.label,
7038
+ map: map,
7039
+ sortable: field.sortable,
7040
+ width: field.width,
7041
+ toggled: field.toggled,
7042
+ className:"whitespace-nowrap",
7043
+ quickEdit: quickEditSchema
7044
+ }, field.amis, {name: field.name}));
6874
7045
  }
7046
+ else {
7047
+ const tpl = await getFieldTpl(field, options);
7048
+ let type = 'text';
7049
+ if(tpl){
7050
+ type = 'tpl';
7051
+ }else if(field.type === 'html'){
7052
+ type = 'markdown';
7053
+ }else if(field.type === 'url' && field.show_as_qr){
7054
+ type = 'qr-code';
7055
+ }
7056
+ let className = "";
7057
+ if(field.type === 'textarea'){
7058
+ className = 'min-w-56';
7059
+ }
7060
+ if(field.wrap === false){
7061
+ className += " whitespace-nowrap";
7062
+ }
7063
+ if(!field.hidden && !field.extra){
7064
+ columns.push(Object.assign({}, {
7065
+ name: field.name,
7066
+ label: field.label,
7067
+ sortable: field.sortable,
7068
+ // searchable: field.searchable,
7069
+ width: field.width,
7070
+ type: type,
7071
+ tpl: tpl,
7072
+ toggled: field.toggled,
7073
+ className,
7074
+ quickEdit: quickEditSchema,
7075
+ options: field.type === 'html' ? {html: true} : null
7076
+ // toggled: true
7077
+ }, field.amis, {name: field.name}));
7078
+ }
7079
+ }
7080
+ }
7081
+ // columns.push(getOperation(fields));
7082
+ if(!_$1.some(columns, { name: options.labelFieldName })){
7083
+ const href = Router.getObjectDetailPath({
7084
+ ...options, formFactor: options.formFactor, appId: "${appId}", objectName: options.objectName || "${objectName}", recordId: `\${${options.idFieldName}}`
7085
+ });
7086
+ columns[0].type = "tpl";
7087
+ columns[0].tpl = `<a href="${href}">\${${columns[0].name}}</a>`;
6875
7088
  }
7089
+ return columns;
6876
7090
  }
6877
7091
 
6878
- /*
6879
- img/avatar字段值添加URL前缀使其在amis中正常显示图片。
6880
- */
6881
- function getScriptForAddUrlPrefixForImgFields(fields){
6882
- let imgFieldsKeys = [];
6883
- let imgFields = {};
6884
- fields.forEach((item)=>{
6885
- if(_$1.includes(['image','avatar'], item.type)){
6886
- imgFieldsKeys.push(item.name);
6887
- imgFields[item.name] = {
6888
- name: item.name,
6889
- type: item.type,
6890
- multiple: item.multiple
6891
- };
6892
- }
6893
- });
6894
- if(!imgFieldsKeys.length){
6895
- return '';
6896
- }
6897
- return `
6898
- // image字段值添加URL前缀
6899
- let imgFieldsKeys = ${JSON.stringify(imgFieldsKeys)};
6900
- let imgFields = ${JSON.stringify(imgFields)};
6901
- imgFieldsKeys.forEach((item)=>{
6902
- let imgFieldValue = data[item];
6903
- let imgFieldDisplayValue = data._display && data._display[item];
6904
- if(imgFieldValue && imgFieldValue.length){
6905
- let fieldProps = imgFields[item];
6906
- if(fieldProps.multiple){
6907
- if(imgFieldDisplayValue instanceof Array){
6908
- data[item] = imgFieldDisplayValue.map((i)=>{ return i.url });
6909
- }
6910
- }else{
6911
- data[item] = imgFieldDisplayValue && imgFieldDisplayValue.url;
6912
- }
6913
- }
6914
- })
6915
- `
6916
- }
7092
+ /**
7093
+ * 生成移动端列表每行显示的amis
7094
+ * @param {*} tpls 要显示的每个字段的tpl
7095
+ * @returns {
7096
+ "type": "wrapper",
7097
+ "body": [{
7098
+ "type": "tpl",
7099
+ "tpl": tpls[index].tpl,
7100
+ "className": "truncate"//左侧样式类
7101
+ },{
7102
+ "type": "tpl",
7103
+ "tpl": tpls[index + 1].tpl,
7104
+ "className": "truncate ml-2 flex flex-shrink-0"//右侧样式类
7105
+ }],
7106
+ "size": "none",
7107
+ "className": "flex items-center justify-between"//每行样式类
7108
+ }
7109
+ */
7110
+ function getMobileLines(tpls){
7111
+ let lines = [];
7112
+ let maxLineCount = 2;
7113
+ let lineChildren = [];
7114
+ let isNewLine = false;
7115
+ let isLeft = true;
7116
+ let lineChildrenClassName = "";
7117
+ let lineClassName = "flex items-center justify-between h-[20px]";
7118
+ tpls.forEach(function(item){
7119
+ if(isNewLine && lines.length < maxLineCount){
7120
+ lines.push({
7121
+ "type": "wrapper",
7122
+ "body": lineChildren,
7123
+ "size": "none",
7124
+ "className": lineClassName
7125
+ });
7126
+ lineChildren = [];
7127
+ }
7128
+ if(isLeft){
7129
+ // 左侧半行
7130
+ lineChildrenClassName = "steedos-listview-item-left truncate";
7131
+ if(item.field.is_wide){
7132
+ // 左侧全行样式可以单独写
7133
+ lineChildrenClassName = "steedos-listview-item-wide truncate";
7134
+ }
7135
+ if(lines.length === 0){
7136
+ // 第一个字段加粗黑色显示
7137
+ lineChildrenClassName += " font-bold text-gray-800";
7138
+ }
7139
+ }
7140
+ else {
7141
+ // 右侧半行
7142
+ lineChildrenClassName = "steedos-listview-item-right truncate ml-2 flex flex-shrink-0";
7143
+ }
7144
+ lineChildren.push({
7145
+ "type": "tpl",
7146
+ "tpl": item.tpl,
7147
+ "className": lineChildrenClassName
7148
+ });
6917
7149
 
6918
- /*
6919
- file字段值重写使其在amis中正常显示附件名、点击附件名下载文件。
6920
- */
6921
- function getScriptForRewriteValueForFileFields(fields){
6922
- let fileFieldsKeys = [];
6923
- let fileFields = {};
6924
- fields.forEach((item)=>{
6925
- if(item.type === 'file'){
6926
- fileFieldsKeys.push(item.name);
6927
- fileFields[item.name] = {
6928
- name: item.name,
6929
- multiple: item.multiple
6930
- };
7150
+ if(item.field.is_wide){
7151
+ // 宽字段占整行
7152
+ isLeft = true;
7153
+ isNewLine = true;
7154
+ }
7155
+ else {
7156
+ isLeft = !isLeft;
7157
+ isNewLine = isLeft;
6931
7158
  }
6932
7159
  });
6933
- if(!fileFieldsKeys.length){
6934
- return '';
7160
+
7161
+ if(lineChildren.length && lines.length < maxLineCount){
7162
+ lines.push({
7163
+ "type": "wrapper",
7164
+ "body": lineChildren,
7165
+ "size": "none",
7166
+ "className": lineClassName
7167
+ });
6935
7168
  }
6936
- return `
6937
- // file字段值重写以便编辑时正常显示附件名、点击附件名正常下载附件
6938
- let fileFieldsKeys = ${JSON.stringify(fileFieldsKeys)};
6939
- let fileFields = ${JSON.stringify(fileFields)};
6940
- fileFieldsKeys.forEach((item)=>{
6941
- let fileFieldValue = data[item];
6942
- let fileFieldDisplayValue = data._display && data._display[item];
6943
- if(fileFieldValue && fileFieldValue.length){
6944
- if(fileFields[item].multiple){
6945
- if(fileFieldDisplayValue instanceof Array){
6946
- data[item] = fileFieldDisplayValue.map((item, index)=>{
6947
- return {
6948
- value: fileFieldValue[index],
6949
- name: item.name,
6950
- url: item.url + "?download=true",
6951
- state: "uploaded"
6952
- }
6953
- });
6954
- }
6955
- }else{
6956
- data[item] = [{
6957
- value: fileFieldValue,
6958
- name: fileFieldDisplayValue.name,
6959
- url: fileFieldDisplayValue.url + "?download=true",
6960
- state: "uploaded"
6961
- }];
6962
- }
6963
- }
6964
- })
6965
- `
7169
+
7170
+ return lines;
6966
7171
  }
6967
7172
 
6968
- async function getEditFormInitApi(object, recordId, fields, options){
6969
- const data = await getFindOneQuery$1(object, recordId, fields);
6970
- data.recordId = "${recordId}";
6971
- data.objectName = "${objectName}";
6972
- data.uiSchema = "${uiSchema}";
6973
- data.global = "${global}";
6974
- data.context = "${context}";
6975
- data.defaultData = "${defaultData}";
6976
- data._master = "${_master}";
6977
-
6978
- return {
6979
- method: "post",
6980
- url: getApi$2() + '&objectName=${objectName}' ,
6981
- // sendOn: "!!this.recordId",
6982
- cache: API_CACHE,
6983
- requestAdaptor: `
6984
- // 所有不想在network请求中发送的数据都应该从data中分离出来,data变量只需要留下query才需要发送出去
6985
- var { recordId, objectName, uiSchema, global, context, ...data} = api.data;
6986
- if(!recordId){
6987
- // 新建则不请求任何数据
6988
- data.query = "{data:" + objectName + "(filters: " + JSON.stringify(["_id", "=", null]) + ", top: 1){_id}}";
7173
+ async function getMobileTableColumns(fields, options){
7174
+ const columns = [];
7175
+ let nameField = {};
7176
+ let tpls = [];
7177
+ for (const field of fields) {
7178
+ let tpl = "";
7179
+ if(field.is_name || field.name === options.labelFieldName){
7180
+ nameField = field;
7181
+ options.onlyDisplayLabel = true;
7182
+ tpl = await getFieldTpl(field, options);
7183
+ }
7184
+ else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7185
+ // 图片和附件类型字段暂时显示为附件名称,后续需要再优化
7186
+ tpl = `\${_display.${field.name}.name}`;
7187
+ }
7188
+ else {
7189
+ if(field.type === 'lookup' || field.type === 'master_detail'){
7190
+ options.onlyDisplayLabel = true;
6989
7191
  }
6990
- api.data = data;
6991
- ${options.initApiRequestAdaptor || ''}
6992
- return api;
6993
- `,
6994
- adaptor: `
6995
- const recordId = api.body.recordId;
6996
- let initialValues={};
6997
- if(recordId && payload.data.data){
6998
- var data = payload.data.data[0];
6999
- const dataKeys = _.keys(data);
7000
- const uiSchema = api.body.uiSchema;
7001
- const fieldKeys = uiSchema && _.keys(uiSchema.fields);
7192
+ tpl = await getFieldTpl(field, options);
7193
+ }
7194
+ if(!tpl){
7195
+ tpl = `\${${field.name}}`;
7196
+ }
7197
+ if(!field.hidden && !field.extra){
7198
+ tpls.push({ field, tpl });
7199
+ }
7200
+ }
7201
+ const url = getNameTplUrl(nameField, options);
7002
7202
 
7003
- if(data){
7004
- ${getScriptForAddUrlPrefixForImgFields(fields)}
7005
- ${getScriptForRewriteValueForFileFields(fields)}
7203
+ const columnLines = getMobileLines(tpls);
7006
7204
 
7007
- _.each(dataKeys, function(key){
7008
- if(fieldKeys.indexOf(key)<0){
7009
- delete data[key];
7010
- }
7011
- })
7012
-
7013
- //初始化接口返回的字段移除字段值为null的字段
7014
- for (key in data){
7015
- if(data[key] === null){
7016
- delete data[key];
7017
- }
7205
+
7206
+ let column = {
7207
+ name: nameField.name,
7208
+ label: nameField.label,
7209
+ sortable: nameField.sortable,
7210
+ type: "button",
7211
+ level: "link",
7212
+ actionType: "link",
7213
+ link: url,
7214
+ innerClassName: "steedos-listview-item block text-gray-500",
7215
+ body: {
7216
+ "type": "wrapper",
7217
+ "body": columnLines,
7218
+ "size": "none",
7219
+ "className": "p-1"
7220
+ }
7221
+ };
7222
+
7223
+ if(options.objectName === 'cms_files'){
7224
+ if(window.Meteor?.isCordova){
7225
+ column = {
7226
+ ...column,
7227
+ actionType: "",
7228
+ link: "",
7229
+ onEvent: {
7230
+ "click": {
7231
+ "actions": [
7232
+ {
7233
+ "script": `
7234
+ let cms_url = "/api/files/files/"+event.data.versions[0]+"?download=true"
7235
+ Steedos.cordovaDownload(encodeURI(Steedos.absoluteUrl(cms_url)), event.data.name);
7236
+ `,
7237
+ "actionType": "custom"
7238
+ }
7239
+ ],
7240
+ "weight": 0
7018
7241
  }
7019
- };
7020
- initialValues = data;
7021
- }
7022
- else{
7023
- var uiSchema = api.body.uiSchema;
7024
- var defaultData = api.body.defaultData;
7025
- var defaultValues = {};
7026
- _.each(uiSchema?.fields, function(field){
7027
- var value = SteedosUI.getFieldDefaultValue(field, api.body.global);
7028
- if(value){
7029
- defaultValues[field.name] = value;
7030
- }
7031
- });
7032
- if(defaultData && _.isObject(defaultData) && !_.isArray(defaultData)){
7033
- defaultValues = Object.assign({}, defaultValues, defaultData)
7034
7242
  }
7035
- if(uiSchema.form){
7036
- try{
7037
- var objectFormConfig = JSON.parse(uiSchema.form);
7038
- var formInitialValuesFun = objectFormConfig.initialValues;
7039
- if(formInitialValuesFun){
7040
- formInitialValuesFun = new Function("return " + formInitialValuesFun)();
7041
- }
7042
- if(typeof formInitialValuesFun === "function"){
7043
- initialValues = formInitialValuesFun.apply({doc: defaultValues || {} , global: api.body.global, master: api.body._master })
7044
- }
7045
- }
7046
- catch(ex){
7047
- console.warn(ex);
7243
+ };
7244
+ }else {
7245
+ column = {
7246
+ ...column,
7247
+ actionType: "",
7248
+ link: "",
7249
+ onEvent: {
7250
+ "click": {
7251
+ "actions": [
7252
+ {
7253
+ "args": {
7254
+ "api": {
7255
+ "url": url,
7256
+ "method": "get",
7257
+ "headers": {
7258
+ "Authorization": "Bearer ${context.tenantId},${context.authToken}"
7259
+ }
7260
+ }
7261
+ },
7262
+ "actionType": "download"
7263
+ }
7264
+ ],
7265
+ "weight": 0
7048
7266
  }
7049
7267
  }
7050
- if(_.isObject(initialValues)){
7051
- // uiSchema.form.initialValues为函数且执行后为json,则优先取initialValues中的默认值
7052
- initialValues = Object.assign({}, defaultValues, initialValues);
7053
- }
7054
- else{
7055
- initialValues = defaultValues;
7056
- }
7057
- }
7058
- // data下的变量需要在保存接口(getSaveApi)中被删除。
7059
- payload.data = {
7060
- ...initialValues
7061
- }
7062
- ${options.initApiAdaptor || ''}
7063
- return payload;
7064
- `,
7065
- responseData: {
7066
- initialValues: "$$",
7067
- editFormInited: true
7068
- },
7069
- data: data,
7070
- headers: {
7071
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7268
+ };
7072
7269
  }
7270
+
7073
7271
  }
7074
- }
7075
7272
 
7273
+ columns.push(column);
7274
+
7076
7275
 
7077
- function getSaveApi(object, recordId, fields, options){
7078
- return {
7079
- method: 'post',
7080
- url: getApi$2(),
7081
- data: getSaveQuery(object, recordId),
7082
- requestAdaptor: getSaveRequestAdaptor(fields, options),
7083
- responseData: {
7084
- "recordId": "${record._id}"
7085
- },
7086
- adaptor: `
7087
- if(payload.errors){
7088
- payload.status = 2;
7089
- payload.msg = window.t ? window.t(payload.errors[0].message) : payload.errors[0].message;
7090
- }
7091
- ${options.apiAdaptor || ''}
7092
- return payload;
7093
- `,
7094
- headers: {
7095
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7096
- }
7097
- }
7276
+ return columns;
7098
7277
  }
7099
7278
 
7100
- function getBatchDelete(objectName){
7279
+ function getDefaultParams(options){
7101
7280
  return {
7102
- method: 'post',
7103
- url: getApi$2(),
7104
- requestAdaptor: `
7105
- var ids = api.data.ids.split(",");
7106
- var deleteArray = [];
7107
- ids.forEach((id,index)=>{
7108
- deleteArray.push(\`delete__\${index}:${objectName}__delete(id: "\${id}")\`);
7109
- })
7110
- api.data = {query: \`mutation{\${deleteArray.join(',')}}\`};
7111
- return api;
7112
- `,
7113
- data: {
7114
- ids: `\${ids}`
7115
- },
7116
- headers: {
7117
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
7118
- }
7281
+ perPage: options.top || options.perPage || config.listView.perPage
7119
7282
  }
7120
7283
  }
7121
7284
 
7122
- /*
7123
- * @Author: baozhoutao@steedos.com
7124
- * @Date: 2022-05-26 16:02:08
7125
- * @LastEditors: baozhoutao@steedos.com
7126
- * @LastEditTime: 2023-03-13 16:01:40
7127
- * @Description:
7128
- */
7129
-
7130
- const getFieldSchemaArray = (formFields)=>{
7131
- let fieldSchemaArray = [];
7132
- fieldSchemaArray.length = 0;
7285
+ function getButtonVisibleOn(button){
7286
+ let visible= button.visible;
7133
7287
 
7134
- _$1.forEach(formFields, (field) => {
7135
- if (!field.group || field.group == 'null' || field.group == '-')
7136
- field.group = '通用';
7137
- const fieldName = field.name;
7138
- let isObjectField = /\w+\.\w+/.test(fieldName);
7139
- if (field.type == 'grid' || field.type == 'object') {
7140
- // field.group = field.label
7141
- field.is_wide = true;
7142
- }
7143
-
7144
- if (!isObjectField){
7145
- if(!field.hidden){
7146
- fieldSchemaArray.push(Object.assign({name: fieldName}, field, {permission: {allowEdit: true}}));
7147
- }
7288
+ if(button._visible){
7289
+ visible = button._visible;
7148
7290
  }
7149
- });
7150
- return fieldSchemaArray;
7151
- };
7152
-
7153
- const getSection = async (formFields, permissionFields, fieldSchemaArray, sectionName, ctx) => {
7154
- const sectionFields = _$1.filter(fieldSchemaArray, { 'group': sectionName });
7155
- if(sectionFields.length == _$1.filter(sectionFields, ['hidden', true]).length){
7156
- return ;
7157
- }
7158
-
7159
- const fieldSetBody = [];
7160
-
7161
- for (const perField of sectionFields) {
7162
- let field = perField;
7163
- if(perField.type === 'grid'){
7164
- field = await getGridFieldSubFields(perField, formFields);
7165
- // console.log(`perField.type grid ===> field`, field)
7166
- }else if(perField.type === 'object'){
7167
- field = await getObjectFieldSubFields(perField, formFields);
7168
- // console.log(`perField.type object ===> field`, field)
7169
- }
7170
- if(field.name.indexOf(".") < 0){
7171
- ctx.__formFields = formFields;
7172
- const amisField = await convertSFieldToAmisField(field, field.readonly, ctx);
7173
- // console.log(`${field.name} amisField`, field, amisField)
7174
- if(amisField){
7175
- fieldSetBody.push(amisField);
7176
- }
7177
- }
7178
- }
7179
-
7180
- // fieldSet 已支持显隐控制
7181
- const sectionFieldsVisibleOn = _$1.map(_$1.compact(_$1.map(fieldSetBody, 'visibleOn')) , (visibleOn)=>{
7182
- return visibleOn;
7183
- });
7184
- const section = {
7185
- "type": "fieldSet",
7186
- "title": sectionName,
7187
- "collapsable": true,
7188
- "body": fieldSetBody,
7189
- };
7190
- if(sectionFieldsVisibleOn.length > 0 && fieldSetBody.length === sectionFieldsVisibleOn.length){
7191
- section.visibleOn = `${sectionFieldsVisibleOn.join(" || ")}`;
7192
- }
7193
- return section
7194
- };
7195
7291
 
7196
- const getSections = async (permissionFields, formFields, ctx) => {
7197
- const fieldSchemaArray = getFieldSchemaArray(formFields);
7198
- const _sections = _$1.groupBy(fieldSchemaArray, 'group');
7199
- const sections = [];
7200
- var sectionHeaderVisibleOn=[];
7201
- for (const key in _sections) {
7202
- const section = await getSection(formFields, permissionFields, fieldSchemaArray, key, ctx);
7203
- if(section.body.length > 0){
7204
- if(section.visibleOn){
7205
- sectionHeaderVisibleOn.push(section.visibleOn);
7206
- }
7207
- sections.push(section);
7292
+ if(isBoolean(visible)){
7293
+ visible = visible.toString();
7208
7294
  }
7209
- }
7210
- /*
7211
- 为了实现只有一个分组时隐藏该分组标题,需要分三种情况(分组如果没有visibleon属性就代表一定显示,有visibleon需要进行判断)
7212
- 1.所有分组中只有一个分组没有visibleon,还需要判断其他有visibleon的分组是否显示,只有其他都不显示时,才需要隐藏标题;反之,有任何一个显示,就不需要隐藏标题
7213
- 2.所有分组都有visibleon
7214
- 2.1 当前分组为隐藏时,标题就设置为隐藏
7215
- 2.2 当前分组为显示时,其他分组只要有一个是显示,就显示该分组标题
7216
- 2.3 当前分组为显示时,其他分组都隐藏,就隐藏该分组标题
7217
- 3.所有分组中有两个以上的分组没有visibleon(这种情况不用处理)
7218
- */
7219
- if(ctx.mode == "edit"){
7220
- if (sections.length - sectionHeaderVisibleOn.length == 1) {
7221
- sections.forEach((section) => {
7222
- section.headingClassName = {
7223
- "hidden": `!(${sectionHeaderVisibleOn.join(" || ") || 'false'})`
7224
- };
7225
- });
7226
- } else if (sections.length == sectionHeaderVisibleOn.length) {
7227
- sections.forEach((section, index) => {
7228
- var tempSectionHeaderVisibleOn = sectionHeaderVisibleOn.slice();
7229
- tempSectionHeaderVisibleOn.splice(index, 1);
7230
- section.headingClassName = {
7231
- "hidden": `!((${tempSectionHeaderVisibleOn.join(" || ") || 'false'}) && ${sectionHeaderVisibleOn[index]})`
7232
- };
7233
- });
7234
- }
7235
- }
7236
-
7237
- return sections;
7238
- };
7239
7295
 
7240
- /*
7241
- * @Author: baozhoutao@steedos.com
7242
- * @Date: 2022-07-07 11:02:29
7243
- * @LastEditors: baozhoutao@steedos.com
7244
- * @LastEditTime: 2023-03-07 17:19:34
7245
- * @Description:
7246
- */
7296
+ if(visible){
7297
+ // if(visible.indexOf("Meteor.") > 0 || visible.indexOf("Creator.") > 0 || visible.indexOf("Session.") > 0){
7298
+ // console.warn('无效的visible', visible)
7299
+ // return 'false';
7300
+ // }
7301
+ if(visible.trim().startsWith('function')){
7302
+ return `${visible}(objectName, typeof _id === 'undefined' ? null: _id, typeof record === 'undefined' ? (typeof recordPermissions === 'undefined' ? {} : recordPermissions) : record.recordPermissions, data)`
7303
+ }
7304
+ return visible;
7305
+ }
7247
7306
 
7248
- async function getFormBody(permissionFields, formFields, ctx){
7249
- return await getSections(permissionFields, formFields, ctx);
7307
+ if(button.type === 'amis_button'){
7308
+ const amisSchema = button.amis_schema;
7309
+ if(amisSchema && amisSchema.body && amisSchema.body.length > 0){
7310
+ const btn1 = amisSchema.body[0];
7311
+ return btn1.visibleOn
7312
+ }
7313
+ }
7250
7314
  }
7251
7315
 
7252
- // lodash的defaultsDeep函数有bug,无法正确合并值为数值的节点,重写修正该函数
7253
- // 源码出处:https://github.com/nodeutils/defaults-deep
7254
- const defaultsDeep = (...args)=>{
7255
- let output = {};
7256
- toArray(args).reverse().forEach(item=> {
7257
- mergeWith(output, item, (objectValue, sourceValue) => {
7258
- return isArray(sourceValue) ? sourceValue : undefined;
7316
+ async function getTableOperation(ctx){
7317
+ const buttons = ctx.buttons;
7318
+ const operationButtons = [];
7319
+ each(buttons, (button)=>{
7320
+ if(isBoolean(button.visible)){
7321
+ button.visible = button.visible.toString();
7322
+ }
7323
+ // operationButtons.push({
7324
+ // type: 'button',
7325
+ // label: button.label,
7326
+ // visibleOn: button.visible ? `${button.visible}` : (button._visible ? `${button._visible}` : null),
7327
+ // onEvent: {
7328
+ // click: {
7329
+ // actions: []
7330
+ // }
7331
+ // }
7332
+ // })
7333
+
7334
+ operationButtons.push({
7335
+ type: 'steedos-object-button',
7336
+ name: button.name,
7337
+ objectName: button.objectName,
7338
+ visibleOn: getButtonVisibleOn(button),
7339
+ className: 'antd-Button--default'
7259
7340
  });
7260
7341
  });
7261
- return output;
7262
- };
7263
-
7264
- function getBulkActions(objectSchema){
7265
- return [
7266
- {
7267
- "type": "button",
7268
- "level": "danger",
7269
- "label": "批量删除",
7270
- "actionType": "ajax",
7271
- "confirmText": "确定要删除吗",
7272
- "className": "hidden",
7273
- "id": "batchDelete",
7274
- "api": getBatchDelete(objectSchema.name),
7275
- }
7276
- // {
7277
- // "label": "批量修改",
7278
- // "actionType": "dialog",
7279
- // "dialog": {
7280
- // "title": "批量编辑",
7281
- // "name": "sample-bulk-edit",
7282
- // "body": {
7283
- // "type": "form",
7284
- // "api": "https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/sample/bulkUpdate2",
7285
- // "controls": [
7286
- // {
7287
- // "type": "hidden",
7288
- // "name": "ids"
7289
- // },
7290
- // {
7291
- // "type": "text",
7292
- // "name": "name",
7293
- // "label": "Name"
7294
- // }
7295
- // ]
7296
- // }
7297
- // }
7298
- // }
7299
- ]
7342
+ if(operationButtons.length < 1){
7343
+ return ;
7344
+ }
7345
+ return {
7346
+ type: 'operation',
7347
+ label: '操作',
7348
+ fixed: 'right',
7349
+ labelClassName: 'text-center',
7350
+ className: 'text-center steedos-listview-operation w-20',
7351
+ buttons: [
7352
+ {
7353
+ "type": "steedos-dropdown-button",
7354
+ "label": "xxx",
7355
+ "buttons": operationButtons,
7356
+ "placement": "bottomRight",
7357
+ "overlayClassName": "shadow !min-w-[160px]",
7358
+ "trigger": ["click"],
7359
+ "id": "u:c2140a365019",
7360
+ onOpenApi: {
7361
+ url: `\${context.rootUrl}/service/api/@\${objectName}/recordPermissions/\${_id}`,
7362
+ method: "get",
7363
+ data: {
7364
+ $: "$$",
7365
+ objectName: "${objectName}",
7366
+ listViewId: "${listViewId}",
7367
+ appId: "${appId}",
7368
+ formFactor: "${formFactor}",
7369
+ context: `\${context}`
7370
+ },
7371
+ headers: {
7372
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7373
+ },
7374
+ adaptor: `
7375
+ payload = {
7376
+ record: {
7377
+ recordPermissions: payload
7378
+ }
7379
+ };
7380
+ return payload;
7381
+ `,
7382
+ }
7383
+ }
7384
+ ]
7385
+ }
7300
7386
  }
7301
7387
 
7302
- async function getObjectCRUD(objectSchema, fields, options){
7303
- // console.time('getObjectCRUD');
7304
- const { top, perPage, showDisplayAs = false, displayAs, crudClassName = "" } = options;
7305
- const nonpaged = objectSchema.paging && objectSchema.paging.enabled === false;
7306
- const isTreeObject = objectSchema.enable_tree;
7307
- const bulkActions = getBulkActions(objectSchema);
7308
- const bodyProps = {
7309
- // toolbar: getToolbar(),
7310
- // headerToolbar: getObjectHeaderToolbar(objectSchema, options.formFactor, {showDisplayAs}),
7311
- headerToolbarClassName: "px-4 py-2 border-gray-300 bg-gray-100 border-solid border-b",
7312
- footerToolbar: getObjectFooterToolbar(objectSchema, options.formFactor, {
7313
- disableStatistics: options.queryCount === false
7314
- }),
7315
- filter: options.filterVisible !== false && await getObjectFilter(objectSchema, fields, options),
7316
- };
7317
- if(options.formFactor !== 'SMALL' || ["split"].indexOf(options.displayAs) == -1){
7318
- Object.assign(bodyProps, {
7319
- bulkActions: options.bulkActions != false ? bulkActions : false
7320
- });
7388
+ async function getTableSchema$1(fields, options){
7389
+ if(!options){
7390
+ options = {};
7321
7391
  }
7322
- // yml里配置的 不分页和enable_tree:true 优先级最高,组件中输入的top次之。
7323
- options.queryCount = true;
7324
- if(nonpaged || isTreeObject){
7325
- options.top = 50000;
7326
- bodyProps.footerToolbar = [];
7327
- options.queryCount = true; // 禁止翻页的时候, 需要查找总数
7328
- }else if(top){
7329
- bodyProps.footerToolbar = [];
7330
- if(options.isRelated){
7331
- options.queryCount = true;
7332
- }else {
7333
- options.queryCount = false;
7334
- }
7392
+ let columns = [];
7393
+ if(options.formFactor === 'SMALL' || ["split"].indexOf(options.displayAs) > -1){
7394
+ columns = await getMobileTableColumns(fields, options);
7335
7395
  }
7336
- // console.log(`getObjectHeaderToolbar====2===>`, options.filterVisible)
7337
- bodyProps.headerToolbar = getObjectHeaderToolbar(objectSchema, options.formFactor, {
7338
- showDisplayAs,
7339
- hiddenCount: options.queryCount === false,
7340
- headerToolbarItems: options.headerToolbarItems,
7341
- filterVisible: options.filterVisible
7342
- });
7396
+ else {
7397
+ columns = await getTableColumns(fields, options);
7398
+ columns.push(await getTableOperation(options));
7399
+ }
7400
+ return {
7401
+ mode: "table",
7402
+ name: "thelist",
7403
+ headerToolbarClassName: "py-2 px-2 border-gray-300 bg-gray-100 border-solid border-b",
7404
+ className: "",
7405
+ draggable: false,
7406
+ defaultParams: getDefaultParams(options),
7407
+ columns: columns,
7408
+ syncLocation: false,
7409
+ keepItemSelectionOnPageChange: true,
7410
+ checkOnItemClick: false,
7411
+ labelTpl: `\${${options.labelFieldName}}`,
7412
+ autoFillHeight: false, // 自动高度效果不理想,先关闭
7413
+ columnsTogglable: false,
7414
+ }
7415
+ }
7343
7416
 
7344
7417
 
7345
- let body = null;
7346
- const id = `listview_${objectSchema.name}`;
7347
- if(options.formFactor === 'SMALL' && false){
7348
- delete bodyProps.bulkActions;
7349
- delete bodyProps.headerToolbar;
7350
- delete bodyProps.footerToolbar;
7351
- const card = await getCardSchema(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: objectSchema.NAME_FIELD_KEY || 'name'}, options, {actions: false}));
7352
- body = Object.assign({}, card , {
7353
- type: 'crud',
7354
- primaryField: '_id',
7355
- id: id,
7356
- name: id,
7357
- keepItemSelectionOnPageChange: false,
7358
- api: await getTableApi(objectSchema, fields, options),
7359
- hiddenOn: options.tableHiddenOn,
7360
- },
7361
- bodyProps
7362
- );
7363
- }else {
7364
- let labelFieldName = objectSchema.NAME_FIELD_KEY || 'name';
7365
- // organizations 对象的历史遗留问题, fullname 被标记为了 名称字段. 在此处特殊处理.
7366
- if(objectSchema.name === 'organizations'){
7367
- labelFieldName = 'name';
7368
- }
7369
- const table = await getTableSchema$1(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: labelFieldName}, options));
7370
- delete table.mode;
7371
7418
 
7372
- body = Object.assign({}, table, {
7373
- type: 'crud',
7374
- primaryField: '_id',
7375
- affixHeader: false,
7376
- id: id,
7377
- name: id,
7378
- keepItemSelectionOnPageChange: true,
7379
- api: await getTableApi(objectSchema, fields, options),
7380
- hiddenOn: options.tableHiddenOn,
7381
- autoFillHeight: options.isRelated ? false : true,
7382
- className: `flex-auto ${crudClassName || ""}`,
7383
- bodyClassName: "bg-white",
7384
- crudClassName: crudClassName,
7385
- },
7386
- bodyProps,
7387
- );
7419
+ /**
7420
+ *
7421
+ * @param {*} mainObject
7422
+ * @param {*} fields
7423
+ * @param {*} options = {filter: listview 过滤条件, ...}
7424
+ * @returns
7425
+ */
7426
+ async function getTableApi(mainObject, fields, options){
7427
+ const searchableFields = [];
7428
+ let { filter, filtersFunction, sort, top, setDataToComponentId = '' } = options;
7429
+
7430
+ if(_$1.isArray(filter)){
7431
+ filter = _$1.map(filter, function(item){
7432
+ if(item.operation){
7433
+ return [item.field, item.operation, item.value];
7434
+ }else {
7435
+ return item
7436
+ }
7437
+ });
7388
7438
  }
7439
+ if(!filter){
7440
+ filter = [];
7441
+ }
7442
+ let baseFilters = null;
7443
+ if(filter){
7444
+ baseFilters = filter;
7445
+ }
7446
+ _$1.each(fields,function(field){
7447
+ if(field.searchable){
7448
+ searchableFields.push(field.name);
7449
+ }
7450
+ });
7389
7451
 
7390
- const defaults = options.defaults;
7391
- if (defaults) {
7392
- const listSchema = defaults.listSchema || {};
7393
- body = defaultsDeep({}, listSchema, body);
7394
- const headerSchema = defaults.headerSchema;
7395
- const footerSchema = defaults.footerSchema;
7396
- if (headerSchema || footerSchema) {
7397
- let wrappedBody = [body];
7398
- if (headerSchema) {
7399
- if(___default.isArray(headerSchema)){
7400
- wrappedBody = ___default.union(headerSchema,wrappedBody);
7401
- }
7402
- else {
7403
- wrappedBody.unshift(headerSchema);
7404
- }
7452
+ const fileFields = {};
7453
+ const fileFieldsKeys = [];
7454
+ // 含有optionsFunction属性, 无reference_to属性的lookup字段
7455
+ const lookupFields = {};
7456
+ fields.forEach((item)=>{
7457
+ if(_$1.includes(['image','avatar','file'], item.type)){
7458
+ fileFieldsKeys.push(item.name);
7459
+ fileFields[item.name] = {
7460
+ name: item.name,
7461
+ type: item.type,
7462
+ multiple: item.multiple
7463
+ };
7405
7464
  }
7406
- if (footerSchema) {
7407
- if(___default.isArray(footerSchema)){
7408
- wrappedBody = ___default.union(wrappedBody,footerSchema);
7409
- }
7410
- else {
7411
- wrappedBody.push(footerSchema);
7412
- }
7465
+ if(_$1.includes(['lookup'], item.type) && !item.reference_to ){
7466
+ lookupFields[item.name] = item;
7413
7467
  }
7414
- body = wrappedBody;
7415
- }
7468
+ });
7469
+
7470
+ let valueField = mainObject.key_field || '_id';
7471
+ const api = await getApi(mainObject, null, fields, {count: options.queryCount, alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"`});
7472
+
7473
+ if(options.isRelated){
7474
+ api.url += "&recordId=${_master.recordId}";
7416
7475
  }
7417
- // console.timeEnd('getObjectCRUD');
7418
- // TODO: data应该只留loaded,其他属性都改为从上层传递下来
7419
- return {
7420
- type: 'service',
7421
- className: '',
7422
- id: `service_${id}`,
7423
- name: `page`,
7424
- data: {
7425
- objectName: objectSchema.name,
7426
- // _id: null,
7427
- recordPermissions: objectSchema.permissions,
7428
- uiSchema: objectSchema,
7429
- // loaded: false //crud接收适配器中设置为true,否则就是刷新浏览器第一次加载
7430
- },
7431
- body: body
7432
- }
7433
- }
7434
7476
 
7435
- const getGlobalData = (mode)=>{
7436
- const user = getSteedosAuth();
7437
- return {mode: mode, user: user, spaceId: user.spaceId, userId: user.userId}
7438
- };
7477
+ api.data.$term = "$term";
7478
+ api.data.term = "$term";
7479
+ api.data.$self = "$$";
7480
+ api.data.self = "$$";
7481
+ api.data.filter = "$filter";
7482
+ api.data.loaded = "${loaded}";
7483
+ api.data.listViewId = "${listViewId}";
7484
+ api.data.listName = "${listName}";
7485
+ api.requestAdaptor = `
7486
+ // selfData 中的数据由 CRUD 控制. selfData中,只能获取到 CRUD 给定的data. 无法从数据链中获取数据.
7487
+ let selfData = JSON.parse(JSON.stringify(api.data.$self));
7488
+ // 保留一份初始data,以供自定义发送适配器中获取原始数据。
7489
+ const data = _.cloneDeep(api.data);
7490
+ try{
7491
+ // TODO: 不应该直接在这里取localStorage,应该从外面传入
7492
+ const listViewId = api.data.listViewId;
7493
+ const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
7494
+ let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
7495
+ if(localListViewProps){
7496
+ localListViewProps = JSON.parse(localListViewProps);
7497
+ selfData = Object.assign({}, localListViewProps, selfData);
7498
+ if(!api.data.filter){
7499
+ api.data.filter = localListViewProps.filter;
7500
+ }
7501
+ if(!api.data.loaded){
7502
+ // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
7503
+ // 所以会把localSearchableFilter中已经存过的页码覆盖
7504
+ // 如果是第一次加载组件始终让翻页页码从本地存储中取值
7505
+ let formFactor = "${options.formFactor}";
7506
+ // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
7507
+ api.data.pageNo = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
7508
+ }
7509
+ }
7510
+ }
7511
+ catch(ex){
7512
+ console.error("本地存储中crud参数解析异常:", ex);
7513
+ }
7514
+ ${baseFilters ? `var systemFilters = ${JSON.stringify(baseFilters)};` : 'var systemFilters = [];'}
7515
+ var _ids = []
7516
+ const filtersFunction = ${filtersFunction};
7517
+ if(filtersFunction){
7518
+ const _filters = filtersFunction(systemFilters, api.data.$self);
7519
+ if(api.data.listName == "recent"){
7520
+ _ids = _filters[2]
7521
+ }
7522
+ if(_filters && _filters.length > 0){
7523
+ if(_.isEmpty(systemFilters)){
7524
+ systemFilters = _filters || [];
7525
+ }else{
7526
+ systemFilters = [systemFilters, 'and', _filters];
7527
+ }
7528
+ }
7529
+ }
7530
+ let userFilters =[];
7531
+
7532
+ if(_.isEmpty(systemFilters)){
7533
+ systemFilters = api.data.filter || [];
7534
+ }else{
7535
+ if(!_.isEmpty(api.data.filter)){
7536
+ systemFilters = [systemFilters, 'and', api.data.filter];
7537
+ }
7538
+ }
7539
+ var pageSize = api.data.pageSize || 10;
7540
+ var pageNo = api.data.pageNo || 1;
7541
+ var skip = (pageNo - 1) * pageSize;
7542
+ var orderBy = api.data.orderBy || '';
7543
+ var orderDir = api.data.orderDir || '';
7544
+ var sort = orderBy + ' ' + orderDir;
7545
+ sort = orderBy ? sort : "${sort || ''}";
7546
+ var allowSearchFields = ${JSON.stringify(searchableFields)};
7547
+ if(api.data.$term){
7548
+ userFilters = [["name", "contains", "'+ api.data.$term +'"]];
7549
+ }else if(selfData.op === 'loadOptions' && selfData.value){
7550
+ userFilters = [["${valueField.name}", "=", selfData.value]];
7551
+ }
7552
+
7553
+ var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
7439
7554
 
7440
- const getFormFields = (objectSchema, formProps)=>{
7441
- /**
7442
- * fieldsExtend: 重写字段定义
7443
- * fields: 包含的字段
7444
- * excludedFields: 排除的字段
7445
- */
7446
- const { fieldsExtend, fields: includedFields, excludedFields } = formProps;
7447
-
7448
- let fields = {};
7449
- // 以uiSchema fields 为基础, 遍历字段, 并更新字段定义
7450
- ___default.forEach(objectSchema.fields, (field, fieldName)=>{
7451
- if(!lodash.has(field, "name")){
7452
- field.name = fieldName;
7453
- }
7454
- if(fieldsExtend && fieldsExtend[fieldName]){
7455
- fields[field.name] = Object.assign({}, field, fieldsExtend[fieldName], {name: field.name});
7456
- }else {
7457
- fields[field.name] = field;
7458
- }
7459
- });
7555
+ if(searchableFilter.length > 0){
7556
+ if(userFilters.length > 0 ){
7557
+ userFilters = [userFilters, 'and', searchableFilter];
7558
+ }else{
7559
+ userFilters = searchableFilter;
7560
+ }
7561
+ }
7460
7562
 
7461
- if(!___default.isEmpty(includedFields) && ___default.isArray(includedFields)){
7462
- const includedFieldsMap = {};
7463
- ___default.each(includedFields, (fName, index)=>{
7464
- if(fields[fName]){
7465
- includedFieldsMap[fName] = Object.assign({}, fields[fName], {sort_no: index});
7466
- }
7467
- });
7468
- fields = includedFieldsMap;
7469
- }
7563
+ if(allowSearchFields){
7564
+ allowSearchFields.forEach(function(key){
7565
+ const keyValue = selfData[key];
7566
+ if(_.isString(keyValue)){
7567
+ userFilters.push([key, "contains", keyValue]);
7568
+ }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
7569
+ userFilters.push([key, "=", keyValue]);
7570
+ }
7571
+ })
7572
+ }
7470
7573
 
7471
- if(!___default.isEmpty(excludedFields) && ___default.isArray(excludedFields)){
7472
- ___default.each(excludedFields, (fName)=>{
7473
- delete fields[fName];
7474
- });
7475
- }
7574
+ if(selfData.__keywords && allowSearchFields){
7575
+ const keywordsFilters = [];
7576
+ allowSearchFields.forEach(function(key, index){
7577
+ const keyValue = selfData.__keywords;
7578
+ if(keyValue){
7579
+ keywordsFilters.push([key, "contains", keyValue]);
7580
+ if(index < allowSearchFields.length - 1){
7581
+ keywordsFilters.push('or');
7582
+ }
7583
+ }
7584
+ })
7585
+ userFilters.push(keywordsFilters);
7586
+ };
7476
7587
 
7477
- return lodash.sortBy(___default.values(fields), "sort_no");
7478
- };
7588
+ let filters = [];
7479
7589
 
7480
- async function getObjectForm(objectSchema, ctx){
7481
- const { recordId, formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, tabId, appId, defaults } = ctx;
7482
- const fields = ___default.values(objectSchema.fields);
7483
- const formFields = getFormFields(objectSchema, ctx);
7484
- const formSchema = defaults && defaults.formSchema || {};
7485
- if(___default.has(formSchema, 'className')){
7486
- formSchema.className = 'steedos-amis-form';
7487
- }
7488
- const amisSchema = {
7489
- type: 'service',
7490
- className: 'p-0',
7491
- name: `page_edit_${recordId}`,
7492
- api: await getEditFormInitApi(objectSchema, recordId, fields, ctx),
7493
- data:{
7494
- editFormInited: false
7495
- },
7496
- // data: {global: getGlobalData('edit'), recordId: recordId, objectName: objectSchema.name, context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
7497
- initApi: null,
7498
- initFetch: null ,
7499
- body: [defaultsDeep({}, formSchema, {
7500
- type: "form",
7501
- mode: layout,
7502
- data: {
7503
- "&": "${initialValues}"
7504
- },
7505
- labelAlign,
7506
- persistData: false,
7507
- resetAfterSubmit: true,
7508
- preventEnterSubmit: true,
7509
- promptPageLeave: true,
7510
- canAccessSuperData: false,
7511
- name: `form_edit_${recordId}`,
7512
- debug: false,
7513
- title: "",
7514
- submitText: "", // amis 表单不显示提交按钮, 表单提交由项目代码接管
7515
- api: await getSaveApi(objectSchema, recordId, fields, ctx),
7516
- initFetch: recordId != 'new',
7517
- body: await getFormBody(fields, formFields, ctx),
7518
- panelClassName:'m-0 sm:rounded-lg shadow-none border-none',
7519
- bodyClassName: 'p-0',
7520
- className: 'steedos-amis-form',
7521
- hiddenOn: "${editFormInited != true}",
7522
- onEvent: {
7523
- "submitSucc": {
7524
- "weight": 0,
7525
- "actions": [
7526
- {
7527
- "actionType": "broadcast",
7528
- "args": {
7529
- "eventName": `@data.changed.${objectSchema.name}`
7530
- },
7531
- "data": {
7532
- "objectName": `${objectSchema.name}`,
7533
- "displayAs": "${displayAs}"
7534
- }
7535
- },
7536
- {
7537
- "actionType": "broadcast",
7538
- "args": {
7539
- "eventName": "@data.changed.${_master.objectName}"
7540
- },
7541
- "data": {
7542
- "objectName": "${_master.objectName}",
7543
- "_isRelated": "${_isRelated || _master._isRelated}"
7544
- },
7545
- "expression": `\${_master.objectName != '${objectSchema.name}' && _master.objectName}`
7546
- },
7547
- // {
7548
- // "actionType": "custom",
7549
- // "script": "debugger;"
7550
- // },
7551
- // {
7552
- // "args": {},
7553
- // "actionType": "closeDialog"
7554
- // }
7555
- ]
7556
- }
7590
+ if(!_.isEmpty(systemFilters)){
7591
+ filters = systemFilters;
7592
+ };
7593
+ if(api.data.$self.additionalFilters){
7594
+ if(_.isString(api.data.$self.additionalFilters)){
7595
+ userFilters.push(eval(api.data.$self.additionalFilters))
7596
+ }else{
7597
+ userFilters.push(api.data.$self.additionalFilters)
7598
+ }
7557
7599
  }
7558
- })]
7559
- };
7560
- if(formSchema.id){
7561
- amisSchema.id = `service-${formSchema.id}`;
7562
- }
7563
- return amisSchema;
7564
- }
7565
7600
 
7566
- async function getObjectDetail(objectSchema, recordId, ctx){
7567
- const { formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, formInitProps } = ctx;
7568
- const fields = ___default.values(objectSchema.fields);
7569
- const formFields = getFormFields(objectSchema, ctx);
7570
- const serviceId = `service_detail_page`;
7571
- return {
7572
- type: 'service',
7573
- name: `page_readonly_${recordId}`,
7574
- id: serviceId,
7575
- data: {global: getGlobalData('read'), context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
7576
- api: await getReadonlyFormInitApi(objectSchema, recordId, fields, formInitProps),
7577
- body: [
7578
- {
7579
- "type": "wrapper", //form 的 hiddenOn 会导致 form onEvent 异常, 使用wrapper包裹一次form,并在wrapper上控制显隐
7580
- hiddenOn: "${recordLoaded != true}",
7581
- "className": "p-0 m-0",
7582
- "body": {
7583
- type: "form",
7584
- mode: layout,
7585
- labelAlign,
7586
- persistData: false,
7587
- promptPageLeave: false,
7588
- name: `form_readonly_${recordId}`,
7589
- debug: false,
7590
- title: "",
7591
- data: {
7592
- "formData": "$$"
7593
- },
7594
- wrapWithPanel: false,
7595
- body: await getFormBody(map(fields, (field)=>{field.readonly = true; return field;}), map(formFields, (field)=>{field.readonly = true; return field;}), Object.assign({}, ctx, {showSystemFields: true})),
7596
- className: 'steedos-amis-form bg-white',
7597
- actions: [], // 不显示表单默认的提交按钮
7598
- onEvent: {
7599
- [`@data.changed.${objectSchema.name}`]: { // 由于amis service 组件的 onEvent 存在bug ,此处借助form来刷新 上层 service https://github.com/baidu/amis/issues/6294
7600
- "actions": [
7601
- {
7602
- "actionType": "reload",
7603
- "componentId": serviceId,
7604
- "expression": "this.__deletedRecord != true"
7605
- },
7606
- {
7607
- // "args": {
7608
- // "url": "/app/${appId}/${objectName}/grid/${side_listview_id}",
7609
- // "blank": false
7610
- // },
7611
- "actionType": "custom",
7612
- "script": "Steedos.goBack()",
7613
- "expression": "this.__deletedRecord === true"
7614
- }
7615
- ]
7601
+ if(api.data.$self._isRelated){
7602
+ const self = api.data.$self;
7603
+ const relatedKey = self.relatedKey;
7604
+ const refField = self.uiSchema.fields[relatedKey];
7605
+ const masterRecord = self._master.record;
7606
+ const masterObjectName = self._master.objectName;
7607
+ let relatedValue = self._master.recordId;
7608
+ if(refField.reference_to_field && refField.reference_to_field != '_id'){
7609
+ relatedValue = masterRecord[refField.reference_to_field]
7610
+ }
7611
+ let relatedFilters;
7612
+ if (
7613
+ refField._reference_to ||
7614
+ (refField.reference_to && !_.isString(refField.reference_to))
7615
+ ) {
7616
+ relatedFilters = [
7617
+ [relatedKey + "/o", "=", masterObjectName],
7618
+ [relatedKey + "/ids", "=", relatedValue],
7619
+ ];
7620
+ } else {
7621
+ relatedFilters = [relatedKey, "=", relatedValue];
7622
+ }
7623
+ userFilters.push(relatedFilters)
7624
+ }
7625
+
7626
+ if(!_.isEmpty(userFilters)){
7627
+ if(_.isEmpty(filters)){
7628
+ filters = userFilters;
7629
+ }else{
7630
+ filters = [filters, 'and', userFilters]
7631
+ }
7632
+ }
7633
+ api.data._ids = _ids;
7634
+ api.data = {
7635
+ query: api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim())
7636
+ }
7637
+ ${options.requestAdaptor || ''}
7638
+ return api;
7639
+ `;
7640
+ api.adaptor = `
7641
+ if(api.body.listName == "recent"){
7642
+ payload.data.rows = _.sortBy(payload.data.rows, function(item){
7643
+ return _.indexOf(api.body._ids, item._id)
7644
+ });
7645
+ }
7646
+ const enable_tree = ${mainObject.enable_tree};
7647
+ if(!enable_tree){
7648
+ _.each(payload.data.rows, function(item, index){
7649
+ const {pageNo, pageSize} = api.body;
7650
+ const skip = (pageNo - 1) * pageSize;
7651
+ item._index = skip + index + 1;
7652
+ })
7653
+ }
7654
+ window.postMessage(Object.assign({type: "listview.loaded"}), "*");
7655
+ let fileFields = ${JSON.stringify(fileFields)};
7656
+ let lookupFields = ${JSON.stringify(lookupFields)};
7657
+ _.each(payload.data.rows, function(item, index){
7658
+ _.each(fileFields , (field, key)=>{
7659
+ if(item[key] && item._display && item._display[key]){
7660
+ let value = item._display[key];
7661
+ if(!_.isArray(value)){
7662
+ value = [value]
7663
+ };
7664
+ if(field.type === 'file'){
7665
+ item[key] = value
7666
+ }else{
7667
+ item[key] = _.map(value, 'url')
7616
7668
  }
7617
- }
7618
- },
7619
- }
7620
- ],
7621
- onEvent: {
7622
- "fetchInited": {
7623
- "weight": 0,
7624
- "actions": [
7625
- {
7626
- actionType: 'broadcast',
7627
- eventName: "recordLoaded",
7628
- args: {
7629
- eventName: "recordLoaded"
7630
- },
7631
- data: {
7632
- objectName: "${event.data.__objectName}",
7633
- record: "${event.data.__record}"
7634
- },
7635
- expression: "${event.data.__response.error != true}"
7636
- },
7637
- {
7638
- "actionType": "setValue",
7639
- "args": {
7640
- value: {
7641
- "recordLoaded": true,
7642
- }
7643
- },
7644
- expression: "${event.data.__response.error != true}"
7645
7669
  }
7646
- ]
7647
- }
7670
+ })
7671
+ _.each(lookupFields , (field, key)=>{
7672
+ if(item[key]){
7673
+ if(field._optionsFunction){
7674
+ const optionsFunction = eval("(" + field._optionsFunction+ ")")(item);
7675
+ item[key + '__label'] = _.map(_.filter(optionsFunction, function(option){return _.includes(item[key], option.value)}), 'label').join(' ');
7676
+ }
7677
+ }
7678
+ })
7679
+ })
7680
+
7681
+ if(enable_tree){
7682
+ const records = payload.data.rows || [];
7683
+ const getTreeOptions = SteedosUI.getTreeOptions
7684
+ payload.data.rows = getTreeOptions(records,{"valueField":"_id"});
7685
+ }
7686
+
7687
+
7688
+ try{
7689
+ // TODO: 不应该直接在这里取localStorage,应该从外面传入
7690
+ const listViewId = api.body.listViewId;
7691
+ const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
7692
+ /**
7693
+ * localListViewProps规范来自crud请求api中api.data.$self参数值的。
7694
+ * 比如:{"perPage":20,"page":1,"__searchable__name":"7","__searchable__between__n1__c":[null,null],"filter":[["name","contains","a"]]}
7695
+ * __searchable__...:顶部放大镜搜索条件
7696
+ * filter:右侧过滤器
7697
+ * perPage:每页条数
7698
+ * page:当前页码
7699
+ * orderBy:排序字段
7700
+ * orderDir:排序方向
7701
+ */
7702
+ let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
7703
+ let selfData = JSON.parse(JSON.stringify(api.body.$self));
7704
+ if(localListViewProps){
7705
+ localListViewProps = JSON.parse(localListViewProps);
7706
+ selfData = Object.assign({}, localListViewProps, selfData, { filter: api.body.filter });
7707
+ if(!api.body.loaded){
7708
+ // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
7709
+ // 所以会把localSearchableFilter中已经存过的页码覆盖
7710
+ // 如果是第一次加载组件始终让翻页页码从本地存储中取值
7711
+ let formFactor = "${options.formFactor}";
7712
+ // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
7713
+ selfData.page = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
7714
+ }
7648
7715
  }
7716
+ delete selfData.context;
7717
+ delete selfData.global;
7718
+ sessionStorage.setItem(listViewPropsStoreKey, JSON.stringify(selfData));
7719
+ // 返回页码到UI界面
7720
+ payload.data.page= selfData.page;
7649
7721
  }
7722
+ catch(ex){
7723
+ console.error("本地存储中crud参数解析异常:", ex);
7724
+ }
7725
+ // 标记加载过,后续优先从本地存储中加载相关参数
7726
+ payload.data.loaded= true;
7727
+
7728
+ const setDataToComponentId = "${setDataToComponentId}";
7729
+ if(setDataToComponentId){
7730
+ SteedosUI.getRef(api.body.$self.$scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
7731
+ };
7732
+ ${options.adaptor || ''}
7733
+ return payload;
7734
+ `;
7735
+ return api;
7650
7736
  }
7651
7737
 
7652
- /*
7653
- * @Author: baozhoutao@steedos.com
7654
- * @Date: 2022-08-04 10:42:49
7655
- * @LastEditors: baozhoutao@steedos.com
7656
- * @LastEditTime: 2022-08-25 10:28:47
7657
- * @Description:
7658
- */
7659
- var config = {
7660
- listView: {
7661
- newRecordMode: 'modal',
7662
- editRecordMode: 'modal',
7663
- perPage: 20
7738
+ async function getApi(object, recordId, fields, options){
7739
+ const data = await getFindQuery(object, recordId, fields, options);
7740
+ return {
7741
+ method: "post",
7742
+ url: getApi$2(), // + "&recordId=${recordId}"
7743
+ data: data,
7744
+ headers: {
7745
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7746
+ }
7664
7747
  }
7665
- };
7748
+ }
7666
7749
 
7667
- async function getTableColumns(fields, options){
7668
- const columns = [{name: '_index',type: 'text', width: 32, placeholder: ""}];
7669
- for (const field of fields) {
7670
- if((field.is_name || field.name === options.labelFieldName) && options.objectName === 'cms_files'){
7671
- const previewFileScript = `
7672
- var data = event.data;
7673
- var file_name = data.versions ? data.name : "${field.label}";
7674
- var file_id = data._id;
7675
- SteedosUI.previewFile && SteedosUI.previewFile({file_name, file_id});
7676
- `;
7677
- columns.push({
7678
- "type": "button",
7679
- "label": `<%=data.versions ? data.name : "${field.label}"%>`,
7680
- "className": "whitespace-nowrap",
7681
- "level": "link",
7682
- "onEvent": {
7683
- "click": {
7684
- "actions": [
7685
- {
7686
- "args": {
7687
- "api": {
7688
- "url": "${context.rootUrl}/api/files/files/${versions[0]}?download=true",
7689
- "method": "get",
7690
- "headers": {
7691
- "Authorization": "Bearer ${context.tenantId},${context.authToken}"
7692
- }
7693
- }
7694
- },
7695
- "actionType": "download",
7696
- "expression": "!!!window?.nw?.require"//浏览器上直接下载
7697
- },
7698
- {
7699
- "args": {},
7700
- "actionType": "custom",
7701
- "script": previewFileScript,
7702
- "expression": "!!window?.nw?.require" //PC客户端预览附件
7703
- }
7704
- ]
7705
- }
7706
- }
7707
- });
7708
- }else if(field.type === 'toggle'){
7709
- columns.push(Object.assign({}, {
7710
- type: "switch",
7711
- name: field.name,
7712
- label: field.label,
7713
- width: field.width,
7714
- toggled: field.toggled,
7715
- disabled: true,
7716
- className:"whitespace-nowrap",
7717
- }, field.amis, {name: field.name}));
7718
- }else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7719
- columns.push(Object.assign({}, {
7720
- type: "switch",
7721
- name: field.name,
7722
- label: field.label,
7723
- width: field.width,
7724
- toggled: field.toggled,
7725
- disabled: true,
7726
- className:"whitespace-nowrap",
7727
- ...getAmisFileReadonlySchema(field)
7728
- }, field.amis, {name: field.name}));
7729
- }
7730
- else if(field.type === 'select'){
7731
- const map = getSelectMap(field.options);
7732
- columns.push(Object.assign({}, {
7733
- type: "mapping",
7734
- name: field.name,
7735
- label: field.label,
7736
- map: map,
7737
- sortable: field.sortable,
7738
- width: field.width,
7739
- toggled: field.toggled,
7740
- className:"whitespace-nowrap",
7741
- }, field.amis, {name: field.name}));
7750
+ function getRecordPermissionsApi(object, recordId, options){
7751
+ const data = getRecordPermissionsQuery(object, recordId, options);
7752
+ return {
7753
+ method: "post",
7754
+ url: getApi$2(),
7755
+ data: data,
7756
+ headers: {
7757
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7742
7758
  }
7743
- else {
7744
- const tpl = await getFieldTpl(field, options);
7759
+ }
7760
+ }
7745
7761
 
7746
- let type = 'text';
7747
- if(tpl){
7748
- type = 'tpl';
7749
- }else if(field.type === 'html'){
7750
- type = 'markdown';
7751
- }else if(field.type === 'url' && field.show_as_qr){
7752
- type = 'qr-code';
7753
- }
7754
- let className = "";
7755
- if(field.type === 'textarea'){
7756
- className = 'min-w-56';
7757
- }
7758
- if(field.wrap === false){
7759
- className += " whitespace-nowrap";
7762
+ const API_CACHE = 100;
7763
+
7764
+ function getReadonlyFormAdaptor(object, fields){
7765
+ let scriptStr = '';
7766
+ const selectFields = _$1.filter(fields, function(field){return field.name.indexOf('.') < 0 && ((field.type == 'select' && field.options) || ((field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to))});
7767
+ const gridAndObjectFieldsName = _$1.map(_$1.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type === 'object' || field.type === 'grid')}), 'name');
7768
+ _$1.each(selectFields, function(field){
7769
+ if(!_$1.includes(OMIT_FIELDS, field.name)){
7770
+ field.name;
7771
+ if(field.options){
7772
+ const options = JSON.stringify({options: field.options});
7773
+ scriptStr = scriptStr + `var ${field.name}Options= (${options}).options;`;
7774
+ }else if(field.optionsFunction){
7775
+ scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`;
7776
+ }else if(field._optionsFunction){
7777
+ scriptStr = scriptStr + `var ${field.name}Options = eval(${field._optionsFunction})(api.data);`;
7760
7778
  }
7761
- if(!field.hidden && !field.extra){
7762
- columns.push(Object.assign({}, {
7763
- name: field.name,
7764
- label: field.label,
7765
- sortable: field.sortable,
7766
- // searchable: field.searchable,
7767
- width: field.width,
7768
- type: type,
7769
- tpl: tpl,
7770
- toggled: field.toggled,
7771
- className,
7772
- options: field.type === 'html' ? {html: true} : null
7773
- // toggled: true
7774
- }, field.amis, {name: field.name}));
7779
+ if(field.multiple){
7780
+ scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`;
7781
+ }else {
7782
+ scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`;
7783
+ scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`;
7775
7784
  }
7776
7785
  }
7777
-
7786
+ });
7787
+
7788
+ // const refFields = _.filter(fields, function(field){return field.name.indexOf('.') < 0 && (field.type == 'lookup' || field.type == 'master_detail') && !field.reference_to});
7789
+ // _.each(refFields, function(field){
7790
+ // if(!_.includes(OMIT_FIELDS, field.name)){
7791
+ // const valueField = field.reference_to_field || '_id';
7792
+ // scriptStr = scriptStr + `var ${field.name}Options = eval(${field.optionsFunction.toString()})(api.data);`
7793
+ // if(field.multiple){
7794
+ // scriptStr = scriptStr + `data.${field.name}__label = _.map(_.filter(${field.name}Options, function(option){return _.includes(data.${field.name}, option.value)}), 'label');`
7795
+ // }else{
7796
+ // scriptStr = scriptStr + `var ${field.name}Selected = _.find(${field.name}Options, function(option){return data.${field.name} == option.value});`
7797
+ // scriptStr = scriptStr + `data.${field.name}__label = ${field.name}Selected ? ${field.name}Selected.label:null;`
7798
+ // }
7799
+ // }
7800
+ // })
7801
+
7802
+ return `
7803
+ if(payload.data.data.length === 0){
7804
+ return {
7805
+ status: 2,
7806
+ msg: "无法找到记录"
7807
+ }
7778
7808
  }
7779
- // columns.push(getOperation(fields));
7780
- if(!_$1.some(columns, { name: options.labelFieldName })){
7781
- const href = Router.getObjectDetailPath({
7782
- ...options, formFactor: options.formFactor, appId: "${appId}", objectName: options.objectName || "${objectName}", recordId: `\${${options.idFieldName}}`
7783
- });
7784
- columns[0].type = "tpl";
7785
- columns[0].tpl = `<a href="${href}">\${${columns[0].name}}</a>`;
7809
+ if(payload.data.data){
7810
+ var data = payload.data.data[0];
7811
+ var gridAndObjectFieldsName = ${JSON.stringify(gridAndObjectFieldsName)};
7812
+ try{
7813
+ ${scriptStr}
7814
+ ${getScriptForAddUrlPrefixForImgFields(fields)}
7815
+ ${getScriptForRewriteValueForFileFields(fields)}
7816
+ }catch(e){
7817
+ console.error(e)
7818
+ }
7819
+ // 原始记录
7820
+ var record = _.cloneDeep(data);
7821
+ try{
7822
+ _.each(gridAndObjectFieldsName, function(name){
7823
+ data[name] = data._display[name];
7824
+ })
7825
+ }catch(e){
7826
+ console.error(e)
7827
+ }
7828
+ payload.data = data;
7829
+ payload.data.__objectName = "${object.name}";
7830
+ payload.data.__record = record;
7831
+ window.postMessage(Object.assign({type: "record.loaded"}, {record: record}), "*")
7786
7832
  }
7787
- return columns;
7833
+ if(payload.errors){
7834
+ payload.status = 2;
7835
+ payload.msg = payload.errors[0].message;
7836
+ }
7837
+ return payload;
7838
+ `
7788
7839
  }
7789
7840
 
7790
- /**
7791
- * 生成移动端列表每行显示的amis行
7792
- * @param {*} tpls 要显示的每个字段的tpl
7793
- * @returns {
7794
- "type": "wrapper",
7795
- "body": [{
7796
- "type": "tpl",
7797
- "tpl": tpls[index].tpl,
7798
- "className": "truncate"//左侧样式类
7799
- },{
7800
- "type": "tpl",
7801
- "tpl": tpls[index + 1].tpl,
7802
- "className": "truncate ml-2 flex flex-shrink-0"//右侧样式类
7803
- }],
7804
- "size": "none",
7805
- "className": "flex items-center justify-between"//每行样式类
7841
+ async function getReadonlyFormInitApi(object, recordId, fields, options){
7842
+ return {
7843
+ method: "post",
7844
+ url: getApi$2()+"&recordId=${recordId}",
7845
+ cache: API_CACHE,
7846
+ // requestAdaptor: "console.log('getReadonlyFormInitApi requestAdaptor', api);return api;",
7847
+ adaptor: getReadonlyFormAdaptor(object, fields),
7848
+ data: await getFindOneQuery$1(object, recordId, fields, options),
7849
+ headers: {
7850
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7851
+ }
7806
7852
  }
7807
- */
7808
- function getMobileLines(tpls){
7809
- let lines = [];
7810
- let maxLineCount = 2;
7811
- let lineChildren = [];
7812
- let isNewLine = false;
7813
- let isLeft = true;
7814
- let lineChildrenClassName = "";
7815
- let lineClassName = "flex items-center justify-between h-[20px]";
7816
- tpls.forEach(function(item){
7817
- if(isNewLine && lines.length < maxLineCount){
7818
- lines.push({
7819
- "type": "wrapper",
7820
- "body": lineChildren,
7821
- "size": "none",
7822
- "className": lineClassName
7823
- });
7824
- lineChildren = [];
7853
+ }
7854
+
7855
+ /*
7856
+ img/avatar字段值添加URL前缀使其在amis中正常显示图片。
7857
+ */
7858
+ function getScriptForAddUrlPrefixForImgFields(fields){
7859
+ let imgFieldsKeys = [];
7860
+ let imgFields = {};
7861
+ fields.forEach((item)=>{
7862
+ if(_$1.includes(['image','avatar'], item.type)){
7863
+ imgFieldsKeys.push(item.name);
7864
+ imgFields[item.name] = {
7865
+ name: item.name,
7866
+ type: item.type,
7867
+ multiple: item.multiple
7868
+ };
7825
7869
  }
7826
- if(isLeft){
7827
- // 左侧半行
7828
- lineChildrenClassName = "steedos-listview-item-left truncate";
7829
- if(item.field.is_wide){
7830
- // 左侧全行样式可以单独写
7831
- lineChildrenClassName = "steedos-listview-item-wide truncate";
7870
+ });
7871
+ if(!imgFieldsKeys.length){
7872
+ return '';
7873
+ }
7874
+ return `
7875
+ // image字段值添加URL前缀
7876
+ let imgFieldsKeys = ${JSON.stringify(imgFieldsKeys)};
7877
+ let imgFields = ${JSON.stringify(imgFields)};
7878
+ imgFieldsKeys.forEach((item)=>{
7879
+ let imgFieldValue = data[item];
7880
+ let imgFieldDisplayValue = data._display && data._display[item];
7881
+ if(imgFieldValue && imgFieldValue.length){
7882
+ let fieldProps = imgFields[item];
7883
+ if(fieldProps.multiple){
7884
+ if(imgFieldDisplayValue instanceof Array){
7885
+ data[item] = imgFieldDisplayValue.map((i)=>{ return i.url });
7886
+ }
7887
+ }else{
7888
+ data[item] = imgFieldDisplayValue && imgFieldDisplayValue.url;
7889
+ }
7890
+ }
7891
+ })
7892
+ `
7893
+ }
7894
+
7895
+ /*
7896
+ file字段值重写使其在amis中正常显示附件名、点击附件名下载文件。
7897
+ */
7898
+ function getScriptForRewriteValueForFileFields(fields){
7899
+ let fileFieldsKeys = [];
7900
+ let fileFields = {};
7901
+ fields.forEach((item)=>{
7902
+ if(item.type === 'file'){
7903
+ fileFieldsKeys.push(item.name);
7904
+ fileFields[item.name] = {
7905
+ name: item.name,
7906
+ multiple: item.multiple
7907
+ };
7908
+ }
7909
+ });
7910
+ if(!fileFieldsKeys.length){
7911
+ return '';
7912
+ }
7913
+ return `
7914
+ // file字段值重写以便编辑时正常显示附件名、点击附件名正常下载附件
7915
+ let fileFieldsKeys = ${JSON.stringify(fileFieldsKeys)};
7916
+ let fileFields = ${JSON.stringify(fileFields)};
7917
+ fileFieldsKeys.forEach((item)=>{
7918
+ let fileFieldValue = data[item];
7919
+ let fileFieldDisplayValue = data._display && data._display[item];
7920
+ if(fileFieldValue && fileFieldValue.length){
7921
+ if(fileFields[item].multiple){
7922
+ if(fileFieldDisplayValue instanceof Array){
7923
+ data[item] = fileFieldDisplayValue.map((item, index)=>{
7924
+ return {
7925
+ value: fileFieldValue[index],
7926
+ name: item.name,
7927
+ url: item.url + "?download=true",
7928
+ state: "uploaded"
7929
+ }
7930
+ });
7931
+ }
7932
+ }else{
7933
+ data[item] = [{
7934
+ value: fileFieldValue,
7935
+ name: fileFieldDisplayValue.name,
7936
+ url: fileFieldDisplayValue.url + "?download=true",
7937
+ state: "uploaded"
7938
+ }];
7939
+ }
7940
+ }
7941
+ })
7942
+ `
7943
+ }
7944
+
7945
+ async function getEditFormInitApi(object, recordId, fields, options){
7946
+ const data = await getFindOneQuery$1(object, recordId, fields);
7947
+ data.recordId = "${recordId}";
7948
+ data.objectName = "${objectName}";
7949
+ data.uiSchema = "${uiSchema}";
7950
+ data.global = "${global}";
7951
+ data.context = "${context}";
7952
+ data.defaultData = "${defaultData}";
7953
+ data._master = "${_master}";
7954
+
7955
+ return {
7956
+ method: "post",
7957
+ url: getApi$2() + '&objectName=${objectName}' ,
7958
+ // sendOn: "!!this.recordId",
7959
+ cache: API_CACHE,
7960
+ requestAdaptor: `
7961
+ // 所有不想在network请求中发送的数据都应该从data中分离出来,data变量只需要留下query才需要发送出去
7962
+ var { recordId, objectName, uiSchema, global, context, ...data} = api.data;
7963
+ if(!recordId){
7964
+ // 新建则不请求任何数据
7965
+ data.query = "{data:" + objectName + "(filters: " + JSON.stringify(["_id", "=", null]) + ", top: 1){_id}}";
7966
+ }
7967
+ api.data = data;
7968
+ ${options.initApiRequestAdaptor || ''}
7969
+ return api;
7970
+ `,
7971
+ adaptor: `
7972
+ const recordId = api.body.recordId;
7973
+ let initialValues={};
7974
+ if(recordId && payload.data.data){
7975
+ var data = payload.data.data[0];
7976
+ const dataKeys = _.keys(data);
7977
+ const uiSchema = api.body.uiSchema;
7978
+ const fieldKeys = uiSchema && _.keys(uiSchema.fields);
7979
+
7980
+ if(data){
7981
+ ${getScriptForAddUrlPrefixForImgFields(fields)}
7982
+ ${getScriptForRewriteValueForFileFields(fields)}
7983
+
7984
+ _.each(dataKeys, function(key){
7985
+ if(fieldKeys.indexOf(key)<0){
7986
+ delete data[key];
7987
+ }
7988
+ })
7989
+
7990
+ //初始化接口返回的字段移除字段值为null的字段
7991
+ for (key in data){
7992
+ if(data[key] === null){
7993
+ delete data[key];
7994
+ }
7995
+ }
7996
+ };
7997
+ initialValues = data;
7998
+ }
7999
+ else{
8000
+ var uiSchema = api.body.uiSchema;
8001
+ var defaultData = api.body.defaultData;
8002
+ var defaultValues = {};
8003
+ _.each(uiSchema?.fields, function(field){
8004
+ var value = SteedosUI.getFieldDefaultValue(field, api.body.global);
8005
+ if(value){
8006
+ defaultValues[field.name] = value;
8007
+ }
8008
+ });
8009
+ if(defaultData && _.isObject(defaultData) && !_.isArray(defaultData)){
8010
+ defaultValues = Object.assign({}, defaultValues, defaultData)
8011
+ }
8012
+ if(uiSchema.form){
8013
+ try{
8014
+ var objectFormConfig = JSON.parse(uiSchema.form);
8015
+ var formInitialValuesFun = objectFormConfig.initialValues;
8016
+ if(formInitialValuesFun){
8017
+ formInitialValuesFun = new Function("return " + formInitialValuesFun)();
8018
+ }
8019
+ if(typeof formInitialValuesFun === "function"){
8020
+ initialValues = formInitialValuesFun.apply({doc: defaultValues || {} , global: api.body.global, master: api.body._master })
8021
+ }
8022
+ }
8023
+ catch(ex){
8024
+ console.warn(ex);
8025
+ }
8026
+ }
8027
+ if(_.isObject(initialValues)){
8028
+ // uiSchema.form.initialValues为函数且执行后为json,则优先取initialValues中的默认值
8029
+ initialValues = Object.assign({}, defaultValues, initialValues);
8030
+ }
8031
+ else{
8032
+ initialValues = defaultValues;
8033
+ }
7832
8034
  }
7833
- if(lines.length === 0){
7834
- // 第一个字段加粗黑色显示
7835
- lineChildrenClassName += " font-bold text-gray-800";
8035
+ // data下的变量需要在保存接口(getSaveApi)中被删除。
8036
+ payload.data = {
8037
+ ...initialValues
7836
8038
  }
8039
+ ${options.initApiAdaptor || ''}
8040
+ return payload;
8041
+ `,
8042
+ responseData: {
8043
+ initialValues: "$$",
8044
+ editFormInited: true
8045
+ },
8046
+ data: data,
8047
+ headers: {
8048
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7837
8049
  }
7838
- else {
7839
- // 右侧半行
7840
- lineChildrenClassName = "steedos-listview-item-right truncate ml-2 flex flex-shrink-0";
7841
- }
7842
- lineChildren.push({
7843
- "type": "tpl",
7844
- "tpl": item.tpl,
7845
- "className": lineChildrenClassName
7846
- });
7847
-
7848
- if(item.field.is_wide){
7849
- // 宽字段占整行
7850
- isLeft = true;
7851
- isNewLine = true;
7852
- }
7853
- else {
7854
- isLeft = !isLeft;
7855
- isNewLine = isLeft;
7856
- }
7857
- });
7858
-
7859
- if(lineChildren.length && lines.length < maxLineCount){
7860
- lines.push({
7861
- "type": "wrapper",
7862
- "body": lineChildren,
7863
- "size": "none",
7864
- "className": lineClassName
7865
- });
7866
8050
  }
7867
-
7868
- return lines;
7869
8051
  }
7870
8052
 
7871
- async function getMobileTableColumns(fields, options){
7872
- const columns = [];
7873
- let nameField = {};
7874
- let tpls = [];
7875
- for (const field of fields) {
7876
- let tpl = "";
7877
- if(field.is_name || field.name === options.labelFieldName){
7878
- nameField = field;
7879
- options.onlyDisplayLabel = true;
7880
- tpl = await getFieldTpl(field, options);
7881
- }
7882
- else if(field.type === 'avatar' || field.type === 'image' || field.type === 'file'){
7883
- // 图片和附件类型字段暂时显示为附件名称,后续需要再优化
7884
- tpl = `\${_display.${field.name}.name}`;
7885
- }
7886
- else {
7887
- if(field.type === 'lookup' || field.type === 'master_detail'){
7888
- options.onlyDisplayLabel = true;
8053
+
8054
+ function getSaveApi(object, recordId, fields, options){
8055
+ return {
8056
+ method: 'post',
8057
+ url: getApi$2(),
8058
+ data: getSaveQuery(object, recordId),
8059
+ requestAdaptor: getSaveRequestAdaptor(fields, options),
8060
+ responseData: {
8061
+ "recordId": "${record._id}"
8062
+ },
8063
+ adaptor: `
8064
+ if(payload.errors){
8065
+ payload.status = 2;
8066
+ payload.msg = window.t ? window.t(payload.errors[0].message) : payload.errors[0].message;
7889
8067
  }
7890
- tpl = await getFieldTpl(field, options);
7891
- }
7892
- if(!tpl){
7893
- tpl = `\${${field.name}}`;
8068
+ ${options.apiAdaptor || ''}
8069
+ return payload;
8070
+ `,
8071
+ headers: {
8072
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7894
8073
  }
7895
- if(!field.hidden && !field.extra){
7896
- tpls.push({ field, tpl });
8074
+ }
8075
+ }
8076
+
8077
+ function getBatchDelete(objectName){
8078
+ return {
8079
+ method: 'post',
8080
+ url: getApi$2(),
8081
+ requestAdaptor: `
8082
+ var ids = api.data.ids.split(",");
8083
+ var deleteArray = [];
8084
+ ids.forEach((id,index)=>{
8085
+ deleteArray.push(\`delete__\${index}:${objectName}__delete(id: "\${id}")\`);
8086
+ })
8087
+ api.data = {query: \`mutation{\${deleteArray.join(',')}}\`};
8088
+ return api;
8089
+ `,
8090
+ data: {
8091
+ ids: `\${ids}`
8092
+ },
8093
+ headers: {
8094
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
7897
8095
  }
7898
8096
  }
7899
- const url = getNameTplUrl(nameField, options);
8097
+ }
7900
8098
 
7901
- const columnLines = getMobileLines(tpls);
8099
+ const DEFAULT_CALENDAR_OPTIONS = {
8100
+ startDateExpr: "start",
8101
+ endDateExpr: "end",
8102
+ allDayExpr: "is_all_day",
8103
+ textExpr: "name"
8104
+ };
7902
8105
 
8106
+ async function getCalendarApi(mainObject, fields, options) {
8107
+ if (!options) {
8108
+ options = {};
8109
+ }
8110
+ const calendarOptions = options.calendarOptions;
8111
+ const searchableFields = [];
8112
+ let { filter, sort, top, setDataToComponentId = '' } = options;
7903
8113
 
7904
- let column = {
7905
- name: nameField.name,
7906
- label: nameField.label,
7907
- sortable: nameField.sortable,
7908
- type: "button",
7909
- level: "link",
7910
- actionType: "link",
7911
- link: url,
7912
- innerClassName: "steedos-listview-item block text-gray-500",
7913
- body: {
7914
- "type": "wrapper",
7915
- "body": columnLines,
7916
- "size": "none",
7917
- "className": "p-1"
7918
- }
7919
- };
7920
-
7921
- if(options.objectName === 'cms_files'){
7922
- if(window.Meteor?.isCordova){
7923
- column = {
7924
- ...column,
7925
- actionType: "",
7926
- link: "",
7927
- onEvent: {
7928
- "click": {
7929
- "actions": [
7930
- {
7931
- "script": `
7932
- let cms_url = "/api/files/files/"+event.data.versions[0]+"?download=true"
7933
- Steedos.cordovaDownload(encodeURI(Steedos.absoluteUrl(cms_url)), event.data.name);
7934
- `,
7935
- "actionType": "custom"
7936
- }
7937
- ],
7938
- "weight": 0
7939
- }
7940
- }
7941
- };
7942
- }else {
7943
- column = {
7944
- ...column,
7945
- actionType: "",
7946
- link: "",
7947
- onEvent: {
7948
- "click": {
7949
- "actions": [
7950
- {
7951
- "args": {
7952
- "api": {
7953
- "url": url,
7954
- "method": "get",
7955
- "headers": {
7956
- "Authorization": "Bearer ${context.tenantId},${context.authToken}"
7957
- }
7958
- }
7959
- },
7960
- "actionType": "download"
7961
- }
7962
- ],
7963
- "weight": 0
7964
- }
7965
- }
7966
- };
7967
- }
7968
-
7969
- }
8114
+ if (!top) {
8115
+ // 日历请求不翻页
8116
+ top = 200;
8117
+ }
7970
8118
 
7971
- columns.push(column);
7972
-
8119
+ if (___default.isArray(filter)) {
8120
+ filter = ___default.map(filter, function (item) {
8121
+ if (item.operation) {
8122
+ return [item.field, item.operation, item.value];
8123
+ } else {
8124
+ return item
8125
+ }
8126
+ });
8127
+ }
8128
+ if (!filter) {
8129
+ filter = [];
8130
+ }
7973
8131
 
7974
- return columns;
7975
- }
8132
+ ___default.each(fields, function (field) {
8133
+ if (field.searchable) {
8134
+ searchableFields.push(field.name);
8135
+ }
8136
+ });
7976
8137
 
7977
- function getDefaultParams(options){
7978
- return {
7979
- perPage: options.top || options.perPage || config.listView.perPage
8138
+ const idFieldName = mainObject.idFieldName || "_id";
8139
+ let valueField = mainObject.key_field || '_id';
8140
+ const api = await getApi(mainObject, null, fields, { alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"` });
8141
+ api.data.$term = "$term";
8142
+ api.data.$self = "$$";
8143
+ api.data.filter = "$filter";
8144
+ api.data.pageSize = top || 10;
8145
+ api.requestAdaptor = `
8146
+ let selfData = JSON.parse(JSON.stringify(api.data.$self));
8147
+ var filters = api.data.filter || ${JSON.stringify(filter)} || [];
8148
+ const eventFetchInfo = selfData.fetchInfo;
8149
+ const startDateExpr = "${calendarOptions.startDateExpr}";
8150
+ const endDateExpr = "${calendarOptions.endDateExpr}";
8151
+ const eventDurationFilters = [[endDateExpr, ">=", eventFetchInfo.start], [startDateExpr, "<=", eventFetchInfo.end]];
8152
+ if(_.isEmpty(filters)){
8153
+ filters = eventDurationFilters;
8154
+ }else{
8155
+ filters = [filters, 'and', eventDurationFilters]
7980
8156
  }
7981
- }
7982
-
7983
- function getButtonVisibleOn(button){
7984
- let visible= button.visible;
7985
8157
 
7986
- if(button._visible){
7987
- visible = button._visible;
8158
+ if(api.data.$self.additionalFilters){
8159
+ filters.push(api.data.$self.additionalFilters)
7988
8160
  }
7989
8161
 
7990
- if(isBoolean(visible)){
7991
- visible = visible.toString();
8162
+ var pageSize = api.data.pageSize || 10;
8163
+ var pageNo = api.data.pageNo || 1;
8164
+ var skip = (pageNo - 1) * pageSize;
8165
+ var orderBy = api.data.orderBy || '';
8166
+ var orderDir = api.data.orderDir || '';
8167
+ var sort = orderBy + ' ' + orderDir;
8168
+ sort = orderBy ? sort : "${sort}";
8169
+ var allowSearchFields = ${JSON.stringify(searchableFields)};
8170
+ if(api.data.$term){
8171
+ filters = [["name", "contains", "'+ api.data.$term +'"]];
8172
+ }else if(selfData.op === 'loadOptions' && selfData.value){
8173
+ filters = [["${valueField.name}", "=", selfData.value]];
7992
8174
  }
8175
+ var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
7993
8176
 
7994
- if(visible){
7995
- // if(visible.indexOf("Meteor.") > 0 || visible.indexOf("Creator.") > 0 || visible.indexOf("Session.") > 0){
7996
- // console.warn('无效的visible', visible)
7997
- // return 'false';
7998
- // }
7999
- if(visible.trim().startsWith('function')){
8000
- return `${visible}(objectName, typeof _id === 'undefined' ? null: _id, typeof record === 'undefined' ? (typeof recordPermissions === 'undefined' ? {} : recordPermissions) : record.recordPermissions, data)`
8177
+ if(searchableFilter.length > 0){
8178
+ if(filters.length > 0 ){
8179
+ filters = [filters, 'and', searchableFilter];
8180
+ }else{
8181
+ filters = searchableFilter;
8001
8182
  }
8002
- return visible;
8003
8183
  }
8004
8184
 
8005
- if(button.type === 'amis_button'){
8006
- const amisSchema = button.amis_schema;
8007
- if(amisSchema && amisSchema.body && amisSchema.body.length > 0){
8008
- const btn1 = amisSchema.body[0];
8009
- return btn1.visibleOn
8010
- }
8185
+ if(allowSearchFields){
8186
+ allowSearchFields.forEach(function(key){
8187
+ const keyValue = selfData[key];
8188
+ if(_.isString(keyValue)){
8189
+ filters.push([key, "contains", keyValue]);
8190
+ }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8191
+ filters.push([key, "=", keyValue]);
8192
+ }
8193
+ })
8011
8194
  }
8012
- }
8013
-
8014
- async function getTableOperation(ctx){
8015
- const buttons = ctx.buttons;
8016
- const operationButtons = [];
8017
- each(buttons, (button)=>{
8018
- if(isBoolean(button.visible)){
8019
- button.visible = button.visible.toString();
8020
- }
8021
- // operationButtons.push({
8022
- // type: 'button',
8023
- // label: button.label,
8024
- // visibleOn: button.visible ? `${button.visible}` : (button._visible ? `${button._visible}` : null),
8025
- // onEvent: {
8026
- // click: {
8027
- // actions: []
8028
- // }
8029
- // }
8030
- // })
8031
8195
 
8032
- operationButtons.push({
8033
- type: 'steedos-object-button',
8034
- name: button.name,
8035
- objectName: button.objectName,
8036
- visibleOn: getButtonVisibleOn(button),
8037
- className: 'antd-Button--default'
8038
- });
8039
- });
8040
- if(operationButtons.length < 1){
8041
- return ;
8042
- }
8043
- return {
8044
- type: 'operation',
8045
- label: '操作',
8046
- fixed: 'right',
8047
- labelClassName: 'text-center',
8048
- className: 'text-center steedos-listview-operation w-20',
8049
- buttons: [
8050
- {
8051
- "type": "steedos-dropdown-button",
8052
- "label": "xxx",
8053
- "buttons": operationButtons,
8054
- "placement": "bottomRight",
8055
- "overlayClassName": "shadow !min-w-[160px]",
8056
- "trigger": ["click"],
8057
- "id": "u:c2140a365019",
8058
- onOpenApi: {
8059
- url: `\${context.rootUrl}/service/api/@\${objectName}/recordPermissions/\${_id}`,
8060
- method: "get",
8061
- data: {
8062
- $: "$$",
8063
- objectName: "${objectName}",
8064
- listViewId: "${listViewId}",
8065
- appId: "${appId}",
8066
- formFactor: "${formFactor}",
8067
- context: `\${context}`
8068
- },
8069
- headers: {
8070
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8071
- },
8072
- adaptor: `
8073
- payload = {
8074
- record: {
8075
- recordPermissions: payload
8076
- }
8077
- };
8078
- return payload;
8079
- `,
8196
+ if(selfData.__keywords && allowSearchFields){
8197
+ const keywordsFilters = [];
8198
+ allowSearchFields.forEach(function(key, index){
8199
+ const keyValue = selfData.__keywords;
8200
+ if(keyValue){
8201
+ keywordsFilters.push([key, "contains", keyValue]);
8202
+ if(index < allowSearchFields.length - 1){
8203
+ keywordsFilters.push('or');
8080
8204
  }
8081
- }
8082
- ]
8205
+ }
8206
+ })
8207
+ filters.push(keywordsFilters);
8208
+ }
8209
+ api.data.query = api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim());
8210
+ delete api.data.$term;
8211
+ delete api.data.filter;
8212
+ delete api.data.pageSize;
8213
+ delete api.data.pageNo;
8214
+ delete api.data.orderBy;
8215
+ delete api.data.orderDir;
8216
+ return api;
8217
+ `;
8218
+ api.adaptor = `
8219
+ window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8220
+ const setDataToComponentId = "${setDataToComponentId}";
8221
+ if(setDataToComponentId){
8222
+ SteedosUI.getRef(api.body.$self.scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8083
8223
  }
8224
+ const rows = payload.data.rows || [];
8225
+ const selfData = api.data.$self;
8226
+ const events = rows.map(function(n){
8227
+ return {
8228
+ id: n["${idFieldName}"],
8229
+ title: n["${calendarOptions.textExpr}"],
8230
+ start: n["${calendarOptions.startDateExpr}"],
8231
+ end: n["${calendarOptions.endDateExpr}"],
8232
+ allDay: n["${calendarOptions.allDayExpr}"],
8233
+ extendedProps: n
8234
+ }
8235
+ });
8236
+ const successCallback = selfData.successCallback;
8237
+ const failureCallback = selfData.failureCallback;
8238
+ successCallback(events);
8239
+ return payload;
8240
+ `;
8241
+ return api;
8084
8242
  }
8085
8243
 
8086
- async function getTableSchema$1(fields, options){
8087
- if(!options){
8088
- options = {};
8089
- }
8090
- let columns = [];
8091
- if(options.formFactor === 'SMALL' || ["split"].indexOf(options.displayAs) > -1){
8092
- columns = await getMobileTableColumns(fields, options);
8093
- }
8094
- else {
8095
- columns = await getTableColumns(fields, options);
8096
- columns.push(await getTableOperation(options));
8244
+ function getCalendarRecordPermissionsApi(mainObject, recordId) {
8245
+ const api = getRecordPermissionsApi(mainObject, recordId, { alias: 'rows', limit: 1, fields: ["allowEdit"] });
8246
+ api.data.$self = "$$";
8247
+ api.adaptor = `
8248
+ const rows = payload.data.rows || [];
8249
+ const selfData = api.data.$self;
8250
+ const revert = selfData.revert;
8251
+ const recordPermissions = rows[0] && rows[0].recordPermissions;
8252
+ const editable = !!(recordPermissions && recordPermissions.allowEdit);
8253
+ if(!editable){
8254
+ // 没有权限时还原
8255
+ revert && revert();
8097
8256
  }
8098
- return {
8099
- mode: "table",
8100
- name: "thelist",
8101
- headerToolbarClassName: "py-2 px-2 border-gray-300 bg-gray-100 border-solid border-b",
8102
- className: "",
8103
- draggable: false,
8104
- defaultParams: getDefaultParams(options),
8105
- columns: columns,
8106
- syncLocation: false,
8107
- keepItemSelectionOnPageChange: true,
8108
- checkOnItemClick: false,
8109
- labelTpl: `\${${options.labelFieldName}}`,
8110
- autoFillHeight: false, // 自动高度效果不理想,先关闭
8111
- columnsTogglable: false,
8257
+ payload.data.editable = editable;
8258
+ return payload;
8259
+ `;
8260
+ return api;
8261
+ }
8262
+
8263
+ function getCalendarRecordSaveApi(object, calendarOptions) {
8264
+ const formData = {};
8265
+ const idFieldName = object.idFieldName || "_id";
8266
+ formData[idFieldName] = "${event.data.event.id}";
8267
+ const nameFieldKey = object.NAME_FIELD_KEY || "name";
8268
+ formData[nameFieldKey] = "${event.data.event.title}";
8269
+ formData[calendarOptions.startDateExpr] = "${event.data.event.start}";
8270
+ formData[calendarOptions.endDateExpr] = "${event.data.event.end}";
8271
+ formData[calendarOptions.allDayExpr] = "${event.data.event.allDay}";
8272
+ // formData[calendarOptions.textExpr] = "${event.data.event.title}";
8273
+ const apiData = {
8274
+ objectName: "${objectName}",
8275
+ $: formData,
8276
+ $self: "$$"
8277
+ };
8278
+ const saveDataTpl = `
8279
+ const formData = api.data.$;
8280
+ const objectName = api.data.objectName;
8281
+ let query = \`mutation{record: \${objectName}__update(id: "\${formData.${idFieldName}}", doc: {__saveData}){${idFieldName}}}\`;
8282
+ delete formData.${idFieldName};
8283
+ let __saveData = JSON.stringify(JSON.stringify(formData));
8284
+ `;
8285
+ const requestAdaptor = `
8286
+ ${saveDataTpl}
8287
+ api.data.query = query.replace('{__saveData}', __saveData);
8288
+ return api;
8289
+ `;
8290
+
8291
+ return {
8292
+ method: 'post',
8293
+ url: getApi$2(),
8294
+ data: apiData,
8295
+ requestAdaptor: requestAdaptor,
8296
+ adaptor: `
8297
+ if(payload.errors){
8298
+ payload.status = 2;
8299
+ payload.msg = payload.errors[0].message;
8300
+ const revert = api.data.$self.event.data.revert;
8301
+ revert && revert();
8302
+ }
8303
+ return payload;
8304
+ `,
8305
+ headers: {
8306
+ Authorization: "Bearer ${context.tenantId},${context.authToken}"
8112
8307
  }
8308
+ };
8113
8309
  }
8114
8310
 
8115
-
8116
-
8117
8311
  /**
8118
- *
8119
- * @param {*} mainObject
8120
- * @param {*} fields
8121
- * @param {*} options = {filter: listview 过滤条件, ...}
8122
- * @returns
8312
+ * 列表视图Calendar amisSchema
8313
+ * @param {*} objectSchema 对象UISchema
8314
+ * @returns amisSchema
8123
8315
  */
8124
- async function getTableApi(mainObject, fields, options){
8125
- const searchableFields = [];
8126
- let { filter, filtersFunction, sort, top, setDataToComponentId = '' } = options;
8316
+ async function getObjectCalendar(objectSchema, calendarOptions, options) {
8317
+ const permissions = objectSchema.permissions;
8318
+ if (!options) {
8319
+ options = {};
8320
+ }
8127
8321
 
8128
- if(_$1.isArray(filter)){
8129
- filter = _$1.map(filter, function(item){
8130
- if(item.operation){
8131
- return [item.field, item.operation, item.value];
8132
- }else {
8133
- return item
8134
- }
8135
- });
8322
+ calendarOptions = Object.assign({}, DEFAULT_CALENDAR_OPTIONS, omitBy(calendarOptions, isNil));
8323
+
8324
+ const titleFields = calendarOptions.title || [
8325
+ calendarOptions.startDateExpr,
8326
+ calendarOptions.endDateExpr,
8327
+ calendarOptions.allDayExpr,
8328
+ calendarOptions.textExpr
8329
+ ];
8330
+ let fields = [];
8331
+ each(titleFields, function (n) {
8332
+ if (objectSchema.fields[n]) {
8333
+ fields.push(objectSchema.fields[n]);
8136
8334
  }
8137
- if(!filter){
8138
- filter = [];
8335
+ });
8336
+
8337
+ if (objectSchema.fields[calendarOptions.allDayExpr]) {
8338
+ fields.push(objectSchema.fields[calendarOptions.allDayExpr]);
8339
+ }
8340
+
8341
+ let sort = options.sort;
8342
+ if (!sort) {
8343
+ const sortField = options.sortField;
8344
+ const sortOrder = options.sortOrder;
8345
+ if (sortField) {
8346
+ let sortStr = sortField + ' ' + sortOrder || 'asc';
8347
+ sort = sortStr;
8139
8348
  }
8140
- let baseFilters = null;
8141
- if(filter){
8142
- baseFilters = filter;
8349
+ }
8350
+ let initialView = calendarOptions.currentView;
8351
+ if (initialView) {
8352
+ // day, week, month, agenda
8353
+ switch (initialView) {
8354
+ case "day":
8355
+ initialView = "timeGridDay";
8356
+ break;
8357
+ case "week":
8358
+ initialView = "timeGridWeek";
8359
+ break;
8360
+ case "month":
8361
+ initialView = "dayGridMonth";
8362
+ break;
8363
+ case "agenda":
8364
+ initialView = "listWeek";
8365
+ break;
8143
8366
  }
8144
- _$1.each(fields,function(field){
8145
- if(field.searchable){
8146
- searchableFields.push(field.name);
8147
- }
8148
- });
8149
-
8150
- const fileFields = {};
8151
- const fileFieldsKeys = [];
8152
- // 含有optionsFunction属性, 无reference_to属性的lookup字段
8153
- const lookupFields = {};
8154
- fields.forEach((item)=>{
8155
- if(_$1.includes(['image','avatar','file'], item.type)){
8156
- fileFieldsKeys.push(item.name);
8157
- fileFields[item.name] = {
8158
- name: item.name,
8159
- type: item.type,
8160
- multiple: item.multiple
8161
- };
8162
- }
8163
- if(_$1.includes(['lookup'], item.type) && !item.reference_to ){
8164
- lookupFields[item.name] = item;
8165
- }
8166
- });
8367
+ }
8368
+ else {
8369
+ initialView = "timeGridWeek";
8370
+ }
8167
8371
 
8168
- let valueField = mainObject.key_field || '_id';
8169
- const api = await getApi(mainObject, null, fields, {count: options.queryCount, alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"`});
8372
+ options.calendarOptions = calendarOptions;
8373
+ const api = await getCalendarApi(objectSchema, fields, options);
8170
8374
 
8171
- if(options.isRelated){
8172
- api.url += "&recordId=${_master.recordId}";
8173
- }
8375
+ const onGetEventsScript = `
8376
+ const api = ${JSON.stringify(api)};
8377
+ event.data.calendarOptions = ${JSON.stringify(calendarOptions)};
8378
+ doAction({
8379
+ "actionType": 'ajax',
8380
+ "args": {
8381
+ "api": api
8382
+ },
8383
+ });
8384
+ `;
8174
8385
 
8175
- api.data.$term = "$term";
8176
- api.data.term = "$term";
8177
- api.data.$self = "$$";
8178
- api.data.self = "$$";
8179
- api.data.filter = "$filter";
8180
- api.data.loaded = "${loaded}";
8181
- api.data.listViewId = "${listViewId}";
8182
- api.data.listName = "${listName}";
8183
- api.requestAdaptor = `
8184
- // selfData 中的数据由 CRUD 控制. selfData中,只能获取到 CRUD 给定的data. 无法从数据链中获取数据.
8185
- let selfData = JSON.parse(JSON.stringify(api.data.$self));
8186
- // 保留一份初始data,以供自定义发送适配器中获取原始数据。
8187
- const data = _.cloneDeep(api.data);
8188
- try{
8189
- // TODO: 不应该直接在这里取localStorage,应该从外面传入
8190
- const listViewId = api.data.listViewId;
8191
- const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
8192
- let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
8193
- if(localListViewProps){
8194
- localListViewProps = JSON.parse(localListViewProps);
8195
- selfData = Object.assign({}, localListViewProps, selfData);
8196
- if(!api.data.filter){
8197
- api.data.filter = localListViewProps.filter;
8198
- }
8199
- if(!api.data.loaded){
8200
- // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
8201
- // 所以会把localSearchableFilter中已经存过的页码覆盖
8202
- // 如果是第一次加载组件始终让翻页页码从本地存储中取值
8203
- let formFactor = "${options.formFactor}";
8204
- // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
8205
- api.data.pageNo = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
8206
- }
8207
- }
8208
- }
8209
- catch(ex){
8210
- console.error("本地存储中crud参数解析异常:", ex);
8211
- }
8212
- ${baseFilters ? `var systemFilters = ${JSON.stringify(baseFilters)};` : 'var systemFilters = [];'}
8213
- var _ids = []
8214
- const filtersFunction = ${filtersFunction};
8215
- if(filtersFunction){
8216
- const _filters = filtersFunction(systemFilters, api.data.$self);
8217
- if(api.data.listName == "recent"){
8218
- _ids = _filters[2]
8219
- }
8220
- if(_filters && _filters.length > 0){
8221
- if(_.isEmpty(systemFilters)){
8222
- systemFilters = _filters || [];
8223
- }else{
8224
- systemFilters = [systemFilters, 'and', _filters];
8386
+ const onSelectScript = `
8387
+ const data = event.data;
8388
+ const doc = {};
8389
+ doc["${calendarOptions.startDateExpr}"] = data.start;
8390
+ doc["${calendarOptions.endDateExpr}"] = data.end;
8391
+ doc["${calendarOptions.allDayExpr}"] = data.allDay;
8392
+ doc["${calendarOptions.textExpr}"] = data.title;
8393
+ // ObjectForm会认作用域下的变量值
8394
+ // TODO: 待组件支持initValues属性后应该改掉,不应该通过data直接传值
8395
+ // TODO: 全天事件属性传入doc了但是没有生效,需要手动在ObjectForm中勾选全天事件
8396
+ const title = "新建 ${objectSchema.label}";
8397
+ doAction(
8398
+ {
8399
+ "actionType": "dialog",
8400
+ "dialog": {
8401
+ "type": "dialog",
8402
+ "title": title,
8403
+ "body": [
8404
+ {
8405
+ "type": "steedos-object-form",
8406
+ "objectApiName": "\${objectName}",
8407
+ "mode": "edit",
8408
+ "defaultData": doc,
8409
+ "onEvent": {
8410
+ "submitSucc": {
8411
+ "weight": 0,
8412
+ "actions": [
8413
+ {
8414
+ "actionType": "custom",
8415
+ "script": "event.data.view?.calendar.refetchEvents();"
8416
+ }
8417
+ ]
8225
8418
  }
8419
+ }
8226
8420
  }
8421
+ ],
8422
+ "closeOnEsc": false,
8423
+ "closeOnOutside": false,
8424
+ "showCloseButton": true,
8425
+ "size": "lg"
8227
8426
  }
8228
- let userFilters =[];
8229
-
8230
- if(_.isEmpty(systemFilters)){
8231
- systemFilters = api.data.filter || [];
8232
- }else{
8233
- if(!_.isEmpty(api.data.filter)){
8234
- systemFilters = [systemFilters, 'and', api.data.filter];
8235
- }
8236
- }
8237
- var pageSize = api.data.pageSize || 10;
8238
- var pageNo = api.data.pageNo || 1;
8239
- var skip = (pageNo - 1) * pageSize;
8240
- var orderBy = api.data.orderBy || '';
8241
- var orderDir = api.data.orderDir || '';
8242
- var sort = orderBy + ' ' + orderDir;
8243
- sort = orderBy ? sort : "${sort || ''}";
8244
- var allowSearchFields = ${JSON.stringify(searchableFields)};
8245
- if(api.data.$term){
8246
- userFilters = [["name", "contains", "'+ api.data.$term +'"]];
8247
- }else if(selfData.op === 'loadOptions' && selfData.value){
8248
- userFilters = [["${valueField.name}", "=", selfData.value]];
8249
- }
8250
-
8251
- var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
8252
-
8253
- if(searchableFilter.length > 0){
8254
- if(userFilters.length > 0 ){
8255
- userFilters = [userFilters, 'and', searchableFilter];
8256
- }else{
8257
- userFilters = searchableFilter;
8258
- }
8259
- }
8427
+ });
8428
+ `;
8260
8429
 
8261
- if(allowSearchFields){
8262
- allowSearchFields.forEach(function(key){
8263
- const keyValue = selfData[key];
8264
- if(_.isString(keyValue)){
8265
- userFilters.push([key, "contains", keyValue]);
8266
- }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8267
- userFilters.push([key, "=", keyValue]);
8268
- }
8269
- })
8270
- }
8430
+ const onEventClickScript = `
8431
+ const data = event.data;
8432
+ const eventData = data.event;
8433
+ const appId = data.appId;
8434
+ const objectName = data.objectName;
8435
+ const eventId = data.event && data.event.id;
8436
+ doAction({
8437
+ "actionType": "dialog",
8438
+ "dialog": {
8439
+ "type": "dialog",
8440
+ "title": "",
8441
+ "body": [
8442
+ {
8443
+ "type": "steedos-record-detail",
8444
+ "objectApiName": "\${objectName}",
8445
+ "recordId": data.event && data.event.id
8446
+ }
8447
+ ],
8448
+ "closeOnEsc": false,
8449
+ "closeOnOutside": false,
8450
+ "showCloseButton": true,
8451
+ "size": "lg",
8452
+ "actions": []
8453
+ }
8454
+ });
8455
+ `;
8271
8456
 
8272
- if(selfData.__keywords && allowSearchFields){
8273
- const keywordsFilters = [];
8274
- allowSearchFields.forEach(function(key, index){
8275
- const keyValue = selfData.__keywords;
8276
- if(keyValue){
8277
- keywordsFilters.push([key, "contains", keyValue]);
8278
- if(index < allowSearchFields.length - 1){
8279
- keywordsFilters.push('or');
8280
- }
8281
- }
8282
- })
8283
- userFilters.push(keywordsFilters);
8284
- };
8457
+ const recordId = "${event.id}";
8458
+ const recordPermissionsApi = getCalendarRecordPermissionsApi(objectSchema, recordId);
8459
+ const recordSaveApi = getCalendarRecordSaveApi(objectSchema, calendarOptions);
8285
8460
 
8286
- let filters = [];
8461
+ const businessHours = {
8462
+ daysOfWeek: [1, 2, 3, 4, 5],
8463
+ startTime: '08:00',
8464
+ endTime: '18:00',
8465
+ };
8466
+ if (!isEmpty(calendarOptions.startDayHour)) {
8467
+ businessHours.startTime = `${calendarOptions.startDayHour}:00`;
8468
+ }
8469
+ if (!isEmpty(calendarOptions.endDayHour)) {
8470
+ businessHours.endTime = `${calendarOptions.endDayHour}:00`;
8471
+ }
8287
8472
 
8288
- if(!_.isEmpty(systemFilters)){
8289
- filters = systemFilters;
8290
- };
8291
- if(api.data.$self.additionalFilters){
8292
- if(_.isString(api.data.$self.additionalFilters)){
8293
- userFilters.push(eval(api.data.$self.additionalFilters))
8294
- }else{
8295
- userFilters.push(api.data.$self.additionalFilters)
8296
- }
8473
+ const onEvent = {
8474
+ "getEvents": {
8475
+ "weight": 0,
8476
+ "actions": [
8477
+ {
8478
+ "componentId": "",
8479
+ "args": {
8480
+ },
8481
+ "actionType": "custom",
8482
+ "script": onGetEventsScript
8297
8483
  }
8298
-
8299
- if(api.data.$self._isRelated){
8300
- const self = api.data.$self;
8301
- const relatedKey = self.relatedKey;
8302
- const refField = self.uiSchema.fields[relatedKey];
8303
- const masterRecord = self._master.record;
8304
- const masterObjectName = self._master.objectName;
8305
- let relatedValue = self._master.recordId;
8306
- if(refField.reference_to_field && refField.reference_to_field != '_id'){
8307
- relatedValue = masterRecord[refField.reference_to_field]
8308
- }
8309
- let relatedFilters;
8310
- if (
8311
- refField._reference_to ||
8312
- (refField.reference_to && !_.isString(refField.reference_to))
8313
- ) {
8314
- relatedFilters = [
8315
- [relatedKey + "/o", "=", masterObjectName],
8316
- [relatedKey + "/ids", "=", relatedValue],
8317
- ];
8318
- } else {
8319
- relatedFilters = [relatedKey, "=", relatedValue];
8320
- }
8321
- userFilters.push(relatedFilters)
8484
+ ]
8485
+ },
8486
+ "select": {
8487
+ "weight": 0,
8488
+ "actions": [
8489
+ {
8490
+ "componentId": "",
8491
+ "args": {
8492
+ },
8493
+ "actionType": "custom",
8494
+ "script": onSelectScript
8322
8495
  }
8323
-
8324
- if(!_.isEmpty(userFilters)){
8325
- if(_.isEmpty(filters)){
8326
- filters = userFilters;
8327
- }else{
8328
- filters = [filters, 'and', userFilters]
8329
- }
8496
+ ]
8497
+ },
8498
+ "eventClick": {
8499
+ "weight": 0,
8500
+ "actions": [
8501
+ {
8502
+ "componentId": "",
8503
+ "args": {
8504
+ },
8505
+ "actionType": "custom",
8506
+ "script": onEventClickScript
8330
8507
  }
8331
- api.data._ids = _ids;
8332
- api.data = {
8333
- query: api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim())
8508
+ ]
8509
+ },
8510
+ "eventAdd": {
8511
+ "weight": 0,
8512
+ "actions": [
8513
+ {
8514
+ "componentId": "",
8515
+ "args": {
8516
+ },
8517
+ "actionType": "custom",
8518
+ "script": "console.log('eventAdd'); console.log(event);"
8334
8519
  }
8335
- ${options.requestAdaptor || ''}
8336
- return api;
8337
- `;
8338
- api.adaptor = `
8339
- if(api.body.listName == "recent"){
8340
- payload.data.rows = _.sortBy(payload.data.rows, function(item){
8341
- return _.indexOf(api.body._ids, item._id)
8342
- });
8343
- }
8344
- const enable_tree = ${mainObject.enable_tree};
8345
- if(!enable_tree){
8346
- _.each(payload.data.rows, function(item, index){
8347
- const {pageNo, pageSize} = api.body;
8348
- const skip = (pageNo - 1) * pageSize;
8349
- item._index = skip + index + 1;
8350
- })
8351
- }
8352
- window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8353
- let fileFields = ${JSON.stringify(fileFields)};
8354
- let lookupFields = ${JSON.stringify(lookupFields)};
8355
- _.each(payload.data.rows, function(item, index){
8356
- _.each(fileFields , (field, key)=>{
8357
- if(item[key] && item._display && item._display[key]){
8358
- let value = item._display[key];
8359
- if(!_.isArray(value)){
8360
- value = [value]
8361
- };
8362
- if(field.type === 'file'){
8363
- item[key] = value
8364
- }else{
8365
- item[key] = _.map(value, 'url')
8366
- }
8367
- }
8368
- })
8369
- _.each(lookupFields , (field, key)=>{
8370
- if(item[key]){
8371
- if(field._optionsFunction){
8372
- const optionsFunction = eval("(" + field._optionsFunction+ ")")(item);
8373
- item[key + '__label'] = _.map(_.filter(optionsFunction, function(option){return _.includes(item[key], option.value)}), 'label').join(' ');
8374
- }
8375
- }
8376
- })
8377
- })
8378
-
8379
- if(enable_tree){
8380
- const records = payload.data.rows || [];
8381
- const getTreeOptions = SteedosUI.getTreeOptions
8382
- payload.data.rows = getTreeOptions(records,{"valueField":"_id"});
8383
- }
8384
-
8385
-
8386
- try{
8387
- // TODO: 不应该直接在这里取localStorage,应该从外面传入
8388
- const listViewId = api.body.listViewId;
8389
- const listViewPropsStoreKey = location.pathname + "/crud/" + listViewId ;
8390
- /**
8391
- * localListViewProps规范来自crud请求api中api.data.$self参数值的。
8392
- * 比如:{"perPage":20,"page":1,"__searchable__name":"7","__searchable__between__n1__c":[null,null],"filter":[["name","contains","a"]]}
8393
- * __searchable__...:顶部放大镜搜索条件
8394
- * filter:右侧过滤器
8395
- * perPage:每页条数
8396
- * page:当前页码
8397
- * orderBy:排序字段
8398
- * orderDir:排序方向
8399
- */
8400
- let localListViewProps = sessionStorage.getItem(listViewPropsStoreKey);
8401
- let selfData = JSON.parse(JSON.stringify(api.body.$self));
8402
- if(localListViewProps){
8403
- localListViewProps = JSON.parse(localListViewProps);
8404
- selfData = Object.assign({}, localListViewProps, selfData, { filter: api.body.filter });
8405
- if(!api.body.loaded){
8406
- // 第一次加载组件,比如刷新浏览器时因为api.data.pageNo有默认值1
8407
- // 所以会把localSearchableFilter中已经存过的页码覆盖
8408
- // 如果是第一次加载组件始终让翻页页码从本地存储中取值
8409
- let formFactor = "${options.formFactor}";
8410
- // 移动端不识别本地存储中的翻页页码,否则点击加载更多按钮后无法刷新回第一页
8411
- selfData.page = formFactor === "SMALL" ? 1 : (localListViewProps.page || 1);
8520
+ ]
8521
+ },
8522
+ "eventChange": {
8523
+ "weight": 0,
8524
+ "actions": [
8525
+ {
8526
+ "actionType": 'ajax',
8527
+ "args": {
8528
+ "api": recordPermissionsApi
8529
+ }
8530
+ },
8531
+ {
8532
+ "actionType": "toast",
8533
+ "expression": "!event.data.editable",
8534
+ "args": {
8535
+ "msgType": "error",
8536
+ "msg": "您没有编辑该记录的权限!",
8537
+ "position": "top-center"
8538
+ }
8539
+ },
8540
+ {
8541
+ "actionType": 'ajax',
8542
+ "expression": "event.data.editable",
8543
+ "args": {
8544
+ "api": recordSaveApi,
8545
+ "messages": {
8546
+ "success": objectSchema.label + "修改成功",
8547
+ "failed": objectSchema.label + "修改失败!"
8412
8548
  }
8549
+ }
8550
+ }
8551
+ ]
8552
+ },
8553
+ "eventRemove": {
8554
+ "weight": 0,
8555
+ "actions": [
8556
+ {
8557
+ "componentId": "",
8558
+ "args": {
8559
+ },
8560
+ "actionType": "custom",
8561
+ "script": "console.log('eventRemove'); console.log(event);"
8562
+ }
8563
+ ]
8564
+ },
8565
+ "eventsSet": {
8566
+ "weight": 0,
8567
+ "actions": [
8568
+ {
8569
+ "componentId": "",
8570
+ "args": {
8571
+ },
8572
+ "actionType": "custom",
8573
+ "script": "console.log('eventsSet'); console.log(event);"
8413
8574
  }
8414
- delete selfData.context;
8415
- delete selfData.global;
8416
- sessionStorage.setItem(listViewPropsStoreKey, JSON.stringify(selfData));
8417
- // 返回页码到UI界面
8418
- payload.data.page= selfData.page;
8419
- }
8420
- catch(ex){
8421
- console.error("本地存储中crud参数解析异常:", ex);
8575
+ ]
8422
8576
  }
8423
- // 标记加载过,后续优先从本地存储中加载相关参数
8424
- payload.data.loaded= true;
8577
+ };
8425
8578
 
8426
- const setDataToComponentId = "${setDataToComponentId}";
8427
- if(setDataToComponentId){
8428
- SteedosUI.getRef(api.body.$self.$scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8429
- };
8430
- ${options.adaptor || ''}
8431
- return payload;
8432
- `;
8433
- return api;
8434
- }
8579
+ Object.assign(onEvent, options.onEvent);
8435
8580
 
8436
- async function getApi(object, recordId, fields, options){
8437
- const data = await getFindQuery(object, recordId, fields, options);
8438
- return {
8439
- method: "post",
8440
- url: getApi$2(), // + "&recordId=${recordId}"
8441
- data: data,
8442
- headers: {
8443
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8444
- }
8581
+ const config = options.config || {};
8582
+ if(config.eventContent && typeof config.eventContent === "string"){
8583
+ const hasReturn = /\breturn\b/.test(config.eventContent);
8584
+ if(hasReturn){
8585
+ try {
8586
+ // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8587
+ let fn = new Function("arg", config.eventContent);
8588
+ config.eventContent = fn;
8589
+ } catch (e) {
8590
+ console.warn(e);
8591
+ }
8445
8592
  }
8446
- }
8593
+ }
8447
8594
 
8448
- function getRecordPermissionsApi(object, recordId, options){
8449
- const data = getRecordPermissionsQuery(object, recordId, options);
8450
- return {
8451
- method: "post",
8452
- url: getApi$2(),
8453
- data: data,
8454
- headers: {
8455
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8456
- }
8595
+ if(config.noEventsContent && typeof config.noEventsContent === "string"){
8596
+ const hasReturn = /\breturn\b/.test(config.noEventsContent);
8597
+ if(hasReturn){
8598
+ try {
8599
+ // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8600
+ let fn = new Function("arg", config.noEventsContent);
8601
+ config.noEventsContent = fn;
8602
+ } catch (e) {
8603
+ console.warn(e);
8604
+ }
8457
8605
  }
8606
+ }
8607
+
8608
+ const amisSchema = {
8609
+ "type": "steedos-fullcalendar",
8610
+ "label": "",
8611
+ "name": "fullcalendar",
8612
+ "placeholder":"${additionalFilters}",//用于触发reload
8613
+ "editable": permissions.allowEdit,
8614
+ "selectable": permissions.allowCreate,
8615
+ "selectMirror": permissions.allowCreate,
8616
+ "initialView": initialView,
8617
+ "businessHours": businessHours,
8618
+ ...config,
8619
+ "onEvent": onEvent
8620
+ };
8621
+ return amisSchema;
8458
8622
  }
8459
8623
 
8460
- const DEFAULT_CALENDAR_OPTIONS = {
8461
- startDateExpr: "start",
8462
- endDateExpr: "end",
8463
- allDayExpr: "is_all_day",
8464
- textExpr: "name"
8624
+ /*
8625
+ * @Author: baozhoutao@steedos.com
8626
+ * @Date: 2022-05-26 16:02:08
8627
+ * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
8628
+ * @LastEditTime: 2023-06-04 15:49:23
8629
+ * @Description:
8630
+ */
8631
+
8632
+ const getFieldSchemaArray = (formFields) => {
8633
+ let fieldSchemaArray = [];
8634
+ fieldSchemaArray.length = 0;
8635
+
8636
+ _$1.forEach(formFields, (field) => {
8637
+ if (!field.group || field.group == 'null' || field.group == '-')
8638
+ field.group = '通用';
8639
+ const fieldName = field.name;
8640
+ let isObjectField = /\w+\.\w+/.test(fieldName);
8641
+ if (field.type == 'grid' || field.type == 'object') {
8642
+ // field.group = field.label
8643
+ field.is_wide = true;
8644
+ }
8645
+
8646
+ if (!isObjectField) {
8647
+ if (!field.hidden) {
8648
+ fieldSchemaArray.push(Object.assign({ name: fieldName }, field, { permission: { allowEdit: true } }));
8649
+ }
8650
+ }
8651
+ });
8652
+ return fieldSchemaArray;
8465
8653
  };
8466
8654
 
8467
- async function getCalendarApi(mainObject, fields, options) {
8468
- if (!options) {
8469
- options = {};
8655
+ const getSection = async (formFields, permissionFields, fieldSchemaArray, sectionName, ctx) => {
8656
+ if (!ctx) {
8657
+ ctx = {};
8470
8658
  }
8471
- const calendarOptions = options.calendarOptions;
8472
- const searchableFields = [];
8473
- let { filter, sort, top, setDataToComponentId = '' } = options;
8474
-
8475
- if (!top) {
8476
- // 日历请求不翻页
8477
- top = 200;
8659
+ const sectionFields = _$1.filter(fieldSchemaArray, { 'group': sectionName });
8660
+ if (sectionFields.length == _$1.filter(sectionFields, ['hidden', true]).length) {
8661
+ return;
8478
8662
  }
8479
8663
 
8480
- if (___default.isArray(filter)) {
8481
- filter = ___default.map(filter, function (item) {
8482
- if (item.operation) {
8483
- return [item.field, item.operation, item.value];
8484
- } else {
8485
- return item
8664
+ const fieldSetBody = [];
8665
+
8666
+ for (const perField of sectionFields) {
8667
+ let field = perField;
8668
+ if (perField.type === 'grid') {
8669
+ field = await getGridFieldSubFields(perField, formFields);
8670
+ // console.log(`perField.type grid ===> field`, field)
8671
+ } else if (perField.type === 'object') {
8672
+ field = await getObjectFieldSubFields(perField, formFields);
8673
+ // console.log(`perField.type object ===> field`, field)
8674
+ }
8675
+ if (field.name.indexOf(".") < 0) {
8676
+ ctx.__formFields = formFields;
8677
+ const amisField = await convertSFieldToAmisField(field, field.readonly, ctx);
8678
+ // console.log(`${field.name} amisField`, field, amisField)
8679
+ if (amisField) {
8680
+ fieldSetBody.push(amisField);
8486
8681
  }
8487
- });
8682
+ }
8488
8683
  }
8489
- if (!filter) {
8490
- filter = [];
8684
+
8685
+ // fieldSet 已支持显隐控制
8686
+ const sectionFieldsVisibleOn = _$1.map(_$1.compact(_$1.map(fieldSetBody, 'visibleOn')), (visibleOn) => {
8687
+ return visibleOn;
8688
+ });
8689
+
8690
+ let section = {
8691
+ "type": "fieldSet",
8692
+ "title": sectionName,
8693
+ "collapsable": true,
8694
+ "body": fieldSetBody,
8695
+ };
8696
+
8697
+ if (ctx.enableTabs) {
8698
+ section = {
8699
+ "title": sectionName,
8700
+ "body": fieldSetBody,
8701
+ };
8491
8702
  }
8492
8703
 
8493
- ___default.each(fields, function (field) {
8494
- if (field.searchable) {
8495
- searchableFields.push(field.name);
8704
+ if (sectionFieldsVisibleOn.length > 0 && fieldSetBody.length === sectionFieldsVisibleOn.length) {
8705
+ section.visibleOn = `${sectionFieldsVisibleOn.join(" || ")}`;
8706
+ }
8707
+ return section
8708
+ };
8709
+
8710
+ const getSections = async (permissionFields, formFields, ctx) => {
8711
+ if (!ctx) {
8712
+ ctx = {};
8713
+ }
8714
+ const fieldSchemaArray = getFieldSchemaArray(formFields);
8715
+ const _sections = _$1.groupBy(fieldSchemaArray, 'group');
8716
+ const sections = [];
8717
+ var sectionVisibleOns = [];
8718
+ for (const key in _sections) {
8719
+ const section = await getSection(formFields, permissionFields, fieldSchemaArray, key, ctx);
8720
+ if (section.body.length > 0) {
8721
+ if (section.visibleOn) {
8722
+ sectionVisibleOns.push(section.visibleOn);
8723
+ }
8724
+ else {
8725
+ sectionVisibleOns.push("true");
8726
+ }
8727
+ sections.push(section);
8496
8728
  }
8729
+ }
8730
+ /*
8731
+ 为了实现只有一个分组时隐藏该分组标题,需要分三种情况(分组如果没有visibleon属性就代表一定显示,有visibleon需要进行判断)
8732
+ 1 当前分组为隐藏时,标题就设置为隐藏
8733
+ 2 当前分组为显示时,其他分组只要有一个是显示,就显示该分组标题
8734
+ 3 当前分组为显示时,其他分组都隐藏,就隐藏该分组标题
8735
+ */
8736
+ sections.forEach((section, index) => {
8737
+ var tempSectionVisibleOns = sectionVisibleOns.slice();
8738
+ tempSectionVisibleOns.splice(index, 1);
8739
+ section.headingClassName = {
8740
+ "hidden": `!((${tempSectionVisibleOns.join(" || ") || 'false'}) && ${sectionVisibleOns[index]})`
8741
+ };
8497
8742
  });
8498
8743
 
8499
- const idFieldName = mainObject.idFieldName || "_id";
8500
- let valueField = mainObject.key_field || '_id';
8501
- const api = await getApi(mainObject, null, fields, { alias: 'rows', limit: top, queryOptions: `filters: {__filters}, top: {__top}, skip: {__skip}, sort: "{__sort}"` });
8502
- api.data.$term = "$term";
8503
- api.data.$self = "$$";
8504
- api.data.filter = "$filter";
8505
- api.data.pageSize = top || 10;
8506
- api.requestAdaptor = `
8507
- let selfData = JSON.parse(JSON.stringify(api.data.$self));
8508
- var filters = api.data.filter || ${JSON.stringify(filter)} || [];
8509
- const eventFetchInfo = selfData.fetchInfo;
8510
- const startDateExpr = "${calendarOptions.startDateExpr}";
8511
- const endDateExpr = "${calendarOptions.endDateExpr}";
8512
- const eventDurationFilters = [[endDateExpr, ">=", eventFetchInfo.start], [startDateExpr, "<=", eventFetchInfo.end]];
8513
- if(_.isEmpty(filters)){
8514
- filters = eventDurationFilters;
8515
- }else{
8516
- filters = [filters, 'and', eventDurationFilters]
8517
- }
8744
+ if (ctx.enableTabs) {
8745
+ // TODO: 以下sectionHeaderVisibleOn代码逻辑是为实现只有一个选项卡时给选项卡添加sectionHeaderVisibleOn样式类来把选项卡顶部卡头隐藏
8746
+ // 但是 amis filter过滤器有两个bug造成此功能不好实现:
8747
+ // 1.filter过滤器只支持对象数组,并不支持boolean或字符串数组,见: https://github.com/baidu/amis/issues/7078
8748
+ // 2.filter过滤器的返回结果无法进一步获取最终过滤后的数组长度,见:https://github.com/baidu/amis/issues/7077
8749
+ // let sectionHeaderVisibleOn = "false";
8750
+ // if(sectionVisibleOns.length){
8751
+ // sectionHeaderVisibleOn = "[" + sectionVisibleOns.join(",") + "]" + "|filter:equals:true.length > 1";
8752
+ // }
8753
+ // console.log("===sectionHeaderVisibleOn===", sectionHeaderVisibleOn);
8754
+ // sectionHeaderVisibleOn = "[true]|filter:equals:true.length > 1";
8755
+ // sectionHeaderVisibleOn = "false";
8756
+ // sectionHeaderVisibleOn = "[1,1,1]|filter:equals:1.length > 1";
8757
+ return [
8758
+ {
8759
+ "type": "tabs",
8760
+ // "className": {
8761
+ // "hiddenFormTabs": `!(${sectionHeaderVisibleOn})`
8762
+ // },
8763
+ "tabs": sections,
8764
+ "tabsMode": ctx.tabsMode
8765
+ }
8766
+ ]
8767
+ }
8768
+
8769
+ return sections;
8770
+ };
8771
+
8772
+ /*
8773
+ * @Author: baozhoutao@steedos.com
8774
+ * @Date: 2022-07-07 11:02:29
8775
+ * @LastEditors: baozhoutao@steedos.com
8776
+ * @LastEditTime: 2023-03-07 17:19:34
8777
+ * @Description:
8778
+ */
8779
+
8780
+ async function getFormBody(permissionFields, formFields, ctx){
8781
+ return await getSections(permissionFields, formFields, ctx);
8782
+ }
8783
+
8784
+ // lodash的defaultsDeep函数有bug,无法正确合并值为数值的节点,重写修正该函数
8785
+ // 源码出处:https://github.com/nodeutils/defaults-deep
8786
+ const defaultsDeep = (...args)=>{
8787
+ let output = {};
8788
+ toArray(args).reverse().forEach(item=> {
8789
+ mergeWith(output, item, (objectValue, sourceValue) => {
8790
+ return isArray(sourceValue) ? sourceValue : undefined;
8791
+ });
8792
+ });
8793
+ return output;
8794
+ };
8795
+
8796
+ function getBulkActions(objectSchema){
8797
+ return [
8798
+ {
8799
+ "type": "button",
8800
+ "level": "danger",
8801
+ "label": "批量删除",
8802
+ "actionType": "ajax",
8803
+ "confirmText": "确定要删除吗",
8804
+ "className": "hidden",
8805
+ "id": "batchDelete",
8806
+ "api": getBatchDelete(objectSchema.name),
8807
+ }
8808
+ // {
8809
+ // "label": "批量修改",
8810
+ // "actionType": "dialog",
8811
+ // "dialog": {
8812
+ // "title": "批量编辑",
8813
+ // "name": "sample-bulk-edit",
8814
+ // "body": {
8815
+ // "type": "form",
8816
+ // "api": "https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/sample/bulkUpdate2",
8817
+ // "controls": [
8818
+ // {
8819
+ // "type": "hidden",
8820
+ // "name": "ids"
8821
+ // },
8822
+ // {
8823
+ // "type": "text",
8824
+ // "name": "name",
8825
+ // "label": "Name"
8826
+ // }
8827
+ // ]
8828
+ // }
8829
+ // }
8830
+ // }
8831
+ ]
8832
+ }
8518
8833
 
8519
- if(api.data.$self.additionalFilters){
8520
- filters.push(api.data.$self.additionalFilters)
8834
+ async function getObjectCRUD(objectSchema, fields, options){
8835
+ // console.time('getObjectCRUD');
8836
+ const { top, perPage, showDisplayAs = false, displayAs, crudClassName = "" } = options;
8837
+ const nonpaged = objectSchema.paging && objectSchema.paging.enabled === false;
8838
+ const isTreeObject = objectSchema.enable_tree;
8839
+ const bulkActions = getBulkActions(objectSchema);
8840
+ const bodyProps = {
8841
+ // toolbar: getToolbar(),
8842
+ // headerToolbar: getObjectHeaderToolbar(objectSchema, options.formFactor, {showDisplayAs}),
8843
+ headerToolbarClassName: "px-4 py-2 border-gray-300 bg-gray-100 border-solid border-b",
8844
+ footerToolbar: getObjectFooterToolbar(objectSchema, options.formFactor, {
8845
+ disableStatistics: options.queryCount === false
8846
+ }),
8847
+ filter: options.filterVisible !== false && await getObjectFilter(objectSchema, fields, options),
8848
+ };
8849
+ if(options.formFactor !== 'SMALL' || ["split"].indexOf(options.displayAs) == -1){
8850
+ Object.assign(bodyProps, {
8851
+ bulkActions: options.bulkActions != false ? bulkActions : false
8852
+ });
8521
8853
  }
8522
-
8523
- var pageSize = api.data.pageSize || 10;
8524
- var pageNo = api.data.pageNo || 1;
8525
- var skip = (pageNo - 1) * pageSize;
8526
- var orderBy = api.data.orderBy || '';
8527
- var orderDir = api.data.orderDir || '';
8528
- var sort = orderBy + ' ' + orderDir;
8529
- sort = orderBy ? sort : "${sort}";
8530
- var allowSearchFields = ${JSON.stringify(searchableFields)};
8531
- if(api.data.$term){
8532
- filters = [["name", "contains", "'+ api.data.$term +'"]];
8533
- }else if(selfData.op === 'loadOptions' && selfData.value){
8534
- filters = [["${valueField.name}", "=", selfData.value]];
8854
+ // yml里配置的 不分页和enable_tree:true 优先级最高,组件中输入的top次之。
8855
+ options.queryCount = true;
8856
+ if(nonpaged || isTreeObject){
8857
+ options.top = 5000;
8858
+ bodyProps.footerToolbar = [];
8859
+ options.queryCount = true; // 禁止翻页的时候, 需要查找总数
8860
+ }else if(top){
8861
+ bodyProps.footerToolbar = [];
8862
+ if(options.isRelated){
8863
+ options.queryCount = true;
8864
+ }else {
8865
+ options.queryCount = false;
8866
+ }
8535
8867
  }
8536
- var searchableFilter = SteedosUI.getSearchFilter(selfData) || [];
8868
+ // console.log(`getObjectHeaderToolbar====2===>`, options.filterVisible)
8869
+ bodyProps.headerToolbar = getObjectHeaderToolbar(objectSchema, options.formFactor, {
8870
+ showDisplayAs,
8871
+ hiddenCount: options.queryCount === false,
8872
+ headerToolbarItems: options.headerToolbarItems,
8873
+ filterVisible: options.filterVisible
8874
+ });
8537
8875
 
8538
- if(searchableFilter.length > 0){
8539
- if(filters.length > 0 ){
8540
- filters = [filters, 'and', searchableFilter];
8541
- }else{
8542
- filters = searchableFilter;
8543
- }
8544
- }
8545
8876
 
8546
- if(allowSearchFields){
8547
- allowSearchFields.forEach(function(key){
8548
- const keyValue = selfData[key];
8549
- if(_.isString(keyValue)){
8550
- filters.push([key, "contains", keyValue]);
8551
- }else if(_.isArray(keyValue) || _.isBoolean(keyValue) || keyValue){
8552
- filters.push([key, "=", keyValue]);
8877
+ let body = null;
8878
+ const id = `listview_${objectSchema.name}`;
8879
+ if(options.formFactor === 'SMALL' && false){
8880
+ delete bodyProps.bulkActions;
8881
+ delete bodyProps.headerToolbar;
8882
+ delete bodyProps.footerToolbar;
8883
+ const card = await getCardSchema(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: objectSchema.NAME_FIELD_KEY || 'name'}, options, {actions: false}));
8884
+ body = Object.assign({}, card , {
8885
+ type: 'crud',
8886
+ primaryField: '_id',
8887
+ id: id,
8888
+ name: id,
8889
+ keepItemSelectionOnPageChange: false,
8890
+ api: await getTableApi(objectSchema, fields, options),
8891
+ hiddenOn: options.tableHiddenOn,
8892
+ },
8893
+ bodyProps
8894
+ );
8895
+ }else {
8896
+ let labelFieldName = objectSchema.NAME_FIELD_KEY || 'name';
8897
+ // organizations 对象的历史遗留问题, fullname 被标记为了 名称字段. 在此处特殊处理.
8898
+ if(objectSchema.name === 'organizations'){
8899
+ labelFieldName = 'name';
8900
+ }
8901
+ const table = await getTableSchema$1(fields, Object.assign({idFieldName: objectSchema.idFieldName, labelFieldName: labelFieldName, permissions:objectSchema.permissions,enable_inline_edit:objectSchema.enable_inline_edit}, options));
8902
+ delete table.mode;
8903
+ //image与avatar需要在提交修改时特别处理
8904
+ const imageNames = ___default.compact(___default.map(___default.filter(fields, (field) => ["image","avatar"].includes(field.type)), 'name'));
8905
+ const quickSaveApiRequestAdaptor = `
8906
+ var graphqlOrder = "";
8907
+ var imageNames = ${JSON.stringify(imageNames)};
8908
+ api.data.rowsDiff.forEach(function (item, index) {
8909
+ for(key in item){
8910
+ if(_.includes(imageNames, key)){
8911
+ if(typeof item[key] == "string"){
8912
+ const match = item[key].match(/\\/([^\\/]+)$/);
8913
+ item[key] = match && match.length > 1?match[1]:"";
8914
+ }else{
8915
+ item[key] = _.map(item[key], function(ele){
8916
+ const match = ele.match(/\\/([^\\/]+)$/);
8917
+ return match && match.length > 1?match[1]:"";
8918
+ })
8919
+ }
8553
8920
  }
8921
+ }
8922
+ const itemOrder = 'update' + index + ':' + api.data.objectName + '__update(id:"' + item._id + '", doc:' + JSON.stringify(JSON.stringify(_.omit(item, '_id'))) + ') {_id}';
8923
+ graphqlOrder += itemOrder;
8554
8924
  })
8555
- }
8556
-
8557
- if(selfData.__keywords && allowSearchFields){
8558
- const keywordsFilters = [];
8559
- allowSearchFields.forEach(function(key, index){
8560
- const keyValue = selfData.__keywords;
8561
- if(keyValue){
8562
- keywordsFilters.push([key, "contains", keyValue]);
8563
- if(index < allowSearchFields.length - 1){
8564
- keywordsFilters.push('or');
8565
- }
8925
+ graphqlOrder = 'mutation {' + graphqlOrder + '}';
8926
+ return {
8927
+ ...api,
8928
+ data: {
8929
+ query: graphqlOrder
8566
8930
  }
8567
- })
8568
- filters.push(keywordsFilters);
8569
- }
8570
- api.data.query = api.data.query.replace(/{__filters}/g, JSON.stringify(filters)).replace('{__top}', pageSize).replace('{__skip}', skip).replace('{__sort}', sort.trim());
8571
- delete api.data.$term;
8572
- delete api.data.filter;
8573
- delete api.data.pageSize;
8574
- delete api.data.pageNo;
8575
- delete api.data.orderBy;
8576
- delete api.data.orderDir;
8577
- return api;
8578
- `;
8579
- api.adaptor = `
8580
- window.postMessage(Object.assign({type: "listview.loaded"}), "*");
8581
- const setDataToComponentId = "${setDataToComponentId}";
8582
- if(setDataToComponentId){
8583
- SteedosUI.getRef(api.body.$self.scopeId)?.getComponentById(setDataToComponentId)?.setData({$count: payload.data.count})
8584
- }
8585
- const rows = payload.data.rows || [];
8586
- const selfData = api.data.$self;
8587
- const events = rows.map(function(n){
8588
- return {
8589
- id: n["${idFieldName}"],
8590
- title: n["${calendarOptions.textExpr}"],
8591
- start: n["${calendarOptions.startDateExpr}"],
8592
- end: n["${calendarOptions.endDateExpr}"],
8593
- allDay: n["${calendarOptions.allDayExpr}"],
8594
- extendedProps: n
8595
- }
8596
- });
8597
- const successCallback = selfData.successCallback;
8598
- const failureCallback = selfData.failureCallback;
8599
- successCallback(events);
8600
- return payload;
8601
- `;
8602
- return api;
8603
- }
8931
+ }
8932
+ `;
8604
8933
 
8605
- function getCalendarRecordPermissionsApi(mainObject, recordId) {
8606
- const api = getRecordPermissionsApi(mainObject, recordId, { alias: 'rows', limit: 1, fields: ["allowEdit"] });
8607
- api.data.$self = "$$";
8608
- api.adaptor = `
8609
- const rows = payload.data.rows || [];
8610
- const selfData = api.data.$self;
8611
- const revert = selfData.revert;
8612
- const recordPermissions = rows[0] && rows[0].recordPermissions;
8613
- const editable = !!(recordPermissions && recordPermissions.allowEdit);
8614
- if(!editable){
8615
- // 没有权限时还原
8616
- revert && revert();
8934
+ body = Object.assign({}, table, {
8935
+ type: 'crud',
8936
+ primaryField: '_id',
8937
+ affixHeader: false,
8938
+ id: id,
8939
+ name: id,
8940
+ keepItemSelectionOnPageChange: true,
8941
+ api: await getTableApi(objectSchema, fields, options),
8942
+ hiddenOn: options.tableHiddenOn,
8943
+ autoFillHeight: options.isRelated ? false : true,
8944
+ className: `flex-auto ${crudClassName || ""}`,
8945
+ bodyClassName: "bg-white",
8946
+ crudClassName: crudClassName,
8947
+ quickSaveApi: {
8948
+ url: `\${context.rootUrl}/graphql`,
8949
+ method: "post",
8950
+ dataType: "json",
8951
+ headers: {
8952
+ Authorization: "Bearer ${context.tenantId},${context.authToken}",
8953
+ },
8954
+ requestAdaptor: quickSaveApiRequestAdaptor,
8955
+ },
8956
+ rowClassNameExpr: options.rowClassNameExpr
8957
+ },
8958
+ bodyProps,
8959
+ );
8617
8960
  }
8618
- payload.data.editable = editable;
8619
- return payload;
8620
- `;
8621
- return api;
8622
- }
8623
-
8624
- function getCalendarRecordSaveApi(object, calendarOptions) {
8625
- const formData = {};
8626
- const idFieldName = object.idFieldName || "_id";
8627
- formData[idFieldName] = "${event.data.event.id}";
8628
- const nameFieldKey = object.NAME_FIELD_KEY || "name";
8629
- formData[nameFieldKey] = "${event.data.event.title}";
8630
- formData[calendarOptions.startDateExpr] = "${event.data.event.start}";
8631
- formData[calendarOptions.endDateExpr] = "${event.data.event.end}";
8632
- formData[calendarOptions.allDayExpr] = "${event.data.event.allDay}";
8633
- // formData[calendarOptions.textExpr] = "${event.data.event.title}";
8634
- const apiData = {
8635
- objectName: "${objectName}",
8636
- $: formData,
8637
- $self: "$$"
8638
- };
8639
- const saveDataTpl = `
8640
- const formData = api.data.$;
8641
- const objectName = api.data.objectName;
8642
- let query = \`mutation{record: \${objectName}__update(id: "\${formData.${idFieldName}}", doc: {__saveData}){${idFieldName}}}\`;
8643
- delete formData.${idFieldName};
8644
- let __saveData = JSON.stringify(JSON.stringify(formData));
8645
- `;
8646
- const requestAdaptor = `
8647
- ${saveDataTpl}
8648
- api.data.query = query.replace('{__saveData}', __saveData);
8649
- return api;
8650
- `;
8651
8961
 
8652
- return {
8653
- method: 'post',
8654
- url: getApi$2(),
8655
- data: apiData,
8656
- requestAdaptor: requestAdaptor,
8657
- adaptor: `
8658
- if(payload.errors){
8659
- payload.status = 2;
8660
- payload.msg = payload.errors[0].message;
8661
- const revert = api.data.$self.event.data.revert;
8662
- revert && revert();
8962
+ const defaults = options.defaults;
8963
+ if (defaults) {
8964
+ const listSchema = defaults.listSchema || {};
8965
+ body = defaultsDeep({}, listSchema, body);
8966
+ const headerSchema = defaults.headerSchema;
8967
+ const footerSchema = defaults.footerSchema;
8968
+ if (headerSchema || footerSchema) {
8969
+ let wrappedBody = [body];
8970
+ if (headerSchema) {
8971
+ if(___default.isArray(headerSchema)){
8972
+ wrappedBody = ___default.union(headerSchema,wrappedBody);
8973
+ }
8974
+ else {
8975
+ wrappedBody.unshift(headerSchema);
8976
+ }
8663
8977
  }
8664
- return payload;
8665
- `,
8666
- headers: {
8667
- Authorization: "Bearer ${context.tenantId},${context.authToken}"
8978
+ if (footerSchema) {
8979
+ if(___default.isArray(footerSchema)){
8980
+ wrappedBody = ___default.union(wrappedBody,footerSchema);
8981
+ }
8982
+ else {
8983
+ wrappedBody.push(footerSchema);
8984
+ }
8985
+ }
8986
+ body = wrappedBody;
8987
+ }
8988
+ }
8989
+ // console.timeEnd('getObjectCRUD');
8990
+ // TODO: data应该只留loaded,其他属性都改为从上层传递下来
8991
+ return {
8992
+ type: 'service',
8993
+ className: '',
8994
+ id: `service_${id}`,
8995
+ name: `page`,
8996
+ data: {
8997
+ objectName: objectSchema.name,
8998
+ // _id: null,
8999
+ recordPermissions: objectSchema.permissions,
9000
+ uiSchema: objectSchema,
9001
+ // loaded: false //crud接收适配器中设置为true,否则就是刷新浏览器第一次加载
9002
+ },
9003
+ body: body
8668
9004
  }
8669
- };
8670
9005
  }
8671
9006
 
8672
- /**
8673
- * 列表视图Calendar amisSchema
8674
- * @param {*} objectSchema 对象UISchema
8675
- * @returns amisSchema
8676
- */
8677
- async function getObjectCalendar(objectSchema, calendarOptions, options) {
8678
- const permissions = objectSchema.permissions;
8679
- if (!options) {
8680
- options = {};
8681
- }
8682
-
8683
- calendarOptions = Object.assign({}, DEFAULT_CALENDAR_OPTIONS, omitBy(calendarOptions, isNil));
9007
+ const getGlobalData = (mode)=>{
9008
+ const user = getSteedosAuth();
9009
+ return {mode: mode, user: user, spaceId: user.spaceId, userId: user.userId}
9010
+ };
8684
9011
 
8685
- const titleFields = calendarOptions.title || [
8686
- calendarOptions.startDateExpr,
8687
- calendarOptions.endDateExpr,
8688
- calendarOptions.allDayExpr,
8689
- calendarOptions.textExpr
8690
- ];
8691
- let fields = [];
8692
- each(titleFields, function (n) {
8693
- if (objectSchema.fields[n]) {
8694
- fields.push(objectSchema.fields[n]);
9012
+ const getFormFields = (objectSchema, formProps)=>{
9013
+ /**
9014
+ * fieldsExtend: 重写字段定义
9015
+ * fields: 包含的字段
9016
+ * excludedFields: 排除的字段
9017
+ */
9018
+ const { fieldsExtend, fields: includedFields, excludedFields } = formProps;
9019
+
9020
+ let fields = {};
9021
+ // 以uiSchema fields 为基础, 遍历字段, 并更新字段定义
9022
+ ___default.forEach(objectSchema.fields, (field, fieldName)=>{
9023
+ if(!lodash.has(field, "name")){
9024
+ field.name = fieldName;
9025
+ }
9026
+ if(fieldsExtend && fieldsExtend[fieldName]){
9027
+ fields[field.name] = Object.assign({}, field, fieldsExtend[fieldName], {name: field.name});
9028
+ }else {
9029
+ fields[field.name] = field;
8695
9030
  }
8696
9031
  });
8697
9032
 
8698
- if (objectSchema.fields[calendarOptions.allDayExpr]) {
8699
- fields.push(objectSchema.fields[calendarOptions.allDayExpr]);
9033
+ if(!___default.isEmpty(includedFields) && ___default.isArray(includedFields)){
9034
+ const includedFieldsMap = {};
9035
+ ___default.each(includedFields, (fName, index)=>{
9036
+ if(fields[fName]){
9037
+ includedFieldsMap[fName] = Object.assign({}, fields[fName], {sort_no: index});
9038
+ }
9039
+ });
9040
+ fields = includedFieldsMap;
8700
9041
  }
8701
9042
 
8702
- let sort = options.sort;
8703
- if (!sort) {
8704
- const sortField = options.sortField;
8705
- const sortOrder = options.sortOrder;
8706
- if (sortField) {
8707
- let sortStr = sortField + ' ' + sortOrder || 'asc';
8708
- sort = sortStr;
8709
- }
8710
- }
8711
- let initialView = calendarOptions.currentView;
8712
- if (initialView) {
8713
- // day, week, month, agenda
8714
- switch (initialView) {
8715
- case "day":
8716
- initialView = "timeGridDay";
8717
- break;
8718
- case "week":
8719
- initialView = "timeGridWeek";
8720
- break;
8721
- case "month":
8722
- initialView = "dayGridMonth";
8723
- break;
8724
- case "agenda":
8725
- initialView = "listWeek";
8726
- break;
8727
- }
8728
- }
8729
- else {
8730
- initialView = "timeGridWeek";
9043
+ if(!___default.isEmpty(excludedFields) && ___default.isArray(excludedFields)){
9044
+ ___default.each(excludedFields, (fName)=>{
9045
+ delete fields[fName];
9046
+ });
8731
9047
  }
8732
9048
 
8733
- options.calendarOptions = calendarOptions;
8734
- const api = await getCalendarApi(objectSchema, fields, options);
9049
+ return lodash.sortBy(___default.values(fields), "sort_no");
9050
+ };
8735
9051
 
8736
- const onGetEventsScript = `
8737
- const api = ${JSON.stringify(api)};
8738
- event.data.calendarOptions = ${JSON.stringify(calendarOptions)};
8739
- doAction({
8740
- "actionType": 'ajax',
8741
- "args": {
8742
- "api": api
9052
+ async function getObjectForm(objectSchema, ctx){
9053
+ const { recordId, formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, tabId, appId, defaults } = ctx;
9054
+ const fields = ___default.values(objectSchema.fields);
9055
+ const formFields = getFormFields(objectSchema, ctx);
9056
+ const formSchema = defaults && defaults.formSchema || {};
9057
+ if(___default.has(formSchema, 'className')){
9058
+ formSchema.className = 'steedos-amis-form';
9059
+ }
9060
+ const amisSchema = {
9061
+ type: 'service',
9062
+ className: 'p-0',
9063
+ name: `page_edit_${recordId}`,
9064
+ api: await getEditFormInitApi(objectSchema, recordId, fields, ctx),
9065
+ data:{
9066
+ editFormInited: false
8743
9067
  },
8744
- });
8745
- `;
9068
+ // data: {global: getGlobalData('edit'), recordId: recordId, objectName: objectSchema.name, context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
9069
+ initApi: null,
9070
+ initFetch: null ,
9071
+ body: [defaultsDeep({}, formSchema, {
9072
+ type: "form",
9073
+ mode: layout,
9074
+ data: {
9075
+ "&": "${initialValues}"
9076
+ },
9077
+ labelAlign,
9078
+ persistData: false,
9079
+ resetAfterSubmit: true,
9080
+ preventEnterSubmit: true,
9081
+ promptPageLeave: true,
9082
+ canAccessSuperData: false,
9083
+ name: `form_edit_${recordId}`,
9084
+ debug: false,
9085
+ title: "",
9086
+ submitText: "", // amis 表单不显示提交按钮, 表单提交由项目代码接管
9087
+ api: await getSaveApi(objectSchema, recordId, fields, ctx),
9088
+ initFetch: recordId != 'new',
9089
+ body: await getFormBody(fields, formFields, ctx),
9090
+ panelClassName:'m-0 sm:rounded-lg shadow-none border-none',
9091
+ bodyClassName: 'p-0',
9092
+ className: 'steedos-amis-form',
9093
+ hiddenOn: "${editFormInited != true}",
9094
+ onEvent: {
9095
+ "submitSucc": {
9096
+ "weight": 0,
9097
+ "actions": [
9098
+ {
9099
+ "actionType": "broadcast",
9100
+ "args": {
9101
+ "eventName": `@data.changed.${objectSchema.name}`
9102
+ },
9103
+ "data": {
9104
+ "objectName": `${objectSchema.name}`,
9105
+ "displayAs": "${displayAs}"
9106
+ }
9107
+ },
9108
+ {
9109
+ "actionType": "broadcast",
9110
+ "args": {
9111
+ "eventName": "@data.changed.${_master.objectName}"
9112
+ },
9113
+ "data": {
9114
+ "objectName": "${_master.objectName}",
9115
+ "_isRelated": "${_isRelated || _master._isRelated}"
9116
+ },
9117
+ "expression": `\${_master.objectName != '${objectSchema.name}' && _master.objectName}`
9118
+ },
9119
+ // {
9120
+ // "actionType": "custom",
9121
+ // "script": "debugger;"
9122
+ // },
9123
+ // {
9124
+ // "args": {},
9125
+ // "actionType": "closeDialog"
9126
+ // }
9127
+ ]
9128
+ }
9129
+ }
9130
+ })]
9131
+ };
9132
+ if(formSchema.id){
9133
+ amisSchema.id = `service-${formSchema.id}`;
9134
+ }
9135
+ return amisSchema;
9136
+ }
8746
9137
 
8747
- const onSelectScript = `
8748
- const data = event.data;
8749
- const doc = {};
8750
- doc["${calendarOptions.startDateExpr}"] = data.start;
8751
- doc["${calendarOptions.endDateExpr}"] = data.end;
8752
- doc["${calendarOptions.allDayExpr}"] = data.allDay;
8753
- doc["${calendarOptions.textExpr}"] = data.title;
8754
- // ObjectForm会认作用域下的变量值
8755
- // TODO: 待组件支持initValues属性后应该改掉,不应该通过data直接传值
8756
- // TODO: 全天事件属性传入doc了但是没有生效,需要手动在ObjectForm中勾选全天事件
8757
- const title = "新建 ${objectSchema.label}";
8758
- doAction(
8759
- {
8760
- "actionType": "dialog",
8761
- "dialog": {
8762
- "type": "dialog",
8763
- "title": title,
8764
- "body": [
8765
- {
8766
- "type": "steedos-object-form",
8767
- "objectApiName": "\${objectName}",
8768
- "mode": "edit",
8769
- "defaultData": doc,
8770
- "onEvent": {
8771
- "submitSucc": {
8772
- "weight": 0,
9138
+ async function getObjectDetail(objectSchema, recordId, ctx){
9139
+ const { formFactor, layout = formFactor === 'SMALL' ? 'normal' : "normal", labelAlign, formInitProps } = ctx;
9140
+ const fields = ___default.values(objectSchema.fields);
9141
+ const formFields = getFormFields(objectSchema, ctx);
9142
+ const serviceId = `service_detail_page`;
9143
+ return {
9144
+ type: 'service',
9145
+ name: `page_readonly_${recordId}`,
9146
+ id: serviceId,
9147
+ data: {global: getGlobalData('read'), context: {rootUrl: getRootUrl(), tenantId: getTenantId(), authToken: getAuthToken()}},
9148
+ api: await getReadonlyFormInitApi(objectSchema, recordId, fields, formInitProps),
9149
+ body: [
9150
+ {
9151
+ "type": "wrapper", //form 的 hiddenOn 会导致 form onEvent 异常, 使用wrapper包裹一次form,并在wrapper上控制显隐
9152
+ hiddenOn: "${recordLoaded != true}",
9153
+ "className": "p-0 m-0",
9154
+ "body": {
9155
+ type: "form",
9156
+ mode: layout,
9157
+ labelAlign,
9158
+ persistData: false,
9159
+ promptPageLeave: false,
9160
+ name: `form_readonly_${recordId}`,
9161
+ debug: false,
9162
+ title: "",
9163
+ data: {
9164
+ "formData": "$$"
9165
+ },
9166
+ wrapWithPanel: false,
9167
+ body: await getFormBody(map(fields, (field)=>{field.readonly = true; return field;}), map(formFields, (field)=>{field.readonly = true; return field;}), Object.assign({}, ctx, {showSystemFields: true})),
9168
+ className: 'steedos-amis-form bg-white',
9169
+ actions: [], // 不显示表单默认的提交按钮
9170
+ onEvent: {
9171
+ [`@data.changed.${objectSchema.name}`]: { // 由于amis service 组件的 onEvent 存在bug ,此处借助form来刷新 上层 service https://github.com/baidu/amis/issues/6294
8773
9172
  "actions": [
8774
9173
  {
9174
+ "actionType": "reload",
9175
+ "componentId": serviceId,
9176
+ "expression": "this.__deletedRecord != true"
9177
+ },
9178
+ {
9179
+ // "args": {
9180
+ // "url": "/app/${appId}/${objectName}/grid/${side_listview_id}",
9181
+ // "blank": false
9182
+ // },
8775
9183
  "actionType": "custom",
8776
- "script": "event.data.view?.calendar.refetchEvents();"
9184
+ "script": "Steedos.goBack()",
9185
+ "expression": "this.__deletedRecord === true"
8777
9186
  }
8778
9187
  ]
8779
9188
  }
8780
9189
  }
8781
- }
8782
- ],
8783
- "closeOnEsc": false,
8784
- "closeOnOutside": false,
8785
- "showCloseButton": true,
8786
- "size": "lg"
8787
- }
8788
- });
8789
- `;
8790
-
8791
- const onEventClickScript = `
8792
- const data = event.data;
8793
- const eventData = data.event;
8794
- const appId = data.appId;
8795
- const objectName = data.objectName;
8796
- const eventId = data.event && data.event.id;
8797
- doAction({
8798
- "actionType": "dialog",
8799
- "dialog": {
8800
- "type": "dialog",
8801
- "title": "",
8802
- "body": [
8803
- {
8804
- "type": "steedos-record-detail",
8805
- "objectApiName": "\${objectName}",
8806
- "recordId": data.event && data.event.id
8807
- }
8808
- ],
8809
- "closeOnEsc": false,
8810
- "closeOnOutside": false,
8811
- "showCloseButton": true,
8812
- "size": "lg",
8813
- "actions": []
8814
- }
8815
- });
8816
- `;
8817
-
8818
- const recordId = "${event.id}";
8819
- const recordPermissionsApi = getCalendarRecordPermissionsApi(objectSchema, recordId);
8820
- const recordSaveApi = getCalendarRecordSaveApi(objectSchema, calendarOptions);
8821
-
8822
- const businessHours = {
8823
- daysOfWeek: [1, 2, 3, 4, 5],
8824
- startTime: '08:00',
8825
- endTime: '18:00',
8826
- };
8827
- if (!isEmpty(calendarOptions.startDayHour)) {
8828
- businessHours.startTime = `${calendarOptions.startDayHour}:00`;
8829
- }
8830
- if (!isEmpty(calendarOptions.endDayHour)) {
8831
- businessHours.endTime = `${calendarOptions.endDayHour}:00`;
8832
- }
8833
-
8834
- const onEvent = {
8835
- "getEvents": {
8836
- "weight": 0,
8837
- "actions": [
8838
- {
8839
- "componentId": "",
8840
- "args": {
8841
- },
8842
- "actionType": "custom",
8843
- "script": onGetEventsScript
8844
- }
8845
- ]
8846
- },
8847
- "select": {
8848
- "weight": 0,
8849
- "actions": [
8850
- {
8851
- "componentId": "",
8852
- "args": {
8853
- },
8854
- "actionType": "custom",
8855
- "script": onSelectScript
8856
- }
8857
- ]
8858
- },
8859
- "eventClick": {
8860
- "weight": 0,
8861
- "actions": [
8862
- {
8863
- "componentId": "",
8864
- "args": {
8865
- },
8866
- "actionType": "custom",
8867
- "script": onEventClickScript
8868
- }
8869
- ]
8870
- },
8871
- "eventAdd": {
8872
- "weight": 0,
8873
- "actions": [
8874
- {
8875
- "componentId": "",
8876
- "args": {
8877
9190
  },
8878
- "actionType": "custom",
8879
- "script": "console.log('eventAdd'); console.log(event);"
8880
- }
8881
- ]
8882
- },
8883
- "eventChange": {
8884
- "weight": 0,
8885
- "actions": [
8886
- {
8887
- "actionType": 'ajax',
8888
- "args": {
8889
- "api": recordPermissionsApi
8890
- }
8891
- },
8892
- {
8893
- "actionType": "toast",
8894
- "expression": "!event.data.editable",
8895
- "args": {
8896
- "msgType": "error",
8897
- "msg": "您没有编辑该记录的权限!",
8898
- "position": "top-center"
8899
9191
  }
8900
- },
8901
- {
8902
- "actionType": 'ajax',
8903
- "expression": "event.data.editable",
8904
- "args": {
8905
- "api": recordSaveApi,
8906
- "messages": {
8907
- "success": objectSchema.label + "修改成功",
8908
- "failed": objectSchema.label + "修改失败!"
9192
+ ],
9193
+ onEvent: {
9194
+ "fetchInited": {
9195
+ "weight": 0,
9196
+ "actions": [
9197
+ {
9198
+ actionType: 'broadcast',
9199
+ eventName: "recordLoaded",
9200
+ args: {
9201
+ eventName: "recordLoaded"
9202
+ },
9203
+ data: {
9204
+ objectName: "${event.data.__objectName}",
9205
+ record: "${event.data.__record}"
9206
+ },
9207
+ expression: "${event.data.__response.error != true}"
9208
+ },
9209
+ {
9210
+ "actionType": "setValue",
9211
+ "args": {
9212
+ value: {
9213
+ "recordLoaded": true,
9214
+ }
9215
+ },
9216
+ expression: "${event.data.__response.error != true}"
8909
9217
  }
9218
+ ]
8910
9219
  }
8911
9220
  }
8912
- ]
8913
- },
8914
- "eventRemove": {
8915
- "weight": 0,
8916
- "actions": [
8917
- {
8918
- "componentId": "",
8919
- "args": {
8920
- },
8921
- "actionType": "custom",
8922
- "script": "console.log('eventRemove'); console.log(event);"
8923
- }
8924
- ]
8925
- },
8926
- "eventsSet": {
8927
- "weight": 0,
8928
- "actions": [
8929
- {
8930
- "componentId": "",
8931
- "args": {
8932
- },
8933
- "actionType": "custom",
8934
- "script": "console.log('eventsSet'); console.log(event);"
8935
- }
8936
- ]
8937
- }
8938
- };
8939
-
8940
- Object.assign(onEvent, options.onEvent);
8941
-
8942
- const config = options.config || {};
8943
- if(config.eventContent && typeof config.eventContent === "string"){
8944
- const hasReturn = /\breturn\b/.test(config.eventContent);
8945
- if(hasReturn){
8946
- try {
8947
- // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8948
- let fn = new Function("arg", config.eventContent);
8949
- config.eventContent = fn;
8950
- } catch (e) {
8951
- console.warn(e);
8952
- }
8953
- }
8954
- }
8955
-
8956
- if(config.noEventsContent && typeof config.noEventsContent === "string"){
8957
- const hasReturn = /\breturn\b/.test(config.noEventsContent);
8958
- if(hasReturn){
8959
- try {
8960
- // 如果是包括return语句的字符串,则按函数解析,见 https://fullcalendar.io/docs/content-injection
8961
- let fn = new Function("arg", config.noEventsContent);
8962
- config.noEventsContent = fn;
8963
- } catch (e) {
8964
- console.warn(e);
8965
- }
8966
9221
  }
8967
- }
8968
-
8969
- const amisSchema = {
8970
- "type": "steedos-fullcalendar",
8971
- "label": "",
8972
- "name": "fullcalendar",
8973
- "placeholder":"${additionalFilters}",//用于触发reload
8974
- "editable": permissions.allowEdit,
8975
- "selectable": permissions.allowCreate,
8976
- "selectMirror": permissions.allowCreate,
8977
- "initialView": initialView,
8978
- "businessHours": businessHours,
8979
- ...config,
8980
- "onEvent": onEvent
8981
- };
8982
- return amisSchema;
8983
9222
  }
8984
9223
 
8985
9224
  /*
@@ -9401,8 +9640,8 @@ async function getRelatedListSchema(
9401
9640
  /*
9402
9641
  * @Author: baozhoutao@steedos.com
9403
9642
  * @Date: 2022-07-05 15:55:39
9404
- * @LastEditors: baozhoutao@steedos.com
9405
- * @LastEditTime: 2023-04-28 11:11:29
9643
+ * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
9644
+ * @LastEditTime: 2023-06-04 17:36:49
9406
9645
  * @Description:
9407
9646
  */
9408
9647
 
@@ -9733,7 +9972,8 @@ async function getListSchema(
9733
9972
  "requestAdaptor": listView.requestAdaptor,
9734
9973
  "adaptor": listView.adaptor,
9735
9974
  "headerToolbarItems": ctx.headerToolbarItems,
9736
- "filterVisible": ctx.filterVisible
9975
+ "filterVisible": ctx.filterVisible,
9976
+ "rowClassNameExpr": ctx.rowClassNameExpr
9737
9977
  };
9738
9978
  return {
9739
9979
  uiSchema,