Skip to content

Commit

Permalink
new logic of storing last BA
Browse files Browse the repository at this point in the history
  • Loading branch information
OmerGery committed Jan 15, 2024
1 parent b50f5f2 commit dd22a5a
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 24 deletions.
64 changes: 45 additions & 19 deletions examples/client/Locomotion/src/context/newRideContext/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import { useNavigation } from '@react-navigation/native';
import _, { pick } from 'lodash';
import moment, { Moment } from 'moment-timezone';
import debounce from 'lodash/debounce';
import { PAYMENT_MODES } from '../../pages/Payments/consts';
import offlinePaymentMethod from '../../pages/Payments/offlinePaymentMethod';
import i18n from '../../I18n';
import { FutureRidesContext } from '../futureRides';
import { UserContext } from '../user';
import PaymentContext from '../payments';
import { getPosition, DEFAULT_COORDS } from '../../services/geo';
import {
getPlaces, getGeocode, getPlaceDetails, getLocationTimezone,
getPlaces, getGeocode, getPlaceDetails,
} from './google-api';
import StorageService from '../../services/storage';
import Mixpanel from '../../services/Mixpanel';
Expand Down Expand Up @@ -231,6 +234,7 @@ const HISTORY_RECORDS_NUM = 10;
const RidePageContextProvider = ({ children }: {
children: any
}) => {
const { getClientDefaultMethod } = PaymentContext.useContainer();
const { locationGranted, user } = useContext(UserContext);
const {
isStationsEnabled,
Expand Down Expand Up @@ -271,8 +275,11 @@ const RidePageContextProvider = ({ children }: {
clearInterval(intervalRef.current);
};

const saveLastRide = async (rideId: string) => {
await StorageService.save({ lastRideId: rideId });
const saveLastRide = async (rideId: string, rideBusinessAccountId: string) => {
await Promise.all([
StorageService.save({ lastRideId: rideId }),
StorageService.save({ lastBusinessAccountId: rideBusinessAccountId || PAYMENT_MODES.PERSONAL }),
]);
};

const clearLastRide = async () => {
Expand Down Expand Up @@ -325,13 +332,13 @@ const RidePageContextProvider = ({ children }: {
cleanRequestStopPoints();
setRide(newRide);
changeBsPage(BS_PAGES.ACTIVE_RIDE);
saveLastRide(newRide.id);
saveLastRide(newRide.id, newRide.businessAccountId);
},
[RIDE_STATES.ACTIVE]: (activeRide: any) => {
cleanRequestStopPoints();
setRide(activeRide);
changeBsPage(BS_PAGES.ACTIVE_RIDE);
saveLastRide(activeRide.id);
saveLastRide(activeRide.id, activeRide.businessAccountId);
},
[RIDE_STATES.CANCELED]: (canceledRide: any) => {
if (canceledRide.canceledBy !== user?.id) {
Expand Down Expand Up @@ -388,7 +395,32 @@ const RidePageContextProvider = ({ children }: {
return timezoneResponse.time;
};

const getServiceEstimations = async (throwError = true) => {
const updateRidePayload = (newRide: RideInterface) => {
setRide({
...ride,
...newRide,
});
};

const getBusinessAccountIdWithFallback = async (paymentChosen: boolean) => {
const doNotUseFallback = paymentChosen || businessAccountId;
if (doNotUseFallback) {
return businessAccountId;
}
const [notFirstRide, fallbackId] = await Promise.all([
StorageService.get('lastRideId'),
StorageService.get('lastBusinessAccountId'),
]);
const defaultPaymentMethod = notFirstRide ? getClientDefaultMethod() : null;
const usePersonalPayment = !fallbackId || fallbackId === PAYMENT_MODES.PERSONAL || defaultPaymentMethod;
if (usePersonalPayment) { return null; }
updateRidePayload({ paymentMethodId: offlinePaymentMethod.id });
setBusinessAccountId(fallbackId);
return fallbackId;
};

const getServiceEstimations = async (throwError = true, paymentChosen = true) => {
const relevantBusinessAccountId = await getBusinessAccountIdWithFallback(paymentChosen);
changeBsPage(BS_PAGES.SERVICE_ESTIMATIONS);
try {
const formattedStopPoints = formatStopPointsForEstimations(requestStopPoints);
Expand All @@ -400,7 +432,7 @@ const RidePageContextProvider = ({ children }: {
scheduledTime = await getLocationTimezoneTime(formattedStopPoints[0].lat, formattedStopPoints[0].lng, unixScheduledTo);
}
const { estimations, services } = await rideApi
.createServiceEstimations(formattedStopPoints, scheduledTime, businessAccountId);
.createServiceEstimations(formattedStopPoints, scheduledTime, relevantBusinessAccountId);

const tags = getEstimationTags(estimations);
const formattedEstimations = formatEstimations(services, estimations, tags);
Expand Down Expand Up @@ -439,24 +471,24 @@ const RidePageContextProvider = ({ children }: {
}
};

const tryServiceEstimations = async () => {
const tryServiceEstimations = async (paymentChosen = true) => {
const serviceEstimationsInterval = await getServiceEstimationsFetchingInterval();
await getServiceEstimations();
await getServiceEstimations(true, paymentChosen);
clearInterval(intervalRef.current);
intervalRef.current = setInterval(async () => {
if (intervalRef.current) {
await getServiceEstimations(false);
await getServiceEstimations(false, true);
}
}, ((serviceEstimationsInterval || 60) * 1000));
};

const validateStopPointInTerritory = (stopPoints: any[]) => checkStopPointsInTerritory(stopPoints);

const validateRequestedStopPoints = (reqSps: any[]) => {
const validateRequestedStopPoints = (reqSps: any[], paymentChosen = true) => {
const stopPoints = reqSps;
const isSpsReady = stopPoints.every(r => r.lat && r.lng && r.description);
if (stopPoints.length && isSpsReady) {
tryServiceEstimations();
tryServiceEstimations(paymentChosen);
} else if (![BS_PAGES.ADDRESS_SELECTOR, BS_PAGES.LOADING].includes(currentBsPage)) {
// reset req stop point request
if (!ride.id) {
Expand Down Expand Up @@ -607,7 +639,7 @@ const RidePageContextProvider = ({ children }: {
}, 4000);

useEffect(() => {
validateRequestedStopPoints(requestStopPoints);
validateRequestedStopPoints(requestStopPoints, false);
}, [requestStopPoints]);

const getRideFromApi = async (rideId: string): Promise<RideInterface> => formatRide(await rideApi.getRide(rideId));
Expand Down Expand Up @@ -1147,12 +1179,6 @@ const RidePageContextProvider = ({ children }: {
}
};

const updateRidePayload = (newRide: RideInterface) => {
setRide({
...ride,
...newRide,
});
};

const patchRideRating = async (rideId: string, rating: number | null, feedback: RideFeedback | null): Promise<any> => {
if (!rating && !feedback) {
Expand Down
12 changes: 11 additions & 1 deletion examples/client/Locomotion/src/context/payments/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import { createContainer } from 'unstated-next';
import { StorageService } from '../../services';
import i18n from '../../I18n';
import { PAYMENT_STATES } from '../../lib/commonTypes';
import Mixpanel from '../../services/Mixpanel';
Expand Down Expand Up @@ -38,11 +39,20 @@ const usePayments = () => {
}
};

const handleBusinessAccountStorage = async (businessAccounts) => {
const lastBusinessAccountId = await StorageService.get('lastBusinessAccountId');
if (businessAccounts?.length > 0 && !lastBusinessAccountId) {
await StorageService.save({ lastBusinessAccountId: businessAccounts[0].id });
}
};

const loadCustomer = async () => {
const customerData = await getCustomer();
setCustomer(customerData);
setPaymentMethods(customerData.paymentMethods);
setBusinessPaymentMethods(customerData.businessAccounts);
const { businessAccounts } = customerData;
setBusinessPaymentMethods(businessAccounts);
await handleBusinessAccountStorage(businessAccounts);
return customerData;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const RideOptions = () => {
serviceEstimations,
chosenService,
updateBusinessAccountId,
businessAccountId,
} = useContext(RidePageContext);

const {
Expand Down Expand Up @@ -112,6 +113,7 @@ const RideOptions = () => {
/>

<ChoosePaymentMethod
selectedBusinessAccountId={businessAccountId}
showBusinessPaymentMethods={usePayments.businessPaymentMethods?.length > 0}
onAddNewMethod={() => {
clearPopup();
Expand Down
1 change: 0 additions & 1 deletion examples/client/Locomotion/src/pages/Payments/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export const PAYMENT_TABS = [
Svg: businessPaymentIcon,
},
];
export const INITIAL_ACTIVE_PAYMENT_TAB = PAYMENT_TABS[0].id;
export const paymentMethodToIconMap = {
[PAYMENT_METHODS.CASH]: cashIcon,
[PAYMENT_METHODS.OFFLINE]: offlineIcon,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Modal from 'react-native-modal';
import { useNavigation } from '@react-navigation/native';
import EmptyState from '../../Components/EmptyState';
import Mixpanel from '../../services/Mixpanel';
import { INITIAL_ACTIVE_PAYMENT_TAB, PAYMENT_MODES, PAYMENT_TABS } from '../../pages/Payments/consts';
import { PAYMENT_MODES, PAYMENT_TABS } from '../../pages/Payments/consts';
import TabSwitch from '../../Components/TabSwitch';
import { getPaymentMethod } from '../../pages/Payments/cardDetailUtils';
import CloseButton from '../../Components/CloseButton';
Expand Down Expand Up @@ -39,6 +39,7 @@ interface PaymentMethodPopupProps {
onAddNewMethod: () => void;
showOffline: boolean;
showBusinessPaymentMethods: boolean;
selectedBusinessAccountId: string | null;
}

const PaymentMethodPopup = ({
Expand All @@ -51,11 +52,14 @@ const PaymentMethodPopup = ({
onAddNewMethod,
showOffline,
showBusinessPaymentMethods,
selectedBusinessAccountId,
}: PaymentMethodPopupProps) => {
const usePayments = PaymentsContext.useContainer();
const { chosenService } = useContext(MewRidePageContext);
const [selectedPaymentId, setSelectedPaymentId] = useState<string | undefined>(selected);
const [activePaymentTab, setActivePaymentTab] = useState(INITIAL_ACTIVE_PAYMENT_TAB);
const [activePaymentTab, setActivePaymentTab] = useState(
selectedBusinessAccountId ? PAYMENT_MODES.BUSINESS : PAYMENT_MODES.PERSONAL,
);
const isBusinessMode = activePaymentTab === PAYMENT_MODES.BUSINESS;
const personalPaymentMethods = [
...usePayments.paymentMethods,
Expand Down Expand Up @@ -83,7 +87,11 @@ const PaymentMethodPopup = ({
setSelectedPaymentId(selected);
} else {
const paymentMethod = await usePayments.getClientDefaultMethod();
setSelectedPaymentId(paymentMethod?.id);
if (paymentMethod?.id) {
setSelectedPaymentId(paymentMethod?.id);
} else if (selectedBusinessAccountId) {
setSelectedPaymentId(selectedBusinessAccountId);
}
}
};

Expand Down

0 comments on commit dd22a5a

Please sign in to comment.