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
2 changes: 1 addition & 1 deletion FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ Validation: loader logs a warning and skips any sentence-builder question whose
- `FeedTreatService` — buy & feed a treat
- `AchievementsService` / `GetAchievementsQuery` — achievements
- `DailyReturnNotificationService` — D1+ return push, picks least-progressed module, claim-before-send (#940); leaves people in their first 8 days to `FirstWeekNudgeService` (once that is switched on)
- `FirstWeekNudgeService` — days 1, 3 and 7 after registration, at about the hour of joining: a message with the next lesson (title and goal from `IMiniAppContentProvider.LessonOrder` — the mini-app's order, Georgian with Cyrillic reading) of the module gone furthest in (the alphabet's first lesson if none is finished) and a button straight into it (`src=push_first_week_d<n>`). Only to those who opened the mini-app and have not studied in the last 20 h; skips blocked users and those with notifications off; a day missed by more than a day is skipped. Only people registered after it was switched on (marker `first_week_switched_on`). Once per day and person: triggers `first_week_d1` / `_d3` / `_d7` never expire
- `FirstWeekNudgeService` — days 1, 3 and 7 after registration, at about the hour of joining: a message with the next lesson (title and goal from `IMiniAppContentProvider.LessonOrder` — the mini-app's order, Georgian with Cyrillic reading) of the module gone furthest in (the alphabet's first lesson if none is finished) and a button straight into it (`src=push_first_week_d<n>`). Only to those who opened the mini-app and have not studied in the last 20 h; skips blocked users and those with notifications off; a day missed by more than a day is skipped. Only people registered after it was switched on (marker `first_week_switched_on`). Once per day and person: triggers `first_week_d1` / `_d3` / `_d7` never expire. On day 7 whoever studies in earnest (`EngagedOffer`: ≥5 finished lessons, onboarding not counted, on ≥2 different days; no payment, no running Pro) gets the offer of the old prices instead of the day-7 message, however recently they studied: trigger `engaged_offer`; after the rise the old prices hold for this person for 72 h (`PriceSchedule.OfferEndsAtAsync` — `/plans` returns `offerEndsAtUtc`, `/purchase` charges the old price, the paywall says until when; message and button say «сниженная цена»); before the rise the message says that buying before it keeps the old prices for good. Button opens the paywall (`?paywall=1&src=push_engaged_offer`)
- `StreakNotificationService` — streak-milestone push at exact 7 / 30 / 100 days; per-milestone `streak_{n}` trigger (epic #894, §82, #995)
- `FirstOpenReminderService` — one reminder from Bombora to a newcomer who started the bot and has not opened the mini-app (no `MiniAppUserProgress` row) 24–72h after registration; same single button as the first message. Skips blocked users and those with notifications off. Only people registered after the reminder was first switched on (marker row `first_open_reminder_switched_on` in `NotificationTriggers`) — never the older base. Once per person: the `first_open_reminder` trigger never expires
- `CoinsNotificationService` — coins-stale push when ≥50 spendable XP + no feeding in 7d; 7-day cooldown via `coins` trigger (epic #894, §82, #994)
Expand Down
6 changes: 6 additions & 0 deletions src/Application/Common/Interfaces/IUserNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,11 @@ Task SendReferralBonusGrantedAsync(
/// A first-week message (see <c>FirstWeekNudgeService</c>): the text and one web-app button straight into
/// the lesson, tagged <c>src=push_first_week_d&lt;day&gt;</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
/// <summary>
/// The day-7 offer of the old prices (see <c>EngagedOffer</c>): the text and one web-app button that opens the
/// paywall, tagged <c>src=push_engaged_offer</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
Task SendEngagedOfferAsync(User user, string text, string button, CancellationToken ct);

Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct);
}
61 changes: 61 additions & 0 deletions src/Application/MiniApp/EngagedOffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Domain.Entities;

namespace Application.MiniApp;

/// <summary>
/// The day-7 message to a newcomer who studies in earnest: the old prices — until the rise for everyone,
/// after it for this person for <see cref="PriceSchedule.OfferLasts"/>. Paid days start after the free ones,
/// so buying early loses nothing.
/// </summary>
public static class EngagedOffer
{
/// <summary>Lessons finished in the first week, on at least <see cref="MinDays"/> different days.</summary>
public const int MinLessons = 5;
public const int MinDays = 2;

private static readonly string[] Months =
["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];

/// <summary>«1 декабря» / «12 декабря, 18:00» — Tbilisi time (UTC+4, no daylight saving).</summary>
public static string TbilisiDate(DateTime utc, bool withTime = false)
{
var t = utc.AddHours(4);
return withTime ? $"{t.Day} {Months[t.Month - 1]}, {t:HH:mm}" : $"{t.Day} {Months[t.Month - 1]}";
}

public static string Button(DateTime nowUtc, PriceSchedule prices) =>
prices.HasRisen(nowUtc) ? "Купить по сниженной цене" : "Купить по старой цене";

public static string Text(int lessons, DateTime nowUtc, PriceSchedule prices)
{
var quarter = SubscriptionPlans.ByPlan(SubscriptionPlan.Quarter)!;
var year = SubscriptionPlans.ByPlan(SubscriptionPlan.Year)!;
var head = $"Уроков за неделю: {lessons} — ты занимаешься всерьёз 💪";
const string freeDays = "Бесплатные дни не сгорят: оплаченный срок начнётся после них.";

if (!prices.HasRisen(nowUtc))
return $"""
{head}

С {TbilisiDate(prices.RiseAtUtc)} цены вырастут, а пока:
• 3 месяца — {quarter.StarsPrice} ⭐ (потом {SubscriptionPlans.RaisedPrice(quarter)} ⭐)
• год — {year.StarsPrice} ⭐ (потом {SubscriptionPlans.RaisedPrice(year)} ⭐)

Кто купит до {TbilisiDate(prices.RiseAtUtc)}, будет продлевать по этой цене и дальше — навсегда. {freeDays}

Купи сейчас — кнопка ниже.
""";

return $"""
{head}

Специально для тебя — сниженная цена на 72 часа, до {TbilisiDate(nowUtc + PriceSchedule.OfferLasts, withTime: true)} по Тбилиси:
• 3 месяца — {quarter.StarsPrice} ⭐ вместо {SubscriptionPlans.RaisedPrice(quarter)} ⭐
• год — {year.StarsPrice} ⭐ вместо {SubscriptionPlans.RaisedPrice(year)} ⭐

{freeDays}

Купи сейчас по сниженной цене — кнопка ниже.
""";
}
}
17 changes: 17 additions & 0 deletions src/Application/MiniApp/PriceSchedule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ namespace Application.MiniApp;
/// <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.
/// A newcomer who studies in earnest gets the old prices for <see cref="OfferLasts"/> on day 7
/// (<see cref="Notifications.FirstWeekNudgeService"/>, trigger <see cref="OfferSource"/>).
/// </summary>
public class PriceSchedule
{
Expand All @@ -18,6 +20,21 @@ public class PriceSchedule

public bool HasRisen(DateTime nowUtc) => nowUtc >= RiseAtUtc;

/// <summary>The offer of the old prices to a newcomer who studies in earnest; its trigger row's
/// <c>LastSentAt</c> is when it was made.</summary>
public const string OfferSource = "engaged_offer";
public static readonly TimeSpan OfferLasts = TimeSpan.FromHours(72);

/// <summary>Until when this person's offer of the old prices runs; null — no offer running.</summary>
public async Task<DateTime?> OfferEndsAtAsync(ITraleDbContext db, long telegramId, DateTime nowUtc, CancellationToken ct)
{
var madeAt = await db.NotificationTriggers
.Where(t => t.UserId == telegramId && t.Source == OfferSource)
.Select(t => (DateTime?)t.LastSentAt)
.FirstOrDefaultAsync(ct);
return madeAt is { } at && at + OfferLasts > nowUtc ? at + OfferLasts : null;
}

/// <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);
Expand Down
42 changes: 42 additions & 0 deletions src/Application/Notifications/FirstWeekNudgeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Application.Common;
using Application.Common.Interfaces;
using Application.Common.Interfaces.MiniApp;
using Application.MiniApp;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
Expand All @@ -19,6 +20,10 @@ namespace Application.Notifications;
/// the existing base gets nothing. While someone is in their first week, <see cref="DailyReturnNotificationService"/>
/// leaves them to these messages.
///
/// On day 7 whoever studies in earnest — <see cref="EngagedOffer.MinLessons"/> lessons on <see cref="EngagedOffer.MinDays"/>
/// different days, no payment, no running Pro — gets the offer of the old prices (<see cref="EngagedOffer"/>,
/// trigger <see cref="PriceSchedule.OfferSource"/>) instead of the day-7 message, whenever they last studied.
///
/// Once per day and person: the trigger <c>first_week_d1</c> / <c>_d3</c> / <c>_d7</c> is claimed before
/// sending and never expires, so neither a second run nor a second instance sends it again. A day that was
/// missed by more than a day (the worker was down) is skipped.
Expand All @@ -27,6 +32,7 @@ public class FirstWeekNudgeService(
ITraleDbContext db,
IMiniAppContentProvider content,
IUserNotificationService notificationService,
PriceSchedule prices,
ILoggerFactory loggerFactory) : IFirstWeekNudgeService
{
private readonly ILogger _logger = loggerFactory.CreateLogger<FirstWeekNudgeService>();
Expand All @@ -52,6 +58,9 @@ public async Task DispatchAsync(DateTime nowUtc, CancellationToken ct)
{
var switchedOnAt = await SwitchedOnAtAsync(db, nowUtc, ct);

if (switchedOnAt <= nowUtc - TimeSpan.FromDays(7))
await OfferToEngagedAsync(nowUtc, switchedOnAt, ct);

foreach (var day in Days)
{
var registeredBefore = nowUtc - TimeSpan.FromDays(day);
Expand Down Expand Up @@ -89,6 +98,39 @@ public async Task DispatchAsync(DateTime nowUtc, CancellationToken ct)
await db.SaveChangesAsync(ct);
}

private async Task OfferToEngagedAsync(DateTime nowUtc, DateTime switchedOnAt, CancellationToken ct)
{
var registeredBefore = nowUtc - TimeSpan.FromDays(7);
var registeredAfter = registeredBefore - TimeSpan.FromDays(1);
var day7 = SourceFor(7);

var due = await db.Users
.Where(u => u.IsActive && u.NotificationsEnabled
&& u.RegisteredAtUtc >= switchedOnAt
&& u.RegisteredAtUtc <= registeredBefore
&& u.RegisteredAtUtc > registeredAfter
&& !db.Payments.Any(p => p.UserId == u.Id)
&& !db.NotificationTriggers.Any(t => t.UserId == u.TelegramId && (t.Source == day7 || t.Source == PriceSchedule.OfferSource)))
.ToListAsync(ct);

foreach (var user in due.Where(u => !u.HasActivePro(nowUtc)))
{
var done = await db.LessonEvents
.Where(e => e.UserId == user.Id && e.Event == "lesson_complete" && e.ModuleId != "onboarding" && e.CreatedAtUtc >= user.RegisteredAtUtc)
.Select(e => e.CreatedAtUtc)
.ToListAsync(ct);
if (done.Count < EngagedOffer.MinLessons || done.Select(at => at.Date).Distinct().Count() < EngagedOffer.MinDays)
continue;

if (!await db.TryClaimNotificationTriggerAsync(user.TelegramId, PriceSchedule.OfferSource, null, nowUtc, Never, ct))
continue;
// The offer stands in for the day-7 message.
await db.TryClaimNotificationTriggerAsync(user.TelegramId, day7, "offer", nowUtc, Never, ct);

await notificationService.SendEngagedOfferAsync(user, EngagedOffer.Text(done.Count, nowUtc, prices), EngagedOffer.Button(nowUtc, prices), ct);
}
}

/// <summary>The day's message: the next lesson of the module the person has gone furthest in
/// (the alphabet for someone who has not finished a lesson yet). Null — nothing left to take.</summary>
public FirstWeekNudge? Build(int day, string completedLessonsJson)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,38 @@ await _client.SendTextMessageAsync(
await Task.Delay(BulkSendDelay, ct);
}

public async Task SendEngagedOfferAsync(Domain.Entities.User user, string text, string button, CancellationToken ct)
{
if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return;

var keyboard = new InlineKeyboardMarkup(new[]
{
new[] { InlineKeyboardButton.WithWebApp(button, new WebAppInfo { Url = $"{_botConfig.NormalizedHost()}/?paywall=1&src=push_engaged_offer" }) }
});

try
{
await _client.SendTextMessageAsync(chatId: user.TelegramId, text: text, replyMarkup: keyboard, cancellationToken: ct);
}
catch (ApiRequestException ex) when (ex.ErrorCode == 429)
{
var retryAfterSeconds = ex.Parameters?.RetryAfter ?? 1;
_logger.LogInformation(
"Engaged offer for {TelegramId} hit rate limit; retrying after {RetryAfter}s",
user.TelegramId, retryAfterSeconds);
await Task.Delay(TimeSpan.FromSeconds(retryAfterSeconds), ct);
await _client.SendTextMessageAsync(chatId: user.TelegramId, text: text, replyMarkup: keyboard, cancellationToken: ct);
}
catch (ApiRequestException ex) when (ex.ErrorCode == 403)
{
_logger.LogInformation("Engaged offer for {TelegramId} blocked (403); marking user inactive", user.TelegramId);
user.IsActive = false;
return;
}

await Task.Delay(BulkSendDelay, ct);
}

public async Task SendFirstWeekNudgeAsync(Domain.Entities.User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct)
{
if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return;
Expand Down
13 changes: 10 additions & 3 deletions src/Trale/Controllers/MiniAppController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,15 @@ public async Task<IActionResult> GetPlans([FromServices] PriceSchedule prices, C
var applyTestPricing = user != null && TestPricingTelegramIds.Contains(user.TelegramId);
var keepsOldPrices = user != null && await prices.KeepsOldPricesAsync(_dbContext, user.Id, ct);
var now = DateTime.UtcNow;
// The offer of the old prices to a newcomer who studies in earnest — it matters only after the rise.
var offerEndsAt = user != null && !keepsOldPrices && prices.HasRisen(now)
? await prices.OfferEndsAtAsync(_dbContext, user.TelegramId, now, ct) : null;

var plans = SubscriptionPlans.All.Select(p => new
{
id = p.Plan.ToString(),
payloadId = p.PayloadId,
stars = applyTestPricing ? TestPricingStars : prices.PriceFor(p, now, keepsOldPrices),
stars = applyTestPricing ? TestPricingStars : prices.PriceFor(p, now, keepsOldPrices || offerEndsAt != null),
// 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,
Expand All @@ -205,7 +208,9 @@ public async Task<IActionResult> GetPlans([FromServices] PriceSchedule prices, C
// 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
keepsOldPrices,
// The old prices for a while, offered to a newcomer who studies in earnest; null — no offer running.
offerEndsAtUtc = offerEndsAt
});
}

Expand Down Expand Up @@ -280,7 +285,9 @@ public async Task<IActionResult> Purchase([FromBody] PurchaseRequest req, [FromS
return BadRequest(new { error = "invalid_plan" });
}

plan = plan with { StarsPrice = prices.PriceFor(plan, DateTime.UtcNow, await prices.KeepsOldPricesAsync(_dbContext, user.Id, ct)) };
var oldPrices = await prices.KeepsOldPricesAsync(_dbContext, user.Id, ct)
|| await prices.OfferEndsAtAsync(_dbContext, user.TelegramId, DateTime.UtcNow, ct) != null;
plan = plan with { StarsPrice = prices.PriceFor(plan, DateTime.UtcNow, oldPrices) };

if (TestPricingTelegramIds.Contains(user.TelegramId))
{
Expand Down
4 changes: 3 additions & 1 deletion src/Trale/miniapp-src/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,9 @@ export const api = {
/** До повышения — когда цены вырастут; после — null. */
pricesRiseAtUtc?: string | null
/** Платил до повышения: старые цены навсегда. */
keepsOldPrices?: boolean }>('/api/miniapp/plans'),
keepsOldPrices?: boolean
/** Сниженная (старая) цена втянувшемуся новичку — до этого момента; null — предложения нет. */
offerEndsAtUtc?: string | null }>('/api/miniapp/plans'),

purchase: (plan: string) =>
request<{ ok: boolean; alreadyPro?: boolean; invoiceLink?: string }>('/api/miniapp/purchase', {
Expand Down
7 changes: 7 additions & 0 deletions src/Trale/miniapp-src/src/components/ProPaywall.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,11 @@ describe('ProPaywall — повышение цен', () => {
expect(screen.queryByTestId('paywall-price-rise')).toBeNull()
expect(screen.queryByTestId('paywall-regular-price')).toBeNull()
})

it('shows a newcomer the price for their own until the offer ends', async () => {
api.plans.mockResolvedValue({ plans: [month(100, 149)], pricesRiseAtUtc: null, keepsOldPrices: false, offerEndsAtUtc: '2026-12-12T14:00:00Z' } as never)
await open()
expect(screen.getByTestId('paywall-offer').textContent).toBe('Специально для тебя — сниженная цена до 12 декабря, 18:00 по Тбилиси. Купи сейчас, потом цена станет обычной.')
expect(screen.getByTestId('paywall-regular-price').textContent).toBe('149 ⭐')
})
})
Loading
Loading