Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: purchase points and sponsors #12

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .easignore
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,6 @@ dist/*
!dist/apple-app-site-association

# Below is why we need .easignore
# https://github.com/expo/eas-cli/issues/1253
# google-services.json
# GoogleService-Info.plist
2 changes: 1 addition & 1 deletion app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default ({config}: ConfigContext): ExpoConfig => ({
'expo-build-properties',
{
// https://github.com/software-mansion/react-native-screens/issues/2219
ios: {newArchEnabled: true},
ios: {newArchEnabled: true, deploymentTarget: '15.0'},
android: {newArchEnabled: true},
},
],
Expand Down
30 changes: 30 additions & 0 deletions app/(app)/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import useAppState from '../../../src/hooks/useAppState';
import {openEmail} from '../../../src/utils/common';
import ErrorBoundary from 'react-native-error-boundary';
import FallbackComponent from '../../../src/components/uis/FallbackComponent';
import {showAlert} from '../../../src/utils/alert';

const Container = styled.View`
background-color: ${({theme}) => theme.bg.basic};
Expand Down Expand Up @@ -121,6 +122,35 @@ export default function Settings(): JSX.Element {
),
title: t('settings.updateProfile'),
},
{
onPress: () => {
if (Platform.OS !== 'web') {
push('/settings/points');
return;
}

showAlert(t('error.notSupportedInWeb'));
},
startElement: (
<Icon
name="Coins"
size={24}
style={css`
margin-right: 16px;
`}
/>
),
endElement: (
<Icon
name="CaretRight"
size={16}
style={css`
margin-left: auto;
`}
/>
),
title: t('settings.points'),
},
{
onPress: () => push('/settings/block-users'),
startElement: (
Expand Down
248 changes: 248 additions & 0 deletions app/(app)/settings/points.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
import {
endConnection,
finishTransaction,
getProducts,
initConnection,
isProductAndroid,
isProductIos,
purchaseErrorListener,
purchaseUpdatedListener,
requestPurchase,
} from 'expo-iap';
import type {
Product,
ProductPurchase,
PurchaseError,
} from 'expo-iap/build/ExpoIap.types';
import type {} from 'expo-iap/build/types/ExpoIapAndroid.types';
import {Stack} from 'expo-router';
import {useEffect, useState} from 'react';
import {InteractionManager, View} from 'react-native';
import {t} from '../../../src/STRINGS';
import styled, {css} from '@emotion/native';
import {
fetchCreatePurchase,
fetchUserPoints,
} from '../../../src/apis/purchaseQueries';
import {useRecoilValue} from 'recoil';
import {authRecoilState} from '../../../src/recoil/atoms';
import {Button, Icon, Typography, useDooboo} from 'dooboo-ui';
import {showAlert} from '../../../src/utils/alert';

const productSkus = [
'cpk.points.200',
'cpk.points.500',
'cpk.points.1000',
'cpk.points.5000',
'cpk.points.10000',
'cpk.points.30000',
];

const Container = styled.View`
background-color: ${({theme}) => theme.bg.basic};

flex: 1;
align-self: stretch;
`;

const Content = styled.ScrollView`
padding: 16px;
`;

export default function App() {
const [isConnected, setIsConnected] = useState(false);
const [products, setProducts] = useState<Product[]>([]);
const [userPoints, setUserPoints] = useState(0);
const {authId} = useRecoilValue(authRecoilState);
const {theme} = useDooboo();

useEffect(() => {
const getUserPoints = async () => {
const data = await fetchUserPoints(authId!);
setUserPoints(data || 0);
};

authId && getUserPoints();
}, [authId]);

useEffect(() => {
const initIAP = async () => {
if (await initConnection()) {
setIsConnected(true);
}

const products = await getProducts(productSkus);
products.sort((a, b) => {
if (isProductAndroid(a) && isProductAndroid(b)) {
return (
parseInt(a?.oneTimePurchaseOfferDetails?.priceAmountMicros || '0') -
parseInt(b?.oneTimePurchaseOfferDetails?.priceAmountMicros || '0')
);
}

if (isProductIos(a) && isProductIos(b)) {
return a.price - b.price;
}

return 0;
});
setProducts(products);
};

initIAP();

return () => {
endConnection();
};
}, []);

useEffect(() => {
const purchaseUpdatedSubs = purchaseUpdatedListener(
(purchase: ProductPurchase) => {
const ackPurchase = async (purchase: ProductPurchase) => {
await finishTransaction({
purchase,
isConsumable: true,
});
};

InteractionManager.runAfterInteractions(async () => {
const receipt = purchase && purchase.transactionReceipt;

if (receipt) {
const result = await fetchCreatePurchase({
authId: authId!,
points: parseInt(purchase?.productId.split('.').pop() || '0'),
productId: purchase?.productId || '',
receipt,
});

if (result) {
ackPurchase(purchase);
}
}
});
},
);

const purchaseErrorSubs = purchaseErrorListener((error: PurchaseError) => {
InteractionManager.runAfterInteractions(() => {
showAlert(error?.message);
});
});

return () => {
purchaseUpdatedSubs.remove();
purchaseErrorSubs.remove();
endConnection();
};
}, [authId]);

return (
<Container>
<Stack.Screen options={{title: t('points.title')}} />
<View
style={css`
align-self: stretch;

flex-direction: row;
padding: 8px 16px;
align-items: center;
gap: 12px;
background-color: ${theme.bg.paper};
`}
>
<Typography.Body2
style={css`
font-family: Pretendard-Bold;
`}
>
{t('points.myPoints')}
</Typography.Body2>
<View
style={css`
flex-direction: row;
align-items: center;
gap: 4px;
`}
>
<Icon name="Coins" />
<Typography.Body2
style={css`
font-family: Pretendard-Bold;
`}
>
{userPoints}
</Typography.Body2>
</View>
</View>

<Content>
{isConnected
? products.map((item) => {
if (isProductAndroid(item)) {
return (
<View
key={item.title}
style={css`
flex: 1;
margin-bottom: 8px;

flex-direction: row;
gap: 12px;
justify-content: space-between;
`}
>
<Typography.Body2>
<Icon name="Coins" /> {item.title}
</Typography.Body2>
<Button
text={item.oneTimePurchaseOfferDetails?.formattedPrice}
onPress={() => {
requestPurchase({skus: [item.productId]});
}}
/>
</View>
);
}

if (isProductIos(item)) {
return (
<View
key={item.id}
style={css`
flex: 1;
margin-bottom: 8px;

flex-direction: row;
gap: 12px;
justify-content: space-between;
`}
>
<Typography.Body2>
<Icon name="Coins" /> {item.displayName}
</Typography.Body2>
<Button
text={item.displayPrice}
size="small"
color="success"
styles={{
container: css`
border-width: 0;
width: 88px;
padding: 6px 4px;
`,
}}
onPress={() => {
requestPurchase({sku: item.id});
}}
/>
</View>
);
}
})
: null}
</Content>
</Container>
);
}
47 changes: 46 additions & 1 deletion app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ import {useEffect, useState} from 'react';
import type {ColorSchemeName} from 'react-native';
import {Platform, useColorScheme} from 'react-native';
import {GestureHandlerRootView, RectButton} from 'react-native-gesture-handler';
import {
checkForUpdateAsync,
fetchUpdateAsync,
reloadAsync,
useUpdates,
} from 'expo-updates';
import {dark, light} from '@dooboo-ui/theme';
import styled, {css} from '@emotion/native';
import * as Notifications from 'expo-notifications';
Expand Down Expand Up @@ -29,6 +35,7 @@ import CustomLoadingIndicator from '../src/components/uis/CustomLoadingIndicator
import {fetchUserProfile} from '../src/apis/profileQueries';
import {registerForPushNotificationsAsync} from '../src/utils/notifications';
import {fetchAddPushToken} from '../src/apis/pushTokenQueries';
import useAppState from '../src/hooks/useAppState';

SplashScreen.preventAutoHideAsync();

Expand Down Expand Up @@ -59,6 +66,44 @@ function App(): JSX.Element | null {
const {back, replace} = useRouter();
const [{authId}, setAuth] = useRecoilState(authRecoilState);
const [initialRouteName, setInitialRouteName] = useState<string>();
const [checkEasUpdate, setCheckEasUpdate] = useState(false);
const {isUpdateAvailable, isUpdatePending} = useUpdates();

useEffect(() => {
if (isUpdatePending) {
reloadAsync();
}
}, [isUpdatePending]);

useAppState((state) => {
if (state === 'active') {
/* check eas updates */
const checkUpdate = async (): Promise<void> => {
if (Platform.OS === 'web' || __DEV__) {
return;
}

await checkForUpdateAsync();

try {
if (isUpdateAvailable) {
setCheckEasUpdate(true);
await fetchUpdateAsync();
}
} catch (e) {
if (__DEV__) {
console.error(e);
}
} finally {
setCheckEasUpdate(false);
}
};

checkUpdate();

return;
}
});

useEffect(() => {
const {data} = supabase.auth.onAuthStateChange(async (evt, session) => {
Expand Down Expand Up @@ -185,7 +230,7 @@ function App(): JSX.Element | null {
}
}, [assetLoaded, authId]);

if (!initialRouteName) {
if (!initialRouteName || checkEasUpdate) {
return <CustomLoadingIndicator />;
}

Expand Down
Binary file removed assets/adaptive_icon.png
Binary file not shown.
Loading
Loading