couponTabView.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // component/global/couponTabView.tsx
  2. import * as React from 'react';
  3. import {
  4. View,
  5. Text,
  6. useWindowDimensions,
  7. StyleSheet,
  8. ImageSourcePropType,
  9. ScrollView,
  10. ActivityIndicator,
  11. Pressable,
  12. Alert
  13. } from 'react-native';
  14. import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
  15. import { IndividualCouponComponent } from '../accountPages/walletPageComponent';
  16. import { formatCouponDate } from '../../util/lib';
  17. import { useCallback, useEffect, useRef, useState } from 'react';
  18. import { walletService } from '../../service/walletService';
  19. import { useChargingStore } from '../../providers/scan_qr_payload_store';
  20. import { chargeStationService } from '../../service/chargeStationService';
  21. import { router } from 'expo-router';
  22. import axios from 'axios';
  23. import { useTranslation } from '../../util/hooks/useTranslation';
  24. export interface TabItem {
  25. imgURL: ImageSourcePropType;
  26. date: string;
  27. time: string;
  28. chargeStationName: string;
  29. chargeStationAddress: string;
  30. distance: string;
  31. }
  32. interface TabViewComponentProps {
  33. titles: string[];
  34. }
  35. const FirstRoute = ({
  36. coupons,
  37. loading,
  38. handleCouponClick
  39. }: {
  40. coupons: any;
  41. loading: boolean;
  42. handleCouponClick: any;
  43. }) => {
  44. const { t } = useTranslation();
  45. return (
  46. <View className="flex-1">
  47. <ScrollView
  48. style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}
  49. contentContainerStyle={{ paddingBottom: 200 }}
  50. >
  51. <View className="flex-1 flex-col">
  52. {loading ? (
  53. <View className="items-center justify-center">
  54. <ActivityIndicator />
  55. </View>
  56. ) : (
  57. <View className="">
  58. <View>
  59. {coupons.filter(
  60. (coupon: any) =>
  61. coupon.permission == true &&
  62. coupon.is_consumed === false &&
  63. (coupon.expire_date === null || new Date(coupon.expire_date) > new Date())
  64. ).length === 0 ? (
  65. <Text className="pl-4">{t('selectCoupons.coupon.noCoupon')}</Text>
  66. ) : (
  67. coupons
  68. .filter(
  69. (coupon: any) =>
  70. coupon.permission == true &&
  71. coupon.is_consumed === false &&
  72. (coupon.expire_date === null ||
  73. new Date(coupon.expire_date) > new Date())
  74. )
  75. .sort(
  76. (a: any, b: any) =>
  77. new Date(a.expire_date).getTime() - new Date(b.expire_date).getTime()
  78. )
  79. .slice(0, 30)
  80. .map((coupon: any, index: any) => (
  81. <IndividualCouponComponent
  82. onCouponClick={handleCouponClick}
  83. // key={coupon.redeem_code}
  84. key={`${coupon.id}-${index}`}
  85. title={coupon.coupon.name}
  86. price={coupon.coupon.amount}
  87. detail={coupon.coupon.description}
  88. date={formatCouponDate(coupon.expire_date)}
  89. setOpacity={false}
  90. redeem_code={coupon.id}
  91. />
  92. ))
  93. )}
  94. </View>
  95. </View>
  96. )}
  97. </View>
  98. </ScrollView>
  99. </View>
  100. );
  101. };
  102. const SecondRoute = ({ coupons }: { coupons: any }) => {
  103. const { t } = useTranslation();
  104. return (
  105. <ScrollView style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}>
  106. <View className="flex-1 flex-col">
  107. {coupons
  108. .filter(
  109. (coupon: any) =>
  110. coupon.is_consumed === true ||
  111. (coupon.expire_date !== null && new Date(coupon.expire_date) < new Date())
  112. )
  113. .slice(0, 30)
  114. .map((coupon: any, index: any) => (
  115. <IndividualCouponComponent
  116. key={`${coupon.id}-${index}`}
  117. title={coupon.coupon.name}
  118. price={coupon.coupon.amount}
  119. detail={coupon.coupon.description}
  120. date={formatCouponDate(coupon.expire_date)}
  121. setOpacity={true}
  122. noCircle={true}
  123. />
  124. ))}
  125. </View>
  126. </ScrollView>
  127. );
  128. };
  129. const CouponTabViewComponent: React.FC<TabViewComponentProps> = ({ titles }) => {
  130. const { t } = useTranslation();
  131. const layout = useWindowDimensions();
  132. const [loading, setLoading] = useState(false);
  133. const [coupons, setCoupons] = useState([]);
  134. const [userID, setUserID] = useState('');
  135. const {
  136. current_price_store,
  137. setCurrentPriceStore,
  138. stationID,
  139. promotion_code,
  140. setPromotionCode,
  141. setCouponDetail,
  142. coupon_detail,
  143. total_power,
  144. setTotalPower,
  145. setProcessedCouponStore,
  146. setSumOfCoupon
  147. } = useChargingStore();
  148. useEffect(() => {
  149. const fetchData = async () => {
  150. try {
  151. setLoading(true);
  152. const info = await walletService.getCustomerInfo();
  153. const coupon = await walletService.getCouponForSpecificUser(info.id);
  154. setUserID(info.id);
  155. setCoupons(coupon);
  156. } catch (error) {
  157. console.log(error);
  158. } finally {
  159. setLoading(false);
  160. }
  161. };
  162. fetchData();
  163. }, []);
  164. //fetch current price for coupon valid calculation
  165. useEffect(() => {
  166. const fetchCurrentPrice = async () => {
  167. try {
  168. const response = await chargeStationService.getOriginalPriceInPay(stationID);
  169. setCurrentPriceStore(response);
  170. } catch (error) {
  171. // More specific error handling
  172. if (axios.isAxiosError(error)) {
  173. const errorMessage = error.response?.data?.message || 'Network error occurred';
  174. Alert.alert(t('common.error'), `${t('selectCoupons.error_fetching_balance')}: ${errorMessage}`, [
  175. {
  176. text: t('common.ok'),
  177. onPress: () => {
  178. cleanupData();
  179. router.push('/mainPage');
  180. }
  181. }
  182. ]);
  183. } else {
  184. Alert.alert(t('common.error'), t('selectCoupons.error_fetching_balance'), [
  185. {
  186. text: t('common.ok'),
  187. onPress: () => {
  188. cleanupData();
  189. router.push('/mainPage');
  190. }
  191. }
  192. ]);
  193. }
  194. }
  195. };
  196. fetchCurrentPrice();
  197. }, []);
  198. const handleCouponClick = async (clickedCoupon: string) => {
  199. let temp_promotion_code = [...promotion_code];
  200. if (!current_price_store) {
  201. Alert.alert(t('common.error'), t('selectCoupons.error_fetching_balance'), [
  202. {
  203. text: t('common.ok'),
  204. onPress: () => {
  205. cleanupData();
  206. router.push('/mainPage');
  207. }
  208. }
  209. ]);
  210. return;
  211. }
  212. let orderAmount = current_price_store * total_power;
  213. //when i click on a coupon, if coupone doesnt already exist in the stack, i add it to the stack
  214. if (!promotion_code.includes(clickedCoupon)) {
  215. const found_coupon = coupons.find((coupon: any) => coupon.id === clickedCoupon);
  216. temp_promotion_code = [...promotion_code, found_coupon.id];
  217. try {
  218. const valid = await chargeStationService.validateCoupon(temp_promotion_code, orderAmount);
  219. if (valid === true) {
  220. setCouponDetail([...coupon_detail, found_coupon]);
  221. setPromotionCode([...promotion_code, clickedCoupon]);
  222. } else {
  223. Alert.alert(t('selectCoupons.coupon.invalid_condition_title'), t('selectCoupons.coupon.invalid_condition_message'));
  224. }
  225. } catch (error) {
  226. console.log(error);
  227. }
  228. } else {
  229. //coupon already exists, this de-select the coupon
  230. const index_of_clicked_coupon = promotion_code.findIndex((i) => i === clickedCoupon);
  231. const newPromotionCode = [...promotion_code];
  232. newPromotionCode.splice(index_of_clicked_coupon, 1);
  233. setPromotionCode(newPromotionCode);
  234. const newCouponDetail = coupon_detail.filter((detail: any) => detail.id !== clickedCoupon);
  235. setCouponDetail(newCouponDetail);
  236. }
  237. };
  238. const cleanupData = () => {
  239. setPromotionCode([]);
  240. setCouponDetail([]);
  241. setProcessedCouponStore([]);
  242. setSumOfCoupon(0);
  243. setTotalPower(null);
  244. };
  245. const renderScene = useCallback(
  246. ({ route }: { route: any }) => {
  247. switch (route.key) {
  248. case 'firstRoute':
  249. return <FirstRoute coupons={coupons} loading={loading} handleCouponClick={handleCouponClick} />;
  250. case 'secondRoute':
  251. return <SecondRoute coupons={coupons} />;
  252. default:
  253. return null;
  254. }
  255. },
  256. [coupons, loading, handleCouponClick]
  257. );
  258. const [routes] = React.useState([
  259. { key: 'firstRoute', title: titles[0] },
  260. { key: 'secondRoute', title: titles[1] }
  261. ]);
  262. const [index, setIndex] = React.useState(0);
  263. const renderTabBar = (props: any) => (
  264. <TabBar
  265. {...props}
  266. indicatorStyle={{
  267. backgroundColor: '#025c72'
  268. }}
  269. style={{
  270. backgroundColor: 'white',
  271. borderColor: '#DBE4E8',
  272. elevation: 0,
  273. marginHorizontal: 15,
  274. borderBottomWidth: 0.5
  275. }}
  276. />
  277. );
  278. return (
  279. <TabView
  280. navigationState={{ index, routes }}
  281. renderScene={renderScene}
  282. onIndexChange={setIndex}
  283. initialLayout={{ width: layout.width }}
  284. renderTabBar={renderTabBar}
  285. commonOptions={{
  286. label: ({ route, focused }) => (
  287. <Text
  288. style={{
  289. color: focused ? '#025c72' : '#888888',
  290. fontWeight: focused ? '900' : 'thin',
  291. fontSize: 20
  292. }}
  293. >
  294. {route.title}
  295. </Text>
  296. )
  297. }}
  298. />
  299. );
  300. };
  301. export default CouponTabViewComponent;
  302. const styles = StyleSheet.create({
  303. container: { flexDirection: 'row' },
  304. image: { width: 100, height: 100, margin: 15, borderRadius: 10 },
  305. textContainer: { flexDirection: 'column', gap: 8, marginTop: 20 },
  306. floatingButton: {
  307. elevation: 5,
  308. shadowColor: '#000',
  309. shadowOffset: { width: 0, height: 2 },
  310. shadowOpacity: 0.25,
  311. shadowRadius: 3.84
  312. }
  313. });