mnemo_cards/mnemo_cards_backend/lib/cron/add_free_packs.dart
Dmitry a6abcfa7e6
Some checks failed
Backend CI / test (push) Waiting to run
Backend CI / build (push) Blocked by required conditions
Web App CI / test (push) Waiting to run
Web App CI / build (push) Blocked by required conditions
Deploy Mnemo Cards / Deploy Backend (push) Waiting to run
Deploy Mnemo Cards / Deploy Web App (push) Blocked by required conditions
Deploy Mnemo Cards / Final Verification (push) Blocked by required conditions
Mobile App CI / test (push) Has been cancelled
Deploy Telegram Bot / Deploy Telegram Bot (push) Has been cancelled
Mobile App CI / build-android (push) Has been cancelled
Mobile App CI / build-ios (push) Has been cancelled
repo
2026-01-08 19:07:56 +03:00

66 lines
2 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:mnemo_cards_backend/packs/free_packs_distributor.dart';
import 'package:mnemo_cards_backend/user/user_repository.dart';
import 'task.dart' as task;
class AddFreePacks with task.Task {
final FreePacksDistributor _freePacksDistributor;
final UserRepository _userRepository;
AddFreePacks(this._freePacksDistributor, this._userRepository);
@override
String get name => 'add_free_packs';
@override
Future<void> task() async {
final freePacks = await _freePacksDistributor.getFreePacks();
print('$name found ${freePacks.length} free packs');
if (freePacks.isEmpty) {
print('No free packs found');
return;
}
final freePackIds = freePacks.map((p) => p.id).toSet();
// Получаем всех пользователей
final allUsers = await _userRepository.getAllUsers();
// Фильтруем пользователей, у которых нет хотя бы одного из freePacks
final usersToUpdate = <String>[];
for (final user in allUsers) {
if (user.id == null) continue;
final userPacks = await _userRepository.getUserPacks(user.id!);
final userPackIds = userPacks.map((p) => p.id).whereType<String>().toSet();
// Если у пользователя нет хотя бы одного из freePacks
if (!freePackIds.every((packId) => userPackIds.contains(packId))) {
usersToUpdate.add(user.id!);
}
}
print(
'Found ${usersToUpdate.length} users for ${freePacks.length} free packs: ${freePacks.map((e) => e.title).join(',')}',
);
// Добавляем freePacks пользователям
for (final userId in usersToUpdate) {
try {
for (final pack in freePacks) {
if (pack.id == null) continue;
await _userRepository.grantPackAccess(
userId: userId,
packId: pack.id!,
grantType: 'free',
);
}
} catch (e) {
print('$name on user $userId: $e');
}
}
}
@override
int get intervalSeconds => 600;
}