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

Update android app purchase #1343

Merged
Merged
Show file tree
Hide file tree
Changes from 16 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
65 changes: 43 additions & 22 deletions src/components/Settings/Subscribe/Subscribe.component.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ import {
import { isAndroid } from '../../../cordova-util';
import { CircularProgress } from '@material-ui/core';

import { Link } from 'react-router-dom';
import RefreshIcon from '@material-ui/icons/Refresh';

import {
EXPIRED,
NOT_SUBSCRIBED,
PROCCESING,
ON_HOLD
} from '../../../providers/SubscriptionProvider/SubscriptionProvider.constants';

const propTypes = {
/**
* Callback fired when clicking the back button
Expand All @@ -51,7 +61,11 @@ const propTypes = {
/**
* User email
*/
email: PropTypes.string.isRequired
email: PropTypes.string.isRequired,
/**
* Handle update store
*/
onUpdateStore: PropTypes.func
};

const defaultProps = {
Expand All @@ -69,7 +83,8 @@ const Subscribe = ({
location: { country, countryCode },
onSubmitPeople,
products,
subscription
subscription,
onUpdateStore
}) => {
const renderIncludedFeatures = () => {
return INCLUDED_FEATURES.map(feature => {
Expand All @@ -88,9 +103,11 @@ const Subscribe = ({
};
const renderProducts = () => {
return products.map(product => {
//const canPurchase = product.canPurchase();
const canPurchase =
subscription.androidSubscriptionState === NOT_SUBSCRIBED ||
subscription.androidSubscriptionState === EXPIRED ||
subscription.androidSubscriptionState === ON_HOLD;
return product.offers.map(offer => {
//const canPurchase = window.CdvPurchase.store.canPurchase(offer.id);
return [
<Grid
key={offer.id}
Expand All @@ -116,8 +133,10 @@ const Subscribe = ({
variant="contained"
fullWidth={true}
color="primary"
onClick={subscribe(product, offer)}
//disabled={!canPurchase}
{...(!isLogged
? { component: Link, to: '/login-signup' }
: { onClick: subscribe(product, offer) })}
disabled={!canPurchase}
>
<FormattedMessage {...messages.subscribe} />
</Button>
Expand All @@ -141,25 +160,27 @@ const Subscribe = ({
};

const renderSubscriptionStatus = () => {
let productStatus = 'processing';
const { isSubscribed, androidSubscriptionState, expiryDate } = subscription;
let productStatus = PROCCESING;
const {
isSubscribed,
androidSubscriptionState,
expiryDate,
error
} = subscription;

const ERROR = 'error';

if (isAndroid()) {
//const productStatus = getProductStatus(subscriptions);
productStatus = isSubscribed
? androidSubscriptionState
: getProductStatus();
productStatus = error.showError ? ERROR : androidSubscriptionState;
}

const alertProps = {
// owned: 'success',
// approved: 'warning',
// initiated: 'warning',
active: 'success',
canceled: 'warning',
in_grace_period: 'warning',
proccesing: 'info',
not_subscribed: 'info',
error: 'error',

on_hold: 'warning', //TODO
paused: 'info', //TODO
Expand All @@ -173,20 +194,20 @@ const Subscribe = ({

return [
<Alert
variant="outlined"
variant="filled"
severity={alertProps[productStatus]}
// color="info"
className="Subscribe__Alert"
icon={
productStatus === 'proccesing' ? <CircularProgress size={20} /> : ''
productStatus === PROCCESING ? <CircularProgress size={20} /> : ''
}
action={
productStatus === 'proccesing' ? (
<Button color="inherit" size="small">
<FormattedMessage {...messages.refresh} />
</Button>
) : (
productStatus === NOT_SUBSCRIBED || productStatus === ERROR ? (
''
) : (
<Button color="inherit" size="small" onClick={onUpdateStore}>
<RefreshIcon />
</Button>
)
}
>
Expand Down
3 changes: 1 addition & 2 deletions src/components/Settings/Subscribe/Subscribe.constants.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
//export const AVAIABLE_PRODUCTS_ID = [{ subscriptionId: "premium_full", planId: "premium-full-features-yearl" }];
//repoTest
export const AVAIABLE_PRODUCTS_ID = [
{
subscriptionId: 'premium_full',
planId: ['premium-full-features-yearl', 'premium-full-feature-monthly']
}
];

export const INCLUDED_FEATURES = [
'onlineNeuralVoices',
'copyPublicBoards',
Expand Down
99 changes: 77 additions & 22 deletions src/components/Settings/Subscribe/Subscribe.container.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@ import API from '../../../api';

import { isAndroid } from '../../../cordova-util';
import { AVAIABLE_PRODUCTS_ID } from './Subscribe.constants';
import { updateSubscriberId } from '../../../providers/SubscriptionProvider/SubscriptionProvider.actions';
import {
comprobeSubscription,
updateSubscriberId,
updateSubscription,
updateAndroidSubscriptionState,
updateSubscriptionError
} from '../../../providers/SubscriptionProvider/SubscriptionProvider.actions';
import {
NOT_SUBSCRIBED,
PROCCESING
} from '../../../providers/SubscriptionProvider/SubscriptionProvider.constants';

export class SubscribeContainer extends PureComponent {
static propTypes = {
Expand All @@ -23,30 +33,20 @@ export class SubscribeContainer extends PureComponent {
};

componentDidMount() {
if (isAndroid())
if (isAndroid()) {
window.CdvPurchase.store.when('subscription').updated(this.setProducts);
//window.store.when('subscription').updated(this.setProducts);
this.props.comprobeSubscription();
}
this.setProducts();
}

componentWillUnmount() {
//if (isAndroid()) window.CdvPurchase.store.off(this.setProducts); //window.store.off(this.setProducts);
}

setProducts = () => {
if (isAndroid()) {
// const products = AVAIABLE_PRODUCTS_ID.map(product => {
// //return window.store.get(product.subscriptionId);
// });
//return this.setState({ products: products });

const validProducts = window.CdvPurchase.store.products.filter(
product =>
product.offers.length > 0 &&
AVAIABLE_PRODUCTS_ID.some(p => p.subscriptionId === product.id)
);
console.log('products set products', validProducts);

return this.setState({ products: validProducts });
}

Expand Down Expand Up @@ -79,14 +79,62 @@ export class SubscribeContainer extends PureComponent {

handleSubmit = async () => {};

handleUpdateStore = () => {
const { comprobeSubscription } = this.props;

window.CdvPurchase.store.update();
comprobeSubscription();
};

handleError = e => {
const { updateSubscriptionError, updateSubscription } = this.props;

updateSubscriptionError({
showError: true,
message: e.message,
code: e.code
});

updateSubscription({
isSubscribed: false,
expiryDate: null,
androidSubscriptionState: NOT_SUBSCRIBED
});

setTimeout(() => {
updateSubscriptionError({
showError: false,
message: '',
code: ''
});
}, 3000);
};

handleSubscribe = (product, offer) => async event => {
const { user, isLogged, location, updateSubscriberId } = this.props;
const {
user,
isLogged,
location,
updateSubscriberId,
updateSubscription,
subscription
} = this.props;
if (isAndroid()) {
if (isLogged) {
if (
isLogged &&
subscription.androidSubscriptionState === NOT_SUBSCRIBED
) {
try {
updateSubscription({
isSubscribed: false,
expiryDate: null,
androidSubscriptionState: PROCCESING
});

const subscriber = await API.getSubscriber(user.id);
updateSubscriberId(subscriber._id);
window.CdvPurchase.store.order(offer);
const order = await window.CdvPurchase.store.order(offer);
if (order && order.isError) throw order;
} catch (e) {
if (e.response?.data.error === 'subscriber not found') {
try {
Expand All @@ -102,16 +150,18 @@ export class SubscribeContainer extends PureComponent {
};
const res = await API.createSubscriber(newSubscriber);
updateSubscriberId(res._id);
window.CdvPurchase.store.order(offer);
const order = await window.CdvPurchase.store.order(offer);
if (order && order.isError) throw order;
} catch (e) {
console.error('Cannot suscribe product', e.message);
console.error('Cannot subscribe product', e.message);
this.handleError(e);
}
}
console.error('Cannot subscribe product', e.message);
this.handleError(e);
}
}
}

//TODO open modal
};

render() {
Expand All @@ -129,6 +179,7 @@ export class SubscribeContainer extends PureComponent {
products={this.state.products}
subscription={this.props.subscription}
updateSubscriberId={this.props.updateSubscriberId}
onUpdateStore={this.handleUpdateStore}
/>
);
}
Expand All @@ -155,7 +206,11 @@ const mapStateToProps = state => {
};

const mapDispatchToProps = {
updateSubscriberId
updateSubscriberId,
updateSubscription,
comprobeSubscription,
updateAndroidSubscriptionState,
updateSubscriptionError
};

export default connect(
Expand Down
30 changes: 19 additions & 11 deletions src/components/Settings/Subscribe/Subscribe.helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ export const getProductStatus = () => {
);

// if (isOwned(subscriptions)) return 'OWNED';
if (isApproved(subscriptions) || isInitiated(subscriptions))
if (isApproved(subscriptions))
//|| isInitiated(subscriptions))
return 'proccesing';
return 'not_subscribed';
};
Expand All @@ -14,16 +15,25 @@ const isOwned = products => {
};

const isApproved = products => {
return !!findLocalTransaction(
products,
t => t.state === window.CdvPurchase.TransactionState.APPROVED
console.log(
'Is aprroved verified purchase',
!!!findVerifiedPurchase(products, p => !p.isExpired)
);
return (
!!findLocalTransaction(
products,
t => t.state === window.CdvPurchase.TransactionState.APPROVED
) && !!!findVerifiedPurchase(products, p => !p.isExpired)
);
};

const isInitiated = products => {
return !!findLocalTransaction(
products,
t => t.state === window.CdvPurchase.TransactionState.INITIATED
return (
!!findLocalTransaction(
products,
t => t.state === window.CdvPurchase.TransactionState.INITIATED
) &&
!!findVerifiedPurchase(products, p => new Date(p.expiryDate) < Date.now())
);
};

Expand All @@ -40,10 +50,8 @@ const findVerifiedPurchase = (products, filter) => {
const findLocalTransaction = (products, filter) => {
// find if some of those products are part of a receipt
for (const product of products) {
console.log(product);
const transaction = window.CdvPurchase.store.findInLocalReceipts(product);
//const transaction = findInLocalReceipts(product);
console.log('transaction in local receipt', transaction);
//const transaction = window.CdvPurchase.store.findInLocalReceipts(product);
const transaction = findInLocalReceipts(product);
RodriSanchez1 marked this conversation as resolved.
Show resolved Hide resolved
if (!transaction) continue;
if (filter(transaction)) return transaction;
}
Expand Down
4 changes: 4 additions & 0 deletions src/components/Settings/Subscribe/Subscribe.messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,9 @@ export default defineMessages({
refresh: {
id: 'cboard.components.Settings.Subscribe.refresh',
defaultMessage: 'REFRESH'
},
error: {
id: 'cboard.components.Settings.Subscribe.error',
defaultMessage: 'Oops something went wrong. Please try again later'
}
});
Loading