Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>` (stored in the same list, `MiniAppUserProgress.OnboardingHintsJson`, without starting the gap). Unknown keys are rejected. |
Expand Down Expand Up @@ -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=<key>`, 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-<yyyy>-<MM>-<slug>`, 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-<yyyy>-<MM>`, `-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`. |
Expand Down
15 changes: 12 additions & 3 deletions src/Application/Admin/BroadcastCampaignService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@ public async Task<IReadOnlyDictionary<BroadcastAudience, int>> CountAudiencesAsy
var users = await LoadReachableUsersAsync(ct);
var now = DateTime.UtcNow;
var lastActive = await LoadLastActivityAsync(ct);
var payers = await LoadPayersAsync(ct);
return Enum.GetValues<BroadcastAudience>()
.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)));
}

/// <summary>
Expand Down Expand Up @@ -242,7 +243,8 @@ public async Task<CampaignPrepareResult> 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<Guid>()
Expand Down Expand Up @@ -670,10 +672,14 @@ private Task<List<User>> LoadReachableUsersAsync(CancellationToken ct) =>
/// same ones the mini-app's paywall uses, so "access ended" here is exactly "sees the paywall".</summary>
/// <param name="lastActive">When each person last did something (<see cref="LoadLastActivityAsync"/>);
/// needed only for the audiences by activity.</param>
/// <param name="payers">Who has a payment that was not refunded; needed only for <see cref="BroadcastAudience.Paid"/>
/// and <see cref="BroadcastAudience.NeverPaid"/>.</param>
public static bool IsIn(
User user, BroadcastAudience audience, DateTime now, long ownerTelegramId,
IReadOnlyDictionary<Guid, DateTime>? lastActive = null) => audience switch
IReadOnlyDictionary<Guid, DateTime>? lastActive = null, IReadOnlySet<Guid>? 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),
Expand All @@ -689,6 +695,9 @@ private static DateTime LastActive(User user, IReadOnlyDictionary<Guid, DateTime

private Task<Dictionary<Guid, DateTime>> LoadLastActivityAsync(CancellationToken ct) => UserActivity.LoadLastAsync(db, ct);

private async Task<IReadOnlySet<Guid>> 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;
}

Expand Down
28 changes: 28 additions & 0 deletions src/Application/MiniApp/PriceSchedule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Application.Common;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace Application.MiniApp;

/// <summary>
/// Prices go up on <see cref="RiseAtUtc"/> — 1 December 2026, 00:00 Tbilisi — from
/// <see cref="SubscriptionPlanInfo.StarsPrice"/> to <see cref="SubscriptionPlans.RaisedPrice"/> (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.
/// </summary>
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;

/// <summary>A payment before the rise that was not refunded — the old prices stay for this person.</summary>
public Task<bool> KeepsOldPricesAsync(ITraleDbContext db, Guid userId, CancellationToken ct) =>
db.Payments.AnyAsync(p => p.UserId == userId && p.RefundedAtUtc == null && p.PurchasedAtUtc < RiseAtUtc, ct);

/// <summary>What this person pays for the plan now.</summary>
public int PriceFor(SubscriptionPlanInfo plan, DateTime nowUtc, bool keepsOldPrices) =>
keepsOldPrices || !HasRisen(nowUtc) ? plan.StarsPrice : SubscriptionPlans.RaisedPrice(plan);
}
13 changes: 13 additions & 0 deletions src/Application/MiniApp/SubscriptionPlans.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ public static class SubscriptionPlans
new(SubscriptionPlan.Lifetime, "Stars_Pro_Lifetime", 1399, null, "Навсегда", "Про-доступ навсегда"),
};

/// <summary>Prices from <see cref="PriceSchedule.RiseAtUtc"/> on, for everyone who has not paid before.</summary>
private static readonly IReadOnlyDictionary<SubscriptionPlan, int> Raised = new Dictionary<SubscriptionPlan, int>
{
[SubscriptionPlan.Month] = 149,
[SubscriptionPlan.Quarter] = 349,
[SubscriptionPlan.HalfYear] = 649,
[SubscriptionPlan.Year] = 1199,
};

/// <summary>The plan's price after the rise; a plan that does not go up keeps its price.</summary>
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);

Expand Down
6 changes: 5 additions & 1 deletion src/Domain/Entities/BroadcastCampaign.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,9 @@ public enum BroadcastAudience
/// <summary>Studied in the last 30 days (a lesson answer, a word added, a quiz or a verb session), or registered within them.</summary>
ActiveLately = 5,
/// <summary>No such trace for more than 30 days.</summary>
InactiveLong = 6
InactiveLong = 6,
/// <summary>Paid at least once (a payment that was not refunded) — not a gift of access.</summary>
Paid = 7,
/// <summary>Never paid; a gift of access does not count as paying.</summary>
NeverPaid = 8
}
21 changes: 17 additions & 4 deletions src/Trale/Controllers/MiniAppController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,24 +178,35 @@ public async Task<IActionResult> GetMe(CancellationToken ct)
}

[HttpGet("plans")]
public async Task<IActionResult> GetPlans(CancellationToken ct)
public async Task<IActionResult> 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
Expand Down Expand Up @@ -244,7 +255,7 @@ public async Task<IActionResult> Refund([FromBody] RefundRequest req, Cancellati
}

[HttpPost("purchase")]
public async Task<IActionResult> Purchase([FromBody] PurchaseRequest req, CancellationToken ct)
public async Task<IActionResult> Purchase([FromBody] PurchaseRequest req, [FromServices] PriceSchedule prices, CancellationToken ct)
{
var user = await ResolveUserAsync(ct);
if (user == null)
Expand All @@ -269,6 +280,8 @@ public async Task<IActionResult> 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(
Expand Down
1 change: 1 addition & 0 deletions src/Trale/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
builder.Services.AddHostedService<ReturnPushWorker>();
builder.Services.AddHostedService<HourlyNotificationWorker>();
builder.Services.AddHostedService<CampaignSendWorker>();
builder.Services.AddSingleton(new Application.MiniApp.PriceSchedule());
builder.Services.AddHostedService<FinishTranslationsOnShutdown>();

// The address is 1402 everywhere (Docker, k8s, the dev bot). A second local instance — the real
Expand Down
2 changes: 2 additions & 0 deletions src/Trale/miniapp-src/src/admin/words.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: 'только я (посмотреть)' }
]

Expand Down
10 changes: 8 additions & 2 deletions src/Trale/miniapp-src/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', {
Expand Down Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions src/Trale/miniapp-src/src/components/ProPaywall.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
Loading
Loading