<commit_before>import { get } from 'lodash';
import config from 'config';
import HelloWorks from 'helloworks-sdk';
import s3 from '../lib/awsS3';
import models from '../models';
import fs from 'fs';
import logger from '../lib/logger';
import { encrypt } from '../lib/encryption';

const { User, LegalDocument, RequiredLegalDocument } = models;
const {
  requestStatus: { ERROR, RECEIVED },
} = LegalDocument;
const {
  documentType: { US_TAX_FORM },
} = RequiredLegalDocument;

const HELLO_WORKS_KEY = get(config, 'helloworks.key');
const HELLO_WORKS_SECRET = get(config, 'helloworks.secret');
const HELLO_WORKS_WORKFLOW_ID = get(config, 'helloworks.workflowId');

const HELLO_WORKS_S3_BUCKET = get(config, 'helloworks.aws.s3.bucket');
const ENCRYPTION_KEY = get(config, 'helloworks.documentEncryptionKey');

const client = new HelloWorks({
  apiKeyId: HELLO_WORKS_KEY,
  apiKeySecret: HELLO_WORKS_SECRET,
});

async function callback(req, res) {
  const {
    body: { status, workflow_id: workflowId, data, id, metadata },
  } = req;

  if (status && status === 'completed' && workflowId == HELLO_WORKS_WORKFLOW_ID) {
    const { email, year } = metadata;
    const documentId = Object.keys(data)[0];

    const user = await User.findOne({
      where: {
        email,
      },
    });
    const doc = await LegalDocument.findByTypeYearUser({ year, documentType: US_TAX_FORM, user });

    client.workflowInstances
      .getInstanceDocument({
        instanceId: id,
        documentId,
      })
      .then(buff => Promise.resolve(encrypt(buff, ENCRYPTION_KEY)))
      .then(UploadToS3({ id: user.id, year, documentType: US_TAX_FORM }))
      .then(({ Location: location }) => {
        doc.requestStatus = RECEIVED;
        doc.documentLink = location;
        return doc.save();
      })
      .then(() => res.sendStatus(200))
      .catch(err => {
        doc.requestStatus = ERROR;
        doc.save();
        logger.error('error saving tax form: ', err);
        res.sendStatus(400);
      });
  } else {
    res.sendStatus(200);
  }
}

function UploadToS3({ id, year, documentType }) {
  return function uploadToS3(buffer) {
    const bucket = HELLO_WORKS_S3_BUCKET;
    const key = createTaxFormFilename({ id, year, documentType });

    if (!s3) {
      // s3 may not be set in a dev env<commit_msg>Change name of uploaded document to be the user collective username.<commit_after>import { get } from 'lodash';
import config from 'config';
import HelloWorks from 'helloworks-sdk';
import s3 from '../lib/awsS3';
import models from '../models';
import fs from 'fs';
import logger from '../lib/logger';
import { encrypt } from '../lib/encryption';

const { User, LegalDocument, RequiredLegalDocument } = models;
const {
  requestStatus: { ERROR, RECEIVED },
} = LegalDocument;
const {
  documentType: { US_TAX_FORM },
} = RequiredLegalDocument;

const HELLO_WORKS_KEY = get(config, 'helloworks.key');
const HELLO_WORKS_SECRET = get(config, 'helloworks.secret');
const HELLO_WORKS_WORKFLOW_ID = get(config, 'helloworks.workflowId');

const HELLO_WORKS_S3_BUCKET = get(config, 'helloworks.aws.s3.bucket');
const ENCRYPTION_KEY = get(config, 'helloworks.documentEncryptionKey');

const client = new HelloWorks({
  apiKeyId: HELLO_WORKS_KEY,
  apiKeySecret: HELLO_WORKS_SECRET,
});

async function callback(req, res) {
  const {
    body: { status, workflow_id: workflowId, data, id, metadata },
  } = req;

  if (status && status === 'completed' && workflowId == HELLO_WORKS_WORKFLOW_ID) {
    const { email, year } = metadata;
    const documentId = Object.keys(data)[0];

    const user = await User.findOne({
      where: {
        email,
      },
    });

    const userCollectiveName = await user.username;

    const doc = await LegalDocument.findByTypeYearUser({ year, documentType: US_TAX_FORM, user });

    client.workflowInstances
      .getInstanceDocument({
        instanceId: id,
        documentId,
      })
      .then(buff => Promise.resolve(encrypt(buff, ENCRYPTION_KEY)))
      .then(UploadToS3({ id: userCollectiveName, year, documentType: US_TAX_FORM }))
      .then(({ Location: location }) => {
        doc.requestStatus = RECEIVED;
        doc.documentLink = location;
        return doc.save();
      })
      .then(() => res.sendStatus(200))
      .catch(err => {
        doc.requestStatus = ERROR;
        doc.save();
        logger.error('error saving tax form: ', err);
        res.sendStatus(400);
      });
  } else {
    res.sendStatus(200);
  }
}

function UploadToS3({ id, year, documentType }) {
  return function uploadToS3(buffer) {
    const bucket = HELLO_WORKS_S3_BUCKET;
    const key = createTaxFormFilename({ id, year, documentType });

    if (!s3) {
      // s3 may not be set in a dev env
{'fraction_non_alphanumeric': 0.13222269084774357, 'fraction_numerical': 0.008435259384226065, 'mean_word_length': 3.445173383317713, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4130127', 'n_tokens_mistral': 1598, 'n_tokens_neox': 1538, 'n_words': 371}