All files / src/services/api customer.ts

42.5% Statements 17/40
25.8% Branches 8/31
26.66% Functions 4/15
42.5% Lines 17/40

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226                      99x                                     99x 8x           99x                                                                                     99x         784x 784x   784x     8x       8x 8x                                     784x             99x                                                                                                 99x                           99x         1x                                               99x                      
import { UseQueryOptions, useInfiniteQuery, useQuery } from "react-query";
import { customInstance } from "./index";
import { ROWS_PER_PAGE } from "@hooks/common/usePagination";
import { Customer } from "@customTypes/customer.types";
import { useGetCurrentMerchantId } from "@hooks/common";
import { ProductParams } from "./products/queryFactory";
import { useAppDispatch } from "@redux/hooks";
import { updatePermissions } from "@redux/slices/app";
import { MemberRoleName } from "@customTypes/team.member";
import { QKEY_LIST_CUSTOMERS } from "@constants/queryKeys";
 
export const getCustomers = ({
  queryString,
  page,
  sorting,
  searchQuery,
  merchID,
  maxRowsPerPage = ROWS_PER_PAGE,
}: ProductParams & { merchID: number }) => {
  const search = searchQuery ? `&q="${searchQuery}"` : "";
  const filterQuery = queryString ? `filter=${queryString}` : "";
 
  return customInstance({
    url: `/merchants/${merchID}/customers?${filterQuery}&sort=${
      sorting || "-id"
    }${search}&page=${page}&max=${maxRowsPerPage}`,
    method: "GET",
  });
};
 
export const getCustomerById = (merchID: number, id?: number) => {
  return customInstance({
    url: `/merchants/${merchID}/customers/${id}`,
    method: "GET",
  });
};
 
export const useGetCustomers = (
  params: ProductParams,
  options: Omit<
    UseQueryOptions<any, any, any, any>,
    "queryKey" | "queryFn"
  > = {},
) => {
  const dispatch = useAppDispatch();
  const { merchantId } = useGetCurrentMerchantId();
 
  return useQuery(
    [
      "list-all-customers",
      params.sorting,
      params.page,
      params.searchQuery,
      params.queryString,
      params.maxRowsPerPage,
      merchantId,
    ],
    async () => {
      const data = await getCustomers({
        merchID: merchantId,
        ...params,
      });
      return data;
    },
    {
      ...options,
      retry: 2,
      onError(err: any) {
        if (err.not_authorized) {
          dispatch(
            updatePermissions({
              customers_list: true,
            }),
          );
        }
      },
    },
  );
};
 
export const useGetCustomerById = (
  id?: number,
  overrideMerchantId?: number,
  merchantID?: number,
) => {
  const dispatch = useAppDispatch();
  const { merchantId } = useGetCurrentMerchantId();
 
  const { data, isLoading, isRefetching } = useQuery<Customer>(
    ["customer", id],
    async () => {
      const usedMerchantId = merchantID
        ? merchantID
        : overrideMerchantId ?? merchantId;
 
      const data = await getCustomerById(usedMerchantId, id);
      return data;
    },
    {
      enabled: !!id && !!(merchantId || overrideMerchantId),
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      retry: 1,
      onError(err: any) {
        if (err.not_authorized) {
          dispatch(
            updatePermissions({
              view_customer: true,
            }),
          );
        }
      },
    },
  );
 
  return {
    data,
    isLoading: isLoading || isRefetching,
    isDataLoading: isLoading,
  };
};
 
export const useGetInfiniteCustomers = (params: any) => {
  const { merchantId } = useGetCurrentMerchantId();
  const { data, isLoading, isFetching, fetchNextPage, hasNextPage, refetch } =
    useInfiniteQuery(
      [QKEY_LIST_CUSTOMERS, params.page, params.searchQuery],
      async ({ pageParam = 1 }) => {
        const data = await getCustomers({
          merchID: merchantId,
          ...params,
          page: pageParam,
        });
 
        const numberOfPages = Math.ceil(
          Number(data.total ?? 0) / ROWS_PER_PAGE,
        );
 
        return {
          data: data.data,
          total: data.total,
          nextCursor: numberOfPages >= pageParam + 1 ? pageParam + 1 : null,
        };
      },
      {
        enabled: !!merchantId,
        getNextPageParam: (lastPage: any, x) => {
          return lastPage.nextCursor;
        },
      },
    );
 
  const customers = data?.pages?.[0]?.data
    ? data.pages.map((row: any) => row.data).flat()
    : [];
 
  return {
    customers,
    isLoading: isLoading || isFetching,
    fetchNextPage,
    hasNextPage,
    refetch,
  };
};
 
export interface InviteType {
  //title: string;
  InviteMember?: boolean;
  MemberRole: MemberRoleName;
  Emails: string[];
}
export const inviteMembers = (id: number, data: InviteType) => {
  return customInstance({
    url: `/accounts/${id}/members-invites`,
    method: "POST",
    data,
  });
};
 
export interface CreateMemberTypes {
  email: string;
  memberRole: MemberRoleName;
  merchantId: string | number;
}
 
export const createTeamMember = ({
  email,
  memberRole,
  merchantId,
}: CreateMemberTypes) => {
  return customInstance({
    url: `/accounts/${merchantId}/members`,
    method: "POST",
    data: {
      email: email,
      memberRole: memberRole,
      inviteMember: true,
    },
  });
};
 
export interface EditMemberTypes {
  merchantId: string | number;
  accID: string | number;
  data: {
    firstName: string;
    lastName: string;
    occupation: string;
    employer: string;
    memberRole: MemberRoleName;
    roleOnly: boolean;
  };
}
 
export const editTeamMember = ({
  merchantId,
  accID,
  data,
}: EditMemberTypes) => {
  return customInstance({
    url: `/accounts/${merchantId}/members/${accID}`,
    method: "PATCH",
    data,
  });
};