From 9cca85d20ecfeac24a6eeb5f6e17bba9bb42b802 Mon Sep 17 00:00:00 2001 From: Dmitry Afonchenko Date: Mon, 9 Nov 2026 20:05:01 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A1=201=20=D0=B4=D0=B5=D0=BA=D0=B0=D0=B1?= =?UTF-8?q?=D1=80=D1=8F=20=D1=86=D0=B5=D0=BD=D1=8B=20+~50%,=20=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=20=D0=BF=D0=BB=D0=B0=D1=82=D0=B8=D0=BB=20=E2=80=94=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=81=D1=82=D0=B0=D1=80=D1=8B=D0=BC=20=D0=BD?= =?UTF-8?q?=D0=B0=D0=B2=D1=81=D0=B5=D0=B3=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PriceSchedule: с 30.11 20:00 UTC (1 декабря по Тбилиси) 149/349/649/1199 ⭐ вместо 100/249/449/849, кроме тех, у кого есть невозвращённая оплата до этой даты. /plans отдаёт цену для человека, цену для всех, дату повышения и keepsOldPrices; /purchase выставляет счёт по той же цене. Пейволл до даты говорит, когда вырастут цены, а плативших благодарит. В рассылках — группы «платили хоть раз» и «ни разу не платили» (подаренный доступ — не оплата). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TAcLBj2Fn8nAKE4qWyn5es --- FEATURES.md | 6 +- .../Admin/BroadcastCampaignService.cs | 15 ++- src/Application/MiniApp/PriceSchedule.cs | 28 ++++ src/Application/MiniApp/SubscriptionPlans.cs | 13 ++ src/Domain/Entities/BroadcastCampaign.cs | 6 +- src/Trale/Controllers/MiniAppController.cs | 21 ++- src/Trale/Program.cs | 1 + src/Trale/miniapp-src/src/admin/words.ts | 2 + src/Trale/miniapp-src/src/api.ts | 10 +- .../src/components/ProPaywall.test.tsx | 28 ++++ .../miniapp-src/src/components/ProPaywall.tsx | 30 ++++- .../__tests__/AdminBroadcastScreen.test.tsx | 2 +- .../__tests__/SurveyBuilderScreen.test.tsx | 2 +- .../Admin/BroadcastCampaignTests.cs | 26 ++++ tests/IntegrationTests/DSL/SignedMiniApp.cs | 5 +- .../MiniApp/PriceRiseTests.cs | 125 ++++++++++++++++++ 16 files changed, 303 insertions(+), 17 deletions(-) create mode 100644 src/Application/MiniApp/PriceSchedule.cs create mode 100644 tests/IntegrationTests/MiniApp/PriceRiseTests.cs diff --git a/FEATURES.md b/FEATURES.md index 8f45df5b..fc80ab00 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -238,9 +238,9 @@ Location: `src/Trale/Controllers/`. Routes relative to controller base. Test gre | GET | `/api/miniapp/content` | Module catalog (filtered by user level). | | GET | `/api/miniapp/modules/{moduleId}/lessons/{lessonId}/questions` | Lesson questions. For a caller with trial/Pro each question carries `verb` — the parse (verb, tense, person) of the catalog verb form in its correct answer, else in the built sentence, audio transcript or question text; wrong options are not searched. `null` otherwise and for callers without access. | | GET | `/api/miniapp/me` | Authenticated user profile (isPro, trial, subscription). `uiHintsSeen` lists the one-time interface hints (`ui:…`: rules and first-move hints of verb games, the verb card's person hint, the lesson chip hint) the user has already seen, so they do not come back after a reload or on another device. | -| GET | `/api/miniapp/plans` | Pro plan list with Stars pricing. | +| GET | `/api/miniapp/plans` | Pro plan list with Stars pricing: `stars` — what this person pays now, `regularStars` — the price for everyone after the rise. `PriceSchedule.RiseAtUtc` (1 Dec 2026, 00:00 Tbilisi): from then on 149 / 349 / 649 / 1199 ⭐ instead of 100 / 249 / 449 / 849 for everyone except whoever has a payment before the rise that was not refunded (`keepsOldPrices` — old prices for good, the paywall thanks them). Until the rise `pricesRiseAtUtc` says when, and the paywall tells people to buy at today's price. | | POST | `/api/miniapp/refund` | Refund a Stars payment within the allowed window. | -| POST | `/api/miniapp/purchase` | Create Telegram Stars invoice link. | +| POST | `/api/miniapp/purchase` | Create Telegram Stars invoice link at the price this person pays now (`PriceSchedule.PriceFor`). | | POST | `/api/miniapp/treat` | Feed mascot (spend XP on a treat). | | POST | `/api/miniapp/level` | Persist user level after onboarding. | | POST | `/api/miniapp/onboarding/hint-seen` | Mark a hint as shown: an onboarding step (starts the ~20h gap to the next one) or a one-time interface hint `ui:` (stored in the same list, `MiniAppUserProgress.OnboardingHintsJson`, without starting the gap). Unknown keys are rejected. | @@ -302,7 +302,7 @@ Location: `src/Trale/Controllers/`. Routes relative to controller base. Test gre | POST | `/api/admin/users/{telegramId}/revoke-pro` | Revoke Pro. | | GET | `/api/admin/broadcast/preview` | Preview broadcast target. | | POST | `/api/admin/broadcast` | Send broadcast (one shot: the whole segment inside one request, no pauses, no record of who got it — for small segments only). | -| GET | `/api/admin/campaigns/audiences` | How many reachable people each campaign audience has now: `accessEnded`, `onTrial`, `paying`, `proLapsed`, `owner`, and by activity — `activeLately` / `inactiveLong`: whether the person studied in the last 30 days (a lesson answer, a word added, a quiz or a verb session started; someone with no such trace counts from the day they registered). Reachable = has not blocked the bot and has not turned notifications off. | +| GET | `/api/admin/campaigns/audiences` | How many reachable people each campaign audience has now: `accessEnded`, `onTrial`, `paying`, `proLapsed`, `owner`, and by activity — `activeLately` / `inactiveLong`: whether the person studied in the last 30 days (a lesson answer, a word added, a quiz or a verb session started; someone with no such trace counts from the day they registered); `paid` / `neverPaid` — has a payment that was not refunded (a gift of access is not paying). Reachable = has not blocked the bot and has not turned notifications off. | | POST | `/api/admin/campaigns/prepare` | Pick recipients of a campaign — a random sample of `sampleSize`, or everyone not picked yet — and record them. Sends nothing. `giftDays` (0–30, needs a button) makes the campaign give that many days of access to a recipient who opens its button; `giftOfferDays` (default 14) — for how long after the campaign's creation. `dryRun` (default true) only counts. Repeating never picks a person twice. `survey` (`{intro, questions: [{text, kind: choice | text, options, allowOther}]}`, 1–6 questions, 2–6 options each; the first question has options, 4 at most, because it goes under the message as buttons) makes it a survey: the message is the intro and the first question, a survey without a gift has no mini-app button, and its form cannot change once the campaign exists. A survey with `giftDays` > 0 goes out as its intro (required) with one web-app button `buttonText` (required) that opens the form (`screen=survey&s=`, set by the server — `buttonQuery` is refused); its first question may be of any kind; its gift is given at the end of the form for at least one answer (opening the button gives nothing) and is added on top of the access a person has (`User.ExtendAccessDays`, the referral reward's rule: a running subscription, trial or bonus period is extended from its own end; with no access the days count from the open; lifetime gets nothing) — unlike an ordinary campaign's gift (`User.GiftAccessDays`: days from the open, nothing for access that already runs longer). A gift survey sent to the `owner` audience gives no days. With an empty `key` and `newSurveySlug` the server names a new survey itself — `survey---`, with a number when taken — and returns the key; such a campaign is always a new one. With an empty `key` and `newBroadcast` the server names an ordinary campaign itself (`broadcast--`, `-test` for a trial to oneself). `anotherAudience` adds one more audience to an existing campaign — people already in it are skipped, so the message and the gift reach a person once. | | POST | `/api/admin/campaigns/{key}/send` | Send the next batch (≤100) of picked recipients, 10 messages per second; one of the two things that make a campaign message leave. Blocked users are flagged inactive; on Telegram's 429 the batch stops and says how long to wait. | | POST | `/api/admin/campaigns/{key}/send-all` | The other one: marks the campaign to be sent to everyone picked (`BroadcastCampaigns.SendAllRequestedAtUtc`) — `CampaignSendWorker` sends it batch by batch whether or not the admin page stays open, and the owner gets a bot message when no one is left waiting. Sends nothing itself. The status has `sendingAll`. | diff --git a/src/Application/Admin/BroadcastCampaignService.cs b/src/Application/Admin/BroadcastCampaignService.cs index 53a44e0b..be98a748 100644 --- a/src/Application/Admin/BroadcastCampaignService.cs +++ b/src/Application/Admin/BroadcastCampaignService.cs @@ -62,8 +62,9 @@ public async Task> CountAudiencesAsy var users = await LoadReachableUsersAsync(ct); var now = DateTime.UtcNow; var lastActive = await LoadLastActivityAsync(ct); + var payers = await LoadPayersAsync(ct); return Enum.GetValues() - .ToDictionary(a => a, a => users.Count(u => IsIn(u, a, now, ownerTelegramId, lastActive))); + .ToDictionary(a => a, a => users.Count(u => IsIn(u, a, now, ownerTelegramId, lastActive, payers))); } /// @@ -242,7 +243,8 @@ public async Task PrepareAsync( var now = DateTime.UtcNow; var users = await LoadReachableUsersAsync(ct); var lastActive = await LoadLastActivityAsync(ct); - var audience = users.Where(u => IsIn(u, draft.Audience, now, ownerTelegramId, lastActive)).ToList(); + var payers = await LoadPayersAsync(ct); + var audience = users.Where(u => IsIn(u, draft.Audience, now, ownerTelegramId, lastActive, payers)).ToList(); var alreadyPicked = campaign == null ? new HashSet() @@ -670,10 +672,14 @@ private Task> LoadReachableUsersAsync(CancellationToken ct) => /// same ones the mini-app's paywall uses, so "access ended" here is exactly "sees the paywall". /// When each person last did something (); /// needed only for the audiences by activity. + /// Who has a payment that was not refunded; needed only for + /// and . public static bool IsIn( User user, BroadcastAudience audience, DateTime now, long ownerTelegramId, - IReadOnlyDictionary? lastActive = null) => audience switch + IReadOnlyDictionary? lastActive = null, IReadOnlySet? payers = null) => audience switch { + BroadcastAudience.Paid => payers?.Contains(user.Id) == true, + BroadcastAudience.NeverPaid => payers?.Contains(user.Id) == false, BroadcastAudience.ActiveLately => LastActive(user, lastActive) > now.AddDays(-ActivityWindowDays), BroadcastAudience.InactiveLong => LastActive(user, lastActive) <= now.AddDays(-ActivityWindowDays), BroadcastAudience.AccessEnded => !user.IsPro && !user.HasActiveTrial(now), @@ -689,6 +695,9 @@ private static DateTime LastActive(User user, IReadOnlyDictionary> LoadLastActivityAsync(CancellationToken ct) => UserActivity.LoadLastAsync(db, ct); + private async Task> LoadPayersAsync(CancellationToken ct) => + (await db.Payments.AsNoTracking().Where(p => p.RefundedAtUtc == null).Select(p => p.UserId).Distinct().ToListAsync(ct)).ToHashSet(); + private static string? Trim(string? error) => error is { Length: > 500 } ? error[..500] : error; } diff --git a/src/Application/MiniApp/PriceSchedule.cs b/src/Application/MiniApp/PriceSchedule.cs new file mode 100644 index 00000000..a3056b25 --- /dev/null +++ b/src/Application/MiniApp/PriceSchedule.cs @@ -0,0 +1,28 @@ +using Application.Common; +using Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Application.MiniApp; + +/// +/// Prices go up on — 1 December 2026, 00:00 Tbilisi — from +/// to (about +50%). +/// Whoever paid before that keeps the old prices for good: a thank-you to the first buyers. +/// Until the rise everybody pays the old prices and the paywall says when they go up. +/// +public class PriceSchedule +{ + public static readonly DateTime DefaultRiseAtUtc = new(2026, 11, 30, 20, 0, 0, DateTimeKind.Utc); + + public DateTime RiseAtUtc { get; init; } = DefaultRiseAtUtc; + + public bool HasRisen(DateTime nowUtc) => nowUtc >= RiseAtUtc; + + /// A payment before the rise that was not refunded — the old prices stay for this person. + public Task KeepsOldPricesAsync(ITraleDbContext db, Guid userId, CancellationToken ct) => + db.Payments.AnyAsync(p => p.UserId == userId && p.RefundedAtUtc == null && p.PurchasedAtUtc < RiseAtUtc, ct); + + /// What this person pays for the plan now. + public int PriceFor(SubscriptionPlanInfo plan, DateTime nowUtc, bool keepsOldPrices) => + keepsOldPrices || !HasRisen(nowUtc) ? plan.StarsPrice : SubscriptionPlans.RaisedPrice(plan); +} diff --git a/src/Application/MiniApp/SubscriptionPlans.cs b/src/Application/MiniApp/SubscriptionPlans.cs index ff5a508b..29c35973 100644 --- a/src/Application/MiniApp/SubscriptionPlans.cs +++ b/src/Application/MiniApp/SubscriptionPlans.cs @@ -39,6 +39,19 @@ public static class SubscriptionPlans new(SubscriptionPlan.Lifetime, "Stars_Pro_Lifetime", 1399, null, "Навсегда", "Про-доступ навсегда"), }; + /// Prices from on, for everyone who has not paid before. + private static readonly IReadOnlyDictionary Raised = new Dictionary + { + [SubscriptionPlan.Month] = 149, + [SubscriptionPlan.Quarter] = 349, + [SubscriptionPlan.HalfYear] = 649, + [SubscriptionPlan.Year] = 1199, + }; + + /// The plan's price after the rise; a plan that does not go up keeps its price. + public static int RaisedPrice(SubscriptionPlanInfo plan) => + Raised.TryGetValue(plan.Plan, out var stars) ? stars : plan.StarsPrice; + public static SubscriptionPlanInfo? ByPayload(string payload) => Known.FirstOrDefault(p => p.PayloadId == payload); diff --git a/src/Domain/Entities/BroadcastCampaign.cs b/src/Domain/Entities/BroadcastCampaign.cs index 4ceb6fe6..f6b691c2 100644 --- a/src/Domain/Entities/BroadcastCampaign.cs +++ b/src/Domain/Entities/BroadcastCampaign.cs @@ -84,5 +84,9 @@ public enum BroadcastAudience /// Studied in the last 30 days (a lesson answer, a word added, a quiz or a verb session), or registered within them. ActiveLately = 5, /// No such trace for more than 30 days. - InactiveLong = 6 + InactiveLong = 6, + /// Paid at least once (a payment that was not refunded) — not a gift of access. + Paid = 7, + /// Never paid; a gift of access does not count as paying. + NeverPaid = 8 } diff --git a/src/Trale/Controllers/MiniAppController.cs b/src/Trale/Controllers/MiniAppController.cs index cf9ae45e..101030cf 100644 --- a/src/Trale/Controllers/MiniAppController.cs +++ b/src/Trale/Controllers/MiniAppController.cs @@ -178,24 +178,35 @@ public async Task GetMe(CancellationToken ct) } [HttpGet("plans")] - public async Task GetPlans(CancellationToken ct) + public async Task GetPlans([FromServices] PriceSchedule prices, CancellationToken ct) { // Resolve caller so whitelisted test users see the 1⭐ test price in the // plan cards, matching what Purchase() will then charge them. Anonymous / // unresolved callers fall through to normal SubscriptionPlans prices. var user = await ResolveUserAsync(ct); var applyTestPricing = user != null && TestPricingTelegramIds.Contains(user.TelegramId); + var keepsOldPrices = user != null && await prices.KeepsOldPricesAsync(_dbContext, user.Id, ct); + var now = DateTime.UtcNow; var plans = SubscriptionPlans.All.Select(p => new { id = p.Plan.ToString(), payloadId = p.PayloadId, - stars = applyTestPricing ? TestPricingStars : p.StarsPrice, + stars = applyTestPricing ? TestPricingStars : prices.PriceFor(p, now, keepsOldPrices), + // The price for everyone after the rise — a card shows it crossed out when this person pays less. + regularStars = SubscriptionPlans.RaisedPrice(p), durationDays = p.DurationDays, title = p.Title, description = p.Description }); - return Ok(new { plans }); + return Ok(new + { + plans, + // Until the rise — when prices go up; null after it. + pricesRiseAtUtc = prices.HasRisen(now) ? (DateTime?)null : prices.RiseAtUtc, + // Paid before the rise: the old prices stay for good, and the paywall thanks them. + keepsOldPrices + }); } public class PurchaseRequest @@ -244,7 +255,7 @@ public async Task Refund([FromBody] RefundRequest req, Cancellati } [HttpPost("purchase")] - public async Task Purchase([FromBody] PurchaseRequest req, CancellationToken ct) + public async Task Purchase([FromBody] PurchaseRequest req, [FromServices] PriceSchedule prices, CancellationToken ct) { var user = await ResolveUserAsync(ct); if (user == null) @@ -269,6 +280,8 @@ public async Task Purchase([FromBody] PurchaseRequest req, Cancel return BadRequest(new { error = "invalid_plan" }); } + plan = plan with { StarsPrice = prices.PriceFor(plan, DateTime.UtcNow, await prices.KeepsOldPricesAsync(_dbContext, user.Id, ct)) }; + if (TestPricingTelegramIds.Contains(user.TelegramId)) { _logger.LogWarning( diff --git a/src/Trale/Program.cs b/src/Trale/Program.cs index 77cb0dab..8bcd036b 100644 --- a/src/Trale/Program.cs +++ b/src/Trale/Program.cs @@ -48,6 +48,7 @@ builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +builder.Services.AddSingleton(new Application.MiniApp.PriceSchedule()); builder.Services.AddHostedService(); // The address is 1402 everywhere (Docker, k8s, the dev bot). A second local instance — the real diff --git a/src/Trale/miniapp-src/src/admin/words.ts b/src/Trale/miniapp-src/src/admin/words.ts index 9e41fbaf..9fbb21e9 100644 --- a/src/Trale/miniapp-src/src/admin/words.ts +++ b/src/Trale/miniapp-src/src/admin/words.ts @@ -9,6 +9,8 @@ export const AUDIENCES: { id: CampaignAudience; name: string }[] = [ { id: 'proLapsed', name: 'подписка закончилась' }, { id: 'activeLately', name: 'занимались за последние 30 дней' }, { id: 'inactiveLong', name: 'не занимались больше 30 дней' }, + { id: 'paid', name: 'платили хоть раз' }, + { id: 'neverPaid', name: 'ни разу не платили' }, { id: 'owner', name: 'только я (посмотреть)' } ] diff --git a/src/Trale/miniapp-src/src/api.ts b/src/Trale/miniapp-src/src/api.ts index 061356f3..e332f8e5 100644 --- a/src/Trale/miniapp-src/src/api.ts +++ b/src/Trale/miniapp-src/src/api.ts @@ -244,10 +244,16 @@ export const api = { id: string payloadId: string stars: number + /** Цена для всех после повышения; карточка зачёркивает её, когда этот человек платит меньше. */ + regularStars?: number durationDays: number | null title: string description: string - }> }>('/api/miniapp/plans'), + }> + /** До повышения — когда цены вырастут; после — null. */ + pricesRiseAtUtc?: string | null + /** Платил до повышения: старые цены навсегда. */ + keepsOldPrices?: boolean }>('/api/miniapp/plans'), purchase: (plan: string) => request<{ ok: boolean; alreadyPro?: boolean; invoiceLink?: string }>('/api/miniapp/purchase', { @@ -564,7 +570,7 @@ export interface FeedbackOptionCount { count: number } -export type CampaignAudience = 'accessEnded' | 'onTrial' | 'paying' | 'proLapsed' | 'owner' | 'activeLately' | 'inactiveLong' +export type CampaignAudience = 'accessEnded' | 'onTrial' | 'paying' | 'proLapsed' | 'owner' | 'activeLately' | 'inactiveLong' | 'paid' | 'neverPaid' export interface CampaignStatusDto { key: string diff --git a/src/Trale/miniapp-src/src/components/ProPaywall.test.tsx b/src/Trale/miniapp-src/src/components/ProPaywall.test.tsx index 51f6d935..5656e15e 100644 --- a/src/Trale/miniapp-src/src/components/ProPaywall.test.tsx +++ b/src/Trale/miniapp-src/src/components/ProPaywall.test.tsx @@ -116,3 +116,31 @@ describe('ProPaywall — «Что смутило?»', () => { expect(feedback.paywallQuestion).not.toHaveBeenCalled() }) }) + +describe('ProPaywall — повышение цен', () => { + const month = (stars: number, regularStars: number) => + ({ id: 'Month', payloadId: 'Stars_Pro_Month', stars, regularStars, durationDays: 30, title: '1 месяц', description: '30 дней' }) + + it('before the rise says when prices go up and what the month will cost', async () => { + api.plans.mockResolvedValue({ plans: [month(100, 149)], pricesRiseAtUtc: '2026-11-30T20:00:00Z', keepsOldPrices: false } as never) + await open() + expect(screen.getByTestId('paywall-price-rise').textContent).toBe('С 1 декабря цены вырастут. Купи сейчас — заплатишь по нынешней цене.') + expect(screen.getByText(/с 1 декабря — 149 ⭐/)).toBeTruthy() + }) + + it('thanks whoever paid before and shows their old price under the crossed-out new one', async () => { + api.plans.mockResolvedValue({ plans: [month(100, 149)], pricesRiseAtUtc: null, keepsOldPrices: true } as never) + await open() + expect(screen.getByTestId('paywall-price-thanks').textContent).toContain('Для тебя цены не вырастут — навсегда') + expect(screen.getByTestId('paywall-regular-price').textContent).toBe('149 ⭐') + expect(screen.queryByTestId('paywall-price-rise')).toBeNull() + }) + + it('after the rise a new buyer just sees the price', async () => { + api.plans.mockResolvedValue({ plans: [month(149, 149)], pricesRiseAtUtc: null, keepsOldPrices: false } as never) + await open() + expect(screen.queryByTestId('paywall-price-thanks')).toBeNull() + expect(screen.queryByTestId('paywall-price-rise')).toBeNull() + expect(screen.queryByTestId('paywall-regular-price')).toBeNull() + }) +}) diff --git a/src/Trale/miniapp-src/src/components/ProPaywall.tsx b/src/Trale/miniapp-src/src/components/ProPaywall.tsx index cc824956..52c9f7fc 100644 --- a/src/Trale/miniapp-src/src/components/ProPaywall.tsx +++ b/src/Trale/miniapp-src/src/components/ProPaywall.tsx @@ -17,6 +17,7 @@ interface Plan { id: string payloadId: string stars: number + regularStars?: number durationDays: number | null title: string description: string @@ -30,6 +31,13 @@ const QUESTION_WAIT_MS = 2000 // Default/recommended plan highlighted first by the UI. const RECOMMENDED_PLAN = 'Year' +const MONTHS = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'] +/** «1 декабря» — день по Тбилиси (UTC+4, без перехода на летнее время). */ +export function tbilisiDay(utc: string): string { + const d = new Date(new Date(utc).getTime() + 4 * 3600_000) + return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}` +} + /** * Pro paywall bottom sheet with tier selection. * Opens Telegram Stars invoice natively inside the mini-app via @@ -40,6 +48,8 @@ export default function ProPaywall({ trigger, onClose, onPurchaseSuccess }: Prop const [state, setState] = useState('loading-plans') const [plans, setPlans] = useState([]) const [selectedPlan, setSelectedPlan] = useState(RECOMMENDED_PLAN) + const [riseAt, setRiseAt] = useState(null) + const [keepsOldPrices, setKeepsOldPrices] = useState(false) // «Что смутило?»: сервер заранее говорит, есть ли что спросить, если шторку закроют не купив, // — тогда закрытие не ждёт ответа сети, когда спрашивать нечего. Сам показ сервер запоминает при закрытии. const questionDue = useRef(false) @@ -63,6 +73,8 @@ export default function ProPaywall({ trigger, onClose, onPurchaseSuccess }: Prop .plans() .then((r) => { setPlans(r.plans) + setRiseAt(r.pricesRiseAtUtc ?? null) + setKeepsOldPrices(r.keepsOldPrices === true) setState('default') if (!r.plans.some((p) => p.id === RECOMMENDED_PLAN) && r.plans.length > 0) { setSelectedPlan(r.plans[0].id) @@ -337,6 +349,17 @@ export default function ProPaywall({ trigger, onClose, onPurchaseSuccess }: Prop ))} + {/* Цены: благодарность тем, кто уже платил, или когда цены вырастут */} + {keepsOldPrices ? ( +
+ Спасибо, что ты с нами с самого начала! Для тебя цены не вырастут — навсегда. +
+ ) : riseAt ? ( +
+ С {tbilisiDay(riseAt)} цены вырастут. Купи сейчас — заплатишь по нынешней цене. +
+ ) : null} + {/* Plans */}
{plans.map((p) => { @@ -365,9 +388,14 @@ export default function ProPaywall({ trigger, onClose, onPurchaseSuccess }: Prop
{p.title}
{perMonthLabel(p)} + {riseAt && !keepsOldPrices && p.regularStars && p.regularStars > p.stars + ? ` · с ${tbilisiDay(riseAt)} — ${p.regularStars} ⭐` : ''}
-
+
+ {!riseAt && p.regularStars && p.regularStars > p.stars && ( + {p.regularStars} ⭐ + )} {p.stars} ⭐
diff --git a/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx b/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx index 16418ef2..731923cc 100644 --- a/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx +++ b/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx @@ -25,7 +25,7 @@ let navigate: Mock<(s: Screen) => void> let confirm: Mock<(text: string) => boolean> beforeEach(() => { Object.values(api).forEach(f => f.mockReset()) - api.audiences.mockResolvedValue({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512 }) + api.audiences.mockResolvedValue({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512, paid: 8, neverPaid: 565 }) navigate = vi.fn<(s: Screen) => void>() confirm = vi.fn<(text: string) => boolean>(() => true) vi.stubGlobal('confirm', confirm) diff --git a/src/Trale/miniapp-src/src/screens/__tests__/SurveyBuilderScreen.test.tsx b/src/Trale/miniapp-src/src/screens/__tests__/SurveyBuilderScreen.test.tsx index fff1cbd2..518add97 100644 --- a/src/Trale/miniapp-src/src/screens/__tests__/SurveyBuilderScreen.test.tsx +++ b/src/Trale/miniapp-src/src/screens/__tests__/SurveyBuilderScreen.test.tsx @@ -61,7 +61,7 @@ let navigate: Mock<(s: Screen) => void> beforeEach(() => { ;[...Object.values(campaigns), ...Object.values(surveys), ...Object.values(feedback)].forEach(f => (f as ReturnType).mockReset()) surveys.presets.mockResolvedValue(kit) - campaigns.audiences.mockResolvedValue({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512 }) + campaigns.audiences.mockResolvedValue({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512, paid: 8, neverPaid: 565 }) feedback.overview.mockResolvedValue(listed([])) navigate = vi.fn<(s: Screen) => void>() window.scrollTo = vi.fn() as never diff --git a/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs b/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs index 0fdaf62a..5c1daf6f 100644 --- a/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs +++ b/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs @@ -517,6 +517,32 @@ public async Task Rejected_by_telegram_is_recorded_with_the_reason() row.Error.Should().Be("400: chat not found"); } + [Test] + public async Task Paid_means_a_real_payment_not_a_gift_of_access() + { + var payers = await AccessEnded(2); + await AddUsers(3, 100, u => { u.IsPro = true; u.SubscriptionPlan = SubscriptionPlan.Month; u.SubscribedUntil = DateTime.UtcNow.AddDays(9); }); // gifted + var refunded = await AccessEnded(1); + await InScope(async sp => + { + var db = sp.GetRequiredService(); + foreach (var (user, refundedAt) in payers.Select(u => (u, (DateTime?)null)).Append((refunded[0], DateTime.UtcNow))) + db.Payments.Add(new Payment + { + Id = Guid.NewGuid(), UserId = user.Id, TelegramPaymentChargeId = Guid.NewGuid().ToString(), PayloadId = "Stars_Pro_Month", + Plan = SubscriptionPlan.Month, Amount = 100, Currency = "XTR", PurchasedAtUtc = DateTime.UtcNow.AddDays(-40), RefundedAtUtc = refundedAt + }); + return await db.SaveChangesAsync(CancellationToken.None); + }); + + var (_, counts) = await Call(HttpMethod.Get, "campaigns/audiences"); + + counts.GetProperty("paid").GetInt32().Should().Be(2); + counts.GetProperty("neverPaid").GetInt32().Should().Be(5, "the owner, three with gifted access and one refunded"); + await Prepare("thanks", "paid", sampleSize: null); + (await Deliveries("thanks")).Select(d => d.UserId).Should().BeEquivalentTo(payers.Select(u => u.Id)); + } + // ── Sent by the server ─────────────────────────────────────────────────── private Task RoundWith(ICampaignMessageSender sender) => InScope(sp => diff --git a/tests/IntegrationTests/DSL/SignedMiniApp.cs b/tests/IntegrationTests/DSL/SignedMiniApp.cs index 77a5baad..51d0ffb2 100644 --- a/tests/IntegrationTests/DSL/SignedMiniApp.cs +++ b/tests/IntegrationTests/DSL/SignedMiniApp.cs @@ -19,7 +19,8 @@ public static class SignedMiniApp private const string Token = "integration-test-token"; public const string Host = "https://test.tralebot.example"; - public static TraleTestApplication WithSignedLogin(this TraleTestApplication app, long ownerTelegramId) + /// Last word on the services, after the signed-login defaults. + public static TraleTestApplication WithSignedLogin(this TraleTestApplication app, long ownerTelegramId, Action? configure = null) { using var scope = app.Services.CreateScope(); var connectionString = scope.ServiceProvider.GetRequiredService().Database.GetConnectionString()!; @@ -44,6 +45,8 @@ public static TraleTestApplication WithSignedLogin(this TraleTestApplication app { services.Remove(worker); } + + configure?.Invoke(services); }); } diff --git a/tests/IntegrationTests/MiniApp/PriceRiseTests.cs b/tests/IntegrationTests/MiniApp/PriceRiseTests.cs new file mode 100644 index 00000000..b8fd7f16 --- /dev/null +++ b/tests/IntegrationTests/MiniApp/PriceRiseTests.cs @@ -0,0 +1,125 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Application.Common; +using Application.MiniApp; +using Domain.Entities; +using FluentAssertions; +using IntegrationTests.DSL; +using IntegrationTests.Fakes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Telegram.Bot; +using Telegram.Bot.Requests; + +namespace IntegrationTests.MiniApp; + +/// +/// Prices go up on a set day for everyone who has not paid before; until then the paywall says when, and +/// whoever paid before keeps the old prices for good — both in the cards and in the invoice. +/// +public class PriceRiseTests : TestBase +{ + private const long Owner = 4_000_000_101; + private static long _nextTelegramId = 6_100_000_000; + + private TraleTestApplication App(DateTime riseAtUtc) => _testServer.WithSignedLogin(Owner, services => + { + services.RemoveAll(); + services.AddSingleton(new PriceSchedule { RiseAtUtc = riseAtUtc }); + }); + + private static async Task NewUser(TraleTestApplication app, DateTime? paidAt = null, bool refunded = false) + { + await using var scope = app.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = Create.User(Interlocked.Increment(ref _nextTelegramId), "Buyer"); + user.RegisteredAtUtc = DateTime.UtcNow.AddDays(-200); + db.Users.Add(user); + if (paidAt != null) + db.Payments.Add(new Payment + { + Id = Guid.NewGuid(), UserId = user.Id, TelegramPaymentChargeId = Guid.NewGuid().ToString(), + PayloadId = "Stars_Pro_Month", Plan = SubscriptionPlan.Month, Amount = 100, Currency = "XTR", + PurchasedAtUtc = paidAt.Value, RefundedAtUtc = refunded ? paidAt.Value.AddDays(1) : null + }); + await db.SaveChangesAsync(CancellationToken.None); + return user; + } + + private static async Task Plans(TraleTestApplication app, User user) + { + using var client = app.ClientFor(user.TelegramId); + return await client.GetFromJsonAsync("/api/miniapp/plans"); + } + + private static int Stars(JsonElement plans, string plan) => + plans.GetProperty("plans").EnumerateArray().Single(p => p.GetProperty("id").GetString() == plan).GetProperty("stars").GetInt32(); + + private static async Task InvoiceStars(TraleTestApplication app, User user, string plan) + { + var telegram = (TelegramClientFake)app.Services.GetRequiredService(); + var mark = telegram.Requests.Count; + using var client = app.ClientFor(user.TelegramId); + (await client.PostAsJsonAsync("/api/miniapp/purchase", new { plan })).EnsureSuccessStatusCode(); + return telegram.Requests.Skip(mark).OfType().Single().Prices.Single().Amount; + } + + [Test] + public async Task Before_the_rise_everyone_pays_the_old_price_and_hears_when_it_goes_up() + { + var riseAt = DateTime.UtcNow.AddDays(10); + await using var app = App(riseAt); + var user = await NewUser(app); + + var plans = await Plans(app, user); + + Stars(plans, "Month").Should().Be(100); + Stars(plans, "Year").Should().Be(849); + plans.GetProperty("plans")[0].GetProperty("regularStars").GetInt32().Should().Be(149); + plans.GetProperty("pricesRiseAtUtc").GetDateTime().Should().BeCloseTo(riseAt, TimeSpan.FromSeconds(1)); + plans.GetProperty("keepsOldPrices").GetBoolean().Should().BeFalse(); + (await InvoiceStars(app, user, "Quarter")).Should().Be(249); + } + + [Test] + public async Task After_the_rise_a_new_buyer_pays_the_new_price() + { + await using var app = App(DateTime.UtcNow.AddDays(-1)); + var user = await NewUser(app); + + var plans = await Plans(app, user); + + Stars(plans, "Month").Should().Be(149); + Stars(plans, "Quarter").Should().Be(349); + Stars(plans, "HalfYear").Should().Be(649); + Stars(plans, "Year").Should().Be(1199); + plans.GetProperty("pricesRiseAtUtc").ValueKind.Should().Be(JsonValueKind.Null); + (await InvoiceStars(app, user, "Year")).Should().Be(1199); + } + + [Test] + public async Task Whoever_paid_before_the_rise_keeps_the_old_prices_for_good() + { + var riseAt = DateTime.UtcNow.AddDays(-1); + await using var app = App(riseAt); + var loyal = await NewUser(app, paidAt: riseAt.AddDays(-30)); + + var plans = await Plans(app, loyal); + + plans.GetProperty("keepsOldPrices").GetBoolean().Should().BeTrue(); + Stars(plans, "Month").Should().Be(100); + (await InvoiceStars(app, loyal, "Quarter")).Should().Be(249); + } + + [Test] + public async Task A_refunded_payment_or_one_after_the_rise_does_not_keep_the_old_prices() + { + var riseAt = DateTime.UtcNow.AddDays(-5); + await using var app = App(riseAt); + var refunded = await NewUser(app, paidAt: riseAt.AddDays(-30), refunded: true); + var paidAfter = await NewUser(app, paidAt: riseAt.AddDays(1)); + + Stars(await Plans(app, refunded), "Month").Should().Be(149); + Stars(await Plans(app, paidAfter), "Month").Should().Be(149); + } +}