diff --git a/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart b/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart index 5103f54..007cd2f 100644 --- a/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart +++ b/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart @@ -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(); diff --git a/lib/features/operations/blocs/operation_details_form_cubit.dart b/lib/features/operations/blocs/operation_details_form_cubit.dart index 0998efe..f8b6530 100644 --- a/lib/features/operations/blocs/operation_details_form_cubit.dart +++ b/lib/features/operations/blocs/operation_details_form_cubit.dart @@ -40,8 +40,11 @@ class OperationDetailsFormCubit extends Cubit { 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 { modelId: modelId ?? current.modelId, description: description ?? current.description, expirationDate: expirationDate ?? current.expirationDate, + quantity: sanitizedQuantity, ); emit( @@ -111,6 +115,7 @@ class OperationDetailsFormCubit extends Cubit { 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, ); diff --git a/lib/features/operations/blocs/operation_details_list_cubit.dart b/lib/features/operations/blocs/operation_details_list_cubit.dart index c04202b..ffe0398 100644 --- a/lib/features/operations/blocs/operation_details_list_cubit.dart +++ b/lib/features/operations/blocs/operation_details_list_cubit.dart @@ -94,4 +94,22 @@ class OperationDetailsListCubit extends Cubit { ), ); } + + /// 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.from(state.details); + updatedDetails[index] = updatedDetails[index].copyWith(quantity: clamped); + emit( + OperationDetailsListState( + details: updatedDetails, + selectedIds: state.selectedIds, + status: OperationDetailsListStatus.updated, + ), + ); + } } diff --git a/lib/features/operations/models/operation_detail_model.dart b/lib/features/operations/models/operation_detail_model.dart index 5e67e2a..8912e16 100644 --- a/lib/features/operations/models/operation_detail_model.dart +++ b/lib/features/operations/models/operation_detail_model.dart @@ -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 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) : 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, }; } } diff --git a/lib/features/operations/models/operation_type.dart b/lib/features/operations/models/operation_type.dart index ff18192..0035f86 100644 --- a/lib/features/operations/models/operation_type.dart +++ b/lib/features/operations/models/operation_type.dart @@ -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; diff --git a/lib/features/operations/ui/operation_list_screen.dart b/lib/features/operations/ui/operation_list_screen.dart index 76391ec..4e9aa9d 100644 --- a/lib/features/operations/ui/operation_list_screen.dart +++ b/lib/features/operations/ui/operation_list_screen.dart @@ -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), diff --git a/lib/features/operations/ui/widgets/operation_details_section.dart b/lib/features/operations/ui/widgets/operation_details_section.dart index fc630d7..d4b01c6 100644 --- a/lib/features/operations/ui/widgets/operation_details_section.dart +++ b/lib/features/operations/ui/widgets/operation_details_section.dart @@ -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() + .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() + .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() + .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 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, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/targets/data/target_progress_service.dart b/lib/features/targets/data/target_progress_service.dart index be36824..fc16fa4 100644 --- a/lib/features/targets/data/target_progress_service.dart +++ b/lib/features/targets/data/target_progress_service.dart @@ -46,13 +46,10 @@ class TargetProgressService { ); // 2. Query su operations nel periodo target per lo store - final storeCounts = {}; - final staffCounts = >{}; - - // Inizializza contatori - for (final def in metricDefinitions) { - storeCounts[def.key] = 0; - } + Map storeCounts = { + for (final def in metricDefinitions) def.key: 0, + }; + Map> 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; - - 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? ?? []; - - 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?; - 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); + 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 storeCounts, + Map> staffCounts, + }) aggregateOperationCounts(List operations) { + final storeCounts = { + for (final def in metricDefinitions) def.key: 0, + }; + final staffCounts = >{}; + + 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? ?? []; + + 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?; + 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 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 []; } } diff --git a/pubspec.yaml b/pubspec.yaml index 36bf932..0213da1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.5.5+89 +version: 2.5.6+90 environment: sdk: ^3.11.3 diff --git a/test/features/operations/blocs/operation_details_quantity_test.dart b/test/features/operations/blocs/operation_details_quantity_test.dart new file mode 100644 index 0000000..619e692 --- /dev/null +++ b/test/features/operations/blocs/operation_details_quantity_test.dart @@ -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(); + }); + }); +} + diff --git a/test/features/operations/models/operation_detail_model_test.dart b/test/features/operations/models/operation_detail_model_test.dart new file mode 100644 index 0000000..45c9ce7 --- /dev/null +++ b/test/features/operations/models/operation_detail_model_test.dart @@ -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); + }); + }); +} + diff --git a/test/features/targets/data/target_progress_service_test.dart b/test/features/targets/data/target_progress_service_test.dart new file mode 100644 index 0000000..61a84cd --- /dev/null +++ b/test/features/targets/data/target_progress_service_test.dart @@ -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); + }); + }); +} +