walletPageComponent.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import {
  2. View,
  3. Image,
  4. Text,
  5. ScrollView,
  6. AppState,
  7. Pressable,
  8. ImageBackground,
  9. ActivityIndicator,
  10. Modal,
  11. Alert,
  12. TextInput,
  13. Linking,
  14. StyleSheet,
  15. TouchableOpacity,
  16. Dimensions
  17. } from 'react-native';
  18. import { SafeAreaView } from 'react-native-safe-area-context';
  19. import { router } from 'expo-router';
  20. import { CrossLogoSvg } from '../global/SVG';
  21. import { use, useEffect, useRef, useState } from 'react';
  22. import { walletService } from '../../service/walletService';
  23. import NormalButton from '../global/normal_button';
  24. import sha256 from 'crypto-js/sha256';
  25. import { useChargingStore } from '../../providers/scan_qr_payload_store';
  26. import { PaymentBonusList } from '../../service/type/walletServiceType';
  27. import { useTranslation } from '../../util/hooks/useTranslation';
  28. interface AmountInputModalProps {
  29. visible: boolean;
  30. onClose: () => void;
  31. onConfirm: (amount: number) => void;
  32. }
  33. const AmountInputModal = ({ visible, onClose, onConfirm }: AmountInputModalProps) => {
  34. const { t } = useTranslation(); // 使用翻译钩子
  35. const [amounts, setAmounts] = useState<Array<{amount: number, percentage: number}>>([]);
  36. useEffect(() => {
  37. const fetchData = async () => {
  38. const res: PaymentBonusList[] = await walletService.getPaymentBonusList()
  39. setAmounts(res.map(item => ({amount: item.base_amount, percentage: item.gift_amount})))
  40. }
  41. if (visible){
  42. fetchData()
  43. }
  44. }, [visible])
  45. const getFontSize = () => {
  46. const { width } = Dimensions.get('window');
  47. if (width < 320) return 8;
  48. if (width < 350) return 10; //super small phones
  49. if (width < 375) return 12; // Smaller phones
  50. if (width < 414) return 14; // Average phones
  51. return 16; // Larger phones
  52. };
  53. return (
  54. <Modal animationType="fade" transparent={true} visible={visible} onRequestClose={onClose}>
  55. <View
  56. style={{
  57. flex: 1,
  58. justifyContent: 'center',
  59. alignItems: 'center',
  60. backgroundColor: 'rgba(0,0,0,0.5)'
  61. }}
  62. >
  63. <View
  64. style={{
  65. backgroundColor: 'white',
  66. padding: 20,
  67. borderRadius: 10,
  68. width: '80%'
  69. }}
  70. >
  71. <Text style={{ fontSize: 20, marginBottom: 20 }}>{t('wallet.amount_modal.title')}</Text>
  72. <View
  73. style={{
  74. flexDirection: 'row',
  75. flexWrap: 'wrap',
  76. justifyContent: 'space-between',
  77. marginBottom: 20
  78. }}
  79. >
  80. {amounts.map((amount) => (
  81. <Pressable
  82. key={amount.amount}
  83. onPress={() => onConfirm(amount.amount)}
  84. style={{
  85. backgroundColor: '#02677D',
  86. padding: 10,
  87. borderRadius: 5,
  88. width: '48%',
  89. alignItems: 'center',
  90. marginBottom: 10
  91. }}
  92. >
  93. <Text style={{ color: 'white', fontSize: getFontSize() }}>
  94. ${amount.amount}
  95. {amount.percentage > 0 ? ` (${t('wallet.amount_modal.gift_prefix')}${amount.percentage}) ` : ''}
  96. </Text>
  97. </Pressable>
  98. ))}
  99. </View>
  100. <Text>{t('wallet.amount_modal.gift_note')}</Text>
  101. <Pressable onPress={onClose} style={{ padding: 10, alignItems: 'center', marginTop: 10 }}>
  102. <Text style={{ color: 'red' }}>{t('wallet.amount_modal.cancel')}</Text>
  103. </Pressable>
  104. </View>
  105. </View>
  106. </Modal>
  107. );
  108. };
  109. export const IndividualCouponComponent = ({
  110. title,
  111. price,
  112. detail,
  113. date,
  114. setOpacity,
  115. redeem_code,
  116. onCouponClick = () => {}, // 添加默认空函数防止 undefined 报错
  117. noCircle
  118. }: {
  119. title: string;
  120. price: string;
  121. detail: string;
  122. onCouponClick?: (clickedCoupon: string, clickedCouponDescription: string) => void;
  123. date: string;
  124. setOpacity?: boolean;
  125. redeem_code?: string;
  126. noCircle?: boolean;
  127. }) => {
  128. const { t } = useTranslation(); // 使用翻译钩子
  129. const { promotion_code } = useChargingStore();
  130. return (
  131. <ImageBackground
  132. source={require('../../assets/empty_coupon.png')}
  133. resizeMode="contain"
  134. style={{ width: '100%', aspectRatio: 16 / 5, justifyContent: 'center' }}
  135. className={`mb-3 lg:mb-4
  136. ${setOpacity ? 'opacity-50' : ''}`}
  137. >
  138. {/* largest container */}
  139. <Pressable
  140. className="flex-row w-full h-full "
  141. onPress={setOpacity ? () => {} : () => onCouponClick(redeem_code as string, title)}
  142. >
  143. {/* price column on the left */}
  144. <View className="flex-row items-center w-[31%] justify-center">
  145. <Text className="pl-1 lg:pl-2 text-[#02677D] text-base md:text-lg lg:text-xl">$</Text>
  146. <Text className="text-3xl lg:text-4xl text-[#02677D] font-[600]">{price}</Text>
  147. </View>
  148. {/* this is a hack for good coupon display */}
  149. <View className="w-[7%] " />
  150. {/* detail column on the right */}
  151. <View className=" w-[62%] flex flex-col justify-evenly">
  152. <View className="flex flex-row justify-between items-center w-[90%]">
  153. <Text className="text-base lg:text-lg xl:text-xl">{title}</Text>
  154. {/* if opacity is true=used coupon= no circle */}
  155. {noCircle ? (
  156. <></>
  157. ) : (
  158. <View
  159. style={{
  160. width: 24,
  161. height: 24,
  162. borderRadius: 12,
  163. borderWidth: 2,
  164. borderColor: '#02677D',
  165. justifyContent: 'center',
  166. alignItems: 'center'
  167. }}
  168. className={`${promotion_code?.includes(redeem_code as string) ? 'bg-[#02677D]' : 'bg-white'}`}
  169. >
  170. <Text className="text-white">{promotion_code?.indexOf(redeem_code as string) + 1}</Text>
  171. </View>
  172. )}
  173. </View>
  174. <Text numberOfLines={2} ellipsizeMode="tail" className="text-xs w-[90%]">
  175. {detail}
  176. </Text>
  177. <View className="flex flex-row">
  178. <Text className="text-sm lg:text-base xl:text-lg">{t('wallet.coupon.valid_until')}{' '}</Text>
  179. <Text className="text-sm lg:text-base xl:text-lg font-bold text-[#02677D]">{date}</Text>
  180. </View>
  181. </View>
  182. </Pressable>
  183. </ImageBackground>
  184. );
  185. };
  186. const WalletPageComponent = () => {
  187. const { t } = useTranslation(); // 使用翻译钩子
  188. const [walletBalance, setWalletBalance] = useState<string | null>(null);
  189. const [loading, setLoading] = useState<boolean>(false);
  190. const [coupons, setCoupons] = useState([]);
  191. const [paymentType, setPaymentType] = useState({});
  192. const [userID, setUserID] = useState('');
  193. const [amount, setAmount] = useState<number>(0);
  194. const [amountModalVisible, setAmountModalVisible] = useState(false);
  195. const [outTradeNo, setOutTradeNo] = useState('');
  196. const PAYMENT_CHECK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
  197. const [paymentStatus, setPaymentStatus] = useState(null);
  198. const [isExpectingPayment, setIsExpectingPayment] = useState(false);
  199. const appState = useRef(AppState.currentState);
  200. const paymentInitiatedTime = useRef<number>(null);
  201. // 优惠券注释
  202. useEffect(() => {
  203. const fetchData = async () => {
  204. try {
  205. setLoading(true);
  206. const info = await walletService.getCustomerInfo();
  207. const coupon = await walletService.getCouponForSpecificUser(info.id);
  208. const useableConpon = coupon.filter((couponObj: any) => {
  209. const today = new Date();
  210. if (couponObj.expire_date === null) {
  211. return couponObj.is_consumed === false;
  212. }
  213. const expireDate = new Date(couponObj.expire_date);
  214. return expireDate > today && couponObj.is_consumed === false;
  215. });
  216. setCoupons(useableConpon);
  217. } catch (error) {
  218. console.error(t('wallet.error_fetching_coupons'), error);
  219. } finally {
  220. setLoading(false);
  221. }
  222. };
  223. fetchData();
  224. }, []);
  225. //monitor app state
  226. useEffect(() => {
  227. const subscription = AppState.addEventListener('change', (nextAppState) => {
  228. if (
  229. appState.current.match(/inactive|background/) &&
  230. nextAppState === 'active' &&
  231. isExpectingPayment &&
  232. // outTradeNo &&
  233. paymentInitiatedTime.current
  234. ) {
  235. const currentTime = new Date().getTime();
  236. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  237. checkPaymentStatus();
  238. } else {
  239. // Payment check timeout reached
  240. setIsExpectingPayment(false);
  241. setOutTradeNo('');
  242. paymentInitiatedTime.current = null;
  243. Alert.alert(
  244. t('wallet.payment_timeout_title'),
  245. t('wallet.payment_timeout_message')
  246. );
  247. }
  248. }
  249. appState.current = nextAppState;
  250. });
  251. return () => {
  252. subscription.remove();
  253. };
  254. }, [outTradeNo, isExpectingPayment]);
  255. //check payment status
  256. const checkPaymentStatus = async () => {
  257. try {
  258. const result = await walletService.checkPaymentStatus(outTradeNo);
  259. setPaymentStatus(result);
  260. if (result && !result.some((item: any) => item.errmsg?.includes(t('wallet.processing')))) {
  261. // Payment successful
  262. Alert.alert(t('wallet.payment_success_title'), t('wallet.payment_success_message'), [
  263. {
  264. text: t('wallet.success'),
  265. onPress: async () => {
  266. const wallet = await walletService.getWalletBalance();
  267. setWalletBalance(wallet);
  268. }
  269. }
  270. ]);
  271. } else {
  272. Alert.alert(t('wallet.payment_failed_title'), t('wallet.payment_failed_message'));
  273. }
  274. setIsExpectingPayment(false);
  275. setOutTradeNo('');
  276. paymentInitiatedTime.current = null;
  277. } catch (error) {
  278. console.error(t('wallet.error_checking_payment_status'), error);
  279. Alert.alert(t('wallet.error_title'), t('wallet.payment_status_check_failed'));
  280. }
  281. };
  282. //fetch customer wallet balance
  283. useEffect(() => {
  284. const fetchData = async () => {
  285. try {
  286. setLoading(true);
  287. const info = await walletService.getCustomerInfo();
  288. const wallet = await walletService.getWalletBalance();
  289. setUserID(info.id);
  290. setWalletBalance(wallet);
  291. // setCoupons(coupon);
  292. } catch (error) {
  293. console.error(t('wallet.error_fetching_balance'), error);
  294. } finally {
  295. setLoading(false);
  296. }
  297. };
  298. fetchData();
  299. }, []);
  300. const formatMoney = (amount: any) => {
  301. if (amount === null || amount === undefined || isNaN(Number(amount))) {
  302. return t('wallet.loading');
  303. }
  304. if (typeof amount !== 'number') {
  305. amount = Number(amount);
  306. }
  307. // Check if the number is a whole number
  308. if (Number.isInteger(amount)) {
  309. return amount.toLocaleString('en-US');
  310. }
  311. // For decimal numbers, show one decimal place
  312. return Number(amount)
  313. .toFixed(1)
  314. .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  315. };
  316. const filterPaymentOptions = (options: Record<string, any>, allowedKeys: string[]) => {
  317. return Object.fromEntries(Object.entries(options).filter(([key]) => allowedKeys.includes(key)));
  318. };
  319. function formatTime(utcTimeString: string) {
  320. // Parse the UTC time string
  321. const date = new Date(utcTimeString);
  322. // Add 8 hours
  323. date.setHours(date.getHours());
  324. // Format the date
  325. const year = date.getFullYear();
  326. const month = String(date.getMonth() + 1).padStart(2, '0');
  327. const day = String(date.getDate()).padStart(2, '0');
  328. const hours = String(date.getHours()).padStart(2, '0');
  329. const minutes = String(date.getMinutes()).padStart(2, '0');
  330. const seconds = String(date.getSeconds()).padStart(2, '0');
  331. // Return the formatted string
  332. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  333. }
  334. useEffect(() => {
  335. const fetchPaymentType = async () => {
  336. const response = await walletService.selectPaymentType();
  337. // console.log('response', response);
  338. const filteredPaymentTypes = filterPaymentOptions(response, ['union_pay_wap_payment', 'payme_wap_payment']);
  339. setPaymentType(filteredPaymentTypes);
  340. };
  341. fetchPaymentType();
  342. }, []);
  343. const handleAmountConfirm = async (inputAmount: number) => {
  344. setAmountModalVisible(false);
  345. try {
  346. const response = await walletService.getOutTradeNo();
  347. if (response) {
  348. setOutTradeNo(response);
  349. setIsExpectingPayment(true);
  350. paymentInitiatedTime.current = new Date().getTime();
  351. const now = new Date();
  352. const formattedTime = formatTime(now.toISOString());
  353. let amount = inputAmount * 100;
  354. const origin = 'https://openapi-hk.qfapi.com/checkstand/#/?';
  355. const obj = {
  356. // appcode: '6937EF25DF6D4FA78BB2285441BC05E9',
  357. appcode: '636E234FB30D43598FC8F0140A1A7282',
  358. goods_name: t('wallet.top_up_goods_name'),
  359. out_trade_no: response,
  360. paysource: 'crazycharge_checkout',
  361. return_url: 'https://www.google.com',
  362. failed_url: 'https://www.google.com',
  363. notify_url: 'https://api.crazycharge.com.hk/api/v1/clients/qfpay/webhook',
  364. sign_type: 'sha256',
  365. txamt: amount,
  366. txcurrcd: 'HKD',
  367. txdtm: formattedTime
  368. };
  369. const paramStringify = (json: Record<string, any>, flag?: boolean) => {
  370. let str = '';
  371. let keysArr = Object.keys(json);
  372. keysArr.sort().forEach((val) => {
  373. if (!json[val]) return;
  374. str += `${val}=${flag ? encodeURIComponent(json[val]) : json[val]}&`;
  375. });
  376. return str.slice(0, -1);
  377. };
  378. // const api_key = '8F59E31F6ADF4D2894365F2BB6D2FF2C';
  379. const api_key = '3E2727FBA2DA403EA325E73F36B07824';
  380. const params = paramStringify(obj);
  381. const sign = sha256(`${params}${api_key}`).toString();
  382. const url = `${origin}${paramStringify(obj, true)}&sign=${sign}`;
  383. try {
  384. const supported = await Linking.canOpenURL(url);
  385. if (supported) {
  386. await Linking.openURL(url);
  387. } else {
  388. Alert.alert(t('wallet.error_title'), t('wallet.try_again_later'));
  389. }
  390. } catch (error) {
  391. console.error(t('wallet.top_up_failed'), error);
  392. Alert.alert(t('wallet.error_title'), t('wallet.top_up_failed_message'));
  393. }
  394. } else {
  395. }
  396. } catch (error) {
  397. console.error(t('wallet.error_processing_top_up'), error);
  398. }
  399. };
  400. const handleCouponClick = async (couponName: string, couponDescription: string) => {
  401. router.push({
  402. pathname: '/couponDetailPage',
  403. params: {
  404. couponName: couponName,
  405. couponDescription: couponDescription
  406. }
  407. });
  408. };
  409. const formattedAmount = formatMoney(walletBalance);
  410. return (
  411. <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
  412. <ScrollView className="flex-1 ">
  413. <View className="flex-1 mx-[5%]">
  414. <View style={{ marginTop: 25 }}>
  415. <Pressable
  416. onPress={() => {
  417. router.replace('/accountMainPage');
  418. }}
  419. >
  420. <CrossLogoSvg />
  421. </Pressable>
  422. <Text style={{ fontSize: 45, marginVertical: 25 }}>{t('wallet.title')}</Text>
  423. </View>
  424. <View>
  425. <ImageBackground
  426. className="flex-col-reverse shadow-lg"
  427. style={{ height: 200 }}
  428. source={require('../../assets/walletCard1.png')}
  429. resizeMode="contain"
  430. >
  431. <View className="mx-[5%] pb-6">
  432. <Text className="text-white text-xl">{t('wallet.balance_label')}</Text>
  433. <View className="flex-row items-center justify-between flex-wrap w-full">
  434. <Text style={{ fontSize: 52 }} className=" text-white font-bold">
  435. {loading ? (
  436. <View className="items-center justify-center">
  437. <ActivityIndicator />
  438. </View>
  439. ) : (
  440. <>
  441. <Text>$</Text>
  442. {formattedAmount === t('wallet.loading') || amount == null ? (
  443. <ActivityIndicator />
  444. ) : (
  445. `${formattedAmount}`
  446. )}
  447. </>
  448. )}
  449. </Text>
  450. <Pressable
  451. className="rounded-2xl items-center justify-center p-3 px-5"
  452. style={{
  453. backgroundColor: 'rgba(231, 242, 248, 0.2)'
  454. }}
  455. onPress={() => {
  456. setAmountModalVisible(true);
  457. }}
  458. >
  459. <Text className="text-white font-bold">+ {t('wallet.top_up')}</Text>
  460. </Pressable>
  461. </View>
  462. </View>
  463. </ImageBackground>
  464. </View>
  465. <View className="flex-row-reverse mt-2 mb-6">
  466. <Pressable
  467. onPress={() => {
  468. router.push({
  469. pathname: '/paymentRecord',
  470. params: { walletBalance: formatMoney(walletBalance) }
  471. });
  472. }}
  473. >
  474. <Text className="text-[#02677D] text-lg underline">{t('wallet.payment_records')}</Text>
  475. </Pressable>
  476. </View>
  477. </View>
  478. <View className="w-full h-1 bg-[#DBE4E8]" />
  479. <View className="flex-1 flex-col mt-4 mx-[5%]">
  480. <NormalButton
  481. onPress={() => router.push('couponPage')}
  482. title={
  483. <Text className="text-white font-bold text-lg">{t('wallet.view_all_coupons')}</Text>
  484. }
  485. extendedStyle={{
  486. padding: 15
  487. }}
  488. />
  489. </View>
  490. </ScrollView>
  491. <AmountInputModal
  492. visible={amountModalVisible}
  493. onClose={() => setAmountModalVisible(false)}
  494. onConfirm={handleAmountConfirm}
  495. />
  496. </SafeAreaView>
  497. );
  498. };
  499. const styles = StyleSheet.create({
  500. button: {
  501. maxWidth: '100%',
  502. fontSize: 16,
  503. backgroundColor: '#025c72',
  504. justifyContent: 'center',
  505. alignItems: 'center',
  506. borderRadius: 12,
  507. padding: 20
  508. },
  509. buttonPressed: {
  510. backgroundColor: '#28495c'
  511. }
  512. });
  513. export default WalletPageComponent;