Skip to content

feat: purchase points and sponsors #12

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

Open
wants to merge 9 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 .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"Onesignal",
"Pressable",
"Pretendard",
"supabase",
"svgs"
],
"typescript.tsdk": "node_modules/typescript/lib"
Expand Down
3 changes: 2 additions & 1 deletion app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,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.1'},
android: {newArchEnabled: true},
},
],
Expand All @@ -58,6 +58,7 @@ export default ({config}: ConfigContext): ExpoConfig => ({
],
},
],
'expo-iap',
[
'expo-notifications',
{
Expand Down
29 changes: 29 additions & 0 deletions app/(home)/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,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
258 changes: 258 additions & 0 deletions app/(home)/settings/points.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
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, useCPK} from 'cpk-ui';
import {showAlert} from '../../../src/utils/alert';
import useSupabase from '../../../src/hooks/useSupabase';

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 {supabase} = useSupabase();
const {theme} = useCPK();

useEffect(() => {
const getUserPoints = async () => {
if (!supabase) return;

const data = await fetchUserPoints({
authId: authId!,
supabase,
});
setUserPoints(data || 0);
};

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

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 || 0 - (b.price || 0);
}

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 (!supabase) return;

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

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

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

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

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.id]});
}}
/>
</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>
);
}
Loading