All files / apps/host/src/hooks useProfileRequests.ts

100% Statements 81/81
93.5% Branches 72/77
100% Functions 18/18
100% Lines 80/80

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                                                          1x 1x                                     4x       1x 24x 1x     23x     1x 20x 17x     3x 2x   2x 1x       2x     1x 26x 86x 6x       20x     1x 16x 2x     14x 14x 24x   24x 4x     20x   20x 3x     17x 17x     14x 3x 10x 2x     8x 8x           11x 11x   11x 1x     10x 16x       13x 65x   65x 14x     65x     13x     1x 14x 1x           13x   13x       13x 13x             13x 9x   9x           4x 4x   4x           1x 2x         2x           1x 4x   4x     1x         4x   4x         4x           1x 3x   1x         1x 3x   1x        
import { useQuery } from '@tanstack/react-query';
 
import { REQUEST_POLICY, runRequestEffect } from '@repo/services/effectRequest';
 
import {
  type ChartRequestActivity,
  type ChartRequestPeriod,
  type ChartRequestPeriodInfo,
} from '@/components/ChartRequest';
 
import { CACHE_TIME, ENDPOINTS, QUERY_KEYS } from '@/constants/apis';
 
import { RequestCategory } from '@/types/request';
 
import { https } from '@/services/mainHttpClient';
 
interface ProfileRequestSummary {
  week: ChartRequestPeriodInfo;
  month: ChartRequestPeriodInfo;
}
 
interface ProfileRequestSummaryResponse {
  data?: unknown;
}
 
interface UseProfileRequestOptions {
  enabled?: boolean;
}
 
const REQUEST_CATEGORY_ORDER: RequestCategory[] = Object.values(RequestCategory);
const REQUEST_CATEGORY_ALIAS_MAP: Record<string, RequestCategory> = {
  [RequestCategory.TIME_OFF]: RequestCategory.TIME_OFF,
  timeOff: RequestCategory.TIME_OFF,
  time_off: RequestCategory.TIME_OFF,
  timeoff: RequestCategory.TIME_OFF,
 
  [RequestCategory.BOOK_ROOM]: RequestCategory.BOOK_ROOM,
  bookRoom: RequestCategory.BOOK_ROOM,
  book_room: RequestCategory.BOOK_ROOM,
 
  [RequestCategory.MAINTENANCE]: RequestCategory.MAINTENANCE,
 
  [RequestCategory.REALLOCATION]: RequestCategory.REALLOCATION,
 
  [RequestCategory.MEAL_RESERVATION]: RequestCategory.MEAL_RESERVATION,
  mealReservation: RequestCategory.MEAL_RESERVATION,
  meal_reservation: RequestCategory.MEAL_RESERVATION,
};
 
const createEmptyPeriod = (): ChartRequestPeriodInfo => ({
  activities: [],
});
 
const resolveRequestCategory = (value: unknown): RequestCategory | null => {
  if (typeof value !== 'string') {
    return null;
  }
 
  return REQUEST_CATEGORY_ALIAS_MAP[value] ?? null;
};
 
const parseCount = (value: unknown) => {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value;
  }
 
  if (typeof value === 'string' && value.trim().length > 0) {
    const parsed = Number(value);
 
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }
 
  return null;
};
 
const pickPeriodPayload = (payload: Record<string, unknown>, keys: string[]) => {
  for (const key of keys) {
    if (key in payload) {
      return payload[key];
    }
  }
 
  return undefined;
};
 
const normalizePeriodPayload = (payload: unknown): ChartRequestPeriodInfo => {
  if (!payload || typeof payload !== 'object') {
    return createEmptyPeriod();
  }
 
  const counterByCategory = new Map<RequestCategory, number>();
  const appendActivity = (category: unknown, count: unknown) => {
    const resolvedCategory = resolveRequestCategory(category);
 
    if (!resolvedCategory) {
      return;
    }
 
    const parsedCount = parseCount(count);
 
    if (parsedCount === null || parsedCount < 0) {
      return;
    }
 
    const previousCount = counterByCategory.get(resolvedCategory) ?? 0;
    counterByCategory.set(resolvedCategory, previousCount + parsedCount);
  };
 
  if (Array.isArray(payload)) {
    payload.forEach(item => {
      if (!item || typeof item !== 'object') {
        return;
      }
 
      const itemRecord = item as Record<string, unknown>;
      appendActivity(
        itemRecord.category ?? itemRecord.type ?? itemRecord.name,
        itemRecord.count ?? itemRecord.total ?? itemRecord.value,
      );
    });
  } else {
    const payloadRecord = payload as Record<string, unknown>;
    const activities = payloadRecord.activities;
 
    if (Array.isArray(activities)) {
      return normalizePeriodPayload(activities);
    }
 
    Object.entries(payloadRecord).forEach(([category, count]) => {
      appendActivity(category, count);
    });
  }
 
  const activities = REQUEST_CATEGORY_ORDER.reduce<ChartRequestActivity[]>((result, category) => {
    const count = counterByCategory.get(category);
 
    if (typeof count === 'number' && count > 0) {
      result.push({ category, count });
    }
 
    return result;
  }, []);
 
  return { activities };
};
 
export const normalizeProfileRequestSummary = (payload: unknown): ProfileRequestSummary => {
  if (!payload || typeof payload !== 'object') {
    return {
      week: createEmptyPeriod(),
      month: createEmptyPeriod(),
    };
  }
 
  const rootPayload = payload as Record<string, unknown>;
  const dataPayload =
    rootPayload.data && typeof rootPayload.data === 'object' && !Array.isArray(rootPayload.data)
      ? (rootPayload.data as Record<string, unknown>)
      : rootPayload;
 
  const weekPayload = pickPeriodPayload(dataPayload, ['week', 'lastWeek', 'weekly', 'last-week']);
  const monthPayload = pickPeriodPayload(dataPayload, [
    'month',
    'lastMonth',
    'monthly',
    'last-month',
  ]);
 
  if (!weekPayload && !monthPayload) {
    const fallbackPeriod = normalizePeriodPayload(dataPayload);
 
    return {
      week: fallbackPeriod,
      month: fallbackPeriod,
    };
  }
 
  const normalizedWeek = weekPayload ? normalizePeriodPayload(weekPayload) : null;
  const normalizedMonth = monthPayload ? normalizePeriodPayload(monthPayload) : null;
 
  return {
    week: normalizedWeek ?? normalizedMonth ?? createEmptyPeriod(),
    month: normalizedMonth ?? normalizedWeek ?? createEmptyPeriod(),
  };
};
 
const fetchProfileRequestSummary = async (endpoint: string, signal?: AbortSignal) => {
  const [week, month] = await Promise.all([
    fetchProfileRequestPeriod(endpoint, 'week', signal),
    fetchProfileRequestPeriod(endpoint, 'month', signal),
  ]);
 
  return {
    week,
    month,
  };
};
 
const appendPeriodQuery = (endpoint: string, period: ChartRequestPeriod = 'week') => {
  const delimiter = endpoint.includes('?') ? '&' : '?';
 
  return `${endpoint}${delimiter}period=${period}`;
};
 
const fetchProfileRequestPeriod = async (
  endpoint: string,
  period: ChartRequestPeriod = 'week',
  querySignal?: AbortSignal,
) =>
  runRequestEffect(
    async signal => {
      const response = await https.get<ProfileRequestSummaryResponse>(
        appendPeriodQuery(endpoint, period),
        { signal },
      );
 
      return normalizeProfileRequestSummary(response.data)[period];
    },
    REQUEST_POLICY.READ,
    querySignal,
  );
 
export const useGetProfileMyRequests = ({ enabled = true }: UseProfileRequestOptions = {}) =>
  useQuery<ProfileRequestSummary>({
    queryKey: [QUERY_KEYS.PROFILE_MY_REQUESTS],
    queryFn: ({ signal }) => fetchProfileRequestSummary(ENDPOINTS.PROFILE_MY_REQUEST, signal),
    staleTime: CACHE_TIME.SHORT,
    enabled,
  });
 
export const useGetProfileIncomingRequests = ({ enabled = true }: UseProfileRequestOptions = {}) =>
  useQuery<ProfileRequestSummary>({
    queryKey: [QUERY_KEYS.PROFILE_INCOMING_REQUESTS],
    queryFn: ({ signal }) => fetchProfileRequestSummary(ENDPOINTS.PROFILE_INCOMING_REQUEST, signal),
    staleTime: CACHE_TIME.SHORT,
    enabled,
  });