UpgradeDialog.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import * as React from 'react';
  2. import {useContext, useEffect, useState} from 'react';
  3. import Dialog from '@mui/material/Dialog';
  4. import DialogContent from '@mui/material/DialogContent';
  5. import DialogTitle from '@mui/material/DialogTitle';
  6. import {Alert, CardActionArea, CardContent, Chip, Link, ListItem, Switch, useMediaQuery} from "@mui/material";
  7. import theme from "./theme";
  8. import Button from "@mui/material/Button";
  9. import accountApi, {SubscriptionInterval} from "../app/AccountApi";
  10. import session from "../app/Session";
  11. import routes from "./routes";
  12. import Card from "@mui/material/Card";
  13. import Typography from "@mui/material/Typography";
  14. import {AccountContext} from "./App";
  15. import {formatBytes, formatNumber, formatPrice, formatShortDate} from "../app/utils";
  16. import {Trans, useTranslation} from "react-i18next";
  17. import List from "@mui/material/List";
  18. import {Check, Close} from "@mui/icons-material";
  19. import ListItemIcon from "@mui/material/ListItemIcon";
  20. import ListItemText from "@mui/material/ListItemText";
  21. import Box from "@mui/material/Box";
  22. import {NavLink} from "react-router-dom";
  23. import {UnauthorizedError} from "../app/errors";
  24. import DialogContentText from "@mui/material/DialogContentText";
  25. import DialogActions from "@mui/material/DialogActions";
  26. const UpgradeDialog = (props) => {
  27. const { t } = useTranslation();
  28. const { account } = useContext(AccountContext); // May be undefined!
  29. const [error, setError] = useState("");
  30. const [tiers, setTiers] = useState(null);
  31. const [interval, setInterval] = useState(account?.billing?.interval || SubscriptionInterval.YEAR);
  32. const [newTierCode, setNewTierCode] = useState(account?.tier?.code); // May be undefined
  33. const [loading, setLoading] = useState(false);
  34. const fullScreen = useMediaQuery(theme.breakpoints.down('sm'));
  35. useEffect(() => {
  36. const fetchTiers = async () => {
  37. setTiers(await accountApi.billingTiers());
  38. }
  39. fetchTiers(); // Dangle
  40. }, []);
  41. if (!tiers) {
  42. return <></>;
  43. }
  44. const tiersMap = Object.assign(...tiers.map(tier => ({[tier.code]: tier})));
  45. const newTier = tiersMap[newTierCode]; // May be undefined
  46. const currentTier = account?.tier; // May be undefined
  47. const currentInterval = account?.billing?.interval; // May be undefined
  48. const currentTierCode = currentTier?.code; // May be undefined
  49. // Figure out buttons, labels and the submit action
  50. let submitAction, submitButtonLabel, banner;
  51. if (!account) {
  52. submitButtonLabel = t("account_upgrade_dialog_button_redirect_signup");
  53. submitAction = Action.REDIRECT_SIGNUP;
  54. banner = null;
  55. } else if (currentTierCode === newTierCode && (currentInterval === undefined || currentInterval === interval)) {
  56. submitButtonLabel = t("account_upgrade_dialog_button_update_subscription");
  57. submitAction = null;
  58. banner = (currentTierCode) ? Banner.PRORATION_INFO : null;
  59. } else if (!currentTierCode) {
  60. submitButtonLabel = t("account_upgrade_dialog_button_pay_now");
  61. submitAction = Action.CREATE_SUBSCRIPTION;
  62. banner = null;
  63. } else if (!newTierCode) {
  64. submitButtonLabel = t("account_upgrade_dialog_button_cancel_subscription");
  65. submitAction = Action.CANCEL_SUBSCRIPTION;
  66. banner = Banner.CANCEL_WARNING;
  67. } else {
  68. submitButtonLabel = t("account_upgrade_dialog_button_update_subscription");
  69. submitAction = Action.UPDATE_SUBSCRIPTION;
  70. banner = Banner.PRORATION_INFO;
  71. }
  72. // Exceptional conditions
  73. if (loading) {
  74. submitAction = null;
  75. } else if (newTier?.code && account?.reservations?.length > newTier?.limits?.reservations) {
  76. submitAction = null;
  77. banner = Banner.RESERVATIONS_WARNING;
  78. }
  79. const handleSubmit = async () => {
  80. if (submitAction === Action.REDIRECT_SIGNUP) {
  81. window.location.href = routes.signup;
  82. return;
  83. }
  84. try {
  85. setLoading(true);
  86. if (submitAction === Action.CREATE_SUBSCRIPTION) {
  87. const response = await accountApi.createBillingSubscription(newTierCode, interval);
  88. window.location.href = response.redirect_url;
  89. } else if (submitAction === Action.UPDATE_SUBSCRIPTION) {
  90. await accountApi.updateBillingSubscription(newTierCode, interval);
  91. } else if (submitAction === Action.CANCEL_SUBSCRIPTION) {
  92. await accountApi.deleteBillingSubscription();
  93. }
  94. props.onCancel();
  95. } catch (e) {
  96. console.log(`[UpgradeDialog] Error changing billing subscription`, e);
  97. if (e instanceof UnauthorizedError) {
  98. session.resetAndRedirect(routes.login);
  99. } else {
  100. setError(e.message);
  101. }
  102. } finally {
  103. setLoading(false);
  104. }
  105. }
  106. // Figure out discount
  107. let discount = 0, upto = false;
  108. if (newTier?.prices) {
  109. discount = Math.round(((newTier.prices.month*12/newTier.prices.year)-1)*100);
  110. } else {
  111. let n = 0;
  112. for (const t of tiers) {
  113. if (t.prices) {
  114. const tierDiscount = Math.round(((t.prices.month*12/t.prices.year)-1)*100);
  115. if (tierDiscount > discount) {
  116. discount = tierDiscount;
  117. n++;
  118. }
  119. }
  120. }
  121. upto = n > 1;
  122. }
  123. return (
  124. <Dialog
  125. open={props.open}
  126. onClose={props.onCancel}
  127. maxWidth="lg"
  128. fullScreen={fullScreen}
  129. >
  130. <DialogTitle>
  131. <div style={{ display: "flex", flexDirection: "row" }}>
  132. <div style={{ flexGrow: 1 }}>{t("account_upgrade_dialog_title")}</div>
  133. <div style={{
  134. display: "flex",
  135. flexDirection: "row",
  136. alignItems: "center",
  137. marginTop: "4px"
  138. }}>
  139. <Typography component="span" variant="subtitle1">{t("account_upgrade_dialog_interval_monthly")}</Typography>
  140. <Switch
  141. checked={interval === SubscriptionInterval.YEAR}
  142. onChange={(ev) => setInterval(ev.target.checked ? SubscriptionInterval.YEAR : SubscriptionInterval.MONTH)}
  143. />
  144. <Typography component="span" variant="subtitle1">{t("account_upgrade_dialog_interval_yearly")}</Typography>
  145. {discount > 0 &&
  146. <Chip
  147. label={upto ? t("account_upgrade_dialog_interval_yearly_discount_save_up_to", { discount: discount }) : t("account_upgrade_dialog_interval_yearly_discount_save", { discount: discount })}
  148. color="primary"
  149. size="small"
  150. variant={interval === SubscriptionInterval.YEAR ? "filled" : "outlined"}
  151. sx={{ marginLeft: "5px" }}
  152. />
  153. }
  154. </div>
  155. </div>
  156. </DialogTitle>
  157. <DialogContent>
  158. <div style={{
  159. display: "flex",
  160. flexDirection: "row",
  161. marginBottom: "8px",
  162. width: "100%"
  163. }}>
  164. {tiers.map(tier =>
  165. <TierCard
  166. key={`tierCard${tier.code || '_free'}`}
  167. tier={tier}
  168. current={currentTierCode === tier.code} // tier.code or currentTierCode may be undefined!
  169. selected={newTierCode === tier.code} // tier.code may be undefined!
  170. interval={interval}
  171. onClick={() => setNewTierCode(tier.code)} // tier.code may be undefined!
  172. />
  173. )}
  174. </div>
  175. {banner === Banner.CANCEL_WARNING &&
  176. <Alert severity="warning" sx={{ fontSize: "1rem" }}>
  177. <Trans
  178. i18nKey="account_upgrade_dialog_cancel_warning"
  179. values={{ date: formatShortDate(account?.billing?.paid_until || 0) }} />
  180. </Alert>
  181. }
  182. {banner === Banner.PRORATION_INFO &&
  183. <Alert severity="info" sx={{ fontSize: "1rem" }}>
  184. <Trans i18nKey="account_upgrade_dialog_proration_info" />
  185. </Alert>
  186. }
  187. {banner === Banner.RESERVATIONS_WARNING &&
  188. <Alert severity="warning" sx={{ fontSize: "1rem" }}>
  189. <Trans
  190. i18nKey="account_upgrade_dialog_reservations_warning"
  191. count={account?.reservations.length - newTier?.limits.reservations}
  192. components={{
  193. Link: <NavLink to={routes.settings}/>,
  194. }}
  195. />
  196. </Alert>
  197. }
  198. </DialogContent>
  199. <Box sx={{
  200. display: 'flex',
  201. flexDirection: 'row',
  202. justifyContent: 'space-between',
  203. paddingLeft: '24px',
  204. paddingBottom: '8px',
  205. }}>
  206. <DialogContentText
  207. component="div"
  208. aria-live="polite"
  209. sx={{
  210. margin: '0px',
  211. paddingTop: '12px',
  212. paddingBottom: '4px'
  213. }}
  214. >
  215. {config.billing_contact.indexOf('@') !== -1 &&
  216. <><Trans i18nKey="account_upgrade_dialog_billing_contact_email" components={{ Link: <Link href={`mailto:${config.billing_contact}`}/> }}/>{" "}</>
  217. }
  218. {config.billing_contact.match(`^http?s://`) &&
  219. <><Trans i18nKey="account_upgrade_dialog_billing_contact_website" components={{ Link: <Link href={config.billing_contact} target="_blank"/> }}/>{" "}</>
  220. }
  221. {error}
  222. </DialogContentText>
  223. <DialogActions sx={{paddingRight: 2}}>
  224. <Button onClick={props.onCancel}>{t("account_upgrade_dialog_button_cancel")}</Button>
  225. <Button onClick={handleSubmit} disabled={!submitAction}>{submitButtonLabel}</Button>
  226. </DialogActions>
  227. </Box>
  228. </Dialog>
  229. );
  230. };
  231. const TierCard = (props) => {
  232. const { t } = useTranslation();
  233. const tier = props.tier;
  234. let cardStyle, labelStyle, labelText;
  235. if (props.selected) {
  236. cardStyle = { background: "#eee", border: "3px solid #338574" };
  237. labelStyle = { background: "#338574", color: "white" };
  238. labelText = t("account_upgrade_dialog_tier_selected_label");
  239. } else if (props.current) {
  240. cardStyle = { border: "3px solid #eee" };
  241. labelStyle = { background: "#eee", color: "black" };
  242. labelText = t("account_upgrade_dialog_tier_current_label");
  243. } else {
  244. cardStyle = { border: "3px solid transparent" };
  245. }
  246. let monthlyPrice;
  247. if (!tier.prices) {
  248. monthlyPrice = 0;
  249. } else if (props.interval === SubscriptionInterval.YEAR) {
  250. monthlyPrice = tier.prices.year/12;
  251. } else if (props.interval === SubscriptionInterval.MONTH) {
  252. monthlyPrice = tier.prices.month;
  253. }
  254. return (
  255. <Box sx={{
  256. m: "7px",
  257. minWidth: "240px",
  258. flexGrow: 1,
  259. flexShrink: 1,
  260. flexBasis: 0,
  261. borderRadius: "5px",
  262. "&:first-of-type": { ml: 0 },
  263. "&:last-of-type": { mr: 0 },
  264. ...cardStyle
  265. }}>
  266. <Card sx={{ height: "100%" }}>
  267. <CardActionArea sx={{ height: "100%" }}>
  268. <CardContent onClick={props.onClick} sx={{ height: "100%" }}>
  269. {labelStyle &&
  270. <div style={{
  271. position: "absolute",
  272. top: "0",
  273. right: "15px",
  274. padding: "2px 10px",
  275. borderRadius: "3px",
  276. ...labelStyle
  277. }}>{labelText}</div>
  278. }
  279. <Typography variant="subtitle1" component="div">
  280. {tier.name || t("account_basics_tier_free")}
  281. </Typography>
  282. <div>
  283. <Typography component="span" variant="h4" sx={{ fontWeight: 500, marginRight: "3px" }}>{formatPrice(monthlyPrice)}</Typography>
  284. {monthlyPrice > 0 && <>/ {t("account_upgrade_dialog_tier_price_per_month")}</>}
  285. </div>
  286. <List dense>
  287. {tier.limits.reservations > 0 && <Feature>{t("account_upgrade_dialog_tier_features_reservations", { reservations: tier.limits.reservations })}</Feature>}
  288. {tier.limits.reservations === 0 && <NoFeature>{t("account_upgrade_dialog_tier_features_no_reservations")}</NoFeature>}
  289. <Feature>{t("account_upgrade_dialog_tier_features_messages", { messages: formatNumber(tier.limits.messages) })}</Feature>
  290. <Feature>{t("account_upgrade_dialog_tier_features_emails", { emails: formatNumber(tier.limits.emails) })}</Feature>
  291. <Feature>{t("account_upgrade_dialog_tier_features_attachment_file_size", { filesize: formatBytes(tier.limits.attachment_file_size, 0) })}</Feature>
  292. <Feature>{t("account_upgrade_dialog_tier_features_attachment_total_size", { totalsize: formatBytes(tier.limits.attachment_total_size, 0) })}</Feature>
  293. </List>
  294. {tier.prices && props.interval === SubscriptionInterval.MONTH &&
  295. <Typography variant="body2" color="gray">
  296. {t("account_upgrade_dialog_tier_price_billed_monthly", { price: formatPrice(tier.prices.month*12) })}
  297. </Typography>
  298. }
  299. {tier.prices && props.interval === SubscriptionInterval.YEAR &&
  300. <Typography variant="body2" color="gray">
  301. {t("account_upgrade_dialog_tier_price_billed_yearly", { price: formatPrice(tier.prices.year), save: formatPrice(tier.prices.month*12-tier.prices.year) })}
  302. </Typography>
  303. }
  304. </CardContent>
  305. </CardActionArea>
  306. </Card>
  307. </Box>
  308. );
  309. }
  310. const Feature = (props) => {
  311. return <FeatureItem feature={true}>{props.children}</FeatureItem>;
  312. }
  313. const NoFeature = (props) => {
  314. return <FeatureItem feature={false}>{props.children}</FeatureItem>;
  315. }
  316. const FeatureItem = (props) => {
  317. return (
  318. <ListItem disableGutters sx={{m: 0, p: 0}}>
  319. <ListItemIcon sx={{minWidth: "24px"}}>
  320. {props.feature && <Check fontSize="small" sx={{ color: "#338574" }}/>}
  321. {!props.feature && <Close fontSize="small" sx={{ color: "gray" }}/>}
  322. </ListItemIcon>
  323. <ListItemText
  324. sx={{mt: "2px", mb: "2px"}}
  325. primary={
  326. <Typography variant="body1">
  327. {props.children}
  328. </Typography>
  329. }
  330. />
  331. </ListItem>
  332. );
  333. };
  334. const Action = {
  335. REDIRECT_SIGNUP: 1,
  336. CREATE_SUBSCRIPTION: 2,
  337. UPDATE_SUBSCRIPTION: 3,
  338. CANCEL_SUBSCRIPTION: 4
  339. };
  340. const Banner = {
  341. CANCEL_WARNING: 1,
  342. PRORATION_INFO: 2,
  343. RESERVATIONS_WARNING: 3
  344. };
  345. export default UpgradeDialog;