mnemo_cards/mnemo_cards_backend/lib/cron/add_free_packs.dart
Dmitry 829542714a
Some checks are pending
Backend CI / test (push) Waiting to run
Backend 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
product availability
2026-01-08 19:58:13 +03:00

75 lines
2.3 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/packs/product_availability_manager.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;
final ProductAvailabilityManager _productAvailabilityManager;
AddFreePacks(
this._freePacksDistributor,
this._userRepository,
this._productAvailabilityManager,
);
@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 _productAvailabilityManager.grantPackAccess(
userId: userId,
packId: pack.id!,
grantType: 'free',
);
}
} catch (e) {
print('$name on user $userId: $e');
}
}
}
@override
int get intervalSeconds => 600;
}