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