b
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/tasks/models/task_reminder_config.dart';
|
||||
import 'package:flux/features/tasks/models/task_status.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
// Sostituisci con i percorsi corretti di FLUX
|
||||
import 'package:flux/features/tasks/models/task_model.dart';
|
||||
@@ -103,35 +107,104 @@ class TaskRepository {
|
||||
}
|
||||
}
|
||||
|
||||
// --- 2. CREAZIONE DEL TASK ---
|
||||
Future<TaskModel> createTask(TaskModel task) async {
|
||||
Future<void> createTask({
|
||||
required TaskModel task,
|
||||
required List<String> assignedStaffIds,
|
||||
required String currentUserId,
|
||||
required List<TaskReminderConfig> currentUserCustomReminders,
|
||||
TaskReminderConfig?
|
||||
managerForcedOverride, // Opzionale: l'avviso forzato del manager
|
||||
}) async {
|
||||
try {
|
||||
final taskData = task.toMap();
|
||||
// 1. Inserimento del Task principale -> otteniamo il taskId
|
||||
// 2. Inserimento dei record in task_assignments
|
||||
final String taskId = task.id!;
|
||||
|
||||
// Rimuoviamo l'array prima di inviare i dati alla tabella principale,
|
||||
// la "Strada C" impone che la verità assoluta derivi dalla tabella di giunzione!
|
||||
taskData.remove('assigned_to_ids');
|
||||
List<Map<String, dynamic>> remindersToInsert = [];
|
||||
|
||||
// 1. Inseriamo il record base nella tabella tasks
|
||||
final response = await _supabase
|
||||
.from(Tables.tasks)
|
||||
.insert(taskData)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
final newTask = TaskModel.fromMap(response);
|
||||
|
||||
// 2. Se l'utente ha assegnato il task a qualcuno, popoliamo la giunzione
|
||||
if (task.assignedToIds.isNotEmpty && newTask.id != null) {
|
||||
await _syncAssignments(newTask.id!, task.assignedToIds);
|
||||
|
||||
// 3. Ricarichiamo il task appena creato per ottenere l'array e il JOIN aggiornati dal trigger!
|
||||
return await getTaskById(newTask.id!);
|
||||
// 3. Recuperiamo i default degli ALTRI utenti assegnati
|
||||
final otherStaffIds = assignedStaffIds
|
||||
.where((id) => id != currentUserId)
|
||||
.toList();
|
||||
List<dynamic> otherDefaults = [];
|
||||
if (otherStaffIds.isNotEmpty) {
|
||||
otherDefaults = await _supabase
|
||||
.from('staff_task_reminder_defaults')
|
||||
.select()
|
||||
.inFilter('staff_id', otherStaffIds);
|
||||
}
|
||||
|
||||
return newTask;
|
||||
// 4. CICLO DI COSTRUZIONE DELLA CODA REMINDER
|
||||
for (var staffId in assignedStaffIds) {
|
||||
// CASO A: È l'utente loggato che sta creando/partecipando al task
|
||||
if (staffId == currentUserId) {
|
||||
for (var config in currentUserCustomReminders) {
|
||||
final triggerAt = task.dueDate?.subtract(
|
||||
Duration(minutes: config.minutesBefore),
|
||||
);
|
||||
if (triggerAt != null && triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': currentUserId,
|
||||
'minutes_before': config.minutesBefore,
|
||||
'channel': config.channel,
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// CASO B: Sono gli altri assegnatari -> ereditano i loro default personali dal DB
|
||||
else {
|
||||
final staffRules = otherDefaults.where(
|
||||
(row) => row['staff_id'] == staffId,
|
||||
);
|
||||
for (var rule in staffRules) {
|
||||
final minutesBefore = rule['minutes_before'] as int;
|
||||
final triggerAt = task.dueDate?.subtract(
|
||||
Duration(minutes: minutesBefore),
|
||||
);
|
||||
if (triggerAt != null && triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'minutes_before': minutesBefore,
|
||||
'channel': rule['channel'],
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CASO C: Il creatore ha impostato un avviso forzato (Override molto importante)
|
||||
if (managerForcedOverride != null && task.dueDate != null) {
|
||||
final triggerAt = task.dueDate!.subtract(
|
||||
Duration(minutes: managerForcedOverride.minutesBefore),
|
||||
);
|
||||
if (triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId, // Lo beccheranno tutti
|
||||
'minutes_before': managerForcedOverride.minutesBefore,
|
||||
'channel': managerForcedOverride.channel,
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced':
|
||||
true, // Chiude la possibilità di cancellarlo lato utente
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Sparata unica di Bulk Insert su task_reminders
|
||||
if (remindersToInsert.isNotEmpty) {
|
||||
await _supabase.from('task_reminders').insert(remindersToInsert);
|
||||
}
|
||||
} catch (e) {
|
||||
throw Exception('Errore nella creazione del task: $e');
|
||||
throw Exception('Errore creazione task: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +233,107 @@ class TaskRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> createTask({
|
||||
required TaskModel task,
|
||||
required List<String> assignedStaffIds,
|
||||
required String currentUserId,
|
||||
required List<TaskReminderConfig> currentUserCustomReminders,
|
||||
TaskReminderConfig?
|
||||
managerForcedOverride, // Opzionale: l'avviso forzato del manager
|
||||
}) async {
|
||||
try {
|
||||
// 1. Inserimento del Task principale -> otteniamo il taskId
|
||||
// 2. Inserimento dei record in task_assignments
|
||||
final String taskId = task.id;
|
||||
|
||||
List<Map<String, dynamic>> remindersToInsert = [];
|
||||
|
||||
// 3. Recuperiamo i default degli ALTRI utenti assegnati
|
||||
final otherStaffIds = assignedStaffIds
|
||||
.where((id) => id != currentUserId)
|
||||
.toList();
|
||||
List<dynamic> otherDefaults = [];
|
||||
if (otherStaffIds.isNotEmpty) {
|
||||
otherDefaults = await _supabase
|
||||
.from('staff_task_reminder_defaults')
|
||||
.select()
|
||||
.inFilter('staff_id', otherStaffIds);
|
||||
}
|
||||
|
||||
// 4. CICLO DI COSTRUZIONE DELLA CODA REMINDER
|
||||
for (var staffId in assignedStaffIds) {
|
||||
// CASO A: È l'utente loggato che sta creando/partecipando al task
|
||||
if (staffId == currentUserId) {
|
||||
for (var config in currentUserCustomReminders) {
|
||||
final triggerAt = task.dueDate?.subtract(
|
||||
Duration(minutes: config.minutesBefore),
|
||||
);
|
||||
if (triggerAt != null && triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': currentUserId,
|
||||
'minutes_before': config.minutesBefore,
|
||||
'channel': config.channel,
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// CASO B: Sono gli altri assegnatari -> ereditano i loro default personali dal DB
|
||||
else {
|
||||
final staffRules = otherDefaults.where(
|
||||
(row) => row['staff_id'] == staffId,
|
||||
);
|
||||
for (var rule in staffRules) {
|
||||
final minutesBefore = rule['minutes_before'] as int;
|
||||
final triggerAt = task.dueDate?.subtract(
|
||||
Duration(minutes: minutesBefore),
|
||||
);
|
||||
if (triggerAt != null && triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'minutes_before': minutesBefore,
|
||||
'channel': rule['channel'],
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CASO C: Il creatore ha impostato un avviso forzato (Override molto importante)
|
||||
if (managerForcedOverride != null && task.dueDate != null) {
|
||||
final triggerAt = task.dueDate!.subtract(
|
||||
Duration(minutes: managerForcedOverride.minutesBefore),
|
||||
);
|
||||
if (triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': task.companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId, // Lo beccheranno tutti
|
||||
'minutes_before': managerForcedOverride.minutesBefore,
|
||||
'channel': managerForcedOverride.channel,
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
'is_forced':
|
||||
true, // Chiude la possibilità di cancellarlo lato utente
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Sparata unica di Bulk Insert su task_reminders
|
||||
if (remindersToInsert.isNotEmpty) {
|
||||
await _supabase.from('task_reminders').insert(remindersToInsert);
|
||||
}
|
||||
} catch (e) {
|
||||
throw Exception('Errore creazione task: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- 4. ELIMINAZIONE DEL TASK ---
|
||||
Future<void> deleteTask(String taskId) async {
|
||||
try {
|
||||
@@ -202,10 +376,116 @@ class TaskRepository {
|
||||
// 2. Inseriamo le nuove assegnazioni (se ce ne sono)
|
||||
if (staffIds.isNotEmpty) {
|
||||
final List<Map<String, dynamic>> assignments = staffIds
|
||||
.map((staffId) => {'task_id': taskId, 'staff_id': staffId})
|
||||
.map(
|
||||
(staffId) => {
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'company_id': GetIt.I.get<SessionCubit>().state.company!.id!,
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
|
||||
await _supabase.from(Tables.taskAssignments).insert(assignments);
|
||||
}
|
||||
}
|
||||
|
||||
// --- IL MOTORE DELLA MAGIA ---
|
||||
|
||||
Future<void> generateTaskReminders({
|
||||
required String taskId,
|
||||
required String companyId,
|
||||
required List<String> assignedStaffIds,
|
||||
required DateTime? taskDueDate,
|
||||
}) async {
|
||||
if (assignedStaffIds.isEmpty) return;
|
||||
|
||||
try {
|
||||
// 1. Recuperiamo i default di TUTTI i collaboratori coinvolti in un colpo solo
|
||||
final response = await _supabase
|
||||
.from('staff_task_reminder_defaults')
|
||||
.select()
|
||||
.eq('company_id', companyId)
|
||||
.inFilter('staff_id', assignedStaffIds);
|
||||
|
||||
final List<Map<String, dynamic>> remindersToInsert = [];
|
||||
|
||||
for (var staffId in assignedStaffIds) {
|
||||
// Cerchiamo le preferenze di questo specifico membro dello staff
|
||||
final staffDefaults = response.where(
|
||||
(row) => row['staff_id'] == staffId,
|
||||
);
|
||||
|
||||
if (staffDefaults.isEmpty) {
|
||||
// STRATEGIA FALLBACK: Se l'utente non ha mai configurato i suoi default,
|
||||
// creiamo un reminder standard (es. una push 15 min prima) per non lasciarlo scoperto.
|
||||
if (taskDueDate != null) {
|
||||
remindersToInsert.add({
|
||||
'company_id': companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'minutes_before': 15,
|
||||
'channel': 'push',
|
||||
'trigger_at': taskDueDate
|
||||
.subtract(const Duration(minutes: 15))
|
||||
.toIso8601String(),
|
||||
});
|
||||
}
|
||||
|
||||
// E spariamo la push di creazione immediata come comportamento standard
|
||||
_triggerImmediateNotification(staffId, taskId, 'push_creation');
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. GESTIONE NOTIFICHE ISTANTANEE (EVENT-DRIVEN)
|
||||
// Prendiamo la prima riga delle impostazioni dell'utente (tanto le colonne nuove sono speculari)
|
||||
final userSetting = staffDefaults.first;
|
||||
if (userSetting['notify_on_creation_push'] == true) {
|
||||
_triggerImmediateNotification(staffId, taskId, 'push_creation');
|
||||
}
|
||||
if (userSetting['notify_on_creation_email'] == true) {
|
||||
_triggerImmediateNotification(staffId, taskId, 'email_creation');
|
||||
}
|
||||
|
||||
// 3. GESTIONE REMINDER TEMPORIZZATI (TIME-DRIVEN)
|
||||
if (taskDueDate != null) {
|
||||
for (var rule in staffDefaults) {
|
||||
final minutesBefore = rule['minutes_before'] as int;
|
||||
final triggerAt = taskDueDate.subtract(
|
||||
Duration(minutes: minutesBefore),
|
||||
);
|
||||
|
||||
// Se il task scade tra 5 minuti e il reminder è impostato a 1 ora prima,
|
||||
// il trigger_at sarebbe nel passato. Lo inseriamo solo se è nel futuro!
|
||||
if (triggerAt.isAfter(DateTime.now())) {
|
||||
remindersToInsert.add({
|
||||
'company_id': companyId,
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'minutes_before': minutesBefore,
|
||||
'channel': rule['channel'],
|
||||
'trigger_at': triggerAt.toIso8601String(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Bulk Insert dei reminder temporizzati nella coda operativa
|
||||
if (remindersToInsert.isNotEmpty) {
|
||||
await _supabase.from('task_reminders').insert(remindersToInsert);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Errore nella generazione dei reminder: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _triggerImmediateNotification(
|
||||
String staffId,
|
||||
String taskId,
|
||||
String type,
|
||||
) {
|
||||
// Questa funzione chiamerà direttamente l'Edge Function di Supabase
|
||||
// per far squillare il telefono o mandare la mail ADESSO.
|
||||
// La implementeremo appena il backend sarà pronto!
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user