walletPageComponent.tsx 22 KB

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