Files
flux/lib/features/tasks/blocs/task_form_cubit.dart

258 lines
8.4 KiB
Dart
Raw Normal View History

2026-05-26 19:31:25 +02:00
import 'package:equatable/equatable.dart';
2026-05-30 12:12:14 +02:00
import 'package:flutter/foundation.dart';
2026-05-26 19:31:25 +02:00
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
2026-05-30 12:12:14 +02:00
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
2026-05-26 19:31:25 +02:00
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
2026-05-29 12:26:41 +02:00
import 'package:flux/features/settings/data/settings_repository.dart';
2026-05-26 19:31:25 +02:00
import 'package:flux/features/tasks/data/task_repository.dart';
import 'package:flux/features/tasks/models/task_model.dart';
2026-05-29 12:26:41 +02:00
import 'package:flux/features/tasks/models/task_reminder_config.dart';
2026-05-26 19:31:25 +02:00
import 'package:get_it/get_it.dart';
part 'task_form_state.dart';
class TaskFormCubit extends Cubit<TaskFormState> {
2026-05-29 19:24:40 +02:00
final TasksRepository _repository = GetIt.I.get<TasksRepository>();
2026-05-29 12:26:41 +02:00
final SettingsRepository _settingsRepository = GetIt.I
.get<SettingsRepository>();
2026-05-30 12:12:14 +02:00
final _staffRepository = GetIt.I.get<StaffRepository>();
2026-05-29 12:26:41 +02:00
final SessionCubit _sessionCubit = GetIt.I.get<SessionCubit>();
2026-05-30 12:12:14 +02:00
final List<StaffMemberModel>? _preloadedStaff;
2026-05-29 12:26:41 +02:00
2026-05-29 19:24:40 +02:00
TaskFormCubit({
String? initialTaskId, // <-- RIPRISTINATO PER DEEP LINK
TaskModel? existingTask,
2026-05-30 12:12:14 +02:00
List<StaffMemberModel>? allStaff,
}) : _preloadedStaff = allStaff,
super(const TaskFormState()) {
2026-05-29 19:24:40 +02:00
// Avviamo l'inizializzazione centralizzata (gestisce sia mem, sia deep link, sia nuovo)
initForm(initialTaskId: initialTaskId, existingTask: existingTask);
2026-05-26 19:31:25 +02:00
}
2026-05-29 12:26:41 +02:00
String get _companyId => _sessionCubit.state.company!.id!;
String get _currentUserId => _sessionCubit.state.currentStaffMember!.id!;
2026-05-29 19:24:40 +02:00
String? get _currentStoreId => _sessionCubit.state.currentStore?.id;
// --- ARMED INITIALIZATION (Nuovo, Esistente o Deep Link) ---
Future<void> initForm({
String? initialTaskId,
TaskModel? existingTask,
}) async {
emit(state.copyWith(status: TaskFormStatus.loading));
try {
TaskModel? task = existingTask;
// 1. Se arriviamo da Deep Link col solo ID, lo scarichiamo dal DB
if (initialTaskId != null && task == null) {
task = await _repository.fetchTaskById(initialTaskId);
}
if (task != null) {
// CASO: TASK ESISTENTE (Modifica o Deep Link pronto)
emit(
state.copyWith(
id: task.id,
title: task.title,
description: task.description,
dueDate: task.dueDate,
isGlobal: task.isGlobal, // Sfrutta il tuo getter storeId == null
selectedStaffIds: task.assignedToIds,
),
);
await _loadExistingTaskReminders(task.id!);
} else {
// CASO: NUOVO TASK
await _initializeNewTaskReminders();
}
2026-05-26 19:31:25 +02:00
2026-05-29 19:24:40 +02:00
// 2. Carichiamo e raggruppiamo il personale (Global o Store)
await _loadAndGroupStaff();
// Mandiamo lo status a 'initial' così il FormScreen sincronizza i controller di testo!
emit(state.copyWith(status: TaskFormStatus.initial));
} catch (e) {
emit(
state.copyWith(
status: TaskFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
// --- LOGICA GESTIONE STAFF (GLOBAL STAFF / STORE STAFF) ---
Future<void> _loadAndGroupStaff() async {
2026-05-30 12:12:14 +02:00
final List<StaffMemberModel> staffList;
// SE C'È LO STAFF PASCIUTO DALL'APP USA QUELLO, ALTRIMENTI CHIAMA IL REPO
if (_preloadedStaff != null && _preloadedStaff.isNotEmpty) {
staffList = _preloadedStaff;
} else {
staffList = await _staffRepository.getStaffMembers(_companyId);
}
2026-05-29 19:24:40 +02:00
final Map<String, List<StaffMemberModel>> grouped = {};
2026-05-30 12:12:14 +02:00
2026-05-29 19:24:40 +02:00
for (var staff in staffList) {
2026-05-30 12:12:14 +02:00
if (!state.isGlobal) {
final belongsToCurrentStore = staff.assignedStores.any(
(store) => store.id == _currentStoreId,
);
if (!belongsToCurrentStore) continue;
}
if (staff.assignedStores.isEmpty) {
grouped.putIfAbsent('Direzione / Senza Sede', () => []).add(staff);
} else {
for (var store in staff.assignedStores) {
if (!state.isGlobal && store.id != _currentStoreId) continue;
final storeName = store.name;
grouped.putIfAbsent(storeName, () => []).add(staff);
}
}
2026-05-29 19:24:40 +02:00
}
emit(state.copyWith(groupedAvailableStaff: grouped));
}
// Se l'utente switcha su "Globale Aziendale", ricarichiamo lo staff di conseguenza
void toggleGlobalScope(bool g) async {
emit(state.copyWith(isGlobal: g, status: TaskFormStatus.loading));
await _loadAndGroupStaff();
emit(
state.copyWith(status: TaskFormStatus.initial),
); // Ri-notifichiamo la UI
}
// --- INIT REMINDER ---
2026-05-29 12:26:41 +02:00
Future<void> _initializeNewTaskReminders() async {
try {
final defaults = await _settingsRepository.getMyReminderDefaults(
companyId: _companyId,
staffId: _currentUserId,
);
final initialReminders = defaults
.map(
(d) => TaskReminderConfig(
minutesBefore: d.minutesBefore,
channel: d.channel,
),
)
.toList();
emit(state.copyWith(reminders: initialReminders));
} catch (e) {
emit(
state.copyWith(
reminders: const [
TaskReminderConfig(minutesBefore: 15, channel: 'push'),
],
),
);
2026-05-27 16:00:50 +02:00
}
2026-05-26 19:31:25 +02:00
}
2026-05-29 12:26:41 +02:00
Future<void> _loadExistingTaskReminders(String taskId) async {
try {
final existingConfigs = await _repository.fetchPersonalReminders(
taskId: taskId,
staffId: _currentUserId,
);
emit(state.copyWith(reminders: existingConfigs));
} catch (e) {
2026-05-30 12:12:14 +02:00
debugPrint('Errore caricamento reminder: $e');
2026-05-26 19:31:25 +02:00
}
}
2026-05-29 19:24:40 +02:00
// --- AGGIORNAMENTO CAMPI ---
2026-05-29 12:26:41 +02:00
void updateTitle(String t) => emit(state.copyWith(title: t));
void updateDescription(String d) => emit(state.copyWith(description: d));
void updateDueDate(DateTime? d) => emit(state.copyWith(dueDate: d));
2026-05-26 19:31:25 +02:00
2026-05-29 12:26:41 +02:00
void toggleStaffSelection(String staffId) {
final updated = List<String>.from(state.selectedStaffIds);
updated.contains(staffId) ? updated.remove(staffId) : updated.add(staffId);
emit(state.copyWith(selectedStaffIds: updated));
2026-05-26 19:31:25 +02:00
}
2026-05-29 19:24:40 +02:00
void toggleStoreSelection(String storeName, bool selectAll) {
final updated = List<String>.from(state.selectedStaffIds);
final storeStaff = state.groupedAvailableStaff[storeName] ?? [];
for (var staff in storeStaff) {
if (staff.id == null) continue;
if (selectAll) {
if (!updated.contains(staff.id)) updated.add(staff.id!);
} else {
updated.remove(staff.id);
}
}
emit(state.copyWith(selectedStaffIds: updated));
}
// --- AZIONI REMINDER ---
2026-05-29 12:26:41 +02:00
void addReminderRule(int minutesBefore, String channel) {
final updated = List<TaskReminderConfig>.from(state.reminders);
final newConfig = TaskReminderConfig(
minutesBefore: minutesBefore,
channel: channel,
);
2026-05-26 19:31:25 +02:00
2026-05-29 12:26:41 +02:00
if (!updated.contains(newConfig)) {
updated.add(newConfig);
updated.sort((a, b) => a.minutesBefore.compareTo(b.minutesBefore));
emit(state.copyWith(reminders: updated));
}
2026-05-26 19:31:25 +02:00
}
2026-05-29 12:26:41 +02:00
void removeReminderRule(int index) {
final updated = List<TaskReminderConfig>.from(state.reminders)
..removeAt(index);
emit(state.copyWith(reminders: updated));
2026-05-26 19:31:25 +02:00
}
2026-05-29 19:24:40 +02:00
// --- SALVATAGGIO ---
2026-05-29 12:26:41 +02:00
Future<void> saveTask() async {
2026-05-26 19:31:25 +02:00
if (!state.isFormValid) return;
emit(state.copyWith(status: TaskFormStatus.submitting));
2026-05-29 12:26:41 +02:00
final taskToSave = TaskModel(
id: state.id,
companyId: _companyId,
2026-05-29 19:24:40 +02:00
createdById: _currentUserId,
2026-05-29 12:26:41 +02:00
title: state.title.trim(),
description: state.description.trim(),
dueDate: state.dueDate,
2026-05-29 19:24:40 +02:00
storeId: state.isGlobal
? null
: _currentStoreId, // Gestione nativa basata sulla tua logica
2026-05-29 12:26:41 +02:00
assignedToIds: state.selectedStaffIds,
);
2026-05-26 19:31:25 +02:00
2026-05-29 12:26:41 +02:00
try {
2026-05-26 19:31:25 +02:00
if (state.id == null) {
2026-05-29 12:26:41 +02:00
await _repository.createTask(
task: taskToSave,
assignedStaffIds: state.selectedStaffIds,
currentUserId: _currentUserId,
currentUserCustomReminders: state.reminders,
);
2026-05-26 19:31:25 +02:00
} else {
2026-05-29 12:26:41 +02:00
await _repository.updateTask(
task: taskToSave,
assignedStaffIds: state.selectedStaffIds,
currentUserId: _currentUserId,
currentUserCustomReminders: state.reminders,
);
2026-05-26 19:31:25 +02:00
}
emit(state.copyWith(status: TaskFormStatus.success));
} catch (e) {
emit(
state.copyWith(
status: TaskFormStatus.failure,
2026-05-29 12:26:41 +02:00
errorMessage: e.toString(),
2026-05-26 19:31:25 +02:00
),
);
}
}
}