Compare commits

...
11 Commits
Author SHA1 Message Date
brontomark 6d2c563ce2 feat: add customer orders feature with management, forms, and PDF export
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m37s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m38s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m24s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 10m50s
2026-12-02 18:26:45 +01:00
brontomark 5fcc16fb9c refactor: improve responsive layout across dashboard cards and add unit tests
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m20s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m35s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m41s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 10m33s
2026-11-29 13:56:44 +01:00
brontomark 1084b03610 feat: implement auto-save functionality for operations form 2026-11-29 13:17:56 +01:00
brontomark 63edd51420 v
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m0s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m23s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m57s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 14m52s
2026-11-21 15:10:50 +01:00
brontomark 7572f4c061 compilazione linux su docker x retrocompatibilità 2026-11-21 15:10:24 +01:00
brontomark 57a4dc6f68 filtri avanzati operazioni
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m31s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m50s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m26s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m43s
2026-11-21 10:23:04 +01:00
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
75 changed files with 8947 additions and 1302 deletions

No files matched your search

+10 -41
View File
@@ -124,10 +124,10 @@ jobs:
-d "{\"latest_version\": \"$TagVersion\"}"
# -----------------------------------------------------------------
# JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner)
# JOB 4: LINUX APPIMAGE (Build isolata su Ubuntu 22.04 via Docker)
# -----------------------------------------------------------------
build-linux:
runs-on: linux-runner # <--- Etichetta del tuo runner Linux / Fedora in ufficio
runs-on: linux-runner # <--- Etichetta del tuo runner Linux in ufficio
steps:
- name: Checkout del codice
uses: actions/checkout@v3
@@ -138,48 +138,17 @@ jobs:
${{ secrets.ENV_FILE_CONTENT }}
EOF
- name: Pulizia Cache e Fetch Dipendenze
- name: Prepara immagine Docker (Ubuntu 22.04 / x86-64-baseline)
run: |
rm -rf .dart_tool
flutter pub get
docker build -t flux-linux-builder -f docker/linux-appimage.Dockerfile docker
- name: Build Flutter Linux
run: flutter build linux --release
- name: Prepara AppDir per AppImage
- name: Build Flutter Linux e Genera AppImage nel container
run: |
mkdir -p build/Flux.AppDir
cp -r build/linux/x64/release/bundle/* build/Flux.AppDir/
cp assets/icon/icon.png build/Flux.AppDir/flux.png
cat << 'EOF' > build/Flux.AppDir/AppRun
#!/bin/sh
cd "$(dirname "$0")"
exec ./flux "$@"
EOF
chmod +x build/Flux.AppDir/AppRun
cat << 'EOF' > build/Flux.AppDir/Flux.desktop
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Flux
Exec=flux %u
Icon=flux
Categories=Utility;
EOF
- name: Scarica appimagetool se non presente
run: |
if [ ! -f ./appimagetool-x86_64.AppImage ]; then
curl -L -o appimagetool-x86_64.AppImage https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 ./appimagetool-x86_64.AppImage build/Flux.AppDir Flux-x86_64.AppImage
docker run --rm \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
-v "$PWD:/workspace" \
flux-linux-builder
- name: Upload Linux AppImage Asset
uses: https://gitea.com/actions/release-action@main
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -euo pipefail
SRC_DIR="/tmp/flux-src"
APPDIR="/tmp/Flux.AppDir"
OUT_APPIMAGE="/workspace/Flux-x86_64.AppImage"
rm -rf "${SRC_DIR}" "${APPDIR}"
mkdir -p "${SRC_DIR}"
tar -C /workspace \
--exclude='./.git' \
--exclude='./build' \
--exclude='./.dart_tool' \
--exclude='./*.AppImage' \
--exclude='./*.AppDir' \
--exclude='./appimagetool*' \
-cf - . | tar -C "${SRC_DIR}" -xf -
cd "${SRC_DIR}"
flutter pub get
flutter build linux --release
mkdir -p "${APPDIR}"
cp -r build/linux/x64/release/bundle/* "${APPDIR}/"
cp assets/icon/icon.png "${APPDIR}/flux.png"
cat << 'EOF' > "${APPDIR}/AppRun"
#!/bin/sh
cd "$(dirname "$0")"
exec ./flux "$@"
EOF
chmod +x "${APPDIR}/AppRun"
cat << 'EOF' > "${APPDIR}/Flux.desktop"
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Flux
Exec=flux %u
Icon=flux
Categories=Utility;
EOF
ARCH=x86_64 appimagetool "${APPDIR}" "${OUT_APPIMAGE}"
if [ -n "${HOST_UID:-}" ] && [ -n "${HOST_GID:-}" ]; then
chown "${HOST_UID}:${HOST_GID}" "${OUT_APPIMAGE}"
fi
+45
View File
@@ -0,0 +1,45 @@
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
ca-certificates \
clang \
cmake \
curl \
file \
git \
libgtk-3-dev \
liblzma-dev \
libstdc++-12-dev \
ninja-build \
pkg-config \
unzip \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
ARG FLUTTER_CHANNEL=stable
RUN git config --global --add safe.directory '*' \
&& git clone https://github.com/flutter/flutter.git -b "${FLUTTER_CHANNEL}" --depth 1 /opt/flutter
ENV PATH="/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:${PATH}"
RUN flutter config --no-analytics --enable-linux-desktop \
&& flutter precache --linux
RUN curl -fsSL -o /tmp/appimagetool.AppImage \
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage \
&& chmod +x /tmp/appimagetool.AppImage \
&& cd /opt \
&& /tmp/appimagetool.AppImage --appimage-extract \
&& mv /opt/squashfs-root /opt/appimagetool \
&& ln -s /opt/appimagetool/AppRun /usr/local/bin/appimagetool \
&& rm -f /tmp/appimagetool.AppImage
COPY build-linux-appimage.sh /usr/local/bin/build-linux-appimage.sh
RUN chmod +x /usr/local/bin/build-linux-appimage.sh
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/build-linux-appimage.sh"]
+1
View File
@@ -5,6 +5,7 @@ class Tables {
static const String campaigns = 'campaigns';
static const String companies = 'companies';
static const String customers = 'customers';
static const String customerOrders = 'customer_orders';
static const String documentSequences = 'document_sequences';
static const String models = 'models';
static const String notes = 'notes';
@@ -0,0 +1,106 @@
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
/// Modalità di avviso preferita del cliente (condivisa tra Ordini Clienti e Ticket Assistenza)
enum ContactPreference {
whatsappPrimary(
value: 'whatsapp_primary',
label: 'WhatsApp (Principale)',
shortLabel: 'WA Principale',
materialIcon: Icons.chat_bubble_outline_rounded,
color: Colors.green,
usesAlternativePhone: false,
isWhatsapp: true,
isCall: false,
isEmail: false,
),
whatsappAlternative(
value: 'whatsapp_alternative',
label: 'WhatsApp (Recapito Alternativo)',
shortLabel: 'WA Alternativo',
materialIcon: Icons.chat_bubble_outline_rounded,
color: Colors.teal,
usesAlternativePhone: true,
isWhatsapp: true,
isCall: false,
isEmail: false,
),
callPrimary(
value: 'call_primary',
label: 'Telefonata (Principale)',
shortLabel: 'Tel. Principale',
materialIcon: Icons.phone_outlined,
color: Colors.blue,
usesAlternativePhone: false,
isWhatsapp: false,
isCall: true,
isEmail: false,
),
callAlternative(
value: 'call_alternative',
label: 'Telefonata (Recapito Alternativo)',
shortLabel: 'Tel. Alternativo',
materialIcon: Icons.phone_forwarded_outlined,
color: Colors.indigo,
usesAlternativePhone: true,
isWhatsapp: false,
isCall: true,
isEmail: false,
),
email(
value: 'email',
label: 'Email',
shortLabel: 'Email',
materialIcon: Icons.alternate_email_rounded,
color: Colors.deepOrange,
usesAlternativePhone: false,
isWhatsapp: false,
isCall: false,
isEmail: true,
);
final String value;
final String label;
final String shortLabel;
final IconData materialIcon;
final Color color;
final bool usesAlternativePhone;
final bool isWhatsapp;
final bool isCall;
final bool isEmail;
const ContactPreference({
required this.value,
required this.label,
required this.shortLabel,
required this.materialIcon,
required this.color,
required this.usesAlternativePhone,
required this.isWhatsapp,
required this.isCall,
required this.isEmail,
});
Widget buildIcon({double size = 16, Color? overrideColor}) {
final c = overrideColor ?? color;
if (isWhatsapp) {
return FaIcon(FontAwesomeIcons.whatsapp, size: size, color: c);
}
return Icon(materialIcon, size: size, color: c);
}
static ContactPreference fromString(
String? val, {
ContactPreference fallback = ContactPreference.whatsappPrimary,
}) {
if (val == null || val.trim().isEmpty) return fallback;
final clean = val.trim().toLowerCase();
for (final item in ContactPreference.values) {
if (item.value.toLowerCase() == clean ||
item.name.toLowerCase() == clean) {
return item;
}
}
return fallback;
}
}
+5
View File
@@ -143,6 +143,11 @@ class _AppMenuState extends State<AppMenu> {
Routes.tickets,
'/tickets',
),
_SubMenuItem(
'Ordini Clienti',
Routes.customerOrders,
'/orders',
),
_SubMenuItem('Tasks', Routes.tasks, '/tasks'),
_SubMenuItem('Sticky Notes', Routes.notes, '/notes'),
],
+73 -1
View File
@@ -12,6 +12,11 @@ import 'package:flux/features/auth/ui/auth_screen.dart';
import 'package:flux/features/auth/ui/set_password_screen.dart';
import 'package:flux/features/company/bloc/company_settings_cubit.dart';
import 'package:flux/features/company/ui/company_settings_screen.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_form_cubit.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/ui/customer_order_form_screen.dart';
import 'package:flux/features/customer_orders/ui/customer_order_list_screen.dart';
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
@@ -48,6 +53,7 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/ui/financing_form_screen.dart';
import 'package:flux/features/operations/ui/operation_form_screen.dart';
import 'package:flux/features/operations/ui/operation_list_screen.dart';
@@ -119,6 +125,9 @@ class AppRouter {
if (sessionState.status == SessionStatus.unauthenticated) {
// Se sta già andando alle uniche altre pagine pubbliche, lascialo andare
if (isGoingToLogin || isGoingToSetPassword) return null;
if (path != '/' && path.isNotEmpty) {
pendingRoute = state.uri.toString();
}
// Altrimenti bloccalo e mandalo al login
return '/login';
}
@@ -317,13 +326,30 @@ class AppRouter {
GoRoute(
path: '/operations',
name: Routes.operations,
builder: (context, state) => const OperationListScreen(),
builder: (context, state) {
final params = state.extra is OperationFilterParams
? state.extra as OperationFilterParams
: OperationFilterParams.fromQueryParams(
state.uri.queryParameters,
);
return OperationListScreen(
initialFilters: params.isNotEmpty ? params : null,
);
},
),
GoRoute(
path: '/tickets',
name: Routes.tickets,
builder: (context, state) => const TicketListScreen(),
),
GoRoute(
path: '/orders',
name: Routes.customerOrders,
builder: (context, state) => BlocProvider(
create: (_) => sl<CustomerOrderListCubit>(),
child: const CustomerOrderListScreen(),
),
),
GoRoute(
path: '/notes',
name: Routes.notes,
@@ -608,6 +634,52 @@ class AppRouter {
},
),
GoRoute(
path: '/orders/form/:id',
name: Routes.customerOrderForm,
builder: (context, state) {
final String pathId = state.pathParameters['id'] ?? 'new';
final record =
state.extra
as ({
StaffMemberModel? createdBy,
CustomerOrderModel? order,
})?;
final String? realOrderId;
if (pathId == 'new') {
realOrderId = null;
} else if (record?.order?.id != null) {
realOrderId = record!.order!.id;
} else {
realOrderId = pathId;
}
context.read<CustomersListCubit>().loadCustomers();
return MultiBlocProvider(
providers: [
BlocProvider(
create: (_) => AttachmentsBloc(
parentId: realOrderId,
parentType: AttachmentParentType.customerOrder,
),
),
BlocProvider(
create: (_) => CustomerOrderFormCubit(
createdBy: record?.createdBy,
existingOrder: record?.order,
),
),
],
child: CustomerOrderFormScreen(
orderId: realOrderId,
order: record?.order,
),
);
},
),
GoRoute(
path: '/upload/:type/:id',
name: Routes.upload,
+2
View File
@@ -31,4 +31,6 @@ class Routes {
static const String targetForm = 'target-form';
static const String targetDetail = 'target-detail';
static const String financing = 'financing';
static const String customerOrders = 'customer-orders';
static const String customerOrderForm = 'customer-order-form';
}
+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,
@@ -0,0 +1,141 @@
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customers/models/customer_model.dart';
class ContactPreferenceSection extends StatelessWidget {
final ContactPreference selectedPreference;
final ValueChanged<ContactPreference> onPreferenceChanged;
final CustomerModel? customer;
final TextEditingController? alternativePhoneController;
final bool alwaysShowAlternativePhone;
const ContactPreferenceSection({
super.key,
required this.selectedPreference,
required this.onPreferenceChanged,
this.customer,
this.alternativePhoneController,
this.alwaysShowAlternativePhone = false,
});
String _resolveTargetDestination() {
final altText =
alternativePhoneController?.text.trim().isNotEmpty == true
? alternativePhoneController!.text.trim()
: (customer?.alternativePhoneNumber.trim() ?? '');
if (selectedPreference.isEmail) {
return customer?.email.trim() ?? '';
}
if (selectedPreference.usesAlternativePhone) {
return altText;
}
return customer?.phoneNumber.trim() ?? '';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final showAltField =
alwaysShowAlternativePhone || selectedPreference.usesAlternativePhone;
final destination = _resolveTargetDestination();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Modalità di Avviso Cliente',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: ContactPreference.values.map((pref) {
final isSelected = pref == selectedPreference;
return ChoiceChip(
selected: isSelected,
showCheckmark: false,
avatar: pref.buildIcon(
size: 15,
overrideColor: isSelected ? pref.color : Colors.grey.shade600,
),
label: Text(
pref.shortLabel,
style: TextStyle(
fontSize: 12.5,
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
color: isSelected ? pref.color : null,
),
),
selectedColor: pref.color.withValues(alpha: 0.15),
side: BorderSide(
color: isSelected
? pref.color.withValues(alpha: 0.6)
: theme.dividerColor.withValues(alpha: 0.35),
),
onSelected: (_) => onPreferenceChanged(pref),
);
}).toList(),
),
if (customer != null) ...[
const SizedBox(height: 8),
Row(
children: [
Icon(
destination.isNotEmpty
? Icons.check_circle_outline_rounded
: Icons.warning_amber_rounded,
size: 15,
color: destination.isNotEmpty ? Colors.green : Colors.orange,
),
const SizedBox(width: 6),
Expanded(
child: Text(
destination.isNotEmpty
? 'Verrà avvisato su: $destination (${selectedPreference.label})'
: 'Attenzione: nessun recapito impostato per "${selectedPreference.label}"',
style: TextStyle(
fontSize: 12,
color: destination.isNotEmpty
? theme.colorScheme.onSurfaceVariant
: Colors.orange.shade800,
fontWeight: destination.isNotEmpty
? FontWeight.normal
: FontWeight.w600,
),
),
),
],
),
],
if (showAltField && alternativePhoneController != null) ...[
const SizedBox(height: 12),
TextFormField(
controller: alternativePhoneController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: selectedPreference.usesAlternativePhone
? 'Recapito Alternativo *'
: 'Recapito Alternativo (opzionale)',
hintText: 'Es. telefono coniuge / ufficio...',
prefixIcon: const Icon(Icons.phone_forwarded_outlined),
helperText: customer != null
? 'Se compilato, verrà salvato anche sull\'anagrafica del cliente'
: null,
),
validator: (val) {
if (selectedPreference.usesAlternativePhone &&
(val == null || val.trim().isEmpty)) {
return 'Inserisci il recapito alternativo per avvisare il cliente';
}
return null;
},
),
],
],
);
}
}
@@ -85,6 +85,7 @@ class SharedCustomerSection extends StatelessWidget {
),
if (hasCustomer &&
(customer!.phoneNumber.isNotEmpty ||
customer!.alternativePhoneNumber.isNotEmpty ||
customer!.email.isNotEmpty)) ...[
const SizedBox(height: 12), // Un po' più di respiro dal box sopra
// Mettiamo i contatti in un Container con un po' di stile per farli sembrare una "Contact Card" integrata
@@ -148,8 +149,79 @@ class SharedCustomerSection extends StatelessWidget {
],
),
// Sezione divisoria se ci sono entrambi
// --- RIGA RECAPITO ALTERNATIVO ---
if (customer!.phoneNumber.isNotEmpty &&
customer!.alternativePhoneNumber.isNotEmpty)
const Divider(height: 8, thickness: 0.5),
if (customer!.alternativePhoneNumber.isNotEmpty)
Row(
children: [
IconButton(
visualDensity: VisualDensity.compact,
onPressed: () => launchUrl(
Uri.parse(
'https://wa.me/39${customer!.alternativePhoneNumber}',
),
),
icon: const FaIcon(
FontAwesomeIcons.whatsapp,
color: Colors.teal,
size: 20,
),
tooltip: 'WhatsApp su recapito alternativo',
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
SelectableText(
customer!.alternativePhoneNumber,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
Text(
'Recapito alternativo',
style: TextStyle(
fontSize: 10.5,
color: Colors.grey.shade600,
),
),
],
),
),
IconButton(
visualDensity: VisualDensity.compact,
onPressed: () {
Clipboard.setData(
ClipboardData(
text: customer!.alternativePhoneNumber,
),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Recapito alternativo copiato!'),
duration: Duration(seconds: 2),
),
);
},
icon: const Icon(
Icons.copy,
size: 18,
color: Colors.grey,
),
tooltip: 'Copia',
),
],
),
// Sezione divisoria se c'è email dopo un telefono
if ((customer!.phoneNumber.isNotEmpty ||
customer!.alternativePhoneNumber.isNotEmpty) &&
customer!.email.isNotEmpty)
const Divider(height: 8, thickness: 0.5),
@@ -225,6 +225,10 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
state.parentType == AttachmentParentType.ticket ? '' : null,
customerId:
state.parentType == AttachmentParentType.customer ? '' : null,
customerOrderId:
state.parentType == AttachmentParentType.customerOrder
? ''
: null,
name: file.name.fileNameWithoutExtension(),
extension: file.name.fileExtension(),
storagePath: '',
@@ -433,6 +437,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return file.copyWith(shippingDocumentId: event.targetId);
case AttachmentParentType.note:
return file.copyWith(noteId: event.targetId);
case AttachmentParentType.customerOrder:
return file.copyWith(customerOrderId: event.targetId);
}
}
return file;
@@ -609,6 +615,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return Bucket.companyDocuments;
case AttachmentParentType.note:
return Bucket.documents;
case AttachmentParentType.customerOrder:
return Bucket.documents;
}
}
}
@@ -7,7 +7,8 @@ enum AttachmentParentType {
ticket('ticket_id'),
customer('customer_id'),
shippingDocument('shipping_document_id'),
note('note_id');
note('note_id'),
customerOrder('customer_order_id');
final String dbColumn;
const AttachmentParentType(this.dbColumn);
@@ -46,6 +46,8 @@ class AttachmentsRepository {
return 'shipping_document_id';
case AttachmentParentType.note:
return 'note_id';
case AttachmentParentType.customerOrder:
return 'customer_order_id';
}
}
@@ -200,6 +202,8 @@ class AttachmentsRepository {
AttachmentParentType.ticket: file.ticketId,
AttachmentParentType.customer: file.customerId,
AttachmentParentType.shippingDocument: file.shippingDocumentId,
AttachmentParentType.note: file.noteId,
AttachmentParentType.customerOrder: file.customerOrderId,
};
// 2. Simuliamo la rimozione del collegamento per il contesto attuale
@@ -26,6 +26,7 @@ class AttachmentModel extends Equatable {
final String? ticketId;
final String? shippingDocumentId;
final String? noteId;
final String? customerOrderId;
final String name;
final String extension;
final String? storagePath;
@@ -44,6 +45,7 @@ class AttachmentModel extends Equatable {
this.ticketId,
this.shippingDocumentId,
this.noteId,
this.customerOrderId,
required this.name,
required this.extension,
this.storagePath,
@@ -71,6 +73,7 @@ class AttachmentModel extends Equatable {
ticketId,
shippingDocumentId,
noteId,
customerOrderId,
name,
extension,
storagePath,
@@ -122,6 +125,7 @@ class AttachmentModel extends Equatable {
String? ticketId,
String? shippingDocumentId,
String? noteId,
String? customerOrderId,
String? name,
String? extension,
String? storagePath,
@@ -139,6 +143,7 @@ class AttachmentModel extends Equatable {
ticketId: ticketId ?? this.ticketId,
shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId,
noteId: noteId ?? this.noteId,
customerOrderId: customerOrderId ?? this.customerOrderId,
name: name ?? this.name,
extension: extension ?? this.extension,
storagePath: storagePath ?? this.storagePath,
@@ -161,6 +166,7 @@ class AttachmentModel extends Equatable {
ticketId: map['ticket_id'] as String?,
shippingDocumentId: map['shipping_document_id'] as String?,
noteId: map['note_id'] as String?,
customerOrderId: map['customer_order_id'] as String?,
name: map['name'] as String,
extension: map['extension'] as String,
storagePath: map['storage_path'] as String?,
@@ -185,11 +191,12 @@ class AttachmentModel extends Equatable {
'ticket_id': ticketId,
'shipping_document_id': shippingDocumentId,
'note_id': noteId,
'customer_order_id': customerOrderId,
'file_size': fileSize,
'company_id': companyId,
'thumbnail_path': thumbnailPath,
'cropped_storage_path': croppedStoragePath,
'view_mode': viewMode?.value,
'view_mode': (viewMode ?? AttachmentViewMode.original).value,
};
}
}
@@ -0,0 +1,320 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customers/data/customer_repository.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/service_locator.dart';
part 'customer_order_form_state.dart';
class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final CustomerRepository _customerRepository = sl<CustomerRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
CustomerOrderFormCubit({
StaffMemberModel? createdBy,
CustomerOrderModel? existingOrder,
}) : super(
CustomerOrderFormState(
order:
existingOrder ??
CustomerOrderModel.empty().copyWith(
createdById: createdBy?.id,
createdByName: createdBy?.name,
),
),
);
Future<void> initForm({
String? orderId,
CustomerOrderModel? existingOrder,
}) async {
final companyId = _sessionCubit.state.company?.id ?? '';
if (existingOrder != null && existingOrder.id != null) {
emit(
state.copyWith(
order: existingOrder,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
// Aggiorniamo anche in background con i dettagli freschi (es. da scansione o relazioni)
final fresh = await _repository.getOrderById(existingOrder.id!);
if (fresh != null && !isClosed) {
emit(state.copyWith(order: fresh));
}
return;
}
if (orderId != null && orderId.isNotEmpty) {
emit(state.copyWith(status: CustomerOrderFormStatus.loading));
final fetched = await _repository.getOrderById(orderId);
if (fetched == null) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Ordine non trovato.',
),
);
return;
}
emit(
state.copyWith(
order: fetched,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
return;
}
// Nuovo ordine
final currentStore = _sessionCubit.state.currentStore;
final currentStaff = _sessionCubit.state.currentStaffMember;
final newOrder = state.order.copyWith(
companyId: companyId,
storeId: currentStore?.id,
storeDisplayName: currentStore?.name,
createdById: state.order.createdById ?? currentStaff?.id,
createdByName: state.order.createdByName ?? currentStaff?.name,
orderDate: DateTime.now(),
status: CustomerOrderStatus.toOrder,
);
emit(
state.copyWith(
order: newOrder,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
}
Future<void> _loadAvailableTags(String companyId) async {
if (companyId.isEmpty) return;
final tags = await _repository.fetchDistinctTags(companyId);
if (!isClosed) {
emit(state.copyWith(availableTags: tags));
}
}
void updateCustomer(CustomerModel customer) {
final currentAlt = state.order.alternativePhoneNumber?.trim() ?? '';
final resolvedAlt = currentAlt.isNotEmpty
? currentAlt
: (customer.alternativePhoneNumber.trim().isNotEmpty
? customer.alternativePhoneNumber.trim()
: null);
emit(
state.copyWith(
order: state.order.copyWith(
customerId: customer.id,
customer: customer,
alternativePhoneNumber: resolvedAlt,
),
),
);
}
void updateFields({
DateTime? orderDate,
String? storeId,
String? storeDisplayName,
String? productDescription,
int? quantity,
String? notes,
double? price,
double? deposit,
String? externalCode,
CustomerOrderStatus? status,
ContactPreference? contactPreference,
String? alternativePhoneNumber,
bool? customerNotified,
}) {
DateTime? notifiedAt = state.order.customerNotifiedAt;
bool clearNotifiedAt = false;
if (customerNotified != null) {
if (customerNotified && !state.order.customerNotified) {
notifiedAt = DateTime.now();
} else if (!customerNotified) {
clearNotifiedAt = true;
}
}
emit(
state.copyWith(
order: state.order.copyWith(
orderDate: orderDate ?? state.order.orderDate,
storeId: storeId ?? state.order.storeId,
storeDisplayName: storeDisplayName ?? state.order.storeDisplayName,
productDescription:
productDescription ?? state.order.productDescription,
quantity: quantity ?? state.order.quantity,
notes: notes ?? state.order.notes,
price: price ?? state.order.price,
deposit: deposit ?? state.order.deposit,
externalCode: externalCode ?? state.order.externalCode,
status: status ?? state.order.status,
contactPreference: contactPreference ?? state.order.contactPreference,
alternativePhoneNumber:
alternativePhoneNumber ?? state.order.alternativePhoneNumber,
customerNotified: customerNotified ?? state.order.customerNotified,
customerNotifiedAt: notifiedAt,
clearCustomerNotifiedAt: clearNotifiedAt,
),
),
);
}
void addTag(String rawTag) {
final clean = rawTag.trim();
if (clean.isEmpty) return;
final exists = state.order.tags.any(
(t) => t.toLowerCase() == clean.toLowerCase(),
);
if (exists) return;
final updatedTags = [...state.order.tags, clean];
final updatedAvailable = state.availableTags.any(
(t) => t.toLowerCase() == clean.toLowerCase(),
)
? state.availableTags
: ([...state.availableTags, clean]
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase())));
emit(
state.copyWith(
order: state.order.copyWith(tags: updatedTags),
availableTags: updatedAvailable,
),
);
}
void removeTag(String tag) {
final updatedTags = state.order.tags.where((t) => t != tag).toList();
emit(state.copyWith(order: state.order.copyWith(tags: updatedTags)));
}
/// Salva l'ordine (o crea bozza per allegati / QR)
Future<CustomerOrderModel?> saveOrder({
CustomerOrderStatus? overrideStatus,
bool silentForAttachment = false,
}) async {
final previousStatus = state.order.status;
final orderToSave = overrideStatus != null
? state.order.copyWith(status: overrideStatus)
: state.order;
if (orderToSave.customerId == null || orderToSave.customerId!.isEmpty) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Seleziona un cliente prima di salvare.',
),
);
return null;
}
if (orderToSave.productDescription.trim().isEmpty) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Inserisci il prodotto richiesto dal cliente.',
),
);
return null;
}
if (!silentForAttachment) {
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
}
try {
final CustomerOrderModel saved;
if (orderToSave.id == null || orderToSave.id!.isEmpty) {
saved = await _repository.insertOrder(orderToSave);
} else {
saved = await _repository.updateOrder(orderToSave);
}
await _syncCustomerAlternativePhone(orderToSave);
final transitionedToArrived =
saved.status == CustomerOrderStatus.arrived &&
previousStatus != CustomerOrderStatus.arrived;
emit(
state.copyWith(
status: silentForAttachment
? CustomerOrderFormStatus.ready
: CustomerOrderFormStatus.saved,
order: saved,
justMarkedArrived: transitionedToArrived,
errorMessage: null,
),
);
return saved;
} catch (e) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: e.toString(),
),
);
return null;
}
}
Future<void> markCustomerNotified(bool notified) async {
final now = DateTime.now();
final updated = state.order.copyWith(
customerNotified: notified,
customerNotifiedAt: notified ? now : null,
clearCustomerNotifiedAt: !notified,
);
emit(state.copyWith(order: updated));
if (updated.id != null && updated.id!.isNotEmpty) {
try {
final saved = await _repository.updateOrder(updated);
if (!isClosed) {
emit(state.copyWith(order: saved));
}
} catch (_) {}
}
}
Future<void> deleteOrder() async {
final id = state.order.id;
if (id == null || id.isEmpty) return;
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
try {
await _repository.deleteOrder(id);
emit(state.copyWith(status: CustomerOrderFormStatus.deleted));
} catch (e) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
Future<void> _syncCustomerAlternativePhone(CustomerOrderModel order) async {
final customer = order.customer;
final newAlt = order.alternativePhoneNumber?.trim() ?? '';
if (customer == null || customer.id == null || newAlt.isEmpty) return;
if (customer.alternativePhoneNumber.trim() == newAlt) return;
try {
await _customerRepository.updateCustomer(
customer.copyWith(alternativePhoneNumber: newAlt),
);
} catch (_) {}
}
}
@@ -0,0 +1,52 @@
part of 'customer_order_form_cubit.dart';
enum CustomerOrderFormStatus {
initial,
loading,
ready,
saving,
saved,
deleted,
failure,
}
class CustomerOrderFormState extends Equatable {
final CustomerOrderFormStatus status;
final CustomerOrderModel order;
final List<String> availableTags;
final String? errorMessage;
final bool justMarkedArrived;
const CustomerOrderFormState({
this.status = CustomerOrderFormStatus.initial,
required this.order,
this.availableTags = const [],
this.errorMessage,
this.justMarkedArrived = false,
});
CustomerOrderFormState copyWith({
CustomerOrderFormStatus? status,
CustomerOrderModel? order,
List<String>? availableTags,
String? errorMessage,
bool? justMarkedArrived,
}) {
return CustomerOrderFormState(
status: status ?? this.status,
order: order ?? this.order,
availableTags: availableTags ?? this.availableTags,
errorMessage: errorMessage,
justMarkedArrived: justMarkedArrived ?? false,
);
}
@override
List<Object?> get props => [
status,
order,
availableTags,
errorMessage,
justMarkedArrived,
];
}
@@ -0,0 +1,159 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/service_locator.dart';
part 'customer_order_list_state.dart';
class CustomerOrderListCubit extends Cubit<CustomerOrderListState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
StreamSubscription<void>? _ordersSubscription;
Timer? _searchDebounce;
CustomerOrderListCubit() : super(const CustomerOrderListState()) {
_ordersSubscription = _repository.onOrdersChanged.listen((_) {
loadOrders(silent: true);
loadTags();
});
}
Future<void> init() async {
await Future.wait([loadOrders(), loadTags()]);
}
Future<void> loadTags() async {
final companyId = _sessionCubit.state.company?.id;
if (companyId == null || companyId.isEmpty) return;
final tags = await _repository.fetchDistinctTags(companyId);
if (!isClosed) {
emit(state.copyWith(availableTags: tags));
}
}
Future<void> loadOrders({bool silent = false}) async {
final companyId = _sessionCubit.state.company?.id;
if (companyId == null || companyId.isEmpty) return;
if (!silent) {
emit(state.copyWith(status: CustomerOrderListStatus.loading));
}
try {
final orders = await _repository.fetchOrders(
companyId: companyId,
quickFilter: state.quickFilter,
storeId: state.storeIdFilter,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
selectedTags: state.selectedTags,
);
if (!isClosed) {
emit(
state.copyWith(
status: CustomerOrderListStatus.success,
orders: orders,
errorMessage: null,
),
);
}
} catch (e) {
if (!isClosed) {
emit(
state.copyWith(
status: CustomerOrderListStatus.failure,
errorMessage: e.toString(),
),
);
}
}
}
void setQuickFilter(CustomerOrderQuickFilter filter) {
if (state.quickFilter == filter) return;
emit(state.copyWith(quickFilter: filter));
loadOrders();
}
void setSearchTerm(String query) {
_searchDebounce?.cancel();
emit(
state.copyWith(
searchTerm: query,
clearSearchTerm: query.trim().isEmpty,
),
);
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
loadOrders();
});
}
void setStoreFilter(String? storeId) {
emit(
state.copyWith(
storeIdFilter: storeId,
clearStoreFilter: storeId == null || storeId.isEmpty,
),
);
loadOrders();
}
void setDateRange(DateTimeRange? range) {
emit(
state.copyWith(
dateRange: range,
clearDateRange: range == null,
),
);
loadOrders();
}
void toggleTagFilter(String tag) {
final updated = List<String>.from(state.selectedTags);
if (updated.contains(tag)) {
updated.remove(tag);
} else {
updated.add(tag);
}
emit(state.copyWith(selectedTags: updated));
loadOrders();
}
void resetFilters() {
emit(
state.copyWith(
quickFilter: CustomerOrderQuickFilter.active,
clearStoreFilter: true,
clearSearchTerm: true,
clearDateRange: true,
selectedTags: const [],
),
);
loadOrders();
}
Future<void> quickUpdateStatus(
CustomerOrderModel order,
CustomerOrderStatus newStatus,
) async {
try {
await _repository.updateOrder(order.copyWith(status: newStatus));
} catch (e) {
if (!isClosed) {
emit(state.copyWith(errorMessage: e.toString()));
}
}
}
@override
Future<void> close() {
_ordersSubscription?.cancel();
_searchDebounce?.cancel();
return super.close();
}
}
@@ -0,0 +1,75 @@
part of 'customer_order_list_cubit.dart';
enum CustomerOrderListStatus { initial, loading, success, failure }
class CustomerOrderListState extends Equatable {
final CustomerOrderListStatus status;
final List<CustomerOrderModel> orders;
final List<String> availableTags;
final CustomerOrderQuickFilter quickFilter;
final String? storeIdFilter;
final String? searchTerm;
final DateTimeRange? dateRange;
final List<String> selectedTags;
final String? errorMessage;
const CustomerOrderListState({
this.status = CustomerOrderListStatus.initial,
this.orders = const [],
this.availableTags = const [],
this.quickFilter = CustomerOrderQuickFilter.active,
this.storeIdFilter,
this.searchTerm,
this.dateRange,
this.selectedTags = const [],
this.errorMessage,
});
bool get hasAdvancedFilters =>
(storeIdFilter != null && storeIdFilter!.isNotEmpty) ||
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
dateRange != null ||
selectedTags.isNotEmpty;
CustomerOrderListState copyWith({
CustomerOrderListStatus? status,
List<CustomerOrderModel>? orders,
List<String>? availableTags,
CustomerOrderQuickFilter? quickFilter,
String? storeIdFilter,
bool clearStoreFilter = false,
String? searchTerm,
bool clearSearchTerm = false,
DateTimeRange? dateRange,
bool clearDateRange = false,
List<String>? selectedTags,
String? errorMessage,
}) {
return CustomerOrderListState(
status: status ?? this.status,
orders: orders ?? this.orders,
availableTags: availableTags ?? this.availableTags,
quickFilter: quickFilter ?? this.quickFilter,
storeIdFilter: clearStoreFilter
? null
: (storeIdFilter ?? this.storeIdFilter),
searchTerm: clearSearchTerm ? null : (searchTerm ?? this.searchTerm),
dateRange: clearDateRange ? null : (dateRange ?? this.dateRange),
selectedTags: selectedTags ?? this.selectedTags,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [
status,
orders,
availableTags,
quickFilter,
storeIdFilter,
searchTerm,
dateRange,
selectedTags,
errorMessage,
];
}
@@ -0,0 +1,198 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class CustomerOrdersRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
final StreamController<void> _ordersChangedController =
StreamController<void>.broadcast();
Stream<void> get onOrdersChanged => _ordersChangedController.stream;
void notifyOrdersChanged() {
if (!_ordersChangedController.isClosed) {
_ordersChangedController.add(null);
}
}
static const String _selectRelations = '''
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*)
''';
Future<CustomerOrderModel?> getOrderById(String id) async {
try {
final response = await _supabase
.from(Tables.customerOrders)
.select(_selectRelations)
.eq('id', id)
.single();
return CustomerOrderModel.fromMap(response);
} catch (e) {
debugPrint('Errore getOrderById ($id): $e');
return null;
}
}
Future<List<CustomerOrderModel>> fetchOrders({
required String companyId,
CustomerOrderQuickFilter quickFilter = CustomerOrderQuickFilter.active,
String? storeId,
String? searchTerm,
DateTimeRange? dateRange,
List<String> selectedTags = const [],
}) async {
try {
var query = _supabase
.from(Tables.customerOrders)
.select(_selectRelations)
.eq('company_id', companyId);
final statuses = quickFilter.dbStatuses;
if (statuses != null && statuses.isNotEmpty) {
query = query.inFilter('status', statuses);
}
if (storeId != null && storeId.isNotEmpty) {
query = query.eq('store_id', storeId);
}
if (dateRange != null) {
final start = DateTime(
dateRange.start.year,
dateRange.start.month,
dateRange.start.day,
);
final end = DateTime(
dateRange.end.year,
dateRange.end.month,
dateRange.end.day,
23,
59,
59,
999,
);
query = query
.gte('order_date', start.toUtc().toIso8601String())
.lte('order_date', end.toUtc().toIso8601String());
}
if (selectedTags.isNotEmpty) {
query = query.overlaps('tags', selectedTags);
}
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
try {
final custRes = await _supabase
.from(Tables.customers)
.select('id')
.eq('company_id', companyId)
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%,alternative_phone_number.ilike.%$cleanTerm%');
matchingCustomerIds = (custRes as List)
.map((row) => row['id'].toString())
.toList();
} catch (_) {}
if (matchingCustomerIds.isNotEmpty) {
final idsJoined = matchingCustomerIds.join(',');
query = query.or(
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%,customer_id.in.($idsJoined)',
);
} else {
query = query.or(
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%',
);
}
}
final response = await query.order('order_date', ascending: false);
return (response as List)
.map((map) => CustomerOrderModel.fromMap(map as Map<String, dynamic>))
.toList();
} catch (e) {
debugPrint('Errore fetchOrders: $e');
throw Exception('Impossibile caricare gli ordini: $e');
}
}
/// Recupera l'elenco ordinato di tutte le etichette (tags) già usate nell'azienda per l'autocomplete
Future<List<String>> fetchDistinctTags(String companyId) async {
try {
final response = await _supabase
.from(Tables.customerOrders)
.select('tags')
.eq('company_id', companyId)
.not('tags', 'is', null);
final Set<String> distinct = {};
for (final row in (response as List)) {
final rawList = row['tags'] as List?;
if (rawList != null) {
for (final tag in rawList) {
final clean = tag.toString().trim();
if (clean.isNotEmpty) distinct.add(clean);
}
}
}
final sorted = distinct.toList()
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
return sorted;
} catch (e) {
debugPrint('Errore fetchDistinctTags: $e');
return const [];
}
}
Future<CustomerOrderModel> insertOrder(CustomerOrderModel order) async {
try {
final res = await _supabase
.from(Tables.customerOrders)
.insert(order.toMap())
.select(_selectRelations)
.single();
notifyOrdersChanged();
return CustomerOrderModel.fromMap(res);
} catch (e) {
debugPrint('Errore insertOrder: $e');
throw Exception('Errore nella creazione dell\'ordine: $e');
}
}
Future<CustomerOrderModel> updateOrder(CustomerOrderModel order) async {
try {
final res = await _supabase
.from(Tables.customerOrders)
.update(order.toMap())
.eq('id', order.id!)
.select(_selectRelations)
.single();
notifyOrdersChanged();
return CustomerOrderModel.fromMap(res);
} catch (e) {
debugPrint('Errore updateOrder: $e');
throw Exception('Errore nell\'aggiornamento dell\'ordine: $e');
}
}
Future<void> deleteOrder(String id) async {
try {
await _supabase.from(Tables.customerOrders).delete().eq('id', id);
notifyOrdersChanged();
} catch (e) {
debugPrint('Errore deleteOrder: $e');
throw Exception('Errore nell\'eliminazione dell\'ordine: $e');
}
}
}
@@ -0,0 +1,254 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customers/models/customer_model.dart';
class CustomerOrderModel extends Equatable {
final String? id;
final DateTime? createdAt;
final DateTime? updatedAt;
final DateTime orderDate;
final String companyId;
final String? storeId;
final String? storeDisplayName;
final String? createdById;
final String? createdByName;
final String? customerId;
final CustomerModel? customer;
final String productDescription;
final int quantity;
final String notes;
final double price;
final double deposit;
final String externalCode;
final CustomerOrderStatus status;
final List<String> tags;
final ContactPreference contactPreference;
final String? alternativePhoneNumber;
final bool customerNotified;
final DateTime? customerNotifiedAt;
final List<AttachmentModel> attachments;
const CustomerOrderModel({
this.id,
this.createdAt,
this.updatedAt,
required this.orderDate,
required this.companyId,
this.storeId,
this.storeDisplayName,
this.createdById,
this.createdByName,
this.customerId,
this.customer,
this.productDescription = '',
this.quantity = 1,
this.notes = '',
this.price = 0.0,
this.deposit = 0.0,
this.externalCode = '',
this.status = CustomerOrderStatus.toOrder,
this.tags = const [],
this.contactPreference = ContactPreference.whatsappPrimary,
this.alternativePhoneNumber,
this.customerNotified = false,
this.customerNotifiedAt,
this.attachments = const [],
});
/// Importo residuo da incassare in cassa al netto dell'eventuale acconto
double get remainingAmount =>
(price - deposit) > 0 ? (price - deposit) : 0.0;
/// URL deep link codificato nel QR dell'etichetta prodotto
String get deepLinkUrl =>
id != null && id!.isNotEmpty ? 'https://flux.catelli.it/orders/form/$id' : '';
/// Recapito effettivo da usare in base alla preferenza scelta
String get effectiveContactDestination {
if (contactPreference.isEmail) {
return customer?.email.trim() ?? '';
}
if (contactPreference.usesAlternativePhone) {
final orderAlt = alternativePhoneNumber?.trim() ?? '';
if (orderAlt.isNotEmpty) return orderAlt;
return customer?.alternativePhoneNumber.trim() ?? '';
}
return customer?.phoneNumber.trim() ?? '';
}
factory CustomerOrderModel.empty() => CustomerOrderModel(
orderDate: DateTime.now(),
companyId: '',
);
CustomerOrderModel copyWith({
String? id,
DateTime? createdAt,
DateTime? updatedAt,
DateTime? orderDate,
String? companyId,
String? storeId,
String? storeDisplayName,
String? createdById,
String? createdByName,
String? customerId,
CustomerModel? customer,
String? productDescription,
int? quantity,
String? notes,
double? price,
double? deposit,
String? externalCode,
CustomerOrderStatus? status,
List<String>? tags,
ContactPreference? contactPreference,
String? alternativePhoneNumber,
bool? customerNotified,
DateTime? customerNotifiedAt,
bool clearCustomerNotifiedAt = false,
List<AttachmentModel>? attachments,
}) {
return CustomerOrderModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
orderDate: orderDate ?? this.orderDate,
companyId: companyId ?? this.companyId,
storeId: storeId ?? this.storeId,
storeDisplayName: storeDisplayName ?? this.storeDisplayName,
createdById: createdById ?? this.createdById,
createdByName: createdByName ?? this.createdByName,
customerId: customerId ?? this.customerId,
customer: customer ?? this.customer,
productDescription: productDescription ?? this.productDescription,
quantity: quantity != null ? (quantity < 1 ? 1 : quantity) : this.quantity,
notes: notes ?? this.notes,
price: price ?? this.price,
deposit: deposit ?? this.deposit,
externalCode: externalCode ?? this.externalCode,
status: status ?? this.status,
tags: tags ?? this.tags,
contactPreference: contactPreference ?? this.contactPreference,
alternativePhoneNumber:
alternativePhoneNumber ?? this.alternativePhoneNumber,
customerNotified: customerNotified ?? this.customerNotified,
customerNotifiedAt: clearCustomerNotifiedAt
? null
: (customerNotifiedAt ?? this.customerNotifiedAt),
attachments: attachments ?? this.attachments,
);
}
factory CustomerOrderModel.fromMap(Map<String, dynamic> map) {
final rawQty = (map['quantity'] as num?)?.toInt() ?? 1;
final rawTags = (map['tags'] as List?)
?.map((e) => e.toString().trim())
.where((e) => e.isNotEmpty)
.toList() ??
const <String>[];
final createdAtLocal = map['created_at'] != null
? DateTime.parse(map['created_at'] as String).toLocal()
: null;
return CustomerOrderModel(
id: map['id'] as String?,
createdAt: createdAtLocal,
updatedAt: map['updated_at'] != null
? DateTime.parse(map['updated_at'] as String).toLocal()
: null,
orderDate: map['order_date'] != null
? DateTime.parse(map['order_date'] as String).toLocal()
: (createdAtLocal ?? DateTime.now()),
companyId: map['company_id'] as String? ?? '',
storeId: map['store_id'] as String?,
storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(),
createdById: map['created_by_id'] as String?,
createdByName: (map[Tables.staffMembers]?['name'] as String?)?.myFormat(),
customerId: map['customer_id'] as String?,
customer: map[Tables.customers] != null
? CustomerModel.fromMap(
map[Tables.customers] as Map<String, dynamic>,
)
: null,
productDescription: map['product_description'] as String? ?? '',
quantity: rawQty < 1 ? 1 : rawQty,
notes: map['notes'] as String? ?? '',
price: (map['price'] as num?)?.toDouble() ?? 0.0,
deposit: (map['deposit'] as num?)?.toDouble() ?? 0.0,
externalCode: map['external_code'] as String? ?? '',
status: CustomerOrderStatus.fromString(map['status'] as String?),
tags: rawTags,
contactPreference: ContactPreference.fromString(
map['contact_preference'] as String?,
),
alternativePhoneNumber: map['alternative_phone_number'] as String?,
customerNotified: map['customer_notified'] as bool? ?? false,
customerNotifiedAt: map['customer_notified_at'] != null
? DateTime.parse(map['customer_notified_at'] as String).toLocal()
: null,
attachments: (map[Tables.attachments] as List?)
?.map(
(x) => AttachmentModel.fromMap(x as Map<String, dynamic>),
)
.toList() ??
const [],
);
}
Map<String, dynamic> toMap() {
return {
if (id != null && id!.isNotEmpty) 'id': id,
'order_date': orderDate.toUtc().toIso8601String(),
'company_id': companyId,
'store_id': storeId,
if (createdById != null && createdById!.isNotEmpty)
'created_by_id': createdById,
'customer_id': customerId,
'product_description': productDescription.trim(),
'quantity': quantity < 1 ? 1 : quantity,
'notes': notes.trim(),
'price': price,
'deposit': deposit,
'external_code': externalCode.trim(),
'status': status.value,
'tags': tags.map((t) => t.trim()).where((t) => t.isNotEmpty).toList(),
'contact_preference': contactPreference.value,
'alternative_phone_number': alternativePhoneNumber?.trim(),
'customer_notified': customerNotified,
'customer_notified_at': customerNotifiedAt?.toUtc().toIso8601String(),
};
}
@override
List<Object?> get props => [
id,
createdAt,
updatedAt,
orderDate,
companyId,
storeId,
storeDisplayName,
createdById,
createdByName,
customerId,
customer,
productDescription,
quantity,
notes,
price,
deposit,
externalCode,
status,
tags,
contactPreference,
alternativePhoneNumber,
customerNotified,
customerNotifiedAt,
attachments,
];
}
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
/// Stato del ciclo di vita di un Ordine Cliente
enum CustomerOrderStatus {
toOrder(
value: 'to_order',
label: 'Da ordinare',
icon: Icons.shopping_cart_checkout_rounded,
color: Colors.deepOrange,
isActive: true,
),
ordered(
value: 'ordered',
label: 'Ordinato',
icon: Icons.local_shipping_outlined,
color: Colors.blue,
isActive: true,
),
arrived(
value: 'arrived',
label: 'Arrivato',
icon: Icons.inventory_2_rounded,
color: Colors.teal,
isActive: true,
),
delivered(
value: 'delivered',
label: 'Consegnato',
icon: Icons.check_circle_rounded,
color: Colors.green,
isActive: false,
),
cancelled(
value: 'cancelled',
label: 'Annullato',
icon: Icons.cancel_outlined,
color: Colors.grey,
isActive: false,
);
final String value;
final String label;
final IconData icon;
final Color color;
final bool isActive;
const CustomerOrderStatus({
required this.value,
required this.label,
required this.icon,
required this.color,
required this.isActive,
});
static CustomerOrderStatus fromString(String? val) {
if (val == null || val.trim().isEmpty) return CustomerOrderStatus.toOrder;
final clean = val.trim().toLowerCase();
for (final s in CustomerOrderStatus.values) {
if (s.value == clean || s.name.toLowerCase() == clean) {
return s;
}
}
return CustomerOrderStatus.toOrder;
}
}
/// Filtro rapido di stato nella lista Ordini Clienti
enum CustomerOrderQuickFilter {
active('Da ultimare'),
toOrder('Da ordinare'),
ordered('Ordinati'),
arrived('Arrivati'),
delivered('Consegnati'),
all('Tutti');
final String label;
const CustomerOrderQuickFilter(this.label);
List<String>? get dbStatuses {
switch (this) {
case CustomerOrderQuickFilter.active:
return [
CustomerOrderStatus.toOrder.value,
CustomerOrderStatus.ordered.value,
CustomerOrderStatus.arrived.value,
];
case CustomerOrderQuickFilter.toOrder:
return [CustomerOrderStatus.toOrder.value];
case CustomerOrderQuickFilter.ordered:
return [CustomerOrderStatus.ordered.value];
case CustomerOrderQuickFilter.arrived:
return [CustomerOrderStatus.arrived.value];
case CustomerOrderQuickFilter.delivered:
return [CustomerOrderStatus.delivered.value];
case CustomerOrderQuickFilter.all:
return null;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,770 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart';
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:printing/printing.dart';
class CustomerOrderListScreen extends StatefulWidget {
const CustomerOrderListScreen({super.key});
@override
State<CustomerOrderListScreen> createState() =>
_CustomerOrderListScreenState();
}
class _CustomerOrderListScreenState extends State<CustomerOrderListScreen> {
final TextEditingController _searchCtrl = TextEditingController();
@override
void initState() {
super.initState();
context.read<CustomerOrderListCubit>().init();
context.read<StoreCubit>().loadStores();
}
@override
void dispose() {
_searchCtrl.dispose();
super.dispose();
}
Future<void> _createNewOrder(BuildContext context) async {
final createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, order: null),
);
}
Future<void> _pickDateRange(
BuildContext context,
DateTimeRange? current,
) async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2023),
lastDate: DateTime.now().add(const Duration(days: 365)),
initialDateRange: current,
);
if (picked != null && context.mounted) {
context.read<CustomerOrderListCubit>().setDateRange(picked);
}
}
Future<void> _printLabel(BuildContext context, CustomerOrderModel order) async {
final service = CustomerOrderLabelPdfService();
await Printing.layoutPdf(
name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}',
onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final dateFmt = DateFormat('dd/MM/yyyy');
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
return BlocBuilder<CustomerOrderListCubit, CustomerOrderListState>(
builder: (context, state) {
return Scaffold(
backgroundColor: theme.colorScheme.surface,
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _createNewOrder(context),
icon: const Icon(Icons.add_shopping_cart_rounded),
label: const Text('Nuovo Ordine'),
),
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final isMobile = constraints.maxWidth < 650;
final hPad = isMobile ? 16.0 : 24.0;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// --- HEADER & FILTRI ---
Padding(
padding: EdgeInsets.fromLTRB(hPad, 16, hPad, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ordini Clienti',
style: (isMobile
? theme.textTheme.titleLarge
: theme.textTheme.headlineSmall)
?.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'Richieste prodotti, etichette acquisti e ritiri in cassa',
style: theme.textTheme.bodySmall
?.copyWith(
color: theme
.colorScheme
.onSurfaceVariant,
),
),
],
),
),
IconButton(
tooltip: 'Aggiorna lista',
onPressed: () => context
.read<CustomerOrderListCubit>()
.init(),
icon: const Icon(Icons.refresh_rounded),
),
],
),
const SizedBox(height: 12),
// Barra ricerca + Data + Negozio
Wrap(
spacing: 10,
runSpacing: 10,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
SizedBox(
width: isMobile ? double.infinity : 320,
child: TextField(
controller: _searchCtrl,
onChanged: (val) => context
.read<CustomerOrderListCubit>()
.setSearchTerm(val),
decoration: InputDecoration(
hintText:
'Cerca cliente, prodotto, codice cassa...',
prefixIcon: const Icon(
Icons.search,
size: 20,
),
isDense: true,
suffixIcon:
_searchCtrl.text.trim().isNotEmpty
? IconButton(
icon: const Icon(
Icons.clear,
size: 18,
),
onPressed: () {
_searchCtrl.clear();
context
.read<
CustomerOrderListCubit
>()
.setSearchTerm('');
},
)
: null,
),
),
),
// Filtro Date
OutlinedButton.icon(
icon: Icon(
Icons.date_range_outlined,
size: 18,
color: state.dateRange != null
? theme.colorScheme.primary
: null,
),
label: Text(
state.dateRange != null
? '${dateFmt.format(state.dateRange!.start)} - ${dateFmt.format(state.dateRange!.end)}'
: 'Filtra Date',
),
onPressed: () =>
_pickDateRange(context, state.dateRange),
),
if (state.dateRange != null)
IconButton(
tooltip: 'Rimuovi filtro date',
visualDensity: VisualDensity.compact,
onPressed: () => context
.read<CustomerOrderListCubit>()
.setDateRange(null),
icon: const Icon(Icons.close, size: 18),
),
// Filtro Negozio
BlocBuilder<StoreCubit, StoreState>(
builder: (context, storeState) {
if (storeState.stores.length <= 1) {
return const SizedBox.shrink();
}
return DropdownButtonHideUnderline(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
decoration: BoxDecoration(
border: Border.all(
color: theme.dividerColor.withValues(
alpha: 0.5,
),
),
borderRadius: BorderRadius.circular(8),
),
child: DropdownButton<String?>(
value: state.storeIdFilter,
hint: const Text('Tutti i negozi'),
isDense: true,
items: [
const DropdownMenuItem<String?>(
value: null,
child: Text('Tutti i negozi'),
),
...storeState.stores.map(
(s) => DropdownMenuItem<String?>(
value: s.id,
child: Text(s.name),
),
),
],
onChanged: (val) => context
.read<CustomerOrderListCubit>()
.setStoreFilter(val),
),
),
);
},
),
if (state.hasAdvancedFilters)
TextButton.icon(
onPressed: () {
_searchCtrl.clear();
context
.read<CustomerOrderListCubit>()
.resetFilters();
},
icon: const Icon(
Icons.filter_alt_off_outlined,
size: 18,
),
label: const Text('Azzera filtri'),
),
],
),
const SizedBox(height: 10),
// Quick Status Filters (Default: "Da ultimare")
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: CustomerOrderQuickFilter.values.map((
f,
) {
final selected = state.quickFilter == f;
return Padding(
padding: const EdgeInsets.only(right: 8),
child: ChoiceChip(
label: Text(f.label),
selected: selected,
onSelected: (_) => context
.read<CustomerOrderListCubit>()
.setQuickFilter(f),
),
);
}).toList(),
),
),
// Filtro Etichette (se presenti)
if (state.availableTags.isNotEmpty) ...[
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Icon(
Icons.label_outline_rounded,
size: 16,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(width: 6),
...state.availableTags.map((tag) {
final isSelected = state.selectedTags
.contains(tag);
return Padding(
padding: const EdgeInsets.only(right: 6),
child: FilterChip(
visualDensity: VisualDensity.compact,
label: Text(
tag,
style: const TextStyle(fontSize: 12),
),
selected: isSelected,
onSelected: (_) => context
.read<CustomerOrderListCubit>()
.toggleTagFilter(tag),
),
);
}),
],
),
),
],
],
),
),
const Divider(height: 1),
// --- CORPO LISTA ---
Expanded(
child: _buildListBody(
context,
theme,
state,
hPad: hPad,
dateFmt: dateFmt,
currencyFmt: currencyFmt,
),
),
],
);
},
),
),
);
},
);
}
Widget _buildListBody(
BuildContext context,
ThemeData theme,
CustomerOrderListState state, {
required double hPad,
required DateFormat dateFmt,
required NumberFormat currencyFmt,
}) {
if (state.status == CustomerOrderListStatus.loading &&
state.orders.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == CustomerOrderListStatus.failure) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Text(
'Errore nel caricamento ordini:\n${state.errorMessage}',
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error),
),
),
);
}
if (state.orders.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.inventory_2_outlined,
size: 56,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
),
const SizedBox(height: 12),
Text(
'Nessun ordine trovato per i filtri selezionati.',
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: 15,
),
),
],
),
);
}
return ListView.separated(
padding: EdgeInsets.fromLTRB(hPad, 14, hPad, 96),
itemCount: state.orders.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final order = state.orders[index];
return _buildOrderCard(
context,
theme,
order,
dateFmt: dateFmt,
currencyFmt: currencyFmt,
);
},
);
}
Widget _buildOrderCard(
BuildContext context,
ThemeData theme,
CustomerOrderModel order, {
required DateFormat dateFmt,
required NumberFormat currencyFmt,
}) {
final status = order.status;
final pref = order.contactPreference;
final needsCustomerAlert =
status == CustomerOrderStatus.arrived && !order.customerNotified;
return Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(
color: status == CustomerOrderStatus.arrived
? Colors.teal.withValues(alpha: 0.5)
: theme.dividerColor.withValues(alpha: 0.35),
width: status == CustomerOrderStatus.arrived ? 1.4 : 1,
),
),
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': order.id!},
extra: (createdBy: null, order: order),
),
child: Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Riga 1: Data + Negozio + Stato cliccabile + Stampa QR rapida
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.calendar_today_outlined,
size: 13,
color: context.secondaryText,
),
const SizedBox(width: 4),
Text(
dateFmt.format(order.orderDate),
style: TextStyle(
fontSize: 12,
color: context.secondaryText,
fontWeight: FontWeight.w600,
),
),
if (order.storeDisplayName != null &&
order.storeDisplayName!.isNotEmpty) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(
alpha: 0.08,
),
borderRadius: BorderRadius.circular(6),
),
child: Text(
order.storeDisplayName!,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary,
),
),
),
],
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (needsCustomerAlert)
Container(
margin: const EdgeInsets.only(right: 6),
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Colors.amber.shade600),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.notifications_active_outlined,
size: 13,
color: Colors.amber.shade900,
),
const SizedBox(width: 4),
Text(
'Da avvisare',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.amber.shade900,
),
),
],
),
)
else if (order.customerNotified)
Container(
margin: const EdgeInsets.only(right: 6),
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: const Text(
'Avvisato ✓',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
),
// Menu rapido cambio stato
PopupMenuButton<CustomerOrderStatus>(
tooltip: 'Cambia stato rapidamente',
onSelected: (newStatus) {
context
.read<CustomerOrderListCubit>()
.quickUpdateStatus(order, newStatus);
},
itemBuilder: (_) => CustomerOrderStatus.values
.map(
(s) => PopupMenuItem(
value: s,
child: Row(
children: [
Icon(s.icon, size: 18, color: s.color),
const SizedBox(width: 8),
Text(s.label),
],
),
),
)
.toList(),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 9,
vertical: 4,
),
decoration: BoxDecoration(
color: status.color.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: status.color.withValues(alpha: 0.45),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(status.icon, size: 14, color: status.color),
const SizedBox(width: 5),
Text(
status.label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: status.color,
),
),
const SizedBox(width: 2),
Icon(
Icons.arrow_drop_down,
size: 16,
color: status.color,
),
],
),
),
),
if (order.id != null) ...[
const SizedBox(width: 4),
IconButton(
tooltip: 'Stampa etichetta QR',
visualDensity: VisualDensity.compact,
onPressed: () => _printLabel(context, order),
icon: const Icon(Icons.qr_code_2_rounded, size: 20),
),
],
],
),
],
),
const SizedBox(height: 8),
// Riga 2: Prodotto + Quantità
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
order.quantity > 1
? '${order.productDescription} ×${order.quantity}'
: order.productDescription,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
),
),
),
if (order.price > 0) ...[
const SizedBox(width: 8),
Text(
currencyFmt.format(order.price),
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
color: theme.colorScheme.primary,
),
),
],
],
),
const SizedBox(height: 6),
// Riga 3: Cliente + Canale di avviso + Codice Cassa / Acconto
Wrap(
spacing: 12,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.person_outline, size: 15),
const SizedBox(width: 4),
Text(
order.customer?.name ?? 'Cliente sconosciuto',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
pref.buildIcon(size: 14),
const SizedBox(width: 4),
Text(
pref.shortLabel,
style: TextStyle(
fontSize: 12,
color: pref.color,
fontWeight: FontWeight.w600,
),
),
],
),
if (order.externalCode.isNotEmpty)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(5),
),
child: Text(
'Cod. Cassa: ${order.externalCode}',
style: const TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
),
),
),
if (order.deposit > 0)
Text(
'Acconto: ${currencyFmt.format(order.deposit)}',
style: TextStyle(
fontSize: 12,
color: Colors.teal.shade700,
fontWeight: FontWeight.w600,
),
),
],
),
// Riga 4: Etichette (se presenti)
if (order.tags.isNotEmpty) ...[
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 4,
children: order.tags
.map(
(tag) => Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.deepPurple.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.deepPurple.withValues(alpha: 0.3),
),
),
child: Text(
'#$tag',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: Colors.deepPurple,
),
),
),
)
.toList(),
),
],
],
),
),
),
);
}
}
@@ -0,0 +1,116 @@
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
class CustomerOrderLabelPdfService {
/// Genera il PDF dell'etichetta prodotto con QR code, leggendo le misure
/// configurate nelle Impostazioni Azienda (fallback 40 x 30 mm).
Future<pw.Document> generateOrderLabelPdf(CustomerOrderModel order) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
final company = GetIt.I.get<SessionCubit>().state.company;
final widthMm = company?.labelWidth ?? 40.0;
final heightMm = company?.labelHeight ?? 30.0;
final isVertical = company?.isLabelVertical ?? false;
final pageFormat = isVertical
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
: PdfPageFormat(widthMm * PdfPageFormat.mm, heightMm * PdfPageFormat.mm);
final effectiveW = pageFormat.width;
final effectiveH = pageFormat.height;
final minSide = effectiveW < effectiveH ? effectiveW : effectiveH;
final qrSize = (minSide - 6 * PdfPageFormat.mm).clamp(
14 * PdfPageFormat.mm,
26 * PdfPageFormat.mm,
);
final customerName = order.customer?.name ?? 'Cliente';
final qtySuffix = order.quantity > 1 ? ' (x${order.quantity})' : '';
final productLine = '${order.productDescription}$qtySuffix';
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final priceStr = order.price > 0 ? currencyFmt.format(order.price) : '';
final codeStr = order.externalCode.trim();
final qrData = order.deepLinkUrl.isNotEmpty
? order.deepLinkUrl
: (order.id ?? '');
pdf.addPage(
pw.Page(
pageFormat: pageFormat,
margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm),
build: (context) {
final infoBlock = pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
mainAxisAlignment: pw.MainAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text(
customerName,
style: pw.TextStyle(font: boldFont, fontSize: 8.5),
maxLines: 1,
overflow: pw.TextOverflow.clip,
),
pw.SizedBox(height: 1.5),
pw.Text(
productLine,
style: pw.TextStyle(font: font, fontSize: 7.2),
maxLines: 2,
overflow: pw.TextOverflow.clip,
),
if (codeStr.isNotEmpty || priceStr.isNotEmpty) ...[
pw.SizedBox(height: 2),
pw.Text(
[
if (codeStr.isNotEmpty) 'Cod: $codeStr',
if (priceStr.isNotEmpty) priceStr,
].join(' • '),
style: pw.TextStyle(font: boldFont, fontSize: 7.5),
maxLines: 1,
overflow: pw.TextOverflow.clip,
),
],
],
);
final qrWidget = pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(),
data: qrData,
width: qrSize,
height: qrSize,
);
if (effectiveH > effectiveW) {
return pw.Column(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
infoBlock,
pw.SizedBox(height: 2),
qrWidget,
],
);
}
return pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
pw.Expanded(child: infoBlock),
pw.SizedBox(width: 2 * PdfPageFormat.mm),
qrWidget,
],
);
},
),
);
return pdf;
}
}
@@ -65,6 +65,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
void updateFields({
String? name,
String? phoneNumber,
String? alternativePhoneNumber,
String? email,
String? note,
bool? doNotDisturb,
@@ -76,6 +77,8 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
customer: state.customer.copyWith(
name: name ?? state.customer.name,
phoneNumber: phoneNumber ?? state.customer.phoneNumber,
alternativePhoneNumber:
alternativePhoneNumber ?? state.customer.alternativePhoneNumber,
email: email ?? state.customer.email,
note: note ?? state.customer.note,
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
@@ -112,16 +115,19 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
Future<CustomerModel?> quickCreateCustomer({
required String name,
String? phone,
String? alternativePhone,
String? email,
String? note,
required bool isBusiness,
String? fiscalCode,
}) async {
final newCustomer = CustomerModel(
name: name,
phoneNumber: phone ?? '',
alternativePhoneNumber: alternativePhone ?? '',
email: email ?? '',
companyId: _sessionCubit.state.company!.id!,
note: '',
note: note ?? '',
isBusiness: isBusiness,
fiscalCode: fiscalCode?.trim().toUpperCase(),
);
@@ -7,6 +7,7 @@ class CustomerModel extends Equatable {
final DateTime? createdAt;
final String name;
final String phoneNumber;
final String alternativePhoneNumber;
final String email;
final String note;
final DateTime? lastContactDate;
@@ -22,6 +23,7 @@ class CustomerModel extends Equatable {
this.createdAt,
required this.name,
required this.phoneNumber,
this.alternativePhoneNumber = '',
required this.email,
required this.note,
this.lastContactDate,
@@ -39,6 +41,7 @@ class CustomerModel extends Equatable {
createdAt,
name,
phoneNumber,
alternativePhoneNumber,
email,
note,
lastContactDate,
@@ -50,13 +53,13 @@ class CustomerModel extends Equatable {
fiscalCode,
];
factory CustomerModel.empty() => CustomerModel(
factory CustomerModel.empty() => const CustomerModel(
name: '',
phoneNumber: '',
alternativePhoneNumber: '',
email: '',
note: '',
companyId:
'', // Dovrebbe essere sempre fornito, ma lasciamo vuoto per sicurezza
companyId: '',
);
CustomerModel copyWith({
@@ -64,6 +67,7 @@ class CustomerModel extends Equatable {
DateTime? createdAt,
String? name,
String? phoneNumber,
String? alternativePhoneNumber,
String? email,
String? note,
DateTime? lastContactDate,
@@ -79,6 +83,8 @@ class CustomerModel extends Equatable {
createdAt: createdAt ?? this.createdAt,
name: name ?? this.name,
phoneNumber: phoneNumber ?? this.phoneNumber,
alternativePhoneNumber:
alternativePhoneNumber ?? this.alternativePhoneNumber,
email: email ?? this.email,
note: note ?? this.note,
lastContactDate: lastContactDate ?? this.lastContactDate,
@@ -98,8 +104,9 @@ class CustomerModel extends Equatable {
? DateTime.parse(map['created_at'])
: null,
name: (map['name'] as String).myFormat(),
phoneNumber: map['phone_number'],
email: map['email'],
phoneNumber: map['phone_number'] as String? ?? '',
alternativePhoneNumber: map['alternative_phone_number'] as String? ?? '',
email: map['email'] as String? ?? '',
note: map['note'] ?? '',
lastContactDate: map['last_contact_date'] != null
? DateTime.parse(map['last_contact_date'])
@@ -117,11 +124,14 @@ class CustomerModel extends Equatable {
);
}
Map<String, dynamic> toMap() => toJson();
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
'name': name.toLowerCase().trim(),
'phone_number': phoneNumber,
'phone_number': phoneNumber.trim(),
'alternative_phone_number': alternativePhoneNumber.trim(),
'email': email.toLowerCase().trim(),
'note': note,
if (lastContactDate != null)
@@ -23,6 +23,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
// Controller inizializzati con i dati del cliente (se presenti)
final TextEditingController _nomeController = TextEditingController();
final TextEditingController _telefonoController = TextEditingController();
final TextEditingController _telefonoAltController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _noteController = TextEditingController();
final TextEditingController _fiscalCodeController = TextEditingController();
@@ -49,6 +50,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
void dispose() {
_nomeController.dispose();
_telefonoController.dispose();
_telefonoAltController.dispose();
_emailController.dispose();
_noteController.dispose();
_fiscalCodeController.dispose();
@@ -62,6 +64,9 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
if (_telefonoController.text.isEmpty) {
_telefonoController.text = customer.phoneNumber;
}
if (_telefonoAltController.text.isEmpty) {
_telefonoAltController.text = customer.alternativePhoneNumber;
}
if (_emailController.text.isEmpty) {
_emailController.text = customer.email;
}
@@ -78,6 +83,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
context.read<CustomerFormCubit>().updateFields(
name: _nomeController.text.trim(),
phoneNumber: _telefonoController.text.trim(),
alternativePhoneNumber: _telefonoAltController.text.trim(),
email: _emailController.text.trim(),
note: _noteController.text.trim(),
fiscalCode: _fiscalCodeController.text.trim(),
@@ -166,12 +172,19 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
),
const SizedBox(height: 16),
FluxTextField(
label: 'Telefono',
label: 'Telefono Principale',
icon: Icons.phone_android_outlined,
controller: _telefonoController,
keyboardType: TextInputType.phone,
),
const SizedBox(height: 16),
FluxTextField(
label: 'Recapito Alternativo',
icon: Icons.phone_forwarded_outlined,
controller: _telefonoAltController,
keyboardType: TextInputType.phone,
),
const SizedBox(height: 16),
FluxTextField(
label: 'Email',
icon: Icons.alternate_email_outlined,
@@ -15,6 +15,7 @@ class QuickCustomerDialog extends StatefulWidget {
class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
late final TextEditingController _nameCtrl;
final _phoneCtrl = TextEditingController();
final _altPhoneCtrl = TextEditingController();
final _emailCtrl = TextEditingController();
final _noteCtrl = TextEditingController();
bool _isBusiness = false;
@@ -33,6 +34,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
void dispose() {
_nameCtrl.dispose();
_phoneCtrl.dispose();
_altPhoneCtrl.dispose();
_emailCtrl.dispose();
_noteCtrl.dispose();
_fiscalCodeCtrl.dispose();
@@ -52,7 +54,9 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
isBusiness: _isBusiness,
name: _nameCtrl.text.trim(),
phone: _phoneCtrl.text.trim(),
alternativePhone: _altPhoneCtrl.text.trim(),
email: _emailCtrl.text.trim(),
note: _noteCtrl.text.trim(),
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
);
@@ -117,7 +121,18 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
const SizedBox(height: 8),
TextField(
controller: _phoneCtrl,
decoration: const InputDecoration(labelText: "Telefono"),
decoration: const InputDecoration(
labelText: "Telefono Principale",
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 8),
TextField(
controller: _altPhoneCtrl,
decoration: const InputDecoration(
labelText: "Recapito Alternativo (opzionale)",
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
),
@@ -28,59 +28,210 @@ class DashboardDailyRicontattiCard extends StatelessWidget {
builder: (context, state) {
final theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
child: Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.35),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: Colors.amber.shade700.withValues(alpha: 0.06),
blurRadius: 18,
offset: const Offset(0, 6),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(context, theme, state),
Divider(
height: 1,
color: theme.dividerColor.withValues(alpha: 0.15),
),
if (state.status == DashboardDailyRicontattiStatus.loading &&
state.summaries.isEmpty)
_buildLoading(theme)
else if (state.status == DashboardDailyRicontattiStatus.failure)
_buildError(context, theme, state)
else if (state.summaries.isEmpty)
_buildEmpty(theme)
else ...[
_buildOverviewStats(context, theme, state),
Padding(
padding: const EdgeInsets.fromLTRB(18, 0, 18, 18),
child: _buildStaffGrid(context, theme, state.summaries),
return LayoutBuilder(
builder: (context, outerConstraints) {
final isMobile = outerConstraints.maxWidth < 600;
final hPad = isMobile ? 16.0 : 24.0;
final vGap = isMobile ? 16.0 : 24.0;
return Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.35),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: Colors.amber.shade700.withValues(alpha: 0.06),
blurRadius: 18,
offset: const Offset(0, 6),
),
],
),
],
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(context, theme, state, isCompact: isMobile),
Divider(
height: 1,
color: theme.dividerColor.withValues(alpha: 0.15),
),
if (state.status == DashboardDailyRicontattiStatus.loading &&
state.summaries.isEmpty)
_buildLoading(theme)
else if (state.status ==
DashboardDailyRicontattiStatus.failure)
_buildError(context, theme, state)
else if (state.summaries.isEmpty)
_buildEmpty(theme)
else ...[
_buildOverviewStats(
context,
theme,
state,
isCompact: isMobile,
),
Padding(
padding: EdgeInsets.fromLTRB(
isMobile ? 14 : 18,
0,
isMobile ? 14 : 18,
isMobile ? 14 : 18,
),
child: _buildStaffGrid(context, theme, state.summaries),
),
],
],
),
),
);
},
);
},
);
}
Widget _buildTotalPillBadge(DashboardDailyRicontattiState state) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: Colors.amber.shade500.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.4),
),
);
},
);
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${state.totalRicontattiToday}',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Colors.amber.shade900,
),
),
const SizedBox(width: 5),
Text(
'oggi',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.amber.shade800,
),
),
const SizedBox(width: 6),
Text(
'(mese: ${state.totalRicontattiMonth})',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900.withValues(alpha: 0.85),
),
),
],
),
);
}
Widget _buildHeader(
BuildContext context,
ThemeData theme,
DashboardDailyRicontattiState state,
) {
DashboardDailyRicontattiState state, {
bool isCompact = false,
}) {
if (isCompact) {
return Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(9),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.amber.shade600,
Colors.orange.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.event_repeat_rounded,
color: Colors.white,
size: 20,
),
),
const SizedBox(width: 10),
Expanded(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 6,
runSpacing: 4,
children: [
Text(
'FOCUS RICONTATTI DI OGGI',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: 0.3,
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
),
child: Text(
'MANAGER',
style: TextStyle(
fontSize: 9.5,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900,
letterSpacing: 0.4,
),
),
),
],
),
),
IconButton(
tooltip: 'Aggiorna ora',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh_rounded, size: 20),
onPressed: () =>
context.read<DashboardDailyRicontattiCubit>().refresh(),
),
],
),
const SizedBox(height: 6),
Text(
'Raccolta situazioni da ricontattare & bollette',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
_buildTotalPillBadge(state),
],
),
);
}
return Padding(
padding: const EdgeInsets.all(18.0),
child: Row(
@@ -163,48 +314,7 @@ class DashboardDailyRicontattiCard extends StatelessWidget {
),
),
const SizedBox(width: 12),
// Total today & month pill badge
Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: Colors.amber.shade500.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.4),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${state.totalRicontattiToday}',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Colors.amber.shade900,
),
),
const SizedBox(width: 5),
Text(
'oggi',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.amber.shade800,
),
),
const SizedBox(width: 6),
Text(
'(mese: ${state.totalRicontattiMonth})',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900.withValues(alpha: 0.85),
),
),
],
),
),
_buildTotalPillBadge(state),
const SizedBox(width: 6),
IconButton(
tooltip: 'Aggiorna ora',
@@ -220,17 +330,19 @@ class DashboardDailyRicontattiCard extends StatelessWidget {
Widget _buildOverviewStats(
BuildContext context,
ThemeData theme,
DashboardDailyRicontattiState state,
) {
DashboardDailyRicontattiState state, {
bool isCompact = false,
}) {
final hasZeros = state.staffAtZero > 0;
final pad = isCompact ? 14.0 : 18.0;
return Padding(
padding: const EdgeInsets.fromLTRB(18, 14, 18, 14),
padding: EdgeInsets.fromLTRB(pad, 12, pad, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 12,
spacing: isCompact ? 8 : 12,
runSpacing: 8,
children: [
_buildStatChip(
@@ -367,7 +479,7 @@ class DashboardDailyRicontattiCard extends StatelessWidget {
crossAxisCount: crossAxisCount,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
mainAxisExtent: 104,
mainAxisExtent: crossAxisCount == 1 ? 86 : 104,
),
itemBuilder: (context, index) {
final summary = summaries[index];
@@ -126,17 +126,14 @@ class _ExpiringContractsCardContent extends StatelessWidget {
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Nome Cliente & note
Expanded(
flex: 5,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
Row(
children: [
Expanded(
child: Row(
children: [
Flexible(
child: Text(
@@ -150,7 +147,9 @@ class _ExpiringContractsCardContent extends StatelessWidget {
overflow: TextOverflow.ellipsis,
),
),
if (operation.attachments.isNotEmpty) ...[
if (operation
.attachments
.isNotEmpty) ...[
const SizedBox(width: 4),
Icon(
Icons.attach_file,
@@ -160,32 +159,29 @@ class _ExpiringContractsCardContent extends StatelessWidget {
],
],
),
if (phone != null && phone.isNotEmpty)
Text(
phone,
style: TextStyle(
color: context.secondaryText,
fontSize: 11,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(width: 8),
_buildExpiryBadge(context, earliestExp),
],
),
const SizedBox(height: 4),
Row(
children: [
if (phone != null && phone.isNotEmpty) ...[
Text(
phone,
style: TextStyle(
color: context.secondaryText,
fontSize: 11,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(width: 8),
],
),
Expanded(child: _buildBadges(operation)),
],
),
const SizedBox(width: 8),
// Badge Tipo / Subtipo
Expanded(
flex: 4,
child: _buildBadges(operation),
),
const SizedBox(width: 8),
// Data Scadenza Badge
_buildExpiryBadge(context, earliestExp),
],
),
),
@@ -207,8 +203,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();
@@ -235,8 +232,8 @@ class _ExpiringContractsCardContent extends StatelessWidget {
),
child: Text(
label,
style: const TextStyle(
color: Colors.amber,
style: TextStyle(
color: Colors.amber.shade800,
fontSize: 11,
fontWeight: FontWeight.bold,
),
@@ -1,14 +1,36 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
import 'package:flux/features/notes/data/notes_repository.dart';
import 'package:flux/features/notes/models/note_model.dart';
import 'package:go_router/go_router.dart'; // Supponendo tu usi GoRouter per la navigazione
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
class DashboardNoteListCard extends StatelessWidget {
const DashboardNoteListCard({super.key});
Future<void> _createNewNote(BuildContext context) async {
final sessionState = context.read<SessionCubit>().state;
final companyId = sessionState.company?.id;
final currentStaffId = sessionState.currentStaffMember?.id;
if (companyId == null || currentStaffId == null) return;
final emptyNote = NoteModel.empty(
createdBy: currentStaffId,
companyId: companyId,
);
final noteId = await GetIt.I.get<NotesRepository>().saveNote(emptyNote);
if (!context.mounted) return;
context.pushNamed(
Routes.noteForm,
pathParameters: {'id': noteId},
extra: emptyNote.copyWith(id: noteId),
);
}
@override
Widget build(BuildContext context) {
return Card(
@@ -44,55 +66,59 @@ class DashboardNoteListCard extends StatelessWidget {
),
),
const SizedBox(width: 12),
Text(
'Le mie Note',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
Expanded(
child: Text(
'Le mie Note',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
const SizedBox(height: 12),
// Il corpo del widget collegato al Bloc
BlocBuilder<DashboardNoteListCubit, DashboardNoteListState>(
builder: (context, state) {
if (state.status == DashboardNoteListStatus.loading &&
state.notes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
Expanded(
child: BlocBuilder<
DashboardNoteListCubit,
DashboardNoteListState
>(
builder: (context, state) {
if (state.status == DashboardNoteListStatus.loading &&
state.notes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == DashboardNoteListStatus.failure) {
return const Center(
child: Text(
'Errore nel caricamento delle note.',
style: TextStyle(color: Colors.red),
),
);
}
if (state.status == DashboardNoteListStatus.failure) {
return const Center(
child: Text(
'Errore nel caricamento delle note.',
style: TextStyle(color: Colors.red),
),
);
}
if (state.notes.isEmpty) {
return _buildEmptyState(context);
}
if (state.notes.isEmpty) {
return _buildEmptyState(context);
}
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
final displayNotes = state.notes.take(4).toList();
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
final displayNotes = state.notes.take(4).toList();
return SizedBox(
height: 140, // Altezza fissa per lo scroll orizzontale
child: ListView.builder(
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: displayNotes.length,
itemBuilder: (context, index) {
return _buildMiniPostIt(context, displayNotes[index]);
},
),
);
},
);
},
),
),
],
),
@@ -168,7 +194,7 @@ class DashboardNoteListCard extends StatelessWidget {
Widget _buildEmptyState(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.grey.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
@@ -178,16 +204,18 @@ class DashboardNoteListCard extends StatelessWidget {
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.sticky_note_2_outlined,
size: 32,
size: 28,
color: Colors.grey,
),
const SizedBox(height: 8),
const SizedBox(height: 6),
const Text('Nessuna nota presente.'),
TextButton(
onPressed: () => context.push('/notes/create'),
style: TextButton.styleFrom(visualDensity: VisualDensity.compact),
onPressed: () => _createNewNote(context),
child: const Text('Creane una ora'),
),
],
@@ -113,6 +113,17 @@ class _LatestOperationsCardContent extends StatelessWidget {
),
itemBuilder: (context, index) {
final operation = state.operations[index];
final types = operation.details
.map(
(d) =>
d.type?.shortLabel ?? d.type?.value ?? '',
)
.where((t) => t.trim().isNotEmpty)
.toList();
final dateStr = operation.createdAt != null
? "${operation.createdAt!.day.toString().padLeft(2, '0')}/${operation.createdAt!.month.toString().padLeft(2, '0')}"
: '';
return InkWell(
onTap: () => context.pushNamed(
Routes.operationForm,
@@ -123,45 +134,40 @@ class _LatestOperationsCardContent extends StatelessWidget {
padding: const EdgeInsets.symmetric(
vertical: 8.0,
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
flex: 5,
child: Text(
operation.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
Row(
children: [
Expanded(
child: Text(
operation.customer?.name ??
(operation.reference
.trim()
.isNotEmpty
? operation.reference
: 'Cliente sconosciuto'),
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
Expanded(
flex: 5,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
const SizedBox(width: 8),
Text(
dateStr,
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
),
),
child: _buildBadgeList(
operation.details
.map((d) => d.type)
.whereType<String>()
.where(
(t) => t.trim().isNotEmpty,
)
.toList(),
),
),
),
Text(
"${operation.createdAt?.day}/${operation.createdAt?.month}",
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
),
],
),
const SizedBox(height: 4),
_buildBadgeList(types),
],
),
),
@@ -114,6 +114,10 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget {
itemBuilder: (context, index) {
final ticket = state.tickets[index];
final statusColor = ticket.ticketStatus.color;
final dateStr = ticket.createdAt != null
? "${ticket.createdAt!.day.toString().padLeft(2, '0')}/${ticket.createdAt!.month.toString().padLeft(2, '0')}"
: '';
return InkWell(
onTap: () => context.pushNamed(
Routes.ticketForm,
@@ -125,47 +129,50 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget {
vertical: 8.0,
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
width: 8,
height:
30, // Un'altezza fissa per farlo comparire!
width: 6,
height: 34,
decoration: BoxDecoration(
color: statusColor,
borderRadius: BorderRadius.circular(
4,
), // Angoli smussati per stile
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(width: 4),
const SizedBox(width: 10),
Expanded(
flex: 5,
child: Text(
ticket.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
),
),
Expanded(
flex: 5,
child: Text(
ticket.targetModelName ??
'Modello sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w600,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
ticket.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 2),
Text(
ticket.targetModelName ??
'Modello sconosciuto',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: context.secondaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
const SizedBox(width: 8),
Text(
"${ticket.createdAt?.day}/${ticket.createdAt?.month}",
dateStr,
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
File diff suppressed because it is too large. Load diff
+182 -104
View File
@@ -118,103 +118,145 @@ class _HomeScreenState extends State<HomeScreen> {
return Scaffold(
backgroundColor: theme.colorScheme.surface,
body: SafeArea(
child: Column(
children: [
// ==========================================
// 1. HEADER FISSO (Non scrolla mai)
// ==========================================
Container(
padding: const EdgeInsets.all(24.0),
// Un leggero colore di sfondo aiuta a staccare l'header quando il contenuto ci passa sotto
color: theme.colorScheme.surface,
child: _buildHeader(context, theme),
),
child: LayoutBuilder(
builder: (context, constraints) {
final isMobile = constraints.maxWidth < 600;
final isSingleColGrid = constraints.maxWidth < 650;
final hPad = isMobile ? 16.0 : 24.0;
final vGap = isMobile ? 16.0 : 24.0;
// ==========================================
// 2. CORPO DELLA DASHBOARD (Scrollabile)
// ==========================================
Expanded(
child: BlocListener<SessionCubit, SessionState>(
listenWhen: (prev, curr) =>
prev.currentStore?.id != curr.currentStore?.id ||
prev.currentStaffMember?.id != curr.currentStaffMember?.id ||
prev.company?.id != curr.company?.id,
listener: (context, sessionState) {
context.read<DashboardTargetProgressCubit>().updateContext(
return Column(
children: [
// ==========================================
// 1. HEADER FISSO SU DESKTOP / TABLET LARGO
// ==========================================
if (!isMobile)
Container(
padding: const EdgeInsets.all(24.0),
color: theme.colorScheme.surface,
child: _buildHeader(context, theme, isMobile: false),
),
// ==========================================
// 2. CORPO DELLA DASHBOARD (Scrollabile)
// ==========================================
Expanded(
child: BlocListener<SessionCubit, SessionState>(
listenWhen: (prev, curr) =>
prev.currentStore?.id != curr.currentStore?.id ||
prev.currentStaffMember?.id !=
curr.currentStaffMember?.id ||
prev.company?.id != curr.company?.id,
listener: (context, sessionState) {
context.read<DashboardTargetProgressCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
newStaffId: sessionState.currentStaffMember?.id,
);
context.read<DashboardDailyRicontattiCubit>().updateContext(
context.read<DashboardDailyRicontattiCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
);
},
child: CustomScrollView(
slivers: [
// --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) ---
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
child: _buildQuickActions(context),
),
),
// --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) ---
const SliverToBoxAdapter(
child: DashboardDailyRicontattiCard(),
),
// --- 3. HERO TARGET DEL GIORNO ---
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
child: DashboardTargetHeroCard(),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 8)),
// --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) ---
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
sliver: SliverGrid(
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 500,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
childAspectRatio: 1.3,
},
child: CustomScrollView(
slivers: [
// Su mobile l'header scrolla col contenuto così non ruba mezzo schermo
if (isMobile)
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(
hPad,
8.0,
hPad,
14.0,
),
child: _buildHeader(
context,
theme,
isMobile: true,
),
),
delegate: SliverChildListDelegate([
DashboardStoreOperationListCard(),
DashboardStoreTicketListCard(),
DashboardExpiringContractsCard(),
DashboardNoteListCard(),
DashboardTaskListCard(),
]),
),
),
),
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
// --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) ---
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: _buildQuickActions(
context,
isMobile: isMobile,
),
),
),
// --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) ---
const SliverToBoxAdapter(
child: DashboardDailyRicontattiCard(),
),
// --- 3. HERO TARGET DEL GIORNO ---
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: const DashboardTargetHeroCard(),
),
),
SliverToBoxAdapter(
child: SizedBox(height: isMobile ? 4 : 8),
),
// --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) ---
SliverPadding(
padding: EdgeInsets.symmetric(horizontal: hPad),
sliver: SliverGrid(
gridDelegate: isSingleColGrid
? const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
mainAxisSpacing: 14,
mainAxisExtent: 268,
)
: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 500,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
mainAxisExtent: 290,
),
delegate: SliverChildListDelegate([
const DashboardStoreOperationListCard(),
const DashboardStoreTicketListCard(),
const DashboardExpiringContractsCard(),
const DashboardNoteListCard(),
const DashboardTaskListCard(),
]),
),
),
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
),
),
),
),
),
],
],
);
},
),
),
);
}
// ==========================================
Widget _buildHeader(BuildContext context, ThemeData theme) {
Widget _buildHeader(
BuildContext context,
ThemeData theme, {
required bool isMobile,
}) {
final user = context.watch<SessionCubit>().state.currentStaffMember;
final currentStore = context.watch<SessionCubit>().state.currentStore;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
@@ -222,31 +264,33 @@ class _HomeScreenState extends State<HomeScreen> {
children: [
Text(
context.l10n.homeWelcomeBack(user?.name ?? "Utente"),
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: -0.5,
color: context.primaryText, // Uso dell'estensione!
),
style:
(isMobile
? theme.textTheme.titleLarge
: theme.textTheme.headlineMedium)
?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: -0.5,
color: context.primaryText,
),
maxLines: isMobile ? 1 : 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
SizedBox(height: isMobile ? 6 : 8),
InkWell(
onTap: () => _showStoreSelector(context, theme),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
padding: EdgeInsets.symmetric(
horizontal: isMobile ? 10 : 12,
vertical: isMobile ? 5 : 6,
),
decoration: BoxDecoration(
color: context.primary.withValues(
alpha: 0.08,
), // Sfondo delicato
color: context.primary.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: context.primary.withValues(
alpha: 0.2,
), // Bordino netto
color: context.primary.withValues(alpha: 0.2),
),
),
child: Row(
@@ -254,15 +298,24 @@ class _HomeScreenState extends State<HomeScreen> {
children: [
Icon(Icons.storefront, size: 16, color: context.primary),
const SizedBox(width: 8),
Text(
currentStore?.name ?? context.l10n.homeNoStoreFound,
style: TextStyle(
fontWeight: FontWeight.w600,
color: context.primary,
Flexible(
child: Text(
currentStore?.name ?? context.l10n.homeNoStoreFound,
style: TextStyle(
fontSize: isMobile ? 13 : 14,
fontWeight: FontWeight.w600,
color: context.primary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
Icon(Icons.arrow_drop_down, color: context.primary),
Icon(
Icons.arrow_drop_down,
size: 20,
color: context.primary,
),
],
),
),
@@ -270,17 +323,22 @@ class _HomeScreenState extends State<HomeScreen> {
],
),
),
const SizedBox(width: 12),
CircleAvatar(
radius: 24,
// Usiamo il Turchese (accent) in trasparenza per l'avatar
radius: isMobile ? 20 : 24,
backgroundColor: context.accent.withValues(alpha: 0.15),
child: Icon(Icons.person, color: context.accent, size: 26),
child: Icon(
Icons.person,
color: context.accent,
size: isMobile ? 22 : 26,
),
),
],
);
}
Widget _buildQuickActions(BuildContext context) {
Widget _buildQuickActions(BuildContext context, {bool isMobile = false}) {
final gap = isMobile ? 8.0 : 12.0;
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
@@ -289,6 +347,7 @@ class _HomeScreenState extends State<HomeScreen> {
icon: Icons.add,
label: context.l10n.commonOperation,
color: Colors.blue,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
@@ -299,11 +358,12 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.handyman,
label: context.l10n.homeNewOperationTicket,
color: Colors.redAccent,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
@@ -314,11 +374,28 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.add_shopping_cart_rounded,
label: 'Ordine Cliente',
color: Colors.teal,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, order: null),
);
},
),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.note_add,
label: context.l10n.commonNote,
color: Colors.amber,
compact: isMobile,
onTap: () async {
final companyId = context.read<SessionCubit>().state.company!.id!;
final currentStaffId = context
@@ -341,11 +418,12 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.task_alt,
label: context.l10n.commonTask,
color: Colors.orange,
compact: isMobile,
onTap: () {
context.pushNamed(Routes.taskForm, pathParameters: {'id': 'new'});
},
+13 -4
View File
@@ -7,6 +7,7 @@ class QuickActionButton extends StatelessWidget {
final String label;
final Color color;
final VoidCallback onTap;
final bool compact;
const QuickActionButton({
super.key,
@@ -14,6 +15,7 @@ class QuickActionButton extends StatelessWidget {
required this.label,
required this.color,
required this.onTap,
this.compact = false,
});
@override
@@ -22,7 +24,10 @@ class QuickActionButton extends StatelessWidget {
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
padding: EdgeInsets.symmetric(
horizontal: compact ? 12 : 16,
vertical: compact ? 10 : 12,
),
decoration: BoxDecoration(
border: Border.all(color: color.withValues(alpha: 0.3)),
color: color.withValues(alpha: 0.05),
@@ -31,11 +36,15 @@ class QuickActionButton extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 20),
const SizedBox(width: 8),
Icon(icon, color: color, size: compact ? 18 : 20),
SizedBox(width: compact ? 6 : 8),
Text(
label,
style: TextStyle(fontWeight: FontWeight.bold, color: color),
style: TextStyle(
fontSize: compact ? 13 : 14,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
+91 -34
View File
@@ -21,10 +21,13 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
late TextEditingController _titleController;
late TextEditingController _contentController;
late final NotesCubit _notesCubit;
late final String _companyId;
late String _selectedColor;
late bool _isPinned;
late bool _isSharedAll;
late List<String> _selectedStaffIds;
bool _hasPendingChanges = false;
bool _isDeleted = false;
// Inizializziamo il Debouncer a 500 millisecondi
final _debouncer = Debouncer(milliseconds: 500);
@@ -44,6 +47,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
_titleController = TextEditingController(text: widget.note.title ?? '');
_contentController = TextEditingController(text: widget.note.content ?? '');
_notesCubit = context.read<NotesCubit>();
_companyId = widget.note.companyId.isNotEmpty
? widget.note.companyId
: context.read<SessionCubit>().state.company!.id!;
_selectedColor = widget.note.color;
_isPinned = widget.note.isPinned;
_isSharedAll = widget.note.isSharedAll;
@@ -58,29 +64,49 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
void dispose() {
_titleController.removeListener(_onFieldsChanged);
_contentController.removeListener(_onFieldsChanged);
_titleController.dispose();
_contentController.dispose();
_debouncer.dispose();
// --- IL BOTTO FINALE: PULIZIA SILENZIOSA ---
_checkAndCleanupIfEmpty(_note.id!);
// Se ci sono modifiche pendenti non ancora salvate dal debouncer, salviamole subito
if (!_isDeleted) {
_flushIfPending();
// --- IL BOTTO FINALE: PULIZIA SILENZIOSA ---
_checkAndCleanupIfEmpty(_note.id!);
}
_titleController.dispose();
_contentController.dispose();
super.dispose();
}
/// Chiamata ogni volta che l'utente digita una lettera
void _onFieldsChanged() {
_hasPendingChanges = true;
_debouncer.run(() => _triggerAutoSave());
}
void _flushIfPending() {
final isNoteEmpty =
_titleController.text.trim().isEmpty &&
_contentController.text.trim().isEmpty;
if (_hasPendingChanges && !isNoteEmpty) {
_triggerAutoSave();
}
}
void _closeNote() {
FocusScope.of(context).unfocus();
_flushIfPending();
Navigator.of(context).maybePop();
}
/// Salva in background notificando il BLoC (così la bacheca si aggiorna in tempo reale)
void _triggerAutoSave() {
final companyId = context.read<SessionCubit>().state.company!.id!;
_hasPendingChanges = false;
final updatedNote = NoteModel(
id: widget.note.id,
createdBy: widget.note.createdBy,
companyId: companyId,
companyId: _companyId,
title: _titleController.text.trim(),
content: _contentController.text.trim(),
color: _selectedColor,
@@ -98,9 +124,6 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
final titleEmpty = _titleController.text.trim().isEmpty;
final contentEmpty = _contentController.text.trim().isEmpty;
//Se hai un modo per verificare se ci sono allegati associati (es. tramite una query locale o un contatore),
// assicurati che non ce ne siano prima di eliminare.
// Assumiamo che se non ha scritto testo ed è appena stata creata, sia vuota.
if (titleEmpty && contentEmpty) {
// Notifichiamo anche il Bloc dell'avvenuta cancellazione così pulisce lo stato locale
_notesCubit.deleteNote(noteId);
@@ -108,6 +131,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
}
void _deleteNote() {
_isDeleted = true;
_hasPendingChanges = false;
_debouncer.dispose();
_notesCubit.deleteNote(widget.note.id!);
Navigator.pop(context);
}
@@ -223,28 +249,60 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: 'Chiudi nota',
onPressed: _closeNote,
),
flexibleSpace: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeNote,
),
// Freccia indietro chiara per fare contrasto sullo sfondo grigio scuro
iconTheme: const IconThemeData(color: Colors.white70),
),
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 64, left: 16, right: 16),
child: Container(
// 2. IL NOSTRO POST-IT FISICO
decoration: BoxDecoration(
color: noteColor,
borderRadius: BorderRadius.circular(16), // Bordi arrotondati
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.4), // Ombra morbida
blurRadius: 24,
offset: const Offset(0, 12),
),
],
),
padding: const EdgeInsets.all(24.0),
body: Stack(
children: [
// Area esterna cliccabile: toccando fuori dal Post-it la nota si chiude
Positioned.fill(
child: GestureDetector(
key: const ValueKey('note_outside_backdrop'),
behavior: HitTestBehavior.opaque,
onTap: _closeNote,
),
),
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: SingleChildScrollView(
padding: const EdgeInsets.only(
top: 8,
bottom: 48,
left: 16,
right: 16,
),
child: GestureDetector(
key: const ValueKey('note_postit_card'),
behavior: HitTestBehavior.opaque,
onTap: () {},
child: Container(
// 2. IL NOSTRO POST-IT FISICO
decoration: BoxDecoration(
color: noteColor,
borderRadius: BorderRadius.circular(
16,
), // Bordi arrotondati
boxShadow: [
BoxShadow(
color: Colors.black.withValues(
alpha: 0.4,
), // Ombra morbida
blurRadius: 24,
offset: const Offset(0, 12),
),
],
),
padding: const EdgeInsets.all(24.0),
child: Column(
// 3. MainAxisSize.min fa sì che il Post-it sia alto solo quanto serve!
mainAxisSize: MainAxisSize.min,
@@ -393,7 +451,7 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
height: 1.5,
),
maxLines: null,
minLines: 12,
minLines: MediaQuery.sizeOf(context).height < 750 ? 6 : 10,
decoration: const InputDecoration(
hintText: 'Scrivi qui la tua nota...',
hintStyle: TextStyle(color: Colors.black38),
@@ -478,10 +536,6 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
),
],
const SizedBox(height: 24),
const Divider(color: Colors.black12),
const SizedBox(height: 24),
// --- ALLEGATI ---
// SharedAttachmentsSection(
// parentType: AttachmentParentType.note,
@@ -493,6 +547,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
),
),
),
);
),
],
),
);
}
}
@@ -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,
);
@@ -1,6 +1,7 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:uuid/uuid.dart';
part 'operation_details_list_state.dart';
@@ -10,8 +11,12 @@ class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
void addOperationDetail(OperationDetailModel operationDetail) {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final detailToAdd =
(operationDetail.id != null && operationDetail.id!.isNotEmpty)
? operationDetail
: operationDetail.copyWith(id: const Uuid().v4());
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails.add(operationDetail);
updatedDetails.add(detailToAdd);
emit(
OperationDetailsListState(
details: updatedDetails,
@@ -94,4 +99,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,
),
);
}
}
@@ -1,4 +1,6 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
@@ -14,6 +16,12 @@ class OperationFormCubit extends Cubit<OperationFormState> {
final OperationsRepository _repository = sl<OperationsRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
Timer? _debounceTimer;
Timer? _periodicTimer;
static const Duration _debounceDuration = Duration(milliseconds: 1500);
static const Duration _periodicDuration = Duration(seconds: 60);
OperationFormCubit({
StaffMemberModel? createdBy,
OperationModel? existingOperation,
@@ -44,6 +52,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
} else if (operationId != null) {
emit(state.copyWith(status: OperationFormStatus.loading));
try {
@@ -56,6 +65,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
} on Exception catch (e) {
emit(
state.copyWith(
@@ -80,9 +90,10 @@ class OperationFormCubit extends Cubit<OperationFormState> {
),
status: OperationFormStatus.ready,
isNew: true,
hasUnsavedChanges: true,
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
}
} catch (e) {
emit(
@@ -94,11 +105,94 @@ class OperationFormCubit extends Cubit<OperationFormState> {
}
}
// --- SALVATAGGIO ---
// --- TIMER E AUTOSAVE ---
void _scheduleAutoSave() {
_debounceTimer?.cancel();
_debounceTimer = Timer(_debounceDuration, () {
autoSave();
});
}
void _startPeriodicTimer() {
_periodicTimer?.cancel();
_periodicTimer = Timer.periodic(_periodicDuration, (_) {
if (state.hasUnsavedChanges && !state.isAutoSaving) {
autoSave();
}
});
}
Future<void> autoSave() async {
_debounceTimer?.cancel();
if (state.operation.id == null ||
state.status != OperationFormStatus.ready ||
!state.hasUnsavedChanges ||
state.isAutoSaving) {
return;
}
emit(state.copyWith(isAutoSaving: true, autoSaveError: null));
try {
final snapshotBeforeSave = state.operation;
OperationModel operationToSave = snapshotBeforeSave;
if (operationToSave.reference.isEmpty) {
if (operationToSave.customer != null &&
operationToSave.customer!.phoneNumber.isNotEmpty) {
operationToSave = operationToSave.copyWith(
reference: '${operationToSave.customer?.phoneNumber} - auto',
);
}
}
final savedOperation = await _repository.updateOperation(operationToSave);
final savedTimestamp = savedOperation.updatedAt ?? DateTime.now();
final bool hasNewChanges = state.operation != snapshotBeforeSave;
emit(
state.copyWith(
isAutoSaving: false,
hasUnsavedChanges: hasNewChanges,
lastSavedAt: savedTimestamp,
autoSaveError: null,
operation: state.operation.copyWith(
createdAt: savedOperation.createdAt,
updatedAt: savedTimestamp,
details: savedOperation.details,
),
),
);
} catch (e) {
debugPrint('Errore durante autosave operazione: $e');
emit(
state.copyWith(
isAutoSaving: false,
autoSaveError: e.toString(),
),
);
}
}
Future<void> flushAutoSave() async {
_debounceTimer?.cancel();
if (state.hasUnsavedChanges && !state.isAutoSaving) {
await autoSave();
}
}
// --- SALVATAGGIO MANUALE DEFINITIVO ---
Future<void> saveOperation({required OperationStatus targetStatus}) async {
_debounceTimer?.cancel();
emit(
state.copyWith(status: OperationFormStatus.saving, errorMessage: null),
state.copyWith(
status: OperationFormStatus.saving,
isAutoSaving: false,
errorMessage: null,
),
);
try {
@@ -118,13 +212,14 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
}
}
await _repository.updateOperation(operationToSave);
final savedOperation = await _repository.updateOperation(operationToSave);
emit(
state.copyWith(
status: OperationFormStatus.success,
operation: operationToSave,
operation: savedOperation,
isNew: false,
hasUnsavedChanges: false,
lastSavedAt: savedOperation.updatedAt ?? DateTime.now(),
),
);
} catch (e) {
@@ -139,7 +234,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
// --- ANNULLA E ELIMINA SE NUOVA ---
Future<void> discardAndExit() async {
emit(state.copyWith(status: OperationFormStatus.saving));
_debounceTimer?.cancel();
_periodicTimer?.cancel();
emit(state.copyWith(status: OperationFormStatus.saving, isAutoSaving: false));
try {
if (state.isNew && state.operation.id != null) {
await _repository.deleteOperation(state.operation.id!);
@@ -165,7 +262,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
final id = state.operation.id;
if (id == null || id.isEmpty) return;
emit(state.copyWith(status: OperationFormStatus.saving));
_debounceTimer?.cancel();
_periodicTimer?.cancel();
emit(state.copyWith(status: OperationFormStatus.saving, isAutoSaving: false));
try {
await _repository.deleteOperation(id);
emit(
@@ -204,6 +303,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
_scheduleAutoSave();
}
void updateCustomer(CustomerModel customer) {
@@ -214,11 +314,20 @@ class OperationFormCubit extends Cubit<OperationFormState> {
isBusiness: isBusiness,
);
emit(state.copyWith(operation: updatedOperation, hasUnsavedChanges: true));
_scheduleAutoSave();
}
void updateOperationDetailsList(List<OperationDetailModel> details) {
final current = state.operation;
final updated = current.copyWith(details: details);
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
_scheduleAutoSave();
}
@override
Future<void> close() {
_debounceTimer?.cancel();
_periodicTimer?.cancel();
return super.close();
}
}
@@ -16,6 +16,9 @@ class OperationFormState extends Equatable {
final String? errorMessage;
final bool isNew;
final bool hasUnsavedChanges;
final bool isAutoSaving;
final DateTime? lastSavedAt;
final String? autoSaveError;
const OperationFormState({
this.status = OperationFormStatus.initial,
@@ -23,6 +26,9 @@ class OperationFormState extends Equatable {
this.errorMessage,
this.isNew = false,
this.hasUnsavedChanges = false,
this.isAutoSaving = false,
this.lastSavedAt,
this.autoSaveError,
});
OperationFormState copyWith({
@@ -31,6 +37,9 @@ class OperationFormState extends Equatable {
String? errorMessage,
bool? isNew,
bool? hasUnsavedChanges,
bool? isAutoSaving,
DateTime? lastSavedAt,
String? autoSaveError,
}) {
return OperationFormState(
status: status ?? this.status,
@@ -38,6 +47,9 @@ class OperationFormState extends Equatable {
errorMessage: errorMessage,
isNew: isNew ?? this.isNew,
hasUnsavedChanges: hasUnsavedChanges ?? this.hasUnsavedChanges,
isAutoSaving: isAutoSaving ?? this.isAutoSaving,
lastSavedAt: lastSavedAt ?? this.lastSavedAt,
autoSaveError: autoSaveError,
);
}
@@ -48,5 +60,8 @@ class OperationFormState extends Equatable {
errorMessage,
isNew,
hasUnsavedChanges,
isAutoSaving,
lastSavedAt,
autoSaveError,
];
}
@@ -5,7 +5,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:get_it/get_it.dart';
part 'operation_list_state.dart';
@@ -40,6 +42,11 @@ class OperationListCubit extends Cubit<OperationListState> {
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
detailType: state.detailType,
subType: state.subType,
categoryKey: state.categoryKey,
staffId: state.staffId,
storeId: state.storeId,
);
if (currentFetchId != _fetchId) return;
@@ -85,6 +92,11 @@ class OperationListCubit extends Cubit<OperationListState> {
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
detailType: state.detailType,
subType: state.subType,
categoryKey: state.categoryKey,
staffId: state.staffId,
storeId: state.storeId,
);
if (currentFetchId != _fetchId) return;
@@ -112,13 +124,74 @@ class OperationListCubit extends Cubit<OperationListState> {
}
}
void updateFilters({String? text, DateTimeRange? range}) {
/// Applica un set completo di parametri di filtro (es. proveniente da una card Obiettivo)
void applyFilterParams(OperationFilterParams params) {
emit(
state.copyWith(
// 🥷 FORZIAMO IL TIPO: Diciamo a Dart che il risultato del ternario è proprio una funzione
searchTerm: text != null ? () => text : null,
dateRange: range != null ? () => range : null,
searchTerm: () => params.searchTerm,
dateRange: () => params.dateRange,
detailType: () => params.detailType,
subType: () => params.subType,
categoryKey: () => params.categoryKey,
categoryLabel: () => params.categoryLabel,
staffId: () => params.staffId,
staffDisplayName: () => params.staffDisplayName,
storeId: () => params.storeId,
currentPage: 1,
hasReachedMax: false,
),
);
loadSpecificPageDesktop(1);
}
void updateFilters({
String? text,
DateTimeRange? range,
OperationType? detailType,
String? subType,
String? categoryKey,
String? categoryLabel,
String? staffId,
String? staffDisplayName,
String? storeId,
bool clearText = false,
bool clearRange = false,
bool clearDetailType = false,
bool clearSubType = false,
bool clearCategory = false,
bool clearStaff = false,
bool clearStore = false,
}) {
emit(
state.copyWith(
searchTerm: clearText
? () => null
: (text != null ? () => text : null),
dateRange: clearRange
? () => null
: (range != null ? () => range : null),
detailType: clearDetailType
? () => null
: (detailType != null ? () => detailType : null),
subType: clearSubType
? () => null
: (subType != null ? () => subType : null),
categoryKey: clearCategory
? () => null
: (categoryKey != null ? () => categoryKey : null),
categoryLabel: clearCategory
? () => null
: (categoryLabel != null ? () => categoryLabel : null),
staffId: clearStaff
? () => null
: (staffId != null ? () => staffId : null),
staffDisplayName: clearStaff
? () => null
: (staffDisplayName != null ? () => staffDisplayName : null),
storeId: clearStore
? () => null
: (storeId != null ? () => storeId : null),
currentPage: 1, // Reset obbligatorio alla prima pagina
hasReachedMax: false,
),
@@ -129,10 +202,7 @@ class OperationListCubit extends Cubit<OperationListState> {
}
void clearFilters() {
// Invece di un const vuoto che potrebbe bruciarti l'impostazione itemsPerPage,
// creiamo uno stato pulito ma manteniamo la preferenza di paginazione.
emit(OperationListState(itemsPerPage: state.itemsPerPage));
loadSpecificPageDesktop(1);
}
@@ -13,9 +13,16 @@ class OperationListState extends Equatable {
final int totalItems;
final bool hasReachedMax;
// 🥷 I FILTRI MANCANTI (Riparati!)
// Filtri Avanzati
final String? searchTerm;
final DateTimeRange? dateRange;
final OperationType? detailType;
final String? subType;
final String? categoryKey;
final String? categoryLabel;
final String? staffId;
final String? staffDisplayName;
final String? storeId;
const OperationListState({
this.status = OperationListStatus.initial,
@@ -27,11 +34,54 @@ class OperationListState extends Equatable {
this.hasReachedMax = false,
this.searchTerm,
this.dateRange,
this.detailType,
this.subType,
this.categoryKey,
this.categoryLabel,
this.staffId,
this.staffDisplayName,
this.storeId,
});
int get totalPages => (totalItems / itemsPerPage).ceil();
// 🥷 COPYWITH AVANZATO: Gestisce lo sbiancamento dei filtri alla perfezione
bool get hasActiveFilters =>
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
dateRange != null ||
detailType != null ||
(subType != null && subType!.trim().isNotEmpty) ||
categoryKey != null ||
staffId != null ||
storeId != null;
int get activeFiltersCount {
int count = 0;
if (searchTerm != null && searchTerm!.trim().isNotEmpty) count++;
if (dateRange != null) count++;
if (detailType != null) count++;
if (subType != null && subType!.trim().isNotEmpty && categoryKey == null) {
count++;
}
if (categoryKey != null) count++;
if (staffId != null) count++;
if (storeId != null) count++;
return count;
}
OperationFilterParams toFilterParams() {
return OperationFilterParams(
searchTerm: searchTerm,
dateRange: dateRange,
detailType: detailType,
subType: subType,
categoryKey: categoryKey,
categoryLabel: categoryLabel,
staffId: staffId,
staffDisplayName: staffDisplayName,
storeId: storeId,
);
}
OperationListState copyWith({
OperationListStatus? status,
List<OperationModel>? operations,
@@ -40,9 +90,15 @@ class OperationListState extends Equatable {
int? itemsPerPage,
int? totalItems,
bool? hasReachedMax,
String? Function()? searchTerm, // Callback per gestire il null esplicito
DateTimeRange? Function()?
dateRange, // Callback per gestire il null esplicito
String? Function()? searchTerm,
DateTimeRange? Function()? dateRange,
OperationType? Function()? detailType,
String? Function()? subType,
String? Function()? categoryKey,
String? Function()? categoryLabel,
String? Function()? staffId,
String? Function()? staffDisplayName,
String? Function()? storeId,
}) {
return OperationListState(
status: status ?? this.status,
@@ -52,10 +108,17 @@ class OperationListState extends Equatable {
itemsPerPage: itemsPerPage ?? this.itemsPerPage,
totalItems: totalItems ?? this.totalItems,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
// Se passi la funzione la eseguiamo, altrimenti teniamo il valore corrente
searchTerm: searchTerm != null ? searchTerm() : this.searchTerm,
dateRange: dateRange != null ? dateRange() : this.dateRange,
detailType: detailType != null ? detailType() : this.detailType,
subType: subType != null ? subType() : this.subType,
categoryKey: categoryKey != null ? categoryKey() : this.categoryKey,
categoryLabel:
categoryLabel != null ? categoryLabel() : this.categoryLabel,
staffId: staffId != null ? staffId() : this.staffId,
staffDisplayName:
staffDisplayName != null ? staffDisplayName() : this.staffDisplayName,
storeId: storeId != null ? storeId() : this.storeId,
);
}
@@ -70,5 +133,12 @@ class OperationListState extends Equatable {
hasReachedMax,
searchTerm,
dateRange,
detailType,
subType,
categoryKey,
categoryLabel,
staffId,
staffDisplayName,
storeId,
];
}
@@ -8,6 +8,7 @@ import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/operations/models/paginated_operations.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:uuid/uuid.dart';
class OperationsRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
@@ -54,6 +55,10 @@ class OperationsRepository {
String? storeId,
String? staffId,
String? providerId,
OperationType? detailType,
String? subType,
String? categoryKey,
bool? isBusiness,
required int page,
int itemsPerPage = 20,
String? searchTerm,
@@ -67,6 +72,12 @@ class OperationsRepository {
final from = (page - 1) * itemsPerPage;
final to = from + itemsPerPage - 1;
final hasDetailFilter = detailType != null ||
(subType != null && subType.trim().isNotEmpty) ||
(categoryKey != null && categoryKey != 'business');
final detailJoin = hasDetailFilter ? '!inner' : '';
var query = _supabase
.from(Tables.operations)
.select('''
@@ -75,7 +86,7 @@ class OperationsRepository {
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
${Tables.operationDetails}$detailJoin(
*,
${Tables.providers}(*),
${Tables.models}(*)
@@ -87,25 +98,63 @@ class OperationsRepository {
query = query.eq('show_in_dashboard', true);
}
// Se veniamo da una categoria target, escludiamo le operazioni annullate/scartate
if (categoryKey != null) {
query = query.neq('status', 'failure');
}
// Filtro Range Date
if (dateRange != null) {
final start = dateRange.start;
final end = (dateRange.end.hour == 0 && dateRange.end.minute == 0)
? DateTime(
dateRange.end.year,
dateRange.end.month,
dateRange.end.day,
23,
59,
59,
999,
)
: dateRange.end;
query = query
.gte('created_at', dateRange.start.toIso8601String())
.lte('created_at', dateRange.end.toIso8601String());
.gte('created_at', start.toIso8601String())
.lte('created_at', end.toIso8601String());
}
if (storeId != null) {
query = query.or('store_id.eq.$storeId,store_id.is.null');
if (storeId != null && storeId.isNotEmpty) {
if (categoryKey != null) {
query = query.eq('store_id', storeId);
} else {
query = query.or('store_id.eq.$storeId,store_id.is.null');
}
}
if (staffId != null) {
query = query.or('staff_id.eq.$staffId,staff_id.is.null');
if (staffId != null && staffId.isNotEmpty) {
query = query.eq('staff_id', staffId);
}
if (providerId != null) {
if (providerId != null && providerId.isNotEmpty) {
query = query.or('provider_id.eq.$providerId,provider_id.is.null');
}
// Filtro per Dettaglio Operazione / Categoria
if (categoryKey == 'business' || isBusiness == true) {
query = query.or(
'is_business.eq.true,${Tables.operationDetails}.type.eq.Business',
);
} else {
if (detailType != null) {
query = query.eq('${Tables.operationDetails}.type', detailType.value);
}
if (subType != null && subType.trim().isNotEmpty) {
query = query.ilike(
'${Tables.operationDetails}.sub_type',
'%${subType.trim()}%',
);
}
}
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
@@ -206,20 +255,46 @@ class OperationsRepository {
}
}
Future<void> updateOperation(OperationModel operation) async {
Future<OperationModel> updateOperation(OperationModel operation) async {
try {
await _supabase
final updatedRow = await _supabase
.from(Tables.operations)
.update(operation.toMap())
.eq('id', operation.id!);
.eq('id', operation.id!)
.select()
.maybeSingle();
final currentDetailIds =
operation.details
.map((d) => d.id)
.where((id) => id != null && id.isNotEmpty)
.cast<String>()
.toList();
final DateTime resolvedUpdatedAt = updatedRow?['updated_at'] != null
? DateTime.parse(updatedRow!['updated_at'] as String).toLocal()
: DateTime.now();
final DateTime? resolvedCreatedAt =
operation.createdAt ??
(updatedRow?['created_at'] != null
? DateTime.parse(updatedRow!['created_at'] as String).toLocal()
: null);
final updatedDetails = <OperationDetailModel>[];
for (OperationDetailModel detail in operation.details) {
final detailId = (detail.id != null && detail.id!.isNotEmpty)
? detail.id!
: const Uuid().v4();
final detailToSave = detail.copyWith(
id: detailId,
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
updatedDetails.add(detailToSave);
}
final currentDetailIds = updatedDetails.map((d) => d.id!).toList();
if (currentDetailIds.isNotEmpty) {
await _supabase
.from(Tables.operationDetails)
@@ -233,20 +308,12 @@ class OperationsRepository {
.eq('operation_id', operation.id!);
}
for (OperationDetailModel detail in operation.details) {
final detailToSave = detail.copyWith(
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
}
notifyOperationsChanged();
return operation.copyWith(
createdAt: resolvedCreatedAt,
updatedAt: resolvedUpdatedAt,
details: updatedDetails,
);
} catch (e) {
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
throw Exception('Errore nel salvataggio dell\'operazione: $e');
@@ -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,
};
}
}
@@ -0,0 +1,221 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/targets/models/target_model.dart';
/// Parametri per il filtraggio avanzato delle operazioni
class OperationFilterParams extends Equatable {
final String? searchTerm;
final DateTimeRange? dateRange;
final OperationType? detailType;
final String? subType;
final String? categoryKey;
final String? categoryLabel;
final String? staffId;
final String? staffDisplayName;
final String? storeId;
const OperationFilterParams({
this.searchTerm,
this.dateRange,
this.detailType,
this.subType,
this.categoryKey,
this.categoryLabel,
this.staffId,
this.staffDisplayName,
this.storeId,
});
factory OperationFilterParams.empty() => const OperationFilterParams();
bool get isEmpty =>
(searchTerm == null || searchTerm!.trim().isEmpty) &&
dateRange == null &&
detailType == null &&
(subType == null || subType!.trim().isEmpty) &&
categoryKey == null &&
staffId == null &&
storeId == null;
bool get isNotEmpty => !isEmpty;
/// Costruisce i filtri a partire da una categoria di target (es. clic da card obiettivo MNP, Calcio, ecc.)
factory OperationFilterParams.fromTargetCategory({
required String categoryKey,
required String categoryLabel,
required TargetModel target,
String? staffId,
String? staffDisplayName,
}) {
OperationType? detailType;
String? subType;
switch (categoryKey) {
case 'mnp':
detailType = OperationType.mnp;
break;
case 'unica':
detailType = OperationType.unica;
break;
case 'nip':
detailType = OperationType.nip;
break;
case 'al':
detailType = OperationType.al;
break;
case 'telepass':
detailType = OperationType.telepass;
break;
case 'fin':
detailType = OperationType.fin;
break;
case 'upselling':
detailType = OperationType.upselling;
break;
case 'cb':
detailType = OperationType.cb;
break;
case 'ricontatti':
detailType = OperationType.ricontatto;
break;
case 'calcio':
detailType = OperationType.entertainment;
subType = 'calcio';
break;
case 'contenuti':
detailType = OperationType.entertainment;
break;
case 'business':
detailType = OperationType.business;
break;
case 'energiaTim':
case 'energiaAltri':
detailType = OperationType.energy;
break;
}
return OperationFilterParams(
categoryKey: categoryKey,
categoryLabel: categoryLabel,
detailType: detailType,
subType: subType,
dateRange: DateTimeRange(
start: target.startDay,
end: target.endDay,
),
storeId: target.storeId,
staffId: staffId,
staffDisplayName: staffDisplayName,
);
}
/// Estrae i parametri dai queryParameters di GoRouter
factory OperationFilterParams.fromQueryParams(Map<String, String> query) {
if (query.isEmpty) return const OperationFilterParams();
DateTimeRange? range;
final startStr = query['startDate'];
final endStr = query['endDate'];
if (startStr != null && endStr != null) {
try {
final start = DateTime.parse(startStr);
final end = DateTime.parse(endStr);
range = DateTimeRange(start: start, end: end);
} catch (_) {}
}
final typeStr = query['type'] ?? query['detailType'];
final opType = OperationType.fromValue(typeStr);
return OperationFilterParams(
searchTerm: query['search'] ?? query['searchTerm'],
dateRange: range,
detailType: opType,
subType: query['subType'],
categoryKey: query['categoryKey'],
categoryLabel: query['categoryLabel'],
staffId: query['staffId'],
staffDisplayName: query['staffDisplayName'],
storeId: query['storeId'],
);
}
Map<String, String> toQueryParams() {
final map = <String, String>{};
if (searchTerm != null && searchTerm!.isNotEmpty) {
map['search'] = searchTerm!;
}
if (dateRange != null) {
map['startDate'] = dateRange!.start.toIso8601String();
map['endDate'] = dateRange!.end.toIso8601String();
}
if (detailType != null) {
map['type'] = detailType!.value;
}
if (subType != null && subType!.isNotEmpty) {
map['subType'] = subType!;
}
if (categoryKey != null) {
map['categoryKey'] = categoryKey!;
}
if (categoryLabel != null) {
map['categoryLabel'] = categoryLabel!;
}
if (staffId != null) {
map['staffId'] = staffId!;
}
if (staffDisplayName != null) {
map['staffDisplayName'] = staffDisplayName!;
}
if (storeId != null) {
map['storeId'] = storeId!;
}
return map;
}
OperationFilterParams copyWith({
String? searchTerm,
DateTimeRange? dateRange,
OperationType? detailType,
String? subType,
String? categoryKey,
String? categoryLabel,
String? staffId,
String? staffDisplayName,
String? storeId,
bool clearSearch = false,
bool clearRange = false,
bool clearDetailType = false,
bool clearSubType = false,
bool clearCategory = false,
bool clearStaff = false,
bool clearStore = false,
}) {
return OperationFilterParams(
searchTerm: clearSearch ? null : (searchTerm ?? this.searchTerm),
dateRange: clearRange ? null : (dateRange ?? this.dateRange),
detailType: clearDetailType ? null : (detailType ?? this.detailType),
subType: clearSubType ? null : (subType ?? this.subType),
categoryKey: clearCategory ? null : (categoryKey ?? this.categoryKey),
categoryLabel: clearCategory ? null : (categoryLabel ?? this.categoryLabel),
staffId: clearStaff ? null : (staffId ?? this.staffId),
staffDisplayName:
clearStaff ? null : (staffDisplayName ?? this.staffDisplayName),
storeId: clearStore ? null : (storeId ?? this.storeId),
);
}
@override
List<Object?> get props => [
searchTerm,
dateRange,
detailType,
subType,
categoryKey,
categoryLabel,
staffId,
staffDisplayName,
storeId,
];
}
@@ -28,6 +28,7 @@ enum OperationStatus {
class OperationModel extends Equatable {
final String? id;
final DateTime? createdAt;
final DateTime? updatedAt;
final String note;
final bool showInDashboard;
final String companyId;
@@ -50,6 +51,7 @@ class OperationModel extends Equatable {
const OperationModel({
this.id,
this.createdAt,
this.updatedAt,
this.note = '',
this.showInDashboard = true,
required this.companyId,
@@ -69,6 +71,7 @@ class OperationModel extends Equatable {
OperationModel copyWith({
String? id,
DateTime? createdAt,
DateTime? updatedAt,
String? note,
bool? showInDashboard,
String? companyId,
@@ -86,6 +89,7 @@ class OperationModel extends Equatable {
}) => OperationModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
note: note ?? this.note,
showInDashboard: showInDashboard ?? this.showInDashboard,
companyId: companyId ?? this.companyId,
@@ -106,6 +110,7 @@ class OperationModel extends Equatable {
List<Object?> get props => [
id,
createdAt,
updatedAt,
note,
showInDashboard,
companyId,
@@ -126,6 +131,7 @@ class OperationModel extends Equatable {
return OperationModel(
id: null,
createdAt: null,
updatedAt: null,
showInDashboard: false,
companyId: '',
details: const [],
@@ -136,7 +142,10 @@ class OperationModel extends Equatable {
return OperationModel(
id: map['id'] as String?,
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'])
? DateTime.parse(map['created_at'] as String).toLocal()
: null,
updatedAt: map['updated_at'] != null
? DateTime.parse(map['updated_at'] as String).toLocal()
: null,
note: map['note'] as String? ?? '',
showInDashboard: map['show_in_dashboard'] as bool? ?? true,
@@ -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;
@@ -8,6 +8,7 @@ import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/ui/widgets/financing_qr_dialog.dart';
import 'package:flux/features/operations/ui/widgets/operation_details_section.dart';
import 'package:intl/intl.dart';
class OperationFormScreen extends StatefulWidget {
final String? operationId;
@@ -21,7 +22,8 @@ class OperationFormScreen extends StatefulWidget {
enum _UnsavedChangesAction { cancel, saveAndClose, discard }
class _OperationFormScreenState extends State<OperationFormScreen> {
class _OperationFormScreenState extends State<OperationFormScreen>
with WidgetsBindingObserver {
final _formKey = GlobalKey<FormState>();
bool _isInitialized = false;
@@ -33,6 +35,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_referenceController.addListener(_onFieldChanged);
_notesController.addListener(_onFieldChanged);
@@ -51,6 +54,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_referenceController.removeListener(_onFieldChanged);
_notesController.removeListener(_onFieldChanged);
_referenceController.dispose();
@@ -58,6 +62,19 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused ||
state == AppLifecycleState.hidden ||
state == AppLifecycleState.detached) {
if (_isInitialized && mounted) {
_flushControllersToCubit();
context.read<OperationFormCubit>().flushAutoSave();
}
}
}
void _onFieldChanged() {
if (!_isInitialized) return;
_flushControllersToCubit();
@@ -191,6 +208,116 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
}
}
Widget _buildAutoSaveIndicator(OperationFormState formState) {
if (formState.isAutoSaving) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Salvataggio automatico in corso...',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(width: 6),
Text(
'Salvataggio...',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
fontStyle: FontStyle.italic,
),
),
],
),
),
);
}
if (formState.autoSaveError != null) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Errore salvataggio: ${formState.autoSaveError}',
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.cloud_off, size: 16, color: Colors.red),
SizedBox(width: 4),
Text(
'Errore salvataggio',
style: TextStyle(fontSize: 12, color: Colors.red),
),
],
),
),
);
}
if (formState.hasUnsavedChanges) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Modifiche non salvate (salvataggio a breve...)',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Text(
'In modifica...',
style: TextStyle(
fontSize: 12,
color: Colors.orange.shade800,
),
),
],
),
),
);
}
if (formState.lastSavedAt != null) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message:
'Ultimo salvataggio alle ${DateFormat('HH:mm:ss').format(formState.lastSavedAt!)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.cloud_done_rounded, size: 16, color: Colors.green),
const SizedBox(width: 4),
Text(
'Salvato ${DateFormat('HH:mm').format(formState.lastSavedAt!)}',
style: TextStyle(
fontSize: 12,
color: Colors.green.shade700,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
}
return const SizedBox.shrink();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -274,21 +401,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
overflow: TextOverflow.ellipsis,
),
actions: [
if (formState.hasUnsavedChanges)
Padding(
padding: const EdgeInsets.only(right: 4.0),
child: Tooltip(
message: 'Modifiche non salvate',
child: Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
),
),
_buildAutoSaveIndicator(formState),
IconButton(
icon: const Icon(Icons.save),
tooltip: formState.hasUnsavedChanges
@@ -296,18 +409,20 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
: 'Nessuna modifica da salvare',
onPressed:
formState.hasUnsavedChanges &&
formState.status != OperationFormStatus.saving
? () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: false,
)
: null,
formState.status != OperationFormStatus.saving &&
!formState.isAutoSaving
? () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: false,
)
: null,
),
IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
tooltip: 'Elimina pratica',
onPressed:
formState.status != OperationFormStatus.saving
formState.status != OperationFormStatus.saving &&
!formState.isAutoSaving
? () => _showDeleteConfirmationDialog(formContext)
: null,
),
@@ -542,13 +657,71 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
);
}
Widget _buildTimestampsBar(OperationFormState state) {
final createdAt = state.operation.createdAt;
final updatedAt =
state.lastSavedAt ?? state.operation.updatedAt ?? createdAt;
if (createdAt == null && updatedAt == null) {
return const SizedBox.shrink();
}
final dateTimeFormat = DateFormat('dd/MM/yyyy HH:mm');
final fullFormat = DateFormat('dd/MM/yyyy HH:mm:ss');
final mutedColor = Theme.of(
context,
).colorScheme.onSurfaceVariant.withValues(alpha: 0.8);
return Padding(
padding: const EdgeInsets.only(left: 4, right: 4, bottom: 12),
child: Wrap(
spacing: 20,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (createdAt != null)
Tooltip(
message: 'Creata il ${fullFormat.format(createdAt)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.schedule_rounded, size: 14, color: mutedColor),
const SizedBox(width: 5),
Text(
'Creata: ${dateTimeFormat.format(createdAt)}',
style: TextStyle(fontSize: 12, color: mutedColor),
),
],
),
),
if (updatedAt != null)
Tooltip(
message: 'Ultima modifica il ${fullFormat.format(updatedAt)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.history_rounded, size: 15, color: mutedColor),
const SizedBox(width: 5),
Text(
'Ultima modifica: ${dateTimeFormat.format(updatedAt)}',
style: TextStyle(fontSize: 12, color: mutedColor),
),
],
),
),
],
),
);
}
Widget _buildResponsiveLayout(
bool isUltraWide,
bool isDesktop,
OperationFormState state,
) {
final Widget cardsLayout;
if (isUltraWide) {
return Column(
cardsLayout = Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -564,7 +737,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
} else if (isDesktop) {
return Row(
cardsLayout = Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
@@ -579,7 +752,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
} else {
return Column(
cardsLayout = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_cardAnagrafica(state),
@@ -589,6 +762,14 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildTimestampsBar(state),
cardsLayout,
],
);
}
// --- LE CARD MODULARIZZATE E COLORATE ---
@@ -6,12 +6,16 @@ import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/operations/ui/widgets/operation_filter_sheet.dart';
import 'package:go_router/go_router.dart';
class OperationListScreen extends StatefulWidget {
const OperationListScreen({super.key});
final OperationFilterParams? initialFilters;
const OperationListScreen({super.key, this.initialFilters});
@override
State<OperationListScreen> createState() => _OperationListScreenState();
@@ -34,18 +38,43 @@ class _OperationListScreenState extends State<OperationListScreen> {
super.initState();
_scrollController.addListener(_onScroll);
// Primo caricamento: partiamo da pagina 1
// (Il Cubit deciderà se fare il boot iniziale o se c'era già roba in cache)
// Primo caricamento: partiamo da pagina 1 o applichiamo filtri iniziali
WidgetsBinding.instance.addPostFrameCallback((_) {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
if (isDesktop) {
context.read<OperationListCubit>().loadSpecificPageDesktop(1);
final cubit = context.read<OperationListCubit>();
if (widget.initialFilters != null && widget.initialFilters!.isNotEmpty) {
if (widget.initialFilters!.searchTerm != null &&
widget.initialFilters!.searchTerm!.isNotEmpty) {
_searchController.text = widget.initialFilters!.searchTerm!;
_showSearchBar = true;
}
cubit.applyFilterParams(widget.initialFilters!);
} else {
context.read<OperationListCubit>().loadNextPageMobile(refresh: true);
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
if (isDesktop) {
cubit.loadSpecificPageDesktop(1);
} else {
cubit.loadNextPageMobile(refresh: true);
}
}
});
}
@override
void didUpdateWidget(covariant OperationListScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialFilters != oldWidget.initialFilters &&
widget.initialFilters != null) {
if (widget.initialFilters!.searchTerm != null &&
widget.initialFilters!.searchTerm!.isNotEmpty) {
_searchController.text = widget.initialFilters!.searchTerm!;
_showSearchBar = true;
}
context
.read<OperationListCubit>()
.applyFilterParams(widget.initialFilters!);
}
}
void _onScroll() {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
// 🥷 COMPORTAMENTO IBRIDO: Lo scroll infinito si attiva SOLO su mobile
@@ -138,120 +167,72 @@ class _OperationListScreenState extends State<OperationListScreen> {
actions: [
IconButton(
icon: Icon(_showSearchBar ? Icons.close : Icons.search),
tooltip: _showSearchBar ? 'Chiudi ricerca' : 'Cerca',
onPressed: () {
setState(() {
_showSearchBar = !_showSearchBar;
if (!_showSearchBar) {
_debounce?.cancel();
_searchController.clear();
context.read<OperationListCubit>().clearFilters();
context.read<OperationListCubit>().updateFilters(
clearText: true,
);
}
});
},
),
if (!isDesktop) // Il pull-to-refresh c'è già su mobile, su desktop mettiamo un tasto manuale
IconButton(
icon: const Icon(Icons.filter_list),
onPressed: () {
// TODO: Bottone Filtri Avanzati (es. DateRange Picker)
},
),
BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
return IconButton(
icon: state.hasActiveFilters
? Badge(
label: Text('${state.activeFiltersCount}'),
child: const Icon(Icons.filter_list),
)
: const Icon(Icons.filter_list),
tooltip: 'Filtri avanzati',
onPressed: () => _openFilterModal(context, state),
);
},
),
BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
if (!state.hasActiveFilters) {
return const SizedBox.shrink();
}
return IconButton(
icon: const Icon(Icons.filter_alt_off),
tooltip: 'Azzera filtri',
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
);
},
),
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Ricarica',
onPressed: () {
context.read<OperationListCubit>().refreshCurrentPage();
},
),
],
),
// --- CORPO RESPONSIVO ---
body: BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
if (state.status == OperationListStatus.loading &&
state.operations.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
return Column(
children: [
// Barra orizzontale filtri attivi (se presenti)
_buildActiveFiltersBar(context, state),
if (state.operations.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Nessuna pratica trovata."),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () => isDesktop
? context
.read<OperationListCubit>()
.loadSpecificPageDesktop(1)
: context.read<OperationListCubit>().loadNextPageMobile(
refresh: true,
),
child: const Text("Ricarica"),
),
],
Expanded(
child: _buildBodyContent(context, state, isDesktop),
),
);
}
// 🥷 SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
if (isDesktop) {
return Column(
children: [
Expanded(
child: GridView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
420, // Larghezza bilanciata per le card su desktop
mainAxisExtent:
185, // Altezza controllata per evitare buchi bianchi
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: state.operations.length,
itemBuilder: (context, index) {
final operation = state.operations[index];
return _buildResponsiveCard(operation);
},
),
),
_buildDesktopPaginationFooter(
state,
), // La barra in fondo stile Gmail
],
);
}
// 🥷 SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
return RefreshIndicator(
onRefresh: () => context
.read<OperationListCubit>()
.loadNextPageMobile(refresh: true),
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.only(
bottom: 80,
left: 8,
right: 8,
top: 8,
),
itemCount: state.hasReachedMax
? state.operations.length
: state.operations.length + 1,
itemBuilder: (context, index) {
if (index >= state.operations.length) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
final operation = state.operations[index];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: _buildResponsiveCard(operation),
);
},
),
],
);
},
),
@@ -273,6 +254,289 @@ class _OperationListScreenState extends State<OperationListScreen> {
);
}
void _openFilterModal(BuildContext context, OperationListState state) {
OperationFilterSheet.show(
context,
currentFilters: state.toFilterParams(),
onApply: (newParams) {
context.read<OperationListCubit>().applyFilterParams(newParams);
},
onReset: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
);
}
Widget _buildActiveFiltersBar(
BuildContext context,
OperationListState state,
) {
if (!state.hasActiveFilters) return const SizedBox.shrink();
final theme = Theme.of(context);
final cubit = context.read<OperationListCubit>();
return Container(
width: double.infinity,
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.25),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: ActionChip(
visualDensity: VisualDensity.compact,
avatar: const Icon(
Icons.filter_alt_off,
size: 14,
color: Colors.redAccent,
),
label: const Text(
'Azzera tutto',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.redAccent,
),
),
backgroundColor: Colors.redAccent.withValues(alpha: 0.08),
side: BorderSide(
color: Colors.redAccent.withValues(alpha: 0.3),
),
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
cubit.clearFilters();
},
),
),
if (state.categoryLabel != null || state.detailType != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: Icon(
state.detailType?.icon ?? Icons.category,
size: 14,
color: state.detailType?.color ?? theme.colorScheme.primary,
),
label: Text(
state.categoryLabel != null
? 'Obiettivo: ${state.categoryLabel}'
: (state.subType != null && state.subType!.isNotEmpty
? '${state.detailType!.shortLabel} (${state.subType})'
: state.detailType!.shortLabel),
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(
clearDetailType: true,
clearSubType: true,
clearCategory: true,
),
),
),
],
if (state.staffDisplayName != null || state.staffId != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.person, size: 14),
label: Text(
'Addetto: ${state.staffDisplayName ?? 'Selezionato'}',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(clearStaff: true),
),
),
],
if (state.dateRange != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.date_range, size: 14),
label: Text(
'${_formatDate(state.dateRange!.start)} - ${_formatDate(state.dateRange!.end)}',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(clearRange: true),
),
),
],
if (state.searchTerm != null &&
state.searchTerm!.trim().isNotEmpty) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.search, size: 14),
label: Text(
'"${state.searchTerm}"',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () {
_searchController.clear();
cubit.updateFilters(clearText: true);
},
),
),
],
],
),
),
);
}
Widget _buildBodyContent(
BuildContext context,
OperationListState state,
bool isDesktop,
) {
if (state.status == OperationListStatus.loading &&
state.operations.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.operations.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
state.hasActiveFilters
? Icons.filter_list_off
: Icons.inbox_outlined,
size: 48,
color: Colors.grey.shade400,
),
const SizedBox(height: 12),
Text(
state.hasActiveFilters
? 'Nessuna operazione trovata con i filtri attuali.'
: 'Nessuna pratica trovata.',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
if (state.hasActiveFilters)
ElevatedButton.icon(
icon: const Icon(Icons.filter_alt_off, size: 18),
label: const Text('Azzera filtri'),
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
)
else
ElevatedButton(
onPressed: () => isDesktop
? context
.read<OperationListCubit>()
.loadSpecificPageDesktop(1)
: context.read<OperationListCubit>().loadNextPageMobile(
refresh: true,
),
child: const Text('Ricarica'),
),
],
),
),
);
}
// SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
if (isDesktop) {
return Column(
children: [
Expanded(
child: GridView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 420,
mainAxisExtent: 185,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: state.operations.length,
itemBuilder: (context, index) {
final operation = state.operations[index];
return _buildResponsiveCard(operation);
},
),
),
_buildDesktopPaginationFooter(state),
],
);
}
// SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
return RefreshIndicator(
onRefresh: () => context
.read<OperationListCubit>()
.loadNextPageMobile(refresh: true),
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.only(
bottom: 80,
left: 8,
right: 8,
top: 8,
),
itemCount: state.hasReachedMax
? state.operations.length
: state.operations.length + 1,
itemBuilder: (context, index) {
if (index >= state.operations.length) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
final operation = state.operations[index];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: _buildResponsiveCard(operation),
);
},
),
);
}
String _formatDate(DateTime dt) {
return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
}
// --- COSTRUZIONE DELLA COMPONENTISTICA DETTAGLIATA ---
Widget _buildResponsiveCard(OperationModel operation) {
@@ -427,9 +691,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,
),
),
),
],
),
);
}
}
@@ -0,0 +1,649 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_type.dart';
/// BottomSheet per impostare i filtri avanzati della lista operazioni
class OperationFilterSheet extends StatefulWidget {
final OperationFilterParams currentFilters;
final ValueChanged<OperationFilterParams> onApply;
final VoidCallback onReset;
const OperationFilterSheet({
super.key,
required this.currentFilters,
required this.onApply,
required this.onReset,
});
static Future<void> show(
BuildContext context, {
required OperationFilterParams currentFilters,
required ValueChanged<OperationFilterParams> onApply,
required VoidCallback onReset,
}) {
return showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => OperationFilterSheet(
currentFilters: currentFilters,
onApply: onApply,
onReset: onReset,
),
);
}
@override
State<OperationFilterSheet> createState() => _OperationFilterSheetState();
}
class _OperationFilterSheetState extends State<OperationFilterSheet> {
OperationType? _selectedType;
late TextEditingController _subTypeController;
StaffMemberModel? _selectedStaff;
DateTimeRange? _selectedDateRange;
@override
void initState() {
super.initState();
_selectedType = widget.currentFilters.detailType;
_subTypeController = TextEditingController(
text: widget.currentFilters.subType ?? '',
);
_selectedDateRange = widget.currentFilters.dateRange;
// Inizializza l'addetto se presente
if (widget.currentFilters.staffId != null) {
final staffState = context.read<StaffCubit>().state;
final staffList = staffState.storeStaff.isNotEmpty
? staffState.storeStaff
: staffState.allStaff;
for (final s in staffList) {
if (s.id == widget.currentFilters.staffId) {
_selectedStaff = s;
break;
}
}
}
}
@override
void dispose() {
_subTypeController.dispose();
super.dispose();
}
void _setDatePreset(String preset) {
final now = DateTime.now();
switch (preset) {
case 'today':
final start = DateTime(now.year, now.month, now.day, 0, 0, 0);
final end = DateTime(now.year, now.month, now.day, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'last7':
final start = DateTime(now.year, now.month, now.day - 6, 0, 0, 0);
final end = DateTime(now.year, now.month, now.day, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'thisMonth':
final start = DateTime(now.year, now.month, 1, 0, 0, 0);
final end = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'lastMonth':
final start = DateTime(now.year, now.month - 1, 1, 0, 0, 0);
final end = DateTime(now.year, now.month, 0, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'all':
setState(() => _selectedDateRange = null);
break;
}
}
Future<void> _pickCustomDateRange() async {
final now = DateTime.now();
final picked = await showDateRangePicker(
context: context,
initialDateRange: _selectedDateRange ??
DateTimeRange(
start: DateTime(now.year, now.month, 1),
end: DateTime(now.year, now.month, now.day),
),
firstDate: DateTime(2020),
lastDate: DateTime(now.year + 5),
);
if (picked != null) {
setState(() {
_selectedDateRange = DateTimeRange(
start: DateTime(
picked.start.year,
picked.start.month,
picked.start.day,
0,
0,
0,
),
end: DateTime(
picked.end.year,
picked.end.month,
picked.end.day,
23,
59,
59,
),
);
});
}
}
void _apply() {
final subText = _subTypeController.text.trim();
final params = widget.currentFilters.copyWith(
detailType: _selectedType,
subType: subText.isNotEmpty ? subText : null,
staffId: _selectedStaff?.id,
staffDisplayName: _selectedStaff?.name,
dateRange: _selectedDateRange,
clearDetailType: _selectedType == null,
clearSubType: subText.isEmpty,
clearStaff: _selectedStaff == null,
clearRange: _selectedDateRange == null,
// Se l'utente ha modificato manualmente tipo o sottotipo, svuotiamo categoryKey specifica
clearCategory: _selectedType != widget.currentFilters.detailType,
);
widget.onApply(params);
Navigator.of(context).pop();
}
void _reset() {
widget.onReset();
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final mediaQuery = MediaQuery.of(context);
return DraggableScrollableSheet(
initialChildSize: 0.85,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (_, scrollController) {
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
),
child: Column(
children: [
// Maniglia top
Center(
child: Container(
width: 40,
height: 4,
margin: const EdgeInsets.only(top: 12, bottom: 8),
decoration: BoxDecoration(
color: theme.dividerColor,
borderRadius: BorderRadius.circular(2),
),
),
),
// Header
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
Icons.tune,
color: theme.colorScheme.primary,
size: 22,
),
const SizedBox(width: 8),
Text(
'Filtri Avanzati',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
TextButton.icon(
onPressed: _reset,
icon: const Icon(Icons.filter_alt_off, size: 18),
label: const Text('Azzera tutto'),
style: TextButton.styleFrom(
foregroundColor: Colors.redAccent,
),
),
],
),
),
const Divider(height: 1),
// Corpo con i filtri
Expanded(
child: ListView(
controller: scrollController,
padding: const EdgeInsets.all(20),
children: [
// 1. TIPO SERVIZIO / DETTAGLIO
_buildSectionTitle(
theme,
title: 'Tipo di Servizio / Dettaglio',
icon: Icons.category_outlined,
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti'),
selected: _selectedType == null,
onSelected: (selected) {
if (selected) {
setState(() {
_selectedType = null;
_subTypeController.clear();
});
}
},
),
...OperationType.values.map((type) {
final isSelected = _selectedType == type;
return ChoiceChip(
avatar: Icon(
type.icon,
size: 16,
color: isSelected ? Colors.white : type.color,
),
label: Text(type.shortLabel),
selected: isSelected,
selectedColor: type.color,
labelStyle: TextStyle(
color: isSelected ? Colors.white : null,
fontWeight:
isSelected ? FontWeight.bold : FontWeight.normal,
),
onSelected: (selected) {
setState(() {
_selectedType = selected ? type : null;
if (!selected) _subTypeController.clear();
});
},
);
}),
],
),
const SizedBox(height: 24),
// 2. SOTTOTIPO / SPECIFICA (se applicabile)
if (_selectedType != null) ...[
_buildSectionTitle(
theme,
title: 'Sottotipo / Offerta specifica',
icon: Icons.subdirectory_arrow_right,
),
const SizedBox(height: 10),
if (_selectedType == OperationType.entertainment) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti i contenuti'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...EntertainmentSubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
avatar: sub == EntertainmentSubtypes.calcio
? const Icon(Icons.sports_soccer, size: 15)
: (sub == EntertainmentSubtypes.cinemaTv
? const Icon(Icons.movie_outlined, size: 15)
: null),
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
] else if (_selectedType == OperationType.energy) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutte le forniture'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...EnergySubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
] else if (_selectedType == OperationType.ricontatto) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti i ricontatti'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...RicontattoSubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
],
TextField(
controller: _subTypeController,
decoration: InputDecoration(
labelText: 'Filtro testuale sottotipo (opzionale)',
hintText: 'Es. DAZN, TIMVISION, Luce...',
prefixIcon: const Icon(Icons.search, size: 18),
suffixIcon: _subTypeController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear, size: 18),
onPressed: () => setState(
() => _subTypeController.clear(),
),
)
: null,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 24),
],
// 3. COLLABORATORE / ADDETTO
_buildSectionTitle(
theme,
title: 'Collaboratore / Addetto',
icon: Icons.person_outline,
),
const SizedBox(height: 10),
BlocBuilder<StaffCubit, StaffState>(
builder: (context, staffState) {
final rawList = staffState.storeStaff.isNotEmpty
? staffState.storeStaff
: staffState.allStaff;
final activeStaff =
rawList.where((s) => s.isActive).toList();
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti gli addetti'),
selected: _selectedStaff == null,
onSelected: (sel) {
if (sel) setState(() => _selectedStaff = null);
},
),
...activeStaff.map((staff) {
final isSel = _selectedStaff?.id == staff.id;
return ChoiceChip(
avatar: CircleAvatar(
radius: 10,
backgroundColor: isSel
? Colors.white
: theme.colorScheme.primary.withValues(
alpha: 0.2,
),
child: Text(
staff.name.isNotEmpty
? staff.name[0].toUpperCase()
: '?',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: isSel
? theme.colorScheme.primary
: theme.colorScheme.primary,
),
),
),
label: Text(staff.name),
selected: isSel,
onSelected: (sel) {
setState(() {
_selectedStaff = sel ? staff : null;
});
},
);
}),
],
);
},
),
const SizedBox(height: 24),
// 4. RANGE DATE / PERIODO
_buildSectionTitle(
theme,
title: 'Periodo / Data Creazione',
icon: Icons.calendar_month_outlined,
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ActionChip(
avatar: const Icon(Icons.all_inclusive, size: 16),
label: const Text('Sempre'),
backgroundColor: _selectedDateRange == null
? theme.colorScheme.primaryContainer
: null,
onPressed: () => _setDatePreset('all'),
),
ActionChip(
label: const Text('Oggi'),
onPressed: () => _setDatePreset('today'),
),
ActionChip(
label: const Text('Ultimi 7 gg'),
onPressed: () => _setDatePreset('last7'),
),
ActionChip(
label: const Text('Questo mese'),
onPressed: () => _setDatePreset('thisMonth'),
),
ActionChip(
label: const Text('Mese scorso'),
onPressed: () => _setDatePreset('lastMonth'),
),
ActionChip(
avatar: const Icon(Icons.date_range, size: 16),
label: const Text('Personalizzato...'),
onPressed: _pickCustomDateRange,
),
],
),
if (_selectedDateRange != null) ...[
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 10,
),
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer
.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: theme.colorScheme.primary.withValues(
alpha: 0.3,
),
),
),
child: Row(
children: [
Icon(
Icons.check_circle_outline,
size: 18,
color: theme.colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Dal ${_formatDate(_selectedDateRange!.start)} al ${_formatDate(_selectedDateRange!.end)}',
style: TextStyle(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
fontSize: 13,
),
),
),
IconButton(
icon: const Icon(Icons.close, size: 18),
onPressed: () =>
setState(() => _selectedDateRange = null),
tooltip: 'Rimuovi filtro data',
),
],
),
),
],
],
),
),
// Footer con bottoni di conferma
Container(
padding: EdgeInsets.fromLTRB(
20,
12,
20,
12 + mediaQuery.viewPadding.bottom,
),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
border: Border(
top: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
),
),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Annulla'),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: ElevatedButton.icon(
icon: const Icon(Icons.done),
label: const Text('Applica Filtri'),
onPressed: _apply,
),
),
],
),
),
],
),
);
},
);
}
Widget _buildSectionTitle(
ThemeData theme, {
required String title,
required IconData icon,
}) {
return Row(
children: [
Icon(icon, size: 18, color: theme.colorScheme.primary),
const SizedBox(width: 6),
Text(
title,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
),
],
);
}
String _formatDate(DateTime dt) {
return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
}
}
@@ -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 [];
}
}
+243 -137
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/targets/blocs/target_detail_cubit.dart';
import 'package:flux/features/targets/blocs/target_detail_state.dart';
import 'package:flux/features/targets/models/target_model.dart';
@@ -453,6 +454,25 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
);
}
void _navigateToOperationsForCategory(
CategoryProgress cat, {
String? staffId,
String? staffName,
}) {
final params = OperationFilterParams.fromTargetCategory(
categoryKey: cat.key,
categoryLabel: cat.label,
target: widget.target,
staffId: staffId,
staffDisplayName: staffName,
);
context.pushNamed(
Routes.operations,
extra: params,
);
}
Widget _buildCategoryCard(
ThemeData theme,
CategoryProgress cat,
@@ -492,98 +512,142 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Container(
// Bordo laterale sinistro spesso 6px: VERDE, VERDINO, ROSA, ROSSO!
decoration: BoxDecoration(
border: Border(
left: BorderSide(
color: hasTargets ? pacingTheme.primary : Colors.grey.shade400,
width: 6,
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () => _navigateToOperationsForCategory(cat),
child: Container(
// Bordo laterale sinistro spesso 6px: VERDE, VERDINO, ROSA, ROSSO!
decoration: BoxDecoration(
border: Border(
left: BorderSide(
color: hasTargets ? pacingTheme.primary : Colors.grey.shade400,
width: 6,
),
),
),
),
),
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Intestazione: Categoria + Status Badge Cromatico + Volume ENORME
Row(
crossAxisAlignment: CrossAxisAlignment.center,
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 10,
runSpacing: 6,
children: [
Text(
cat.label,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
// Intestazione: Categoria + Status Badge Cromatico + Volume ENORME
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 10,
runSpacing: 6,
children: [
Text(
cat.label,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: pacingTheme.background,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: pacingTheme.border, width: 1.2),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(pacingTheme.icon, size: 14, color: pacingTheme.text),
const SizedBox(width: 5),
Text(
statusLabel,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: pacingTheme.text,
),
),
],
),
),
],
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: pacingTheme.background,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: pacingTheme.border, width: 1.2),
),
child: Row(
),
// Realizzato vs S1 / S2: GRANDE e BEN VISIBILE + Tasto Apri
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Icon(pacingTheme.icon, size: 14, color: pacingTheme.text),
const SizedBox(width: 5),
Text(
statusLabel,
'${cat.actualPieces}',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: pacingTheme.text,
fontSize: 24,
fontWeight: FontWeight.w900,
color: isDoneS1 ? const Color(0xFF15803D) : theme.colorScheme.onSurface,
),
),
Text(
' / ${cat.targetS1}',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
),
if (cat.targetS2 > 0) ...[
const SizedBox(width: 6),
Text(
'(Sfida: ${cat.targetS2})',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: isDoneS2 ? const Color(0xFF15803D) : Colors.purple.shade700,
),
),
],
],
),
),
],
),
),
// Realizzato vs S1 / S2: GRANDE e BEN VISIBILE
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'${cat.actualPieces}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w900,
color: isDoneS1 ? const Color(0xFF15803D) : theme.colorScheme.onSurface,
),
),
Text(
' / ${cat.targetS1}',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
),
if (cat.targetS2 > 0) ...[
const SizedBox(width: 6),
Text(
'(Sfida: ${cat.targetS2})',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: isDoneS2 ? const Color(0xFF15803D) : Colors.purple.shade700,
const SizedBox(width: 10),
Tooltip(
message: 'Vedi operazioni (${cat.actualPieces})',
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 6,
),
decoration: BoxDecoration(
color: pacingTheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: pacingTheme.primary.withValues(alpha: 0.3),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.list_alt,
size: 15,
color: pacingTheme.primary,
),
const SizedBox(width: 4),
Icon(
Icons.arrow_forward_ios,
size: 11,
color: pacingTheme.primary,
),
],
),
),
),
),
],
],
),
],
),
],
),
const SizedBox(height: 12),
// Barra di avanzamento
@@ -689,7 +753,9 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
),
),
),
);
),
),
);
}
// ==========================================
@@ -969,7 +1035,12 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
),
const SizedBox(height: 10),
...sp.categories.values.where((c) => c.targetS1 > 0 || c.targetS2 > 0).map((c) {
return _buildStaffCategoryRow(theme, c);
return _buildStaffCategoryRow(
theme,
c,
staffId: it.staffId,
staffName: staffName,
);
}),
],
),
@@ -988,14 +1059,18 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
);
}
Widget _buildStaffCategoryRow(ThemeData theme, CategoryProgress c) {
Widget _buildStaffCategoryRow(
ThemeData theme,
CategoryProgress c, {
String? staffId,
String? staffName,
}) {
final isDoneS1 = c.actualPieces >= c.targetS1;
final isDoneS2 = c.targetS2 > 0 && c.actualPieces >= c.targetS2;
final pacingTheme = PacingTheme.of(c.status);
return Container(
margin: const EdgeInsets.only(bottom: 8.0),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(10),
@@ -1003,67 +1078,98 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
left: BorderSide(color: pacingTheme.primary, width: 4),
),
),
child: Row(
children: [
Expanded(
flex: 3,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: () => _navigateToOperationsForCategory(
c,
staffId: staffId,
staffName: staffName,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
children: [
Text(
c.label,
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold),
),
Text(
pacingTheme.label,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: pacingTheme.primary,
Expanded(
flex: 3,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
c.label,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
Text(
pacingTheme.label,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: pacingTheme.primary,
),
),
],
),
),
Expanded(
flex: 2,
child: Text(
'${c.actualPieces} / ${c.targetS1}${c.targetS2 > 0 ? ' (S2: ${c.targetS2})' : ''}',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
flex: 2,
child: Text(
'Med: ${c.actualDailyRate.toStringAsFixed(1)}/gg',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
flex: 2,
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: pacingTheme.background,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: pacingTheme.border),
),
child: Text(
isDoneS2
? 'S2 OK 🚀'
: (isDoneS1
? 'S1 OK 🎉'
: 'Req: ${c.requiredDailyRateS1.toStringAsFixed(1)}/gg'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: pacingTheme.text,
),
),
),
),
const SizedBox(width: 6),
Icon(
Icons.arrow_forward_ios,
size: 12,
color: Colors.grey.shade500,
),
],
),
),
Expanded(
flex: 2,
child: Text(
'${c.actualPieces} / ${c.targetS1}${c.targetS2 > 0 ? ' (S2: ${c.targetS2})' : ''}',
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 2,
child: Text(
'Med: ${c.actualDailyRate.toStringAsFixed(1)}/gg',
style: TextStyle(fontSize: 12, color: theme.colorScheme.primary, fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 2,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: pacingTheme.background,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: pacingTheme.border),
),
child: Text(
isDoneS2
? 'S2 OK 🚀'
: (isDoneS1
? 'S1 OK 🎉'
: 'Req: ${c.requiredDailyRateS1.toStringAsFixed(1)}/gg'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: pacingTheme.text,
),
),
),
),
],
),
),
);
}
@@ -1,5 +1,7 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customers/data/customer_repository.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
@@ -11,6 +13,8 @@ import 'ticket_form_state.dart';
class TicketFormCubit extends Cubit<TicketFormState> {
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
final CustomerRepository _customerRepository =
GetIt.I.get<CustomerRepository>();
final SessionCubit _sessionCubit = GetIt.I.get<SessionCubit>();
// Costruttore: prepariamo subito il ticket base con i dati di chi lo crea
@@ -73,13 +77,18 @@ class TicketFormCubit extends Cubit<TicketFormState> {
/// 2. AGGIORNAMENTO CLIENTE (Usato dal nostro SharedCustomerSection!)
void updateCustomer(CustomerModel customer) {
final existingAlt = state.ticket.alternativePhoneNumber?.trim() ?? '';
final resolvedAlt = existingAlt.isNotEmpty
? existingAlt
: (customer.alternativePhoneNumber.trim().isNotEmpty
? customer.alternativePhoneNumber.trim()
: null);
emit(
state.copyWith(
ticket: state.ticket.copyWith(
customerId: customer.id,
customer: customer,
alternativePhoneNumber:
state.ticket.alternativePhoneNumber ?? customer.phoneNumber,
alternativePhoneNumber: resolvedAlt,
),
),
);
@@ -129,6 +138,7 @@ class TicketFormCubit extends Cubit<TicketFormState> {
String? sourceSn,
String? sourcePassword,
String? alternativePhoneNumber,
ContactPreference? contactPreference,
bool? hasCourtesyDevice,
String? includedAccessories,
String? publicNotes,
@@ -153,6 +163,8 @@ class TicketFormCubit extends Cubit<TicketFormState> {
sourceSn: sourceSn ?? state.ticket.sourceSn,
alternativePhoneNumber:
alternativePhoneNumber ?? state.ticket.alternativePhoneNumber,
contactPreference:
contactPreference ?? state.ticket.contactPreference,
hasCourtesyDevice:
hasCourtesyDevice ?? state.ticket.hasCourtesyDevice,
includedAccessories:
@@ -188,6 +200,7 @@ class TicketFormCubit extends Cubit<TicketFormState> {
} else {
savedTicket = await _repository.updateTicket(ticketToSave);
}
await _syncCustomerAlternativePhone(ticketToSave);
emit(
state.copyWith(
status: TicketFormStatus.success,
@@ -368,6 +381,20 @@ class TicketFormCubit extends Cubit<TicketFormState> {
}
}
Future<void> _syncCustomerAlternativePhone(TicketModel ticket) async {
final customer = ticket.customer;
final newAlt = ticket.alternativePhoneNumber?.trim() ?? '';
if (customer == null || customer.id == null || newAlt.isEmpty) return;
if (customer.alternativePhoneNumber.trim() == newAlt) return;
try {
await _customerRepository.updateCustomer(
customer.copyWith(alternativePhoneNumber: newAlt),
);
} catch (_) {
// Non blocchiamo il salvataggio del ticket se l'aggiornamento anagrafica fallisce
}
}
Future<void> deleteTicket() async {
final currentTicket = state.ticket;
@@ -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) {
@@ -1,4 +1,5 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/tickets/models/shipping_document_model.dart';
@@ -106,6 +107,7 @@ class TicketModel extends Equatable {
final String? internalNotes;
final String? referenceId;
final String? alternativePhoneNumber;
final ContactPreference contactPreference;
final bool hasCourtesyDevice;
final TicketType ticketType;
final TicketStatus ticketStatus;
@@ -145,6 +147,7 @@ class TicketModel extends Equatable {
this.internalNotes,
this.referenceId,
this.alternativePhoneNumber,
this.contactPreference = ContactPreference.whatsappPrimary,
this.hasCourtesyDevice = false,
required this.ticketType,
this.ticketStatus = TicketStatus.closed,
@@ -199,6 +202,7 @@ class TicketModel extends Equatable {
String? internalNotes,
String? referenceId,
String? alternativePhoneNumber,
ContactPreference? contactPreference,
bool? hasCourtesyDevice,
TicketType? ticketType,
TicketStatus? ticketStatus,
@@ -240,6 +244,7 @@ class TicketModel extends Equatable {
referenceId: referenceId ?? this.referenceId,
alternativePhoneNumber:
alternativePhoneNumber ?? this.alternativePhoneNumber,
contactPreference: contactPreference ?? this.contactPreference,
hasCourtesyDevice: hasCourtesyDevice ?? this.hasCourtesyDevice,
ticketType: ticketType ?? this.ticketType,
ticketStatus: ticketStatus ?? this.ticketStatus,
@@ -292,6 +297,9 @@ class TicketModel extends Equatable {
internalNotes: map['internal_notes'] as String?,
referenceId: map['reference_id'] as String?,
alternativePhoneNumber: map['alternative_phone_number'] as String?,
contactPreference: ContactPreference.fromString(
map['contact_preference'] as String?,
),
hasCourtesyDevice: map['has_courtesy_device'] as bool? ?? false,
ticketType: TicketType.fromString(map['ticket_type'] as String),
ticketStatus: TicketStatus.fromString(map['ticket_status'] as String),
@@ -347,6 +355,7 @@ class TicketModel extends Equatable {
'internal_notes': internalNotes,
'reference_id': referenceId,
'alternative_phone_number': alternativePhoneNumber,
'contact_preference': contactPreference.value,
'has_courtesy_device': hasCourtesyDevice,
'ticket_type': ticketType.value,
'ticket_status': ticketStatus.value,
@@ -381,6 +390,7 @@ class TicketModel extends Equatable {
publicNotes,
internalNotes,
alternativePhoneNumber,
contactPreference,
hasCourtesyDevice,
ticketType,
ticketStatus,
@@ -5,6 +5,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/widgets/shared_forms/attachments_section.dart';
import 'package:flux/core/widgets/shared_forms/contact_preference_section.dart';
import 'package:flux/core/widgets/shared_forms/customer_section.dart';
import 'package:flux/core/widgets/shared_forms/model_section.dart';
import 'package:flux/core/widgets/staff_selector_modal.dart';
@@ -679,16 +680,25 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
const Divider(height: 32), */
SharedCustomerSection(
customer: ticket.customer,
onCustomerSelected: (customer) =>
context.read<TicketFormCubit>().updateCustomer(customer),
onCustomerSelected: (customer) {
if (_altPhoneCtrl.text.trim().isEmpty &&
customer.alternativePhoneNumber.trim().isNotEmpty) {
_altPhoneCtrl.text = customer.alternativePhoneNumber.trim();
}
context.read<TicketFormCubit>().updateCustomer(customer);
},
),
const SizedBox(height: 16),
TextFormField(
controller: _altPhoneCtrl,
decoration: const InputDecoration(
labelText: 'Recapito Alternativo',
prefixIcon: Icon(Icons.phone),
),
ContactPreferenceSection(
selectedPreference: ticket.contactPreference,
customer: ticket.customer,
alternativePhoneController: _altPhoneCtrl,
alwaysShowAlternativePhone: true,
onPreferenceChanged: (pref) {
context.read<TicketFormCubit>().updateFields(
contactPreference: pref,
);
},
),
],
);
+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,
);
}
},
),
);
+6
View File
@@ -5,6 +5,8 @@ import 'package:flux/core/theme/bloc/theme_bloc.dart';
import 'package:flux/features/attachments/data/attachments_repository.dart';
import 'package:flux/features/auth/bloc/auth_cubit.dart';
import 'package:flux/features/company/data/company_repository.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
import 'package:flux/features/customers/data/customer_repository.dart';
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
@@ -60,6 +62,9 @@ Future<void> init() async {
sl.registerLazySingleton<CoreRepository>(() => CoreRepository());
sl.registerLazySingleton<StoreRepository>(() => StoreRepository());
sl.registerLazySingleton<CustomerRepository>(() => CustomerRepository());
sl.registerLazySingleton<CustomerOrdersRepository>(
() => CustomerOrdersRepository(),
);
sl.registerLazySingleton<ProductRepository>(() => ProductRepository());
sl.registerLazySingleton<StaffRepository>(() => StaffRepository());
sl.registerLazySingleton<OperationsRepository>(() => OperationsRepository());
@@ -103,4 +108,5 @@ Future<void> init() async {
sl.registerFactory<TrackingCubit>(() => TrackingCubit());
sl.registerFactory<NotesCubit>(() => NotesCubit());
sl.registerFactory<TargetListCubit>(() => TargetListCubit());
sl.registerFactory<CustomerOrderListCubit>(() => CustomerOrderListCubit());
}
+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.7.0+95
environment:
sdk: ^3.11.3
@@ -0,0 +1,92 @@
-- =========================================================================
-- MIGRAZIONE ORDINI CLIENTI, RECAPITO ALTERNATIVO & MODALITÀ AVVISO
-- =========================================================================
-- 1. Aggiunta recapito alternativo ai Clienti
ALTER TABLE public.customers
ADD COLUMN IF NOT EXISTS alternative_phone_number text DEFAULT '';
-- 2. Aggiunta modalità di avviso preferita ai Ticket di Assistenza
ALTER TABLE public.tickets
ADD COLUMN IF NOT EXISTS contact_preference text DEFAULT 'whatsapp_primary';
-- 3. Creazione tabella Ordini Clienti (customer_orders)
CREATE TABLE IF NOT EXISTS public.customer_orders (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
order_date timestamptz NOT NULL DEFAULT now(),
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
store_id uuid REFERENCES public.stores(id) ON DELETE SET NULL,
created_by_id uuid REFERENCES public.staff_members(id) ON DELETE SET NULL,
customer_id uuid REFERENCES public.customers(id) ON DELETE SET NULL,
product_description text NOT NULL DEFAULT '',
quantity integer NOT NULL DEFAULT 1,
notes text NOT NULL DEFAULT '',
price numeric(10, 2) NOT NULL DEFAULT 0,
deposit numeric(10, 2) NOT NULL DEFAULT 0,
external_code text NOT NULL DEFAULT '',
status text NOT NULL DEFAULT 'to_order',
tags text[] NOT NULL DEFAULT '{}',
contact_preference text NOT NULL DEFAULT 'whatsapp_primary',
alternative_phone_number text,
customer_notified boolean NOT NULL DEFAULT false,
customer_notified_at timestamptz
);
-- Indici per filtri rapidi (azienda, stato, date, etichette GIN)
CREATE INDEX IF NOT EXISTS idx_customer_orders_company_status
ON public.customer_orders(company_id, status);
CREATE INDEX IF NOT EXISTS idx_customer_orders_order_date
ON public.customer_orders(company_id, order_date DESC);
CREATE INDEX IF NOT EXISTS idx_customer_orders_tags_gin
ON public.customer_orders USING GIN (tags);
-- 4. Collegamento allegati (attachments) agli Ordini Clienti
ALTER TABLE public.attachments
ADD COLUMN IF NOT EXISTS customer_order_id uuid REFERENCES public.customer_orders(id) ON DELETE CASCADE;
CREATE INDEX IF NOT EXISTS idx_attachments_customer_order_id
ON public.attachments(customer_order_id);
-- 5. Trigger automatico per updated_at su customer_orders
CREATE OR REPLACE FUNCTION public.set_customer_orders_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_customer_orders_updated_at ON public.customer_orders;
CREATE TRIGGER trg_customer_orders_updated_at
BEFORE UPDATE ON public.customer_orders
FOR EACH ROW
EXECUTE FUNCTION public.set_customer_orders_updated_at();
-- 6. Row Level Security (RLS) per multi-tenancy aziendale
ALTER TABLE public.customer_orders ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Accesso ordini per membri azienda" ON public.customer_orders;
CREATE POLICY "Accesso ordini per membri azienda"
ON public.customer_orders
FOR ALL
TO authenticated
USING (
company_id IN (
SELECT sm.company_id FROM public.staff_members sm WHERE sm.user_id = auth.uid()
UNION
SELECT c.id FROM public.companies c WHERE c.user_id = auth.uid()
)
)
WITH CHECK (
company_id IN (
SELECT sm.company_id FROM public.staff_members sm WHERE sm.user_id = auth.uid()
UNION
SELECT c.id FROM public.companies c WHERE c.user_id = auth.uid()
)
);
@@ -0,0 +1,142 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customers/models/customer_model.dart';
void main() {
group('ContactPreference enum', () {
test('fromString resolves values and falls back to whatsappPrimary', () {
expect(
ContactPreference.fromString('whatsapp_alternative'),
ContactPreference.whatsappAlternative,
);
expect(
ContactPreference.fromString('call_primary'),
ContactPreference.callPrimary,
);
expect(
ContactPreference.fromString('call_alternative'),
ContactPreference.callAlternative,
);
expect(
ContactPreference.fromString('email'),
ContactPreference.email,
);
expect(
ContactPreference.fromString(null),
ContactPreference.whatsappPrimary,
);
});
});
group('CustomerOrderStatus & CustomerOrderQuickFilter', () {
test('active quick filter includes only to_order, ordered, arrived', () {
expect(CustomerOrderQuickFilter.active.dbStatuses, [
'to_order',
'ordered',
'arrived',
]);
expect(CustomerOrderQuickFilter.all.dbStatuses, isNull);
});
test('fromString parses status values cleanly', () {
expect(
CustomerOrderStatus.fromString('arrived'),
CustomerOrderStatus.arrived,
);
expect(
CustomerOrderStatus.fromString('delivered'),
CustomerOrderStatus.delivered,
);
expect(
CustomerOrderStatus.fromString('unknown'),
CustomerOrderStatus.toOrder,
);
});
});
group('CustomerOrderModel', () {
test('computes remainingAmount, deepLinkUrl, and effectiveContactDestination', () {
const customer = CustomerModel(
id: 'cust-1',
name: 'Mario Rossi',
phoneNumber: '3331112233',
alternativePhoneNumber: '3479998877',
email: 'mario@example.com',
note: '',
companyId: 'comp-1',
);
final order = CustomerOrderModel(
id: 'ord-123',
orderDate: DateTime(2026, 12, 2, 10, 30),
companyId: 'comp-1',
customerId: 'cust-1',
customer: customer,
productDescription: 'Cover MagSafe iPhone 16 Pro',
quantity: 2,
price: 29.90,
deposit: 10.00,
externalCode: 'ART-8891',
status: CustomerOrderStatus.arrived,
tags: const ['Amazon', 'Urgente'],
contactPreference: ContactPreference.whatsappAlternative,
);
expect(order.remainingAmount, closeTo(19.90, 0.001));
expect(
order.deepLinkUrl,
'https://flux.catelli.it/orders/form/ord-123',
);
expect(order.effectiveContactDestination, '3479998877');
final emailOrder = order.copyWith(
contactPreference: ContactPreference.email,
);
expect(emailOrder.effectiveContactDestination, 'mario@example.com');
});
test('fromMap and toMap round-trip fields accurately', () {
final map = {
'id': 'ord-99',
'created_at': '2026-12-02T09:00:00.000Z',
'updated_at': '2026-12-02T11:30:00.000Z',
'order_date': '2026-12-02T09:00:00.000Z',
'company_id': 'comp-1',
'store_id': 'store-1',
'customer_id': 'cust-1',
'product_description': 'Vetro Temperato S24',
'quantity': 0, // clamped to 1
'notes': 'Con cornice nera',
'price': 15,
'deposit': 5.5,
'external_code': 'VET-024',
'status': 'ordered',
'tags': ['FornitoreB', 'Display'],
'contact_preference': 'call_alternative',
'alternative_phone_number': '0299887766',
'customer_notified': true,
'customer_notified_at': '2026-12-02T11:29:00.000Z',
};
final parsed = CustomerOrderModel.fromMap(map);
expect(parsed.id, 'ord-99');
expect(parsed.quantity, 1);
expect(parsed.price, 15.0);
expect(parsed.deposit, 5.5);
expect(parsed.externalCode, 'VET-024');
expect(parsed.status, CustomerOrderStatus.ordered);
expect(parsed.tags, ['FornitoreB', 'Display']);
expect(parsed.contactPreference, ContactPreference.callAlternative);
expect(parsed.customerNotified, isTrue);
expect(parsed.customerNotifiedAt, isNotNull);
final serialized = parsed.toMap();
expect(serialized['external_code'], 'VET-024');
expect(serialized['status'], 'ordered');
expect(serialized['contact_preference'], 'call_alternative');
expect(serialized['tags'], ['FornitoreB', 'Display']);
});
});
}
@@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/notes/blocs/notes_cubit.dart';
import 'package:flux/features/notes/models/note_model.dart';
import 'package:flux/features/notes/ui/notes_form_screen.dart';
class _FakeNotesCubit extends Cubit<NotesState> implements NotesCubit {
final List<NoteModel> savedNotes = [];
final List<String> deletedNoteIds = [];
_FakeNotesCubit() : super(NotesState());
@override
String? get companyId => 'comp-1';
@override
String? get staffId => 'staff-1';
@override
void startListening() {}
@override
void stopListening() {}
@override
Future<void> saveNote(NoteModel note) async {
savedNotes.add(note);
}
@override
Future<void> deleteNote(String noteId) async {
deletedNoteIds.add(noteId);
}
}
void main() {
group('NoteFormScreen outside click behavior', () {
testWidgets(
'clicking inside Post-it keeps note open, clicking outside saves and closes',
(tester) async {
tester.view.physicalSize = const Size(1200, 900);
tester.view.devicePixelRatio = 1.0;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
final fakeCubit = _FakeNotesCubit();
final note = NoteModel(
id: 'note-1',
createdBy: 'staff-1',
companyId: 'comp-1',
title: 'Titolo iniziale',
content: 'Contenuto',
collaboratorIds: const [],
);
await tester.pumpWidget(
BlocProvider<NotesCubit>.value(
value: fakeCubit,
child: MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => NoteFormScreen(note: note),
),
);
},
child: const Text('Apri Nota'),
),
),
),
),
),
),
);
await tester.tap(find.text('Apri Nota'));
await tester.pumpAndSettle();
expect(find.byType(NoteFormScreen), findsOneWidget);
// 1. Tap dentro il Post-it: la nota resta aperta
await tester.tap(find.text('Condividi con tutti'));
await tester.pumpAndSettle();
expect(find.byType(NoteFormScreen), findsOneWidget);
// 2. Digitiamo nel titolo e clicchiamo subito fuori (senza aspettare i 500ms del debouncer)
await tester.enterText(
find.widgetWithText(TextFormField, 'Titolo iniziale'),
'Titolo aggiornato',
);
// Tap a sinistra fuori dal Post-it centrato (maxWidth 680 su schermo 1200 -> x=50 è fuori)
await tester.tapAt(const Offset(50, 450));
await tester.pumpAndSettle();
// La nota si è chiusa e ha salvato immediatamente le modifiche pendenti
expect(find.byType(NoteFormScreen), findsNothing);
expect(fakeCubit.savedNotes.last.title, 'Titolo aggiornato');
expect(fakeCubit.deletedNoteIds, isEmpty);
},
);
});
}
@@ -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,95 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_type.dart';
void main() {
group('OperationListState filter properties', () {
test('hasActiveFilters returns false on default initial state', () {
const state = OperationListState();
expect(state.hasActiveFilters, isFalse);
expect(state.activeFiltersCount, 0);
});
test('hasActiveFilters returns true when any filter is set', () {
const withSearch = OperationListState(searchTerm: 'Mario');
expect(withSearch.hasActiveFilters, isTrue);
expect(withSearch.activeFiltersCount, 1);
final withDate = OperationListState(
dateRange: DateTimeRange(
start: DateTime(2026, 11, 1),
end: DateTime(2026, 11, 30),
),
);
expect(withDate.hasActiveFilters, isTrue);
expect(withDate.activeFiltersCount, 1);
const withType = OperationListState(detailType: OperationType.telepass);
expect(withType.hasActiveFilters, isTrue);
expect(withType.activeFiltersCount, 1);
const withStaff = OperationListState(
staffId: 'staff-1',
staffDisplayName: 'Marco',
);
expect(withStaff.hasActiveFilters, isTrue);
expect(withStaff.activeFiltersCount, 1);
const withMultiple = OperationListState(
searchTerm: 'Test',
detailType: OperationType.mnp,
staffId: 'staff-1',
);
expect(withMultiple.hasActiveFilters, isTrue);
expect(withMultiple.activeFiltersCount, 3);
});
test('toFilterParams accurately exports state into OperationFilterParams', () {
final state = OperationListState(
searchTerm: 'Cliente',
detailType: OperationType.mnp,
subType: 'Vodafone',
staffId: 'staff-42',
staffDisplayName: 'Alessandro',
categoryKey: 'mnp',
categoryLabel: 'MNP',
storeId: 'store-1',
dateRange: DateTimeRange(
start: DateTime(2026, 11, 1),
end: DateTime(2026, 11, 30),
),
);
final OperationFilterParams params = state.toFilterParams();
expect(params.searchTerm, 'Cliente');
expect(params.detailType, OperationType.mnp);
expect(params.subType, 'Vodafone');
expect(params.staffId, 'staff-42');
expect(params.staffDisplayName, 'Alessandro');
expect(params.categoryKey, 'mnp');
expect(params.storeId, 'store-1');
expect(params.dateRange, state.dateRange);
});
test('copyWith can clear individual filters with explicit callbacks', () {
final state = OperationListState(
searchTerm: 'Test',
detailType: OperationType.mnp,
staffId: 'staff-1',
);
final cleared = state.copyWith(
searchTerm: () => null,
detailType: () => null,
);
expect(cleared.searchTerm, isNull);
expect(cleared.detailType, isNull);
expect(cleared.staffId, 'staff-1');
expect(cleared.hasActiveFilters, isTrue);
expect(cleared.activeFiltersCount, 1);
});
});
}
@@ -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,143 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/targets/models/target_model.dart';
void main() {
group('OperationFilterParams Tests', () {
test('empty() produces an empty params instance', () {
final empty = OperationFilterParams.empty();
expect(empty.isEmpty, isTrue);
expect(empty.isNotEmpty, isFalse);
expect(empty.detailType, isNull);
expect(empty.staffId, isNull);
expect(empty.dateRange, isNull);
expect(empty.searchTerm, isNull);
});
test('fromTargetCategory maps MNP category accurately', () {
final target = TargetModel.empty(
companyId: 'comp-1',
storeId: 'store-1',
startDay: DateTime(2026, 11, 1),
endDay: DateTime(2026, 11, 30, 23, 59, 59),
);
final params = OperationFilterParams.fromTargetCategory(
categoryKey: 'mnp',
categoryLabel: 'MNP',
target: target,
staffId: 'staff-99',
staffDisplayName: 'Marco',
);
expect(params.categoryKey, 'mnp');
expect(params.categoryLabel, 'MNP');
expect(params.detailType, OperationType.mnp);
expect(params.subType, isNull);
expect(params.storeId, 'store-1');
expect(params.staffId, 'staff-99');
expect(params.staffDisplayName, 'Marco');
expect(params.dateRange?.start, target.startDay);
expect(params.dateRange?.end, target.endDay);
expect(params.isNotEmpty, isTrue);
});
test('fromTargetCategory maps Calcio category to entertainment with calcio subtype', () {
final target = TargetModel.empty(
companyId: 'comp-1',
storeId: 'store-1',
);
final params = OperationFilterParams.fromTargetCategory(
categoryKey: 'calcio',
categoryLabel: 'Calcio',
target: target,
);
expect(params.categoryKey, 'calcio');
expect(params.detailType, OperationType.entertainment);
expect(params.subType, 'calcio');
});
test('fromTargetCategory maps Contenuti, Unica, Telepass, etc.', () {
final target = TargetModel.empty();
final contenuti = OperationFilterParams.fromTargetCategory(
categoryKey: 'contenuti',
categoryLabel: 'Contenuti',
target: target,
);
expect(contenuti.detailType, OperationType.entertainment);
final unica = OperationFilterParams.fromTargetCategory(
categoryKey: 'unica',
categoryLabel: 'TIM Unica',
target: target,
);
expect(unica.detailType, OperationType.unica);
final telepass = OperationFilterParams.fromTargetCategory(
categoryKey: 'telepass',
categoryLabel: 'Telepass',
target: target,
);
expect(telepass.detailType, OperationType.telepass);
final energy = OperationFilterParams.fromTargetCategory(
categoryKey: 'energiaTim',
categoryLabel: 'Energia TIM',
target: target,
);
expect(energy.detailType, OperationType.energy);
});
test('toQueryParams and fromQueryParams serialization round-trip', () {
final original = OperationFilterParams(
searchTerm: 'Mario Rossi',
dateRange: DateTimeRange(
start: DateTime(2026, 11, 1),
end: DateTime(2026, 11, 30),
),
detailType: OperationType.telepass,
subType: 'Base',
categoryKey: 'telepass',
categoryLabel: 'Telepass',
staffId: 'staff-1',
staffDisplayName: 'Luca',
storeId: 'store-1',
);
final query = original.toQueryParams();
final reconstructed = OperationFilterParams.fromQueryParams(query);
expect(reconstructed.searchTerm, original.searchTerm);
expect(reconstructed.detailType, original.detailType);
expect(reconstructed.subType, original.subType);
expect(reconstructed.categoryKey, original.categoryKey);
expect(reconstructed.staffId, original.staffId);
expect(reconstructed.staffDisplayName, original.staffDisplayName);
expect(reconstructed.storeId, original.storeId);
expect(reconstructed.dateRange?.start, original.dateRange?.start);
expect(reconstructed.dateRange?.end, original.dateRange?.end);
});
test('copyWith properly updates and clears individual filters', () {
final initial = OperationFilterParams(
searchTerm: 'Test',
detailType: OperationType.mnp,
staffId: 's-1',
);
final updated = initial.copyWith(
searchTerm: 'New Test',
clearDetailType: true,
);
expect(updated.searchTerm, 'New Test');
expect(updated.detailType, isNull);
expect(updated.staffId, 's-1');
});
});
}
@@ -0,0 +1,61 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flux/features/operations/models/operation_model.dart';
void main() {
group('OperationModel timestamps', () {
test('empty() initializes createdAt and updatedAt to null', () {
final empty = OperationModel.empty();
expect(empty.createdAt, isNull);
expect(empty.updatedAt, isNull);
});
test('fromMap parses created_at and updated_at into local DateTime', () {
final model = OperationModel.fromMap({
'id': 'op-1',
'company_id': 'comp-1',
'store_id': 'store-1',
'status': 'success',
'created_at': '2026-11-29T09:15:00.000Z',
'updated_at': '2026-11-29T12:30:00.000Z',
});
expect(model.createdAt, isNotNull);
expect(model.updatedAt, isNotNull);
expect(model.createdAt!.isUtc, isFalse);
expect(model.updatedAt!.isUtc, isFalse);
expect(model.createdAt!.toUtc(), DateTime.utc(2026, 11, 29, 9, 15));
expect(model.updatedAt!.toUtc(), DateTime.utc(2026, 11, 29, 12, 30));
});
test('fromMap handles missing updated_at gracefully', () {
final model = OperationModel.fromMap({
'id': 'op-2',
'company_id': 'comp-1',
'store_id': 'store-1',
'status': 'draft',
'created_at': '2026-11-29T09:15:00.000Z',
});
expect(model.createdAt, isNotNull);
expect(model.updatedAt, isNull);
});
test('copyWith and Equatable include updatedAt', () {
final t1 = DateTime(2026, 11, 29, 10, 0);
final t2 = DateTime(2026, 11, 29, 13, 30);
final a = OperationModel(
id: 'op-1',
companyId: 'comp-1',
createdAt: t1,
updatedAt: t1,
);
final b = a.copyWith(updatedAt: t2);
expect(b.createdAt, t1);
expect(b.updatedAt, t2);
expect(a == b, isFalse);
expect(b, a.copyWith(updatedAt: t2));
});
});
}
@@ -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);
});
});
}