Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63edd51420 | ||
|
|
7572f4c061 | ||
|
|
57a4dc6f68 | ||
|
|
4b111766dc | ||
|
|
2bf668a088 | ||
|
|
0adb1a8f1c | ||
|
|
606a1fc3a9 | ||
|
|
4e3732597b | ||
|
|
53496a2a9d | ||
|
|
0cc7c76df9 | ||
|
|
ca67d86a71 | ||
|
|
33e309909e | ||
|
|
ab64bf0621 | ||
|
|
dcb19cf839 | ||
|
|
bc9e0769cd | ||
|
|
7dd8a3ac71 | ||
|
|
70db03066b |
No files matched your search
@@ -57,16 +57,22 @@ jobs:
|
||||
- name: Aggiorna Link Windows su Supabase
|
||||
run: |
|
||||
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
|
||||
$headers = @{
|
||||
"apikey" = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Authorization" = "Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Content-Type" = "application/json"
|
||||
$apiKey = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if ([string]::IsNullOrWhiteSpace($apiKey)) {
|
||||
$apiKey = "sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
}
|
||||
$body = (@{
|
||||
$body = @{
|
||||
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
|
||||
latest_version = $TagVersion
|
||||
} | ConvertTo-Json)
|
||||
Invoke-RestMethod -Uri "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.windows" -Method Patch -Headers $headers -Body $body -UserAgent "flux-runner"
|
||||
} | ConvertTo-Json -Compress
|
||||
|
||||
[System.IO.File]::WriteAllText("$PWD\payload.json", $body, (New-Object System.Text.UTF8Encoding($false)))
|
||||
curl.exe -i -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.windows" `
|
||||
-H "apikey: $apiKey" `
|
||||
-H "Authorization: Bearer $apiKey" `
|
||||
-H "Content-Type: application/json" `
|
||||
--data-binary "@payload.json"
|
||||
Remove-Item -Force "$PWD\payload.json"
|
||||
|
||||
- name: Pulisci Workspace Windows
|
||||
if: always()
|
||||
@@ -107,17 +113,21 @@ jobs:
|
||||
- name: Aggiorna Versione Web su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.web" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.web" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-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
|
||||
@@ -128,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
|
||||
@@ -180,9 +159,13 @@ jobs:
|
||||
- name: Aggiorna Link Linux su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.AppImage" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.AppImage" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\", \"latest_version\": \"$TagVersion\"}"
|
||||
|
||||
@@ -230,8 +213,12 @@ jobs:
|
||||
- name: Aggiorna Link macOS su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.macos" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}"
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -48,6 +48,8 @@ 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';
|
||||
import 'package:flux/features/settings/blocs/reminder_defaults_cubit.dart';
|
||||
@@ -97,8 +99,13 @@ class AppRouter {
|
||||
final isGoingToSetPassword = state.matchedLocation == '/set-password';
|
||||
|
||||
// 1. LA PASSATOIA VIP (DEVE ESSERE IN CIMA)
|
||||
// Usiamo state.uri.path perché state.matchedLocation a volte fa i capricci coi deep link iniziali
|
||||
final isPublicRoute = state.uri.path.startsWith('/upload');
|
||||
// Usiamo sia state.uri.path che state.matchedLocation per sicurezza con i deep link
|
||||
final path = state.uri.path;
|
||||
final matched = state.matchedLocation;
|
||||
final isPublicRoute = path.startsWith('/upload') ||
|
||||
path.startsWith('/financing') ||
|
||||
matched.startsWith('/upload') ||
|
||||
matched.startsWith('/financing');
|
||||
|
||||
if (isPublicRoute) {
|
||||
// Ritorna null esplicitamente per dire al router "Rimani qui e non fare altri controlli"
|
||||
@@ -154,6 +161,14 @@ class AppRouter {
|
||||
child: const OnboardingScreen(),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/financing/:sessionId',
|
||||
name: Routes.financing,
|
||||
builder: (context, state) {
|
||||
final sessionId = state.pathParameters['sessionId'] ?? '';
|
||||
return FinancingFormScreen(sessionId: sessionId);
|
||||
},
|
||||
),
|
||||
|
||||
// --- CORE APP (DENTRO LA SHELL CON NAVIGATION BAR/RAIL) ---
|
||||
ShellRoute(
|
||||
@@ -303,7 +318,16 @@ 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',
|
||||
|
||||
@@ -30,4 +30,5 @@ class Routes {
|
||||
static const String targets = 'targets';
|
||||
static const String targetForm = 'target-form';
|
||||
static const String targetDetail = 'target-detail';
|
||||
static const String financing = 'financing';
|
||||
}
|
||||
@@ -46,4 +46,104 @@ class ImageUtils {
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ruota fisicamente i byte di un'immagine di un numero di quarti di giro (90° * quarterTurns).
|
||||
static Uint8List rotateBytes(
|
||||
Uint8List bytes, {
|
||||
required int quarterTurns,
|
||||
String? extension,
|
||||
}) {
|
||||
final turns = quarterTurns % 4;
|
||||
if (turns == 0) return bytes;
|
||||
|
||||
try {
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) return bytes;
|
||||
|
||||
final angle = turns * 90;
|
||||
final rotated = img.copyRotate(image, angle: angle);
|
||||
|
||||
final ext = extension?.toLowerCase().replaceAll('.', '');
|
||||
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
|
||||
|
||||
if (isPng) {
|
||||
return Uint8List.fromList(img.encodePng(rotated));
|
||||
} else {
|
||||
return Uint8List.fromList(img.encodeJpg(rotated, quality: 92));
|
||||
}
|
||||
} catch (_) {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/widgets/qr_upload_dialog.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
@@ -153,13 +154,55 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
if ((ext == 'jpg' || ext == 'jpeg' || ext == 'png') &&
|
||||
file.bytes != null) {
|
||||
previewWidget = Image.memory(file.bytes!, fit: BoxFit.contain);
|
||||
} else if (ext == 'pdf') {
|
||||
previewWidget = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
} else if (ext == 'pdf' && file.bytes != null) {
|
||||
Widget pdfThumb;
|
||||
try {
|
||||
final doc = await pdfrx.PdfDocument.openData(
|
||||
file.bytes!,
|
||||
sourceName: file.name,
|
||||
);
|
||||
if (doc.pages.isNotEmpty) {
|
||||
final page = doc.pages.first;
|
||||
final pageImg = await page.render(
|
||||
fullWidth: 300,
|
||||
fullHeight: (300.0 * (page.height / page.width)).roundToDouble(),
|
||||
);
|
||||
if (pageImg != null) {
|
||||
final uiImg = await pageImg.createImage();
|
||||
final bd = await uiImg.toByteData(format: ui.ImageByteFormat.png);
|
||||
if (bd != null) {
|
||||
pdfThumb = Image.memory(bd.buffer.asUint8List(), fit: BoxFit.contain);
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
uiImg.dispose();
|
||||
pageImg.dispose();
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
await doc.dispose();
|
||||
} catch (_) {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
previewWidget = pdfThumb;
|
||||
} else {
|
||||
previewWidget = const Center(
|
||||
child: Icon(Icons.insert_drive_file, size: 80, color: Colors.blue),
|
||||
previewWidget = Center(
|
||||
child: Icon(
|
||||
ext == 'pdf' ? Icons.picture_as_pdf : Icons.insert_drive_file,
|
||||
size: 80,
|
||||
color: ext == 'pdf' ? Colors.red : Colors.blue,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -173,6 +216,8 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
? widget.titleForUpload
|
||||
: '${widget.titleForUpload}_${i + 1}';
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
final finalName = await showDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
@@ -315,12 +360,168 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
DeleteSpecificAttachmentEvent(targetFile),
|
||||
);
|
||||
},
|
||||
onViewModeChanged: (targetFile, newMode) {
|
||||
operationFilesBloc.add(
|
||||
UpdateAttachmentViewModeEvent(targetFile, newMode),
|
||||
);
|
||||
},
|
||||
onAttachmentUpdated: (updatedFile) {
|
||||
operationFilesBloc.add(
|
||||
AttachmentUpdatedEvent(updatedFile),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _downloadFileWeb(String fileName, Uint8List bytes) {
|
||||
final blob = html.Blob([bytes]);
|
||||
final url = html.Url.createObjectUrlFromBlob(blob);
|
||||
html.AnchorElement(href: url)
|
||||
..setAttribute('download', fileName)
|
||||
..click();
|
||||
html.Url.revokeObjectUrl(url);
|
||||
}
|
||||
|
||||
Future<void> _downloadSelectedFiles(
|
||||
List<AttachmentModel> selectedFiles,
|
||||
) async {
|
||||
if (selectedFiles.isEmpty) return;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => const Center(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text('Download allegati in corso...'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final List<({String name, Uint8List bytes})> downloadedList = [];
|
||||
|
||||
for (final file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
|
||||
if (fileBytes != null && fileBytes.isNotEmpty) {
|
||||
String fullName = file.name;
|
||||
final ext = file.extension.toLowerCase().replaceAll('.', '');
|
||||
if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) {
|
||||
fullName = '$fullName.$ext';
|
||||
}
|
||||
downloadedList.add((name: fullName, bytes: fileBytes));
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pop(context); // Chiude il loader
|
||||
}
|
||||
|
||||
if (downloadedList.isEmpty) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Nessun file scaricabile trovato.')),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (kIsWeb) {
|
||||
for (int i = 0; i < downloadedList.length; i++) {
|
||||
final item = downloadedList[i];
|
||||
_downloadFileWeb(item.name, item.bytes);
|
||||
if (downloadedList.length > 1) {
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
}
|
||||
}
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
downloadedList.length == 1
|
||||
? 'Download avviato: ${downloadedList.first.name}'
|
||||
: '${downloadedList.length} file scaricati!',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Desktop / Mobile
|
||||
if (downloadedList.length == 1) {
|
||||
final item = downloadedList.first;
|
||||
final String? savePath = await FilePicker.saveFile(
|
||||
dialogTitle: 'Salva file',
|
||||
fileName: item.name,
|
||||
initialDirectory: _exportDirectory,
|
||||
bytes: item.bytes,
|
||||
);
|
||||
|
||||
if (savePath != null) {
|
||||
final targetFile = File(savePath);
|
||||
await targetFile.writeAsBytes(item.bytes);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('File salvato in: $savePath')),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final String? selectedDirectory = await FilePicker.getDirectoryPath(
|
||||
dialogTitle:
|
||||
'Seleziona cartella dove salvare i file (${downloadedList.length})',
|
||||
initialDirectory: _exportDirectory,
|
||||
);
|
||||
|
||||
if (selectedDirectory != null) {
|
||||
for (final item in downloadedList) {
|
||||
final targetFile = File('$selectedDirectory/${item.name}');
|
||||
await targetFile.writeAsBytes(item.bytes);
|
||||
}
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${downloadedList.length} file salvati in: $selectedDirectory',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
if (Navigator.canPop(context)) Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Errore durante il download: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportMergedPdf(List<AttachmentModel> selectedFiles) async {
|
||||
if (!kIsWeb && (_exportDirectory == null || _exportDirectory!.isEmpty)) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -343,11 +544,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
for (var file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
@@ -360,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);
|
||||
}
|
||||
}
|
||||
@@ -440,7 +640,7 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
|
||||
// 5. SALVATAGGIO SUL DISCO
|
||||
if (kIsWeb) {
|
||||
// Trigger download web
|
||||
_downloadFileWeb('$finalName.pdf', mergedPdfBytes);
|
||||
} else {
|
||||
final fileToSave = File('$_exportDirectory/$finalName.pdf');
|
||||
await fileToSave.writeAsBytes(mergedPdfBytes);
|
||||
@@ -486,11 +686,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
for (var file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
@@ -509,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,
|
||||
@@ -592,7 +791,7 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
final singlePdfBytes = await pdf.save();
|
||||
|
||||
if (kIsWeb) {
|
||||
// Trigger download web
|
||||
_downloadFileWeb('$finalName.pdf', singlePdfBytes);
|
||||
} else {
|
||||
final fileToSave = File('$_exportDirectory/$finalName.pdf');
|
||||
await fileToSave.writeAsBytes(singlePdfBytes);
|
||||
@@ -620,7 +819,17 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocBuilder<AttachmentsBloc, AttachmentsState>(
|
||||
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
|
||||
listener: (context, state) {
|
||||
if (state.status == AttachmentsStatus.failure && state.error != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.error!),
|
||||
backgroundColor: theme.colorScheme.error,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final allFiles = state.allFiles;
|
||||
final selectedFiles = state.selectedFiles;
|
||||
@@ -870,6 +1079,15 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
);
|
||||
},
|
||||
),
|
||||
// Bottone Scarica Selezionati
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.teal,
|
||||
),
|
||||
icon: const Icon(Icons.download),
|
||||
label: Text('Scarica (${selectedFiles.length})'),
|
||||
onPressed: () => _downloadSelectedFiles(selectedFiles),
|
||||
),
|
||||
// IL NUOVO BOTTONE ESPORTA CON MENU A TENDINA
|
||||
PopupMenuButton<String>(
|
||||
tooltip: 'Opzioni di esportazione',
|
||||
@@ -1069,7 +1287,6 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
itemCount: allFiles.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = allFiles[index];
|
||||
final isPdf = file.extension == 'pdf';
|
||||
final isSelected = selectedFiles.contains(file);
|
||||
final isLocal =
|
||||
file.localBytes !=
|
||||
@@ -1115,28 +1332,12 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
),
|
||||
child: isPdf
|
||||
? const Icon(
|
||||
Icons.picture_as_pdf,
|
||||
size: 48,
|
||||
color: Colors.red,
|
||||
)
|
||||
: isLocal
|
||||
? ClipRRect(
|
||||
borderRadius:
|
||||
const BorderRadius.vertical(
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
child: Image.memory(
|
||||
file.localBytes!,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.image,
|
||||
size: 48,
|
||||
color: Colors.blue,
|
||||
), // Da remoto metterai il tuo NetworkImage se vuoi
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
child: _AttachmentThumbnail(file: file),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Nome File
|
||||
@@ -1223,3 +1424,240 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AttachmentThumbnail extends StatefulWidget {
|
||||
final AttachmentModel file;
|
||||
|
||||
const _AttachmentThumbnail({required this.file});
|
||||
|
||||
@override
|
||||
State<_AttachmentThumbnail> createState() => _AttachmentThumbnailState();
|
||||
}
|
||||
|
||||
class _AttachmentThumbnailState extends State<_AttachmentThumbnail> {
|
||||
static final Map<String, Uint8List> _thumbnailCache = {};
|
||||
|
||||
Uint8List? _bytes;
|
||||
bool _isLoading = true;
|
||||
|
||||
String get _cacheKey {
|
||||
if (widget.file.thumbnailPath != null &&
|
||||
widget.file.thumbnailPath!.isNotEmpty) {
|
||||
return 'thumb_${widget.file.thumbnailPath}';
|
||||
}
|
||||
return widget.file.id ??
|
||||
widget.file.storagePath ??
|
||||
'${widget.file.name}_${widget.file.fileSize}';
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadThumbnail();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _AttachmentThumbnail oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.file.id != oldWidget.file.id ||
|
||||
widget.file.thumbnailPath != oldWidget.file.thumbnailPath ||
|
||||
widget.file.storagePath != oldWidget.file.storagePath ||
|
||||
widget.file.localBytes != oldWidget.file.localBytes) {
|
||||
_loadThumbnail();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadThumbnail() async {
|
||||
final key = _cacheKey;
|
||||
if (_thumbnailCache.containsKey(key)) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = _thumbnailCache[key];
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final file = widget.file;
|
||||
|
||||
// ⚡ Se il worker sul server ha generato il thumbnail (WebP), lo scarichiamo direttamente!
|
||||
if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty) {
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final thumbBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.thumbnailPath!,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
if (thumbBytes.isNotEmpty) {
|
||||
_thumbnailCache[key] = thumbBytes;
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = thumbBytes;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint(
|
||||
'Impossibile scaricare thumbnail da ${file.thumbnailPath}, procedo con fallback: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List? sourceBytes;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
sourceBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
sourceBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
|
||||
if (sourceBytes == null || sourceBytes.isEmpty) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Uint8List? finalThumbnailBytes;
|
||||
final isPdf =
|
||||
file.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
if (isPdf) {
|
||||
final document = await pdfrx.PdfDocument.openData(
|
||||
sourceBytes,
|
||||
sourceName: file.name,
|
||||
);
|
||||
if (document.pages.isNotEmpty) {
|
||||
final page = document.pages.first;
|
||||
const renderWidth = 300.0;
|
||||
final renderHeight =
|
||||
(300.0 * (page.height / page.width)).roundToDouble();
|
||||
final pageImage = await page.render(
|
||||
fullWidth: renderWidth,
|
||||
fullHeight: renderHeight,
|
||||
);
|
||||
if (pageImage != null) {
|
||||
final uiImage = await pageImage.createImage();
|
||||
final byteData = await uiImage.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
if (byteData != null) {
|
||||
finalThumbnailBytes = byteData.buffer.asUint8List();
|
||||
}
|
||||
uiImage.dispose();
|
||||
pageImage.dispose();
|
||||
}
|
||||
}
|
||||
await document.dispose();
|
||||
} else {
|
||||
finalThumbnailBytes = ImageUtils.normalizeOrientation(
|
||||
sourceBytes,
|
||||
extension: file.extension,
|
||||
);
|
||||
}
|
||||
|
||||
if (finalThumbnailBytes != null) {
|
||||
_thumbnailCache[key] = finalThumbnailBytes;
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = finalThumbnailBytes;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isPdf =
|
||||
widget.file.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
if (_bytes != null) {
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Image.memory(
|
||||
_bytes!,
|
||||
fit: BoxFit.cover,
|
||||
filterQuality: FilterQuality.medium,
|
||||
),
|
||||
if (isPdf)
|
||||
Positioned(
|
||||
bottom: 6,
|
||||
left: 6,
|
||||
child: Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.9),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 3,
|
||||
offset: Offset(0, 1),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.picture_as_pdf, size: 10, color: Colors.white),
|
||||
SizedBox(width: 3),
|
||||
Text(
|
||||
'PDF',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_isLoading) {
|
||||
return Center(
|
||||
child: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: isPdf ? Colors.red : Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: Icon(
|
||||
isPdf ? Icons.picture_as_pdf : Icons.image,
|
||||
size: 48,
|
||||
color: isPdf ? Colors.red : Colors.blue,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
@@ -16,6 +16,7 @@ part 'attachments_state.dart';
|
||||
|
||||
class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
final _repository = GetIt.I.get<AttachmentsRepository>();
|
||||
StreamSubscription<List<AttachmentModel>>? _realtimeSubscription;
|
||||
|
||||
AttachmentsBloc({String? parentId, required AttachmentParentType parentType})
|
||||
: super(
|
||||
@@ -36,6 +37,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
on<DeleteSpecificAttachmentEvent>(_onDeleteSpecificAttachment);
|
||||
on<SelectAllAttachmentsEvent>(_onSelectAllAttachments);
|
||||
on<ClearAttachmentSelectionEvent>(_onClearAttachmentSelection);
|
||||
on<RemoteAttachmentsUpdatedEvent>(_onRemoteAttachmentsUpdated);
|
||||
on<UpdateAttachmentViewModeEvent>(_onUpdateAttachmentViewMode);
|
||||
on<AttachmentUpdatedEvent>(_onAttachmentUpdated);
|
||||
|
||||
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
if (parentId != null && currentCompanyId != null) {
|
||||
@@ -43,6 +47,12 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_realtimeSubscription?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
|
||||
FutureOr<void> _onParentEntitySaved(
|
||||
ParentEntitySavedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
@@ -65,7 +75,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
bytes: file.localBytes,
|
||||
);
|
||||
|
||||
// Chiamiamo il metodo generico passando il parentId e il TYPE
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: event.newParentId,
|
||||
parentType: state.parentType,
|
||||
@@ -96,26 +105,75 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
final currentId = event.parentId ?? state.parentId;
|
||||
if (currentId == null || currentId.isEmpty) return;
|
||||
|
||||
if (currentId != null) {
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
emit(
|
||||
state.copyWith(
|
||||
parentId: currentId,
|
||||
status:
|
||||
state.remoteFiles.isEmpty
|
||||
? AttachmentsStatus.loading
|
||||
: state.status,
|
||||
),
|
||||
);
|
||||
|
||||
await emit.forEach(
|
||||
_repository.getFilesStream(
|
||||
currentId,
|
||||
state.parentType,
|
||||
), // Passiamo il tipo!
|
||||
onData: (List<AttachmentModel> data) =>
|
||||
state.copyWith(status: AttachmentsStatus.ready, remoteFiles: data),
|
||||
onError: (error, stackTrace) => state.copyWith(
|
||||
status: AttachmentsStatus.failure,
|
||||
error: error.toString(),
|
||||
// 1. Caricamento immediato via REST (Robusto e istantaneo)
|
||||
try {
|
||||
final remoteList = await _repository.getFiles(
|
||||
currentId,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: remoteList,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint("Avviso REST getFiles: $e");
|
||||
if (state.remoteFiles.isEmpty) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.failure,
|
||||
error: "Impossibile recuperare gli allegati: $e",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Iscrizione Realtime in background (senza bloccare la coda eventi)
|
||||
await _realtimeSubscription?.cancel();
|
||||
try {
|
||||
_realtimeSubscription = _repository
|
||||
.getFilesStream(currentId, state.parentType)
|
||||
.listen(
|
||||
(data) {
|
||||
add(RemoteAttachmentsUpdatedEvent(data));
|
||||
},
|
||||
onError: (error) {
|
||||
debugPrint("Avviso stream Realtime AttachmentsBloc: $error");
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint("Avviso inizializzazione Realtime: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void _onAddAttachments(
|
||||
void _onRemoteAttachmentsUpdated(
|
||||
RemoteAttachmentsUpdatedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: event.files,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
FutureOr<void> _onAddAttachments(
|
||||
AddAttachmentsEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
@@ -132,32 +190,48 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
|
||||
if (currentId == null) {
|
||||
final newLocalFiles = event.files.map((file) {
|
||||
// FISCHIO SALVAVITA PER DESKTOP: se i bytes sono nulli, li leggiamo dal path fisico!
|
||||
Uint8List? rawBytes = file.bytes;
|
||||
if (rawBytes == null && file.path != null) {
|
||||
rawBytes = File(file.path!).readAsBytesSync();
|
||||
}
|
||||
// Normalizziamo i file garantendo la presenza dei byte (fondamentale su desktop)
|
||||
final processedFiles =
|
||||
event.files.map((file) {
|
||||
Uint8List? rawBytes = file.bytes;
|
||||
if (rawBytes == null && file.path != null && !kIsWeb) {
|
||||
try {
|
||||
final f = File(file.path!);
|
||||
if (f.existsSync()) {
|
||||
rawBytes = f.readAsBytesSync();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
return AttachmentModel(
|
||||
id: null,
|
||||
companyId: currentCompanyId,
|
||||
operationId: state.parentType == AttachmentParentType.operation
|
||||
? ''
|
||||
: null,
|
||||
ticketId: state.parentType == AttachmentParentType.ticket ? '' : null,
|
||||
customerId: state.parentType == AttachmentParentType.customer
|
||||
? ''
|
||||
: null,
|
||||
name: file.name.fileNameWithoutExtension(),
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: rawBytes, // Ora i byte ci sono al 100% anche su Mac!
|
||||
);
|
||||
}).toList();
|
||||
return PlatformFile(
|
||||
name: file.name,
|
||||
size: file.size > 0 ? file.size : (rawBytes?.length ?? 0),
|
||||
bytes: rawBytes,
|
||||
path: file.path,
|
||||
readStream: file.readStream,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
|
||||
if (currentId == null || currentId.isEmpty) {
|
||||
final newLocalFiles =
|
||||
processedFiles.map((file) {
|
||||
return AttachmentModel(
|
||||
id: null,
|
||||
companyId: currentCompanyId,
|
||||
operationId:
|
||||
state.parentType == AttachmentParentType.operation ? '' : null,
|
||||
ticketId:
|
||||
state.parentType == AttachmentParentType.ticket ? '' : null,
|
||||
customerId:
|
||||
state.parentType == AttachmentParentType.customer ? '' : null,
|
||||
name: file.name.fileNameWithoutExtension(),
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: file.bytes,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -171,18 +245,31 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
// BIVIO 2: PRATICA ESISTENTE (Upload immediato)
|
||||
emit(state.copyWith(status: AttachmentsStatus.uploading));
|
||||
try {
|
||||
final List<Future<void>> uploadTasks = event.files.map((file) {
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: currentId,
|
||||
parentType: state.parentType,
|
||||
pickedFile: file,
|
||||
companyId: currentCompanyId,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
}).toList();
|
||||
final List<Future<void>> uploadTasks =
|
||||
processedFiles.map((file) {
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: currentId,
|
||||
parentType: state.parentType,
|
||||
pickedFile: file,
|
||||
companyId: currentCompanyId,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
await Future.wait(uploadTasks);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
|
||||
// Aggiornamento immediato via REST (garantisce visualizzazione immediata anche senza WebSocket)
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
currentId,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -223,11 +310,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
// 2. Gestione Foto Fotocamera (XFile)
|
||||
if (event.photos != null) {
|
||||
for (var photo in event.photos!) {
|
||||
// Leggiamo i byte asincronamente
|
||||
final bytes = await photo.readAsBytes();
|
||||
final fileSize = await photo.length();
|
||||
|
||||
// Lo travestiamo da PlatformFile per passarlo al Repository!
|
||||
final fakePlatformFile = PlatformFile(
|
||||
name: photo.name,
|
||||
size: fileSize,
|
||||
@@ -247,9 +332,18 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
}
|
||||
}
|
||||
|
||||
// Esecuzione parallela di tutti i documenti e foto
|
||||
await Future.wait(uploadTasks);
|
||||
emit(state.copyWith(status: AttachmentsStatus.success));
|
||||
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.success,
|
||||
remoteFiles: updatedFiles,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -268,7 +362,22 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
currentContextType: state.parentType,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
|
||||
if (state.parentId != null) {
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
selectedFiles: [],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -293,7 +402,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
SelectAllAttachmentsEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
// Prendiamo TUTTI i file (locali e remoti) e li buttiamo nei selezionati
|
||||
emit(state.copyWith(selectedFiles: state.allFiles));
|
||||
}
|
||||
|
||||
@@ -301,7 +409,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
ClearAttachmentSelectionEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
// Svuotiamo brutalmente la lista
|
||||
emit(state.copyWith(selectedFiles: []));
|
||||
}
|
||||
|
||||
@@ -311,38 +418,36 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
) async {
|
||||
if (state.selectedFiles.isEmpty) return;
|
||||
|
||||
// BIVIO 1: PRATICA/TICKET NON ANCORA SALVATA (Modalità Locale)
|
||||
if (state.parentId == null) {
|
||||
final updatedLocalFiles = state.localFiles.map((file) {
|
||||
if (state.selectedFiles.contains(file)) {
|
||||
// Assegniamo dinamicamente l'ID in base all'entità scelta
|
||||
switch (event.targetType) {
|
||||
case AttachmentParentType.customer:
|
||||
return file.copyWith(customerId: event.targetId);
|
||||
case AttachmentParentType.ticket:
|
||||
return file.copyWith(ticketId: event.targetId);
|
||||
case AttachmentParentType.operation:
|
||||
return file.copyWith(operationId: event.targetId);
|
||||
case AttachmentParentType.shippingDocument:
|
||||
return file.copyWith(shippingDocumentId: event.targetId);
|
||||
case AttachmentParentType.note:
|
||||
return file.copyWith(noteId: event.targetId);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.map((file) {
|
||||
if (state.selectedFiles.contains(file)) {
|
||||
switch (event.targetType) {
|
||||
case AttachmentParentType.customer:
|
||||
return file.copyWith(customerId: event.targetId);
|
||||
case AttachmentParentType.ticket:
|
||||
return file.copyWith(ticketId: event.targetId);
|
||||
case AttachmentParentType.operation:
|
||||
return file.copyWith(operationId: event.targetId);
|
||||
case AttachmentParentType.shippingDocument:
|
||||
return file.copyWith(shippingDocumentId: event.targetId);
|
||||
case AttachmentParentType.note:
|
||||
return file.copyWith(noteId: event.targetId);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
localFiles: updatedLocalFiles,
|
||||
selectedFiles: [], // Svuotiamo la selezione
|
||||
selectedFiles: [],
|
||||
status: AttachmentsStatus.ready,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 2: PRATICA/TICKET ESISTENTE (Modalità Remota su DB)
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
try {
|
||||
final List<Future<void>> linkTasks = [];
|
||||
@@ -361,8 +466,17 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
|
||||
await Future.wait(linkTasks);
|
||||
|
||||
// Lo stream aggiornerà automaticamente la UI
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
selectedFiles: [],
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -377,23 +491,35 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
RenameAttachmentEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
// BIVIO 1: File Locale (Bozza)
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(name: event.newName);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(name: event.newName);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 2: File Remoto (Salvato su DB)
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
try {
|
||||
await _repository.renameAttachment(event.file.id!, event.newName);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
if (state.parentId != null) {
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -409,13 +535,68 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles
|
||||
.where((f) => f != event.file)
|
||||
.toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.where((f) => f != event.file).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _onUpdateAttachmentViewMode(
|
||||
UpdateAttachmentViewModeEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(viewMode: event.viewMode);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.file.id == null) return;
|
||||
|
||||
try {
|
||||
final updatedRemoteFiles = state.remoteFiles.map((f) {
|
||||
if (f.id == event.file.id) {
|
||||
return f.copyWith(viewMode: event.viewMode);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(remoteFiles: updatedRemoteFiles));
|
||||
|
||||
await _repository.updateAttachmentViewMode(event.file.id!, event.viewMode);
|
||||
} catch (e) {
|
||||
debugPrint("Errore aggiornamento viewMode in DB: $e");
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _onAttachmentUpdated(
|
||||
AttachmentUpdatedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
final updatedRemote = state.remoteFiles.map((f) {
|
||||
if (f.id == event.file.id) {
|
||||
return event.file;
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
|
||||
final updatedLocal = state.localFiles.map((f) {
|
||||
if (f.id == event.file.id || (f.id == null && f.name == event.file.name)) {
|
||||
return event.file;
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
|
||||
emit(state.copyWith(
|
||||
remoteFiles: updatedRemote,
|
||||
localFiles: updatedLocal,
|
||||
));
|
||||
}
|
||||
|
||||
Bucket get _getBucketForParentType {
|
||||
switch (state.parentType) {
|
||||
case AttachmentParentType.customer:
|
||||
|
||||
@@ -71,3 +71,28 @@ class DeleteSpecificAttachmentEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
const DeleteSpecificAttachmentEvent(this.file);
|
||||
}
|
||||
|
||||
class RemoteAttachmentsUpdatedEvent extends AttachmentsEvent {
|
||||
final List<AttachmentModel> files;
|
||||
const RemoteAttachmentsUpdatedEvent(this.files);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [files];
|
||||
}
|
||||
|
||||
class UpdateAttachmentViewModeEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
final AttachmentViewMode viewMode;
|
||||
const UpdateAttachmentViewModeEvent(this.file, this.viewMode);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [file, viewMode];
|
||||
}
|
||||
|
||||
class AttachmentUpdatedEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
const AttachmentUpdatedEvent(this.file);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [file];
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'dart:typed_data';
|
||||
import 'dart:io';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
|
||||
@@ -47,6 +49,28 @@ class AttachmentsRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// RECUPERA I FILE IN MODALITÀ REST (Immediato e affidabile)
|
||||
Future<List<AttachmentModel>> getFiles(
|
||||
String parentId,
|
||||
AttachmentParentType parentType,
|
||||
) async {
|
||||
try {
|
||||
final columnName = _getColumnNameForParent(parentType);
|
||||
|
||||
final response = await _supabase
|
||||
.from(Tables.attachments)
|
||||
.select()
|
||||
.eq(columnName, parentId)
|
||||
.order('created_at', ascending: true);
|
||||
|
||||
return (response as List)
|
||||
.map((map) => AttachmentModel.fromMap(map as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception("Impossibile recuperare gli allegati dal DB: $e");
|
||||
}
|
||||
}
|
||||
|
||||
/// RECUPERA I FILE IN TEMPO REALE
|
||||
Stream<List<AttachmentModel>> getFilesStream(
|
||||
String parentId,
|
||||
@@ -75,7 +99,6 @@ class AttachmentsRepository {
|
||||
String? rawFileName, // Alternativa: nome del file
|
||||
}) async {
|
||||
// 🛡️ L'ASSERT NINJA: O c'è il pickedFile, o ci sono i byte e il nome.
|
||||
// L'assert funziona solo in debug, ma è perfetto per beccare subito errori di chiamata!
|
||||
assert(
|
||||
pickedFile != null || (rawBytes != null && rawFileName != null),
|
||||
'Devi passare o un PlatformFile, oppure rawBytes e rawFileName!',
|
||||
@@ -88,25 +111,35 @@ class AttachmentsRepository {
|
||||
final int finalFileSize;
|
||||
|
||||
if (pickedFile != null) {
|
||||
if (pickedFile.bytes == null) {
|
||||
Uint8List? fileBytes = pickedFile.bytes;
|
||||
// Se su Desktop i bytes sono nulli ma abbiamo il path, leggiamo direttamente da disco
|
||||
if (fileBytes == null && pickedFile.path != null && !kIsWeb) {
|
||||
try {
|
||||
final f = File(pickedFile.path!);
|
||||
if (f.existsSync()) {
|
||||
fileBytes = f.readAsBytesSync();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (fileBytes == null) {
|
||||
throw Exception(
|
||||
"I bytes del file sono vuoti! Ricarica la pagina senza cache.",
|
||||
);
|
||||
}
|
||||
finalBytes = pickedFile.bytes!;
|
||||
finalBytes = fileBytes;
|
||||
finalFileName = pickedFile.name;
|
||||
finalFileSize = pickedFile.size;
|
||||
finalFileSize = pickedFile.size > 0 ? pickedFile.size : finalBytes.length;
|
||||
} else {
|
||||
// Se pickedFile è null, grazie all'assert sappiamo che questi non lo sono
|
||||
finalBytes = rawBytes!;
|
||||
finalFileName = rawFileName!;
|
||||
finalFileSize = finalBytes.length; // Calcoliamo la size dai byte reali
|
||||
finalFileSize = finalBytes.length;
|
||||
}
|
||||
|
||||
// 2. Estraiamo l'estensione e puliamo il nome
|
||||
final extension = finalFileName.contains('.')
|
||||
? finalFileName.split('.').last
|
||||
: ''; // Fallback se il file non ha estensione
|
||||
: '';
|
||||
|
||||
final cleanName = finalFileName
|
||||
.replaceAll(RegExp(r'[^\w\s\.-]'), '')
|
||||
@@ -123,7 +156,10 @@ class AttachmentsRepository {
|
||||
.uploadBinary(
|
||||
storagePath,
|
||||
finalBytes,
|
||||
fileOptions: FileOptions(contentType: _guessContentType(extension)),
|
||||
fileOptions: FileOptions(
|
||||
contentType: _guessContentType(extension),
|
||||
upsert: true,
|
||||
),
|
||||
);
|
||||
|
||||
// 5. Creiamo la mappa per il DB dinamicamente
|
||||
@@ -185,10 +221,17 @@ class AttachmentsRepository {
|
||||
// B. Nessuno usa più questo file! ELIMINAZIONE FISICA TOTALE.
|
||||
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
|
||||
|
||||
if (file.storagePath != null) {
|
||||
await _supabase.storage.from(bucket.value).remove([
|
||||
final pathsToRemove = <String>[
|
||||
if (file.storagePath != null && file.storagePath!.isNotEmpty)
|
||||
file.storagePath!,
|
||||
]);
|
||||
if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty)
|
||||
file.thumbnailPath!,
|
||||
if (file.croppedStoragePath != null &&
|
||||
file.croppedStoragePath!.isNotEmpty)
|
||||
file.croppedStoragePath!,
|
||||
];
|
||||
if (pathsToRemove.isNotEmpty) {
|
||||
await _supabase.storage.from(bucket.value).remove(pathsToRemove);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,7 +259,6 @@ class AttachmentsRepository {
|
||||
required String targetId,
|
||||
}) async {
|
||||
try {
|
||||
// Facciamo un semplice UPDATE aggiungendo l'ID nella colonna giusta
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({targetType.dbColumn: targetId})
|
||||
@@ -226,9 +268,107 @@ class AttachmentsRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// AGGIORNA LA MODALITÀ DI VISUALIZZAZIONE PREFERITA (cropped / original)
|
||||
Future<void> updateAttachmentViewMode(
|
||||
String fileId,
|
||||
AttachmentViewMode viewMode,
|
||||
) async {
|
||||
try {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'view_mode': viewMode.value})
|
||||
.eq('id', fileId);
|
||||
} catch (e) {
|
||||
throw Exception(
|
||||
"Errore nell'aggiornamento della modalità di visualizzazione: $e",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Salva la rotazione permanente del file originale aggiornando storage_path con un nuovo timestamp.
|
||||
/// Questo farà scattare il trigger Postgres per il worker Python (autocrop e thumbnail).
|
||||
Future<AttachmentModel> rotateAttachment({
|
||||
required AttachmentModel attachment,
|
||||
required int quarterTurns,
|
||||
required Bucket bucket,
|
||||
}) async {
|
||||
final turns = quarterTurns % 4;
|
||||
if (turns == 0) return attachment;
|
||||
if (attachment.storagePath == null || attachment.storagePath!.isEmpty) {
|
||||
throw Exception("Impossibile ruotare: storagePath mancante.");
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Recuperiamo i byte originali
|
||||
Uint8List originalBytes;
|
||||
if (attachment.localBytes != null) {
|
||||
originalBytes = attachment.localBytes!;
|
||||
} else {
|
||||
originalBytes = await downloadAttachmentBytes(
|
||||
storagePath: attachment.storagePath!,
|
||||
bucket: bucket,
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Ruotiamo fisicamente i pixel
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
originalBytes,
|
||||
quarterTurns: turns,
|
||||
extension: attachment.extension,
|
||||
);
|
||||
|
||||
// 3. Generiamo il nuovo storagePath con un nuovo timestamp per evitare cache e triggerare l'update
|
||||
final oldPath = attachment.storagePath!;
|
||||
final lastSlash = oldPath.lastIndexOf('/');
|
||||
final dir = lastSlash != -1 ? oldPath.substring(0, lastSlash) : '';
|
||||
final filename =
|
||||
lastSlash != -1 ? oldPath.substring(lastSlash + 1) : oldPath;
|
||||
final nameWithoutTimestamp =
|
||||
filename.replaceFirst(RegExp(r'^\d+_'), '');
|
||||
final newTimestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final newStoragePath = dir.isNotEmpty
|
||||
? '$dir/${newTimestamp}_$nameWithoutTimestamp'
|
||||
: '${newTimestamp}_$nameWithoutTimestamp';
|
||||
|
||||
// 4. Carichiamo il nuovo file ruotato nello storage
|
||||
await _supabase.storage
|
||||
.from(bucket.value)
|
||||
.uploadBinary(
|
||||
newStoragePath,
|
||||
rotatedBytes,
|
||||
fileOptions: FileOptions(
|
||||
contentType: _guessContentType(attachment.extension),
|
||||
upsert: true,
|
||||
),
|
||||
);
|
||||
|
||||
// 5. Aggiorniamo il record su Postgres (triggera il worker Python)
|
||||
final updateData = {
|
||||
'storage_path': newStoragePath,
|
||||
'file_size': rotatedBytes.length,
|
||||
};
|
||||
|
||||
if (attachment.id != null) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update(updateData)
|
||||
.eq('id', attachment.id!);
|
||||
}
|
||||
|
||||
// 6. Restituiamo il modello aggiornato
|
||||
return attachment.copyWith(
|
||||
storagePath: newStoragePath,
|
||||
fileSize: rotatedBytes.length,
|
||||
localBytes: rotatedBytes,
|
||||
);
|
||||
} catch (e) {
|
||||
throw Exception("Errore durante il salvataggio della rotazione: $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper per indovinare il content-type base
|
||||
String _guessContentType(String extension) {
|
||||
switch (extension.toLowerCase()) {
|
||||
switch (extension.toLowerCase().replaceAll('.', '')) {
|
||||
case 'pdf':
|
||||
return 'application/pdf';
|
||||
case 'png':
|
||||
@@ -236,6 +376,28 @@ class AttachmentsRepository {
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return 'image/jpeg';
|
||||
case 'webp':
|
||||
return 'image/webp';
|
||||
case 'heic':
|
||||
return 'image/heic';
|
||||
case 'heif':
|
||||
return 'image/heif';
|
||||
case 'gif':
|
||||
return 'image/gif';
|
||||
case 'svg':
|
||||
return 'image/svg+xml';
|
||||
case 'txt':
|
||||
return 'text/plain';
|
||||
case 'csv':
|
||||
return 'text/csv';
|
||||
case 'doc':
|
||||
return 'application/msword';
|
||||
case 'docx':
|
||||
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
case 'xls':
|
||||
return 'application/vnd.ms-excel';
|
||||
case 'xlsx':
|
||||
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
|
||||
@@ -2,6 +2,22 @@ import 'dart:typed_data';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
enum AttachmentViewMode {
|
||||
cropped('cropped'),
|
||||
original('original');
|
||||
|
||||
final String value;
|
||||
const AttachmentViewMode(this.value);
|
||||
|
||||
static AttachmentViewMode? fromString(String? val) {
|
||||
if (val == null) return null;
|
||||
final clean = val.trim().toLowerCase();
|
||||
if (clean == 'cropped') return AttachmentViewMode.cropped;
|
||||
if (clean == 'original') return AttachmentViewMode.original;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class AttachmentModel extends Equatable {
|
||||
final String? id;
|
||||
final DateTime? createdAt;
|
||||
@@ -13,6 +29,9 @@ class AttachmentModel extends Equatable {
|
||||
final String name;
|
||||
final String extension;
|
||||
final String? storagePath;
|
||||
final String? thumbnailPath;
|
||||
final String? croppedStoragePath;
|
||||
final AttachmentViewMode? viewMode;
|
||||
final int fileSize;
|
||||
final Uint8List? localBytes;
|
||||
final String companyId;
|
||||
@@ -28,11 +47,21 @@ class AttachmentModel extends Equatable {
|
||||
required this.name,
|
||||
required this.extension,
|
||||
this.storagePath,
|
||||
this.thumbnailPath,
|
||||
this.croppedStoragePath,
|
||||
this.viewMode,
|
||||
required this.fileSize,
|
||||
this.localBytes,
|
||||
required this.companyId,
|
||||
});
|
||||
|
||||
factory AttachmentModel.empty() => const AttachmentModel(
|
||||
name: '',
|
||||
extension: '',
|
||||
fileSize: 0,
|
||||
companyId: '',
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
@@ -45,6 +74,9 @@ class AttachmentModel extends Equatable {
|
||||
name,
|
||||
extension,
|
||||
storagePath,
|
||||
thumbnailPath,
|
||||
croppedStoragePath,
|
||||
viewMode,
|
||||
fileSize,
|
||||
localBytes,
|
||||
companyId,
|
||||
@@ -54,6 +86,25 @@ class AttachmentModel extends Equatable {
|
||||
|
||||
bool get isPdf => extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
String? get effectiveStoragePath {
|
||||
if (viewMode == AttachmentViewMode.cropped) {
|
||||
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
|
||||
return croppedStoragePath;
|
||||
}
|
||||
return storagePath;
|
||||
} else if (viewMode == AttachmentViewMode.original) {
|
||||
if (storagePath != null && storagePath!.isNotEmpty) {
|
||||
return storagePath;
|
||||
}
|
||||
return croppedStoragePath;
|
||||
}
|
||||
// Default fallback quando viewMode non è specificato
|
||||
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
|
||||
return croppedStoragePath;
|
||||
}
|
||||
return storagePath;
|
||||
}
|
||||
|
||||
String get sizeFormatted {
|
||||
if (fileSize <= 0) return "0 B";
|
||||
const suffixes = ["B", "KB", "MB", "GB", "TB"];
|
||||
@@ -74,6 +125,9 @@ class AttachmentModel extends Equatable {
|
||||
String? name,
|
||||
String? extension,
|
||||
String? storagePath,
|
||||
String? thumbnailPath,
|
||||
String? croppedStoragePath,
|
||||
AttachmentViewMode? viewMode,
|
||||
int? fileSize,
|
||||
Uint8List? localBytes,
|
||||
String? companyId,
|
||||
@@ -88,6 +142,9 @@ class AttachmentModel extends Equatable {
|
||||
name: name ?? this.name,
|
||||
extension: extension ?? this.extension,
|
||||
storagePath: storagePath ?? this.storagePath,
|
||||
thumbnailPath: thumbnailPath ?? this.thumbnailPath,
|
||||
croppedStoragePath: croppedStoragePath ?? this.croppedStoragePath,
|
||||
viewMode: viewMode ?? this.viewMode,
|
||||
fileSize: fileSize ?? this.fileSize,
|
||||
localBytes: localBytes ?? this.localBytes,
|
||||
companyId: companyId ?? this.companyId,
|
||||
@@ -107,6 +164,9 @@ class AttachmentModel extends Equatable {
|
||||
name: map['name'] as String,
|
||||
extension: map['extension'] as String,
|
||||
storagePath: map['storage_path'] as String?,
|
||||
thumbnailPath: map['thumbnail_path'] as String?,
|
||||
croppedStoragePath: map['cropped_storage_path'] as String?,
|
||||
viewMode: AttachmentViewMode.fromString(map['view_mode'] as String?),
|
||||
fileSize: map['file_size'] is int
|
||||
? map['file_size']
|
||||
: int.tryParse(map['file_size']?.toString() ?? '0') ?? 0,
|
||||
@@ -127,6 +187,9 @@ class AttachmentModel extends Equatable {
|
||||
'note_id': noteId,
|
||||
'file_size': fileSize,
|
||||
'company_id': companyId,
|
||||
'thumbnail_path': thumbnailPath,
|
||||
'cropped_storage_path': croppedStoragePath,
|
||||
'view_mode': (viewMode ?? AttachmentViewMode.original).value,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:flux/core/utils/functions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:pdfrx/pdfrx.dart';
|
||||
import 'package:internet_file/internet_file.dart';
|
||||
@@ -14,6 +21,8 @@ class AttachmentViewerScreen extends StatefulWidget {
|
||||
final Function(AttachmentModel attachment, String newName)? onRenameAttachment;
|
||||
final VoidCallback? onDelete;
|
||||
final Function(AttachmentModel attachment)? onDeleteAttachment;
|
||||
final Function(AttachmentModel attachment, AttachmentViewMode viewMode)? onViewModeChanged;
|
||||
final Function(AttachmentModel attachment)? onAttachmentUpdated;
|
||||
|
||||
const AttachmentViewerScreen({
|
||||
super.key,
|
||||
@@ -24,6 +33,8 @@ class AttachmentViewerScreen extends StatefulWidget {
|
||||
this.onRenameAttachment,
|
||||
this.onDelete,
|
||||
this.onDeleteAttachment,
|
||||
this.onViewModeChanged,
|
||||
this.onAttachmentUpdated,
|
||||
}) : assert(
|
||||
attachment != null || (attachments != null && attachments.length > 0),
|
||||
'Devi fornire un allegato o una lista di allegati non vuota.',
|
||||
@@ -39,10 +50,13 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
bool _isLoading = true;
|
||||
bool _isSavingRotation = false;
|
||||
String? _errorMessage;
|
||||
Uint8List? _fileBytes;
|
||||
int _loadToken = 0;
|
||||
int _rotationTurns = 0;
|
||||
bool _showCropped = true;
|
||||
final Map<String, Uint8List> _bytesCache = {};
|
||||
|
||||
AttachmentModel get _currentAttachment => _items[_currentIndex];
|
||||
bool get isPdf =>
|
||||
@@ -51,6 +65,33 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
bool get canGoPrevious => _currentIndex > 0;
|
||||
bool get canGoNext => _currentIndex < _items.length - 1;
|
||||
|
||||
bool get _hasCropped =>
|
||||
_currentAttachment.croppedStoragePath != null &&
|
||||
_currentAttachment.croppedStoragePath!.isNotEmpty;
|
||||
bool get _hasOriginal =>
|
||||
_currentAttachment.storagePath != null &&
|
||||
_currentAttachment.storagePath!.isNotEmpty;
|
||||
bool get canToggleCrop => !isPdf && _hasCropped && _hasOriginal;
|
||||
|
||||
String? get _activeStoragePath {
|
||||
final item = _currentAttachment;
|
||||
if (_showCropped && _hasCropped) {
|
||||
return item.croppedStoragePath;
|
||||
}
|
||||
return item.storagePath;
|
||||
}
|
||||
|
||||
bool _computeInitialShowCropped(AttachmentModel attachment) {
|
||||
if (attachment.viewMode == AttachmentViewMode.original) {
|
||||
return false;
|
||||
}
|
||||
if (attachment.viewMode == AttachmentViewMode.cropped) {
|
||||
return true;
|
||||
}
|
||||
return attachment.croppedStoragePath != null &&
|
||||
attachment.croppedStoragePath!.isNotEmpty;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -65,6 +106,10 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
_currentIndex = 0;
|
||||
}
|
||||
|
||||
if (_items.isNotEmpty) {
|
||||
_showCropped = _computeInitialShowCropped(_currentAttachment);
|
||||
}
|
||||
|
||||
_loadFile();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@@ -92,8 +137,10 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
|
||||
void _changeFile(int newIndex) {
|
||||
if (newIndex < 0 || newIndex >= _items.length) return;
|
||||
final newAttachment = _items[newIndex];
|
||||
setState(() {
|
||||
_currentIndex = newIndex;
|
||||
_showCropped = _computeInitialShowCropped(newAttachment);
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
_fileBytes = null;
|
||||
@@ -102,6 +149,104 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
_loadFile();
|
||||
}
|
||||
|
||||
void _toggleCropView() {
|
||||
if (!canToggleCrop) return;
|
||||
final nextShowCropped = !_showCropped;
|
||||
final nextMode = nextShowCropped
|
||||
? AttachmentViewMode.cropped
|
||||
: AttachmentViewMode.original;
|
||||
final nextPath = nextShowCropped
|
||||
? _currentAttachment.croppedStoragePath
|
||||
: _currentAttachment.storagePath;
|
||||
|
||||
final updatedAttachment = _currentAttachment.copyWith(viewMode: nextMode);
|
||||
|
||||
setState(() {
|
||||
_showCropped = nextShowCropped;
|
||||
_items[_currentIndex] = updatedAttachment;
|
||||
_rotationTurns = 0;
|
||||
});
|
||||
|
||||
if (widget.onViewModeChanged != null) {
|
||||
widget.onViewModeChanged!(updatedAttachment, nextMode);
|
||||
} else if (updatedAttachment.id != null) {
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
repository.updateAttachmentViewMode(updatedAttachment.id!, nextMode);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (nextPath != null && _bytesCache.containsKey(nextPath)) {
|
||||
setState(() {
|
||||
_fileBytes = _bytesCache[nextPath];
|
||||
_isLoading = false;
|
||||
_errorMessage = null;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
_loadFile();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _saveRotation() async {
|
||||
final turns = _rotationTurns % 4;
|
||||
if (turns == 0 || _isSavingRotation) return;
|
||||
|
||||
setState(() {
|
||||
_isSavingRotation = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final updated = await repository.rotateAttachment(
|
||||
attachment: _currentAttachment,
|
||||
quarterTurns: turns,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
_items[_currentIndex] = updated;
|
||||
_rotationTurns = 0;
|
||||
_showCropped = false; // Mostra l'originale ruotato appena salvato
|
||||
_isSavingRotation = false;
|
||||
if (updated.storagePath != null && updated.localBytes != null) {
|
||||
_bytesCache[updated.storagePath!] = updated.localBytes!;
|
||||
}
|
||||
if (updated.localBytes != null) {
|
||||
_fileBytes = updated.localBytes;
|
||||
}
|
||||
});
|
||||
|
||||
widget.onAttachmentUpdated?.call(updated);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Rotazione salvata! Il server aggiornerà ritaglio e anteprima.',
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
duration: Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isSavingRotation = false;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Errore durante il salvataggio della rotazione: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyDownEvent) {
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
|
||||
@@ -127,18 +272,47 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
Uint8List? bytes;
|
||||
if (item.localBytes != null) {
|
||||
bytes = item.localBytes;
|
||||
} else if (item.storagePath != null &&
|
||||
item.storagePath!.isNotEmpty) {
|
||||
final signedUrl = await getSignedUrl(item.storagePath!);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
final path = _activeStoragePath;
|
||||
if (path != null && path.isNotEmpty) {
|
||||
if (_bytesCache.containsKey(path)) {
|
||||
bytes = _bytesCache[path];
|
||||
} else {
|
||||
try {
|
||||
final signedUrl = await getSignedUrl(path);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
} catch (e) {
|
||||
// Se fallisce il ritaglio e abbiamo l'originale, proviamo l'originale come fallback
|
||||
if (_showCropped && _hasOriginal && item.storagePath != path) {
|
||||
final signedUrl = await getSignedUrl(item.storagePath!);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
_showCropped = false;
|
||||
} else {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isPdf) {
|
||||
bytes = ImageUtils.normalizeOrientation(
|
||||
bytes,
|
||||
extension: item.extension,
|
||||
);
|
||||
}
|
||||
|
||||
_bytesCache[path] = bytes;
|
||||
}
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
}
|
||||
}
|
||||
|
||||
if (token != _loadToken || !mounted) return;
|
||||
|
||||
if (bytes != null && !isPdf) {
|
||||
bytes = ImageUtils.normalizeOrientation(bytes, extension: item.extension);
|
||||
if (bytes != null && !isPdf && item.localBytes != null) {
|
||||
bytes = ImageUtils.normalizeOrientation(
|
||||
bytes,
|
||||
extension: item.extension,
|
||||
);
|
||||
}
|
||||
|
||||
setState(() {
|
||||
@@ -248,6 +422,56 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _downloadCurrentFile() async {
|
||||
final bytes = _fileBytes;
|
||||
if (bytes == null || bytes.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('File non ancora caricato o non disponibile.'),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
String fullName = _currentAttachment.name;
|
||||
final ext = _currentAttachment.extension.toLowerCase().replaceAll('.', '');
|
||||
if (_showCropped && canToggleCrop) {
|
||||
fullName = '${fullName}_cropped';
|
||||
}
|
||||
if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) {
|
||||
fullName = '$fullName.$ext';
|
||||
}
|
||||
|
||||
if (kIsWeb) {
|
||||
final blob = html.Blob([bytes]);
|
||||
final url = html.Url.createObjectUrlFromBlob(blob);
|
||||
html.AnchorElement(href: url)
|
||||
..setAttribute('download', fullName)
|
||||
..click();
|
||||
html.Url.revokeObjectUrl(url);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Download avviato: $fullName')),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
final savePath = await FilePicker.saveFile(
|
||||
dialogTitle: 'Salva file',
|
||||
fileName: fullName,
|
||||
bytes: bytes,
|
||||
);
|
||||
if (savePath != null) {
|
||||
final targetFile = File(savePath);
|
||||
await targetFile.writeAsBytes(bytes);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('File salvato in: $savePath')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Focus(
|
||||
@@ -268,14 +492,64 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
style: const TextStyle(fontSize: 16),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (hasMultipleFiles)
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (hasMultipleFiles) ...[
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
if (canToggleCrop)
|
||||
const Text(
|
||||
' • ',
|
||||
style: TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
],
|
||||
if (canToggleCrop)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: _showCropped
|
||||
? Colors.amber.withValues(alpha: 0.2)
|
||||
: Colors.white10,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(
|
||||
color: _showCropped
|
||||
? Colors.amberAccent
|
||||
: Colors.white30,
|
||||
width: 0.8,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
_showCropped ? 'Ritaglio automatico' : 'Originale',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: _showCropped
|
||||
? Colors.amberAccent
|
||||
: Colors.white70,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
if (canToggleCrop)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
_showCropped
|
||||
? Icons.photo_size_select_actual_outlined
|
||||
: Icons.crop,
|
||||
color: _showCropped ? Colors.amberAccent : Colors.white,
|
||||
),
|
||||
tooltip: _showCropped
|
||||
? 'Passa alla foto originale'
|
||||
: 'Passa al ritaglio automatico',
|
||||
onPressed: _toggleCropView,
|
||||
),
|
||||
if (!isPdf)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.rotate_right),
|
||||
@@ -286,6 +560,43 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!isPdf && _rotationTurns % 4 != 0)
|
||||
_isSavingRotation
|
||||
? const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 10),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
|
||||
child: FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.green.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: const Icon(Icons.check, size: 16),
|
||||
label: const Text(
|
||||
'Salva',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
onPressed: _saveRotation,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
tooltip: 'Scarica',
|
||||
onPressed: _downloadCurrentFile,
|
||||
),
|
||||
if (widget.onRename != null || widget.onRenameAttachment != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
|
||||
@@ -352,7 +352,9 @@ class _FileCard extends StatelessWidget {
|
||||
height: MediaQuery.of(context).size.height * 0.8,
|
||||
child: file.isPdf
|
||||
? PdfViewerWidget(storagePath: file.storagePath)
|
||||
: ImageViewerWidget(storagePath: file.storagePath),
|
||||
: ImageViewerWidget(
|
||||
storagePath: file.effectiveStoragePath,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
+3
-2
@@ -207,8 +207,9 @@ class _ExpiringContractsCardContent extends StatelessWidget {
|
||||
.map((d) {
|
||||
final tLabel = d.type?.shortLabel ?? d.type?.value ?? '';
|
||||
final sub = d.subType?.trim() ?? '';
|
||||
if (sub.isNotEmpty) return '$tLabel: $sub';
|
||||
return tLabel;
|
||||
final base = sub.isNotEmpty ? '$tLabel: $sub' : tLabel;
|
||||
if (base.isEmpty) return '';
|
||||
return d.quantity > 1 ? '$base ×${d.quantity}' : base;
|
||||
})
|
||||
.where((l) => l.isNotEmpty)
|
||||
.toList();
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.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/targets/models/target_progress_model.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -524,6 +525,29 @@ class _DashboardTargetHeroCardState extends State<DashboardTargetHeroCard> {
|
||||
);
|
||||
}
|
||||
|
||||
void _navigateToOperationsForCategory(
|
||||
CategoryProgress category, {
|
||||
bool isManager = false,
|
||||
}) {
|
||||
final state = context.read<DashboardTargetProgressCubit>().state;
|
||||
final target = state.target;
|
||||
if (target == null) return;
|
||||
|
||||
final staffId = isManager ? null : state.currentStaffId;
|
||||
|
||||
final params = OperationFilterParams.fromTargetCategory(
|
||||
categoryKey: category.key,
|
||||
categoryLabel: category.label,
|
||||
target: target,
|
||||
staffId: staffId,
|
||||
);
|
||||
|
||||
context.pushNamed(
|
||||
Routes.operations,
|
||||
extra: params,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryDailyPacingCard(
|
||||
ThemeData theme,
|
||||
CategoryProgress category, {
|
||||
@@ -534,67 +558,89 @@ class _DashboardTargetHeroCardState extends State<DashboardTargetHeroCard> {
|
||||
final isAchieved = category.isAchieved;
|
||||
final hasS2 = category.targetS2 > 0;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
return Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(
|
||||
color: pacingTheme.border.withValues(alpha: 0.7),
|
||||
width: 1.2,
|
||||
onTap: () => _navigateToOperationsForCategory(
|
||||
category,
|
||||
isManager: isManager,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: pacingTheme.primary.withValues(alpha: 0.04),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header tessera: Nome metrica + Pillola di stato
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
category.label.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
letterSpacing: 0.3,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: pacingTheme.background,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: pacingTheme.border, width: 0.8),
|
||||
),
|
||||
child: Text(
|
||||
isAchieved
|
||||
? 'Preso! 🎉'
|
||||
: (category.status == TargetPacingStatus.inLineS1 ||
|
||||
category.status == TargetPacingStatus.inLineS2
|
||||
? 'In linea ✅'
|
||||
: (category.status == TargetPacingStatus.recoverable
|
||||
? 'Da spingere ⚡'
|
||||
: 'In ritardo 🔴')),
|
||||
style: TextStyle(
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: pacingTheme.text,
|
||||
),
|
||||
),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(
|
||||
color: pacingTheme.border.withValues(alpha: 0.7),
|
||||
width: 1.2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: pacingTheme.primary.withValues(alpha: 0.04),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header tessera: Nome metrica + Pillola di stato
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
category.label.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
letterSpacing: 0.3,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: pacingTheme.background,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: pacingTheme.border, width: 0.8),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
isAchieved
|
||||
? 'Preso! 🎉'
|
||||
: (category.status == TargetPacingStatus.inLineS1 ||
|
||||
category.status ==
|
||||
TargetPacingStatus.inLineS2
|
||||
? 'In linea ✅'
|
||||
: (category.status ==
|
||||
TargetPacingStatus.recoverable
|
||||
? 'Da spingere ⚡'
|
||||
: 'In ritardo 🔴')),
|
||||
style: TextStyle(
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: pacingTheme.text,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Icon(
|
||||
Icons.arrow_forward_ios,
|
||||
size: 8,
|
||||
color: pacingTheme.text,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
@@ -757,7 +803,9 @@ class _DashboardTargetHeroCardState extends State<DashboardTargetHeroCard> {
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInLineSummaryBanner(
|
||||
|
||||
@@ -40,8 +40,11 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
|
||||
String? modelId,
|
||||
String? description,
|
||||
DateTime? expirationDate,
|
||||
int? quantity,
|
||||
}) {
|
||||
final current = state.operationDetail;
|
||||
final sanitizedQuantity =
|
||||
quantity != null ? (quantity < 1 ? 1 : quantity) : current.quantity;
|
||||
final updated = current.copyWith(
|
||||
type: type ?? current.type,
|
||||
subType: subType ?? current.subType,
|
||||
@@ -56,6 +59,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
|
||||
modelId: modelId ?? current.modelId,
|
||||
description: description ?? current.description,
|
||||
expirationDate: expirationDate ?? current.expirationDate,
|
||||
quantity: sanitizedQuantity,
|
||||
);
|
||||
|
||||
emit(
|
||||
@@ -111,6 +115,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
|
||||
final updated = current.copyWith(
|
||||
type: newType,
|
||||
subType: newType == OperationType.energy ? EnergySubtypes.luce : null,
|
||||
quantity: newType.supportsQuantity ? current.quantity : 1,
|
||||
provider: selectedProvider != null ? () => selectedProvider : null,
|
||||
providerId: selectedProvider?.id,
|
||||
);
|
||||
|
||||
@@ -94,4 +94,22 @@ class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Aggiorna la quantità/valore di un dettaglio esistente (minimo 1)
|
||||
void updateOperationDetailQuantity(int index, int newQuantity) {
|
||||
if (index < 0 || index >= state.details.length) return;
|
||||
final clamped = newQuantity < 1 ? 1 : newQuantity;
|
||||
if (state.details[index].quantity == clamped) return;
|
||||
|
||||
emit(state.copyWith(status: OperationDetailsListStatus.ready));
|
||||
final updatedDetails = List<OperationDetailModel>.from(state.details);
|
||||
updatedDetails[index] = updatedDetails[index].copyWith(quantity: clamped);
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: updatedDetails,
|
||||
selectedIds: state.selectedIds,
|
||||
status: OperationDetailsListStatus.updated,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
@@ -54,6 +54,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 +71,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 +85,7 @@ class OperationsRepository {
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*),
|
||||
${Tables.operationDetails}(
|
||||
${Tables.operationDetails}$detailJoin(
|
||||
*,
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(*)
|
||||
@@ -87,25 +97,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 = [];
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
class FinancingTranslations {
|
||||
static const List<FinancingLanguage> supportedLanguages = [
|
||||
FinancingLanguage(code: 'it', name: 'Italiano', flag: '🇮🇹', isRtl: false),
|
||||
FinancingLanguage(code: 'en', name: 'English', flag: '🇬🇧', isRtl: false),
|
||||
FinancingLanguage(code: 'fr', name: 'Français', flag: '🇫🇷', isRtl: false),
|
||||
FinancingLanguage(code: 'es', name: 'Español', flag: '🇪🇸', isRtl: false),
|
||||
FinancingLanguage(code: 'ar', name: 'العربية', flag: '🇸🇦', isRtl: true),
|
||||
FinancingLanguage(code: 'uk', name: 'Українська', flag: '🇺🇦', isRtl: false),
|
||||
FinancingLanguage(code: 'ru', name: 'Русский', flag: '🇷🇺', isRtl: false),
|
||||
FinancingLanguage(code: 'mk', name: 'Македонски', flag: '🇲🇰', isRtl: false),
|
||||
FinancingLanguage(code: 'sq', name: 'Shqip', flag: '🇦🇱', isRtl: false),
|
||||
];
|
||||
|
||||
static const List<String> canonicalMaritalStatuses = [
|
||||
'Celibe / Nubile',
|
||||
'Coniugato/a',
|
||||
'Separato/a',
|
||||
'Divorziato/a',
|
||||
'Vedovo/a',
|
||||
];
|
||||
|
||||
static const List<String> canonicalIncomeRanges = [
|
||||
'Fino a 2.000 €',
|
||||
'Da 2.000 € a 5.000 €',
|
||||
'Oltre 5.000 €',
|
||||
];
|
||||
|
||||
static FinancingStrings getStrings(String langCode) {
|
||||
switch (langCode) {
|
||||
case 'en':
|
||||
return const FinancingStrings(
|
||||
title: 'Financing Details',
|
||||
subtitle: 'Please fill in the information below required for your financing application.',
|
||||
maritalStatusLabel: 'Marital Status',
|
||||
maritalOptions: ['Single', 'Married', 'Separated', 'Divorced', 'Widowed'],
|
||||
occupationLabel: 'Occupation',
|
||||
occupationHint: 'e.g. Employee, Factory Worker, Self-employed...',
|
||||
incomeLabel: 'Net Monthly Income',
|
||||
incomeOptions: ['Up to €2,000', 'From €2,000 to €5,000', 'Over €5,000'],
|
||||
submitButton: 'Submit Information',
|
||||
errorRequired: 'Please complete all fields before submitting.',
|
||||
successTitle: 'Information Submitted!',
|
||||
successSubtitle: 'Thank you! Your information has been safely received by our store. You can close this page.',
|
||||
);
|
||||
case 'fr':
|
||||
return const FinancingStrings(
|
||||
title: 'Informations de Financement',
|
||||
subtitle: 'Veuillez renseigner les informations requises pour votre demande de financement.',
|
||||
maritalStatusLabel: 'État Civil',
|
||||
maritalOptions: ['Célibataire', 'Marié(e)', 'Séparé(e)', 'Divorcé(e)', 'Veuf / Veuve'],
|
||||
occupationLabel: 'Profession',
|
||||
occupationHint: 'Ex. Employé, Ouvrier, Artisan, Indépendant...',
|
||||
incomeLabel: 'Revenu Mensuel Net',
|
||||
incomeOptions: ['Jusqu\'à 2 000 €', 'De 2 000 € à 5 000 €', 'Plus de 5 000 €'],
|
||||
submitButton: 'Envoyer les données',
|
||||
errorRequired: 'Veuillez remplir tous les champs avant de soumettre.',
|
||||
successTitle: 'Données transmises avec succès !',
|
||||
successSubtitle: 'Merci ! Les informations ont été reçues par notre conseiller. Vous pouvez fermer cette page.',
|
||||
);
|
||||
case 'es':
|
||||
return const FinancingStrings(
|
||||
title: 'Datos para Financiación',
|
||||
subtitle: 'Completa los siguientes datos necesarios para la solicitud de financiación.',
|
||||
maritalStatusLabel: 'Estado Civil',
|
||||
maritalOptions: ['Soltero/a', 'Casado/a', 'Separado/a', 'Divorciado/a', 'Viudo/a'],
|
||||
occupationLabel: 'Profesión',
|
||||
occupationHint: 'Ej. Empleado, Obrero, Autónomo, Comerciante...',
|
||||
incomeLabel: 'Ingreso Mensual Neto',
|
||||
incomeOptions: ['Hasta 2.000 €', 'De 2.000 € a 5.000 €', 'Más de 5.000 €'],
|
||||
submitButton: 'Enviar Datos',
|
||||
errorRequired: 'Por favor, completa todos los campos antes de enviar.',
|
||||
successTitle: '¡Datos enviados con éxito!',
|
||||
successSubtitle: '¡Gracias! Nuestro asesor ha recibido tus datos. Ya puedes cerrar esta pantalla.',
|
||||
);
|
||||
case 'ar':
|
||||
return const FinancingStrings(
|
||||
title: 'بيانات التمويل',
|
||||
subtitle: 'يرجى تعبئة البيانات التالية المطلوبة لإتمام معاملة التمويل.',
|
||||
maritalStatusLabel: 'الحالة الاجتماعية',
|
||||
maritalOptions: ['أعزب / عزباء', 'متزوج / متزوجة', 'منفصل / منفصلة', 'مطلق / مطلقة', 'أرمل / أرملة'],
|
||||
occupationLabel: 'المهنة',
|
||||
occupationHint: 'مثال: موظف، عامل، تاجر، عمل حر...',
|
||||
incomeLabel: 'الدخل الشهري الصافي',
|
||||
incomeOptions: ['حتى 2,000 يورو', 'من 2,000 إلى 5,000 يورو', 'أكثر من 5,000 يورو'],
|
||||
submitButton: 'إرسال البيانات',
|
||||
errorRequired: 'يرجى ملء جميع الحقول قبل الإرسال.',
|
||||
successTitle: 'تم إرسال البيانات بنجاح!',
|
||||
successSubtitle: 'شكراً لك! لقد استلم موظفنا البيانات بنجاح. يمكنك إغلاق هذه الصفحة الآن.',
|
||||
);
|
||||
case 'uk':
|
||||
return const FinancingStrings(
|
||||
title: 'Дані для фінансування',
|
||||
subtitle: 'Будь ласка, заповніть наступні дані, необхідні для оформлення фінансування.',
|
||||
maritalStatusLabel: 'Сімейний стан',
|
||||
maritalOptions: ['Неодружений / Незаміжня', 'Одружений / Заміжня', 'Розлучений / Розлучена', 'Проживає окремо', 'Вдівець / Вдова'],
|
||||
occupationLabel: 'Професія / Посада',
|
||||
occupationHint: 'Наприклад: Службовець, Робітник, ФОП...',
|
||||
incomeLabel: 'Чистий щомісячний дохід',
|
||||
incomeOptions: ['До 2 000 €', 'Від 2 000 € до 5 000 €', 'Понад 5 000 €'],
|
||||
submitButton: 'Надіслати дані',
|
||||
errorRequired: 'Будь ласка, заповніть усі поля перед відправленням.',
|
||||
successTitle: 'Дані успішно надіслано!',
|
||||
successSubtitle: 'Дякуємо! Наш фахівець отримав ваші дані. Ви можете закрити цю сторінку.',
|
||||
);
|
||||
case 'ru':
|
||||
return const FinancingStrings(
|
||||
title: 'Данные для финансирования',
|
||||
subtitle: 'Пожалуйста, заполните следующие данные, необходимые для оформления финансирования.',
|
||||
maritalStatusLabel: 'Семейное положение',
|
||||
maritalOptions: ['Холост / Не замужем', 'Женат / Замужем', 'Проживает раздельно', 'Разведен / Разведена', 'Вдовец / Вдова'],
|
||||
occupationLabel: 'Профессия / Должность',
|
||||
occupationHint: 'Например: Служащий, Рабочий, Предприниматель...',
|
||||
incomeLabel: 'Чистый ежемесячный доход',
|
||||
incomeOptions: ['До 2 000 €', 'От 2 000 € до 5 000 €', 'Более 5 000 €'],
|
||||
submitButton: 'Отправить данные',
|
||||
errorRequired: 'Пожалуйста, заполните все поля перед отправкой.',
|
||||
successTitle: 'Данные успешно отправлены!',
|
||||
successSubtitle: 'Спасибо! Наш сотрудник получил ваши данные. Вы можете закрыть эту страницу.',
|
||||
);
|
||||
case 'mk':
|
||||
return const FinancingStrings(
|
||||
title: 'Податоци за финансирање',
|
||||
subtitle: 'Ве молиме пополнете ги следните податоци потребни за апликацијата за финансирање.',
|
||||
maritalStatusLabel: 'Брачна состојба',
|
||||
maritalOptions: ['Неженет / Немажена', 'Оженет / Мажена', 'Разделен / Разделена', 'Разведен / Разведена', 'Вдовец / Вдовица'],
|
||||
occupationLabel: 'Професија',
|
||||
occupationHint: 'Пр. Вработен, Работник, Трговец...',
|
||||
incomeLabel: 'Нето месечен приход',
|
||||
incomeOptions: ['До 2.000 €', 'Од 2.000 € до 5.000 €', 'Над 5.000 €'],
|
||||
submitButton: 'Испрати податоци',
|
||||
errorRequired: 'Ве молиме пополнете ги сите полиња пред испраќање.',
|
||||
successTitle: 'Податоците се успешно испратени!',
|
||||
successSubtitle: 'Ви благодариме! Нашиот оператор ги прими вашите податоци. Можете да го затворите овој прозорец.',
|
||||
);
|
||||
case 'sq':
|
||||
return const FinancingStrings(
|
||||
title: 'Të dhënat për Financim',
|
||||
subtitle: 'Ju lutemi plotësoni të dhënat e mëposhtme të nevojshme për kërkesën për financim.',
|
||||
maritalStatusLabel: 'Gjendja Civile',
|
||||
maritalOptions: ['Beqar / Beqare', 'I/E martuar', 'I/E ndarë', 'I/E divorcuar', 'I/E ve'],
|
||||
occupationLabel: 'Profesioni',
|
||||
occupationHint: 'P.sh. Punonjës, Punëtor, Tregtar, Vetëpunësuar...',
|
||||
incomeLabel: 'Të Ardhurat Mujore Neto',
|
||||
incomeOptions: ['Deri në 2.000 €', 'Nga 2.000 € në 5.000 €', 'Mbi 5.000 €'],
|
||||
submitButton: 'Dërgo të Dhënat',
|
||||
errorRequired: 'Ju lutemi plotësoni të gjitha fushat para dërgimit.',
|
||||
successTitle: 'Të dhënat u dërguan me sukses!',
|
||||
successSubtitle: 'Faleminderit! Operatori ynë i pranoi të dhënat tuaja. Mund ta mbyllni këtë faqe.',
|
||||
);
|
||||
case 'it':
|
||||
default:
|
||||
return const FinancingStrings(
|
||||
title: 'Dati per Finanziamento',
|
||||
subtitle: 'Compila i seguenti dati necessari per la pratica di finanziamento.',
|
||||
maritalStatusLabel: 'Stato Civile',
|
||||
maritalOptions: ['Celibe / Nubile', 'Coniugato/a', 'Separato/a', 'Divorziato/a', 'Vedovo/a'],
|
||||
occupationLabel: 'Professione',
|
||||
occupationHint: 'Es. Impiegato, Operaio, Commerciante, Autonomo...',
|
||||
incomeLabel: 'Reddito Mensile Netto',
|
||||
incomeOptions: ['Fino a 2.000 €', 'Da 2.000 € a 5.000 €', 'Oltre 5.000 €'],
|
||||
submitButton: 'Invia Dati',
|
||||
errorRequired: 'Per favore compila tutti i campi prima di inviare.',
|
||||
successTitle: 'Dati inviati con successo!',
|
||||
successSubtitle: 'Grazie! Le informazioni sono state ricevute dal nostro operatore. Puoi chiudere questa schermata.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static String formatNoteText({
|
||||
required int maritalStatusIndex,
|
||||
required String occupation,
|
||||
required int incomeRangeIndex,
|
||||
required String languageName,
|
||||
}) {
|
||||
final marital = (maritalStatusIndex >= 0 && maritalStatusIndex < canonicalMaritalStatuses.length)
|
||||
? canonicalMaritalStatuses[maritalStatusIndex]
|
||||
: 'Non specificato';
|
||||
|
||||
final income = (incomeRangeIndex >= 0 && incomeRangeIndex < canonicalIncomeRanges.length)
|
||||
? canonicalIncomeRanges[incomeRangeIndex]
|
||||
: 'Non specificato';
|
||||
|
||||
final cleanOccupation = occupation.trim().isNotEmpty ? occupation.trim() : 'Non specificata';
|
||||
|
||||
return '''
|
||||
[DATI FINANZIAMENTO]
|
||||
• Stato civile: $marital
|
||||
• Professione: $cleanOccupation
|
||||
• Reddito mensile: $income
|
||||
(Compilato dal cliente via QR - Lingua: $languageName)''';
|
||||
}
|
||||
}
|
||||
|
||||
class FinancingLanguage {
|
||||
final String code;
|
||||
final String name;
|
||||
final String flag;
|
||||
final bool isRtl;
|
||||
|
||||
const FinancingLanguage({
|
||||
required this.code,
|
||||
required this.name,
|
||||
required this.flag,
|
||||
required this.isRtl,
|
||||
});
|
||||
}
|
||||
|
||||
class FinancingStrings {
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final String maritalStatusLabel;
|
||||
final List<String> maritalOptions;
|
||||
final String occupationLabel;
|
||||
final String occupationHint;
|
||||
final String incomeLabel;
|
||||
final List<String> incomeOptions;
|
||||
final String submitButton;
|
||||
final String errorRequired;
|
||||
final String successTitle;
|
||||
final String successSubtitle;
|
||||
|
||||
const FinancingStrings({
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.maritalStatusLabel,
|
||||
required this.maritalOptions,
|
||||
required this.occupationLabel,
|
||||
required this.occupationHint,
|
||||
required this.incomeLabel,
|
||||
required this.incomeOptions,
|
||||
required this.submitButton,
|
||||
required this.errorRequired,
|
||||
required this.successTitle,
|
||||
required this.successSubtitle,
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class FinancingFormScreen extends StatefulWidget {
|
||||
final String sessionId;
|
||||
|
||||
const FinancingFormScreen({
|
||||
super.key,
|
||||
required this.sessionId,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FinancingFormScreen> createState() => _FinancingFormScreenState();
|
||||
}
|
||||
|
||||
class _FinancingFormScreenState extends State<FinancingFormScreen> {
|
||||
FinancingLanguage _currentLang = FinancingTranslations.supportedLanguages.first; // Default Italiano
|
||||
final _occupationController = TextEditingController();
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
int? _selectedMaritalIndex;
|
||||
int? _selectedIncomeIndex;
|
||||
|
||||
bool _isSubmitting = false;
|
||||
bool _isSuccess = false;
|
||||
String? _errorMessage;
|
||||
|
||||
RealtimeChannel? _channel;
|
||||
StreamSubscription? _ackSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initRealtimeChannel();
|
||||
}
|
||||
|
||||
void _initRealtimeChannel() {
|
||||
if (widget.sessionId.isEmpty) return;
|
||||
try {
|
||||
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
|
||||
_channel?.onBroadcast(
|
||||
event: 'ack',
|
||||
callback: (payload) {
|
||||
if (mounted && _isSubmitting) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_isSuccess = true;
|
||||
});
|
||||
}
|
||||
},
|
||||
).subscribe();
|
||||
} catch (e) {
|
||||
debugPrint('Errore init channel financing: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ackSubscription?.cancel();
|
||||
if (_channel != null) {
|
||||
Supabase.instance.client.removeChannel(_channel!);
|
||||
}
|
||||
_occupationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final strings = FinancingTranslations.getStrings(_currentLang.code);
|
||||
|
||||
if (_selectedMaritalIndex == null ||
|
||||
_selectedIncomeIndex == null ||
|
||||
_occupationController.text.trim().isEmpty) {
|
||||
setState(() {
|
||||
_errorMessage = strings.errorRequired;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_errorMessage = null;
|
||||
_isSubmitting = true;
|
||||
});
|
||||
|
||||
final formattedText = FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: _selectedMaritalIndex!,
|
||||
occupation: _occupationController.text.trim(),
|
||||
incomeRangeIndex: _selectedIncomeIndex!,
|
||||
languageName: _currentLang.name,
|
||||
);
|
||||
|
||||
try {
|
||||
if (_channel == null) {
|
||||
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
|
||||
_channel?.subscribe();
|
||||
}
|
||||
|
||||
await _channel?.sendBroadcastMessage(
|
||||
event: 'submit',
|
||||
payload: {
|
||||
'maritalStatusIndex': _selectedMaritalIndex,
|
||||
'occupation': _occupationController.text.trim(),
|
||||
'incomeRangeIndex': _selectedIncomeIndex,
|
||||
'languageCode': _currentLang.code,
|
||||
'languageName': _currentLang.name,
|
||||
'formattedText': formattedText,
|
||||
},
|
||||
);
|
||||
|
||||
// Timeout di sicurezza: se entro 3 secondi non riceviamo ack specifico,
|
||||
// consideriamo comunque la trasmissione completata con successo
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (mounted && _isSubmitting) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_isSuccess = true;
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_errorMessage = 'Errore di connessione: $e';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final strings = FinancingTranslations.getStrings(_currentLang.code);
|
||||
|
||||
return Directionality(
|
||||
textDirection: _currentLang.isRtl ? TextDirection.rtl : TextDirection.ltr,
|
||||
child: Scaffold(
|
||||
backgroundColor: const Color(0xFFF8FAFC),
|
||||
appBar: AppBar(
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.white,
|
||||
centerTitle: true,
|
||||
title: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.account_balance_wallet_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Flexible(
|
||||
child: Text(
|
||||
strings.title,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF1E293B),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: _isSuccess
|
||||
? _buildSuccessView(strings, theme)
|
||||
: _buildFormView(strings, theme),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSuccessView(FinancingStrings strings, ThemeData theme) {
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
width: 90,
|
||||
height: 90,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.shade50,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.green.shade200, width: 2),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.check_circle_rounded,
|
||||
color: Colors.green.shade600,
|
||||
size: 56,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
strings.successTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF0F172A),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
strings.successSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
color: Colors.grey.shade700,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.blue.shade100),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: Colors.blue.shade700, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
'Sessione completata',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.blue.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFormView(FinancingStrings strings, ThemeData theme) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 540),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// SELETTORE LINGUA
|
||||
_buildLanguageSelector(),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// DESCRIZIONE
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.privacy_tip_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
strings.subtitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
color: Color(0xFF475569),
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 1. STATO CIVILE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.favorite_border,
|
||||
title: strings.maritalStatusLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildChoiceList(
|
||||
options: strings.maritalOptions,
|
||||
selectedIndex: _selectedMaritalIndex,
|
||||
onSelected: (idx) {
|
||||
setState(() => _selectedMaritalIndex = idx);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 2. PROFESSIONE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.work_outline,
|
||||
title: strings.occupationLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
TextFormField(
|
||||
controller: _occupationController,
|
||||
textInputAction: TextInputAction.done,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
decoration: InputDecoration(
|
||||
hintText: strings.occupationHint,
|
||||
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.primary,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
onChanged: (_) {
|
||||
if (_errorMessage != null) {
|
||||
setState(() => _errorMessage = null);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 3. REDDITO MENSILE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.euro_symbol_outlined,
|
||||
title: strings.incomeLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildChoiceList(
|
||||
options: strings.incomeOptions,
|
||||
selectedIndex: _selectedIncomeIndex,
|
||||
onSelected: (idx) {
|
||||
setState(() => _selectedIncomeIndex = idx);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// MESSAGGIO DI ERRORE
|
||||
if (_errorMessage != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.shade50,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: Colors.red.shade200),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Colors.red.shade700, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: TextStyle(
|
||||
color: Colors.red.shade800,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// PULSANTE INVIO
|
||||
SizedBox(
|
||||
height: 54,
|
||||
child: FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
elevation: 1,
|
||||
),
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.send_rounded, size: 20),
|
||||
label: Text(
|
||||
_isSubmitting ? '...' : strings.submitButton,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLanguageSelector() {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 4.0, bottom: 8.0),
|
||||
child: Text(
|
||||
'Seleziona lingua / Choose language:',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF64748B),
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 42,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: FinancingTranslations.supportedLanguages.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(width: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final lang = FinancingTranslations.supportedLanguages[index];
|
||||
final isSelected = lang.code == _currentLang.code;
|
||||
|
||||
return ChoiceChip(
|
||||
showCheckmark: false,
|
||||
labelPadding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
avatar: Text(lang.flag, style: const TextStyle(fontSize: 16)),
|
||||
label: Text(
|
||||
lang.name,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
|
||||
color: isSelected ? Colors.white : const Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedColor: Theme.of(context).colorScheme.primary,
|
||||
backgroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
side: BorderSide(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFFCBD5E1),
|
||||
),
|
||||
),
|
||||
onSelected: (selected) {
|
||||
if (selected) {
|
||||
setState(() {
|
||||
_currentLang = lang;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSectionHeader({
|
||||
required IconData icon,
|
||||
required String title,
|
||||
required ThemeData theme,
|
||||
}) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icon, size: 20, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChoiceList({
|
||||
required List<String> options,
|
||||
required int? selectedIndex,
|
||||
required ValueChanged<int> onSelected,
|
||||
}) {
|
||||
return Column(
|
||||
children: List.generate(options.length, (index) {
|
||||
final label = options[index];
|
||||
final isSelected = selectedIndex == index;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8.0),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: () => onSelected(index),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary.withValues(alpha: 0.08)
|
||||
: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFFCBD5E1),
|
||||
width: isSelected ? 2 : 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isSelected
|
||||
? Icons.radio_button_checked
|
||||
: Icons.radio_button_off,
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFF94A3B8),
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,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/ui/widgets/financing_qr_dialog.dart';
|
||||
import 'package:flux/features/operations/ui/widgets/operation_details_section.dart';
|
||||
|
||||
class OperationFormScreen extends StatefulWidget {
|
||||
@@ -629,6 +630,19 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
title: 'Note Interne',
|
||||
icon: Icons.notes,
|
||||
themeColor: Colors.teal,
|
||||
headerTrailing: OutlinedButton.icon(
|
||||
icon: const Icon(Icons.qr_code_2, size: 18),
|
||||
label: const Text('Dati Finanziamento'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.teal,
|
||||
side: const BorderSide(color: Colors.teal),
|
||||
visualDensity: VisualDensity.compact,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onPressed: _showFinancingQrDialog,
|
||||
),
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _notesController,
|
||||
@@ -649,6 +663,32 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void _showFinancingQrDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogCtx) => FinancingQrDialog(
|
||||
onDataReceived: (formattedData) {
|
||||
setState(() {
|
||||
final existing = _notesController.text.trim();
|
||||
if (existing.isEmpty) {
|
||||
_notesController.text = formattedData;
|
||||
} else {
|
||||
_notesController.text = '$existing\n\n$formattedData';
|
||||
}
|
||||
});
|
||||
_flushControllersToCubit();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Dati finanziamento inseriti nelle note!'),
|
||||
backgroundColor: Colors.teal,
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardAllegati(OperationFormState state) {
|
||||
return _buildCard(
|
||||
title: 'Allegati e Documenti',
|
||||
@@ -679,6 +719,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
required IconData icon,
|
||||
required Color themeColor,
|
||||
required List<Widget> children,
|
||||
Widget? headerTrailing,
|
||||
}) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 24),
|
||||
@@ -703,13 +744,16 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
child: Icon(icon, color: themeColor),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: themeColor,
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: themeColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
?headerTrailing,
|
||||
],
|
||||
),
|
||||
const Divider(height: 32),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
class FinancingQrDialog extends StatefulWidget {
|
||||
final ValueChanged<String> onDataReceived;
|
||||
|
||||
const FinancingQrDialog({
|
||||
super.key,
|
||||
required this.onDataReceived,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FinancingQrDialog> createState() => _FinancingQrDialogState();
|
||||
}
|
||||
|
||||
class _FinancingQrDialogState extends State<FinancingQrDialog> {
|
||||
late final String _sessionId;
|
||||
late final String _deepLinkUrl;
|
||||
RealtimeChannel? _channel;
|
||||
|
||||
bool _isReceived = false;
|
||||
Map<String, dynamic>? _receivedPayload;
|
||||
bool _copied = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sessionId = const Uuid().v4();
|
||||
_deepLinkUrl = 'https://flux.catelli.it/financing/$_sessionId';
|
||||
_setupRealtimeChannel();
|
||||
}
|
||||
|
||||
void _setupRealtimeChannel() {
|
||||
try {
|
||||
_channel = Supabase.instance.client.channel('financing_$_sessionId');
|
||||
_channel?.onBroadcast(
|
||||
event: 'submit',
|
||||
callback: (payload) {
|
||||
if (!mounted) return;
|
||||
|
||||
// Invia risposta di conferma (ACK) allo smartphone del cliente
|
||||
_channel?.sendBroadcastMessage(
|
||||
event: 'ack',
|
||||
payload: {'status': 'ok'},
|
||||
);
|
||||
|
||||
final maritalIndex = payload['maritalStatusIndex'] as int? ?? 0;
|
||||
final occupation = payload['occupation'] as String? ?? '';
|
||||
final incomeIndex = payload['incomeRangeIndex'] as int? ?? 0;
|
||||
final languageName = payload['languageName'] as String? ?? 'Italiano';
|
||||
|
||||
final formattedText = payload['formattedText'] as String? ??
|
||||
FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: maritalIndex,
|
||||
occupation: occupation,
|
||||
incomeRangeIndex: incomeIndex,
|
||||
languageName: languageName,
|
||||
);
|
||||
|
||||
widget.onDataReceived(formattedText);
|
||||
|
||||
setState(() {
|
||||
_isReceived = true;
|
||||
_receivedPayload = {
|
||||
'marital': (maritalIndex >= 0 &&
|
||||
maritalIndex <
|
||||
FinancingTranslations.canonicalMaritalStatuses.length)
|
||||
? FinancingTranslations.canonicalMaritalStatuses[maritalIndex]
|
||||
: 'N/D',
|
||||
'occupation': occupation,
|
||||
'income': (incomeIndex >= 0 &&
|
||||
incomeIndex <
|
||||
FinancingTranslations.canonicalIncomeRanges.length)
|
||||
? FinancingTranslations.canonicalIncomeRanges[incomeIndex]
|
||||
: 'N/D',
|
||||
'language': languageName,
|
||||
};
|
||||
});
|
||||
},
|
||||
).subscribe();
|
||||
} catch (e) {
|
||||
debugPrint('Errore setup realtime channel: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_channel != null) {
|
||||
Supabase.instance.client.removeChannel(_channel!);
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _copyToClipboard() {
|
||||
Clipboard.setData(ClipboardData(text: _deepLinkUrl));
|
||||
setState(() => _copied = true);
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (mounted) setState(() => _copied = false);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Icon(Icons.qr_code_2, color: Colors.teal, size: 28),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
const Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Dati Finanziamento',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
|
||||
),
|
||||
Text(
|
||||
'Raccolta via smartphone cliente',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 380,
|
||||
child: SingleChildScrollView(
|
||||
child: _isReceived
|
||||
? _buildReceivedContent(theme)
|
||||
: _buildQrContent(theme),
|
||||
),
|
||||
),
|
||||
actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
actions: [
|
||||
if (!_isReceived) ...[
|
||||
OutlinedButton.icon(
|
||||
onPressed: _copyToClipboard,
|
||||
icon: Icon(_copied ? Icons.check : Icons.copy, size: 16),
|
||||
label: Text(_copied ? 'Link Copiato!' : 'Copia Link'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
] else ...[
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.teal),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.check, size: 18),
|
||||
label: const Text('Chiudi (Dati inseriti nelle note)'),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQrContent(ThemeData theme) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Fai inquadrare questo codice al cliente con la fotocamera del suo telefono.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade50,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.amber.shade200),
|
||||
),
|
||||
child: Text(
|
||||
'🌐 Il cliente potrà scegliere la lingua (IT, EN, FR, ES, AR, UK, RU, MK, SQ)',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.grey.shade200),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.04),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: QrImageView(
|
||||
data: _deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 210.0,
|
||||
embeddedImage: const AssetImage('assets/images/logo.png'),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.teal),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
'In attesa che il cliente compili i dati...',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: Colors.grey.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildReceivedContent(ThemeData theme) {
|
||||
final marital = _receivedPayload?['marital'] ?? '';
|
||||
final occupation = _receivedPayload?['occupation'] ?? '';
|
||||
final income = _receivedPayload?['income'] ?? '';
|
||||
final lang = _receivedPayload?['language'] ?? '';
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.shade50,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.teal.shade200),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: Colors.teal, size: 28),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Dati ricevuti con successo! 🎉',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: Colors.teal.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
const Divider(height: 1),
|
||||
const SizedBox(height: 12),
|
||||
_buildInfoRow('Stato civile', marital),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Professione', occupation),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Reddito mensile', income),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Lingua cliente', lang),
|
||||
const SizedBox(height: 14),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.notes, size: 18, color: Colors.teal.shade700),
|
||||
const SizedBox(width: 8),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'I dati sono stati automaticamente inseriti nel campo note dell\'operazione.',
|
||||
style: TextStyle(fontSize: 12, color: Colors.black87),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(String label, String value) {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 110,
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.black54,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@@ -53,6 +53,16 @@ class TicketListCard extends StatelessWidget {
|
||||
DeleteSpecificAttachmentEvent(targetFile),
|
||||
);
|
||||
},
|
||||
onViewModeChanged: (targetFile, newMode) {
|
||||
operationFilesBloc.add(
|
||||
UpdateAttachmentViewModeEvent(targetFile, newMode),
|
||||
);
|
||||
},
|
||||
onAttachmentUpdated: (updatedFile) {
|
||||
operationFilesBloc.add(
|
||||
AttachmentUpdatedEvent(updatedFile),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -39,9 +39,16 @@ import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
final sl = GetIt.instance;
|
||||
|
||||
Future<void> init() async {
|
||||
final envUrl = dotenv.env['SUPABASE_URL']?.trim();
|
||||
final envKey = dotenv.env['SUPABASE_PUBLISHABLE_KEY']?.trim();
|
||||
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? '',
|
||||
url: (envUrl != null && envUrl.isNotEmpty)
|
||||
? envUrl
|
||||
: 'https://supabaseapi.catelli.it',
|
||||
publishableKey: (envKey != null && envKey.isNotEmpty)
|
||||
? envKey
|
||||
: 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo',
|
||||
);
|
||||
sl.registerSingleton<SupabaseClient>(Supabase.instance.client);
|
||||
sl.registerSingleton<SharedPreferences>(
|
||||
|
||||
+5
-5
@@ -76,7 +76,7 @@ PODS:
|
||||
- path_provider_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- pdfx (1.0.0):
|
||||
- pdfium_flutter (0.1.5):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- printing (1.0.0):
|
||||
@@ -97,7 +97,7 @@ DEPENDENCIES:
|
||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
|
||||
- path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`)
|
||||
- pdfx (from `Flutter/ephemeral/.symlinks/plugins/pdfx/darwin`)
|
||||
- pdfium_flutter (from `Flutter/ephemeral/.symlinks/plugins/pdfium_flutter/darwin`)
|
||||
- printing (from `Flutter/ephemeral/.symlinks/plugins/printing/macos`)
|
||||
- shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`)
|
||||
@@ -131,8 +131,8 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos
|
||||
path_provider_foundation:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin
|
||||
pdfx:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/pdfx/darwin
|
||||
pdfium_flutter:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/pdfium_flutter/darwin
|
||||
printing:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/printing/macos
|
||||
shared_preferences_foundation:
|
||||
@@ -157,7 +157,7 @@ SPEC CHECKSUMS:
|
||||
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
|
||||
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
pdfx: 824a9108791a81e400da7d1a903ab73668365072
|
||||
pdfium_flutter: f29beeb612293cc42df95beee223a4925ce2458e
|
||||
printing: 7916ffaaede65713863e621de9a4742d9fa723b9
|
||||
PromisesObjC: 752c3227f599e3467650e47ea36f433eeb10c273
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: flux
|
||||
description: "Gestione attività negozio di telefonia"
|
||||
publish_to: 'none'
|
||||
version: 2.1.3+77
|
||||
version: 2.5.8+92
|
||||
|
||||
environment:
|
||||
sdk: ^3.11.3
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
void main() {
|
||||
group('ImageUtils Tests', () {
|
||||
test('rotateBytes with quarterTurns 0 or 4 returns original bytes', () {
|
||||
final dummy = Uint8List.fromList([1, 2, 3, 4]);
|
||||
expect(ImageUtils.rotateBytes(dummy, quarterTurns: 0), equals(dummy));
|
||||
expect(ImageUtils.rotateBytes(dummy, quarterTurns: 4), equals(dummy));
|
||||
});
|
||||
|
||||
test('rotateBytes correctly rotates an image by 90 degrees', () {
|
||||
// Creiamo un'immagine 10x20 (larghezza 10, altezza 20)
|
||||
final testImg = img.Image(width: 10, height: 20);
|
||||
final encodedPng = Uint8List.fromList(img.encodePng(testImg));
|
||||
|
||||
// Ruotiamo di 1 quarto (90°)
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
encodedPng,
|
||||
quarterTurns: 1,
|
||||
extension: 'png',
|
||||
);
|
||||
|
||||
final decoded = img.decodeImage(rotatedBytes);
|
||||
expect(decoded, isNotNull);
|
||||
// Dopo 90 gradi di rotazione, larghezza e altezza devono invertirsi (20x10)
|
||||
expect(decoded!.width, 20);
|
||||
expect(decoded.height, 10);
|
||||
});
|
||||
|
||||
test('rotateBytes correctly rotates an image by 180 degrees', () {
|
||||
final testImg = img.Image(width: 15, height: 30);
|
||||
final encodedPng = Uint8List.fromList(img.encodePng(testImg));
|
||||
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
encodedPng,
|
||||
quarterTurns: 2,
|
||||
extension: 'png',
|
||||
);
|
||||
|
||||
final decoded = img.decodeImage(rotatedBytes);
|
||||
expect(decoded, isNotNull);
|
||||
expect(decoded!.width, 15);
|
||||
expect(decoded.height, 30);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
|
||||
void main() {
|
||||
group('AttachmentModel Tests', () {
|
||||
test('empty() creates a valid default empty instance', () {
|
||||
final empty = AttachmentModel.empty();
|
||||
expect(empty.name, '');
|
||||
expect(empty.extension, '');
|
||||
expect(empty.fileSize, 0);
|
||||
expect(empty.companyId, '');
|
||||
expect(empty.thumbnailPath, isNull);
|
||||
expect(empty.croppedStoragePath, isNull);
|
||||
expect(empty.storagePath, isNull);
|
||||
expect(empty.viewMode, isNull);
|
||||
});
|
||||
|
||||
test('fromMap and toMap handle thumbnailPath, croppedStoragePath, and viewMode correctly', () {
|
||||
final map = {
|
||||
'id': 'att-123',
|
||||
'created_at': '2026-10-15T10:00:00.000Z',
|
||||
'customer_id': 'cust-1',
|
||||
'operation_id': 'op-1',
|
||||
'ticket_id': 'tick-1',
|
||||
'shipping_document_id': 'ship-1',
|
||||
'note_id': 'note-1',
|
||||
'name': 'documento_test',
|
||||
'extension': 'jpg',
|
||||
'storage_path': 'company/operation/op-1/orig.jpg',
|
||||
'thumbnail_path': 'company/operation/op-1/thumb.webp',
|
||||
'cropped_storage_path': 'company/operation/op-1/crop.jpg',
|
||||
'view_mode': 'cropped',
|
||||
'file_size': 204800,
|
||||
'company_id': 'comp-99',
|
||||
};
|
||||
|
||||
final model = AttachmentModel.fromMap(map);
|
||||
|
||||
expect(model.id, 'att-123');
|
||||
expect(model.name, 'documento_test');
|
||||
expect(model.extension, 'jpg');
|
||||
expect(model.storagePath, 'company/operation/op-1/orig.jpg');
|
||||
expect(model.thumbnailPath, 'company/operation/op-1/thumb.webp');
|
||||
expect(model.croppedStoragePath, 'company/operation/op-1/crop.jpg');
|
||||
expect(model.viewMode, AttachmentViewMode.cropped);
|
||||
expect(model.fileSize, 204800);
|
||||
expect(model.companyId, 'comp-99');
|
||||
|
||||
final serialized = model.toMap();
|
||||
expect(serialized['thumbnail_path'], 'company/operation/op-1/thumb.webp');
|
||||
expect(serialized['cropped_storage_path'], 'company/operation/op-1/crop.jpg');
|
||||
expect(serialized['storage_path'], 'company/operation/op-1/orig.jpg');
|
||||
expect(serialized['view_mode'], 'cropped');
|
||||
});
|
||||
|
||||
test('effectiveStoragePath resolves properly according to viewMode', () {
|
||||
const orig = 'company/orig.jpg';
|
||||
const crop = 'company/crop.jpg';
|
||||
|
||||
// 1. viewMode = cropped -> crop
|
||||
final croppedModel = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
expect(croppedModel.effectiveStoragePath, crop);
|
||||
|
||||
// 2. viewMode = original -> orig
|
||||
final originalModel = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
expect(originalModel.effectiveStoragePath, orig);
|
||||
|
||||
// 3. viewMode = null -> defaults to crop if available
|
||||
final defaultWithCrop = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
);
|
||||
expect(defaultWithCrop.effectiveStoragePath, crop);
|
||||
|
||||
// 4. viewMode = cropped but croppedStoragePath is null -> fallback to orig
|
||||
final fallbackToOrig = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
expect(fallbackToOrig.effectiveStoragePath, orig);
|
||||
});
|
||||
|
||||
test('copyWith properly updates thumbnailPath, croppedStoragePath, and viewMode', () {
|
||||
final initial = AttachmentModel.empty().copyWith(
|
||||
name: 'test',
|
||||
extension: 'png',
|
||||
companyId: 'comp-1',
|
||||
);
|
||||
|
||||
final updated = initial.copyWith(
|
||||
thumbnailPath: 'thumbs/1.webp',
|
||||
croppedStoragePath: 'crops/1.png',
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
|
||||
expect(updated.thumbnailPath, 'thumbs/1.webp');
|
||||
expect(updated.croppedStoragePath, 'crops/1.png');
|
||||
expect(updated.viewMode, AttachmentViewMode.original);
|
||||
expect(updated.name, 'test');
|
||||
});
|
||||
|
||||
test('Equatable props comparison works as expected', () {
|
||||
final a = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
final b = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
final c = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
|
||||
expect(a, equals(b));
|
||||
expect(a, isNot(equals(c)));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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,56 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
|
||||
void main() {
|
||||
group('FinancingTranslations', () {
|
||||
test('contains all 9 requested languages', () {
|
||||
final supportedCodes = FinancingTranslations.supportedLanguages.map((l) => l.code).toSet();
|
||||
expect(
|
||||
supportedCodes,
|
||||
containsAll([
|
||||
'it',
|
||||
'en',
|
||||
'fr',
|
||||
'es',
|
||||
'ar',
|
||||
'uk',
|
||||
'ru',
|
||||
'mk',
|
||||
'sq',
|
||||
]),
|
||||
);
|
||||
expect(FinancingTranslations.supportedLanguages.length, 9);
|
||||
});
|
||||
|
||||
test('Arabic is marked as RTL', () {
|
||||
final ar = FinancingTranslations.supportedLanguages.firstWhere((l) => l.code == 'ar');
|
||||
expect(ar.isRtl, isTrue);
|
||||
|
||||
final it = FinancingTranslations.supportedLanguages.firstWhere((l) => l.code == 'it');
|
||||
expect(it.isRtl, isFalse);
|
||||
});
|
||||
|
||||
test('formatNoteText outputs canonical Italian labels regardless of language', () {
|
||||
final noteText = FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: 0, // Celibe / Nubile
|
||||
occupation: 'Ingegnere Informatico',
|
||||
incomeRangeIndex: 1, // Da 2.000 € a 5.000 €
|
||||
languageName: 'العربية (Arabo)',
|
||||
);
|
||||
|
||||
expect(noteText, contains('[DATI FINANZIAMENTO]'));
|
||||
expect(noteText, contains('Stato civile: Celibe / Nubile'));
|
||||
expect(noteText, contains('Professione: Ingegnere Informatico'));
|
||||
expect(noteText, contains('Reddito mensile: Da 2.000 € a 5.000 €'));
|
||||
expect(noteText, contains('Lingua: العربية (Arabo)'));
|
||||
});
|
||||
|
||||
test('each language has exactly 5 marital status and 3 income range options', () {
|
||||
for (final lang in FinancingTranslations.supportedLanguages) {
|
||||
final strings = FinancingTranslations.getStrings(lang.code);
|
||||
expect(strings.maritalOptions.length, 5, reason: 'Language ${lang.code} should have 5 marital options');
|
||||
expect(strings.incomeOptions.length, 3, reason: 'Language ${lang.code} should have 3 income options');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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,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);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user