UpgradeDialog.js 14 KB

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