HEX
Server: nginx/1.18.0
System: Linux test-ipsremont 5.4.0-214-generic #234-Ubuntu SMP Fri Mar 14 23:50:27 UTC 2025 x86_64
User: ips (1000)
PHP: 8.0.30
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/quadcode.com/builds/-DFbjr9L/0/foach/quadcode.com/src/routes/api/Pipedrive.ts
import Pipedrive from 'pipedrive';
import { env } from '$env/dynamic/public';
import escapeRegExp from '../../utils/escapeRegExp';
import type { IRequest } from '../../type/form';
import WLogger from './WLogger';
import Sanitizing from './Sanitizing';

const apiClient = new Pipedrive.ApiClient();

const apiToken = apiClient.authentications.api_key;
apiToken.apiKey = env?.PUBLIC_API_KEY;

const apiInstance = new Pipedrive.PersonsApi(apiClient);
const apiInstanceLead = new Pipedrive.LeadsApi(apiClient);

const initialInvestments = {
  0: 47,
  1: 48,
  2: 49,
  3: 50,
  4: 51,
  5: 52,
};

const PIPEDRIVE_FIELDS = {
  LANDING_URL: '60d21dc88f7166c7d9c9581d960d5e0a1d7c0700',
  UTM_CAMPAIGN: '326a053a02f760969835c6d66320ba8146971532',
  UTM_MEDIUM: '06b0e97e69412bf996c7cbf3b0eb7259d2117e6b',
  UTM_SOURCE: '3e1cca698c4828ffa2545d72fa47250f1db952f9',
  TEXT: '921534be957ee8cf90d2b5d394f121856020a92a',
  GCLID: 'b011c07cae8c07827c38a04ef5a11d481b510c62',
  LANG: '94f45dcab632c59ee4d51e7cb8b97440d228fd6d',
  ADDITIONAL: '7737f00c7861b969d3a888a1ee51ab72bbc265df',
  BUSINESS_IDENTIFICATION: '8ef4834cd30972e74ef404a671ae3c760f0a7d40',
  INITIAL_INVESTMENT: '41be2a605ac5c07491b38614095b6bbef81d4ad5',
  REGION: 'b0bb331b1e7fba2c621219cc290a2e72acdfb4de',
  CALENDLY_SCHEDULED: '00e5e40c0247bc7eae2aadfd9a406ad373b7ac28',
};

const searchPerson = async (email: string) => {
  const opts = {
    exactMatch: true,
  };

  if (!email) {
    WLogger.log('error', '[Pipedrive]: SEARCH PERSON END', Sanitizing({ email: email }));
    return;
  }

  return await apiInstance
    .searchPersons(email, opts)
    .then((res) => {
      WLogger.log('info', '[Pipedrive]: SEARCH PERSON END', { ...res });

      return res;
    })
    .catch((error) => {
      WLogger.log('error', '[Pipedrive]: SEARCH PERSON END', { ...error });
      return error;
    });
};

const addPerson = async (data) => {
  if (!data.email || !data.phone || !data.name || !data.add_time) {
    WLogger.log('error', '[Pipedrive]: ADD PERSON END', Sanitizing(data));
    return;
  }

  return await apiInstance
    .addPerson(data)
    .then((res) => {
      WLogger.log('info', '[Pipedrive]: ADD PERSON END', { ...res });

      return res;
    })
    .catch((error) => {
      WLogger.log('error', '[Pipedrive]: ADD PERSON END', { ...error });

      return error;
    });
};

const addLead = async (data) => {
  if (!data.title || !data.person_id) {
    WLogger.log('error', '[Pipedrive]: ADD LEAD END', Sanitizing(data));
    return;
  }

  return await apiInstanceLead
    .addLead(data)
    .then((res) => {
      WLogger.log('info', '[Pipedrive]: ADD LEAD END', { ...res });

      return res;
    })
    .catch((error) => {
      WLogger.log('error', '[Pipedrive]: ADD LEAD END', { ...error });

      return error;
    });
};

const sendPipedrive = async (values: IRequest) => {
  const additional = { ...values };
  WLogger.log('info', '[Pipedrive]: START', Sanitizing(additional));

  if (!env?.PUBLIC_API_KEY) {
    WLogger.log('error', '[Pipedrive]: END', { error: `PUBLIC_API_KEY: undefined` });

    return;
  }

  let personId = null;

  WLogger.log('info', '[Pipedrive]: SEARCH PERSON START', Sanitizing(additional));

  const result = await searchPerson(additional['email']);

  if (result?.success && result?.data?.items?.[0]?.item) {
    personId = result.data.items[0].item.id;
  }

  if (!personId) {
    const date = new Date();
    const dateFormat = `${date.getFullYear()}-${
      date.getMonth() + 1
    }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;

    const data = {
      name: escapeRegExp(additional['name'], false),
      email: additional['email'],
      phone: additional['phone'].replace(/[^+\d]/g, ''),
      add_time: dateFormat,
    };

    WLogger.log('info', '[Pipedrive]: ADD PERSON START', Sanitizing(data));

    const result = await addPerson(data);

    if (result?.success && result?.data?.id) {
      personId = result.data.id;
    }
  }

  const data = {
    title: `New lead from ${additional['landing_url']} from ${additional['email']}`,
    person_id: personId,
    [PIPEDRIVE_FIELDS.TEXT]: escapeRegExp(additional['text'], false),
  };

  if (additional?.['utm_campaign']) {
    data[PIPEDRIVE_FIELDS.UTM_CAMPAIGN] = escapeRegExp(additional?.['utm_campaign'], false);
  }

  if (additional?.['utm_medium']) {
    data[PIPEDRIVE_FIELDS.UTM_MEDIUM] = escapeRegExp(additional?.['utm_medium'], false);
  }

  if (additional?.['utm_source']) {
    data[PIPEDRIVE_FIELDS.UTM_SOURCE] = escapeRegExp(additional?.['utm_source'], false);
  }

  if (additional?.['gclid']) {
    data[PIPEDRIVE_FIELDS.GCLID] = escapeRegExp(additional?.['gclid'], false);
  }

  if (additional?.['landing_url']) {
    data[PIPEDRIVE_FIELDS.LANDING_URL] = escapeRegExp(additional?.['landing_url'], false);
  }

  if (additional?.['language']) {
    data[PIPEDRIVE_FIELDS.LANG] = escapeRegExp(additional?.['language'], false);
  }

  if (personId) {
    WLogger.log('info', '[Pipedrive]: ADD LEAD START', Sanitizing(data));

    await addLead(data);
  } else {
    WLogger.log('error', '[Pipedrive]: END', { error: `person_id: ${personId}` });
  }

  WLogger.log('info', '[Pipedrive]: END', Sanitizing(additional));
};

export default sendPipedrive;