Billing / plus frontend (#2130)

* [wip] initial

* [wip] subscriptions/plus frontend

* [wip] finish payment flow

* Charges page

* finish most subscriptions work

* Finish

* update eslint

* Fix issues

* fix intl extract

* fix omorphia locale extract

* fix responsiveness

* fix lint
This commit is contained in:
Geometrically
2024-08-15 23:21:30 -07:00
committed by GitHub
parent 1b3744baa2
commit 3a4843fb46
44 changed files with 2353 additions and 201 deletions

View File

@@ -116,6 +116,5 @@
.normal-page__content {
max-width: calc(60rem - 0.75rem);
overflow-x: hidden;
}
}

View File

@@ -2,10 +2,6 @@
display: none !important;
}
.w-100 {
width: 100%;
}
body {
overflow-y: scroll;
overflow-x: hidden;

View File

@@ -39,6 +39,16 @@ export const initAuth = async (oldToken = null) => {
authCookie.value = route.query.code;
}
if (route.fullPath.includes("new_account=true") && route.path !== "/auth/welcome") {
const redirect = route.path.startsWith("/auth/") ? null : route.fullPath;
await navigateTo(
`/auth/welcome?authToken=${route.query.code}${
redirect ? `&redirect=${encodeURIComponent(redirect)}` : ""
}`,
);
}
if (authCookie.value) {
auth.token = authCookie.value;

View File

@@ -0,0 +1,6 @@
export const useUserCountry = () =>
useState("userCountry", () => {
const headers = useRequestHeaders(["cf-ipcountry"]);
return headers["cf-ipcountry"] ?? "US";
});

View File

@@ -12,20 +12,27 @@ export const initUser = async () => {
const auth = (await useAuth()).value;
const user = {
notifications: [],
collections: [],
follows: [],
subscriptions: [],
lastUpdated: 0,
};
if (auth.user && auth.user.id) {
try {
const [follows, collections] = await Promise.all([
useBaseFetch(`user/${auth.user.id}/follows`),
useBaseFetch(`user/${auth.user.id}/collections`, { apiVersion: 3 }),
const headers = {
Authorization: auth.token,
};
const [follows, collections, subscriptions] = await Promise.all([
useBaseFetch(`user/${auth.user.id}/follows`, { headers }, true),
useBaseFetch(`user/${auth.user.id}/collections`, { apiVersion: 3, headers }, true),
useBaseFetch(`billing/subscriptions`, { internal: true, headers }, true),
]);
user.collections = collections;
user.follows = follows;
user.subscriptions = subscriptions;
user.lastUpdated = Date.now();
} catch (err) {
console.error(err);
@@ -170,6 +177,5 @@ export const logout = async () => {
await useAuth("none");
useCookie("auth-token").value = null;
await navigateTo("/");
stopLoading();
};

View File

@@ -18,6 +18,21 @@
</nuxt-link>
</template>
</div>
<div
v-if="
user &&
user.subscriptions &&
user.subscriptions.some((x) => x.status === 'payment-failed') &&
route.path !== '/settings/billing'
"
class="email-nag"
>
<span>{{ formatMessage(subscriptionPaymentFailedBannerMessages.title) }}</span>
<nuxt-link class="btn" to="/settings/billing">
<SettingsIcon />
{{ formatMessage(subscriptionPaymentFailedBannerMessages.action) }}
</nuxt-link>
</div>
<div
v-if="
config.public.apiBaseUrl.startsWith('https://staging-api.modrinth.com') &&
@@ -454,6 +469,12 @@ const { formatMessage } = useVIntl();
const app = useNuxtApp();
const auth = await useAuth();
const user = ref();
if (import.meta.client) {
user.value = await useUser();
}
const cosmetics = useCosmetics();
const flags = useFeatureFlags();
const tags = useTags();
@@ -484,6 +505,18 @@ const addEmailBannerMessages = defineMessages({
},
});
const subscriptionPaymentFailedBannerMessages = defineMessages({
title: {
id: "layout.banner.subscription-payment-failed.title",
defaultMessage:
"Your subscription failed to renew. Please update your payment method to prevent losing access.",
},
action: {
id: "layout.banner.subscription-payment-failed.button",
defaultMessage: "Update billing info",
},
});
const stagingBannerMessages = defineMessages({
title: {
id: "layout.banner.staging.title",

View File

@@ -368,6 +368,12 @@
"layout.banner.staging.title": {
"message": "Youre viewing Modrinths staging environment."
},
"layout.banner.subscription-payment-failed.button": {
"message": "Update billing info"
},
"layout.banner.subscription-payment-failed.title": {
"message": "Your subscription failed to renew. Please update your payment method to prevent losing access."
},
"layout.banner.verify-email.action": {
"message": "Re-send verification email"
},
@@ -788,6 +794,93 @@
"settings.authorized-apps.title": {
"message": "Authorized apps"
},
"settings.billing.modal.cancel.action": {
"message": "Cancel subscription"
},
"settings.billing.modal.cancel.description": {
"message": "This will cancel your subscription. You will retain your perks until the end of the current billing cycle."
},
"settings.billing.modal.cancel.title": {
"message": "Are you sure you want to cancel your subscription?"
},
"settings.billing.modal.delete.action": {
"message": "Remove this payment method"
},
"settings.billing.modal.delete.description": {
"message": "This will remove this payment method forever (like really forever)."
},
"settings.billing.modal.delete.title": {
"message": "Are you sure you want to remove this payment method?"
},
"settings.billing.payment_method.action.add": {
"message": "Add payment method"
},
"settings.billing.payment_method.action.history": {
"message": "View past charges"
},
"settings.billing.payment_method.action.primary": {
"message": "Make primary"
},
"settings.billing.payment_method.card_display": {
"message": "{card_brand} ending in {last_four}"
},
"settings.billing.payment_method.card_expiry": {
"message": "Expires {month}/{year}"
},
"settings.billing.payment_method.none": {
"message": "You have not added any payment methods."
},
"settings.billing.payment_method.primary": {
"message": "Primary"
},
"settings.billing.payment_method.title": {
"message": "Payment methods"
},
"settings.billing.payment_method_type.amazon_pay": {
"message": "Amazon Pay"
},
"settings.billing.payment_method_type.amex": {
"message": "American Express"
},
"settings.billing.payment_method_type.cashapp": {
"message": "Cash App"
},
"settings.billing.payment_method_type.diners": {
"message": "Diners Club"
},
"settings.billing.payment_method_type.discover": {
"message": "Discover"
},
"settings.billing.payment_method_type.eftpos": {
"message": "EFTPOS"
},
"settings.billing.payment_method_type.jcb": {
"message": "JCB"
},
"settings.billing.payment_method_type.mastercard": {
"message": "MasterCard"
},
"settings.billing.payment_method_type.paypal": {
"message": "PayPal"
},
"settings.billing.payment_method_type.unionpay": {
"message": "UnionPay"
},
"settings.billing.payment_method_type.unknown": {
"message": "Unknown payment method"
},
"settings.billing.payment_method_type.visa": {
"message": "Visa"
},
"settings.billing.subscription.description": {
"message": "Manage your Modrinth subscriptions."
},
"settings.billing.subscription.title": {
"message": "Subscriptions"
},
"settings.billing.title": {
"message": "Billing and subscriptions"
},
"settings.display.banner.developer-mode.button": {
"message": "Deactivate developer mode"
},
@@ -827,6 +920,9 @@
"settings.display.project-list-layouts.user": {
"message": "User profile pages"
},
"settings.display.project-list.layouts.collection": {
"message": "Collection"
},
"settings.display.sidebar.advanced-rendering.description": {
"message": "Enables advanced rendering such as blur effects that may cause performance issues without hardware-accelerated rendering."
},

View File

@@ -272,7 +272,7 @@
<hr class="card-divider" />
</div>
<div class="input-group">
<template v-if="auth.user">
<template v-if="auth.user && user && user.follows">
<button
v-if="!user.follows.find((x) => x.id === project.id)"
class="btn"
@@ -486,7 +486,12 @@
>our documentation</a
>.
</MessageBanner>
<Promotion v-if="tags.approvedStatuses.includes(project.status)" />
<Promotion
v-if="
tags.approvedStatuses.includes(project.status) &&
(!auth.user || !isPermission(auth.user.badges, 1 << 0))
"
/>
<div class="navigation-card">
<NavRow
:links="[
@@ -1128,7 +1133,11 @@ const route = useNativeRoute();
const config = useRuntimeConfig();
const auth = await useAuth();
const user = await useUser();
const user = ref();
if (import.meta.client) {
user.value = await useUser();
}
const cosmetics = useCosmetics();
const tags = useTags();
const flags = useFeatureFlags();

View File

@@ -181,13 +181,7 @@ const route = useNativeRoute();
const redirectTarget = route.query.redirect || "";
if (route.fullPath.includes("new_account=true")) {
await navigateTo(
`/auth/welcome?authToken=${route.query.code}${
route.query.redirect ? `&redirect=${encodeURIComponent(route.query.redirect)}` : ""
}`,
);
} else if (route.query.code) {
if (route.query.code && !route.fullPath.includes("new_account=true")) {
await finishSignIn();
}

View File

@@ -205,14 +205,6 @@ const route = useNativeRoute();
const redirectTarget = route.query.redirect;
if (route.fullPath.includes("new_account=true")) {
await navigateTo(
`/auth/welcome?authToken=${route.query.code}${
route.query.redirect ? `&redirect=${encodeURIComponent(route.query.redirect)}` : ""
}`,
);
}
if (auth.value.user) {
await navigateTo("/dashboard");
}

View File

@@ -73,7 +73,7 @@ useHead({
const subscribe = ref(true);
async function continueSignUp() {
const route = useNativeRoute();
const route = useRoute();
await useAuth(route.query.authToken);
await useUser();

View File

@@ -249,7 +249,7 @@
</div>
</div>
<div class="normal-page__content">
<Promotion :external="false" query-param="" />
<Promotion v-if="!auth.user || !isPermission(auth.user.badges, 1 << 0)" :external="false" />
<nav class="navigation-card">
<NavRow

View File

@@ -32,7 +32,7 @@
<BoxIcon />
{{
formatMessage(messages.projectsCountLabel, {
count: formatCompactNumber(user.follows.length),
count: formatCompactNumber(user ? user.follows.length : 0),
})
}}
</div>
@@ -127,8 +127,8 @@ useHead({
title: () => `${formatMessage(messages.collectionsLongTitle)} - Modrinth`,
});
const user = await useUser();
const auth = await useAuth();
const user = await useUser();
if (import.meta.client) {
await initUserFollows();

View File

@@ -129,7 +129,7 @@
</div>
<div v-if="!routeHasSettings" class="normal-page__content">
<ModalCreation ref="modal_creation" :organization-id="organization.id" />
<Promotion :external="false" query-param="" />
<Promotion v-if="!auth.user || !isPermission(auth.user.badges, 1 << 0)" :external="false" />
<div v-if="isInvited" class="universal-card information invited">
<h2>Invitation to join {{ organization.name }}</h2>
<p>You have been invited to join {{ organization.name }}.</p>

View File

@@ -0,0 +1,159 @@
<template>
<PurchaseModal
ref="purchaseModal"
:product="midasProduct"
:country="country"
publishable-key="pk_test_51JbFxJJygY5LJFfKV50mnXzz3YLvBVe2Gd1jn7ljWAkaBlRz3VQdxN9mXcPSrFbSqxwAb0svte9yhnsmm7qHfcWn00R611Ce7b"
:send-billing-request="
async (body) =>
await useBaseFetch('billing/payment', { internal: true, method: 'POST', body })
"
:fetch-payment-data="fetchPaymentData"
:on-error="
(err) =>
data.$notify({
group: 'main',
title: 'An error occurred',
type: 'error',
text: err.message ?? (err.data ? err.data.description : err),
})
"
:customer="customer"
:payment-methods="paymentMethods"
:return-url="`${config.public.siteUrl}/settings/billing`"
/>
<div class="main-hero">
<div class="flex max-w-screen-lg flex-col items-center gap-4 text-center">
<ModrinthPlusIcon class="h-8 w-max text-contrast" />
<h1 class="m-0 text-[4rem]">Support creators and go ad-free</h1>
<p class="m-0 mb-4 text-[18px] leading-relaxed">
Subscribe to Modrinth Plus to go ad-free, support Modrinth's development, and get an
exclusive profile badge! Half your subscription goes directly to Modrinth creators. Cancel
anytime.
</p>
<p class="m-0 text-[2rem] font-bold text-purple">
{{ formatPrice(vintl.locale, price.prices.intervals.monthly, price.currency_code) }}/mo
</p>
<p class="m-0 mb-4 text-secondary">
or save
{{ calculateSavings(price.prices.intervals.monthly, price.prices.intervals.yearly) }}% with
annual billing!
</p>
<nuxt-link
v-if="auth.user && isPermission(auth.user.badges, 1 << 0)"
to="/settings/billing"
class="btn btn-purple btn-large"
>
<SettingsIcon />
Manage subscription
</nuxt-link>
<button v-else-if="auth.user" class="btn btn-purple btn-large" @click="purchaseModal.show()">
Subscribe
</button>
<nuxt-link
v-else
:to="`/auth/sign-in?redirect=${encodeURIComponent('/plus?showModal=true')}`"
class="btn btn-purple btn-large"
>
Subscribe
</nuxt-link>
</div>
</div>
<div class="perks-hero">
<h2>What you get with Modrinth Plus!</h2>
<div class="mt-8 grid max-w-screen-lg gap-8 lg:grid-cols-3">
<div class="flex flex-col gap-4 rounded-xl bg-bg-raised p-4">
<HeartIcon class="h-8 w-8 text-purple" />
<span class="text-lg font-bold">Support Modrinth creators</span>
<span class="leading-5 text-secondary">
50% of your subscription goes directly to Modrinth creators.
</span>
</div>
<div class="flex flex-col gap-4 rounded-xl bg-bg-raised p-4">
<SparklesIcon class="h-8 w-8 text-purple" />
<span class="text-lg font-bold">Remove all ads</span>
<span class="leading-5 text-secondary">
Never see an advertisement again on the Modrinth app or the website.
</span>
</div>
<div class="flex flex-col gap-4 rounded-xl bg-bg-raised p-4">
<StarIcon class="h-8 w-8 text-purple" />
<span class="text-lg font-bold">Profile badge</span>
<span class="leading-5 text-secondary">Get an exclusive badge on your user page.</span>
</div>
</div>
<span class="mt-4 text-secondary">...and much more coming soon!</span>
</div>
</template>
<script setup>
import {
ModrinthPlusIcon,
HeartIcon,
SparklesIcon,
StarIcon,
SettingsIcon,
} from "@modrinth/assets";
import { PurchaseModal } from "@modrinth/ui";
import { calculateSavings, formatPrice, getCurrency } from "@modrinth/utils";
import { products } from "~/generated/state.json";
const title = "Subscribe to Modrinth Plus!";
const description =
"Subscribe to Modrinth Plus to go ad-free, support Modrinth's development, and get an exclusive profile badge! Half your subscription goes directly to Modrinth creators.";
useSeoMeta({
title,
description,
ogTitle: title,
ogDescription: description,
});
const vintl = useVIntl();
const data = useNuxtApp();
const config = useRuntimeConfig();
const auth = await useAuth();
const purchaseModal = ref();
const midasProduct = ref(products.find((x) => x.metadata.type === "midas"));
const country = useUserCountry();
const price = computed(() =>
midasProduct.value.prices.find((x) => x.currency_code === getCurrency(country.value)),
);
const customer = ref();
const paymentMethods = ref([]);
async function fetchPaymentData() {
[customer.value, paymentMethods.value] = await Promise.all([
useBaseFetch("billing/customer", { internal: true }),
useBaseFetch("billing/payment_methods", { internal: true }),
]);
}
const route = useRoute();
onMounted(() => {
if (route.query.showModal) {
purchaseModal.value.show();
}
});
</script>
<style lang="scss" scoped>
.main-hero {
background: linear-gradient(360deg, rgba(199, 138, 255, 0.2) 10.92%, var(--color-bg) 100%),
var(--color-accent-contrast);
margin-top: -4rem;
padding: 11.25rem 1rem 8rem;
display: flex;
align-items: center;
flex-direction: column;
}
.perks-hero {
background-color: var(--color-accent-contrast);
display: flex;
align-items: center;
flex-direction: column;
padding: 4rem 1rem;
}
</style>

View File

@@ -216,7 +216,7 @@
</section>
</aside>
<section class="normal-page__content">
<Promotion :external="false" query-param="" />
<Promotion v-if="!auth.user || !isPermission(auth.user.badges, 1 << 0)" :external="false" />
<div class="card search-controls">
<div class="search-filter-container">
<button
@@ -369,6 +369,7 @@ const route = useNativeRoute();
const cosmetics = useCosmetics();
const tags = useTags();
const auth = await useAuth();
const query = ref("");
const facets = ref([]);

View File

@@ -47,6 +47,12 @@
>
<MonitorSmartphoneIcon />
</NavStackItem>
<NavStackItem
link="/settings/billing"
:label="formatMessage(commonSettingsMessages.billing)"
>
<CardIcon />
</NavStackItem>
</template>
<template v-if="auth.user">
<h3>Developer</h3>
@@ -81,6 +87,7 @@ import {
ShieldIcon,
KeyIcon,
LanguagesIcon,
CardIcon,
} from "@modrinth/assets";
import NavStack from "~/components/ui/NavStack.vue";
import NavStackItem from "~/components/ui/NavStackItem.vue";

View File

@@ -0,0 +1,88 @@
<template>
<div>
<section class="card">
<Breadcrumbs
current-title="Past charges"
:link-stack="[{ href: '/settings/billing', label: 'Billing and subscriptions' }]"
/>
<h2>Past charges</h2>
<p>All of your past charges to your Modrinth account will be listed here:</p>
<div
v-for="charge in charges"
:key="charge.id"
class="universal-card recessed flex items-center justify-between gap-4"
>
<div class="flex flex-col gap-1">
<div class="flex items-center gap-1">
<span class="font-bold text-primary">
<template v-if="charge.product.metadata.type === 'midas'"> Modrinth Plus </template>
<template v-else> Unknown product </template>
<template v-if="charge.metadata.modrinth_subscription_interval">
{{ charge.metadata.modrinth_subscription_interval }}
</template>
</span>
<span>{{ formatPrice(charge.amount, charge.currency) }}</span>
</div>
<div class="flex items-center gap-1">
<Badge :color="charge.status === 'succeeded' ? 'green' : 'red'" :type="charge.status" />
{{ $dayjs.unix(charge.created).format("YYYY-MM-DD") }}
</div>
</div>
<a
v-if="charge.receipt_url"
class="iconified-button raised-button"
:href="charge.receipt_url"
>
<ReceiptTextIcon />
View receipt
</a>
</div>
</section>
</div>
</template>
<script setup>
import { ReceiptTextIcon } from "@modrinth/assets";
import { Breadcrumbs, Badge } from "@modrinth/ui";
import { products } from "~/generated/state.json";
definePageMeta({
middleware: "auth",
});
const vintl = useVIntl();
const { data: charges } = await useAsyncData(
"billing/payments",
() => useBaseFetch("billing/payments", { internal: true }),
{
transform: (charges) => {
return charges.map((charge) => {
const product = products.find((product) =>
product.prices.some((price) => price.id === charge.metadata.modrinth_price_id),
);
charge.product = product;
return charge;
});
},
},
);
// TODO move to omorphia utils , duplicated from index
function formatPrice(price, currency) {
const formatter = new Intl.NumberFormat(vintl.locale, {
style: "currency",
currency,
});
const maxDigits = formatter.resolvedOptions().maximumFractionDigits;
const convertedPrice = price / Math.pow(10, maxDigits);
return formatter.format(convertedPrice);
}
console.log(charges);
</script>

View File

@@ -0,0 +1,668 @@
<template>
<section class="universal-card">
<h2>{{ formatMessage(messages.subscriptionTitle) }}</h2>
<p>{{ formatMessage(messages.subscriptionDescription) }}</p>
<div class="universal-card recessed">
<ConfirmModal
ref="modal_cancel"
:title="formatMessage(cancelModalMessages.title)"
:description="formatMessage(cancelModalMessages.description)"
:proceed-label="formatMessage(cancelModalMessages.action)"
@proceed="cancelSubscription(cancelSubscriptionId)"
/>
<div class="flex flex-wrap justify-between gap-4">
<div class="flex flex-col gap-4">
<template v-if="midasSubscription">
<span v-if="midasSubscription.status === 'active'">
You're currently subscribed to:
</span>
<span v-else-if="midasSubscription.status === 'payment-processing'" class="text-orange">
Your payment is being processed. Perks will activate once payment is complete.
</span>
<span v-else-if="midasSubscription.status === 'cancelled'">
You've cancelled your subscription. <br />
You will retain your perks until the end of the current billing cycle.
</span>
<span v-else-if="midasSubscription.status === 'payment-failed'" class="text-red">
Your subscription payment failed. Please update your payment method.
</span>
</template>
<span v-else>Become a subscriber to Modrinth Plus!</span>
<ModrinthPlusIcon class="h-8 w-min" />
<div class="flex flex-col gap-2">
<span class="font-bold">Benefits</span>
<div class="flex items-center gap-2">
<CheckCircleIcon class="h-5 w-5 text-brand" />
<span>Ad-free browsing on modrinth.com and Modrinth App</span>
</div>
<div class="flex items-center gap-2">
<CheckCircleIcon class="h-5 w-5 text-brand" />
<span>Modrinth+ badge on your profile</span>
</div>
<div class="flex items-center gap-2">
<CheckCircleIcon class="h-5 w-5 text-brand" />
<span>Support Modrinth and creators directly</span>
</div>
</div>
</div>
<div class="flex w-full flex-wrap justify-between gap-4 xl:w-auto xl:flex-col">
<div class="flex flex-col gap-1 xl:ml-auto xl:text-right">
<span class="text-2xl font-bold text-dark">
<template v-if="midasSubscription">
{{
formatPrice(
vintl.locale,
midasSubscriptionPrice.prices.intervals[midasSubscription.interval],
midasSubscriptionPrice.currency_code,
)
}}
/
{{ midasSubscription.interval }}
</template>
<template v-else>
{{ formatPrice(vintl.locale, price.prices.intervals.monthly, price.currency_code) }}
/ month
</template>
</span>
<template v-if="midasSubscription">
<span class="text-sm text-secondary">
Since {{ $dayjs(midasSubscription.created).format("MMMM D, YYYY") }}
</span>
<span v-if="midasSubscription.status === 'active'" class="text-sm text-secondary">
Renews {{ $dayjs(midasSubscription.expires).format("MMMM D, YYYY") }}
</span>
<span
v-else-if="midasSubscription.status === 'cancelled'"
class="text-sm text-secondary"
>
Expires {{ $dayjs(midasSubscription.expires).format("MMMM D, YYYY") }}
</span>
</template>
<span v-else class="text-sm text-secondary">
Or
{{ formatPrice(vintl.locale, price.prices.intervals.yearly, price.currency_code) }} /
year (save
{{
calculateSavings(price.prices.intervals.monthly, price.prices.intervals.yearly)
}}%)!
</span>
</div>
<div
v-if="midasSubscription && midasSubscription.status === 'payment-failed'"
class="ml-auto flex flex-row-reverse items-center gap-2"
>
<button
v-if="midasSubscription && midasSubscription.status === 'payment-failed'"
class="iconified-button raised-button"
@click="
() => {
purchaseModalStep = 0;
$refs.purchaseModal.show();
}
"
>
<UpdatedIcon />
Update method
</button>
<OverflowMenu
class="btn icon-only transparent"
:options="[
{
id: 'cancel',
action: () => {
cancelSubscriptionId = midasSubscription.id;
$refs.modal_cancel.show();
},
},
]"
>
<MoreVerticalIcon />
<template #cancel><XIcon /> Cancel</template>
</OverflowMenu>
</div>
<button
v-else-if="midasSubscription && midasSubscription.status !== 'cancelled'"
class="iconified-button raised-button !ml-auto"
@click="
() => {
cancelSubscriptionId = midasSubscription.id;
$refs.modal_cancel.show();
}
"
>
<XIcon /> Cancel
</button>
<button
v-else
class="btn btn-purple btn-large ml-auto"
@click="
() => {
purchaseModalStep = 0;
$refs.purchaseModal.show();
}
"
>
<RightArrowIcon />
Subscribe
</button>
</div>
</div>
</div>
</section>
<section class="universal-card">
<ConfirmModal
ref="modal_confirm"
:title="formatMessage(deleteModalMessages.title)"
:description="formatMessage(deleteModalMessages.description)"
:proceed-label="formatMessage(deleteModalMessages.action)"
@proceed="removePaymentMethod(removePaymentMethodIndex)"
/>
<PurchaseModal
ref="purchaseModal"
:product="midasProduct"
:country="country"
publishable-key="pk_test_51JbFxJJygY5LJFfKV50mnXzz3YLvBVe2Gd1jn7ljWAkaBlRz3VQdxN9mXcPSrFbSqxwAb0svte9yhnsmm7qHfcWn00R611Ce7b"
:send-billing-request="
async (body) =>
await useBaseFetch('billing/payment', { internal: true, method: 'POST', body })
"
:on-error="
(err) =>
data.$notify({
group: 'main',
title: 'An error occurred',
type: 'error',
text: err.message ?? (err.data ? err.data.description : err),
})
"
:customer="customer"
:payment-methods="paymentMethods"
:return-url="`${config.public.siteUrl}/settings/billing`"
/>
<NewModal ref="addPaymentMethodModal">
<template #title>
<span class="text-lg font-extrabold text-contrast">
{{ formatMessage(messages.paymentMethodTitle) }}
</span>
</template>
<div class="min-h-[16rem] md:w-[600px]">
<div
v-show="loadingPaymentMethodModal !== 2"
class="flex min-h-[16rem] items-center justify-center"
>
<AnimatedLogo class="w-[80px]" />
</div>
<div v-show="loadingPaymentMethodModal === 2" class="min-h-[16rem] p-1">
<div id="address-element"></div>
<div id="payment-element" class="mt-4"></div>
</div>
<div v-show="loadingPaymentMethodModal === 2" class="input-group push-right mt-auto pt-4">
<button class="btn" @click="$refs.addPaymentMethodModal.hide()">
<XIcon />
{{ formatMessage(commonMessages.cancelButton) }}
</button>
<button class="btn btn-primary" :disabled="loadingAddMethod" @click="submit">
<PlusIcon />
{{ formatMessage(messages.paymentMethodAdd) }}
</button>
</div>
</div>
</NewModal>
<div class="header__row">
<div class="header__title">
<h2 class="text-2xl">{{ formatMessage(messages.paymentMethodTitle) }}</h2>
</div>
<nuxt-link class="btn" to="/settings/billing/charges">
<HistoryIcon /> {{ formatMessage(messages.paymentMethodHistory) }}
</nuxt-link>
<button class="btn" @click="addPaymentMethod">
<PlusIcon /> {{ formatMessage(messages.paymentMethodAdd) }}
</button>
</div>
<div
v-if="!paymentMethods || paymentMethods.length === 0"
class="universal-card recessed !mb-0"
>
{{ formatMessage(messages.paymentMethodNone) }}
</div>
<div v-else class="flex flex-col gap-4">
<div
v-for="(method, index) in paymentMethods"
:key="index"
class="universal-card recessed !mb-0 flex items-center justify-between"
>
<div class="flex gap-2">
<CardIcon v-if="method.type === 'card'" class="h-8 w-8" />
<CurrencyIcon v-else-if="method.type === 'cashapp'" class="h-8 w-8" />
<PayPalIcon v-else-if="method.type === 'paypal'" class="h-8 w-8" />
<div class="flex flex-col">
<div class="flex items-center gap-2">
<div class="font-bold text-contrast">
<template v-if="method.type === 'card'">
{{
formatMessage(messages.paymentMethodCardDisplay, {
card_brand:
formatMessage(paymentMethodTypes[method.card.brand]) ??
formatMessage(paymentMethodTypes.unknown),
last_four: method.card.last4,
})
}}
</template>
<template v-else>
{{
formatMessage(paymentMethodTypes[method.type]) ??
formatMessage(paymentMethodTypes.unknown)
}}
</template>
</div>
<div
v-if="primaryPaymentMethodId === method.id"
class="border-r-ma rounded-full bg-button-bg px-2 py-0.5 text-sm font-bold text-secondary"
>
{{ formatMessage(messages.paymentMethodPrimary) }}
</div>
</div>
<div v-if="method.type === 'card'" class="text-secondary">
{{
formatMessage(messages.paymentMethodCardExpiry, {
month: method.card.exp_month,
year: method.card.exp_year,
})
}}
</div>
<div v-else-if="method.type === 'cashapp'" class="text-secondary">
{{ method.cashapp.cashtag }}
</div>
<div v-else-if="method.type === 'paypal'" class="text-secondary">
{{ method.paypal.payer_email }}
</div>
</div>
</div>
<OverflowMenu
class="btn icon-only transparent"
:options="
[
{
id: 'primary',
action: () => editPaymentMethod(index, true),
},
{
id: 'remove',
action: () => {
removePaymentMethodIndex = index;
$refs.modal_confirm.show();
},
color: 'red',
hoverOnly: true,
},
].slice(primaryPaymentMethodId === method.id ? 1 : 0, 2)
"
>
<MoreVerticalIcon />
<template #primary>
<StarIcon />
{{ formatMessage(messages.paymentMethodMakePrimary) }}
</template>
<template #edit>
<EditIcon />
{{ formatMessage(commonMessages.editButton) }}
</template>
<template #remove>
<TrashIcon />
{{ formatMessage(commonMessages.deleteLabel) }}
</template>
</OverflowMenu>
</div>
</div>
</section>
</template>
<script setup>
import { ConfirmModal, NewModal, OverflowMenu, AnimatedLogo, PurchaseModal } from "@modrinth/ui";
import {
PlusIcon,
XIcon,
CardIcon,
MoreVerticalIcon,
TrashIcon,
EditIcon,
StarIcon,
PayPalIcon,
CurrencyIcon,
CheckCircleIcon,
RightArrowIcon,
ModrinthPlusIcon,
UpdatedIcon,
HistoryIcon,
} from "@modrinth/assets";
import { calculateSavings, formatPrice, createStripeElements, getCurrency } from "@modrinth/utils";
import { ref } from "vue";
import { products } from "~/generated/state.json";
definePageMeta({
middleware: "auth",
});
const data = useNuxtApp();
const config = useRuntimeConfig();
const vintl = useVIntl();
const { formatMessage } = vintl;
const deleteModalMessages = defineMessages({
title: {
id: "settings.billing.modal.delete.title",
defaultMessage: "Are you sure you want to remove this payment method?",
},
description: {
id: "settings.billing.modal.delete.description",
defaultMessage: "This will remove this payment method forever (like really forever).",
},
action: {
id: "settings.billing.modal.delete.action",
defaultMessage: "Remove this payment method",
},
});
const cancelModalMessages = defineMessages({
title: {
id: "settings.billing.modal.cancel.title",
defaultMessage: "Are you sure you want to cancel your subscription?",
},
description: {
id: "settings.billing.modal.cancel.description",
defaultMessage:
"This will cancel your subscription. You will retain your perks until the end of the current billing cycle.",
},
action: {
id: "settings.billing.modal.cancel.action",
defaultMessage: "Cancel subscription",
},
});
const messages = defineMessages({
subscriptionTitle: {
id: "settings.billing.subscription.title",
defaultMessage: "Subscriptions",
},
subscriptionDescription: {
id: "settings.billing.subscription.description",
defaultMessage: "Manage your Modrinth subscriptions.",
},
paymentMethodTitle: {
id: "settings.billing.payment_method.title",
defaultMessage: "Payment methods",
},
paymentMethodNone: {
id: "settings.billing.payment_method.none",
defaultMessage: "You have not added any payment methods.",
},
paymentMethodHistory: {
id: "settings.billing.payment_method.action.history",
defaultMessage: "View past charges",
},
paymentMethodAdd: {
id: "settings.billing.payment_method.action.add",
defaultMessage: "Add payment method",
},
paymentMethodPrimary: {
id: "settings.billing.payment_method.primary",
defaultMessage: "Primary",
},
paymentMethodMakePrimary: {
id: "settings.billing.payment_method.action.primary",
defaultMessage: "Make primary",
},
paymentMethodCardDisplay: {
id: "settings.billing.payment_method.card_display",
defaultMessage: "{card_brand} ending in {last_four}",
},
paymentMethodCardExpiry: {
id: "settings.billing.payment_method.card_expiry",
defaultMessage: "Expires {month}/{year}",
},
});
const paymentMethodTypes = defineMessages({
visa: {
id: "settings.billing.payment_method_type.visa",
defaultMessage: "Visa",
},
amex: { id: "settings.billing.payment_method_type.amex", defaultMessage: "American Express" },
diners: { id: "settings.billing.payment_method_type.diners", defaultMessage: "Diners Club" },
discover: { id: "settings.billing.payment_method_type.discover", defaultMessage: "Discover" },
eftpos: { id: "settings.billing.payment_method_type.eftpos", defaultMessage: "EFTPOS" },
jcb: { id: "settings.billing.payment_method_type.jcb", defaultMessage: "JCB" },
mastercard: {
id: "settings.billing.payment_method_type.mastercard",
defaultMessage: "MasterCard",
},
unionpay: { id: "settings.billing.payment_method_type.unionpay", defaultMessage: "UnionPay" },
paypal: { id: "settings.billing.payment_method_type.paypal", defaultMessage: "PayPal" },
cashapp: { id: "settings.billing.payment_method_type.cashapp", defaultMessage: "Cash App" },
amazon_pay: {
id: "settings.billing.payment_method_type.amazon_pay",
defaultMessage: "Amazon Pay",
},
unknown: {
id: "settings.billing.payment_method_type.unknown",
defaultMessage: "Unknown payment method",
},
});
let stripe = null;
let elements = null;
function loadStripe() {
try {
if (!stripe) {
stripe = Stripe(
"pk_test_51JbFxJJygY5LJFfKV50mnXzz3YLvBVe2Gd1jn7ljWAkaBlRz3VQdxN9mXcPSrFbSqxwAb0svte9yhnsmm7qHfcWn00R611Ce7b",
);
}
} catch {}
}
const [
{ data: paymentMethods, refresh: refreshPaymentMethods },
{ data: customer, refresh: refreshCustomer },
{ data: subscriptions, refresh: refreshSubscriptions },
] = await Promise.all([
useAsyncData("billing/payment_methods", () =>
useBaseFetch("billing/payment_methods", { internal: true }),
),
useAsyncData("billing/customer", () => useBaseFetch("billing/customer", { internal: true })),
useAsyncData("billing/subscriptions", () =>
useBaseFetch("billing/subscriptions", { internal: true }),
),
]);
async function refresh() {
await Promise.all([refreshPaymentMethods(), refreshCustomer(), refreshSubscriptions()]);
}
const midasProduct = ref(products.find((x) => x.metadata.type === "midas"));
const midasSubscription = computed(() =>
subscriptions.value.find((x) => midasProduct.value.prices.find((y) => y.id === x.price_id)),
);
const midasSubscriptionPrice = computed(() =>
midasSubscription.value
? midasProduct.value.prices.find((x) => x.id === midasSubscription.value.price_id)
: null,
);
const purchaseModal = ref();
const country = useUserCountry();
const price = computed(() =>
midasProduct.value.prices.find((x) => x.currency_code === getCurrency(country.value)),
);
// Initialize subscription with fake data if redirected from checkout
const route = useRoute();
const router = useRouter();
if (route.query.priceId && route.query.plan && route.query.redirect_status) {
let status;
if (route.query.redirect_status === "succeeded") {
status = "active";
} else if (route.query.redirect_status === "processing") {
status = "payment-processing";
} else {
status = "payment-failed";
}
subscriptions.value.push({
id: "temp",
price_id: route.query.priceId,
interval: route.query.plan,
created: Date.now(),
expires: route.query.plan === "yearly" ? Date.now() + 31536000000 : Date.now() + 2629746000,
status,
});
await router.replace({ query: {} });
}
const primaryPaymentMethodId = computed(() => {
if (
customer.value &&
customer.value.invoice_settings &&
customer.value.invoice_settings.default_payment_method
) {
return customer.value.invoice_settings.default_payment_method;
} else if (paymentMethods.value && paymentMethods.value[0] && paymentMethods.value[0].id) {
return paymentMethods.value[0].id;
} else {
return null;
}
});
const addPaymentMethodModal = ref();
const loadingPaymentMethodModal = ref(0);
async function addPaymentMethod() {
try {
loadingPaymentMethodModal.value = 0;
addPaymentMethodModal.value.show();
const result = await useBaseFetch("billing/payment_method", {
internal: true,
method: "POST",
});
loadStripe();
const {
elements: elementsVal,
addressElement,
paymentElement,
} = createStripeElements(stripe, paymentMethods.value, {
clientSecret: result.client_secret,
});
elements = elementsVal;
paymentElement.on("ready", () => {
loadingPaymentMethodModal.value += 1;
});
addressElement.on("ready", () => {
loadingPaymentMethodModal.value += 1;
});
} catch (err) {
data.$notify({
group: "main",
title: "An error occurred",
text: err.data ? err.data.description : err,
type: "error",
});
}
}
const loadingAddMethod = ref(false);
async function submit() {
startLoading();
loadingAddMethod.value = true;
loadStripe();
const { error } = await stripe.confirmSetup({
elements,
confirmParams: {
return_url: `${config.public.siteUrl}/settings/billing`,
},
});
if (error && error.type !== "validation_error") {
data.$notify({
group: "main",
title: "An error occurred",
text: error.message,
type: "error",
});
} else if (!error) {
await refresh();
addPaymentMethodModal.value.close();
}
loadingAddMethod.value = false;
stopLoading();
}
const removePaymentMethodIndex = ref();
async function editPaymentMethod(index, primary) {
startLoading();
try {
await useBaseFetch(`billing/payment_method/${paymentMethods.value[index].id}`, {
internal: true,
method: "PATCH",
data: {
primary,
},
});
await refresh();
} catch (err) {
data.$notify({
group: "main",
title: "An error occurred",
text: err.data ? err.data.description : err,
type: "error",
});
}
stopLoading();
}
async function removePaymentMethod(index) {
startLoading();
try {
await useBaseFetch(`billing/payment_method/${paymentMethods.value[index].id}`, {
internal: true,
method: "DELETE",
});
await refresh();
} catch (err) {
data.$notify({
group: "main",
title: "An error occurred",
text: err.data ? err.data.description : err,
type: "error",
});
}
stopLoading();
}
const cancelSubscriptionId = ref();
async function cancelSubscription(id) {
startLoading();
try {
await useBaseFetch(`billing/subscription/${id}`, {
internal: true,
method: "DELETE",
});
await refresh();
} catch (err) {
data.$notify({
group: "main",
title: "An error occurred",
text: err.data ? err.data.description : err,
type: "error",
});
}
stopLoading();
}
</script>

View File

@@ -121,7 +121,7 @@
</div>
</div>
<div class="normal-page__content">
<Promotion :external="false" query-param="" />
<Promotion v-if="!auth.user || !isPermission(auth.user.badges, 1 << 0)" :external="false" />
<nav class="navigation-card">
<NavRow
:links="[

View File

@@ -174,4 +174,8 @@ export const commonSettingsMessages = defineMessages({
id: "settings.applications.title",
defaultMessage: "Your applications",
},
billing: {
id: "settings.billing.title",
defaultMessage: "Billing and subscriptions",
},
});