Files
social-app/apps/lib/features/settings/presentation/cubits/automation_jobs_cubit.dart
T

85 lines
2.2 KiB
Dart

import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/automation_job_model.dart';
import '../../data/services/automation_jobs_api.dart';
class AutomationJobsState extends Equatable {
final List<AutomationJobModel> jobs;
final bool isLoading;
final String? error;
const AutomationJobsState({
this.jobs = const [],
this.isLoading = false,
this.error,
});
List<AutomationJobModel> get systemJobs =>
jobs.where((j) => j.isSystem).toList();
List<AutomationJobModel> get userJobs =>
jobs.where((j) => !j.isSystem).toList();
List<AutomationJobModel> get dailyJobs =>
jobs.where((j) => j.isDaily).toList();
List<AutomationJobModel> get weeklyJobs =>
jobs.where((j) => j.isWeekly).toList();
bool get canCreateMore => userJobs.length < 3;
AutomationJobsState copyWith({
List<AutomationJobModel>? jobs,
bool? isLoading,
String? error,
}) {
return AutomationJobsState(
jobs: jobs ?? this.jobs,
isLoading: isLoading ?? this.isLoading,
error: error,
);
}
@override
List<Object?> get props => [jobs, isLoading, error];
}
class AutomationJobsCubit extends Cubit<AutomationJobsState> {
final AutomationJobsApi _api;
AutomationJobsCubit(this._api) : super(AutomationJobsState());
Future<void> loadJobs() async {
emit(state.copyWith(isLoading: true));
try {
final jobs = await _api.list();
emit(state.copyWith(jobs: jobs, isLoading: false));
} catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
Future<void> deleteJob(String id) async {
try {
await _api.delete(id);
await loadJobs();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
Future<void> updateJobStatus({
required String id,
required bool enabled,
}) async {
try {
final updated = await _api.update(
id,
AutomationJobUpdateRequest(status: enabled ? 'active' : 'disabled'),
);
final nextJobs = state.jobs
.map((job) => job.id == id ? updated : job)
.toList();
emit(state.copyWith(jobs: nextJobs));
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
}