Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b111766dc | ||
|
|
2bf668a088 | ||
|
|
0adb1a8f1c |
No files matched your search
@@ -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,
|
||||
|
||||
+3
-2
@@ -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 [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: flux
|
||||
description: "Gestione attività negozio di telefonia"
|
||||
publish_to: 'none'
|
||||
version: 2.5.3+87
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user