couponTabView.tsx 11 KB

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