Skip to content

suryavi/back-up

Repository files navigation

const hubspot = require("@hubspot/api-client");
const { SECRET_NAME } = require("./config.js");
const {
  SimplePublicObjectWithAssociations,
  BatchInputSimplePublicObjectBatchInputForCreate,
  AssociationSpecAssociationCategoryEnum,
} = require("@hubspot/api-client/lib/codegen/crm/companies/index.js");

/**
 * Associations
 */
const associations = {
  CONTRATOS: "2-172399712",
  LICENSE: "2-172399663",
  LINE_ITEMS: "0-8",
  COMPANY: "0-2",
};

const QualificationName = {
  CONTRATOS: "p243643392_contratos",
  LICENSE: "p243643392_licenses",
  APARTMENT: "p243643392_apartments",
  LINE_ITEMS: "line items",
  COMPANY: "companies",
};

/**
 * This function use to fetch line items information
 * @param {hubspot.Client} hubspotClient - HubSpot client instance
 * @param {BatchInputSimplePublicObjectBatchInputForCreate} licenses - lineItemId id
 * @returns  {Promise<SimplePublicObjectWithAssociations>}
 */
async function createLicenses(hubspotClient, licenses) {
  try {
    console.log(JSON.stringify(licenses));
    const response = await hubspotClient.crm.objects.batchApi.create(associations.LICENSE, { inputs: licenses });
    console.log(`Licenses created: ${JSON.stringify(response?.data)}`);
    return response?.data;
  } catch (err) {
    console.error(`Error on ${createLicenses.name}: ${err?.message}`);
    return;
  }
}

// Generate random ID (example: 8-character alphanumeric)
function generateRandomId(length = 8) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

/**
 * This function use to fetch line items information
 * @param {hubspot.Client} hubspotClient - HubSpot client instance
 * @param {*} lineItemId - lineItemId id
 * @returns  {Promise<SimplePublicObjectWithAssociations>}
 */
async function getLineItem(hubspotClient, lineItemId) {
  try {
    const lineItemResponse = await hubspotClient.crm.lineItems.basicApi.getById(lineItemId, ["name", "quantity"], undefined);
    return lineItemResponse;
  } catch (err) {
    console.error(`Error on ${getLineItem.name}: ${err?.message}`);
    return;
  }
}

/**
 * This function use to fetch company information
 * @param {hubspot.Client} hubspotClient - HubSpot client instance
 * @param {string} companyId - Company ID
 * @returns {Promise<SimplePublicObjectWithAssociations>}
 */
async function getCompany(hubspotClient, companyId) {
  try {
    const companyResponse = await hubspotClient.crm.companies.basicApi.getById(companyId, ["vat", "iban", "email4__c"], undefined, [
      associations.CONTRATOS,
    ]);
    return companyResponse;
  } catch (err) {
    console.error(`Error on ${getCompany.name}: ${err?.message}`);
    return;
  }
}

/**
 * This function use to fetch  line items and deal associations.
 * @param {hubspot.Client} hubspotClient - HubSpot client instance
 * @param {string} dealId - Deal
 * @returns {Promise<{ deal: SimplePublicObject, lineItems: SimplePublicObject[], contractId: string }> }
 */
async function getDealAssociations(hubspotClient, dealId) {
  let response = {};
  try {
    const dealResponse = await hubspotClient.crm.deals.basicApi.getById(dealId, [], undefined, Object.values(associations));
    response["deal"] = dealResponse;

    const lineItems = dealResponse?.associations?.[QualificationName.LINE_ITEMS]?.results;
    if (lineItems) response["lineItems"] = await Promise.all(lineItems.map(async (item) => await getLineItem(hubspotClient, item.id)));

    const companyId = dealResponse?.associations?.companies?.results?.[0]?.id;
    if (companyId) {
      const company = await getCompany(hubspotClient, companyId);
      console.log(company);
      response["contractId"] = company?.associations?.[QualificationName.CONTRATOS]?.results?.[0]?.id;
    }

    console.log(response);
  } catch (err) {
    console.error(`Error on ${getDealAssociations.name}: ${err?.message}`);
    return;
  }

  return response;
}

/**
 * Main Function trigger from workflow
 * @param {*} event - Workflow event
 * @param {*} callback - Workflow callback
 */
exports.main = async (event, callback) => {
  console.log(`Start main and record id ${event?.object?.objectId}`);

  let data = {};
  const hubspotClient = new hubspot.Client({
    accessToken: SECRET_NAME,
  });

  try {
    const { lineItems, contractId } = await getDealAssociations(hubspotClient, event?.object?.objectId);

    console.log(contractId);
    for await (const lineItem of lineItems) {
      let licenseBatch = [];
      for (let quantityIndex = 0; quantityIndex < lineItem?.properties?.quantity; quantityIndex++) {
        const productName = lineItem?.properties?.name || "UnknownProduct";
        licenseBatch.push({
          properties: {
            license_id: `${productName} - ${generateRandomId()}`,
            status: "Unused",
          },
          associations: [
            {
              to: {
                id: contractId,
              },
              types: [
                {
                  associationCategory: AssociationSpecAssociationCategoryEnum.UserDefined,
                  associationTypeId: 71,
                },
              ],
            },
          ],
        });
      }
      await createLicenses(hubspotClient, licenseBatch);
    }

    data["message"] = "Licenses created successfully.";
  } catch (e) {
    data["error"] = e?.message || "An error occurred while processing the workflow.";
  }

  callback({
    outputFields: data,
  });
};

this.main(
  {
    origin: {
      portalId: 1,
      actionDefinitionId: 2,
    },
    object: {
      objectType: "DEAL",
      objectId: 145845248714,
    },
    inputFields: {},
    callbackId: "ap-123-456-7-8",
  },
  (response) => {
    console.log(`Workflow response: ${JSON.stringify(response)}`);
  }
);

About

No description, website, or topics provided.

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published