feat(payment): implement first recharge offer functionality and UI updates

This commit is contained in:
2026-07-02 14:39:09 +08:00
parent 7b35fd18c5
commit d4de1370e8
20 changed files with 607 additions and 50 deletions
+32 -32
View File
@@ -1,34 +1,34 @@
GET https://proapi.banlv-ai.com/api/payment/plans 有更新,主要是 /api/payment/plans
结果 前端判断方式
status=200 调用:
success=true GET /api/payment/plans
plans 数量 8 如果用户已登录,请带上:
VIP 套餐 3 个 Authorization: Bearer <token>
credits 套餐 5 个 后端会返回:
snake_keys=[],已经没有 plan_id / amount_cents 这种字段
schema 校验通过:proapi_plans_camel_schema_ok true
前端按这个结构用:
type PaymentPlan = {
planId: string;
planName: string;
orderType: 'vip_monthly' | 'vip_quarterly' | 'vip_annual' | 'dol';
vipDays: number | null;
dolAmount: number | null;
creditBalance: number;
amountCents: number;
originalAmountCents: number | null;
dailyPriceCents: number | null;
currency: string;
};
分组:
const plans = res.data.plans;
const vipPlans = plans.filter(p => p.vipDays !== null);
const creditPlans = plans.filter(p => p.dolAmount !== null);
下单仍然传 planId
{ {
"planId": "vip_monthly", "isFirstRecharge": true,
"payChannel": "stripe", "firstRechargeOffer": {
"autoRenew": true "enabled": true,
"type": "first_recharge_half_price",
"discountPercent": 50
},
"plans": [
{
"planId": "vip_monthly",
"amountCents": 995,
"originalAmountCents": 1990,
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
}
]
} }
价格、币种全部以前端拿到的 amountCents / currency 展示,不要写死。当前我这边访问 pro 返回的是 JPY,这是 Cloudflare 根据访问 IP 判的国家币种。 前端逻辑很简单:
data.isFirstRecharge === true 或 plan.isFirstRechargeOffer === true:展示首充价
amountCents:实际支付价,也就是首充半价
originalAmountCents:划线原价
firstRechargeDiscountPercent:折扣,比如 50
不需要前端自己算半价
创建订单还是原接口:
POST /api/payment/create-order
前端只传原来的 planId/payChannel/autoRenew,不用传首充字段。后端会重新判断首充资格,并按半价创建订单,防止前端伪造价格。
@@ -6,6 +6,7 @@ import {
findSelectedSubscriptionPlan, findSelectedSubscriptionPlan,
getDefaultPayChannelForCountryCode, getDefaultPayChannelForCountryCode,
getDefaultSubscriptionPlanId, getDefaultSubscriptionPlanId,
getFirstRechargeOfferView,
toCoinsOfferPlanViews, toCoinsOfferPlanViews,
toVipOfferPlanViews, toVipOfferPlanViews,
} from "../subscription-screen.helpers"; } from "../subscription-screen.helpers";
@@ -103,6 +104,56 @@ describe("subscription screen helpers", () => {
]); ]);
}); });
it("maps first recharge offer fields to plan views", () => {
const vipViews = toVipOfferPlanViews([
makePlan({
planId: "vip_monthly",
amountCents: 995,
originalAmountCents: 1990,
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
promotionType: "first_recharge_half_price",
}),
]);
const coinViews = toCoinsOfferPlanViews([
makePlan({
planId: "coin_1000",
orderType: "coins_1000",
vipDays: null,
dolAmount: 1000,
amountCents: 495,
originalAmountCents: 990,
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
promotionType: "first_recharge_half_price",
}),
]);
expect(vipViews[0]).toMatchObject({
price: "9.95",
originalPrice: "19.9",
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
});
expect(coinViews[0]).toMatchObject({
price: "4.95",
originalPrice: "9.9",
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
});
expect(
getFirstRechargeOfferView({
isFirstRecharge: true,
discountPercent: 50,
vipPlans: vipViews,
coinPlans: coinViews,
}),
).toMatchObject({
badgeText: "50% OFF",
title: "New User First Recharge",
});
});
it("selects the first VIP plan by default when VIP can be purchased", () => { it("selects the first VIP plan by default when VIP can be purchased", () => {
expect( expect(
getDefaultSubscriptionPlanId({ getDefaultSubscriptionPlanId({
@@ -45,7 +45,7 @@
.row { .row {
display: grid; display: grid;
grid-template-columns: 48px minmax(0, 1fr) auto; grid-template-columns: 48px minmax(0, 1fr) auto auto;
align-items: center; align-items: center;
width: 100%; width: 100%;
min-height: 48px; min-height: 48px;
@@ -102,6 +102,28 @@
line-height: 1.2; line-height: 1.2;
} }
.offerBadge {
justify-self: end;
padding: 4px 8px;
border-radius: 999px;
background: linear-gradient(135deg, #ff5fae 0%, #ff8a34 100%);
color: #ffffff;
font-size: 11px;
font-weight: 900;
line-height: 1;
white-space: nowrap;
box-shadow: 0 7px 16px rgba(255, 95, 174, 0.24);
}
.priceGroup {
display: inline-flex;
min-width: 54px;
flex-direction: column;
align-items: flex-end;
justify-content: center;
line-height: 1;
}
.price { .price {
font-size: 16px; font-size: 16px;
font-weight: 800; font-weight: 800;
@@ -109,6 +131,16 @@
white-space: nowrap; white-space: nowrap;
} }
.originalPrice {
margin-top: 3px;
color: #9c8b91;
font-size: 12px;
font-weight: 800;
line-height: 1;
text-decoration: line-through;
white-space: nowrap;
}
@media (max-width: 360px) { @media (max-width: 360px) {
.title { .title {
font-size: 20px; font-size: 20px;
@@ -120,11 +152,17 @@
} }
.row { .row {
grid-template-columns: 46px minmax(0, 1fr) auto; grid-template-columns: 46px minmax(0, 1fr) auto auto;
} }
.coins, .coins,
.price { .price {
font-size: 14px; font-size: 14px;
} }
.offerBadge {
padding-right: 6px;
padding-left: 6px;
font-size: 10px;
}
} }
@@ -9,6 +9,10 @@ export interface CoinsOfferPlanView {
coins: number; coins: number;
price: string; price: string;
currency: string; currency: string;
originalPrice?: string;
isFirstRechargeOffer?: boolean;
firstRechargeDiscountPercent?: number | null;
promotionType?: string | null;
} }
export interface SubscriptionCoinsOfferSectionProps { export interface SubscriptionCoinsOfferSectionProps {
@@ -45,9 +49,22 @@ export function SubscriptionCoinsOfferSection({
<FaCoins size={18} /> <FaCoins size={18} />
</span> </span>
<span className={styles.coins}>{plan.coins} Coins</span> <span className={styles.coins}>{plan.coins} Coins</span>
<span className={styles.price}> {plan.isFirstRechargeOffer ? (
{plan.currency} <span className={styles.offerBadge}>
{plan.price} {plan.firstRechargeDiscountPercent ?? 50}% OFF
</span>
) : null}
<span className={styles.priceGroup}>
<span className={styles.price}>
{plan.currency}
{plan.price}
</span>
{plan.originalPrice ? (
<span className={styles.originalPrice}>
{plan.currency}
{plan.originalPrice}
</span>
) : null}
</span> </span>
</button> </button>
); );
@@ -18,6 +18,52 @@
display: inline-flex; display: inline-flex;
} }
.firstRechargeBanner {
display: flex;
align-items: center;
gap: 12px;
margin-top: 14px;
padding: 12px 14px;
border: 1px solid rgba(255, 95, 174, 0.28);
border-radius: 22px;
background:
linear-gradient(135deg, rgba(255, 255, 255, 0.96) 0%, rgba(255, 239, 248, 0.94) 100%),
#ffffff;
box-shadow: 0 14px 32px rgba(255, 95, 174, 0.16);
}
.firstRechargeBadge {
flex: 0 0 auto;
padding: 8px 10px;
border-radius: 999px;
background: linear-gradient(135deg, #ff5fae 0%, #ff8a34 100%);
color: #ffffff;
font-size: 13px;
font-weight: 900;
line-height: 1;
box-shadow: 0 10px 22px rgba(255, 95, 174, 0.25);
}
.firstRechargeCopy {
min-width: 0;
}
.firstRechargeTitle {
margin: 0;
color: #181014;
font-size: 17px;
font-weight: 900;
line-height: 1.15;
}
.firstRechargeSubtitle {
margin: 4px 0 0;
color: #75656d;
font-size: 12px;
font-weight: 700;
line-height: 1.25;
}
.offerStack { .offerStack {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -63,9 +63,10 @@
} }
.planCard { .planCard {
position: relative;
display: flex; display: flex;
min-width: 0; min-width: 0;
min-height: 118px; min-height: 128px;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -101,7 +102,25 @@
transform: translateY(-3px); transform: translateY(-3px);
} }
.offerBadge {
position: absolute;
top: 8px;
left: 50%;
max-width: calc(100% - 12px);
padding: 3px 7px;
border-radius: 999px;
background: linear-gradient(135deg, #ff5fae 0%, #ff8a34 100%);
color: #ffffff;
font-size: 10px;
font-weight: 900;
line-height: 1;
white-space: nowrap;
box-shadow: 0 7px 16px rgba(255, 95, 174, 0.28);
transform: translateX(-50%);
}
.planTitle { .planTitle {
margin-top: 12px;
font-size: 19px; font-size: 19px;
font-weight: 800; font-weight: 800;
line-height: 1.15; line-height: 1.15;
@@ -8,6 +8,9 @@ export interface VipOfferPlanView {
price: string; price: string;
currency: string; currency: string;
originalPrice: string; originalPrice: string;
isFirstRechargeOffer?: boolean;
firstRechargeDiscountPercent?: number | null;
promotionType?: string | null;
} }
export interface SubscriptionVipOfferSectionProps { export interface SubscriptionVipOfferSectionProps {
@@ -48,12 +51,19 @@ export function SubscriptionVipOfferSection({
aria-label={`${plan.title}, ${plan.price} ${plan.currency}`} aria-label={`${plan.title}, ${plan.price} ${plan.currency}`}
onClick={() => onSelectPlan(plan.id)} onClick={() => onSelectPlan(plan.id)}
> >
{plan.isFirstRechargeOffer ? (
<span className={styles.offerBadge}>
First recharge {plan.firstRechargeDiscountPercent ?? 50}% OFF
</span>
) : null}
<span className={styles.planTitle}>{plan.title}</span> <span className={styles.planTitle}>{plan.title}</span>
<span className={styles.priceLine}> <span className={styles.priceLine}>
<span className={styles.price}>{plan.price}</span> <span className={styles.price}>{plan.price}</span>
<span className={styles.currency}>{plan.currency}</span> <span className={styles.currency}>{plan.currency}</span>
</span> </span>
<span className={styles.originalPrice}>{plan.originalPrice}</span> <span className={styles.originalPrice}>
{plan.originalPrice || "\u00a0"}
</span>
</button> </button>
); );
})} })}
@@ -6,6 +6,12 @@ import type { VipOfferPlanView } from "./components/subscription-vip-offer-secti
export type SubscriptionType = "vip" | "topup"; export type SubscriptionType = "vip" | "topup";
export interface FirstRechargeOfferView {
badgeText: string;
title: string;
subtitle: string;
}
export function isVipPlan(plan: PaymentPlan): boolean { export function isVipPlan(plan: PaymentPlan): boolean {
return plan.vipDays !== null; return plan.vipDays !== null;
} }
@@ -54,6 +60,9 @@ export function toVipOfferPlanView(plan: PaymentPlan): VipOfferPlanView {
price: formatOfferAmount(plan.amountCents), price: formatOfferAmount(plan.amountCents),
currency: formatOfferCurrency(plan.currency), currency: formatOfferCurrency(plan.currency),
originalPrice: formatOfferAmount(plan.originalAmountCents), originalPrice: formatOfferAmount(plan.originalAmountCents),
isFirstRechargeOffer: plan.isFirstRechargeOffer,
firstRechargeDiscountPercent: plan.firstRechargeDiscountPercent,
promotionType: plan.promotionType,
}; };
} }
@@ -63,6 +72,10 @@ export function toCoinsOfferPlanView(plan: PaymentPlan): CoinsOfferPlanView {
coins: plan.dolAmount ?? 0, coins: plan.dolAmount ?? 0,
price: formatOfferAmount(plan.amountCents), price: formatOfferAmount(plan.amountCents),
currency: formatCoinCurrency(plan.currency), currency: formatCoinCurrency(plan.currency),
originalPrice: formatOfferAmount(plan.originalAmountCents),
isFirstRechargeOffer: plan.isFirstRechargeOffer,
firstRechargeDiscountPercent: plan.firstRechargeDiscountPercent,
promotionType: plan.promotionType,
}; };
} }
@@ -123,3 +136,25 @@ export function getDefaultSubscriptionPlanId(input: {
if (input.selectedPlan !== null) return null; if (input.selectedPlan !== null) return null;
return input.coinPlans[0]?.id ?? null; return input.coinPlans[0]?.id ?? null;
} }
export function getFirstRechargeOfferView(input: {
isFirstRecharge: boolean;
discountPercent?: number | null;
vipPlans: readonly VipOfferPlanView[];
coinPlans: readonly CoinsOfferPlanView[];
}): FirstRechargeOfferView | null {
const promotedPlan = [...input.vipPlans, ...input.coinPlans].find(
(plan) => plan.isFirstRechargeOffer,
);
if (!input.isFirstRecharge && !promotedPlan) return null;
const discountPercent =
promotedPlan?.firstRechargeDiscountPercent ?? input.discountPercent ?? 50;
const badgeText = `${discountPercent}% OFF`;
return {
badgeText,
title: "New User First Recharge",
subtitle:
"Your first recharge price is already applied. No code needed.",
};
}
@@ -16,6 +16,7 @@ import {
import styles from "./components/subscription-screen.module.css"; import styles from "./components/subscription-screen.module.css";
import { import {
findSelectedSubscriptionPlan, findSelectedSubscriptionPlan,
getFirstRechargeOfferView,
getDefaultSubscriptionPlanId, getDefaultSubscriptionPlanId,
toCoinsOfferPlanViews, toCoinsOfferPlanViews,
toVipOfferPlanViews, toVipOfferPlanViews,
@@ -60,6 +61,21 @@ export function SubscriptionScreen({
() => toCoinsOfferPlanViews(payment.plans), () => toCoinsOfferPlanViews(payment.plans),
[payment.plans], [payment.plans],
); );
const firstRechargeOffer = useMemo(
() =>
getFirstRechargeOfferView({
isFirstRecharge: payment.isFirstRecharge,
discountPercent: payment.firstRechargeOffer?.discountPercent,
vipPlans: vipOfferPlans,
coinPlans: directCoinsPlans,
}),
[
directCoinsPlans,
payment.firstRechargeOffer?.discountPercent,
payment.isFirstRecharge,
vipOfferPlans,
],
);
const selectedPlan = findSelectedSubscriptionPlan({ const selectedPlan = findSelectedSubscriptionPlan({
canSubscribeVip, canSubscribeVip,
@@ -111,6 +127,25 @@ export function SubscriptionScreen({
/> />
</header> </header>
{firstRechargeOffer ? (
<section
className={styles.firstRechargeBanner}
aria-label="First recharge offer"
>
<span className={styles.firstRechargeBadge}>
{firstRechargeOffer.badgeText}
</span>
<div className={styles.firstRechargeCopy}>
<h2 className={styles.firstRechargeTitle}>
{firstRechargeOffer.title}
</h2>
<p className={styles.firstRechargeSubtitle}>
{firstRechargeOffer.subtitle}
</p>
</div>
</section>
) : null}
<div className={styles.offerStack}> <div className={styles.offerStack}>
{canSubscribeVip ? ( {canSubscribeVip ? (
<SubscriptionVipOfferSection <SubscriptionVipOfferSection
@@ -31,6 +31,9 @@ describe("PaymentPlan", () => {
originalAmountCents: 2499, originalAmountCents: 2499,
dailyPriceCents: 66, dailyPriceCents: 66,
currency: "JPY", currency: "JPY",
isFirstRechargeOffer: false,
firstRechargeDiscountPercent: null,
promotionType: null,
}); });
}); });
@@ -73,4 +76,42 @@ describe("PaymentPlansResponse", () => {
expect(response.plans).toHaveLength(1); expect(response.plans).toHaveLength(1);
expect(response.plans[0]?.dolAmount).toBe(1000); expect(response.plans[0]?.dolAmount).toBe(1000);
}); });
it("parses first recharge offer metadata", () => {
const response = PaymentPlansResponse.from({
isFirstRecharge: true,
firstRechargeOffer: {
enabled: true,
type: "first_recharge_half_price",
discountPercent: 50,
},
plans: [
{
planId: "vip_monthly",
planName: "VIP Monthly",
orderType: "vip_monthly",
vipDays: 30,
dolAmount: null,
creditBalance: 3000,
amountCents: 995,
originalAmountCents: 1990,
dailyPriceCents: null,
currency: "USD",
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
promotionType: "first_recharge_half_price",
},
],
});
expect(response.isFirstRecharge).toBe(true);
expect(response.firstRechargeOffer?.discountPercent).toBe(50);
expect(response.plans[0]).toMatchObject({
amountCents: 995,
originalAmountCents: 1990,
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
promotionType: "first_recharge_half_price",
});
});
}); });
+3
View File
@@ -18,6 +18,9 @@ export class PaymentPlan {
declare readonly originalAmountCents: number | null; declare readonly originalAmountCents: number | null;
declare readonly dailyPriceCents: number | null; declare readonly dailyPriceCents: number | null;
declare readonly currency: string; declare readonly currency: string;
declare readonly isFirstRechargeOffer: boolean;
declare readonly firstRechargeDiscountPercent: number | null;
declare readonly promotionType: string | null;
private constructor(input: PaymentPlanInput) { private constructor(input: PaymentPlanInput) {
const data = PaymentPlanSchema.parse(input); const data = PaymentPlanSchema.parse(input);
@@ -3,6 +3,7 @@
*/ */
import { import {
PaymentPlansResponseSchema, PaymentPlansResponseSchema,
type FirstRechargeOfferData,
type PaymentPlansResponseData, type PaymentPlansResponseData,
type PaymentPlansResponseInput, type PaymentPlansResponseInput,
} from "@/data/schemas/payment/payment_plans_response"; } from "@/data/schemas/payment/payment_plans_response";
@@ -10,11 +11,15 @@ import {
import { PaymentPlan } from "./payment_plan"; import { PaymentPlan } from "./payment_plan";
export class PaymentPlansResponse { export class PaymentPlansResponse {
declare readonly isFirstRecharge: boolean;
declare readonly firstRechargeOffer: FirstRechargeOfferData | null;
declare readonly plans: PaymentPlan[]; declare readonly plans: PaymentPlan[];
private constructor(input: PaymentPlansResponseInput) { private constructor(input: PaymentPlansResponseInput) {
const data = PaymentPlansResponseSchema.parse(input); const data = PaymentPlansResponseSchema.parse(input);
Object.assign(this, { Object.assign(this, {
isFirstRecharge: data.isFirstRecharge,
firstRechargeOffer: data.firstRechargeOffer,
plans: data.plans.map((plan) => PaymentPlan.from(plan)), plans: data.plans.map((plan) => PaymentPlan.from(plan)),
}); });
Object.freeze(this); Object.freeze(this);
@@ -30,7 +35,11 @@ export class PaymentPlansResponse {
toJson(): PaymentPlansResponseData { toJson(): PaymentPlansResponseData {
return { return {
isFirstRecharge: this.isFirstRecharge,
firstRechargeOffer: this.firstRechargeOffer,
plans: this.plans.map((plan) => plan.toJson()), plans: this.plans.map((plan) => plan.toJson()),
}; };
} }
} }
export type FirstRechargeOffer = FirstRechargeOfferData;
@@ -0,0 +1,135 @@
{
"code": 200,
"message": "success",
"success": true,
"data": {
"isFirstRecharge": true,
"firstRechargeOffer": {
"enabled": true,
"type": "first_recharge_half_price",
"discountPercent": 50
},
"plans": [
{
"planId": "vip_monthly",
"planName": "VIP Monthly",
"orderType": "vip_monthly",
"vipDays": 30,
"dolAmount": null,
"creditBalance": 3000,
"amountCents": 995,
"originalAmountCents": 1990,
"dailyPriceCents": 33,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "vip_quarterly",
"planName": "VIP Quarterly",
"orderType": "vip_quarterly",
"vipDays": 90,
"dolAmount": null,
"creditBalance": 9000,
"amountCents": 2495,
"originalAmountCents": 4990,
"dailyPriceCents": 28,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "vip_annual",
"planName": "VIP Annual",
"orderType": "vip_annual",
"vipDays": 365,
"dolAmount": null,
"creditBalance": 36000,
"amountCents": 8995,
"originalAmountCents": 17990,
"dailyPriceCents": 25,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "dol_1000",
"planName": "1000 Credits",
"orderType": "dol",
"vipDays": null,
"dolAmount": 1000,
"creditBalance": 1000,
"amountCents": 495,
"originalAmountCents": 990,
"dailyPriceCents": null,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "dol_2000",
"planName": "2000 Credits",
"orderType": "dol",
"vipDays": null,
"dolAmount": 2000,
"creditBalance": 2000,
"amountCents": 845,
"originalAmountCents": 1690,
"dailyPriceCents": null,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "dol_3000",
"planName": "3000 Credits",
"orderType": "dol",
"vipDays": null,
"dolAmount": 3000,
"creditBalance": 3000,
"amountCents": 1145,
"originalAmountCents": 2290,
"dailyPriceCents": null,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "dol_5000",
"planName": "5000 Credits",
"orderType": "dol",
"vipDays": null,
"dolAmount": 5000,
"creditBalance": 5000,
"amountCents": 1745,
"originalAmountCents": 3490,
"dailyPriceCents": null,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
},
{
"planId": "dol_10000",
"planName": "10000 Credits",
"orderType": "dol",
"vipDays": null,
"dolAmount": 10000,
"creditBalance": 10000,
"amountCents": 3245,
"originalAmountCents": 6490,
"dailyPriceCents": null,
"currency": "USD",
"isFirstRechargeOffer": true,
"firstRechargeDiscountPercent": 50,
"promotionType": "first_recharge_half_price"
}
]
}
}
+3
View File
@@ -14,6 +14,9 @@ export const PaymentPlanSchema = z.object({
originalAmountCents: z.number().nullable().default(null), originalAmountCents: z.number().nullable().default(null),
dailyPriceCents: z.number().nullable().default(null), dailyPriceCents: z.number().nullable().default(null),
currency: z.string(), currency: z.string(),
isFirstRechargeOffer: z.boolean().default(false),
firstRechargeDiscountPercent: z.number().nullable().default(null),
promotionType: z.string().nullable().default(null),
}); });
export type PaymentPlanInput = z.input<typeof PaymentPlanSchema>; export type PaymentPlanInput = z.input<typeof PaymentPlanSchema>;
@@ -5,7 +5,15 @@ import { z } from "zod";
import { PaymentPlanSchema } from "./payment_plan"; import { PaymentPlanSchema } from "./payment_plan";
export const FirstRechargeOfferSchema = z.object({
enabled: z.boolean(),
type: z.string(),
discountPercent: z.number(),
});
export const PaymentPlansResponseSchema = z.object({ export const PaymentPlansResponseSchema = z.object({
isFirstRecharge: z.boolean().default(false),
firstRechargeOffer: FirstRechargeOfferSchema.nullable().default(null),
plans: z.array(PaymentPlanSchema), plans: z.array(PaymentPlanSchema),
}); });
@@ -15,3 +23,4 @@ export type PaymentPlansResponseInput = z.input<
export type PaymentPlansResponseData = z.output< export type PaymentPlansResponseData = z.output<
typeof PaymentPlansResponseSchema typeof PaymentPlansResponseSchema
>; >;
export type FirstRechargeOfferData = z.output<typeof FirstRechargeOfferSchema>;
@@ -145,6 +145,52 @@ describe("paymentMachine", () => {
actor.stop(); actor.stop();
}); });
it("keeps first recharge offer metadata from the plans response", async () => {
const actor = createActor(
paymentMachine.provide({
actors: {
loadCachedPlans: fromPromise<PaymentPlansResponse | null>(
async () => null,
),
refreshPlans: fromPromise(async () =>
PaymentPlansResponse.from({
isFirstRecharge: true,
firstRechargeOffer: {
enabled: true,
type: "first_recharge_half_price",
discountPercent: 50,
},
plans: [
{
...monthlyPlan,
amountCents: 995,
originalAmountCents: 1990,
isFirstRechargeOffer: true,
firstRechargeDiscountPercent: 50,
promotionType: "first_recharge_half_price",
},
],
}),
),
},
}),
).start();
actor.send({ type: "PaymentInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
const context = actor.getSnapshot().context;
expect(context.isFirstRecharge).toBe(true);
expect(context.firstRechargeOffer?.discountPercent).toBe(50);
expect(context.plans[0]).toMatchObject({
amountCents: 995,
originalAmountCents: 1990,
isFirstRechargeOffer: true,
});
actor.stop();
});
it("hydrates cached plans before refreshing with network plans", async () => { it("hydrates cached plans before refreshing with network plans", async () => {
let resolveRefresh!: (value: PaymentPlansResponse) => void; let resolveRefresh!: (value: PaymentPlansResponse) => void;
const refreshPlansPromise = new Promise<PaymentPlansResponse>((resolve) => { const refreshPlansPromise = new Promise<PaymentPlansResponse>((resolve) => {
+4
View File
@@ -21,6 +21,8 @@ import type {
export interface PaymentContextState { export interface PaymentContextState {
status: string; status: string;
plans: MachineContext["plans"]; plans: MachineContext["plans"];
isFirstRecharge: MachineContext["isFirstRecharge"];
firstRechargeOffer: MachineContext["firstRechargeOffer"];
selectedPlanId: string; selectedPlanId: string;
payChannel: MachineContext["payChannel"]; payChannel: MachineContext["payChannel"];
autoRenew: boolean; autoRenew: boolean;
@@ -50,6 +52,8 @@ export function PaymentProvider({ children }: PaymentProviderProps) {
() => ({ () => ({
status: String(state.value), status: String(state.value),
plans: state.context.plans, plans: state.context.plans,
isFirstRecharge: state.context.isFirstRecharge,
firstRechargeOffer: state.context.firstRechargeOffer,
selectedPlanId: state.context.selectedPlanId, selectedPlanId: state.context.selectedPlanId,
payChannel: state.context.payChannel, payChannel: state.context.payChannel,
autoRenew: state.context.autoRenew, autoRenew: state.context.autoRenew,
+47 -3
View File
@@ -1,4 +1,4 @@
import type { PaymentPlan } from "@/data/dto/payment"; import type { PaymentPlan, PaymentPlansResponse } from "@/data/dto/payment";
import type { PaymentState } from "./payment-state"; import type { PaymentState } from "./payment-state";
@@ -44,7 +44,10 @@ export function getDefaultPlanId(plans: readonly PaymentPlan[]): string {
export function hydratePlansState( export function hydratePlansState(
plans: PaymentPlan[], plans: PaymentPlan[],
selectedPlanId: string, selectedPlanId: string,
): Pick<PaymentState, "plans" | "selectedPlanId" | "autoRenew" | "errorMessage"> { ): Pick<
PaymentState,
"plans" | "selectedPlanId" | "autoRenew" | "errorMessage"
> {
const nextSelectedPlanId = selectedPlanId || getDefaultPlanId(plans); const nextSelectedPlanId = selectedPlanId || getDefaultPlanId(plans);
return { return {
plans, plans,
@@ -54,10 +57,32 @@ export function hydratePlansState(
}; };
} }
export function hydratePlansResponseState(
response: PaymentPlansResponse,
selectedPlanId: string,
): Pick<
PaymentState,
| "plans"
| "isFirstRecharge"
| "firstRechargeOffer"
| "selectedPlanId"
| "autoRenew"
| "errorMessage"
> {
return {
...hydratePlansState(response.plans, selectedPlanId),
isFirstRecharge: response.isFirstRecharge,
firstRechargeOffer: response.firstRechargeOffer,
};
}
export function refreshPlansState( export function refreshPlansState(
plans: PaymentPlan[], plans: PaymentPlan[],
selectedPlanId: string, selectedPlanId: string,
): Pick<PaymentState, "plans" | "selectedPlanId" | "autoRenew" | "errorMessage"> { ): Pick<
PaymentState,
"plans" | "selectedPlanId" | "autoRenew" | "errorMessage"
> {
const nextSelectedPlanId = plans.some((plan) => plan.planId === selectedPlanId) const nextSelectedPlanId = plans.some((plan) => plan.planId === selectedPlanId)
? selectedPlanId ? selectedPlanId
: getDefaultPlanId(plans); : getDefaultPlanId(plans);
@@ -69,6 +94,25 @@ export function refreshPlansState(
}; };
} }
export function refreshPlansResponseState(
response: PaymentPlansResponse,
selectedPlanId: string,
): Pick<
PaymentState,
| "plans"
| "isFirstRecharge"
| "firstRechargeOffer"
| "selectedPlanId"
| "autoRenew"
| "errorMessage"
> {
return {
...refreshPlansState(response.plans, selectedPlanId),
isFirstRecharge: response.isFirstRecharge,
firstRechargeOffer: response.firstRechargeOffer,
};
}
export function selectPlanState( export function selectPlanState(
planId: string, planId: string,
plans: readonly PaymentPlan[], plans: readonly PaymentPlan[],
+15 -8
View File
@@ -13,9 +13,9 @@ import {
} from "./payment-machine.actors"; } from "./payment-machine.actors";
import { import {
hasOrderPollingTimedOut, hasOrderPollingTimedOut,
hydratePlansState, hydratePlansResponseState,
PAYMENT_TIMEOUT_ERROR_MESSAGE, PAYMENT_TIMEOUT_ERROR_MESSAGE,
refreshPlansState, refreshPlansResponseState,
resetOrderState, resetOrderState,
selectPlanState, selectPlanState,
toPaymentErrorMessage, toPaymentErrorMessage,
@@ -63,8 +63,11 @@ export const paymentMachine = setup({
guard: ({ event }) => (event.output?.plans.length ?? 0) > 0, guard: ({ event }) => (event.output?.plans.length ?? 0) > 0,
target: "refreshingPlans", target: "refreshingPlans",
actions: assign(({ context, event }) => { actions: assign(({ context, event }) => {
const plans = event.output?.plans ?? []; if (!event.output) return {};
return hydratePlansState(plans, context.selectedPlanId); return hydratePlansResponseState(
event.output,
context.selectedPlanId,
);
}), }),
}, },
{ {
@@ -83,8 +86,10 @@ export const paymentMachine = setup({
onDone: { onDone: {
target: "ready", target: "ready",
actions: assign(({ context, event }) => { actions: assign(({ context, event }) => {
const plans = event.output.plans; return hydratePlansResponseState(
return hydratePlansState(plans, context.selectedPlanId); event.output,
context.selectedPlanId,
);
}), }),
}, },
onError: { onError: {
@@ -102,8 +107,10 @@ export const paymentMachine = setup({
onDone: { onDone: {
target: "ready", target: "ready",
actions: assign(({ context, event }) => { actions: assign(({ context, event }) => {
const plans = event.output.plans; return refreshPlansResponseState(
return refreshPlansState(plans, context.selectedPlanId); event.output,
context.selectedPlanId,
);
}), }),
}, },
onError: { onError: {
+5
View File
@@ -2,6 +2,7 @@
* Payment 状态机:State 形状 + 初始值 * Payment 状态机:State 形状 + 初始值
*/ */
import type { import type {
FirstRechargeOffer,
PayChannel, PayChannel,
PaymentOrderStatus, PaymentOrderStatus,
PaymentPlan, PaymentPlan,
@@ -9,6 +10,8 @@ import type {
export interface PaymentState { export interface PaymentState {
plans: PaymentPlan[]; plans: PaymentPlan[];
isFirstRecharge: boolean;
firstRechargeOffer: FirstRechargeOffer | null;
selectedPlanId: string; selectedPlanId: string;
payChannel: PayChannel; payChannel: PayChannel;
autoRenew: boolean; autoRenew: boolean;
@@ -23,6 +26,8 @@ export interface PaymentState {
export const initialState: PaymentState = { export const initialState: PaymentState = {
plans: [], plans: [],
isFirstRecharge: false,
firstRechargeOffer: null,
selectedPlanId: "", selectedPlanId: "",
payChannel: "stripe", payChannel: "stripe",
autoRenew: true, autoRenew: true,