feat-tickets (#14)
Some checks failed
Deploy to Cloudflare Pages / build-and-deploy (push) Has been cancelled
Some checks failed
Deploy to Cloudflare Pages / build-and-deploy (push) Has been cancelled
Reviewed-on: #14 Co-authored-by: mark-cachy <marco@catelli.it> Co-committed-by: mark-cachy <marco@catelli.it>
This commit is contained in:
217
lib/features/tickets/blocs/ticket_form_cubit.dart
Normal file
217
lib/features/tickets/blocs/ticket_form_cubit.dart
Normal file
@@ -0,0 +1,217 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'ticket_form_state.dart';
|
||||
|
||||
class TicketFormCubit extends Cubit<TicketFormState> {
|
||||
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
|
||||
final SessionCubit _sessionCubit = GetIt.I.get<SessionCubit>();
|
||||
|
||||
TicketFormCubit()
|
||||
: super(
|
||||
// Inizializziamo con un ticket vuoto di default
|
||||
TicketFormState(ticket: TicketModel.empty()),
|
||||
);
|
||||
|
||||
/// 1. INIZIALIZZAZIONE (Se stiamo modificando un ticket esistente)
|
||||
Future<void> initForm({String? id, TicketModel? existingTicket}) async {
|
||||
if (existingTicket != null) {
|
||||
// SCENARIO 1 (App Native / Navigazione interna Web):
|
||||
// Abbiamo l'oggetto intero passato via 'extra'. Lo mostriamo all'istante!
|
||||
emit(
|
||||
state.copyWith(ticket: existingTicket, status: TicketFormStatus.ready),
|
||||
);
|
||||
} else if (id != null) {
|
||||
// SCENARIO 2 (Web Refresh o Link condiviso):
|
||||
// L'utente ha premuto F5 su /tickets/form/123. L'extra è andato perso, ma abbiamo l'ID!
|
||||
emit(
|
||||
state.copyWith(status: TicketFormStatus.loading),
|
||||
); // Mostriamo uno spinner
|
||||
try {
|
||||
final fetchedTicket = await _repository.getTicketById(
|
||||
id,
|
||||
); // Lo scarichiamo!
|
||||
emit(
|
||||
state.copyWith(ticket: fetchedTicket, status: TicketFormStatus.ready),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketFormStatus.failure,
|
||||
errorMessage: 'Ticket non trovato',
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// SCENARIO 3 (Nuovo Ticket):
|
||||
// È un nuovo ticket! Inseriamo i default base (Azienda, Negozio, Creatore)
|
||||
final currentUser = _sessionCubit.state.currentStaffMember;
|
||||
final currentStore = _sessionCubit.state.currentStore;
|
||||
final companyId = _sessionCubit.state.company?.id ?? '';
|
||||
|
||||
final newTicket = TicketModel.empty().copyWith(
|
||||
companyId: companyId,
|
||||
storeId: currentStore?.id,
|
||||
createdById: currentUser?.id,
|
||||
createdByName: currentUser?.name,
|
||||
// Impostiamo lo stato iniziale
|
||||
ticketStatus: TicketStatus.open,
|
||||
ticketType: TicketType.repair, // Default
|
||||
);
|
||||
|
||||
emit(state.copyWith(ticket: newTicket, status: TicketFormStatus.ready));
|
||||
}
|
||||
}
|
||||
|
||||
/// 2. AGGIORNAMENTO CLIENTE (Usato dal nostro SharedCustomerSection!)
|
||||
void updateCustomer(CustomerModel customer) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
ticket: state.ticket.copyWith(
|
||||
customerId: customer.id,
|
||||
customerName: customer.name,
|
||||
alternativePhoneNumber: customer.phoneNumber, // Comodo come fallback!
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 3. AGGIORNAMENTO MODELLO (Usato dal nostro SharedModelSection!)
|
||||
void updateModel({required String modelId, required String modelName}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
ticket: state.ticket.copyWith(
|
||||
targetModelId: modelId,
|
||||
targetModelName: modelName,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void updateCreator({required String staffId, required String staffName}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
ticket: state.ticket.copyWith(
|
||||
createdById: staffId,
|
||||
createdByName: staffName,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 4. AGGIORNAMENTO GENERICO DEI CAMPI
|
||||
void updateFields({
|
||||
TicketType? ticketType,
|
||||
TicketStatus? status,
|
||||
String? request,
|
||||
String? targetSn,
|
||||
String? alternativePhoneNumber,
|
||||
bool? hasCourtesyDevice,
|
||||
String? includedAccessories,
|
||||
String? publicNotes,
|
||||
String? internalNotes,
|
||||
double? customerPrice,
|
||||
double? internalCost,
|
||||
String? assignedToId,
|
||||
String? assignedToName,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
ticket: state.ticket.copyWith(
|
||||
ticketType: ticketType ?? state.ticket.ticketType,
|
||||
ticketStatus: status ?? state.ticket.ticketStatus,
|
||||
request: request ?? state.ticket.request,
|
||||
targetSn: targetSn ?? state.ticket.targetSn,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? state.ticket.alternativePhoneNumber,
|
||||
hasCourtesyDevice:
|
||||
hasCourtesyDevice ?? state.ticket.hasCourtesyDevice,
|
||||
includedAccessories:
|
||||
includedAccessories ?? state.ticket.includedAccessories,
|
||||
publicNotes: publicNotes ?? state.ticket.publicNotes,
|
||||
internalNotes: internalNotes ?? state.ticket.internalNotes,
|
||||
customerPrice: customerPrice ?? state.ticket.customerPrice,
|
||||
internalCost: internalCost ?? state.ticket.internalCost,
|
||||
assignedToId: assignedToId ?? state.ticket.assignedToId,
|
||||
assignedToName: assignedToName ?? state.ticket.assignedToName,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 5. SALVATAGGIO
|
||||
Future<void> saveTicket({required bool keepAdding}) async {
|
||||
emit(state.copyWith(status: TicketFormStatus.saving));
|
||||
|
||||
try {
|
||||
final ticketToSave = state.ticket;
|
||||
|
||||
// Validazione base
|
||||
if (ticketToSave.customerId == null || ticketToSave.customerId!.isEmpty) {
|
||||
throw Exception("Seleziona un cliente prima di salvare.");
|
||||
}
|
||||
|
||||
final savedTicket = await _repository.saveTicket(ticketToSave);
|
||||
|
||||
if (keepAdding) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketFormStatus.successAndAddAnother,
|
||||
// Svuotiamo il form per il prossimo, mantenendo Store e Creatore ATTUALI
|
||||
ticket: TicketModel.empty().copyWith(
|
||||
companyId: savedTicket.companyId,
|
||||
storeId: savedTicket.storeId,
|
||||
createdById: ticketToSave
|
||||
.createdById, // Manteniamo quello selezionato nella tendina!
|
||||
createdByName: ticketToSave.createdByName,
|
||||
ticketStatus: TicketStatus.open,
|
||||
ticketType: TicketType.repair,
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(
|
||||
state.copyWith(status: TicketFormStatus.success, ticket: savedTicket),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 5.1 SALVATAGGIO SILENZIOSO (Per generare il QR Code al volo)
|
||||
Future<String?> saveTicketDraft() async {
|
||||
// Non mettiamo lo stato 'saving' per non far sfarfallare tutta la UI,
|
||||
// usiamo un caricamento invisibile.
|
||||
try {
|
||||
final ticketToSave = state.ticket;
|
||||
|
||||
if (ticketToSave.customerId == null || ticketToSave.customerId!.isEmpty) {
|
||||
throw Exception("Seleziona un cliente prima di poter usare il QR.");
|
||||
}
|
||||
|
||||
final savedTicket = await _repository.saveTicket(ticketToSave);
|
||||
|
||||
// Aggiorniamo silenziosamente lo stato con il ticket che ora ha un ID!
|
||||
emit(state.copyWith(ticket: savedTicket, status: TicketFormStatus.ready));
|
||||
|
||||
return savedTicket.id;
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
40
lib/features/tickets/blocs/ticket_form_state.dart
Normal file
40
lib/features/tickets/blocs/ticket_form_state.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
// Adatta gli import al tuo progetto!
|
||||
|
||||
enum TicketFormStatus {
|
||||
initial,
|
||||
ready,
|
||||
loading,
|
||||
saving,
|
||||
success,
|
||||
successAndAddAnother,
|
||||
failure,
|
||||
}
|
||||
|
||||
class TicketFormState extends Equatable {
|
||||
final TicketModel ticket;
|
||||
final TicketFormStatus status;
|
||||
final String? errorMessage;
|
||||
|
||||
const TicketFormState({
|
||||
required this.ticket,
|
||||
this.status = TicketFormStatus.initial,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [ticket, status, errorMessage];
|
||||
|
||||
TicketFormState copyWith({
|
||||
TicketModel? ticket,
|
||||
TicketFormStatus? status,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return TicketFormState(
|
||||
ticket: ticket ?? this.ticket,
|
||||
status: status ?? this.status,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
}
|
||||
79
lib/features/tickets/blocs/ticket_list_cubit.dart
Normal file
79
lib/features/tickets/blocs/ticket_list_cubit.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'ticket_list_state.dart';
|
||||
|
||||
class TicketListCubit extends Cubit<TicketListState> {
|
||||
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
|
||||
static const int _limit = 20; // Paginazione a blocchi di 20
|
||||
|
||||
TicketListCubit() : super(const TicketListState()) {
|
||||
fetchTickets(reset: true);
|
||||
}
|
||||
|
||||
/// Recupera i ticket. Se reset = true, svuota la lista e riparte da offset 0.
|
||||
Future<void> fetchTickets({bool reset = false}) async {
|
||||
if (state.isLoading) return;
|
||||
if (!reset && state.hasReachedMax) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoading: true,
|
||||
errorMessage: '',
|
||||
tickets: reset ? [] : state.tickets,
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final currentOffset = reset ? 0 : state.tickets.length;
|
||||
|
||||
final newTickets = await _repository.fetchStoreTickets(
|
||||
offset: currentOffset,
|
||||
limit: _limit,
|
||||
searchTerm: state.searchTerm,
|
||||
dateRange: state.dateRange,
|
||||
statusFilter: state.statusFilter,
|
||||
ticketTypeFilter: state.ticketTypeFilter,
|
||||
staffIdFilter: state.staffIdFilter,
|
||||
);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
tickets: reset ? newTickets : [...state.tickets, ...newTickets],
|
||||
isLoading: false,
|
||||
hasReachedMax: newTickets.length < _limit,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(state.copyWith(isLoading: false, errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggiorna i filtri e ricarica tutto da zero
|
||||
void updateFilters({
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
TicketStatus? statusFilter,
|
||||
TicketType? ticketTypeFilter,
|
||||
String? staffIdFilter,
|
||||
bool clearSearch = false,
|
||||
bool clearDate = false,
|
||||
bool clearStatus = false,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
searchTerm: searchTerm,
|
||||
dateRange: dateRange,
|
||||
statusFilter: statusFilter,
|
||||
ticketTypeFilter: ticketTypeFilter,
|
||||
staffIdFilter: staffIdFilter,
|
||||
clearSearch: clearSearch,
|
||||
clearDate: clearDate,
|
||||
clearStatus: clearStatus,
|
||||
),
|
||||
);
|
||||
fetchTickets(reset: true); // Applica i filtri e ricarica
|
||||
}
|
||||
}
|
||||
69
lib/features/tickets/blocs/ticket_list_state.dart
Normal file
69
lib/features/tickets/blocs/ticket_list_state.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
|
||||
class TicketListState extends Equatable {
|
||||
final List<TicketModel> tickets;
|
||||
final bool isLoading;
|
||||
final bool hasReachedMax;
|
||||
final String errorMessage;
|
||||
|
||||
// Filtri attivi
|
||||
final String? searchTerm;
|
||||
final DateTimeRange? dateRange;
|
||||
final TicketStatus? statusFilter;
|
||||
final TicketType? ticketTypeFilter;
|
||||
final String? staffIdFilter;
|
||||
|
||||
const TicketListState({
|
||||
this.tickets = const [],
|
||||
this.isLoading = false,
|
||||
this.hasReachedMax = false,
|
||||
this.errorMessage = '',
|
||||
this.searchTerm,
|
||||
this.dateRange,
|
||||
this.statusFilter,
|
||||
this.ticketTypeFilter,
|
||||
this.staffIdFilter,
|
||||
});
|
||||
|
||||
TicketListState copyWith({
|
||||
List<TicketModel>? tickets,
|
||||
bool? isLoading,
|
||||
bool? hasReachedMax,
|
||||
String? errorMessage,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
TicketStatus? statusFilter,
|
||||
TicketType? ticketTypeFilter,
|
||||
String? staffIdFilter,
|
||||
bool clearSearch = false,
|
||||
bool clearDate = false,
|
||||
bool clearStatus = false,
|
||||
}) {
|
||||
return TicketListState(
|
||||
tickets: tickets ?? this.tickets,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
searchTerm: clearSearch ? null : (searchTerm ?? this.searchTerm),
|
||||
dateRange: clearDate ? null : (dateRange ?? this.dateRange),
|
||||
statusFilter: clearStatus ? null : (statusFilter ?? this.statusFilter),
|
||||
ticketTypeFilter: ticketTypeFilter ?? this.ticketTypeFilter,
|
||||
staffIdFilter: staffIdFilter ?? this.staffIdFilter,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
tickets,
|
||||
isLoading,
|
||||
hasReachedMax,
|
||||
errorMessage,
|
||||
searchTerm,
|
||||
dateRange,
|
||||
statusFilter,
|
||||
ticketTypeFilter,
|
||||
staffIdFilter,
|
||||
];
|
||||
}
|
||||
238
lib/features/tickets/data/ticket_repository.dart
Normal file
238
lib/features/tickets/data/ticket_repository.dart
Normal file
@@ -0,0 +1,238 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class TicketRepository {
|
||||
final SupabaseClient _supabase = GetIt.I.get<SupabaseClient>();
|
||||
|
||||
TicketRepository();
|
||||
|
||||
static const String _tableName = 'ticket';
|
||||
|
||||
// --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI UNO STORE ---
|
||||
Future<List<TicketModel>> fetchStoreTickets({
|
||||
required int offset,
|
||||
int limit = 50,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
TicketStatus? statusFilter,
|
||||
TicketType? ticketTypeFilter,
|
||||
String? staffIdFilter,
|
||||
}) async {
|
||||
try {
|
||||
var query = _supabase
|
||||
.from(_tableName)
|
||||
.select('''
|
||||
*,
|
||||
customer (*),
|
||||
created_by:staff_member!ticket_staff_id_fkey (*),
|
||||
assigned_to:staff_member!ticket_assigned_to_id_fkey (*),
|
||||
target_model:model!ticket_model_id_1_fkey (*),
|
||||
source_model:model!ticket_model_id_2_fkey (*)
|
||||
''')
|
||||
.eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!);
|
||||
|
||||
// Filtro Range Date
|
||||
if (dateRange != null) {
|
||||
query = query
|
||||
.gte('created_at', dateRange.start.toIso8601String())
|
||||
.lte('created_at', dateRange.end.toIso8601String());
|
||||
}
|
||||
|
||||
if (statusFilter != null) {
|
||||
query = query.eq('status', statusFilter.value);
|
||||
}
|
||||
|
||||
if (ticketTypeFilter != null) {
|
||||
query = query.eq('ticket_type', ticketTypeFilter.value);
|
||||
}
|
||||
|
||||
if (staffIdFilter != null) {
|
||||
query = query.eq('staff_id', staffIdFilter);
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.isNotEmpty) {
|
||||
// Filtra sui campi della tabella principale O su quelli della tabella joinata
|
||||
query = query.or('customer.name.ilike.%$searchTerm%');
|
||||
}
|
||||
|
||||
final response = await query
|
||||
.order('created_at', ascending: false)
|
||||
.range(offset, offset + limit - 1);
|
||||
|
||||
return (response as List).map((map) => TicketModel.fromMap(map)).toList();
|
||||
} catch (e) {
|
||||
throw Exception('$e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI TUTTA L'AZIENDA ---
|
||||
Future<List<TicketModel>> fetchCompanyTickets({
|
||||
required int offset,
|
||||
int limit = 50,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
TicketStatus? ticketStatusFilter,
|
||||
TicketType? ticketTypeFilter,
|
||||
String? staffIdFilter,
|
||||
}) async {
|
||||
try {
|
||||
var query = _supabase
|
||||
.from(_tableName)
|
||||
.select('''
|
||||
*,
|
||||
customer (*),
|
||||
created_by:staff_member!ticket_staff_id_fkey (*),
|
||||
assigned_to:staff_member!ticket_assigned_to_id_fkey (*),
|
||||
target_model:model!ticket_model_id_1_fkey (*),
|
||||
source_model:model!ticket_model_id_2_fkey (*)
|
||||
''')
|
||||
.eq('company_id', GetIt.I.get<SessionCubit>().state.company!.id!);
|
||||
|
||||
// Filtro Range Date
|
||||
if (dateRange != null) {
|
||||
query = query
|
||||
.gte('created_at', dateRange.start.toIso8601String())
|
||||
.lte('created_at', dateRange.end.toIso8601String());
|
||||
}
|
||||
|
||||
if (ticketStatusFilter != null) {
|
||||
query = query.eq('status', ticketStatusFilter.value);
|
||||
}
|
||||
|
||||
if (ticketTypeFilter != null) {
|
||||
query = query.eq('ticket_type', ticketTypeFilter.value);
|
||||
}
|
||||
|
||||
if (staffIdFilter != null) {
|
||||
query = query.eq('staff_id', staffIdFilter);
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.isNotEmpty) {
|
||||
// Filtra sui campi della tabella principale O su quelli della tabella joinata
|
||||
query = query.or('customer.name.ilike.%$searchTerm%');
|
||||
}
|
||||
|
||||
final response = await query
|
||||
.order('created_at', ascending: false)
|
||||
.range(offset, offset + limit - 1);
|
||||
|
||||
return (response as List).map((map) => TicketModel.fromMap(map)).toList();
|
||||
} catch (e) {
|
||||
throw Exception('$e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream dei ticket che necessitano attenzione (es. in scadenza oggi o in ritardo)
|
||||
Stream<List<TicketModel>> getAttentionNeededTicketsStream() {
|
||||
return _supabase
|
||||
.from(_tableName)
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!)
|
||||
// Purtroppo lo stream accetta solo filtri base, quindi ci facciamo
|
||||
// mandare i dati e li filtriamo con la potenza di Dart!
|
||||
.limit(300)
|
||||
.map((listOfMaps) {
|
||||
final now = DateTime.now();
|
||||
final endOfToday = DateTime(now.year, now.month, now.day, 23, 59, 59);
|
||||
|
||||
// 1. Mappiamo tutto in TicketModel
|
||||
final allStoreTickets = listOfMaps
|
||||
.map((map) => TicketModel.fromMap(map))
|
||||
.toList();
|
||||
|
||||
// 2. Filtriamo in memoria!
|
||||
final urgentTickets = allStoreTickets.where((ticket) {
|
||||
// Escludiamo quelli già chiusi o consegnati
|
||||
if (ticket.ticketStatus == TicketStatus.closed ||
|
||||
ticket.ticketStatus == TicketStatus.ready) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Se c'è una data di consegna stimata ed è <= a stasera, è urgente!
|
||||
if (ticket.estimatedDeliveryAt != null) {
|
||||
return ticket.estimatedDeliveryAt!.isBefore(endOfToday);
|
||||
}
|
||||
|
||||
return false;
|
||||
}).toList();
|
||||
|
||||
// 3. Li ordiniamo mettendo i più vecchi/urgenti in cima
|
||||
urgentTickets.sort(
|
||||
(a, b) => a.estimatedDeliveryAt!.compareTo(b.estimatedDeliveryAt!),
|
||||
);
|
||||
|
||||
return urgentTickets;
|
||||
});
|
||||
}
|
||||
|
||||
/// Recupera un ticket specifico CON TUTTE LE RELAZIONI espanse (Cliente e Modelli)
|
||||
/// Questa è la vera magia di Supabase!
|
||||
Future<TicketModel> getTicketById(String ticketId) async {
|
||||
try {
|
||||
// Usiamo i nomi esatti delle Foreign Key che hai definito nell'SQL!
|
||||
final response = await _supabase
|
||||
.from(_tableName)
|
||||
.select('''
|
||||
*,
|
||||
customer (*),
|
||||
target_model:model!ticket_model_id_1_fkey (*),
|
||||
source_model:model!ticket_model_id_2_fkey (*),
|
||||
created_by:staff_member!ticket_staff_id_fkey (*),
|
||||
assigned_to:staff_member!ticket_assigned_to_id_fkey (*),
|
||||
''')
|
||||
.eq('id', ticketId)
|
||||
.single();
|
||||
|
||||
return TicketModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nel recupero del dettaglio ticket: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Salva il ticket con upsert
|
||||
Future<TicketModel> saveTicket(TicketModel ticket) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(_tableName)
|
||||
.upsert(ticket.toMap())
|
||||
.select()
|
||||
.single();
|
||||
|
||||
return TicketModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nella creazione del ticket: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggiorna un ticket esistente
|
||||
Future<TicketModel> updateTicket(TicketModel ticket) async {
|
||||
if (ticket.id == null) {
|
||||
throw Exception('Impossibile aggiornare un ticket senza ID');
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(_tableName)
|
||||
.update(ticket.toMap())
|
||||
.eq('id', ticket.id!)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
return TicketModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nell\'aggiornamento del ticket: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Elimina (o annulla) un ticket
|
||||
Future<void> deleteTicket(String ticketId) async {
|
||||
try {
|
||||
await _supabase.from(_tableName).delete().eq('id', ticketId);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nell\'eliminazione del ticket: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
367
lib/features/tickets/models/ticket_model.dart
Normal file
367
lib/features/tickets/models/ticket_model.dart
Normal file
@@ -0,0 +1,367 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
|
||||
/// Enum per il tipo di ticket
|
||||
enum TicketType {
|
||||
repair('repair', 'Riparazione'),
|
||||
softwareSetup('software_setup', 'Setup software'),
|
||||
dataTransfer('data_transfer', 'Trasferimento dati'),
|
||||
operationTicket('operation_ticket', 'Ticket di operazione'),
|
||||
other('other', 'Altro');
|
||||
|
||||
final String value;
|
||||
final String displayValue;
|
||||
const TicketType(this.value, this.displayValue);
|
||||
|
||||
static TicketType fromString(String val) {
|
||||
return TicketType.values.firstWhere(
|
||||
(e) => e.value == val,
|
||||
orElse: () => TicketType.other,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enum per lo stato del ticket
|
||||
enum TicketStatus {
|
||||
open('open', 'Aperto'),
|
||||
inProgress('in_progress', 'In corso'),
|
||||
waitingForParts('waiting_for_parts', 'In attesa di ricambi'),
|
||||
ready('ready', 'Pronto'),
|
||||
closed('closed', 'Chiuso'),
|
||||
waitingForShipping('waiting_for_shipping', 'In attesa di spedire'),
|
||||
waitingForReturn('waiting_for_return', 'In attesa di ritorno');
|
||||
|
||||
final String value;
|
||||
final String displayValue;
|
||||
const TicketStatus(this.value, this.displayValue);
|
||||
|
||||
static TicketStatus fromString(String? val) {
|
||||
return TicketStatus.values.firstWhere(
|
||||
(e) => e.value == val,
|
||||
orElse: () => TicketStatus.open,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enum per il risultato del ticket (OK / KO)
|
||||
enum TicketResult {
|
||||
success('success', 'Risolto (OK)'),
|
||||
failure('failure', 'Non Risolto (KO)');
|
||||
|
||||
final String value;
|
||||
final String displayValue;
|
||||
const TicketResult(this.value, this.displayValue);
|
||||
|
||||
static TicketResult? fromString(String? val) {
|
||||
if (val == null) return null;
|
||||
return TicketResult.values.firstWhere(
|
||||
(e) => e.value == val,
|
||||
orElse: () => TicketResult.success,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enum per il tipo di garanzia
|
||||
enum WarrantyType {
|
||||
manufacturerWarranty('manufacturer_warranty', 'Garanzia produttore'),
|
||||
providerWarranty('provider_warranty', 'Garanzia gestore'),
|
||||
internalWarranty('internal_warranty', 'Garanzia interna'),
|
||||
noWarranty('no_warranty', 'Fuori garanzia');
|
||||
|
||||
final String value;
|
||||
final String displayValue;
|
||||
const WarrantyType(this.value, this.displayValue);
|
||||
|
||||
static WarrantyType? fromString(String? val) {
|
||||
return WarrantyType.values.firstWhere(
|
||||
(e) => e.value == val,
|
||||
orElse: () => WarrantyType.noWarranty,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class TicketModel extends Equatable {
|
||||
final String? id; // Null se non ancora salvato
|
||||
final DateTime? createdAt;
|
||||
final String companyId;
|
||||
final String? storeId;
|
||||
final String? customerId;
|
||||
final String? targetModelId;
|
||||
final String? targetSn;
|
||||
final String? sourceModelId;
|
||||
final String? sourceSn;
|
||||
final double customerPrice;
|
||||
final double internalCost;
|
||||
final DateTime? closedAt;
|
||||
final DateTime? returnedAt;
|
||||
final String request;
|
||||
final WarrantyType? warrantyType;
|
||||
final String? publicNotes;
|
||||
final String? internalNotes;
|
||||
final int? referenceNumber;
|
||||
final String? alternativePhoneNumber;
|
||||
final bool hasCourtesyDevice;
|
||||
final TicketType ticketType;
|
||||
final TicketStatus ticketStatus;
|
||||
final DateTime? estimatedDeliveryAt;
|
||||
final TicketResult? ticketResult;
|
||||
final String? resolutionNotes;
|
||||
final String? legacyId;
|
||||
final String? customerName;
|
||||
final String? targetModelName;
|
||||
final String? sourceModelName;
|
||||
final String? createdById;
|
||||
final String? createdByName;
|
||||
final String? assignedToId;
|
||||
final String? assignedToName;
|
||||
final String? includedAccessories;
|
||||
|
||||
const TicketModel({
|
||||
this.id,
|
||||
this.createdAt,
|
||||
required this.companyId,
|
||||
this.storeId,
|
||||
this.customerId,
|
||||
this.targetModelId,
|
||||
this.targetSn,
|
||||
this.sourceModelId,
|
||||
this.sourceSn,
|
||||
this.customerPrice = 0.0,
|
||||
this.internalCost = 0.0,
|
||||
this.closedAt,
|
||||
this.returnedAt,
|
||||
this.request = '',
|
||||
this.warrantyType,
|
||||
this.publicNotes,
|
||||
this.internalNotes,
|
||||
this.referenceNumber,
|
||||
this.alternativePhoneNumber,
|
||||
this.hasCourtesyDevice = false,
|
||||
required this.ticketType,
|
||||
this.ticketStatus = TicketStatus.closed,
|
||||
this.estimatedDeliveryAt,
|
||||
this.ticketResult,
|
||||
this.resolutionNotes,
|
||||
this.legacyId,
|
||||
this.customerName,
|
||||
this.targetModelName,
|
||||
this.sourceModelName,
|
||||
this.createdById,
|
||||
this.createdByName,
|
||||
this.assignedToId,
|
||||
this.assignedToName,
|
||||
this.includedAccessories,
|
||||
});
|
||||
|
||||
/// Factory per creare un ticket vuoto (utile per i form di creazione)
|
||||
factory TicketModel.empty({String? companyId, String? storeId}) {
|
||||
return TicketModel(
|
||||
companyId: companyId ?? '',
|
||||
storeId: storeId,
|
||||
ticketType: TicketType.repair, // Valore di default
|
||||
ticketStatus: TicketStatus.open,
|
||||
customerPrice: 0.0,
|
||||
internalCost: 0.0,
|
||||
hasCourtesyDevice: false,
|
||||
request: '',
|
||||
);
|
||||
}
|
||||
|
||||
TicketModel copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
String? companyId,
|
||||
String? storeId,
|
||||
String? customerId,
|
||||
String? targetModelId,
|
||||
String? targetSn,
|
||||
String? sourceModelId,
|
||||
String? sourceSn,
|
||||
double? customerPrice,
|
||||
double? internalCost,
|
||||
DateTime? closedAt,
|
||||
DateTime? returnedAt,
|
||||
String? request,
|
||||
WarrantyType? warrantyType,
|
||||
String? publicNotes,
|
||||
String? internalNotes,
|
||||
int? referenceNumber,
|
||||
String? alternativePhoneNumber,
|
||||
bool? hasCourtesyDevice,
|
||||
TicketType? ticketType,
|
||||
TicketStatus? ticketStatus,
|
||||
DateTime? estimatedDeliveryAt,
|
||||
TicketResult? ticketResult,
|
||||
String? resolutionNotes,
|
||||
String? legacyId,
|
||||
String? customerName,
|
||||
String? targetModelName,
|
||||
String? sourceModelName,
|
||||
String? createdById,
|
||||
String? createdByName,
|
||||
String? assignedToId,
|
||||
String? assignedToName,
|
||||
String? includedAccessories,
|
||||
}) {
|
||||
return TicketModel(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
companyId: companyId ?? this.companyId,
|
||||
storeId: storeId ?? this.storeId,
|
||||
customerId: customerId ?? this.customerId,
|
||||
targetModelId: targetModelId ?? this.targetModelId,
|
||||
targetSn: targetSn ?? this.targetSn,
|
||||
sourceModelId: sourceModelId ?? this.sourceModelId,
|
||||
sourceSn: sourceSn ?? this.sourceSn,
|
||||
customerPrice: customerPrice ?? this.customerPrice,
|
||||
internalCost: internalCost ?? this.internalCost,
|
||||
closedAt: closedAt ?? this.closedAt,
|
||||
returnedAt: returnedAt ?? this.returnedAt,
|
||||
request: request ?? this.request,
|
||||
warrantyType: warrantyType ?? this.warrantyType,
|
||||
publicNotes: publicNotes ?? this.publicNotes,
|
||||
internalNotes: internalNotes ?? this.internalNotes,
|
||||
referenceNumber: referenceNumber ?? this.referenceNumber,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? this.alternativePhoneNumber,
|
||||
hasCourtesyDevice: hasCourtesyDevice ?? this.hasCourtesyDevice,
|
||||
ticketType: ticketType ?? this.ticketType,
|
||||
ticketStatus: ticketStatus ?? this.ticketStatus,
|
||||
estimatedDeliveryAt: estimatedDeliveryAt ?? this.estimatedDeliveryAt,
|
||||
ticketResult: ticketResult ?? this.ticketResult,
|
||||
resolutionNotes: resolutionNotes ?? this.resolutionNotes,
|
||||
legacyId: legacyId ?? this.legacyId,
|
||||
customerName: customerName ?? this.customerName,
|
||||
targetModelName: targetModelName ?? this.targetModelName,
|
||||
sourceModelName: sourceModelName ?? this.sourceModelName,
|
||||
createdById: createdById ?? this.createdById,
|
||||
createdByName: createdByName ?? this.createdByName,
|
||||
assignedToId: assignedToId ?? this.assignedToId,
|
||||
assignedToName: assignedToName ?? this.assignedToName,
|
||||
includedAccessories: includedAccessories ?? this.includedAccessories,
|
||||
);
|
||||
}
|
||||
|
||||
/// Deserializzazione da Supabase
|
||||
factory TicketModel.fromMap(Map<String, dynamic> map) {
|
||||
return TicketModel(
|
||||
id: map['id'] as String,
|
||||
createdAt: map['created_at'] != null
|
||||
? DateTime.parse(map['created_at']).toLocal()
|
||||
: null,
|
||||
companyId: map['company_id'] as String,
|
||||
storeId: map['store_id'] as String?,
|
||||
customerId: map['customer_id'] as String?,
|
||||
targetModelId: map['target_model_id'] as String?,
|
||||
targetSn: map['target_sn'] as String?,
|
||||
sourceModelId: map['source_model_id'] as String?,
|
||||
sourceSn: map['source_sn'] as String?,
|
||||
// Fix per i field numerici di Postgres che potrebbero arrivare come int o double
|
||||
customerPrice: (map['customer_price'] as num?)?.toDouble() ?? 0.0,
|
||||
internalCost: (map['internal_cost'] as num?)?.toDouble() ?? 0.0,
|
||||
closedAt: map['closed_at'] != null
|
||||
? DateTime.parse(map['closed_at']).toLocal()
|
||||
: null,
|
||||
returnedAt: map['returned_at'] != null
|
||||
? DateTime.parse(map['returned_at']).toLocal()
|
||||
: null,
|
||||
request: map['request'] as String? ?? '',
|
||||
warrantyType: WarrantyType.fromString(map['warranty_type'] as String?),
|
||||
publicNotes: map['public_notes'] as String?,
|
||||
internalNotes: map['internal_notes'] as String?,
|
||||
referenceNumber: map['reference_number'] as int?,
|
||||
alternativePhoneNumber: map['alternative_phone_number'] as String?,
|
||||
hasCourtesyDevice: map['has_courtesy_device'] as bool? ?? false,
|
||||
ticketType: TicketType.fromString(map['ticket_type'] as String),
|
||||
ticketStatus: TicketStatus.fromString(map['ticket_status'] as String),
|
||||
estimatedDeliveryAt: map['estimated_delivery_at'] != null
|
||||
? DateTime.parse(map['estimated_delivery_at']).toLocal()
|
||||
: null,
|
||||
ticketResult: TicketResult.fromString(map['ticket_result'] as String?),
|
||||
resolutionNotes: map['resolution_notes'] as String?,
|
||||
legacyId: map['legacy_id'] as String?,
|
||||
customerName: (map['customer']?['name'] as String?).myFormat(),
|
||||
targetModelName: (map['target_model']?['name_with_brand'] as String?)
|
||||
?.myFormat(),
|
||||
sourceModelName: (map['source_model']?['name_with_brand'] as String?)
|
||||
?.myFormat(),
|
||||
createdById: map['staff_id'] as String?,
|
||||
createdByName: (map['staff']?['name'] as String?).myFormat(),
|
||||
assignedToId: map['assigned_to_id'] as String?,
|
||||
assignedToName: (map['assigned_to']?['name'] as String?).myFormat(),
|
||||
includedAccessories: map['included_accessories'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializzazione per Supabase
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
if (id != null) 'id': id,
|
||||
'company_id': companyId,
|
||||
'store_id': storeId,
|
||||
'customer_id': customerId,
|
||||
'target_model_id': targetModelId,
|
||||
'target_sn': targetSn,
|
||||
'source_model_id': sourceModelId,
|
||||
'source_sn': sourceSn,
|
||||
'customer_price': customerPrice,
|
||||
'internal_cost': internalCost,
|
||||
if (closedAt != null) 'closed_at': closedAt!.toUtc().toIso8601String(),
|
||||
if (returnedAt != null)
|
||||
'returned_at': returnedAt!.toUtc().toIso8601String(),
|
||||
'request': request,
|
||||
'created_by_id': createdById,
|
||||
'warranty_type': warrantyType,
|
||||
'public_notes': publicNotes,
|
||||
'internal_notes': internalNotes,
|
||||
'alternative_phone_number': alternativePhoneNumber,
|
||||
'has_courtesy_device': hasCourtesyDevice,
|
||||
'ticket_type': ticketType.value,
|
||||
'ticket_status': ticketStatus.value,
|
||||
if (estimatedDeliveryAt != null)
|
||||
'estimated_delivery_at': estimatedDeliveryAt!.toUtc().toIso8601String(),
|
||||
if (ticketResult != null) 'ticket_result': ticketResult!.value,
|
||||
'resolution_notes': resolutionNotes,
|
||||
'legacy_id': legacyId,
|
||||
'included_accessories': includedAccessories,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
createdAt,
|
||||
companyId,
|
||||
storeId,
|
||||
customerId,
|
||||
targetModelId,
|
||||
targetSn,
|
||||
sourceModelId,
|
||||
sourceSn,
|
||||
customerPrice,
|
||||
internalCost,
|
||||
closedAt,
|
||||
returnedAt,
|
||||
request,
|
||||
warrantyType,
|
||||
publicNotes,
|
||||
internalNotes,
|
||||
referenceNumber,
|
||||
alternativePhoneNumber,
|
||||
hasCourtesyDevice,
|
||||
ticketType,
|
||||
ticketStatus,
|
||||
estimatedDeliveryAt,
|
||||
ticketResult,
|
||||
resolutionNotes,
|
||||
legacyId,
|
||||
includedAccessories,
|
||||
customerName,
|
||||
targetModelName,
|
||||
sourceModelName,
|
||||
createdById,
|
||||
createdByName,
|
||||
assignedToId,
|
||||
assignedToName,
|
||||
];
|
||||
}
|
||||
43
lib/features/tickets/models/ticket_status_extension.dart
Normal file
43
lib/features/tickets/models/ticket_status_extension.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
|
||||
extension TicketStatusVisuals on TicketStatus {
|
||||
Color get color {
|
||||
switch (this) {
|
||||
case TicketStatus.open:
|
||||
return Colors.blueGrey;
|
||||
case TicketStatus.waitingForParts:
|
||||
return Colors.amber.shade700;
|
||||
case TicketStatus.inProgress:
|
||||
return Colors.blue;
|
||||
case TicketStatus.waitingForShipping:
|
||||
// Il tuo rosa storico!
|
||||
return Colors.pinkAccent;
|
||||
case TicketStatus.waitingForReturn:
|
||||
return Colors.purpleAccent;
|
||||
case TicketStatus.ready:
|
||||
return Colors.green;
|
||||
case TicketStatus.closed:
|
||||
return Colors.grey.shade400;
|
||||
}
|
||||
}
|
||||
|
||||
IconData get icon {
|
||||
switch (this) {
|
||||
case TicketStatus.open:
|
||||
return Icons.inbox;
|
||||
case TicketStatus.waitingForParts:
|
||||
return Icons.hourglass_empty;
|
||||
case TicketStatus.inProgress:
|
||||
return Icons.build;
|
||||
case TicketStatus.waitingForShipping:
|
||||
return Icons.local_shipping_outlined;
|
||||
case TicketStatus.waitingForReturn:
|
||||
return Icons.undo;
|
||||
case TicketStatus.ready:
|
||||
return Icons.check_circle_outline;
|
||||
case TicketStatus.closed:
|
||||
return Icons.lock_outline;
|
||||
}
|
||||
}
|
||||
}
|
||||
597
lib/features/tickets/ui/ticket_form_screen.dart
Normal file
597
lib/features/tickets/ui/ticket_form_screen.dart
Normal file
@@ -0,0 +1,597 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/customer_section.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/model_section.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/shared_files_section.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_form_cubit.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_form_state.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/staff_section.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
|
||||
|
||||
class TicketFormScreen extends StatefulWidget {
|
||||
final TicketModel? existingTicket;
|
||||
final String? ticketId;
|
||||
|
||||
const TicketFormScreen({super.key, this.existingTicket, this.ticketId});
|
||||
|
||||
@override
|
||||
State<TicketFormScreen> createState() => _TicketFormScreenState();
|
||||
}
|
||||
|
||||
class _TicketFormScreenState extends State<TicketFormScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
final _altPhoneCtrl = TextEditingController();
|
||||
final _serialCtrl = TextEditingController();
|
||||
final _requestCtrl = TextEditingController();
|
||||
final _accessoriesCtrl = TextEditingController();
|
||||
final _publicNotesCtrl = TextEditingController();
|
||||
final _internalNotesCtrl = TextEditingController();
|
||||
final _priceCtrl = TextEditingController();
|
||||
final _costCtrl = TextEditingController();
|
||||
|
||||
bool _isInitialized = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<TicketFormCubit>().initForm(
|
||||
existingTicket: widget.existingTicket,
|
||||
id: widget.ticketId,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_altPhoneCtrl.dispose();
|
||||
_serialCtrl.dispose();
|
||||
_requestCtrl.dispose();
|
||||
_accessoriesCtrl.dispose();
|
||||
_publicNotesCtrl.dispose();
|
||||
_internalNotesCtrl.dispose();
|
||||
_priceCtrl.dispose();
|
||||
_costCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _syncTextControllers(TicketModel model) {
|
||||
if (_altPhoneCtrl.text.isEmpty) {
|
||||
_altPhoneCtrl.text = model.alternativePhoneNumber ?? '';
|
||||
}
|
||||
if (_serialCtrl.text.isEmpty) _serialCtrl.text = model.targetSn ?? '';
|
||||
if (_requestCtrl.text.isEmpty) _requestCtrl.text = model.request;
|
||||
if (_accessoriesCtrl.text.isEmpty) {
|
||||
_accessoriesCtrl.text = model.includedAccessories ?? '';
|
||||
}
|
||||
if (_publicNotesCtrl.text.isEmpty) {
|
||||
_publicNotesCtrl.text = model.publicNotes ?? '';
|
||||
}
|
||||
if (_internalNotesCtrl.text.isEmpty) {
|
||||
_internalNotesCtrl.text = model.internalNotes ?? '';
|
||||
}
|
||||
if (_priceCtrl.text.isEmpty && model.customerPrice > 0) {
|
||||
_priceCtrl.text = model.customerPrice.toString();
|
||||
}
|
||||
if (_costCtrl.text.isEmpty && model.internalCost > 0) {
|
||||
_costCtrl.text = model.internalCost.toString();
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
void _flushControllersToCubit() {
|
||||
context.read<TicketFormCubit>().updateFields(
|
||||
alternativePhoneNumber: _altPhoneCtrl.text,
|
||||
targetSn: _serialCtrl.text,
|
||||
request: _requestCtrl.text,
|
||||
includedAccessories: _accessoriesCtrl.text,
|
||||
publicNotes: _publicNotesCtrl.text,
|
||||
internalNotes: _internalNotesCtrl.text,
|
||||
customerPrice: double.tryParse(_priceCtrl.text) ?? 0.0,
|
||||
internalCost: double.tryParse(_costCtrl.text) ?? 0.0,
|
||||
);
|
||||
}
|
||||
|
||||
void _saveTicket({required bool keepAdding}) {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
_flushControllersToCubit();
|
||||
context.read<TicketFormCubit>().saveTicket(keepAdding: keepAdding);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _generateIdForQr() async {
|
||||
// 1. Validiamo i campi obbligatori (es. il cliente)
|
||||
if (!_formKey.currentState!.validate()) return null;
|
||||
|
||||
// 2. Sincronizziamo i testi scritti a mano nel Cubit
|
||||
_flushControllersToCubit();
|
||||
|
||||
// 3. Facciamo il salvataggio silenzioso
|
||||
final newId = await context.read<TicketFormCubit>().saveTicketDraft();
|
||||
|
||||
if (newId != null && context.mounted) {
|
||||
// 4. IL TOCCO DI CLASSE: Diciamo all'AttachmentsBloc che ora la pratica ha un ID!
|
||||
// Questo farà partire l'upload automatico di eventuali file "in bozza"
|
||||
context.read<AttachmentsBloc>().add(ParentEntitySavedEvent(newId));
|
||||
}
|
||||
|
||||
return newId;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocConsumer<TicketFormCubit, TicketFormState>(
|
||||
listenWhen: (previous, current) => previous.status != current.status,
|
||||
listener: (context, state) {
|
||||
if (state.status == TicketFormStatus.ready && !_isInitialized) {
|
||||
_syncTextControllers(state.ticket);
|
||||
}
|
||||
|
||||
if (state.status == TicketFormStatus.success) {
|
||||
Navigator.of(context).pop();
|
||||
} else if (state.status == TicketFormStatus.successAndAddAnother) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Scheda salvata! Inserisci la prossima.'),
|
||||
),
|
||||
);
|
||||
_altPhoneCtrl.clear();
|
||||
_serialCtrl.clear();
|
||||
_requestCtrl.clear();
|
||||
_accessoriesCtrl.clear();
|
||||
_publicNotesCtrl.clear();
|
||||
_internalNotesCtrl.clear();
|
||||
_priceCtrl.clear();
|
||||
_costCtrl.clear();
|
||||
_isInitialized = false;
|
||||
} else if (state.status == TicketFormStatus.failure) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.errorMessage ?? 'Errore di salvataggio'),
|
||||
backgroundColor: theme.colorScheme.error,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final ticket = state.ticket;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(
|
||||
ticket.id == null ? 'Nuova Scheda Assistenza' : 'Modifica Scheda',
|
||||
),
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 16.0),
|
||||
child: Chip(
|
||||
label: Text(
|
||||
ticket.ticketStatus.name.toUpperCase(),
|
||||
style: const TextStyle(color: Colors.white, fontSize: 10),
|
||||
),
|
||||
backgroundColor: ticket.ticketStatus.color,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Form(
|
||||
key: _formKey,
|
||||
// IL TRUCCO PER LA TASTIERA: Obblighiamo il tab a seguire il DOM
|
||||
child: FocusTraversalGroup(
|
||||
policy: WidgetOrderTraversalPolicy(),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isUltraWide = constraints.maxWidth > 1400;
|
||||
final isDesktop = constraints.maxWidth > 900;
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: isUltraWide
|
||||
? 1600
|
||||
: (isDesktop ? 1200 : 800),
|
||||
),
|
||||
child: _buildResponsiveLayout(
|
||||
isUltraWide,
|
||||
isDesktop,
|
||||
ticket,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
bottomNavigationBar: SafeArea(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.scaffoldBackgroundColor,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.05),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, -3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: FocusTraversalGroup(
|
||||
// Un gruppo a parte per il footer, così viene visitato per ultimo
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: OutlinedButton(
|
||||
onPressed: state.status == TicketFormStatus.saving
|
||||
? null
|
||||
: () => _saveTicket(keepAdding: true),
|
||||
child: const Text(
|
||||
'Salva e Aggiungi Altro',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: ElevatedButton(
|
||||
onPressed: state.status == TicketFormStatus.saving
|
||||
? null
|
||||
: () => _saveTicket(keepAdding: false),
|
||||
child: state.status == TicketFormStatus.saving
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
color: Colors.white,
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: const Text('Salva ed Esci'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// --- LOGICA DI IMPAGINAZIONE RESPONSIVE ---
|
||||
Widget _buildResponsiveLayout(
|
||||
bool isUltraWide,
|
||||
bool isDesktop,
|
||||
TicketModel ticket,
|
||||
) {
|
||||
if (isUltraWide) {
|
||||
// 3 COLONNE
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [_cardAnagrafica(ticket), _cardDispositivo(ticket)],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 24),
|
||||
Expanded(child: Column(children: [_cardDettagli(ticket)])),
|
||||
const SizedBox(width: 24),
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [_cardCosti(ticket), _cardAssegnazione(ticket)],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else if (isDesktop) {
|
||||
// 2 COLONNE
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [
|
||||
_cardAnagrafica(ticket),
|
||||
_cardDispositivo(ticket),
|
||||
_cardAssegnazione(ticket),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 24),
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [_cardDettagli(ticket), _cardCosti(ticket)],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
// 1 COLONNA (Mobile)
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_cardAnagrafica(ticket),
|
||||
_cardDispositivo(ticket),
|
||||
_cardDettagli(ticket),
|
||||
_cardCosti(ticket),
|
||||
_cardAssegnazione(ticket),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- LE 5 CARD (MODULARIZZATE E COLORATE) ---
|
||||
|
||||
Widget _cardAnagrafica(TicketModel ticket) {
|
||||
return _buildCard(
|
||||
title: 'Anagrafica',
|
||||
icon: Icons.person,
|
||||
themeColor: Colors.indigo,
|
||||
children: [
|
||||
StaffSection(
|
||||
label: 'Creato Da',
|
||||
staffId: ticket.createdById,
|
||||
staffName: ticket.createdByName,
|
||||
onStaffSelected: (staff) => context
|
||||
.read<TicketFormCubit>()
|
||||
.updateCreator(staffId: staff.id!, staffName: staff.name),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
SharedCustomerSection(
|
||||
customerId: ticket.customerId,
|
||||
customerName: ticket.customerName,
|
||||
onCustomerSelected: (customer) =>
|
||||
context.read<TicketFormCubit>().updateCustomer(customer),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _altPhoneCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Recapito Alternativo',
|
||||
prefixIcon: Icon(Icons.phone),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardDispositivo(TicketModel ticket) {
|
||||
return _buildCard(
|
||||
title: 'Dispositivo',
|
||||
icon: Icons.devices,
|
||||
themeColor: Colors.deepOrange,
|
||||
children: [
|
||||
SharedModelSection(
|
||||
label: 'Modello da Riparare',
|
||||
modelId: ticket.targetModelId,
|
||||
modelName: ticket.targetModelName,
|
||||
onModelSelected: (id, name) => context
|
||||
.read<TicketFormCubit>()
|
||||
.updateModel(modelId: id, modelName: name),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _serialCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Seriale / IMEI',
|
||||
prefixIcon: Icon(Icons.qr_code),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardDettagli(TicketModel ticket) {
|
||||
return _buildCard(
|
||||
title: 'Dettagli Riparazione',
|
||||
icon: Icons.build,
|
||||
themeColor: Colors.pink,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<TicketType>(
|
||||
initialValue: ticket.ticketType,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Tipo Lavorazione',
|
||||
),
|
||||
items: TicketType.values
|
||||
.map((t) => DropdownMenuItem(value: t, child: Text(t.name)))
|
||||
.toList(),
|
||||
onChanged: (val) => context
|
||||
.read<TicketFormCubit>()
|
||||
.updateFields(ticketType: val),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<TicketStatus>(
|
||||
initialValue: ticket.ticketStatus,
|
||||
decoration: const InputDecoration(labelText: 'Stato Attuale'),
|
||||
items: TicketStatus.values
|
||||
.map((s) => DropdownMenuItem(value: s, child: Text(s.name)))
|
||||
.toList(),
|
||||
onChanged: (val) =>
|
||||
context.read<TicketFormCubit>().updateFields(status: val),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _requestCtrl,
|
||||
maxLines: 4,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Difetto dichiarato o Richiesta del cliente',
|
||||
alignLabelWithHint: true,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _accessoriesCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Accessori Consegnati',
|
||||
prefixIcon: Icon(Icons.cable),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SwitchListTile(
|
||||
title: const Text('Prestato Telefono di Cortesia?'),
|
||||
value: ticket.hasCourtesyDevice,
|
||||
onChanged: (val) => context.read<TicketFormCubit>().updateFields(
|
||||
hasCourtesyDevice: val,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
side: BorderSide(color: Theme.of(context).dividerColor),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardCosti(TicketModel ticket) {
|
||||
return _buildCard(
|
||||
title: 'Costi & Note',
|
||||
icon: Icons.euro,
|
||||
themeColor: Colors.teal,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _priceCtrl,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Preventivo Cliente (€)',
|
||||
prefixIcon: Icon(Icons.sell_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _costCtrl,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nostro Costo (€)',
|
||||
prefixIcon: Icon(Icons.shopping_cart_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _publicNotesCtrl,
|
||||
maxLines: 2,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Note Pubbliche (Visibili su ricevuta)',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _internalNotesCtrl,
|
||||
maxLines: 3,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Note Interne (Solo per lo Staff)',
|
||||
fillColor: Colors.amber.withValues(alpha: 0.1),
|
||||
filled: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardAssegnazione(TicketModel ticket) {
|
||||
return _buildCard(
|
||||
title: 'Assegnazione e Allegati',
|
||||
icon: Icons.engineering,
|
||||
themeColor: Colors.deepPurple,
|
||||
children: [
|
||||
StaffSection(
|
||||
label: 'Assegnato A',
|
||||
staffId: ticket.assignedToId,
|
||||
staffName: ticket.assignedToName,
|
||||
onStaffSelected: (staff) => context
|
||||
.read<TicketFormCubit>()
|
||||
.updateFields(assignedToId: staff.id, assignedToName: staff.name),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
// ECCO LA MAGIA:
|
||||
SharedFilesSection(
|
||||
titleNameForUpload: ticket.customerName ?? 'Nuovo Ticket',
|
||||
onGenerateIdForQr: _generateIdForQr,
|
||||
),
|
||||
/* SharedAttachmentsSection(
|
||||
parentType: AttachmentParentType.ticket,
|
||||
parentId: ticket.id,
|
||||
), */
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// --- WIDGET BASE PER LA CARD ---
|
||||
Widget _buildCard({
|
||||
required String title,
|
||||
required IconData icon,
|
||||
required Color themeColor,
|
||||
required List<Widget> children,
|
||||
}) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 24),
|
||||
elevation: 0, // Tolta l'ombra standard
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: BorderSide(
|
||||
color: themeColor.withValues(alpha: 0.3),
|
||||
width: 1,
|
||||
), // Bordo colorato delicato
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// Pallino colorato con l'icona dentro
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: themeColor.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(icon, color: themeColor),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: themeColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(height: 32),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
291
lib/features/tickets/ui/ticket_list_screen.dart
Normal file
291
lib/features/tickets/ui/ticket_list_screen.dart
Normal file
@@ -0,0 +1,291 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_state.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
|
||||
|
||||
class TicketListScreen extends StatefulWidget {
|
||||
const TicketListScreen({super.key});
|
||||
|
||||
@override
|
||||
State<TicketListScreen> createState() => _TicketListScreenState();
|
||||
}
|
||||
|
||||
class _TicketListScreenState extends State<TicketListScreen> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// INFINITY SCROLL: Quando arriviamo quasi in fondo, chiediamo altri ticket
|
||||
_scrollController.addListener(() {
|
||||
if (_scrollController.position.pixels >=
|
||||
_scrollController.position.maxScrollExtent - 200) {
|
||||
context.read<TicketListCubit>().fetchTickets();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Assistenza & Riparazioni'),
|
||||
actions: [
|
||||
// Tasto per filtri avanzati (Data, Staff, Tipo) -> Da fare in un BottomSheet!
|
||||
IconButton(
|
||||
icon: const Icon(Icons.filter_list),
|
||||
onPressed: () {
|
||||
// TODO: Aprire BottomSheet filtri avanzati
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// 1. BARRA DI RICERCA
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Cerca per nome cliente...',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
clearSearch: true,
|
||||
);
|
||||
},
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
onSubmitted: (value) {
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
searchTerm: value,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
// 2. FILTRI RAPIDI PER STATO (CHIPS)
|
||||
BlocBuilder<TicketListCubit, TicketListState>(
|
||||
buildWhen: (previous, current) =>
|
||||
previous.statusFilter != current.statusFilter,
|
||||
builder: (context, state) {
|
||||
return SizedBox(
|
||||
height: 50,
|
||||
child: ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
children: [
|
||||
_buildStatusChip(context, state, null, 'Tutti'),
|
||||
...TicketStatus.values.map(
|
||||
(status) => _buildStatusChip(
|
||||
context,
|
||||
state,
|
||||
status,
|
||||
status.displayValue,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const Divider(),
|
||||
|
||||
// 3. LA LISTA DEI TICKET
|
||||
Expanded(
|
||||
child: BlocBuilder<TicketListCubit, TicketListState>(
|
||||
builder: (context, state) {
|
||||
if (state.isLoading && state.tickets.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (state.tickets.isEmpty) {
|
||||
return const Center(child: Text('Nessun ticket trovato.'));
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
controller: _scrollController,
|
||||
itemCount: state.hasReachedMax
|
||||
? state.tickets.length
|
||||
: state.tickets.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
// Se siamo all'ultimo elemento e non abbiamo raggiunto il max, mostriamo il loader
|
||||
if (index >= state.tickets.length) {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final ticket = state.tickets[index];
|
||||
return _TicketCard(ticket: ticket);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: () {
|
||||
// TODO: Navigare alla creazione di un nuovo ticket
|
||||
},
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('Nuovo Ticket'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Widget di supporto per creare le Chip di filtro
|
||||
Widget _buildStatusChip(
|
||||
BuildContext context,
|
||||
TicketListState state,
|
||||
TicketStatus? status,
|
||||
String label,
|
||||
) {
|
||||
final isSelected = state.statusFilter == status;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: ChoiceChip(
|
||||
label: Text(label),
|
||||
selected: isSelected,
|
||||
selectedColor:
|
||||
status?.color.withValues(alpha: 0.2) ??
|
||||
Colors.blue.withValues(alpha: 0.2),
|
||||
onSelected: (selected) {
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
statusFilter: selected ? status : null,
|
||||
clearStatus: !selected && status != null,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// LA CARD DEL TICKET (Il "Colpo d'Occhio")
|
||||
// ---------------------------------------------------------
|
||||
class _TicketCard extends StatelessWidget {
|
||||
final TicketModel ticket;
|
||||
|
||||
const _TicketCard({required this.ticket});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final statusColor = ticket.ticketStatus.color;
|
||||
final statusIcon = ticket.ticketStatus.icon;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
|
||||
clipBehavior: Clip
|
||||
.antiAlias, // Serve per tagliare il container laterale con gli angoli della card
|
||||
child: IntrinsicHeight(
|
||||
// Serve per far sì che il container laterale prenda tutta l'altezza
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// LA STRISCIA COLORATA LATERALE
|
||||
Container(width: 6, color: statusColor),
|
||||
Expanded(
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
title: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
ticket.customerName ?? 'Cliente Sconosciuto',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
// IL BADGE DELLO STATO
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: statusColor.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(statusIcon, size: 14, color: statusColor),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
ticket.ticketStatus.displayValue,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: statusColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 4),
|
||||
// MODELLO O TIPO DI INTERVENTO
|
||||
Text(
|
||||
ticket.targetModelName ?? ticket.ticketType.displayValue,
|
||||
style: const TextStyle(fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// DATA CREAZIONE (Es: 04/05/2026)
|
||||
Text(
|
||||
ticket.createdAt != null
|
||||
? 'Creato il: ${ticket.createdAt!.day}/${ticket.createdAt!.month}/${ticket.createdAt!.year}'
|
||||
: '',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade600,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
// TODO: Aprire il dettaglio del ticket!
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user