Home > Back-end >  How to filter two arrays of splitting?
How to filter two arrays of splitting?

Time:07-07

I'm a bit confused

I am sending emails with nodemailer, and every time I send one I perform certain validations in order to manage the upload limit of the attachments. If the upload limit exceeds what is established, the service divides that email and sends it in different emails with the same subject and body as well as its attachment.

Every time this happens, it does a _.chunk that takes care of splitting the pdfs array into smaller elements. But, it should be noted that before that, he made a method to prepare the attachments and this is in charge of obtaining certain information from the api to paint the pdf buffer and thus put it in the content of the emails.

But now what I want to do is search within the matrix that performs the step before dividing the files those that are equal to the array that obtains the information and if they are equal, carry out the instruction that it sends

I will explain with a graph:

enter image description here

If getAmount.pdfBuffer === attachmentMap // doAction console.log('Equals)

But even though I tried to do it, I couldn't, I don't know if it's because for each attachment that the array has divided, it generates a getAmount array. What do you think I'm doing wrong?

      async sendEmail(
        {
          para: to,
          asunto: subject,
          plantilla: template,
          contexto: context,
        }: CorreoInfoDto,
        attachments: EmailAttachment[],
        driveConfig: OAuthGoogleConfig
      ) {
        const totalSize: number = this.getSizeFromAttachments(attachments);
        const chunkSplit = Math.floor(isNaN(totalSize) ? 1 : totalSize / this.LIMIT_ATTACHMENTS)   1;
        const attachmentsChunk: any[][] = _.chunk(attachments, chunkSplit);
    
        if ((totalSize > this.LIMIT_ATTACHMENTS) && attachmentsChunk?.length >= 1) {
          await Promise.all(
            attachmentsChunk?.map(async (attachment: EmailAttachment[], index) => {
              console.log('attachment', attachment)
              if (this.getSizeFromAttachments(attachment) > this.LIMIT_ATTACHMENTS) {
                const result: GenerateDriveLinkResponse[] = await Promise.all(
                  attachment?.map(item => {
                    const file = new GoogleDriveUploadFile({
                      name: item?.filename,
                      mimeType: MimeTypesEnum.PDF,
                      body: item?.content
                    });
                    return this.uploadFilesService.uploadToDrive(driveConfig, file) as any;
                  })
                )
    
                const texto = result?.map((item, index) => {
                  console.log('item', item?.webViewLink);
                  console.log('index', index);
                  return new SolicitudXLinkDrive({
                    texto: attachment[index].filename,
                    link: item?.webViewLink
                  })
                });
    
                context.links = texto;
    
                const link = `(${index   1}/${attachmentsChunk?.length - 1})`;
    
                const newContext = {
                  getCurrent: link,
                  ...context
                }
    
                const prepareEmail = this.prepareEmail({
                  para: to,
                  asunto: ` ${subject} (${index   1}/${attachmentsChunk?.length})`,
                  plantilla: template,
                  contexto: newContext,
                }, []);
    
                return prepareEmail
    
              } else {
                // this.getCantidad = `(${index   1}/${attachmentsChunk?.length - 1})`;
                console.log('getCantidad', this.getAmount );
    
                const attachmentMap = attachment.map(element => element.content);
                this.getAmount .forEach(element => {
                  if (element.pdfBuffer === attachmentMap) {
                    console.log('do action');
                  }
               })
    
                const link = ` (${index   1}/${attachmentsChunk?.length - 1})`;
                const newContext = {
                  getCurrent: link,
                  ...context
                }
    
                return this.prepareEmail({
                  para: to,
                  asunto: ` ${subject} (Correo ${index   1}/${attachmentsChunk?.length - 1})`,
                  plantilla: template,
                  contexto: newContext,
                }, attachment);
              }
            })
          );
        } else {
          await this.prepareEmail(
            {
              para: to,
              asunto: ` ${subject}`,
              plantilla: template,
              contexto: context,
            },
            attachments,
          );
        }
      }

  async prepareEmail(
    {
      para: to,
      asunto: subject,
      plantilla: template,
      contexto: context,
    }: CorreoInfoDto,
    attachments: EmailAttachment[],
  ) {

    return await this.mailerService.sendMail({
      to,
      from: `${process.env.SENDER_NAME} <${process.env.EMAIL_USER}>`,
      subject,
      template,
      attachments: attachments,
      context: context,
    });
  }
  async sendEmails(correos: EnvioMultiplesCorreosDto) {
    let pdf = null;
    let info: ConfiguracionDocument = null;
    let GDriveConfig: ConfiguracionDocument = null;
    let logo: ConfiguracionDocument = null;
    let forContext = {};

    const documents = Array.isArray(correos.documento_id) ? correos.documento_id : [correos.documento_id];
    const solicitudes = await this.solicitudesService.findByIds(documents);
    const nombresPacientes = solicitudes.reduce((acc, cv) => {
      acc[cv.correlativo_solicitud] = cv['info_paciente']?.nombre_paciente;
      return acc;
    }, {});

    await Promise.all([
      await this.getPdf(correos.tipo_reporte, correos.documento_id, correos?.dividir_archivos).then(data => { pdf = data; }),
      await this.configuracionesService.findByCodes([
        ConfigKeys.TEXTO_CORREO_MUESTRA,
        ConfigKeys[process.env.DRIVE_CONFIG_API],
        ConfigKeys.LOGO_FIRMA_PATMED
      ]).then(data => {
        info = data[0];
        GDriveConfig = data[1];
        logo = data[2];
      })
    ]);
    forContext = this.configuracionesService.castValorObjectToObject(info?.valor_object)
    const attachmentPrepare = this.prepareAttachments(pdf as any, nombresPacientes);

    await this.sendEmail(
      {
        para: correos.para,
        asunto: correos.asunto,
        plantilla: 'muestras',
        contexto: {
          cuerpo: correos.cuerpo,
          titulo: forContext[EnvioCorreoMuestraEnum.titulo],
          direccion: forContext[EnvioCorreoMuestraEnum.direccion],
          movil: forContext[EnvioCorreoMuestraEnum.movil],
          pbx: forContext[EnvioCorreoMuestraEnum.pbx],
          email: forContext[EnvioCorreoMuestraEnum.email],
          logo: logo?.valor,
        },
      },
      attachmentPrepare,
      this.configuracionesService.castValorObjectToObject(GDriveConfig?.valor_object) as any,
    );

    const usuario = new UsuarioBitacoraSolicitudTDTO();
    usuario.createFromUserRequest(this.sharedService.getUserFromRequest());

    solicitudes.forEach((solicitud) => {
      const actual = new BitacoraSolicitudDTO();
      actual.createFromSolicitudDocument(solicitud);

      const newBitacora = new CrearBitacoraSolicitudDTO();
      newBitacora.createNewItem(null, actual, actual, usuario, AccionesBitacora.EmailEnviado);
      this.bitacoraSolicitudesService.create(newBitacora);
    });
  }

  prepareAttachments(item: BufferCorrelativosDTO | BufferXSolicitudDTO[], nombresPacientes: { [key: string]: string }) {
    if (this.sharedService.isAnArray(item)) {
      const castItem: BufferXSolicitudDTO[] = item as any;
      this.getCantidad = castItem;
      return castItem?.map((s) => {
        const namePatient = nombresPacientes[s.correlativo_solicitud];
        return new EmailAttachment().setFromBufferXSolicitudDTO(s, namePatient, 'pdf');
      });
    } else {
      return [new EmailAttachment().setFromBufferCorrelativosDTO(item as any, 'pdf')];
    }
  }

enter image description here

Thank you very much for your attention, I appreciate it. Cheers

CodePudding user response:

You could try using lodash as this has _.intersectionBy and _.intersectionWith functions that should allow you to compare 2 arrays and filter the common values.

There are some good examples here:

How to get intersection with lodash?

  • Related