All files / src/services/api/products reviews.ts

74.57% Statements 44/59
66.66% Branches 24/36
60% Functions 12/20
75% Lines 39/52

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                                              21x           21x                           21x       38x 38x 6x   38x                 3x   3x   38x                           21x       155x 130x 179x     130x         21x         30x     30x 30x 30x 30x     30x   30x                         21x                                                                     21x           94x                   30x                       21x       21x                   21x         94x   21x                     21x 94x               2x                             21x                                               21x                                       21x               21x                  
import {
  useInfiniteQuery,
  UseInfiniteQueryOptions,
  useMutation,
  useQuery,
  UseQueryOptions,
} from "react-query";
import { customInstance } from "@services/api";
import {
  QKEY_EVENT_REVIEWS,
  QKEY_EVENT_REVIEW_STATS,
  QKEY_PUBLIC_EVENT_REVIEWS,
  QKEY_PUBLIC_EVENT_REVIEW_STATS,
} from "@constants/queryKeys";
import {
  EventPublicReviewListResponse,
  EventPublicReviewStats,
  EventReviewApiRow,
  EventReviewListResponse,
  EventReviewStats,
  ReviewRatingFilter,
} from "@features/Events/EventDetail/reviews/review.types";
 
/**
 * PayBuilder 034 — the event reviews reads and the one write.
 *
 * Every call here is gated on `isEventReviewsEnabled`; nothing in this module
 * should be reached with the flag off.
 */
 
/** The default page size for the Reviews tab. */
export const EVENT_REVIEWS_MAX = 25;
 
/**
 * The side panel previews at most four reviews (frames 7878-57940 / 7878-56665)
 * and shows "View all" only when the event has more than that.
 */
export const EVENT_REVIEWS_PREVIEW_MAX = 4;
 
/**
 * Every filter this app sends is FQL over the list view's own columns, so
 * combining them needs nothing special — `;` ANDs the sections.
 *
 * The parentheses are load-bearing: the endpoint ANDs its event + merchant
 * scope on AFTER parsing this, so an unwrapped top-level OR would bind looser
 * than the scope. Every filter this app sends must stay wrapped.
 *
 * `awaitingReply` carries the clock rather than reading one here, and is absent
 * rather than false when the caller does not want that filter — see below for
 * why the filter needs a timestamp at all, and why it must be the caller's.
 */
export const buildReviewFilter = (
  ratings: ReviewRatingFilter[],
  awaitingReply?: { nowSeconds: number },
): string | undefined => {
  const sections: string[] = [];
  if (ratings.length > 0) {
    sections.push(`(${ratings.map((r) => `rating:${r}`).join(",")})`);
  }
  if (awaitingReply) {
    // NOT `canReply`. That field is `sql:"-"` on ProductReviewView — the
    // handler closes it against the app clock after the read — so it has no
    // entry in the view's filter colmap, and the constructor drops an unknown
    // FQL key silently: the request would come back as the unfiltered list with
    // nothing to reveal that the filter had been ignored.
    //
    // The two columns the view does carry say the same thing, and are the form
    // ProductReviewListHandler documents: no reply yet, deadline still ahead.
    sections.push("(hasReply:false)");
    // `d<epoch>` is FQL's date literal, in whole seconds.
    sections.push(`(replyDeadlineAt:>d${awaitingReply.nowSeconds})`);
  }
  return sections.length > 0 ? sections.join(";") : undefined;
};
 
/**
 * The page-walk terminator for both infinite review reads.
 *
 * `page` is 1-based and `total` counts the whole filtered set, so the next page
 * exists while fewer rows are loaded than the count the endpoint reports — but
 * the empty page has to end it first. If `total` and the rows ever disagree (a
 * review deleted mid-scroll, a count and a list that drift), `loaded` stalls
 * below `total` while every further page comes back `[]`: without this the
 * walk keeps asking for `pages.length + 1` forever, "Load more" never goes
 * away, and the deep-link auto-pager above turns that into a request loop.
 */
const nextReviewPage = <T extends { data: unknown[] | null; total: number }>(
  lastPage: T | undefined,
  pages: (T | undefined)[],
): number | undefined => {
  if (!lastPage?.data?.length) return undefined;
  const loaded = pages.reduce(
    (count, page) => count + (page?.data?.length ?? 0),
    0,
  );
  return loaded < (lastPage?.total ?? 0) ? pages.length + 1 : undefined;
};
 
// customInstance is untyped here (it resolves to `any`), so the response shape
// is pinned on the wrapper's return type instead of a call-site generic.
export const getEventReviews = (
  merchantId: number,
  eventId: string | number,
  params?: { filter?: string; q?: string; max?: number; page?: number },
): Promise<EventReviewListResponse> => {
  const query = new URLSearchParams();
  // Newest first. The endpoint forces no ORDER BY of its own — page stability
  // is the caller's contract, so the sort is always sent.
  query.set("sort", "-createdAt");
  query.set("max", String(params?.max ?? EVENT_REVIEWS_MAX));
  Eif (params?.page) query.set("page", String(params.page));
  if (params?.filter) query.set("filter", params.filter);
  // Search runs server-side: the view's document is the comment plus the
  // reviewer's name, so a search matches who wrote it as well as what they said.
  if (params?.q) query.set("q", params.q);
 
  return customInstance({
    url: `/merchants/${merchantId}/products/${eventId}/reviews?${query.toString()}`,
    method: "GET",
  });
};
 
/**
 * A single page of reviews — what the side panel's four-card preview needs.
 *
 * `q` is part of the key, not just of the closure: without it a search would
 * reuse the unfiltered entry, and a focus refetch would write the filtered
 * response back into it.
 */
export const useGetEventReviews = (
  merchantId: number,
  eventId?: string,
  params?: { filter?: string; q?: string; max?: number; page?: number },
  options?: UseQueryOptions<EventReviewListResponse>,
) =>
  useQuery<EventReviewListResponse>(
    [
      QKEY_EVENT_REVIEWS,
      merchantId,
      eventId,
      params?.filter,
      params?.q,
      params?.max,
      params?.page,
    ],
    () => getEventReviews(merchantId, eventId as string, params),
    {
      enabled: Boolean(merchantId && eventId),
      // Re-keyed on every filter change; keeping the previous rows avoids a
      // skeleton flash each time a star chip is toggled.
      keepPreviousData: true,
      ...options,
    },
  );
 
/**
 * The Reviews tab's read: paged, because an event can collect far more than one
 * page of feedback and the tab is the only place the merchant can answer any of
 * it. The tab appends pages behind "Load more" rather than drawing a pager —
 * the list is cards, not a table.
 *
 * Keyed under the same `QKEY_EVENT_REVIEWS` root as the single-page read, so
 * publishing a reply invalidates both with one call.
 */
export const useGetEventReviewsInfinite = (
  merchantId: number,
  eventId?: string,
  params?: { filter?: string; q?: string },
  options?: UseInfiniteQueryOptions<EventReviewListResponse>,
) =>
  useInfiniteQuery<EventReviewListResponse>(
    [
      QKEY_EVENT_REVIEWS,
      "paged",
      merchantId,
      eventId,
      params?.filter,
      params?.q,
    ],
    ({ pageParam = 1 }) =>
      getEventReviews(merchantId, eventId as string, {
        ...params,
        page: pageParam,
      }),
    {
      enabled: Boolean(merchantId && eventId),
      keepPreviousData: true,
      getNextPageParam: nextReviewPage,
      ...options,
    },
  );
 
export const getEventReviewStats = (
  merchantId: number,
  eventId: string | number,
): Promise<EventReviewStats> =>
  customInstance({
    url: `/merchants/${merchantId}/products/${eventId}/reviews/stats`,
    method: "GET",
  });
 
/**
 * The summary is its own read on purpose: it describes the whole event, so it
 * must not carry the list's filters. Sharing one request would make the
 * distribution collapse to whatever the merchant last filtered by.
 */
export const useGetEventReviewStats = (
  merchantId: number,
  eventId?: string,
  options?: UseQueryOptions<EventReviewStats>,
) =>
  useQuery<EventReviewStats>(
    [QKEY_EVENT_REVIEW_STATS, merchantId, eventId],
    () => getEventReviewStats(merchantId, eventId as string),
    { enabled: Boolean(merchantId && eventId), ...options },
  );
 
/**
 * Publish the merchant's single public reply.
 *
 * Returns the review as it now reads, so the caller can render the published
 * reply without a refetch. There is no update or delete counterpart — once
 * published, a reply stands.
 */
export const usePublishReviewReply = (merchantId: number, eventId?: string) =>
  useMutation(
    ({
      reviewId,
      body,
    }: {
      reviewId: number;
      body: string;
    }): Promise<EventReviewApiRow> =>
      customInstance({
        url: `/merchants/${merchantId}/products/${eventId}/reviews/${reviewId}/reply`,
        method: "POST",
        data: { body },
      }),
  );
 
/**
 * The live event page's reads. Unauthenticated and product-scoped: no merchant
 * id, no reply eligibility, and a summary without the awaiting-reply count.
 *
 * Kept separate from the merchant hooks rather than sharing them with a flag —
 * these hit different endpoints and return narrower shapes, and mixing the two
 * is how a merchant-only field ends up on a public page.
 */
export const getPublicEventReviews = (
  productId: string | number,
  params?: { filter?: string; max?: number; page?: number },
): Promise<EventPublicReviewListResponse> => {
  const query = new URLSearchParams();
  query.set("sort", "-createdAt");
  query.set("max", String(params?.max ?? EVENT_REVIEWS_MAX));
  if (params?.page) query.set("page", String(params.page));
  if (params?.filter) query.set("filter", params.filter);
 
  return customInstance({
    url: `/products/${productId}/reviews?${query.toString()}`,
    method: "GET",
  });
};
 
/**
 * The live page's list read, paged.
 *
 * The block has no pager of its own — it is a column on a payment form, not a
 * table — so a single capped read published the newest 25 reviews and left the
 * rest unreachable while the distribution above it counted all of them. This
 * appends behind the same "Show more" the portal's tab uses.
 */
export const useGetPublicEventReviewsInfinite = (
  productId?: string | number,
  params?: { filter?: string },
  options?: UseInfiniteQueryOptions<EventPublicReviewListResponse>,
) =>
  useInfiniteQuery<EventPublicReviewListResponse>(
    [QKEY_PUBLIC_EVENT_REVIEWS, productId, params?.filter],
    ({ pageParam = 1 }) =>
      getPublicEventReviews(productId as string, {
        ...params,
        page: pageParam,
      }),
    {
      enabled: Boolean(productId),
      keepPreviousData: true,
      getNextPageParam: nextReviewPage,
      ...options,
    },
  );
 
export const getPublicEventReviewStats = (
  productId: string | number,
): Promise<EventPublicReviewStats> =>
  customInstance({
    url: `/products/${productId}/reviews/stats`,
    method: "GET",
  });
 
export const useGetPublicEventReviewStats = (
  productId?: string | number,
  options?: UseQueryOptions<EventPublicReviewStats>,
) =>
  useQuery<EventPublicReviewStats>(
    [QKEY_PUBLIC_EVENT_REVIEW_STATS, productId],
    () => getPublicEventReviewStats(productId as string),
    { enabled: Boolean(productId), ...options },
  );