Compare commits

...
5 Commits
Author SHA1 Message Date
brontomark 4b111766dc aggiunta quantità a intrattenimento e unica
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m6s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m23s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m37s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 26m18s
2026-11-12 11:09:34 +01:00
brontomark 2bf668a088 pdf compression
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m43s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m21s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m32s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m39s
2026-11-03 15:38:03 +01:00
brontomark 0adb1a8f1c pdf compression 2026-11-03 15:37:44 +01:00
brontomark 606a1fc3a9 fix lista ticket
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m7s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m28s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m33s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 15m1s
2026-10-23 09:49:14 +02:00
brontomark 4e3732597b fix upload allegati
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m10s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m15s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 10m8s
2026-10-15 17:05:19 +02:00
20 changed files with 974 additions and 189 deletions

No files matched your search

+71
View File
@@ -75,4 +75,75 @@ class ImageUtils {
return bytes;
}
}
/// Ottimizza e comprime un'immagine per l'esportazione in PDF (es. portali TIM).
/// Normalizza l'orientamento EXIF, ridimensiona proporzionalmente se supera [maxDimension]
/// e codifica in JPEG con qualità [quality] per ridurre drasticamente il peso del PDF.
static Uint8List compressForPdf(
Uint8List bytes, {
int maxDimension = 1800,
int quality = 78,
}) {
try {
final decoded = img.decodeImage(bytes);
if (decoded == null) return bytes;
var processed = decoded;
if (processed.exif.imageIfd.hasOrientation &&
processed.exif.imageIfd.orientation != 1) {
processed = img.bakeOrientation(processed);
}
if (processed.width > maxDimension || processed.height > maxDimension) {
processed = _resizeToMaxDimension(processed, maxDimension);
}
return Uint8List.fromList(img.encodeJpg(processed, quality: quality));
} catch (_) {
return bytes;
}
}
/// Converte i pixel grezzi BGRA8888 (es. renderizzati da pdfrx) in un JPEG compresso
/// pronto per l'inserimento nel PDF, evitando il passaggio per PNG lossless.
static Uint8List encodeBgraPixelsToJpg(
Uint8List bgraPixels, {
required int width,
required int height,
int maxDimension = 1800,
int quality = 78,
}) {
var image = img.Image.fromBytes(
width: width,
height: height,
bytes: bgraPixels.buffer,
numChannels: 4,
order: img.ChannelOrder.bgra,
);
if (image.width > maxDimension || image.height > maxDimension) {
image = _resizeToMaxDimension(image, maxDimension);
}
return Uint8List.fromList(img.encodeJpg(image, quality: quality));
}
static img.Image _resizeToMaxDimension(img.Image source, int maxDimension) {
final aspectRatio = source.width / source.height;
final int targetWidth;
final int targetHeight;
if (source.width >= source.height) {
targetWidth = maxDimension;
targetHeight = (maxDimension / aspectRatio).round();
} else {
targetHeight = maxDimension;
targetWidth = (maxDimension * aspectRatio).round();
}
return img.copyResize(
source,
width: targetWidth,
height: targetHeight,
interpolation: img.Interpolation.linear,
);
}
}
@@ -563,29 +563,26 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
sourceName: file.name,
);
for (final page in document.pages) {
final maxSide = page.width > page.height ? page.width : page.height;
final scale = (maxSide * 2 > 1800) ? (1800 / maxSide) : 2.0;
final pageImage = await page.render(
fullWidth: page.width * 2,
fullHeight: page.height * 2,
fullWidth: (page.width * scale).roundToDouble(),
fullHeight: (page.height * scale).roundToDouble(),
);
if (pageImage != null) {
final uiImage = await pageImage.createImage();
final byteData = await uiImage.toByteData(
format: ui.ImageByteFormat.png,
final jpgBytes = ImageUtils.encodeBgraPixelsToJpg(
pageImage.pixels,
width: pageImage.width,
height: pageImage.height,
);
if (byteData != null) {
allPagesAsImages.add(byteData.buffer.asUint8List());
}
uiImage.dispose();
allPagesAsImages.add(jpgBytes);
pageImage.dispose();
}
}
await document.dispose();
} else {
// È un'immagine: normalizziamo l'orientamento EXIF per il PDF
final safeBytes = ImageUtils.normalizeOrientation(
fileBytes,
extension: file.extension,
);
// È un'immagine: normalizziamo orientamento EXIF, ridimensioniamo e comprimiamo in JPEG per il PDF
final safeBytes = ImageUtils.compressForPdf(fileBytes);
allPagesAsImages.add(safeBytes);
}
}
@@ -714,38 +711,35 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
document.pages.length > 1; // Controlliamo se è multipagina!
for (final page in document.pages) {
final maxSide = page.width > page.height ? page.width : page.height;
final scale = (maxSide * 2 > 1800) ? (1800 / maxSide) : 2.0;
final pageImage = await page.render(
fullWidth: page.width * 2,
fullHeight: page.height * 2,
fullWidth: (page.width * scale).roundToDouble(),
fullHeight: (page.height * scale).roundToDouble(),
);
if (pageImage != null) {
final uiImage = await pageImage.createImage();
final byteData = await uiImage.toByteData(
format: ui.ImageByteFormat.png,
final jpgBytes = ImageUtils.encodeBgraPixelsToJpg(
pageImage.pixels,
width: pageImage.width,
height: pageImage.height,
);
// Salviamo l'immagine compressa CON il suo contesto storico
itemsToExport.add(
_ExportItem(
bytes: jpgBytes,
sourceName: baseName,
isMultiPage: isMulti,
pageIndex: page.pageNumber,
),
);
if (byteData != null) {
// Salviamo l'immagine CON il suo contesto storico
itemsToExport.add(
_ExportItem(
bytes: byteData.buffer.asUint8List(),
sourceName: baseName,
isMultiPage: isMulti,
pageIndex: page.pageNumber,
),
);
}
uiImage.dispose();
pageImage.dispose();
}
}
await document.dispose();
} else {
// SE È UN'IMMAGINE, la salviamo normalizzando l'orientamento
final safeBytes = ImageUtils.normalizeOrientation(
fileBytes,
extension: file.extension,
);
// SE È UN'IMMAGINE, normalizziamo orientamento EXIF, ridimensioniamo e comprimiamo in JPEG
final safeBytes = ImageUtils.compressForPdf(fileBytes);
itemsToExport.add(
_ExportItem(
bytes: safeBytes,
@@ -189,7 +189,7 @@ class AttachmentModel extends Equatable {
'company_id': companyId,
'thumbnail_path': thumbnailPath,
'cropped_storage_path': croppedStoragePath,
'view_mode': viewMode?.value,
'view_mode': (viewMode ?? AttachmentViewMode.original).value,
};
}
}
@@ -207,8 +207,9 @@ class _ExpiringContractsCardContent extends StatelessWidget {
.map((d) {
final tLabel = d.type?.shortLabel ?? d.type?.value ?? '';
final sub = d.subType?.trim() ?? '';
if (sub.isNotEmpty) return '$tLabel: $sub';
return tLabel;
final base = sub.isNotEmpty ? '$tLabel: $sub' : tLabel;
if (base.isEmpty) return '';
return d.quantity > 1 ? '$base ×${d.quantity}' : base;
})
.where((l) => l.isNotEmpty)
.toList();
@@ -40,8 +40,11 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
String? modelId,
String? description,
DateTime? expirationDate,
int? quantity,
}) {
final current = state.operationDetail;
final sanitizedQuantity =
quantity != null ? (quantity < 1 ? 1 : quantity) : current.quantity;
final updated = current.copyWith(
type: type ?? current.type,
subType: subType ?? current.subType,
@@ -56,6 +59,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
modelId: modelId ?? current.modelId,
description: description ?? current.description,
expirationDate: expirationDate ?? current.expirationDate,
quantity: sanitizedQuantity,
);
emit(
@@ -111,6 +115,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
final updated = current.copyWith(
type: newType,
subType: newType == OperationType.energy ? EnergySubtypes.luce : null,
quantity: newType.supportsQuantity ? current.quantity : 1,
provider: selectedProvider != null ? () => selectedProvider : null,
providerId: selectedProvider?.id,
);
@@ -94,4 +94,22 @@ class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
),
);
}
/// Aggiorna la quantità/valore di un dettaglio esistente (minimo 1)
void updateOperationDetailQuantity(int index, int newQuantity) {
if (index < 0 || index >= state.details.length) return;
final clamped = newQuantity < 1 ? 1 : newQuantity;
if (state.details[index].quantity == clamped) return;
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails[index] = updatedDetails[index].copyWith(quantity: clamped);
emit(
OperationDetailsListState(
details: updatedDetails,
selectedIds: state.selectedIds,
status: OperationDetailsListStatus.updated,
),
);
}
}
@@ -16,6 +16,7 @@ class OperationDetailModel extends Equatable {
final String companyId;
final String? lastCampaignId;
final String? subType;
final int quantity;
// Aggiunte comode per relazioni
final ProviderModel? provider;
@@ -33,6 +34,7 @@ class OperationDetailModel extends Equatable {
this.companyId = '',
this.lastCampaignId,
this.subType,
this.quantity = 1,
this.provider,
this.model,
});
@@ -50,6 +52,7 @@ class OperationDetailModel extends Equatable {
companyId,
lastCampaignId,
subType,
quantity,
provider,
model,
];
@@ -66,6 +69,7 @@ class OperationDetailModel extends Equatable {
String? companyId,
String? lastCampaignId,
String? subType,
int? quantity,
ProviderModel? Function()? provider,
ModelModel? Function()? model,
}) => OperationDetailModel(
@@ -80,6 +84,7 @@ class OperationDetailModel extends Equatable {
companyId: companyId ?? this.companyId,
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
subType: subType ?? this.subType,
quantity: quantity ?? this.quantity,
provider: provider != null ? provider() : this.provider,
model: model != null ? model() : this.model,
);
@@ -89,6 +94,7 @@ class OperationDetailModel extends Equatable {
}
factory OperationDetailModel.fromMap(Map<String, dynamic> map) {
final rawQuantity = (map['quantity'] as num?)?.toInt() ?? 1;
return OperationDetailModel(
id: map['id'] as String?,
createdAt: map['created_at'] != null
@@ -105,6 +111,7 @@ class OperationDetailModel extends Equatable {
companyId: map['company_id'] as String? ?? '',
lastCampaignId: map['last_campaign_id'] as String?,
subType: map['sub_type'] as String?,
quantity: rawQuantity < 1 ? 1 : rawQuantity,
provider: (map[Tables.providers] != null)
? ProviderModel.fromMap(map[Tables.providers] as Map<String, dynamic>)
: null,
@@ -140,6 +147,7 @@ class OperationDetailModel extends Equatable {
if (lastCampaignId?.isNotEmpty == true)
'last_campaign_id': lastCampaignId,
if (subType?.isNotEmpty == true) 'sub_type': subType,
'quantity': quantity < 1 ? 1 : quantity,
};
}
}
@@ -115,6 +115,10 @@ enum OperationType {
required this.color,
});
/// Indica se il dettaglio supporta una quantità/valore personalizzabile (es. pacchetti multi-canale o Unica)
bool get supportsQuantity =>
this == OperationType.entertainment || this == OperationType.unica;
/// Ricostruisce l'enum dal valore stringa salvato su DB in modo case-insensitive
static OperationType? fromValue(String? val) {
if (val == null || val.trim().isEmpty) return null;
@@ -427,9 +427,11 @@ class _RichOperationCard extends StatelessWidget {
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
final icon = _getIconForType(detail.type, detail.subType);
final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty)
final baseLabel = (detail.subType != null && detail.subType!.isNotEmpty)
? '${detail.type?.shortLabel ?? ''} (${detail.subType})'
: (detail.type?.shortLabel ?? 'Dettaglio');
final typeLabel =
detail.quantity > 1 ? '$baseLabel ×${detail.quantity}' : baseLabel;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
@@ -140,7 +140,10 @@ class OperationDetailsSection extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
typeText,
@@ -150,9 +153,30 @@ class OperationDetailsSection extends StatelessWidget {
fontSize: 14,
),
),
if (detail.quantity > 1)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2,
),
decoration: BoxDecoration(
color: typeColor.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: typeColor.withValues(alpha: 0.35),
),
),
child: Text(
'×${detail.quantity}',
style: TextStyle(
color: typeColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
if (detail.provider?.name != null &&
detail.provider!.name.isNotEmpty) ...[
const SizedBox(width: 8),
detail.provider!.name.isNotEmpty)
Chip(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
@@ -171,7 +195,6 @@ class OperationDetailsSection extends StatelessWidget {
color: providerColor.withValues(alpha: 0.3),
),
),
],
],
),
if (detail.model?.name != null &&
@@ -216,6 +239,34 @@ class OperationDetailsSection extends StatelessWidget {
],
),
],
if (detail.type?.supportsQuantity == true) ...[
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
'Valore / Qtà:',
style: TextStyle(
fontSize: 12,
color: Colors.grey[700],
fontWeight: FontWeight.w500,
),
),
_QuantityStepper(
quantity: detail.quantity,
color: typeColor,
compact: true,
onChanged: (nextQty) {
context
.read<OperationDetailsListCubit>()
.updateOperationDetailQuantity(index, nextQty);
},
),
],
),
],
],
),
),
@@ -769,6 +820,61 @@ class _OperationDetailFormSheetState
const SizedBox(height: 16),
],
// Valore / Quantità (per Entertainment e Unica)
if (currentType.supportsQuantity) ...[
const Text(
'Valore / Quantità',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
const SizedBox(height: 4),
Text(
currentType == OperationType.entertainment
? 'Indica quanti canali/contenuti vale questo pacchetto (es. TIMVISION L = 3).'
: 'Indica quante unità vale questo servizio Unica.',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
),
),
const SizedBox(height: 10),
Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_QuantityStepper(
quantity: detail.quantity,
color: currentType.color,
onChanged: (val) {
context
.read<OperationDetailsFormCubit>()
.updateFields(quantity: val);
},
),
Wrap(
spacing: 6,
children: [1, 2, 3, 4, 5].map((preset) {
return ChoiceChip(
label: Text('×$preset'),
selected: detail.quantity == preset,
onSelected: (selected) {
if (selected) {
context
.read<OperationDetailsFormCubit>()
.updateFields(quantity: preset);
}
},
);
}).toList(),
),
],
),
const SizedBox(height: 16),
],
// 6. Scadenza (Reattiva per tipi complessi)
if ([
OperationType.energy,
@@ -862,3 +968,77 @@ class _OperationDetailFormSheetState
);
}
}
class _QuantityStepper extends StatelessWidget {
final int quantity;
final Color color;
final ValueChanged<int> onChanged;
final bool compact;
const _QuantityStepper({
required this.quantity,
required this.color,
required this.onChanged,
this.compact = false,
});
@override
Widget build(BuildContext context) {
final canDecrement = quantity > 1;
final buttonSize = compact ? 28.0 : 34.0;
final iconSize = compact ? 16.0 : 18.0;
final fontSize = compact ? 13.0 : 15.0;
return Container(
decoration: BoxDecoration(
color: color.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withValues(alpha: 0.3)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
borderRadius: const BorderRadius.horizontal(left: Radius.circular(7)),
onTap: canDecrement ? () => onChanged(quantity - 1) : null,
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: Icon(
Icons.remove,
size: iconSize,
color: canDecrement ? color : Colors.grey.shade400,
),
),
),
Container(
constraints: BoxConstraints(minWidth: compact ? 28 : 34),
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Text(
'$quantity',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: fontSize,
color: color,
),
),
),
InkWell(
borderRadius: const BorderRadius.horizontal(right: Radius.circular(7)),
onTap: () => onChanged(quantity + 1),
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: Icon(
Icons.add,
size: iconSize,
color: color,
),
),
),
],
),
);
}
}
@@ -46,13 +46,10 @@ class TargetProgressService {
);
// 2. Query su operations nel periodo target per lo store
final storeCounts = <String, int>{};
final staffCounts = <String, Map<String, int>>{};
// Inizializza contatori
for (final def in metricDefinitions) {
storeCounts[def.key] = 0;
}
Map<String, int> storeCounts = {
for (final def in metricDefinitions) def.key: 0,
};
Map<String, Map<String, int>> staffCounts = {};
try {
final storeId = target.storeId;
@@ -69,6 +66,7 @@ class TargetProgressService {
${Tables.operationDetails}(
type,
sub_type,
quantity,
provider_id,
${Tables.providers}(name)
)
@@ -79,42 +77,9 @@ class TargetProgressService {
.gte('created_at', target.startDay.toIso8601String())
.lte('created_at', target.endDay.toIso8601String());
final operations = response as List<dynamic>;
for (final op in operations) {
final staffId = op['staff_id'] as String?;
final isBusinessOp = op['is_business'] as bool? ?? false;
final details = op[Tables.operationDetails] as List<dynamic>? ?? [];
if (staffId != null && !staffCounts.containsKey(staffId)) {
staffCounts[staffId] = {
for (final def in metricDefinitions) def.key: 0,
};
}
for (final d in details) {
final typeStr = d['type'] as String?;
final opType = OperationType.fromValue(typeStr);
final subType = (d['sub_type'] as String?)?.trim().toLowerCase();
final providerMap = d[Tables.providers] as Map<String, dynamic>?;
final providerName = (providerMap?['name'] as String?)?.toLowerCase() ?? '';
final categoryKey = _mapDetailToCategory(
opType: opType,
subType: subType,
providerName: providerName,
isBusinessOp: isBusinessOp,
);
if (categoryKey != null && storeCounts.containsKey(categoryKey)) {
storeCounts[categoryKey] = (storeCounts[categoryKey] ?? 0) + 1;
if (staffId != null && staffCounts.containsKey(staffId)) {
staffCounts[staffId]![categoryKey] =
(staffCounts[staffId]![categoryKey] ?? 0) + 1;
}
}
}
}
final aggregated = aggregateOperationCounts(response as List<dynamic>);
storeCounts = aggregated.storeCounts;
staffCounts = aggregated.staffCounts;
}
} catch (e) {
debugPrint('Errore nel caricamento delle operazioni per il target: $e');
@@ -258,50 +223,106 @@ class TargetProgressService {
);
}
/// Mappa un dettaglio operazione alla chiave di metrica target corrispondente
String? _mapDetailToCategory({
/// Aggrega i conteggi di negozio e per addetto a partire dalle righe operazioni
static ({
Map<String, int> storeCounts,
Map<String, Map<String, int>> staffCounts,
}) aggregateOperationCounts(List<dynamic> operations) {
final storeCounts = <String, int>{
for (final def in metricDefinitions) def.key: 0,
};
final staffCounts = <String, Map<String, int>>{};
for (final op in operations) {
final staffId = op['staff_id'] as String?;
final isBusinessOp = op['is_business'] as bool? ?? false;
final details = op[Tables.operationDetails] as List<dynamic>? ?? [];
if (staffId != null && !staffCounts.containsKey(staffId)) {
staffCounts[staffId] = {
for (final def in metricDefinitions) def.key: 0,
};
}
for (final d in details) {
final typeStr = d['type'] as String?;
final opType = OperationType.fromValue(typeStr);
final subType = (d['sub_type'] as String?)?.trim().toLowerCase();
final providerMap = d[Tables.providers] as Map<String, dynamic>?;
final providerName =
(providerMap?['name'] as String?)?.toLowerCase() ?? '';
final rawQty = (d['quantity'] as num?)?.toInt() ?? 1;
final qty = rawQty < 1 ? 1 : rawQty;
final categoryKeys = mapDetailToCategories(
opType: opType,
subType: subType,
providerName: providerName,
isBusinessOp: isBusinessOp,
);
for (final categoryKey in categoryKeys) {
if (storeCounts.containsKey(categoryKey)) {
storeCounts[categoryKey] = (storeCounts[categoryKey] ?? 0) + qty;
if (staffId != null && staffCounts.containsKey(staffId)) {
staffCounts[staffId]![categoryKey] =
(staffCounts[staffId]![categoryKey] ?? 0) + qty;
}
}
}
}
}
return (storeCounts: storeCounts, staffCounts: staffCounts);
}
/// Mappa un dettaglio operazione alle chiavi di metrica target corrispondenti.
/// Un dettaglio Entertainment di tipo Calcio alimenta sia 'calcio' che 'contenuti'.
static List<String> mapDetailToCategories({
required OperationType? opType,
required String? subType,
required String providerName,
required bool isBusinessOp,
}) {
if (opType == null) return null;
if (opType == null) return const [];
if (opType == OperationType.business || isBusinessOp) {
return 'business';
return const ['business'];
}
final normalizedSubType = subType?.trim().toLowerCase();
switch (opType) {
case OperationType.mnp:
return 'mnp';
return const ['mnp'];
case OperationType.unica:
return 'unica';
return const ['unica'];
case OperationType.nip:
return 'nip';
return const ['nip'];
case OperationType.entertainment:
if (subType == 'calcio') {
return 'calcio';
if (normalizedSubType != null && normalizedSubType.contains('calcio')) {
return const ['calcio', 'contenuti'];
}
return 'contenuti';
return const ['contenuti'];
case OperationType.fin:
return 'fin';
return const ['fin'];
case OperationType.upselling:
return 'upselling';
return const ['upselling'];
case OperationType.cb:
return 'cb';
return const ['cb'];
case OperationType.al:
return 'al';
return const ['al'];
case OperationType.telepass:
return 'telepass';
return const ['telepass'];
case OperationType.energy:
if (providerName.contains('tim')) {
return 'energiaTim';
if (providerName.trim().toLowerCase().contains('tim')) {
return const ['energiaTim'];
}
return 'energiaAltri';
return const ['energiaAltri'];
case OperationType.ricontatto:
return 'ricontatti';
return const ['ricontatti'];
default:
return null;
return const [];
}
}
@@ -84,6 +84,8 @@ class TicketListCubit extends Cubit<TicketListState> {
bool clearSearch = false,
bool clearDate = false,
bool clearStatus = false,
bool clearTicketType = false,
bool clearStaff = false,
}) {
emit(
state.copyWith(
@@ -95,11 +97,19 @@ class TicketListCubit extends Cubit<TicketListState> {
clearSearch: clearSearch,
clearDate: clearDate,
clearStatus: clearStatus,
clearTicketType: clearTicketType,
clearStaff: clearStaff,
),
);
loadTickets(refresh: true); // Applica i filtri e ricarica
}
/// Azzera tutti i filtri e ricarica la lista completa
void resetFilters() {
emit(state.resetFilters());
loadTickets(refresh: true);
}
void toggleTicketSelection(TicketModel ticket) {
final currentSelection = Set<TicketModel>.from(state.selectedTickets);
if (currentSelection.contains(ticket)) {
@@ -29,6 +29,13 @@ class TicketListState extends Equatable {
this.staffIdFilter,
});
bool get hasActiveFilters =>
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
dateRange != null ||
statusFilter != null ||
ticketTypeFilter != null ||
(staffIdFilter != null && staffIdFilter!.trim().isNotEmpty);
TicketListState copyWith({
List<TicketModel>? tickets,
bool? isLoading,
@@ -43,6 +50,8 @@ class TicketListState extends Equatable {
bool clearSearch = false,
bool clearDate = false,
bool clearStatus = false,
bool clearTicketType = false,
bool clearStaff = false,
}) {
return TicketListState(
tickets: tickets ?? this.tickets,
@@ -52,12 +61,28 @@ class TicketListState extends Equatable {
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,
ticketTypeFilter:
clearTicketType ? null : (ticketTypeFilter ?? this.ticketTypeFilter),
staffIdFilter: clearStaff ? null : (staffIdFilter ?? this.staffIdFilter),
selectedTickets: selectedTickets ?? this.selectedTickets,
);
}
TicketListState resetFilters() {
return TicketListState(
tickets: tickets,
isLoading: isLoading,
hasReachedMax: hasReachedMax,
errorMessage: errorMessage,
selectedTickets: selectedTickets,
searchTerm: null,
dateRange: null,
statusFilter: null,
ticketTypeFilter: null,
staffIdFilter: null,
);
}
@override
List<Object?> get props => [
tickets,
@@ -66,7 +66,7 @@ class TicketRepository {
}
if (statusFilter != null) {
query = query.eq('status', statusFilter.value);
query = query.eq('ticket_status', statusFilter.value);
}
if (ticketTypeFilter != null) {
@@ -159,7 +159,7 @@ class TicketRepository {
}
if (ticketStatusFilter != null) {
query = query.eq('status', ticketStatusFilter.value);
query = query.eq('ticket_status', ticketStatusFilter.value);
}
if (ticketTypeFilter != null) {
+208 -77
View File
@@ -45,6 +45,12 @@ class _TicketListScreenState extends State<TicketListScreen> {
});
}
void _resetAllFilters() {
_debounce?.cancel();
_searchController.clear();
context.read<TicketListCubit>().resetFilters();
}
@override
void dispose() {
_debounce?.cancel();
@@ -59,6 +65,16 @@ class _TicketListScreenState extends State<TicketListScreen> {
appBar: AppBar(
title: const Text('Assistenza & Riparazioni'),
actions: [
BlocBuilder<TicketListCubit, TicketListState>(
builder: (context, state) {
if (!state.hasActiveFilters) return const SizedBox.shrink();
return IconButton(
tooltip: 'Azzera filtri',
icon: const Icon(Icons.filter_alt_off),
onPressed: _resetAllFilters,
);
},
),
IconButton(
onPressed: () =>
context.read<TicketListCubit>().loadTickets(refresh: true),
@@ -73,87 +89,189 @@ class _TicketListScreenState extends State<TicketListScreen> {
),
],
),
body: Column(
children: [
// 1. BARRA DI RICERCA
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: 'Cerca per cliente, richiesta o riferimento...',
prefixIcon: const Icon(Icons.search),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_debounce?.cancel();
_searchController.clear();
context.read<TicketListCubit>().updateFilters(
clearSearch: true,
);
},
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
body: BlocListener<TicketListCubit, TicketListState>(
listenWhen: (previous, current) =>
previous.searchTerm != current.searchTerm &&
(current.searchTerm == null || current.searchTerm!.isEmpty),
listener: (context, state) {
if (_searchController.text.isNotEmpty) {
_searchController.clear();
}
},
child: Column(
children: [
// 1. BARRA DI RICERCA
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: 'Cerca per cliente, richiesta o riferimento...',
prefixIcon: const Icon(Icons.search),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_debounce?.cancel();
_searchController.clear();
context.read<TicketListCubit>().updateFilters(
clearSearch: true,
);
},
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
onChanged: _onSearchChanged,
onSubmitted: (value) {
_debounce?.cancel();
context.read<TicketListCubit>().updateFilters(
searchTerm: value,
);
},
),
onChanged: _onSearchChanged,
onSubmitted: (value) {
_debounce?.cancel();
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>(
// 2. FILTRI RAPIDI PER STATO (CHIPS)
BlocBuilder<TicketListCubit, TicketListState>(
buildWhen: (previous, current) =>
previous.statusFilter != current.statusFilter ||
previous.hasActiveFilters != current.hasActiveFilters,
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 TicketList(
state: state,
scrollController: _scrollController,
return SizedBox(
height: 50,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8.0),
children: [
if (state.hasActiveFilters)
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: ActionChip(
avatar: const Icon(
Icons.filter_alt_off,
size: 16,
color: Colors.redAccent,
),
label: const Text(
'Azzera filtri',
style: TextStyle(
color: Colors.redAccent,
fontWeight: FontWeight.w600,
),
),
backgroundColor:
Colors.redAccent.withValues(alpha: 0.1),
side: BorderSide(
color: Colors.redAccent.withValues(alpha: 0.3),
),
onPressed: _resetAllFilters,
),
),
_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.errorMessage.isNotEmpty && state.tickets.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 12),
Text(
state.errorMessage,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.red),
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: () => context
.read<TicketListCubit>()
.loadTickets(refresh: true),
icon: const Icon(Icons.refresh),
label: const Text('Riprova'),
),
],
),
),
);
}
if (state.tickets.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
state.hasActiveFilters
? Icons.filter_list_off
: Icons.inbox_outlined,
size: 48,
color: Colors.grey,
),
const SizedBox(height: 12),
Text(
state.hasActiveFilters
? 'Nessun ticket trovato con i filtri selezionati.'
: 'Nessun ticket trovato.',
style: const TextStyle(
fontSize: 16,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
if (state.hasActiveFilters) ...[
const SizedBox(height: 16),
OutlinedButton.icon(
onPressed: _resetAllFilters,
icon: const Icon(Icons.filter_alt_off),
label: const Text('Azzera filtri'),
),
],
],
),
),
);
}
return TicketList(
state: state,
scrollController: _scrollController,
);
},
),
),
],
),
),
floatingActionButton: FloatingActionButton.extended(
icon: const Icon(Icons.add),
@@ -184,16 +302,29 @@ class _TicketListScreenState extends State<TicketListScreen> {
return Padding(
padding: const EdgeInsets.only(right: 8.0),
child: ChoiceChip(
avatar: status != null
? Icon(
status.icon,
size: 16,
color: isSelected ? status.color : null,
)
: const Icon(Icons.apps, size: 16),
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,
);
if (status == null) {
if (!isSelected) {
context.read<TicketListCubit>().updateFilters(clearStatus: true);
}
} else {
context.read<TicketListCubit>().updateFilters(
statusFilter: selected ? status : null,
clearStatus: !selected,
);
}
},
),
);
+1 -1
View File
@@ -1,7 +1,7 @@
name: flux
description: "Gestione attività negozio di telefonia"
publish_to: 'none'
version: 2.5.1+85
version: 2.5.6+90
environment:
sdk: ^3.11.3
@@ -0,0 +1,77 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/blocs/operation_details_form_cubit.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
void main() {
group('OperationDetailsListCubit quantity updates', () {
test('updateOperationDetailQuantity updates target detail and ignores < 1', () {
final cubit = OperationDetailsListCubit(
details: const [
OperationDetailModel(type: OperationType.entertainment, quantity: 1),
OperationDetailModel(type: OperationType.unica, quantity: 2),
],
);
cubit.updateOperationDetailQuantity(0, 3);
expect(cubit.state.details[0].quantity, 3);
expect(cubit.state.status, OperationDetailsListStatus.updated);
// Clamping to minimum 1
cubit.updateOperationDetailQuantity(1, 0);
expect(cubit.state.details[1].quantity, 1);
// Out-of-bounds index is a no-op
cubit.updateOperationDetailQuantity(5, 4);
expect(cubit.state.details.length, 2);
cubit.close();
});
});
group('OperationDetailsFormCubit quantity updates', () {
test('updateFields clamps quantity to at least 1', () {
final cubit = OperationDetailsFormCubit(
initialDetail: const OperationDetailModel(
type: OperationType.entertainment,
quantity: 1,
),
);
cubit.updateFields(quantity: 4);
expect(cubit.state.operationDetail.quantity, 4);
cubit.updateFields(quantity: -2);
expect(cubit.state.operationDetail.quantity, 1);
cubit.close();
});
test('setTypeWithSmartDefaults resets quantity to 1 when type does not support quantity', () {
final cubit = OperationDetailsFormCubit(
initialDetail: const OperationDetailModel(
type: OperationType.entertainment,
quantity: 3,
),
);
// Switching between entertainment and unica preserves quantity
cubit.setTypeWithSmartDefaults(
newType: OperationType.unica,
allProviders: const [],
);
expect(cubit.state.operationDetail.quantity, 3);
// Switching to a type without quantity support resets to 1
cubit.setTypeWithSmartDefaults(
newType: OperationType.al,
allProviders: const [],
);
expect(cubit.state.operationDetail.quantity, 1);
cubit.close();
});
});
}
@@ -0,0 +1,74 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
void main() {
group('OperationDetailModel', () {
test('defaults quantity to 1 in constructor and empty()', () {
const detail = OperationDetailModel();
final empty = OperationDetailModel.empty();
expect(detail.quantity, 1);
expect(empty.quantity, 1);
});
test('fromMap parses quantity and clamps values < 1 to 1', () {
final withQty = OperationDetailModel.fromMap({
'type': 'Entertainment',
'sub_type': 'TIMVISION L',
'quantity': 3,
});
expect(withQty.type, OperationType.entertainment);
expect(withQty.subType, 'TIMVISION L');
expect(withQty.quantity, 3);
final missingQty = OperationDetailModel.fromMap({
'type': 'UNICA',
});
expect(missingQty.type, OperationType.unica);
expect(missingQty.quantity, 1);
final zeroQty = OperationDetailModel.fromMap({
'type': 'Entertainment',
'quantity': 0,
});
expect(zeroQty.quantity, 1);
});
test('toMap serializes quantity and clamps values < 1 to 1', () {
const detail = OperationDetailModel(
type: OperationType.entertainment,
subType: 'Calcio',
quantity: 3,
);
expect(detail.toMap()['quantity'], 3);
const invalidDetail = OperationDetailModel(
type: OperationType.unica,
quantity: 0,
);
expect(invalidDetail.toMap()['quantity'], 1);
});
test('copyWith and Equatable include quantity', () {
const a = OperationDetailModel(
type: OperationType.entertainment,
quantity: 2,
);
final b = a.copyWith(quantity: 3);
expect(b.quantity, 3);
expect(a, isNot(equals(b)));
expect(a.copyWith(), equals(a));
});
test('supportsQuantity is true only for entertainment and unica', () {
expect(OperationType.entertainment.supportsQuantity, isTrue);
expect(OperationType.unica.supportsQuantity, isTrue);
expect(OperationType.al.supportsQuantity, isFalse);
expect(OperationType.mnp.supportsQuantity, isFalse);
expect(OperationType.energy.supportsQuantity, isFalse);
});
});
}
@@ -0,0 +1,110 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/targets/data/target_progress_service.dart';
void main() {
group('TargetProgressService.mapDetailToCategories', () {
test('entertainment Calcio maps to both calcio and contenuti', () {
expect(
TargetProgressService.mapDetailToCategories(
opType: OperationType.entertainment,
subType: 'Calcio',
providerName: 'TIM',
isBusinessOp: false,
),
equals(['calcio', 'contenuti']),
);
expect(
TargetProgressService.mapDetailToCategories(
opType: OperationType.entertainment,
subType: 'TIMVISION Calcio',
providerName: 'TIM',
isBusinessOp: false,
),
equals(['calcio', 'contenuti']),
);
});
test('non-calcio entertainment maps only to contenuti', () {
expect(
TargetProgressService.mapDetailToCategories(
opType: OperationType.entertainment,
subType: 'Disney+',
providerName: 'TIM',
isBusinessOp: false,
),
equals(['contenuti']),
);
expect(
TargetProgressService.mapDetailToCategories(
opType: OperationType.entertainment,
subType: null,
providerName: 'TIM',
isBusinessOp: false,
),
equals(['contenuti']),
);
});
test('unica maps to unica', () {
expect(
TargetProgressService.mapDetailToCategories(
opType: OperationType.unica,
subType: null,
providerName: 'TIM',
isBusinessOp: false,
),
equals(['unica']),
);
});
});
group('TargetProgressService.aggregateOperationCounts', () {
test('accumulates quantity and counts calcio into both calcio and contenuti', () {
final operations = [
{
'staff_id': 'staff-1',
'is_business': false,
'operation_details': [
// 1 Calcio -> +1 calcio, +1 contenuti
{'type': 'Entertainment', 'sub_type': 'Calcio', 'quantity': 1},
// 1 Disney -> +1 contenuti
{'type': 'Entertainment', 'sub_type': 'Disney', 'quantity': 1},
// 1 TIMVISION L da 3 canali -> +3 contenuti
{'type': 'Entertainment', 'sub_type': 'TIMVISION L', 'quantity': 3},
// 1 Unica da 2 -> +2 unica
{'type': 'UNICA', 'sub_type': null, 'quantity': 2},
],
},
{
'staff_id': 'staff-2',
'is_business': false,
'operation_details': [
// Calcio con quantity 2 -> +2 calcio, +2 contenuti
{'type': 'Entertainment', 'sub_type': 'Calcio', 'quantity': 2},
// Dettaglio legacy senza quantity -> default 1
{'type': 'MNP', 'sub_type': null},
],
},
];
final result = TargetProgressService.aggregateOperationCounts(operations);
expect(result.storeCounts['calcio'], 3);
expect(result.storeCounts['contenuti'], 7); // 1 + 1 + 3 + 2
expect(result.storeCounts['unica'], 2);
expect(result.storeCounts['mnp'], 1);
expect(result.staffCounts['staff-1']?['calcio'], 1);
expect(result.staffCounts['staff-1']?['contenuti'], 5);
expect(result.staffCounts['staff-1']?['unica'], 2);
expect(result.staffCounts['staff-2']?['calcio'], 2);
expect(result.staffCounts['staff-2']?['contenuti'], 2);
expect(result.staffCounts['staff-2']?['mnp'], 1);
});
});
}
@@ -0,0 +1,54 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/tickets/blocs/ticket_list_state.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
void main() {
group('TicketListState Tests', () {
test('hasActiveFilters returns false on empty/default state', () {
const state = TicketListState();
expect(state.hasActiveFilters, isFalse);
});
test('hasActiveFilters returns true when statusFilter is set', () {
const state = TicketListState(
statusFilter: TicketStatus.waitingForReturn,
);
expect(state.hasActiveFilters, isTrue);
});
test('hasActiveFilters returns true when searchTerm is set and not empty', () {
const state = TicketListState(searchTerm: 'Mario');
expect(state.hasActiveFilters, isTrue);
const blankState = TicketListState(searchTerm: ' ');
expect(blankState.hasActiveFilters, isFalse);
});
test('resetFilters clears all filters while keeping tickets', () {
const state = TicketListState(
searchTerm: 'iPhone',
statusFilter: TicketStatus.waitingForReturn,
ticketTypeFilter: TicketType.repair,
staffIdFilter: 'staff-123',
);
expect(state.hasActiveFilters, isTrue);
final resetState = state.resetFilters();
expect(resetState.hasActiveFilters, isFalse);
expect(resetState.searchTerm, isNull);
expect(resetState.statusFilter, isNull);
expect(resetState.ticketTypeFilter, isNull);
expect(resetState.staffIdFilter, isNull);
expect(resetState.dateRange, isNull);
});
test('copyWith clearStatus clears statusFilter correctly', () {
const state = TicketListState(
statusFilter: TicketStatus.waitingForReturn,
);
final cleared = state.copyWith(clearStatus: true);
expect(cleared.statusFilter, isNull);
expect(cleared.hasActiveFilters, isFalse);
});
});
}