Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

feat(ReferralSettings):adding-referral-functionality-to-web

Aswin Asok85fa5917fb3d
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 2ebbd629f3..63a34cdb26 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -74,6 +74,7 @@ import { DropdownInput } from "ente-new/photos/components/DropdownInput";
import { ShapeIcon } from "ente-new/photos/components/icons/ShapeIcon";
import { AppLockSettings } from "ente-new/photos/components/sidebar/AppLockSettings";
import { MLSettings } from "ente-new/photos/components/sidebar/MLSettings";
+import { ReferralSettings } from "ente-new/photos/components/sidebar/ReferralSettings";
import { SessionsSettings } from "ente-new/photos/components/sidebar/SessionsSettings";
import { TwoFactorSettings } from "ente-new/photos/components/sidebar/TwoFactorSettings";
import { downloadAppDialogAttributes } from "ente-new/photos/components/utils/download";
@@ -261,6 +262,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
const { show: showHelp, props: helpVisibilityProps } = useModalVisibility();
const { show: showAccount, props: accountVisibilityProps } =
useModalVisibility();
+ const { show: showReferrals, props: referralsVisibilityProps } =
+ useModalVisibility();
const { show: showPreferences, props: preferencesVisibilityProps } =
useModalVisibility();
const { show: showFreeUpSpace, props: freeUpSpaceVisibilityProps } =
@@ -323,6 +326,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
onShowCollectionSummary,
onShowPlanSelector,
showAccount,
+ showReferrals,
showPreferences,
showHelp,
showFreeUpSpace,
@@ -359,6 +363,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
showFreeUpSpace,
showHelp,
showPreferences,
+ showReferrals,
uncategorizedCollectionSummaryID,
],
);
@@ -407,6 +412,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
onShowPlanSelector,
showAccount,
accountVisibilityProps,
+ showReferrals,
+ referralsVisibilityProps,
showPreferences,
preferencesVisibilityProps,
showHelp,
@@ -806,6 +813,8 @@ type UtilitySectionProps = SectionProps &
> & {
showAccount: () => void;
accountVisibilityProps: ModalVisibilityProps;
+ showReferrals: () => void;
+ referralsVisibilityProps: ModalVisibilityProps;
showPreferences: () => void;
preferencesVisibilityProps: ModalVisibilityProps;
showHelp: () => void;
@@ -832,6 +841,8 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
onShowPlanSelector,
showAccount,
accountVisibilityProps,
+ showReferrals,
+ referralsVisibilityProps,
showPreferences,
preferencesVisibilityProps,
showHelp,
@@ -857,6 +868,11 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
label={t("account")}
onClick={showAccount}
/>
+ <RowButton
+ variant="secondary"
+ label={t("referrals")}
+ onClick={showReferrals}
+ />
{isDesktop && (
<RowButton
variant="secondary"
@@ -908,6 +924,10 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
onActionHandled={onAccountActionHandled}
{...{ onAuthenticateUser, onShowPlanSelector }}
/>
+ <ReferralSettings
+ {...referralsVisibilityProps}
+ onRootClose={onCloseSidebar}
+ />
<Preferences
{...preferencesVisibilityProps}
onRootClose={onCloseSidebar}
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index c68054bca6..073858b096 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -257,6 +257,43 @@
"password_changed_elsewhere_message": "Please login again on this device to use your new password to authenticate.",
"go_back": "Go back",
"account": "Account",
+ "referrals": "Referrals",
+ "earn_free_storage": "Earn free storage",
+ "share_code_earn_storage": "Share your code, earn storage.",
+ "referral_step_1": "Customize and share your code.",
+ "referral_step_2": "They sign up for Ente using your code.",
+ "referral_step_3": "{{storageInGB}} GB free for them + {{storageInGB}} GB free for you when they upgrade.",
+ "referrals_paused": "Referrals are currently paused",
+ "referral_fetch_failed": "Unable to fetch referral details. Please try again later.",
+ "change_code": "Change your code",
+ "referral_code_change_hint": "You can customize this code up to 3 times",
+ "referral_code_changes_remaining_one": "You can customize this code 1 more time",
+ "referral_code_changes_remaining_other": "You can customize this code {{count}} more times",
+ "referral_code_invalid": "Code must be 4 to 20 characters, using only letters and numbers",
+ "code_unavailable": "Sorry, this code is unavailable.",
+ "code_change_limit_reached": "Sorry, you have reached the limit of code changes.",
+ "referral_code_change_family_admin_only": "Please contact {{familyAdminEmail}} to change your code.",
+ "apply_code": "Apply code",
+ "apply_code_description": "Enter the code provided by your friend to claim free storage for both of you",
+ "enter_referral_code": "Enter referral code",
+ "invalid_code": "Invalid code",
+ "apply_code_failed": "Failed to apply code",
+ "code_apply_not_eligible": "This account is not eligible to apply a referral code.",
+ "code_already_applied": "You have already applied a referral code.",
+ "code_applied": "Code applied",
+ "referral_applied_refresh_failed": "Your code was applied, but the latest referral details could not be loaded.",
+ "referral_storage_claimed": "{{storageAmountInGB}} GB claimed!",
+ "earn_more_space": "Earn more space!",
+ "referral_storage_for_both": "{{storageAmountInGB}} GB for them + {{storageAmountInGB}} GB for you when they upgrade.",
+ "share_invite": "Share invite",
+ "invite_copied": "Invite copied",
+ "referral_share_text": "Ente Photos is a private and safe home for your photos\n* Download Ente Photos from https://ente.com/app\n* Create an account\n* Apply the referral code {{referralCode}} in Settings -> Referrals\n* Get extra {{referralStorageInGB}} GB free!",
+ "referral_used_your_code": "Used your code",
+ "referral_eligible": "Eligible",
+ "referral_claimed_by_you": "Claimed by you",
+ "referral_earned": "Earned",
+ "referral_usable": "Usable",
+ "referral_usable_info": "Referrals from paid subscribers earn bonus storage.\n\nYou can use storage up to your plan limit. Upgrade to use the rest of your earned storage.",
"recovery_key": "Recovery key",
"do_this_later": "Do this later",
"save_key": "Save Key",
diff --git a/web/packages/new/photos/components/sidebar/ReferralSettings.tsx b/web/packages/new/photos/components/sidebar/ReferralSettings.tsx
new file mode 100644
index 0000000000..3c85cc0d7a
--- /dev/null
+++ b/web/packages/new/photos/components/sidebar/ReferralSettings.tsx
@@ -0,0 +1,834 @@
+import CheckCircleOutlinedIcon from "@mui/icons-material/CheckCircleOutlined";
+import EditIcon from "@mui/icons-material/Edit";
+import { Box, Button, IconButton, Stack, Typography } from "@mui/material";
+import { TitledMiniDialog } from "ente-base/components/MiniDialog";
+import {
+ RowButton,
+ RowButtonDivider,
+ RowButtonGroup,
+} from "ente-base/components/RowButton";
+import {
+ SingleInputForm,
+ type SingleInputFormProps,
+} from "ente-base/components/SingleInputForm";
+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
+import {
+ TitledNestedSidebarDrawer,
+ type NestedSidebarDrawerVisibilityProps,
+} from "ente-base/components/mui/SidebarDrawer";
+import { useModalVisibility } from "ente-base/components/utils/modal";
+import { useBaseContext } from "ente-base/context";
+import {
+ isHTTP4xxError,
+ isHTTPErrorWithStatus,
+ isMuseumHTTPError,
+} from "ente-base/http";
+import log from "ente-base/log";
+import { bytesInGB } from "ente-gallery/utils/units";
+import { useUserDetailsSnapshot } from "ente-new/photos/components/utils/use-snapshot";
+import {
+ changeReferralCode,
+ claimReferralCode,
+ getReferralView,
+ getStorageBonusDetails,
+ normalizeReferralCode,
+ type ReferralView,
+ type StorageBonusDetails,
+} from "ente-new/photos/services/storage-bonus";
+import {
+ familyAdminEmail,
+ isPartOfFamily,
+ pullUserDetails,
+ userDetailsAddOnBonuses,
+ userDetailsSnapshot,
+ type UserDetails,
+} from "ente-new/photos/services/user-details";
+import { openURL } from "ente-new/photos/utils/web";
+import { t } from "i18next";
+import React, { useCallback, useEffect, useRef, useState } from "react";
+
+type ReferralScreen =
+ | "main"
+ | "apply-refreshing"
+ | "apply-refresh-error"
+ | "success"
+ | "details";
+
+type Loadable<T> =
+ | { status: "loading" }
+ | { status: "error" }
+ | { status: "loaded"; value: T };
+
+const referralFAQURL =
+ "https://ente.com/help/photos/features/account/referral-program/";
+const isValidReferralCode = (code: string) => /^[A-Z0-9]{4,20}$/.test(code);
+
+export const ReferralSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
+ open,
+ onClose,
+ onRootClose,
+}) => {
+ const { showMiniDialog } = useBaseContext();
+ const userDetails = useUserDetailsSnapshot();
+ const {
+ show: showEditCodeDialog,
+ props: { open: isEditCodeDialogOpen, onClose: closeEditCodeDialog },
+ } = useModalVisibility();
+ const {
+ show: showApplyCodeDialog,
+ props: { open: isApplyCodeDialogOpen, onClose: closeApplyCodeDialog },
+ } = useModalVisibility();
+ const [screen, setScreen] = useState<ReferralScreen>("main");
+ const [referralView, setReferralView] = useState<Loadable<ReferralView>>({
+ status: "loading",
+ });
+ const [bonusDetails, setBonusDetails] = useState<
+ Loadable<StorageBonusDetails>
+ >({ status: "loading" });
+ const requestNonce = useRef(0);
+ const invalidateFetches = useCallback(() => {
+ requestNonce.current++;
+ }, []);
+
+ const fetchReferralView = useCallback(async (showLoading: boolean) => {
+ const nonce = ++requestNonce.current;
+ if (showLoading) setReferralView({ status: "loading" });
+
+ try {
+ const [view] = await Promise.all([
+ getReferralView(),
+ userDetailsSnapshot() ? Promise.resolve() : pullUserDetails(),
+ ]);
+ if (requestNonce.current != nonce) return;
+ setReferralView({ status: "loaded", value: view });
+ } catch (e) {
+ if (requestNonce.current != nonce) return;
+ log.error("Failed to fetch referral details", e);
+ setReferralView({ status: "error" });
+ throw e;
+ }
+ }, []);
+
+ const loadReferralView = useCallback(() => {
+ void fetchReferralView(true).catch(() => undefined);
+ }, [fetchReferralView]);
+
+ const handleCodeChanged = useCallback(async () => {
+ try {
+ await fetchReferralView(false);
+ } catch (e) {
+ closeEditCodeDialog();
+ setReferralView({ status: "error" });
+ throw e;
+ }
+ }, [closeEditCodeDialog, fetchReferralView]);
+
+ const loadBonusDetails = useCallback(() => {
+ const nonce = ++requestNonce.current;
+ setBonusDetails({ status: "loading" });
+
+ void (async () => {
+ try {
+ const details = await getStorageBonusDetails();
+ if (requestNonce.current != nonce) return;
+ setBonusDetails({ status: "loaded", value: details });
+ } catch (e) {
+ if (requestNonce.current != nonce) return;
+ log.error("Failed to fetch storage bonus details", e);
+ setBonusDetails({ status: "error" });
+ }
+ })();
+ }, []);
+
+ useEffect(() => {
+ if (!open) {
+ closeEditCodeDialog();
+ closeApplyCodeDialog();
+ return;
+ }
+
+ setScreen("main");
+ closeEditCodeDialog();
+ closeApplyCodeDialog();
+ loadReferralView();
+
+ return invalidateFetches;
+ }, [
+ open,
+ loadReferralView,
+ invalidateFetches,
+ closeEditCodeDialog,
+ closeApplyCodeDialog,
+ ]);
+
+ const handleClose = () => {
+ invalidateFetches();
+ closeEditCodeDialog();
+ closeApplyCodeDialog();
+ if (screen != "main") {
+ setScreen("main");
+ } else {
+ onClose();
+ }
+ };
+
+ const handleRootClose = () => {
+ invalidateFetches();
+ closeEditCodeDialog();
+ closeApplyCodeDialog();
+ onClose();
+ onRootClose();
+ };
+
+ const showDetails = () => {
+ setScreen("details");
+ loadBonusDetails();
+ };
+
+ const handleEditCode = () => {
+ if (referralView.status != "loaded" || !userDetails) return;
+
+ if (referralView.value.isFamilyMember) {
+ showMiniDialog({
+ message: t("referral_code_change_family_admin_only", {
+ familyAdminEmail: familyAdminEmail(userDetails) ?? "",
+ }),
+ cancel: t("ok"),
+ });
+ } else {
+ showEditCodeDialog();
+ }
+ };
+
+ const handleCodeApplied = useCallback(async () => {
+ const nonce = ++requestNonce.current;
+ closeApplyCodeDialog();
+ setScreen("apply-refreshing");
+
+ try {
+ const [view, details] = await Promise.all([
+ getReferralView(),
+ getStorageBonusDetails(),
+ pullUserDetails(),
+ ]);
+ if (requestNonce.current != nonce) return;
+
+ setReferralView({ status: "loaded", value: view });
+ setBonusDetails({ status: "loaded", value: details });
+ setScreen("success");
+ } catch (e) {
+ if (requestNonce.current != nonce) return;
+
+ log.error(
+ "Failed to refresh referral details after applying a code",
+ e,
+ );
+ setScreen("apply-refresh-error");
+ }
+ }, [closeApplyCodeDialog]);
+
+ let contents: React.ReactNode;
+ if (referralView.status == "loading") {
+ contents = <Loading />;
+ } else if (referralView.status == "error") {
+ contents = <LoadError onRetry={loadReferralView} />;
+ } else if (!userDetails) {
+ contents = <Loading />;
+ } else if (screen == "apply-refreshing") {
+ contents = <Loading />;
+ } else if (screen == "apply-refresh-error") {
+ contents = (
+ <LoadError
+ message={t("referral_applied_refresh_failed")}
+ onRetry={() => void handleCodeApplied()}
+ />
+ );
+ } else if (screen == "details") {
+ contents = (
+ <DetailsContents
+ referralView={referralView.value}
+ {...{ userDetails, bonusDetails }}
+ onRetry={loadBonusDetails}
+ />
+ );
+ } else if (screen == "success") {
+ contents = (
+ <SuccessContents
+ referralView={referralView.value}
+ onShowDetails={() => setScreen("details")}
+ />
+ );
+ } else {
+ contents = (
+ <MainContents
+ referralView={referralView.value}
+ onShowDetails={showDetails}
+ onEditCode={handleEditCode}
+ onApplyCode={showApplyCodeDialog}
+ />
+ );
+ }
+
+ return (
+ <TitledNestedSidebarDrawer
+ {...{ open }}
+ onClose={handleClose}
+ onRootClose={handleRootClose}
+ title={t(
+ screen == "details"
+ ? "details"
+ : screen == "success"
+ ? "code_applied"
+ : "referrals",
+ )}
+ >
+ <Stack sx={{ px: 2, py: 1, gap: 3 }}>{contents}</Stack>
+ {isEditCodeDialogOpen && referralView.status == "loaded" && (
+ <EditCodeDialog
+ open={isEditCodeDialogOpen}
+ onClose={closeEditCodeDialog}
+ currentCode={referralView.value.code}
+ remainingCodeChangeAttempts={
+ referralView.value.remainingCodeChangeAttempts
+ }
+ onChanged={handleCodeChanged}
+ />
+ )}
+ {isApplyCodeDialogOpen && (
+ <ApplyCodeDialog
+ open={isApplyCodeDialogOpen}
+ onClose={closeApplyCodeDialog}
+ onApplied={handleCodeApplied}
+ onRefresh={() =>
+ void fetchReferralView(false).catch(() => undefined)
+ }
+ />
+ )}
+ </TitledNestedSidebarDrawer>
+ );
+};
+
+const Loading: React.FC = () => (
+ <Box sx={{ textAlign: "center", pt: 4 }}>
+ <ActivityIndicator />
+ </Box>
+);
+
+interface LoadErrorProps {
+ onRetry: () => void;
+ message?: string;
+}
+
+const LoadError: React.FC<LoadErrorProps> = ({ onRetry, message }) => (
+ <Stack sx={{ gap: 2, pt: 3 }}>
+ <Typography sx={{ color: "text.muted" }}>
+ {message ?? t("referral_fetch_failed")}
+ </Typography>
+ <Button fullWidth color="secondary" onClick={onRetry}>
+ {t("retry")}
+ </Button>
+ </Stack>
+);
+
+interface MainContentsProps {
+ referralView: ReferralView;
+ onShowDetails: () => void;
+ onEditCode: () => void;
+ onApplyCode: () => void;
+}
+
+const MainContents: React.FC<MainContentsProps> = ({
+ referralView,
+ onShowDetails,
+ onEditCode,
+ onApplyCode,
+}) => {
+ const { planInfo, code } = referralView;
+ const codeChangeHint =
+ referralView.remainingCodeChangeAttempts == undefined
+ ? t("referral_code_change_hint")
+ : t("referral_code_changes_remaining", {
+ count: referralView.remainingCodeChangeAttempts,
+ });
+
+ return (
+ <>
+ <Stack sx={{ gap: 0.5 }}>
+ <Typography variant="h5">{t("earn_free_storage")}</Typography>
+ <Typography sx={{ color: "text.muted" }}>
+ {t(
+ planInfo.isEnabled
+ ? "share_code_earn_storage"
+ : "referrals_paused",
+ )}
+ </Typography>
+ </Stack>
+ {planInfo.isEnabled && (
+ <>
+ <Stack sx={{ gap: 1 }}>
+ <ReferralCodeCard code={code} onEdit={onEditCode} />
+ <Typography
+ variant="small"
+ sx={{ px: 1, color: "text.muted" }}
+ >
+ {codeChangeHint}
+ </Typography>
+ </Stack>
+ <InviteShareButton
+ code={code}
+ storageInGB={planInfo.storageInGB}
+ />
+ <HowItWorks storageInGB={planInfo.storageInGB} />
+ </>
+ )}
+
+ <RowButtonGroup>
+ {referralView.enableApplyCode && (
+ <>
+ <RowButton
+ variant="secondary"
+ label={t("apply_code")}
+ onClick={onApplyCode}
+ />
+ <RowButtonDivider />
+ </>
+ )}
+ <RowButton
+ variant="secondary"
+ label={t("faq")}
+ onClick={() => openURL(referralFAQURL)}
+ />
+ <RowButtonDivider />
+ <RowButton
+ variant="secondary"
+ label={t("details")}
+ onClick={onShowDetails}
+ />
+ </RowButtonGroup>
+ </>
+ );
+};
+
+interface ReferralCodeCardProps {
+ code: string;
+ onEdit?: () => void;
+}
+
+const ReferralCodeCard: React.FC<ReferralCodeCardProps> = ({
+ code,
+ onEdit,
+}) => (
+ <Box
+ sx={{
+ position: "relative",
+ border: "1px dashed",
+ borderColor: "stroke.muted",
+ borderRadius: 2,
+ px: 2,
+ py: 3,
+ textAlign: "center",
+ }}
+ >
+ <Typography
+ variant="h3"
+ sx={{
+ letterSpacing: "0.08em",
+ overflowWrap: "anywhere",
+ ...(onEdit && { px: 6 }),
+ }}
+ >
+ {code}
+ </Typography>
+ {onEdit && (
+ <IconButton
+ aria-label={t("change_code")}
+ onClick={onEdit}
+ sx={{
+ position: "absolute",
+ top: "50%",
+ right: 4,
+ width: 48,
+ height: 48,
+ transform: "translateY(-50%)",
+ }}
+ >
+ <EditIcon />
+ </IconButton>
+ )}
+ </Box>
+);
+
+interface SuccessContentsProps {
+ referralView: ReferralView;
+ onShowDetails: () => void;
+}
+
+const SuccessContents: React.FC<SuccessContentsProps> = ({
+ referralView,
+ onShowDetails,
+}) => {
+ const { code, planInfo } = referralView;
+
+ return (
+ <>
+ <Stack
+ role="status"
+ aria-live="polite"
+ sx={{ alignItems: "center", gap: 1, pt: 2 }}
+ >
+ <CheckCircleOutlinedIcon
+ sx={{ color: "accent.main", fontSize: 72 }}
+ />
+ <Typography variant="h3" sx={{ textAlign: "center" }}>
+ {t("referral_storage_claimed", {
+ storageAmountInGB: planInfo.storageInGB,
+ })}
+ </Typography>
+ </Stack>
+ <RowButtonGroup>
+ <RowButton
+ variant="secondary"
+ label={t("details")}
+ onClick={onShowDetails}
+ />
+ </RowButtonGroup>
+ <Stack sx={{ gap: 2 }}>
+ <Typography variant="h5">{t("earn_more_space")}</Typography>
+ <ReferralCodeCard code={code} />
+ <Typography sx={{ color: "text.muted" }}>
+ {t("referral_storage_for_both", {
+ storageAmountInGB: planInfo.storageInGB,
+ })}
+ </Typography>
+ <InviteShareButton
+ code={code}
+ storageInGB={planInfo.storageInGB}
+ />
+ </Stack>
+ </>
+ );
+};
+
+interface EditCodeDialogProps {
+ open: boolean;
+ onClose: () => void;
+ currentCode: string;
+ remainingCodeChangeAttempts?: number;
+ onChanged: () => Promise<void>;
+}
+
+const EditCodeDialog: React.FC<EditCodeDialogProps> = ({
+ open,
+ onClose,
+ currentCode,
+ remainingCodeChangeAttempts,
+ onChanged,
+}) => {
+ const handleSubmit: SingleInputFormProps["onSubmit"] = async (
+ code,
+ setFieldError,
+ ) => {
+ const normalized = normalizeReferralCode(code);
+
+ if (normalized == normalizeReferralCode(currentCode)) {
+ onClose();
+ return;
+ }
+
+ if (!isValidReferralCode(normalized)) {
+ setFieldError(t("referral_code_invalid"));
+ return;
+ }
+ if (remainingCodeChangeAttempts === 0) {
+ setFieldError(t("code_change_limit_reached"));
+ return;
+ }
+
+ try {
+ await changeReferralCode(normalized);
+ await onChanged();
+ onClose();
+ } catch (e) {
+ log.error("Failed to change referral code", e);
+
+ const isUnavailable = await isMuseumHTTPError(
+ e,
+ 400,
+ "CODE_ALREADY_EXISTS",
+ );
+ const isChangeLimitReached = await isMuseumHTTPError(
+ e,
+ 429,
+ "REFERRAL_CHANGE_LIMIT_REACHED",
+ );
+
+ setFieldError(
+ isUnavailable || isHTTPErrorWithStatus(e, 400)
+ ? t("code_unavailable")
+ : isChangeLimitReached
+ ? t("code_change_limit_reached")
+ : t("generic_error"),
+ );
+ }
+ };
+
+ return (
+ <TitledMiniDialog {...{ open, onClose }} title={t("change_code")}>
+ <SingleInputForm
+ initialValue={currentCode}
+ label={t("enter_referral_code")}
+ submitButtonTitle={t("save")}
+ onCancel={onClose}
+ onSubmit={handleSubmit}
+ />
+ </TitledMiniDialog>
+ );
+};
+
+interface ApplyCodeDialogProps {
+ open: boolean;
+ onClose: () => void;
+ onApplied: () => Promise<void>;
+ onRefresh: () => void;
+}
+
+const ApplyCodeDialog: React.FC<ApplyCodeDialogProps> = ({
+ open,
+ onClose,
+ onApplied,
+ onRefresh,
+}) => {
+ const handleSubmit: SingleInputFormProps["onSubmit"] = async (
+ code,
+ setFieldError,
+ ) => {
+ const normalized = normalizeReferralCode(code);
+ if (normalized.length < 4) {
+ setFieldError(t("invalid_code"));
+ return;
+ }
+
+ try {
+ await claimReferralCode(normalized);
+ await onApplied();
+ } catch (e) {
+ log.error("Failed to apply referral code", e);
+
+ const isInvalidCode = await isMuseumHTTPError(
+ e,
+ 404,
+ "INVALID_CODE",
+ );
+ const isNotEligible = await isMuseumHTTPError(
+ e,
+ 400,
+ "ACCOUNT_NOT_ELIGIBLE",
+ );
+ const isAlreadyApplied = await isMuseumHTTPError(
+ e,
+ 409,
+ "CODE_ALREADY_APPLIED",
+ );
+
+ if (isNotEligible || isAlreadyApplied) onRefresh();
+ setFieldError(
+ isInvalidCode
+ ? t("invalid_code")
+ : isNotEligible
+ ? t("code_apply_not_eligible")
+ : isAlreadyApplied
+ ? t("code_already_applied")
+ : isHTTP4xxError(e)
+ ? t("apply_code_failed")
+ : t("generic_error"),
+ );
+ }
+ };
+
+ return (
+ <TitledMiniDialog {...{ open, onClose }} title={t("apply_code")}>
+ <Stack sx={{ gap: 1 }}>
+ <Typography
+ id="referral-code-apply-description"
+ sx={{ color: "text.muted" }}
+ >
+ {t("apply_code_description")}
+ </Typography>
+ <SingleInputForm
+ label={t("enter_referral_code")}
+ slotProps={{
+ htmlInput: {
+ "aria-describedby":
+ "referral-code-apply-description",
+ style: { textTransform: "uppercase" },
+ },
+ }}
+ submitButtonTitle={t("apply_code")}
+ onCancel={onClose}
+ onSubmit={handleSubmit}
+ />
+ </Stack>
+ </TitledMiniDialog>
+ );
+};
+
+interface InviteShareButtonProps {
+ code: string;
+ storageInGB: number;
+}
+
+const InviteShareButton: React.FC<InviteShareButtonProps> = ({
+ code,
+ storageInGB,
+}) => {
+ const { onGenericError } = useBaseContext();
+ const [copied, setCopied] = useState(false);
+ const copiedTimeout = useRef<ReturnType<typeof setTimeout> | undefined>(
+ undefined,
+ );
+
+ useEffect(
+ () => () => {
+ if (copiedTimeout.current) clearTimeout(copiedTimeout.current);
+ },
+ [],
+ );
+
+ const handleShare = async () => {
+ const text = t("referral_share_text", {
+ referralCode: code,
+ referralStorageInGB: storageInGB,
+ });
+
+ if (typeof navigator.share == "function") {
+ try {
+ await navigator.share({ text });
+ } catch (e) {
+ if ((e as Error).name == "AbortError") return;
+ log.error("Failed to share referral invite", e);
+ onGenericError(e);
+ }
+ return;
+ }
+
+ try {
+ await navigator.clipboard.writeText(text);
+ setCopied(true);
+ if (copiedTimeout.current) clearTimeout(copiedTimeout.current);
+ copiedTimeout.current = setTimeout(() => setCopied(false), 2000);
+ } catch (e) {
+ onGenericError(e);
+ }
+ };
+
+ return (
+ <Button fullWidth color="accent" onClick={() => void handleShare()}>
+ <span aria-live="polite">
+ {t(copied ? "invite_copied" : "share_invite")}
+ </span>
+ </Button>
+ );
+};
+
+const HowItWorks: React.FC<{ storageInGB: number }> = ({ storageInGB }) => (
+ <Box
+ component="ol"
+ sx={{ m: 0, pl: 3, color: "text.muted", display: "grid", gap: 1.5 }}
+ >
+ {[
+ t("referral_step_1"),
+ t("referral_step_2"),
+ t("referral_step_3", { storageInGB }),
+ ].map((step) => (
+ <Typography component="li" key={step}>
+ {step}
+ </Typography>
+ ))}
+ </Box>
+);
+
+interface DetailsContentsProps {
+ referralView: ReferralView;
+ userDetails: UserDetails;
+ bonusDetails: Loadable<StorageBonusDetails>;
+ onRetry: () => void;
+}
+
+const DetailsContents: React.FC<DetailsContentsProps> = ({
+ referralView,
+ userDetails,
+ bonusDetails,
+ onRetry,
+}) => {
+ if (bonusDetails.status == "loading") return <Loading />;
+ if (bonusDetails.status == "error") return <LoadError {...{ onRetry }} />;
+
+ const details = bonusDetails.value;
+ const addOnStorage = userDetailsAddOnBonuses(userDetails).reduce(
+ (sum, bonus) => sum + bonus.storage,
+ 0,
+ );
+ const planStorage = isPartOfFamily(userDetails)
+ ? (userDetails.familyData?.storage ?? 0)
+ : userDetails.subscription.storage;
+ const usableStorage = Math.min(
+ referralView.claimedStorage,
+ planStorage + addOnStorage,
+ );
+ const formatStorage = (storage: number) =>
+ `${bytesInGB(storage)} ${t("storage_unit.gb")}`;
+
+ const stats = [
+ {
+ label: t("referral_used_your_code"),
+ value: String(details.refCount),
+ },
+ {
+ label: t("referral_eligible"),
+ value: String(details.refUpgradeCount),
+ },
+ ...(details.hasAppliedCode
+ ? [{ label: t("referral_claimed_by_you"), value: "1" }]
+ : []),
+ {
+ label: t("referral_earned"),
+ value: formatStorage(referralView.claimedStorage),
+ },
+ { label: t("referral_usable"), value: formatStorage(usableStorage) },
+ ];
+
+ return (
+ <>
+ <Stack
+ divider={<RowButtonDivider />}
+ sx={{ bgcolor: "fill.faint", borderRadius: 2 }}
+ >
+ {stats.map(({ label, value }) => (
+ <Stack
+ key={label}
+ direction="row"
+ aria-label={`${label}: ${value}`}
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 2,
+ px: 2,
+ py: 1.75,
+ }}
+ >
+ <Typography>{label}</Typography>
+ <Typography sx={{ fontWeight: "medium" }}>
+ {value}
+ </Typography>
+ </Stack>
+ ))}
+ </Stack>
+ <Typography
+ variant="small"
+ sx={{ color: "text.faint", whiteSpace: "pre-line" }}
+ >
+ {t("referral_usable_info")}
+ </Typography>
+ </>
+ );
+};
diff --git a/web/packages/new/photos/services/search/sidebar-search-registry.ts b/web/packages/new/photos/services/search/sidebar-search-registry.ts
index d2a9e74ce4..8b7251193b 100644
--- a/web/packages/new/photos/services/search/sidebar-search-registry.ts
+++ b/web/packages/new/photos/services/search/sidebar-search-registry.ts
@@ -21,6 +21,7 @@ export interface SidebarActionContext {
isHidden?: boolean,
) => Promise<void>;
showAccount: () => void;
+ showReferrals: () => void;
showPreferences: () => void;
showHelp: () => void;
showFreeUpSpace: () => void;
@@ -87,6 +88,18 @@ const sidebarActions = (): SidebarAction[] => {
path: [preferencesCategory, t("account")],
keywords: ["profile", "user"],
},
+ {
+ id: "utility.referrals",
+ label: t("referrals"),
+ path: [preferencesCategory, t("referrals")],
+ keywords: [
+ "referral",
+ "invite",
+ "code",
+ "free storage",
+ "earn storage",
+ ],
+ },
{
id: "utility.watchFolders",
label: t("watch_folders"),
@@ -342,6 +355,10 @@ export const performSidebarAction = async (
ctx.showAccount();
return Promise.resolve();
+ case "utility.referrals":
+ ctx.showReferrals();
+ return Promise.resolve();
+
case "utility.watchFolders":
ctx.onShowWatchFolder();
return Promise.resolve();
diff --git a/web/packages/new/photos/services/search/types.ts b/web/packages/new/photos/services/search/types.ts
index 9863d1ab86..81c3f2ac5e 100644
--- a/web/packages/new/photos/services/search/types.ts
+++ b/web/packages/new/photos/services/search/types.ts
@@ -29,6 +29,7 @@ export type SidebarActionID =
| "shortcuts.hidden"
| "shortcuts.trash"
| "utility.account"
+ | "utility.referrals"
| "utility.watchFolders"
| "utility.freeUpSpace"
| "utility.preferences"
diff --git a/web/packages/new/photos/services/storage-bonus.ts b/web/packages/new/photos/services/storage-bonus.ts
new file mode 100644
index 0000000000..d75c6e30fb
--- /dev/null
+++ b/web/packages/new/photos/services/storage-bonus.ts
@@ -0,0 +1,91 @@
+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
+import { apiURL } from "ente-base/origins";
+import { z } from "zod";
+
+const ReferralView = z.object({
+ planInfo: z.object({ isEnabled: z.boolean(), storageInGB: z.number() }),
+ code: z.string(),
+ enableApplyCode: z.boolean(),
+ /**
+ * `true` iff the user is a non-admin family member; the referral owner is
+ * then the family admin.
+ */
+ isFamilyMember: z.boolean(),
+ /**
+ * Active REFERRAL + SIGN_UP bonus sum of the referral owner (in bytes).
+ */
+ claimedStorage: z.number(),
+ remainingCodeChangeAttempts: z.number().optional(),
+});
+
+/**
+ * Referral information for the currently logged in user.
+ */
+export type ReferralView = z.infer<typeof ReferralView>;
+
+// Remote also returns referralStats and bonuses arrays. They are not modelled
+// here; Zod strips the unknown keys.
+const StorageBonusDetails = z.object({
+ refCount: z.number(),
+ refUpgradeCount: z.number(),
+ hasAppliedCode: z.boolean(),
+});
+
+/**
+ * Aggregate referral bonus details for the currently logged in user.
+ */
+export type StorageBonusDetails = z.infer<typeof StorageBonusDetails>;
+
+export const normalizeReferralCode = (code: string) =>
+ code.trim().toUpperCase();
+
+/**
+ * Fetch the referral view for the currently logged in user from remote.
+ */
+export const getReferralView = async (): Promise<ReferralView> => {
+ const res = await fetch(await apiURL("/storage-bonus/referral-view"), {
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+ return ReferralView.parse(await res.json());
+};
+
+/**
+ * Fetch aggregate storage bonus details for the currently logged in user from
+ * remote.
+ */
+export const getStorageBonusDetails =
+ async (): Promise<StorageBonusDetails> => {
+ const res = await fetch(await apiURL("/storage-bonus/details"), {
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+ return StorageBonusDetails.parse(await res.json());
+ };
+
+/**
+ * Change the referral code for the currently logged in user.
+ */
+export const changeReferralCode = async (code: string): Promise<void> => {
+ ensureOk(
+ await fetch(await apiURL("/storage-bonus/change-code"), {
+ method: "POST",
+ headers: await authenticatedRequestHeaders(),
+ body: JSON.stringify({ code: normalizeReferralCode(code) }),
+ }),
+ );
+};
+
+/**
+ * Claim a referral code for the currently logged in user.
+ */
+export const claimReferralCode = async (code: string): Promise<void> => {
+ ensureOk(
+ await fetch(
+ await apiURL("/storage-bonus/referral-claim", {
+ code: normalizeReferralCode(code),
+ }),
+ { method: "POST", headers: await authenticatedRequestHeaders() },
+ ),
+ );
+};