All files / apps/mealReservation/src/screens/MealRegistration index.tsx

98.66% Statements 74/75
79.01% Branches 64/81
100% Functions 17/17
100% Lines 71/71

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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442                                                                                        1x   1x 10x 10x   10x   10x   10x         10x   10x   10x 10x 11x   10x 10x         10x   10x     10x 10x       10x 10x 10x         10x 9x 1x 1x   10x         10x 10x 1x         10x 10x 1x                                                 10x             10x 10x                 10x 10x         10x   10x       10x     1x 1x 1x     1x 1x 1x       10x 2x 2x   2x               2x                         10x 10x 10x 10x 10x   10x 10x 10x 10x       10x                 10x         10x 10x   10x 1x               9x                                                                               4x 4x     1x                                                                                                                                                           10x                                                                                                                                                            
import React, { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import {
  ActivityIndicator,
  Pressable,
  ScrollView,
  Text,
  View,
} from 'react-native';
 
import { AvatarList } from '@repo/ui/components/AvatarList';
import { AvatarSearchOverlay } from '@repo/ui/components/AvatarSearchOverlay';
import { Button } from '@repo/ui/components/Button';
import { Switch } from '@repo/ui/components/Switch';
import { AvatarIcon } from '@repo/ui/icons/Avatar';
import { MultipleUserIcon } from '@repo/ui/icons/MultipleUser';
import { makeStyles } from '@repo/ui/themes/makeStyles';
import { useTheme } from '@repo/ui/themes/ThemeContext';
import { textStyles } from '@repo/ui/themes/typography';
import { FAB_SUBMIT_GAP, useFabAnchor } from '@repo/ui/utils/useFabAnchor';
 
import { useEmployeeOptions } from '@repo/hooks/useEmployeeQueries';
import {
  useKeyboardPadding,
  useSearchOverlayAnimation,
} from '@repo/hooks/useSearchOverlayAnimation';
import {
  useGetExtraUsers,
  useGetMyMealRegistration,
} from '@repo/hooks/useUserQueries';
 
import {
  RoomBase,
  useCreateMealReservation,
  useGetRooms,
} from '../../hooks/useRequest';
import {
  useMealReservationActionsSelector,
  useMealReservationStateSelector,
} from '../MealReservation/context';
import { useMealReservationRuntime } from '../MealReservation/runtime';
 
import { MealConfigSwitches } from './MealConfigSwitches';
import { useOnBehalfSelection } from './useOnBehalfSelection';
 
const DEFAULT_OFFICES = ['HPT', 'TL18', '604'];
 
export const MealRegistration = () => {
  const styles = useStyles();
  const { theme } = useTheme();
 
  const { form } = useMealReservationStateSelector(state => state);
  const { selectOffice, updateMealConfig, setSubmitting } =
    useMealReservationActionsSelector(actions => actions);
 
  const { isManager, isLoading: isLoadingMe } = useEmployeeOptions();
  const {
    data: extraUsers = [],
    isLoading: isLoadingExtra,
    isError: isErrorExtra,
  } = useGetExtraUsers(!form.isOnBehalf);
 
  const { data: rooms = [] } = useGetRooms(form.isOnBehalf);
 
  const offices = useMemo(() => {
    const list = (rooms as RoomBase[])
      .map((r: RoomBase) => r.office)
      .filter(Boolean);
    const unique = Array.from(new Set(list));
    return unique.length > 0 ? unique : DEFAULT_OFFICES;
  }, [rooms]);
 
  // Fetch registration for the currently active form.user (either me or behalf user)
  const { data: userRegistration, isLoading: isLoadingReg } =
    useGetMyMealRegistration(form.user, !!form.user);
 
  const lastLoadedUserRef = useRef<string | null>(null);
 
  // Reset lastLoadedUserRef when form.user changes
  useEffect(() => {
    lastLoadedUserRef.current = null;
  }, [form.user]);
 
  // Auto-apply selected user's registration when fetched
  useEffect(() => {
    Eif (lastLoadedUserRef.current === null && userRegistration !== undefined) {
      updateMealConfig({
        breakfast: userRegistration?.breakfast ?? false,
        lunch: userRegistration?.lunch ?? false,
        vegetarian: userRegistration?.vegetarian ?? false,
      });
      if (userRegistration?.office) {
        selectOffice(userRegistration.office);
      } else Eif (offices.length > 0) {
        selectOffice(offices[0]);
      }
      lastLoadedUserRef.current = form.user;
    }
  }, [form.user, userRegistration, offices, updateMealConfig, selectOffice]);
 
  // Automatically select default office if onBehalf is enabled and office is empty
  useEffect(() => {
    if (form.isOnBehalf && !form.office && offices.length > 0) {
      selectOffice(offices[0]);
    }
  }, [form.isOnBehalf, form.office, offices, selectOffice]);
 
  // Handle auto resetting vegetarian when lunch is deselected
  useEffect(() => {
    if (!form.lunch && form.vegetarian) {
      updateMealConfig({
        breakfast: form.breakfast,
        lunch: form.lunch,
        vegetarian: false,
      });
    }
  }, [form.lunch, form.breakfast, form.vegetarian, updateMealConfig]);
 
  const {
    state: {
      isSearchOpen,
      searchQuery,
      selectedUser,
      selectedUserIds,
      filteredUsers,
      searchSelectedIds,
    },
    actions: {
      setSearchQuery,
      openSearch,
      handlePressSwitchOnBehalf,
      handleSearchCancel,
      handleToggleAvatarInSearchMode,
      handleSubmitSearchInput,
    },
  } = useOnBehalfSelection(extraUsers);
 
  const {
    searchInputRef,
    isSearchInteractive,
    shouldHideBaseContent,
    searchOverlayAnimatedStyle,
  } = useSearchOverlayAnimation({ isSearchOpen });
  const keyboardPadding = useKeyboardPadding();
 
  const {
    actions: {
      onSubmitSuccess,
      onSubmitError,
      onSubmittingChange,
      setFabOffset,
    },
  } = useMealReservationRuntime();
  const { ref: submitRef, onLayout: onSubmitLayout } = useFabAnchor(
    setFabOffset,
    FAB_SUBMIT_GAP,
  );
 
  useEffect(() => {
    // Hide the FAB while the search overlay covers the Submit button
    Iif (shouldHideBaseContent) setFabOffset?.(-200);
    // Otherwise the Submit button anchors the FAB via useFabAnchor
  }, [shouldHideBaseContent, setFabOffset]);
 
  const { mutate: submitReservation, isPending } = useCreateMealReservation(
    form.user,
    () => {
      setSubmitting(false);
      onSubmittingChange?.(false);
      onSubmitSuccess();
    },
    err => {
      setSubmitting(false);
      onSubmittingChange?.(false);
      onSubmitError(err);
    },
  );
 
  const handleSubmit = useCallback(() => {
    setSubmitting(true);
    onSubmittingChange?.(true);
 
    const payload = {
      breakfast: form.breakfast,
      lunch: form.lunch,
      vegetarian: form.vegetarian,
      ...(form.isOnBehalf && form.office && { office: form.office }),
      ...(form.isOnBehalf && form.user && { user: form.user }),
    };
 
    submitReservation(payload);
  }, [
    form.breakfast,
    form.lunch,
    form.vegetarian,
    form.isOnBehalf,
    form.office,
    form.user,
    submitReservation,
    setSubmitting,
    onSubmittingChange,
  ]);
 
  const hasNoChanges = useMemo(() => {
    const currentBreakfast = form.breakfast;
    const currentLunch = form.lunch;
    const currentVegetarian = form.vegetarian;
    const currentOffice = form.isOnBehalf ? form.office : '';
 
    const origBreakfast = userRegistration?.breakfast ?? false;
    const origLunch = userRegistration?.lunch ?? false;
    const origVegetarian = userRegistration?.vegetarian ?? false;
    const origOffice = form.isOnBehalf
      ? userRegistration?.office || offices[0] || ''
      : '';
 
    return (
      currentBreakfast === origBreakfast &&
      currentLunch === origLunch &&
      currentVegetarian === origVegetarian &&
      currentOffice === origOffice
    );
  }, [form, userRegistration, offices]);
 
  const isDisabledSubmit =
    (form.isOnBehalf && (!form.user || !form.office)) ||
    hasNoChanges ||
    isPending;
 
  const isLoading =
    isLoadingMe || (form.isOnBehalf && isLoadingExtra) || isLoadingReg;
  const isError = isErrorExtra && form.isOnBehalf;
 
  if (isLoading)
    return (
      <ActivityIndicator
        size="large"
        color={theme.colors.icon.brand}
        style={styles.loader}
      />
    );
 
  return (
    <View style={styles.container}>
      <ScrollView
        keyboardShouldPersistTaps="handled"
        contentContainerStyle={[
          styles.scrollContent,
          shouldHideBaseContent && styles.contentHidden,
        ]}
        pointerEvents={shouldHideBaseContent ? 'none' : 'auto'}
      >
        {/* On Behalf Mode Trigger */}
        {isManager && (
          <View style={styles.section}>
            <View style={styles.onBehalfGroup}>
              <Text style={styles.onBehalfLabel}>
                On behalf of someone else
              </Text>
              <Switch
                value={form.isOnBehalf}
                testID="on-behalf-switch"
                accessibilityLabel="On behalf of someone else"
                onValueChange={handlePressSwitchOnBehalf}
              />
            </View>
            {form.isOnBehalf && (
              <AvatarList
                data={selectedUser}
                selectedIds={selectedUserIds}
                onAdd={openSearch}
                onToggle={openSearch}
                numberOfLines={4}
              />
            )}
          </View>
        )}
 
        {/* Location Selection */}
        {form.isOnBehalf && (
          <View style={styles.locationContainer}>
            {offices.map(office => {
              const isSelected = form.office === office;
              return (
                <Pressable
                  key={office}
                  onPress={() => selectOffice(office)}
                  style={[
                    styles.locationTab,
                    isSelected && styles.locationTabSelected,
                  ]}
                  testID={`office-tab-${office}`}
                  accessibilityRole="tab"
                  accessibilityState={{ selected: isSelected }}
                  accessibilityLabel={`Select office ${office}`}
                >
                  <Text
                    style={[
                      styles.locationTabText,
                      isSelected && styles.locationTabTextSelected,
                    ]}
                  >
                    {office}
                  </Text>
                </Pressable>
              );
            })}
          </View>
        )}
 
        <MealConfigSwitches
          breakfast={form.breakfast}
          lunch={form.lunch}
          vegetarian={form.vegetarian}
          onChange={updateMealConfig}
        />
      </ScrollView>
 
      {!shouldHideBaseContent && (
        <View style={styles.buttonContainer}>
          <View ref={submitRef} onLayout={onSubmitLayout}>
            <Button
              onPress={handleSubmit}
              isLoading={isPending}
              style={styles.submitBtn}
              disabled={isDisabledSubmit}
              testID="submit-button"
            >
              Submit
            </Button>
          </View>
        </View>
      )}
 
      {/* Search Overlay */}
      <AvatarSearchOverlay
        isSearchInteractive={isSearchInteractive}
        animatedStyle={searchOverlayAnimatedStyle}
        keyboardPadding={keyboardPadding}
        searchInputRef={searchInputRef}
        isLoading={isLoadingExtra}
        isError={isError}
        errorTextStyle={styles.searchErrorText}
        loaderColor={theme.colors.icon.brand}
        label="on behalf of"
        inputAccessibilityLabel="Search by name"
        isSearchOpen={isSearchOpen}
        searchValue={searchQuery}
        onChangeSearchValue={setSearchQuery}
        onSubmitSearchInput={handleSubmitSearchInput}
        results={filteredUsers}
        selectedIds={searchSelectedIds}
        onToggleResult={handleToggleAvatarInSearchMode}
        noResultsText="No matching people found. Please try a different name"
        onDismiss={handleSearchCancel}
        leadingIcon={<MultipleUserIcon color={theme.colors.icon.active} />}
        emptyState={<AvatarIcon />}
        contentTopSpacing={theme.metrics.spacing[4]}
        centerStatePaddingVertical={theme.metrics.spacing[10]}
      />
    </View>
  );
};
 
const useStyles = makeStyles(theme => ({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background.pageMuted,
  },
  scrollContent: {
    paddingHorizontal: theme.metrics.spacing[4],
    paddingBottom: theme.metrics.spacing[4],
    gap: theme.metrics.spacing[4],
  },
  contentHidden: {
    opacity: 0,
  },
  section: {
    backgroundColor: theme.colors.background.surface,
    padding: theme.metrics.spacing[4],
    borderRadius: theme.metrics.borderRadius[2],
    gap: theme.metrics.spacing[3],
  },
  onBehalfGroup: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  onBehalfLabel: {
    fontWeight: theme.metrics.fontWeight.semiBold,
    textTransform: 'uppercase',
    color: theme.colors.text.onBehalf,
    ...textStyles.content.semiBold,
  },
  buttonContainer: {
    paddingHorizontal: theme.metrics.spacing[4],
    paddingBottom: theme.metrics.spacing[4],
    paddingTop: theme.metrics.spacing[2],
    backgroundColor: theme.colors.background.pageMuted,
  },
  locationContainer: {
    flexDirection: 'row',
    backgroundColor: theme.colors.background.surface,
    padding: theme.metrics.spacing[1],
    borderRadius: theme.metrics.borderRadius[2],
    gap: theme.metrics.spacing[1],
  },
  locationTab: {
    flex: 1,
    paddingVertical: theme.metrics.spacing[3],
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: theme.metrics.borderRadius[2],
  },
  locationTabSelected: {
    backgroundColor: theme.colors.background.current,
  },
  locationTabText: {
    ...textStyles.content.semiBold,
    fontSize: theme.metrics.textSize[14],
    color: theme.colors.text.muted,
  },
  locationTabTextSelected: {
    color: theme.colors.text.primary,
  },
  searchErrorText: {
    ...textStyles.content.regular,
  },
  loader: {
    marginVertical: theme.metrics.spacing[6],
  },
  submitBtn: {
    ...textStyles.content.semiBold,
    backgroundColor: theme.colors.badge.actionDone,
    alignSelf: 'center',
    width: '90%',
    height: 50,
    borderRadius: 50,
  },
}));
 
export default memo(MealRegistration);