All files / apps/reallocation/src/screens/Preview index.tsx

85.71% Statements 54/63
82.69% Branches 43/52
83.33% Functions 15/18
88.23% Lines 45/51

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                                              1x 7x     7x 7x     7x     7x 7x   98x 98x 7x 7x       7x             7x   7x 7x   5x   5x 5x 5x             7x 7x   5x   5x         7x 7x 5x 5x 5x     7x               7x 2x       2x                                                         7x 7x 7x   7x 7x 7x       7x       7x 1x                   6x 1x               5x                                                                                                                     7x                                                                    
import React, { useCallback, useEffect, useMemo } from 'react';
import { ActivityIndicator, ScrollView, Text, View } from 'react-native';
 
import { Button } from '@repo/ui/components/Button';
import { makeStyles } from '@repo/ui/themes/makeStyles';
import { textStyles } from '@repo/ui/themes/typography';
 
import { useEmployeeOptions } from '@repo/hooks/useEmployeeQueries';
 
import { useBlockBackNavigation } from '@repo/utils';
import { formatMoveDate } from '@repo/utils/date';
 
import { useCreateReallocationRequest } from '@/hooks/useRequest';
import { useGetOffice } from '@/hooks/useRoom';
 
import {
  useReallocationActionsSelector,
  useReallocationStateSelector,
} from '../Reallocation/context';
import { useReallocationRuntime } from '../Reallocation/runtime';
 
import { OFFICES } from './constants/office';
 
const Preview = () => {
  const styles = useStyles();
  const {
    actions: { onSubmitSuccess, onSubmitError, onSubmittingChange },
  } = useReallocationRuntime();
  const { form } = useReallocationStateSelector(state => ({
    form: state.form,
  }));
  const setSubmitting = useReallocationActionsSelector(
    actions => actions.setSubmitting,
  );
  const { observers, date, room, reason, originRoom } = form;
  const { officeData } = useGetOffice();
  const origin =
    OFFICES.find(office => office.id === originRoom)?.text || originRoom;
  const destination = OFFICES.find(office => office.id === room)?.text || room;
  const destinationOffice = useMemo(() => {
    Iif (!room || !Array.isArray(officeData)) {
      return '';
    }
 
    return officeData.find(item => item.id === room)?.office || '';
  }, [officeData, room]);
 
  const {
    employeeOptions,
    isLoading: isEmployeeOptionsLoading,
    isError: isEmployeeOptionsError,
  } = useEmployeeOptions();
 
  const selectedObservers = useMemo(() => {
    if (!employeeOptions || !observers) return [];
 
    const observerSet = new Set(observers);
 
    return employeeOptions
      .filter(emp => observerSet.has(emp.id))
      .map(item => ({
        id: item.id,
        name: item.name?.trim() || '',
        uri: item.avatar,
      }));
  }, [employeeOptions, observers]);
 
  const observersText = useMemo(() => {
    if (!selectedObservers.length) return '';
 
    const names = selectedObservers.map(o => o.name);
 
    Eif (names.length === 1) return names[0];
 
    return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
  }, [selectedObservers]);
 
  const mealText = useMemo(() => {
    if (form.mealBreakfast && form.mealLunch) return 'breakfast and lunch';
    Iif (form.mealBreakfast) return 'breakfast';
    Iif (form.mealLunch) return 'lunch';
    return '';
  }, [form.mealBreakfast, form.mealLunch]);
 
  const { mutate: createRequest, isPending } = useCreateReallocationRequest(
    () => {
      setSubmitting(false);
      onSubmitSuccess();
    },
    onSubmitError,
  );
 
  const handleSubmit = useCallback(() => {
    Iif (!form.date || !form.originRoom || !form.room || !form.reason) {
      return;
    }
 
    createRequest({
      category: 'reallocation',
      cc: form.observers,
      data: {
        origin: form.originRoom,
        dest: form.room,
        time: form.date.toISOString(),
        note: form.reason,
      },
      mealConfig: {
        lunch: form.mealLunch ?? false,
        breakfast: form.mealBreakfast ?? false,
        vegetarian: form.mealVegetarian ?? false,
        office: destinationOffice,
      },
    });
  }, [
    form.date,
    form.originRoom,
    form.room,
    form.reason,
    form.observers,
    form.mealLunch,
    form.mealBreakfast,
    form.mealVegetarian,
    createRequest,
    destinationOffice,
  ]);
 
  useEffect(() => {
    setSubmitting(isPending);
    onSubmittingChange?.(isPending);
 
    return () => {
      setSubmitting(false);
      onSubmittingChange?.(false);
    };
  }, [isPending, setSubmitting, onSubmittingChange]);
 
  useBlockBackNavigation(isPending, {
    skipGestureHandling: true,
  });
 
  if (isEmployeeOptionsLoading)
    return (
      <View
        testID="preview-loader"
        style={styles.loadingContainer}
        accessibilityRole="progressbar"
        accessibilityLabel="Loading"
      >
        <ActivityIndicator />
      </View>
    );
  if (isEmployeeOptionsError)
    return (
      <View testID="preview-error" style={styles.loadingContainer}>
        <Text accessibilityRole="alert">
          Failed to load. Please try again later.
        </Text>
      </View>
    );
 
  return (
    <>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
      >
        <Text style={styles.locationText}>
          {'I’d like to kindly request a desk move from '}
          <Text style={styles.highlightText}>{origin}</Text>
          {' to '}
          <Text style={styles.highlightText}>{destination}</Text>
          {'. It would be great if the new desk could be ready by '}
          <Text style={styles.highlightText}>
            {formatMoveDate(date?.toString() || '')}
          </Text>{' '}
          {'.'}
        </Text>
 
        <Text style={styles.locationText}>
          {'The purpose of this move is '}
          <Text style={styles.highlightText}>{reason}</Text>
          {'.'}
        </Text>
 
        {!!mealText && (
          <Text style={styles.locationText}>
            {'I’d also like to reserve '}
            <Text style={styles.highlightText}>{mealText}</Text>
            {'.'}
          </Text>
        )}
 
        {!!observersText && (
          <Text style={styles.locationText}>
            <Text style={styles.highlightText}>{observersText}</Text>
            {selectedObservers.length === 1
              ? ' will be present as an observer during the relocation.'
              : ' will be present as an observers during the relocation.'}
          </Text>
        )}
 
        <Text style={styles.locationText}>
          {'Thank you for your support and assistance!'}
        </Text>
      </ScrollView>
 
      <Button
        style={styles.submitBtn}
        isLoading={isPending}
        onPress={handleSubmit}
        testID="submit-btn"
        accessibilityLabel="Submit reallocation request"
      >
        Submit
      </Button>
    </>
  );
};
 
const useStyles = makeStyles(theme => ({
  container: {
    flex: 1,
    paddingTop: theme.metrics.spacing[6],
  },
  content: {
    paddingHorizontal: theme.metrics.spacing[4],
    gap: theme.metrics.spacing[6.5],
    paddingBottom: theme.metrics.spacing[6],
  },
  locationText: {
    ...textStyles.content.light,
    fontSize: theme.metrics.textSize[16],
    lineHeight: theme.metrics.spacing[6],
  },
  highlightText: {
    ...textStyles.content.semiBold,
  },
  submitBtn: {
    backgroundColor: theme.colors.slate97,
    alignSelf: 'center',
    width: '90%',
    height: 50,
    borderRadius: 50,
    marginBottom: theme.metrics.spacing[3],
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    marginTop: 32,
  },
}));
 
export default Preview;