Pārlūkot izejas kodu

update/delete visit api

Viktoriia 1 mēnesi atpakaļ
vecāks
revīzija
f77eb3a05c

+ 2 - 0
src/modules/api/myRegions/queries/index.ts

@@ -5,3 +5,5 @@ export * from './use-post-set-update-tcc';
 export * from './use-post-get-regions';
 export * from './use-post-get-visits-to-region';
 export * from './use-post-add-visit';
+export * from './use-post-update-visit';
+export * from './use-post-delete-visit';

+ 17 - 0
src/modules/api/myRegions/queries/use-post-delete-visit.tsx

@@ -0,0 +1,17 @@
+import { useMutation } from '@tanstack/react-query';
+
+import { regionsQueryKeys } from '../regions-query-keys';
+import { type PostDeleteVisit, regionsApi } from '../regions-api';
+
+import type { BaseAxiosError } from '../../../../types';
+import { ResponseType } from '@api/response-type';
+
+export const usePostDeleteVisitMutation = () => {
+  return useMutation<ResponseType, BaseAxiosError, PostDeleteVisit, ResponseType>({
+    mutationKey: regionsQueryKeys.deleteVisit(),
+    mutationFn: async (data) => {
+      const response = await regionsApi.deleteVisit(data);
+      return response.data;
+    }
+  });
+};

+ 17 - 0
src/modules/api/myRegions/queries/use-post-update-visit.tsx

@@ -0,0 +1,17 @@
+import { useMutation } from '@tanstack/react-query';
+
+import { regionsQueryKeys } from '../regions-query-keys';
+import { type PostUpdateVisit, regionsApi } from '../regions-api';
+
+import type { BaseAxiosError } from '../../../../types';
+import { ResponseType } from '@api/response-type';
+
+export const usePostUpdateVisitMutation = () => {
+  return useMutation<ResponseType, BaseAxiosError, PostUpdateVisit, ResponseType>({
+    mutationKey: regionsQueryKeys.updateVisit(),
+    mutationFn: async (data) => {
+      const response = await regionsApi.updateVisit(data);
+      return response.data;
+    }
+  });
+};

+ 23 - 1
src/modules/api/myRegions/regions-api.tsx

@@ -120,6 +120,26 @@ export interface PostAddVisit {
   hidden: 0 | 1;
 }
 
+export interface PostUpdateVisit {
+  token: string;
+  region: number;
+  id: number;
+  quality: number;
+  year_from: number;
+  month_from: number;
+  day_from: number;
+  year_to: number;
+  month_to: number;
+  day_to: number;
+  completed: 0 | 1;
+  hidden: 0 | 1;
+}
+
+export interface PostDeleteVisit {
+  token: string;
+  id: number;
+}
+
 export const regionsApi = {
   getMegaregions: (token: string) =>
     request.postForm<PostGetMegaReturn>(API.GET_MEGAREGIONS, { token }),
@@ -135,5 +155,7 @@ export const regionsApi = {
     megaregion: number | 'all' | undefined,
     country: number | 'all' | undefined
   ) => request.postForm<PostGetRegionsReturn>(API.GET_REGIONS, { megaregion, country, token }),
-  addVisit: (data: PostAddVisit) => request.postForm<ResponseType>(API.ADD_VISIT, data)
+  addVisit: (data: PostAddVisit) => request.postForm<ResponseType>(API.ADD_VISIT, data),
+  updateVisit: (data: PostUpdateVisit) => request.postForm<ResponseType>(API.UPDATE_VISIT, data),
+  deleteVisit: (data: PostDeleteVisit) => request.postForm<ResponseType>(API.DELETE_VISIT, data)
 };

+ 3 - 1
src/modules/api/myRegions/regions-query-keys.tsx

@@ -10,5 +10,7 @@ export const regionsQueryKeys = {
     megaregion: number | 'all' | undefined,
     country: number | 'all' | undefined
   ) => ['getRegions', { megaregion, country, token }] as const,
-  addVisit: () => ['addVisit'] as const
+  addVisit: () => ['addVisit'] as const,
+  updateVisit: () => ['updateVisit'] as const,
+  deleteVisit: () => ['deleteVisit'] as const
 };

+ 97 - 21
src/screens/InAppScreens/TravelsScreen/EditNmDataScreen/index.tsx

@@ -15,14 +15,19 @@ import { Picker } from '@react-native-picker/picker';
 import { MaterialCommunityIcons } from '@expo/vector-icons';
 import { Picker as WheelPicker } from 'react-native-wheel-pick';
 import moment from 'moment';
-import { Button, Header, PageWrapper } from 'src/components';
+import { Button, Header, PageWrapper, WarningModal } from 'src/components';
 import { Colors } from 'src/theme';
 import { Dropdown } from 'react-native-searchable-dropdown-kj';
 import { qualityOptions } from '../utils/constants';
 import { getFontSize } from 'src/utils';
 import TrashSVG from 'assets/icons/travels-screens/trash-solid.svg';
 import { storage, StoreType } from 'src/storage';
-import { useGetVisitsQuery, usePostAddVisitMutation } from '@api/myRegions';
+import {
+  useGetVisitsQuery,
+  usePostAddVisitMutation,
+  usePostDeleteVisitMutation,
+  usePostUpdateVisitMutation
+} from '@api/myRegions';
 import ActionSheet from 'react-native-actions-sheet';
 import { ButtonVariants } from 'src/types/components';
 import EditSvg from 'assets/icons/travels-screens/pen-to-square.svg';
@@ -71,6 +76,8 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
 
   const { data: existingVisits } = useGetVisitsQuery(id, token, token ? true : false);
   const { mutateAsync: addVisit } = usePostAddVisitMutation();
+  const { mutateAsync: updateVisitAsync } = usePostUpdateVisitMutation();
+  const { mutateAsync: deleteVisitAsync } = usePostDeleteVisitMutation();
 
   const [visits, setVisits] = useState<Visit[]>([]);
   const [showDatePicker, setShowDatePicker] = useState<DatePickerState | null>(null);
@@ -81,6 +88,15 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
   const [selectedMonth, setSelectedMonth] = useState<number | null>(null);
   const [selectedDay, setSelectedDay] = useState<number | null>(null);
 
+  const [modalState, setModalState] = useState({
+    isWarningVisible: false,
+    type: 'success',
+    title: '',
+    buttonTitle: '',
+    message: '',
+    action: () => {}
+  });
+
   const createEmptyVisit = useCallback(
     (): Visit => ({
       id: Date.now() + Math.random(),
@@ -152,14 +168,35 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
   }, []);
 
   const toggleEditVisit = useCallback(
-    (id: number): void => {
-      const visit = visits.find((v) => v.id === id);
+    async (visitId: number): Promise<void> => {
+      const visit = visits.find((v) => v.id === visitId);
       if (visit && visit.isEditing) {
-        Alert.alert('TO DO edit existing visit');
+        await updateVisitAsync(
+          {
+            token,
+            region: id,
+            id: visitId,
+            quality: visit.quality.id,
+            year_from: visit.startDate?.year || null,
+            month_from: visit.startDate?.month || null,
+            day_from: visit.startDate?.day || null,
+            year_to: visit.endDate?.year || null,
+            month_to: visit.endDate?.month || null,
+            day_to: visit.endDate?.day || null,
+            completed: 1,
+            hidden: 0
+          },
+          {
+            onSuccess: (data) => {},
+            onError: (error) => {
+              console.log('updateVisitAsync error', error);
+            }
+          }
+        );
       }
       setVisits((prevVisits) =>
         prevVisits.map((visit) =>
-          visit.id === id ? { ...visit, isEditing: !visit.isEditing } : visit
+          visit.id === visitId ? { ...visit, isEditing: !visit.isEditing } : visit
         )
       );
     },
@@ -167,18 +204,50 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
   );
 
   const deleteVisit = useCallback(
-    (id: number): void => {
+    async (id: number): Promise<void> => {
       const visitToDelete = visits.find((visit: Visit) => visit.id === id);
       if (!visitToDelete) return;
-
-      Animated.timing(visitToDelete.animatedValue, {
-        toValue: 0,
-        duration: 300,
-        easing: Easing.in(Easing.quad),
-        useNativeDriver: false
-      }).start(() => {
-        setVisits((prevVisits) => prevVisits.filter((visit) => visit.id !== id));
-      });
+      if (visitToDelete.isExisting) {
+        setModalState({
+          type: 'delete',
+          title: `Delete visit`,
+          message: `Are you sure you want to delete this visit?`,
+          action: async () => {
+            await deleteVisitAsync(
+              {
+                token,
+                id: visitToDelete.id
+              },
+              {
+                onSuccess: (res) => {
+                  Animated.timing(visitToDelete.animatedValue, {
+                    toValue: 0,
+                    duration: 300,
+                    easing: Easing.in(Easing.quad),
+                    useNativeDriver: false
+                  }).start(() => {
+                    setVisits((prevVisits) => prevVisits.filter((visit) => visit.id !== id));
+                  });
+                },
+                onError: (err) => {
+                  console.log('delete err', err);
+                }
+              }
+            );
+          },
+          buttonTitle: 'Delete',
+          isWarningVisible: true
+        });
+      } else {
+        Animated.timing(visitToDelete.animatedValue, {
+          toValue: 0,
+          duration: 300,
+          easing: Easing.in(Easing.quad),
+          useNativeDriver: false
+        }).start(() => {
+          setVisits((prevVisits) => prevVisits.filter((visit) => visit.id !== id));
+        });
+      }
     },
     [visits]
   );
@@ -258,7 +327,6 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
       }
 
       newVisits.forEach(async (v) => {
-        console.log('visit', v);
         await addVisit(
           {
             token,
@@ -274,9 +342,7 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
             hidden: 0
           },
           {
-            onSuccess: (data) => {
-              console.log('addVisit data', data);
-            },
+            onSuccess: (data) => {},
             onError: (error) => {
               console.log('addVisit error', error);
             }
@@ -346,7 +412,7 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
     }
 
     for (let i = 1; i <= maxDay; i++) {
-      days.push({ label: i.toString(), value: i });
+      days.push({ label: i.toString(), value: i as never });
     }
 
     return days;
@@ -680,6 +746,16 @@ const EditNmDataScreen = ({ navigation, route }: { navigation: any; route: any }
           </View>
         </View>
       </ActionSheet>
+
+      <WarningModal
+        type={modalState.type}
+        isVisible={modalState.isWarningVisible}
+        buttonTitle={modalState.buttonTitle}
+        message={modalState.message}
+        action={modalState.action}
+        onClose={() => setModalState({ ...modalState, isWarningVisible: false })}
+        title={modalState.title}
+      />
     </PageWrapper>
   );
 };

+ 6 - 2
src/types/api.ts

@@ -217,7 +217,9 @@ export enum API_ENDPOINT {
   GET_COUNTRIES_FOR_LOCATION_DATA = 'get-list-of-countries-for-location-data',
   GET_USERS_LOCATION_FILTERED = 'get-users-location-filtered',
   GET_VISITS_TO_REGION = 'get-visits-to-region',
-  ADD_VISIT = 'add-visit'
+  ADD_VISIT = 'add-visit',
+  UPDATE_VISIT = 'update-visit',
+  DELETE_VISIT = 'delete-visit'
 }
 
 export enum API {
@@ -408,7 +410,9 @@ export enum API {
   GET_USERS_LOCATION_FILTERED = `${API_ROUTE.LOCATION}/${API_ENDPOINT.GET_USERS_LOCATION_FILTERED}`,
   GET_VISITS_TO_REGION = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.GET_VISITS_TO_REGION}`,
   GET_REGIONS = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.GET_REGIONS}`,
-  ADD_VISIT = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.ADD_VISIT}`
+  ADD_VISIT = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.ADD_VISIT}`,
+  UPDATE_VISIT = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.UPDATE_VISIT}`,
+  DELETE_VISIT = `${API_ROUTE.QUICK_ENTER}/${API_ENDPOINT.DELETE_VISIT}`
 }
 
 export type BaseAxiosError = AxiosError;