Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

6.0 KB
Raw Blame
import { wedofAuth } from '../auth';
import { createAction, DynamicPropsValue, isNil, Property } from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { wedofCommon } from '../common/wedof';

export const sendFile = createAction({
  auth: wedofAuth,
  name: 'sendFile',
  classification: 'WRITE',
  displayName: "Envoyer un fichier",
  description: "Permet d'envoyer un fichier pour un dossier (Dossier de formation / Dossier de certification)",
  audience: 'both',
  aiMetadata: {
    description:
      'Uploads a document to a single folder (a training or certification folder selected via the folder-type input), provided as a direct file, a file URL, or a link to download. Not idempotent: each call adds a new document to the folder. Use to attach a file to one specific folder by its number.',
    idempotent: false,
  },
  props: {
    entityClass: Property.StaticDropdown({
      displayName: "Choisir le type de dossier",
      description: "Permet de n'obtenir que les dossiers dans le type considéré - par défaut tous les types sont retournés",
      required: true,
      options: {
        options: [
          {
            value: "certificationFolders",
            label: 'Dossier de certification',
          },
          {
            value: "registrationFolders",
            label: 'Dossier de formation',
          },
        ],
        disabled: false,
      },
    }),
    externalId: Property.ShortText({
      displayName: 'N° du dossier',
      description:
        'Sélectionner la propriété {externalId} du dossier',
      required: true,
    }),
    title: Property.ShortText({
        displayName: 'Titre du fichier',
        required: false,
    }),
    typeId: Property.DynamicProperties({
      auth: wedofAuth,
      displayName: 'Type du fichier',
      refreshers: ['entityClass', 'externalId'],
      required: true,
      props: async ({ auth, entityClass, externalId }) => {
        const fields: DynamicPropsValue = {};
        if (!entityClass) {
          console.error('entityClass is undefined');
          return {};
        }
       if (!externalId) {
          console.error('externalId is undefined');
          return {};
        }
        try {
          const res = await httpClient.sendRequest({
            method: HttpMethod.GET,
            url: `${wedofCommon.baseUrl}/${entityClass}/${externalId}/files`,
            headers: {
              'Content-Type': 'application/json',
              'X-Api-Key': auth as unknown as string,
            },
          });
          const data = res.body;
          if (Array.isArray(data)) {
            data.forEach((field: { id: string | number; name: string; }) => {
              fields[field.id] = Property.StaticDropdown({
                displayName: field.name,
                options: {
                  options: data.map((option: { typeId: string; name: string; }) => ({
                    value: option.typeId,
                    label: option.name,
                  })),
                  disabled: false,
                },
                required: false,
              });
            });
          }
        } catch (error) {
          console.error('Error fetching data:', error);
        }
        return fields;
      },
    }),
    typeFile: Property.StaticDropdown({
      displayName: "Choisir le format d'envoi du fichier",
      description: "Permet de choisir la méthode d'envoi du fichier",
      required: false,
      defaultValue: "file",
      options:  {
          options: [
            {
              value: "file",
              label: 'Attacher un document',
            },
            {
              value: "fileUrl",
              label: 'Ajouter un lien',
            },
            {
              value: "url",
              label: "Ajouter à partir d'un lien",
            },
          ],
       disabled : false,
      },
      
    }),
  files: Property.DynamicProperties({
    auth: wedofAuth,
    description: '',
    displayName: 'ez',
    required: true,
    refreshers: ['typeFile'],
    props: async ({ typeFile }) => {
      const _type = typeFile as unknown as string;
      const props: DynamicPropsValue = {};
      if (_type === "url") {
        props['fileToDownload'] = Property.LongText({
          displayName: "Lien vers le document",
          description: 'URL du fichier à télécharger',
          required: true,
      });
      } else if (_type === "fileUrl") {
        props['file'] = Property.LongText({
          displayName: "Lien a envoyer",
          description: 'URL du fichier',
          required: true,
      });
      } else if (_type === "file") {
        props['file'] = Property.File({
          displayName: "Fichier a envoyer",
          required: true,
      });
      }
      return props;
    },
  }),
  },
  async run(context) {
      const { title, typeId, files } = context.propsValue;
      const file = files['file'];
      const formData = new FormData();
      formData.append('typeId', String(typeId['undefined']));
      if (!isNil(title)) {
        formData.append('title', title);
      }
      if (isUploadedFile(file)) {
        formData.append('file', new Blob([new Uint8Array(file.data)]), file.filename);
      } else if (!isNil(file)) {
        formData.append('file', String(file));
      }
      if (!isNil(files['fileToDownload'])) {
        formData.append('fileToDownload', String(files['fileToDownload']));
      }
      return (
        await httpClient.sendRequest({
          method: HttpMethod.POST,
          url:
            wedofCommon.baseUrl +
            '/' +
            context.propsValue.entityClass +
            '/'+ context.propsValue.externalId + '/files',
          body: formData,
          headers: {
            'X-Api-Key': context.auth.secret_text,
          },
        })
      ).body;
  },
});

function isUploadedFile(value: unknown): value is { filename: string; data: Buffer } {
  return (
    typeof value === 'object' &&
    value !== null &&
    'filename' in value &&
    typeof value.filename === 'string' &&
    'data' in value &&
    Buffer.isBuffer(value.data)
  );
}