All files / src/hooks useCreateCompanyVendorsQuery.tsx

87.5% Statements 21/24
100% Branches 3/3
100% Functions 6/6
87.5% Lines 21/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 663x 3x 3x   3x 3x     4x 3x   1x               2x 2x         8x 8x 8x 8x   4x                       4x 2x             2x     2x     2x             8x    
import { useMutation } from '@tanstack/react-query';
import { request } from '@procore/core-http';
import toast from 'react-hot-toast/headless';
import { VendorData } from '../models/VendorData';
import { useI18nContext } from '@procore/core-react';
import { useAddCompanyContext } from '../Context/AddCompanyContext';
 
export function getUrl(projectId: string | undefined) {
  if (projectId) {
    return `/rest/v1.1/projects/${projectId}/vendors`;
  }
  return '/rest/v1.0/vendors';
}
 
export function getRedirectUrl(
  companyId: number,
  vendorId: string,
  projectId?: string
) {
  if (projectId) {
    return `${window.location.origin}/${projectId}/project/directory/vendors/${vendorId}/edit?create_vendor_success=true`;
  }
  return `${window.location.origin}/${companyId}/company/directory/vendors/${vendorId}/edit?create_vendor_success=true`;
}
 
export function useCreateCompanyVendorsQuery() {
  const i18n = useI18nContext();
  const { companyId, projectId } = useAddCompanyContext();
  const mutation = useMutation({
    mutationFn: async (vendor: VendorData) => {
      const response = await request(getUrl(projectId), {
        method: 'post',
        body: JSON.stringify({
          company_id: companyId,
          vendor,
        }),
        headers: {
          'Procore-Company-ID': companyId.toString(),
          'Content-Type': 'application/json',
        },
      });
 
      if (response.status !== 201) {
        throw new Error(
          i18n.t(
            'views.generic.directory.add_company_package.hook_errors.create_vendor_failed'
          )
        );
      }
 
      return response.json();
    },
    onSuccess(data: { id: string }) {
      window.location.href = getRedirectUrl(companyId, data.id, projectId);
    },
    onError() {
      toast(
        i18n.t(
          'views.generic.directory.add_company_package.hook_errors.create_vendor_failed_toast'
        )
      );
    },
  });
  return mutation;
}