Files
sub2apipay/src/lib/subscription-utils.ts

91 lines
2.9 KiB
TypeScript
Raw Normal View History

export type ValidityUnit = 'day' | 'week' | 'month';
/**
*
* - day: 直接返回
* - week: value * 7
* - month: fromDate value
*/
export function computeValidityDays(value: number, unit: ValidityUnit, fromDate?: Date): number {
if (unit === 'day') return value;
if (unit === 'week') return value * 7;
// month: 计算到 value 个月后同一天的天数差
const from = fromDate ?? new Date();
const target = new Date(from);
target.setMonth(target.getMonth() + value);
return Math.round((target.getTime() - from.getTime()) / (1000 * 60 * 60 * 24));
}
/**
*
* - unit=month, value=1 / Monthly
* - unit=month, value=3 3 / 3 Months
* - unit=week, value=2 2 / 2 Weeks
* - unit=day, value=30 / Monthly ()
* - unit=day, value=90 90 / 90 Days
*/
export function formatValidityLabel(
value: number,
unit: ValidityUnit,
locale: 'zh' | 'en',
): string {
if (unit === 'month') {
if (value === 1) return locale === 'zh' ? '包月' : 'Monthly';
return locale === 'zh' ? `${value}` : `${value} Months`;
}
if (unit === 'week') {
if (value === 1) return locale === 'zh' ? '包周' : 'Weekly';
return locale === 'zh' ? `${value}` : `${value} Weeks`;
}
// day
if (value === 30) return locale === 'zh' ? '包月' : 'Monthly';
return locale === 'zh' ? `${value}` : `${value} Days`;
}
/**
*
* - unit=month, value=1 / / /mo
* - unit=month, value=3 /3 / /3mo
* - unit=week, value=2 /2 / /2wk
* - unit=day, value=30 / / /mo
* - unit=day, value=90 /90 / /90d
*/
export function formatValiditySuffix(
value: number,
unit: ValidityUnit,
locale: 'zh' | 'en',
): string {
if (unit === 'month') {
if (value === 1) return locale === 'zh' ? '/月' : '/mo';
return locale === 'zh' ? `/${value}` : `/${value}mo`;
}
if (unit === 'week') {
if (value === 1) return locale === 'zh' ? '/周' : '/wk';
return locale === 'zh' ? `/${value}` : `/${value}wk`;
}
// day
if (value === 30) return locale === 'zh' ? '/月' : '/mo';
return locale === 'zh' ? `/${value}` : `/${value}d`;
}
/**
*
* - unit=day "30 天"
* - unit=week "2 周"
* - unit=month "1 月"
*/
export function formatValidityDisplay(
value: number,
unit: ValidityUnit,
locale: 'zh' | 'en',
): string {
const unitLabels: Record<ValidityUnit, { zh: string; en: string }> = {
day: { zh: '天', en: 'day(s)' },
week: { zh: '周', en: 'week(s)' },
month: { zh: '月', en: 'month(s)' },
};
const label = locale === 'zh' ? unitLabels[unit].zh : unitLabels[unit].en;
return `${value} ${label}`;
}