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
365 lines
12 KiB
Dart
365 lines
12 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:flux/core/enums_and_consts/consts.dart';
|
|
import 'package:flux/core/utils/working_days_helper.dart';
|
|
import 'package:flux/features/operations/models/operation_type.dart';
|
|
import 'package:flux/features/targets/models/target_metrics.dart';
|
|
import 'package:flux/features/targets/models/target_model.dart';
|
|
import 'package:flux/features/targets/models/target_progress_model.dart';
|
|
import 'package:flux/service_locator.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
|
|
class TargetProgressService {
|
|
final SupabaseClient _supabase;
|
|
|
|
TargetProgressService({SupabaseClient? supabase})
|
|
: _supabase = supabase ?? sl<SupabaseClient>();
|
|
|
|
static const List<({String key, String label})> metricDefinitions = [
|
|
(key: 'mnp', label: 'MNP'),
|
|
(key: 'unica', label: 'TIM Unica'),
|
|
(key: 'nip', label: 'NIP'),
|
|
(key: 'business', label: 'Business'),
|
|
(key: 'contenuti', label: 'Contenuti'),
|
|
(key: 'calcio', label: 'Calcio'),
|
|
(key: 'fin', label: 'Finanziamenti'),
|
|
(key: 'upselling', label: 'Upselling'),
|
|
(key: 'cb', label: 'Customer Base'),
|
|
(key: 'al', label: 'Attivazioni Linea'),
|
|
(key: 'telepass', label: 'Telepass'),
|
|
(key: 'energiaTim', label: 'Energia TIM'),
|
|
(key: 'energiaAltri', label: 'Energia Non TIM'),
|
|
(key: 'ricontatti', label: 'Ricontatti / Bollette'),
|
|
];
|
|
|
|
/// Calcola l'avanzamento completo per un target (di negozio e per ciascun addetto)
|
|
Future<TargetProgressModel> calculateTargetProgress({
|
|
required TargetModel target,
|
|
DateTime? now,
|
|
}) async {
|
|
final effectiveNow = now ?? DateTime.now();
|
|
|
|
// 1. Calcolo giorni lavorativi con esclusione di domeniche e festivi
|
|
final days = WorkingDaysHelper.calculateWorkingDaysPeriod(
|
|
start: target.startDay,
|
|
end: target.endDay,
|
|
now: effectiveNow,
|
|
);
|
|
|
|
// 2. Query su operations nel periodo target per lo store
|
|
Map<String, int> storeCounts = {
|
|
for (final def in metricDefinitions) def.key: 0,
|
|
};
|
|
Map<String, Map<String, int>> staffCounts = {};
|
|
|
|
try {
|
|
final storeId = target.storeId;
|
|
if (storeId != null && storeId.isNotEmpty) {
|
|
final response = await _supabase
|
|
.from(Tables.operations)
|
|
.select('''
|
|
id,
|
|
store_id,
|
|
staff_id,
|
|
created_at,
|
|
status,
|
|
is_business,
|
|
${Tables.operationDetails}(
|
|
type,
|
|
sub_type,
|
|
quantity,
|
|
provider_id,
|
|
${Tables.providers}(name)
|
|
)
|
|
''')
|
|
.eq('company_id', target.companyId)
|
|
.eq('store_id', storeId)
|
|
.neq('status', 'failure')
|
|
.gte('created_at', target.startDay.toIso8601String())
|
|
.lte('created_at', target.endDay.toIso8601String());
|
|
|
|
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');
|
|
}
|
|
|
|
// 3. Costruzione CategoryProgress per il negozio
|
|
final storeCategories = <String, CategoryProgress>{};
|
|
for (final def in metricDefinitions) {
|
|
final actual = storeCounts[def.key] ?? 0;
|
|
final targets = _extractTargetS1S2(target.metrics, def.key);
|
|
|
|
storeCategories[def.key] = CategoryProgress.calculate(
|
|
key: def.key,
|
|
label: def.label,
|
|
actual: actual,
|
|
s1: targets.s1,
|
|
s2: targets.s2,
|
|
elapsedDays: days.elapsed,
|
|
remainingDays: days.remaining,
|
|
totalDays: days.total,
|
|
);
|
|
}
|
|
|
|
// 4. Costruzione avanzamento per singoli addetti (solo addetti attivi)
|
|
final staffProgressMap = <String, TargetProgressModel>{};
|
|
final individualTargetsList = target.individualTargets
|
|
.where((it) => it.staff == null || it.staff!.isActive)
|
|
.toList();
|
|
final inactiveStaffIds = target.individualTargets
|
|
.where((it) => it.staff != null && !it.staff!.isActive)
|
|
.map((it) => it.staffId)
|
|
.toSet();
|
|
|
|
final bool hasExplicitIndividualTargets = individualTargetsList.any(
|
|
(it) => it.metrics.totalLevel1 > 0 || it.metrics.totalLevel2 > 0,
|
|
);
|
|
|
|
final int staffCount = individualTargetsList.isNotEmpty
|
|
? individualTargetsList.length
|
|
: (staffCounts.isNotEmpty ? staffCounts.length : 1);
|
|
|
|
for (final it in individualTargetsList) {
|
|
final sId = it.staffId;
|
|
final sCounts = staffCounts[sId] ?? {};
|
|
final sCategories = <String, CategoryProgress>{};
|
|
|
|
for (final def in metricDefinitions) {
|
|
final actual = sCounts[def.key] ?? 0;
|
|
({int s1, int s2}) targets;
|
|
|
|
if (hasExplicitIndividualTargets) {
|
|
targets = _extractTargetS1S2(it.metrics, def.key);
|
|
} else {
|
|
// Se non sono stati assegnati target individuali, dividi equamente il target del negozio
|
|
final storeTargets = _extractTargetS1S2(target.metrics, def.key);
|
|
targets = (
|
|
s1: staffCount > 0
|
|
? (storeTargets.s1 / staffCount).round()
|
|
: storeTargets.s1,
|
|
s2: staffCount > 0
|
|
? (storeTargets.s2 / staffCount).round()
|
|
: storeTargets.s2,
|
|
);
|
|
}
|
|
|
|
sCategories[def.key] = CategoryProgress.calculate(
|
|
key: def.key,
|
|
label: def.label,
|
|
actual: actual,
|
|
s1: targets.s1,
|
|
s2: targets.s2,
|
|
elapsedDays: days.elapsed,
|
|
remainingDays: days.remaining,
|
|
totalDays: days.total,
|
|
);
|
|
}
|
|
|
|
staffProgressMap[sId] = TargetProgressModel(
|
|
targetId: target.id ?? '',
|
|
storeId: target.storeId,
|
|
staffId: sId,
|
|
staffName: it.staff?.name,
|
|
totalWorkingDays: days.total,
|
|
elapsedWorkingDays: days.elapsed,
|
|
remainingWorkingDays: days.remaining,
|
|
categories: sCategories,
|
|
);
|
|
}
|
|
|
|
// Se ci sono addetti con operazioni che non compaiono in individualTargets, creiamo la loro scheda
|
|
for (final sId in staffCounts.keys) {
|
|
if (inactiveStaffIds.contains(sId)) continue;
|
|
if (!staffProgressMap.containsKey(sId)) {
|
|
final sCounts = staffCounts[sId] ?? {};
|
|
final sCategories = <String, CategoryProgress>{};
|
|
|
|
for (final def in metricDefinitions) {
|
|
final actual = sCounts[def.key] ?? 0;
|
|
final storeTargets = _extractTargetS1S2(target.metrics, def.key);
|
|
final targets = (
|
|
s1: staffCount > 0
|
|
? (storeTargets.s1 / staffCount).round()
|
|
: storeTargets.s1,
|
|
s2: staffCount > 0
|
|
? (storeTargets.s2 / staffCount).round()
|
|
: storeTargets.s2,
|
|
);
|
|
|
|
sCategories[def.key] = CategoryProgress.calculate(
|
|
key: def.key,
|
|
label: def.label,
|
|
actual: actual,
|
|
s1: targets.s1,
|
|
s2: targets.s2,
|
|
elapsedDays: days.elapsed,
|
|
remainingDays: days.remaining,
|
|
totalDays: days.total,
|
|
);
|
|
}
|
|
|
|
staffProgressMap[sId] = TargetProgressModel(
|
|
targetId: target.id ?? '',
|
|
storeId: target.storeId,
|
|
staffId: sId,
|
|
totalWorkingDays: days.total,
|
|
elapsedWorkingDays: days.elapsed,
|
|
remainingWorkingDays: days.remaining,
|
|
categories: sCategories,
|
|
);
|
|
}
|
|
}
|
|
|
|
return TargetProgressModel(
|
|
targetId: target.id ?? '',
|
|
storeId: target.storeId,
|
|
totalWorkingDays: days.total,
|
|
elapsedWorkingDays: days.elapsed,
|
|
remainingWorkingDays: days.remaining,
|
|
categories: storeCategories,
|
|
staffProgress: staffProgressMap,
|
|
);
|
|
}
|
|
|
|
/// 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 const [];
|
|
|
|
if (opType == OperationType.business || isBusinessOp) {
|
|
return const ['business'];
|
|
}
|
|
|
|
final normalizedSubType = subType?.trim().toLowerCase();
|
|
|
|
switch (opType) {
|
|
case OperationType.mnp:
|
|
return const ['mnp'];
|
|
case OperationType.unica:
|
|
return const ['unica'];
|
|
case OperationType.nip:
|
|
return const ['nip'];
|
|
case OperationType.entertainment:
|
|
if (normalizedSubType != null && normalizedSubType.contains('calcio')) {
|
|
return const ['calcio', 'contenuti'];
|
|
}
|
|
return const ['contenuti'];
|
|
case OperationType.fin:
|
|
return const ['fin'];
|
|
case OperationType.upselling:
|
|
return const ['upselling'];
|
|
case OperationType.cb:
|
|
return const ['cb'];
|
|
case OperationType.al:
|
|
return const ['al'];
|
|
case OperationType.telepass:
|
|
return const ['telepass'];
|
|
case OperationType.energy:
|
|
if (providerName.trim().toLowerCase().contains('tim')) {
|
|
return const ['energiaTim'];
|
|
}
|
|
return const ['energiaAltri'];
|
|
case OperationType.ricontatto:
|
|
return const ['ricontatti'];
|
|
default:
|
|
return const [];
|
|
}
|
|
}
|
|
|
|
/// Estrae i valori di Soglia 1 e Soglia 2 per la specifica categoria da TargetMetrics
|
|
({int s1, int s2}) _extractTargetS1S2(TargetMetrics m, String key) {
|
|
switch (key) {
|
|
case 'mnp':
|
|
return (s1: m.mnp1, s2: m.mnp2);
|
|
case 'unica':
|
|
return (s1: m.unica1, s2: m.unica2);
|
|
case 'nip':
|
|
return (s1: m.nip1, s2: m.nip2);
|
|
case 'business':
|
|
return (s1: m.business1, s2: m.business2);
|
|
case 'contenuti':
|
|
return (s1: m.contenuti1, s2: m.contenuti2);
|
|
case 'calcio':
|
|
return (s1: m.calcio1, s2: m.calcio2);
|
|
case 'fin':
|
|
return (s1: m.fin1, s2: m.fin2);
|
|
case 'upselling':
|
|
return (s1: m.upselling1, s2: m.upselling2);
|
|
case 'cb':
|
|
return (s1: m.cb1, s2: m.cb2);
|
|
case 'al':
|
|
return (s1: m.al1, s2: m.al2);
|
|
case 'telepass':
|
|
return (s1: m.telepass1, s2: m.telepass2);
|
|
case 'energiaTim':
|
|
return (s1: m.energiaTim1, s2: m.energiaTim2);
|
|
case 'energiaAltri':
|
|
return (s1: m.energiaAltri1, s2: m.energiaAltri2);
|
|
case 'ricontatti':
|
|
return (s1: m.ricontatti1, s2: m.ricontatti2);
|
|
default:
|
|
return (s1: 0, s2: 0);
|
|
}
|
|
}
|
|
}
|