All files / src/hooks useSaveConnectedCompany.tsx

91.66% Statements 22/24
100% Branches 5/5
100% Functions 6/6
91.66% Lines 22/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 823x 3x 3x 3x 3x                       6x 4x         2x               3x 2x   1x     12x 12x 12x 12x   6x                                 6x 3x             3x     3x     3x             12x    
import { useMutation } from '@tanstack/react-query';
import { request } from '@procore/core-http';
import toast from 'react-hot-toast/headless';
import { useI18nContext } from '@procore/core-react';
import { useAddCompanyContext } from '../Context/AddCompanyContext';
 
interface VendorConnection {
  businessId: string;
  vendorId: number | null;
}
 
export function getUrl(
  companyId: number,
  vendorId: number | null,
  projectId?: string
) {
  if (projectId) {
    return vendorId
      ? `/rest/v1.1/projects/${projectId}/vendors/${vendorId}/actions/add`
      : `/rest/v1.0/projects/${projectId}/connected_vendors`;
  }
 
  return `/rest/v1.0/companies/${companyId}/connected_vendors`;
}
 
export function getRedirectUrl(
  vendorId: string,
  companyId: number,
  projectId?: string | undefined
) {
  if (projectId) {
    return `${window.location.origin}/${projectId}/project/directory/vendors/${vendorId}/edit?add_vendor_success=true`;
  }
  return `${window.location.origin}/${companyId}/company/directory/vendors/${vendorId}/edit?add_vendor_success=true`;
}
 
export function useSaveConnectedCompany() {
  const i18n = useI18nContext();
  const { companyId, projectId } = useAddCompanyContext();
  const mutation = useMutation({
    mutationFn: async (connection: VendorConnection) => {
      const response = await request(
        getUrl(companyId, connection.vendorId, projectId),
        {
          method: 'post',
          body: JSON.stringify({
            company_id: companyId,
            project_id: projectId,
            business_id: connection.businessId,
          }),
          headers: {
            'Procore-Company-ID': companyId.toString(),
            'Content-Type': 'application/json',
          },
        }
      );
 
      // eslint-disable-next-line no-magic-numbers
      if (response.status !== 201) {
        throw new Error(
          i18n.t(
            'views.generic.directory.add_company_package.hook_errors.add_failed_toast'
          )
        );
      }
 
      return response.json();
    },
    onSuccess(data: { id: string }) {
      window.location.href = getRedirectUrl(data.id, companyId, projectId);
    },
    onError() {
      toast(
        i18n.t(
          'views.generic.directory.add_company_package.hook_errors.add_failed_toast'
        )
      );
    },
  });
  return mutation;
}