Extracting and Attaching Files from an External API to NetSuite Transactions

This guide outlines a basic script for integrating with an external API to download bill files (images/PDFs) and attach them to the related transactions in NetSuite. The script can be adapted for various projects that involve downloading and processing files linked to transactions, such as receipts, invoices, or reimbursements.

The script saves the downloaded files in the NetSuite File Cabinet. Ensure you have the correct folder ID where files will be saved.

This script fetches bill data from an external API, downloads the associated bill files, and attaches them to the relevant transaction in NetSuite. It is triggered by a User Event that runs after a transaction is created in NetSuite.

/**

 * @NApiVersion 2.1

 * @NScriptType UserEventScript

 */

define([‘N/https’, ‘N/log’, ‘N/encode’, ‘N/runtime’, ‘N/file’, ‘N/record’, ‘N/render’], function(https, log, encode, runtime, file, record, render) {

   

  // Helper function to fetch JSON data from API

  function fetchJson(url, headers) {

    let response = https.get({ url: url, headers: headers });

    if (response.code !== 200) {

      log.error({ title: ‘API Call Failed’, details: response.body });

      return null;

    }

    return JSON.parse(response.body);

  }

  // Helper function to get script parameters (dummy values)

  function getScriptParameters(){

    try {

      let objScript = runtime.getCurrentScript();

      let apiBase = ‘https://api.example.com/’;

      return {

        apiBase: apiBase,

        apiTokenUrl: apiBase + ‘token’,

        apiBillUrl: apiBase + ‘bills/’,

        folderId: 12345, // Dummy folder ID

        saveAsPdf: true

      };

    } catch (e) {

      log.error(‘getScriptParameters’, e.toString());

    }

  }

  // Helper function to get the access token (dummy authentication)

  function getAccessToken(authCode, apiTokenUrl) {

    try {

      let response = https.post({

        url: apiTokenUrl,

        headers: { ‘Authorization’: ‘Basic ‘ + authCode },

        body: ‘grant_type=client_credentials’

      });

      if (response.code !== 200) {

        log.error(‘Token Request Failed’, response.body);

        throw new Error(‘Failed to obtain access token’);

      }

      return JSON.parse(response.body).access_token;

    } catch (e) {

      log.error(‘getAccessToken’, e.toString());

      return null;

    }

  }

  // Helper function to attach file to transaction

  function attachFileToTransaction(fileId, transactionId) {

    try {

      record.attach({

        record: { type: ‘file’, id: fileId },

        to: { type: ‘transaction’, id: transactionId }

      });

    } catch (e) {

      log.error(‘attachFileToTransaction’, e.toString());

    }

  }

  // Helper function to download bill file and attach it to the transaction

  function downloadBillFile(billId, transactionId, accessToken, objScriptParams) {

    try {

      let billUrl = objScriptParams.apiBillUrl + billId;

      let billData = fetchJson(billUrl, {

        ‘Authorization’: ‘Bearer ‘ + accessToken

      });

      if (!billData || !billData.invoice_urls) {

        log.error(‘Bill data missing’, ‘No invoice URLs found’);

        return;

      }

      for (let i = 0; i < billData.invoice_urls.length; i++) {

        let fileUrl = billData.invoice_urls[i];

        let fileResponse = https.get({ url: fileUrl });

        let fileData = fileResponse.body;

        let fileName = ‘bill_’ + billId + ‘_’ + i + ‘.pdf’; // Example file naming

        let fileObj = file.create({

          name: fileName,

          fileType: file.Type.PDF,

          contents: fileData,

          folder: objScriptParams.folderId

        });

        let fileId = fileObj.save();

        attachFileToTransaction(fileId, transactionId);

      }

    } catch (e) {

      log.error(‘downloadBillFile’, e.toString());

    }

  }

  // After Submit event handler

  function afterSubmit(context) {

    if (context.type !== context.UserEventType.CREATE) return;

    try {

      let objScriptParams = getScriptParameters();

      let recTransaction = context.newRecord;

      let transactionUrl = recTransaction.getValue(‘custbody_transaction_url’);

      if (!transactionUrl) {

        log.error(‘Missing Transaction URL’, ‘The record does not have a transaction URL.’);

        return;

      }

      let billId = transactionUrl.split(‘/’).pop(); // Extract bill ID from URL

      let accessToken = getAccessToken(‘dummyAuthCode’, objScriptParams.apiTokenUrl);

      if (!accessToken) return;

      // Download and attach the bill file

      downloadBillFile(billId, recTransaction.id, accessToken, objScriptParams);

    } catch (e) {

      log.error(‘Error in afterSubmit’, e.toString());

    }

  }

  return {

    afterSubmit: afterSubmit

  };

});

This script simplifies the process of downloading and attaching files from an external API to NetSuite transactions. It can be modified to handle different types of documents or API integrations based on your specific needs.

Leave a comment

Your email address will not be published. Required fields are marked *