mnemo_cards/mnemo_cards_backend/lib/cron/add_free_packs.dart
Dmitry 550b56276e
Some checks are pending
Backend CI / test (push) Waiting to run
Backend CI / build (push) Blocked by required conditions
Mobile App CI / test (push) Waiting to run
Mobile App CI / build-android (push) Blocked by required conditions
Mobile App CI / build-ios (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
Deploy Telegram Bot / Deploy Telegram Bot (push) Waiting to run
postgress fix
2025-12-13 23:55:50 +03:00

65 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/cron/task.dart';
import 'package:mnemo_cards_backend/database/database.dart';
import 'package:mnemo_cards_backend/packs/free_packs_distributor.dart';
import 'task.dart' as task;
class AddFreePacks with task.Task {
final FreePacksDistributor _freePacksDistributor;
final AppDatabase _db;
AddFreePacks(this._freePacksDistributor, this._db);
@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 _db.userDao.getAllUsers();
// Фильтруем пользователей, у которых нет хотя бы одного из freePacks
final usersToUpdate = <String>[];
for (final user in allUsers) {
final userPacks = await _db.userDao.getUserPacks(user.id);
final userPackIds = userPacks.map((p) => p.id).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) {
await _db.userDao.grantPackAccess(
userId: userId,
packId: pack.id,
grantType: 'free',
);
}
} catch (e) {
print('$name on user $userId: $e');
}
}
}
@override
int get intervalSeconds => 600;
}