name: b6_collect_afterUpdate_notification
listenTo: b6_collect
when:
  - afterUpdate
isEnabled: true
handler: |-
  // global: {_:lodash, moment, validator, filters}
  // ctx
  // objects
  // services

  const previousDoc = ctx.params.previousDoc;
  const doc = ctx.params.doc;
  const userId = ctx.params.userId;

  const previousStatus = previousDoc.status;
  const newStatus = doc.status;

  const distributer = doc.distributer || previousDoc.distributer;
  const owner = doc.owner || previousDoc.owner;

  if (previousStatus === "draft" && newStatus === "pending" && distributer) {
      // 从草稿提交到待审核，发通知给审核人，即收集表的下发人 distributer
      const to = distributer;
      const table = await objects.b6_tables.findOne(doc.table, { fields: ['label'] });
      const fromUser = await ctx.getUser(userId, doc.space);
      const notificationTitle = "收集表";
      let notificationDoc = {
          name: `${fromUser.name}正在请求批准`,
          body: notificationTitle,
          related_to: {
              o: "b6_collect",
              ids: [doc._id]
          },
          related_name: table.label + "-" + doc._id,
          from: userId,
          space: doc.space
      };

      ctx.broker.call('notifications.add', {
          message: notificationDoc,
          from: userId,
          to: to
      })
  }
  else if (previousStatus === "pending" && newStatus === "approved" && owner) {
      // 从待审核中点批准按钮，发通知给填报人，即收集表的 owner
      const to = owner;
      const table = await objects.b6_tables.findOne(doc.table, { fields: ['label'] });
      const notificationTitle = "收集表";
      let notificationDoc = {
          name: `您的申请已被核准`,
          body: notificationTitle,
          related_to: {
              o: "b6_collect",
              ids: [doc._id]
          },
          related_name: table.label + "-" + doc._id,
          from: userId,
          space: doc.space
      };

      ctx.broker.call('notifications.add', {
          message: notificationDoc,
          from: userId,
          to: to
      })
  }
  else if (previousStatus === "pending" && newStatus === "draft" && owner) {
      // 从待审核中点拒绝按钮，发通知给填报人，即收集表的 owner
      const to = owner;
      const table = await objects.b6_tables.findOne(doc.table, { fields: ['label'] });
      const notificationTitle = "收集表";
      let notificationDoc = {
          name: `您的申请已被拒绝`,
          body: notificationTitle,
          related_to: {
              o: "b6_collect",
              ids: [doc._id]
          },
          related_name: table.label + "-" + doc._id,
          from: userId,
          space: doc.space
      };

      ctx.broker.call('notifications.add', {
          message: notificationDoc,
          from: userId,
          to: to
      })
  }
authentication_type: none
locked: false
type: code
