如何自定义点击导出动作绑定指定模板

介绍

平台默认的导出会打开弹窗,然后在弹窗内的视图选择是用模板方式导出还是选字段导出,但是有时候有部分场景希望点击导出动作后直接进入导出流程,导出指定的某个模板,我们可以通过覆写打开弹窗的动作来实现该功能。

本文档参考了 表格页自定义按钮如何获取搜索区域的查询条件

代码示例

以下代码大部分场景只需要修改其中excelTplName更换模板即可,另外如何想增加复用性,还可以将该属性改为从元数据的配置中获取。

import {
  ActionType,
  BaseActionWidget,
  BaseElementListViewWidget,
  BooleanHelper,
  ClickResult,
  Condition,
  ExcelExportTask,
  FILE_MODULE_NAME,
  getSessionPath,
  GraphqlHelper,
  http,
  IQueryPageResult,
  ISort,
  queryDslWidget,
  ReturnPromise,
  RuntimeServerAction,
  ServerActionWidget,
  SPI,
  SubmitValue,
  SYSTEM_MODULE_NAME,
  translateValueByKey,
  UrlHelper,
  ViewActionTarget,
  Widget
} from '@kunlun/dependencies';
import { OioNotification } from '@kunlun/vue-ui-antd';

@SPI.ClassFactory(
  BaseActionWidget.Token({
    actionType: [ActionType.View],
    target: [ViewActionTarget.Dialog],
    model: 'ys0328.k2.Model0000000453',
    name: 'internalGotoListExportDialog'
  })
)
export class DemoExportActionWidget extends ServerActionWidget {
  /**
   * excel导出模板名称
   * @protected
   */
  protected excelTplName = '演示抽屉跳转链接导出';

  /**
   * 导出任务的模型编码
   * @protected
   */
  protected exportTaskModel = 'excelExportTask';

  /**
   * 导出任务的方法
   * @protected
   */
  protected exportTaskFun = 'createExportTask';

  /**
   *
   * 是否是同步导出
   */
  @Widget.Reactive()
  protected get syncExport() {
    return BooleanHelper.isTrue(this.getDsl().sync) || !true;
  }

  protected async executeAction(action: RuntimeServerAction, parameters: SubmitValue): Promise<ClickResult> {
    const workbookId = await this.getWorkbookId();
    if (!workbookId) {
      return false;
    }
    let task = {
      workbookDefinition: {
        id: workbookId
      }
    } as ExcelExportTask;

    // 从平台内置的方法获取搜索区域的条件
    const { condition } = this.getSearchRsqlAndQueryParams();

    // 排序规则
    let sortList = [] as ISort[];
    const baseViewWidget = Widget.select(this.rootHandle);
    const listViewWidget = queryDslWidget(baseViewWidget?.getChildrenInstance(), BaseElementListViewWidget);
    if (listViewWidget) {
      sortList = listViewWidget.sortList;
    }

    return this.export(task, condition, sortList);
  }

  protected getUploadBodyGql(id: string, condition: string | Condition, sortList: ISort[]) {
    let queryData = '{}';
    let rsql = condition;
    if (condition instanceof Condition) {
      const conditionBodyData = condition.getConditionBodyData();
      if (conditionBodyData && Object.keys(conditionBodyData).length) {
        queryData = GraphqlHelper.serializableObject(conditionBodyData);
      }
      rsql = condition.toString();
    }

    const sortListStr = (sortList || []).map((sort) => `{field: "${sort.sortField}", direction: ${sort.direction}}`).join(',');
    const sorts = sortListStr ? `sort: {orders: [${sortListStr}]}` : '';
    const conditionWrapper = condition
      ? `,conditionWrapper:{
            rsql: "${rsql}",
            queryData: "${queryData}"
            ${sorts}
          }`
      : '';
    const mutation = `mutation {
      ${this.exportTaskModel}Mutation {
        ${this.exportTaskFun}(data: {sync: ${this.syncExport}, workbookDefinition: {id: ${id}}${conditionWrapper}}) {
          id
          name
          state
        }
      }
    }`;

    return mutation;
  }

  protected async export(task: ExcelExportTask, condition: Condition | string, sortList: ISort[]) {
    let gql = await this.getUploadBodyGql(task.workbookDefinition!.id, condition, sortList);
    const variables = {
      path: getSessionPath()
    };
    let responseResult = false;
    if (this.syncExport) {
      window.open(
        UrlHelper.appendBasePath(
          `/pamirs/${FILE_MODULE_NAME}?query=${encodeURIComponent(gql)}&variables=${encodeURIComponent(
            JSON.stringify(variables)
          )}`
        ),
        '_blank'
      );
      responseResult = true;
    } else {
      const res = await http.mutate(SYSTEM_MODULE_NAME.FILE, gql, variables);
      const data = res.data[`${this.exportTaskModel}Mutation`][this.exportTaskFun] as any;
      responseResult = !!data.id;
    }
    if (responseResult) {
      OioNotification.success(this.translate('kunlun.common.success'));
      return true;
    }
    OioNotification.error(this.translate('kunlun.common.error'));
    return false;
  }

  protected async getWorkbookId(): ReturnPromise<string | undefined> {
    const model = this.model.model!;
    const gql = `{
  excelWorkbookDefinitionQuery {
    queryPage(
      page: {currentPage: 1, size: 1}
      queryWrapper: {rsql: "displayName=='${this.excelTplName}' and model == '${model}' and dataStatus == 'ENABLED' and type =in= ('IMPORT_EXPORT','EXPORT')"}
    ) {
      content {
        displayName
        id
      }
      totalPages
      totalElements
    }
  }
}
`;
    const variables = {
      path: getSessionPath()
    };
    const res = await http.query(SYSTEM_MODULE_NAME.FILE, gql, variables);
    const pageRes = res.data.excelWorkbookDefinitionQuery.queryPage as unknown as IQueryPageResult<any>;
    const id = pageRes.content?.[0]?.id;
    if (!id) {
      OioNotification.warning(translateValueByKey('没有找到匹配的导出模板'));
    }
    return id;
  }
}

Oinone社区 作者:nation原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/18221.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
nation的头像nation数式员工
上一篇 2024年10月8日 pm6:41
下一篇 2024年10月10日 am10:35

相关推荐

  • 【动作】-路由动作跳转后如何主动刷新页面数据

    介绍 当我们使用多tab组件的时候,如果一个viewAction已经打开了一个tab页,再次用该viewAction打开页面的时候,会发现不会根据路由上的业务参数(如详情和编辑页的id参数)主动刷新数据,这个时候可以通过以下方法解决该问题 // 该方法可以在进入新路由页面后刷新数据,推荐将该方法放到工具类 function refreshViewAction(action: any) { const onRefreshTabWithActive = (manager: MultiTabsManager, instance: MultiTabInstance) => { // 进入路由后刷新页面数据 manager.refresh(instance.key); manager.clearOnActive(onRefreshTabWithActive); }; MultiTabsManager.INSTANCE.onActive(onRefreshTabWithActive); executeViewAction(action); } 将原本调用executeViewAction的方法改为refreshViewAction 如果需要扩展executeViewAction的其他入参请自行拓展refreshViewAction的入参

    2024年6月18日
    89000
  • oio-pagination 分页

    API 参数 说明 类型 默认值 版本 currentPage(v-model:currentPage) 当前页数 number – defaultPageSize 默认的每页条数 number 15 disabled 禁用分页 boolean – pageSize 每页条数 number – pageSizeOptions 指定每页可以显示多少条 string[] [’10’, ’15’, ’30’, ’50’, ‘100’, ‘200’] showQuickJumper 是否可以快速跳转至某页 boolean false showSizeChanger 是否展示 pageSize 切换器,当 total 大于 50 时默认为 true boolean – total 数据总数 number 0 事件 事件名称 说明 回调参数 change 页码或 pageSize 改变的回调,参数是改变后的页码及每页条数 Function(page, pageSize) noop

    2023年12月18日
    70400
  • 在前端视图添加自定义的区域块

    添加自定义区域块 平台提供了一系列默认的视图布局,可以帮助开发人员快速构建出复杂的企业应用系统。当然,我们可以使用自定义区域块来扩展表格、表单、画廊、树形等视图。 自定义区域块概述 平台视图布局都是通过XML配置实现的。在视图布局中,我们可以使用一些特定的元素标签来构建视图的表头、表单、搜索区域等部分。而自定义区域块,就是这些元素标签之外的部分。我们可以通过在视图布局的XML中添加自定义区域块,来扩展页面功能。 视图类型及相关元素 视图类型分为表格(TABLE)、表单(FORM)、画廊(GALLERY)、树形(TREE)等。不同类型的视图布局,包含的元素也有所不同。 下面是几种视图类型及其对应的元素: 表格:搜索区域、表格主体,其中表格主体包含了表格上面的动作、表格区域等部分。 表单:表单区域,包含了表单动作、表单区域等部分。 画廊:动作、卡片详细信息。 在表格页面添加自定义区域块 以下是一个示例,演示如何在表格页面顶部添加自定义区域块。 1. 修改视图布局XML 首先,我们需要修改表格视图的XML布局,添加自定义区域块元素标签。 <view type="TABLE"> <!– 这是搜索区域 –> <pack widget="group"> <view type="SEARCH"> <element widget="search" slot="search" slotSupport="field" /> </view> </pack> <!– 这是表格主体 –> <pack widget="group" slot="tableGroup"> <!– 在这里添加自定义区域块元素标签 –> <element widget="MyCustomElement"></element> <!– 这是表格上面的动作 –> <element widget="actionBar" slot="actionBar" slotSupport="action"> <xslot name="actions" slotSupport="action" /> </element> <!– 这是表格区域 –> <element widget="table" slot="table" slotSupport="field"> <element widget="expandColumn" slot="expandRow" /> <xslot name="fields" slotSupport="field" /> <element widget="rowActions" slot="rowActions" slotSupport="action" /> </element> </pack> </view> 在上述代码中,我们添加了一个名为MyCustomElement的元素标签。这将作为我们自定义区域块的容器。 2. 创建自定义Vue组件 接下来,我们需要创建一个Vue组件,并将其指定为自定义元素标签MyCustomElement的模板。 <template> <div> <!– 在这里编写自定义区域块的内容 –> <p>Hello, world!</p> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ components: { }, props: [], setup(props) { return {}; } }); </script> 在上述代码中,我们定义了一个非常简单的Vue组件,它在页面上显示一个“Hello, world!”的文本信息。 3. 创建自定义Element Widget 为了使自定义Vue组件与XML布局文件关联起来,我们需要创建一个对应的Element Widget。 import { BaseElementWidget, SPI, BaseElementViewWidget, Widget, ViewMode, FormWidget, BaseElementWidgetProps } from '@kunlun/dependencies'; import MyCustomElement from './MyCustomElement.vue'; @SPI.ClassFactory(BaseElementWidget.Token({ widget: 'MyCustomElementWidget' })) export class MyCustomElementWidget extends BaseElementWidget { public initialize(props: BaseElementWidgetProps): this { super.initialize(props) this.setComponent(MyCustomElement) return this } } 在上述代码中,我们继承了BaseElementWidget类,并在其中指定了Vue组件MyCustomElement。这样,XML布局文件中的元素标签就能够正确地与Vue组件关联起来。 4. 注册视图布局 最后,我们需要将上述代码配置注册。具体而言,我们需要调用registerLayout方法来将XML布局文件、模块名和视图类型进行关联。 import { registerLayout, ViewType } from '@kunlun/dependencies'; registerLayout( `<view type="TABLE"> <pack widget="group"> <view type="SEARCH"> <element widget="search" slot="search" slotSupport="field" />…

    2023年11月1日
    2.3K00
  • 如何增加页面消息通知轮询的间隔或者关闭轮询

    场景 oinone的前端页面默认自带了消息通知功能,在顶部状态栏可以看到消息的查看入口,默认每隔5秒查询一次最新的消息,我们可以通过自定义消息组件增加该间隔或者是关闭轮询 示例代码 修改轮询间隔 import { MaskWidget, NotificationWidget, SPI } from '@kunlun/dependencies'; @SPI.ClassFactory(MaskWidget.Token({ widget: 'notification' })) export class DemoNotificationWidget extends NotificationWidget { /** * 轮询间隔时间,单位: 秒 * @protected */ protected msgDelay = 30000; } 关闭轮询 import { MaskWidget, NotificationWidget, SPI } from '@kunlun/dependencies'; @SPI.ClassFactory(MaskWidget.Token({ widget: 'notification' })) export class DemoNotificationWidget extends NotificationWidget { protected mounted() { super.mounted(); // 清除轮询的定时器 this.msgTimer && clearInterval(this.msgTimer); // 挂载后手动查询一次消息 this.getMsgTotal(); } }

    2024年8月20日
    83800
  • 运行时上下文API文档(v4)

    运行时上下文 RuntimeContext export interface RuntimeContext<Framework = unknown> extends ContextNode<RuntimeContext<Framework>> { /** * 框架实例 */ frameworkInstance: Framework; /** * 路由路径 */ routers: RouterPath[]; /** * 运行时跳转动作(通过跳转动作创建的运行时上下文具备该属性) */ viewAction?: RuntimeViewAction; /** * 运行时字段(通过字段创建的运行时上下文具备该属性) */ field?: RuntimeModelField; /** * 运行时模块 */ module: RuntimeModule; /** * 运行时模型 */ model: RuntimeModel; /** * 运行时视图 */ view: RuntimeView; /** * 视图布局dsl,从运行时视图解析获得 */ viewLayout: DslDefinition | undefined; /** * 视图模板dsl,从运行时视图解析获得 */ viewDsl: DslDefinition | undefined; /** * 视图最终执行dsl,从运行时视图解析获得或根据布局dsl和模板dsl合并生成 */ viewTemplate: DslDefinition; /** * 扩展数据 */ extendData: Record<string, unknown>; /** * 获取模型 * @param model 模型编码 * @return 返回获取的模型和所在的运行时上下文 */ getModel(model: string): GetModelResult | undefined; /** * 获取模型字段 * @param name 字段名称 * @return 返回获取的模型字段和所在的运行时上下文 */ getModelField(name: string): GetModelFieldResult | undefined; /** * 创建字段上下文 * @param field 运行时模型字段 */ createFieldRuntimeContext(field: RuntimeModelField): RuntimeContext; /** * 深度解析模板,创建必要的子运行时上下文 */ deepResolve(): void; /** * 传输上下文参数到指定运行时上下文 * @param runtimeContext 运行时上下文 * @param clone 是否克隆; 默认: true */ transfer(runtimeContext: RuntimeContext, clone?: boolean); /** * 获取请求字段 */ getRequestModelFields(options?: GetRequestModelFieldsOptions): RequestModelField[]; /** * 获取默认值 */ getDefaultValue(): Promise<Record<string, unknown>>; /** * 获取初始值 */ getInitialValue(): Promise<Record<string, unknown>>; } 相关类型声明 export type GetModelResult = { model: RuntimeModel; runtimeContext: RuntimeContext;…

    2023年11月1日
    66600

Leave a Reply

登录后才能评论