Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6296f49737 | ||
|
|
1fbd2bf8db | ||
|
|
0bc8ae92b9 | ||
|
|
6d2c563ce2 | ||
|
|
5fcc16fb9c | ||
|
|
1084b03610 | ||
|
|
63edd51420 | ||
|
|
7572f4c061 | ||
|
|
57a4dc6f68 | ||
|
|
4b111766dc | ||
|
|
2bf668a088 | ||
|
|
0adb1a8f1c | ||
|
|
606a1fc3a9 | ||
|
|
4e3732597b | ||
|
|
53496a2a9d | ||
|
|
0cc7c76df9 | ||
|
|
ca67d86a71 | ||
|
|
33e309909e | ||
|
|
ab64bf0621 | ||
|
|
dcb19cf839 | ||
|
|
bc9e0769cd | ||
|
|
7dd8a3ac71 | ||
|
|
70db03066b | ||
|
|
addb06a61a | ||
|
|
5e505d96b3 | ||
|
|
66c7094ada | ||
|
|
bd496ad37f | ||
|
|
771f1f921b | ||
|
|
2c02dfcf8b | ||
|
|
89e5d4014d | ||
|
|
8e396a7885 | ||
|
|
9b7b4beaa8 | ||
|
|
531b3ba3f2 | ||
|
|
d0036b729d | ||
|
|
4d791d2213 | ||
|
|
19fc90b830 | ||
|
|
4f0fe7bab5 | ||
|
|
7323f68e62 | ||
|
|
a33b08a0c3 | ||
|
|
c8fdd29cf4 | ||
|
|
00615b92a0 | ||
|
|
832be3d797 | ||
|
|
72f9d88f96 | ||
|
|
d4a6b142c5 | ||
|
|
8da4dc9d75 | ||
|
|
6ad0aa3e23 | ||
|
|
11c5352555 | ||
|
|
a0bdb9a535 | ||
|
|
37d69e3ddc | ||
|
|
524da71a45 | ||
|
|
3949d6d13c | ||
|
|
d5591b2c91 | ||
|
|
97d19f1d17 | ||
|
|
282a959f88 | ||
|
|
aaa6cdf704 | ||
|
|
bc1614c71b | ||
|
|
b71656d0a6 | ||
|
|
9374f4ab46 | ||
|
|
3b3e65bd1c | ||
|
|
ce035e2204 | ||
|
|
70c0c25521 | ||
|
|
8cd55f53f7 | ||
|
|
6e01729bf5 | ||
|
|
4b4d0c5cb6 | ||
|
|
ff27727f10 | ||
|
|
8f0ad23c0b | ||
|
|
729c893463 | ||
|
|
eb31ad7173 | ||
|
|
a652232b25 | ||
|
|
b8f752d246 | ||
|
|
b837a5fa1e | ||
|
|
9154a16fe1 | ||
|
|
48f6f92f9c | ||
|
|
c6e3594850 | ||
|
|
c6a1b203ce | ||
|
|
1c96ff9516 | ||
|
|
409c064902 | ||
|
|
66667fb440 | ||
|
|
c41fcd37b3 | ||
|
|
9cd0b98a16 | ||
|
|
8951bff083 | ||
|
|
a514bba8b2 |
No files matched your search
+146
-37
@@ -18,6 +18,11 @@ jobs:
|
||||
run: |
|
||||
Set-Content -Path ".env" -Value "${{ secrets.ENV_FILE_CONTENT }}"
|
||||
|
||||
- name: Pulizia Cache Dart e Download Dipendenze
|
||||
run: |
|
||||
if (Test-Path ".dart_tool") { Remove-Item -Recurse -Force ".dart_tool" }
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter Windows
|
||||
run: flutter build windows --release
|
||||
|
||||
@@ -49,50 +54,36 @@ jobs:
|
||||
files: "build/windows/installer/FluxInstaller.exe"
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link Windows su Supabase
|
||||
run: |
|
||||
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
|
||||
$apiKey = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if ([string]::IsNullOrWhiteSpace($apiKey)) {
|
||||
$apiKey = "sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
}
|
||||
$body = @{
|
||||
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
|
||||
latest_version = $TagVersion
|
||||
} | 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()
|
||||
run: Remove-Item -Recurse -Force ./*
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 2: ANDROID APK (Gira sul tuo MacBook)
|
||||
# -----------------------------------------------------------------
|
||||
build-android:
|
||||
runs-on: macos-runner # <--- Etichetta del tuo Mac
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Logica Bash per Mac: usiamo le virgolette singole forti per evitare escape strani
|
||||
- name: Crea file .env
|
||||
run: |
|
||||
cat << 'EOF' > .env
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Build Flutter APK
|
||||
run: flutter build apk --release
|
||||
|
||||
# Carichiamo l'APK universale o quelli splittati nelle release di Gitea
|
||||
- name: Upload Android Asset
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: "build/app/outputs/flutter-apk/app-release.apk"
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link Android su Supabase
|
||||
run: |
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.49f18b19-2129-46c0-b690-a97db725b5a8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/app-release.apk\"}"
|
||||
|
||||
- name: Aggiorna Link Windows su Supabase
|
||||
run: |
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.1f888b30-5cbf-4a16-820c-5036a3af0cf8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe\"}"
|
||||
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul tuo MacBook)
|
||||
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul runner Fedora o Mac)
|
||||
# -----------------------------------------------------------------
|
||||
build-web:
|
||||
runs-on: macos-runner # <--- Etichetta del tuo Mac
|
||||
runs-on: cross-runner
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
@@ -103,6 +94,11 @@ jobs:
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Pulizia Cache e Fetch Dipendenze
|
||||
run: |
|
||||
rm -rf .dart_tool
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter Web
|
||||
run: flutter build web --release
|
||||
|
||||
@@ -112,4 +108,117 @@ jobs:
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
|
||||
- name: Aggiorna Versione Web su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
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 (Build isolata su Ubuntu 22.04 via Docker)
|
||||
# -----------------------------------------------------------------
|
||||
build-linux:
|
||||
runs-on: linux-runner # <--- Etichetta del tuo runner Linux in ufficio
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Crea file .env
|
||||
run: |
|
||||
cat << 'EOF' > .env
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Prepara immagine Docker (Ubuntu 22.04 / x86-64-baseline)
|
||||
run: |
|
||||
docker build -t flux-linux-builder -f docker/linux-appimage.Dockerfile docker
|
||||
|
||||
- name: Build Flutter Linux e Genera AppImage nel container
|
||||
run: |
|
||||
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
|
||||
with:
|
||||
files: "Flux-x86_64.AppImage"
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link Linux su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
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\"}"
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 5: MACOS (Gira sul tuo Mac / macos-runner)
|
||||
# -----------------------------------------------------------------
|
||||
build-macos:
|
||||
runs-on: macos-runner
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Crea file .env
|
||||
run: |
|
||||
cat << 'EOF' > .env
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Pulizia Cache e Fetch Dipendenze
|
||||
run: |
|
||||
rm -rf .dart_tool
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter macOS
|
||||
run: flutter build macos --release
|
||||
|
||||
- name: Genera DMG e ZIP macOS
|
||||
run: |
|
||||
# Crea DMG dell'applicazione
|
||||
hdiutil create -volname "Flux" -srcfolder "build/macos/Build/Products/Release/flux.app" -ov -format UDZO "Flux-macOS.dmg"
|
||||
|
||||
# Crea anche archivio ZIP di backup
|
||||
cd build/macos/Build/Products/Release
|
||||
zip -r -y ../../../../Flux-macOS.zip "flux.app"
|
||||
cd -
|
||||
|
||||
- name: Upload macOS Assets
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: |
|
||||
Flux-macOS.dmg
|
||||
Flux-macOS.zip
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link macOS su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
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\"}"
|
||||
@@ -46,3 +46,7 @@ app.*.map.json
|
||||
/android/app/release
|
||||
|
||||
.env
|
||||
|
||||
appimagetool*
|
||||
*.AppDir
|
||||
*.AppImage
|
||||
@@ -11,6 +11,10 @@ analyzer:
|
||||
- "ios/**"
|
||||
- "macos/**"
|
||||
- ".dart_tool/**"
|
||||
- android/**
|
||||
- web/**
|
||||
- windows/**
|
||||
- linux/**
|
||||
|
||||
linter:
|
||||
rules:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
@@ -8,6 +11,13 @@ plugins {
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
// 2. CARICHIAMO IL KEYSTORE QUI FUORI IN MODO PULITO
|
||||
val keystoreProperties = Properties()
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.catellisrl.flux"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
@@ -23,7 +33,6 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.catellisrl.flux"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
@@ -33,11 +42,22 @@ android {
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties["keyAlias"] as String?
|
||||
keyPassword = keystoreProperties["keyPassword"] as String?
|
||||
storeFile = keystoreProperties["storeFile"]?.let { file(it as String) }
|
||||
storePassword = keystoreProperties["storePassword"] as String?
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
signingConfig = if (keystorePropertiesFile.exists()) {
|
||||
signingConfigs.getByName("release")
|
||||
} else {
|
||||
signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -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"]
|
||||
@@ -0,0 +1 @@
|
||||
␍ .env␍asset.envassets/icon/icon.png␍assetassets/icon/icon.png assets/images/flux_logo_dark.png␍asset assets/images/flux_logo_dark.png!assets/images/flux_logo_light.png␍asset!assets/images/flux_logo_light.pngassets/svg/flux_logo_dark.svg␍assetassets/svg/flux_logo_dark.svgassets/svg/flux_logo_light.svg␍assetassets/svg/flux_logo_light.svgMpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otf␍assetMpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otfKpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otf␍assetKpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otfIpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf␍assetIpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf
|
||||
@@ -0,0 +1 @@
|
||||
[{"family":"MaterialIcons","fonts":[{"asset":"fonts/MaterialIcons-Regular.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeBrands","fonts":[{"weight":400,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeRegular","fonts":[{"weight":400,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeSolid","fonts":[{"weight":900,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf"}]}]
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"format-version":[1,0,0],"native-assets":{}}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 45 KiB |
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="220mm"
|
||||
height="70mm"
|
||||
viewBox="0 0 220 70"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="linearGradient4">
|
||||
<stop
|
||||
style="stop-color:#0467a8;stop-opacity:1;"
|
||||
offset="0.17659575"
|
||||
id="stop6" />
|
||||
<stop
|
||||
style="stop-color:#09a8bd;stop-opacity:1;"
|
||||
offset="1"
|
||||
id="stop7" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
xlink:href="#linearGradient4"
|
||||
id="linearGradient5"
|
||||
x1="2.1388452"
|
||||
y1="38.851192"
|
||||
x2="70.730141"
|
||||
y2="38.851192"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="translate(0,-1.0583333)" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata1">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<path
|
||||
d="m 79.119202,16.272909 v 38.473103 h 5.331457 V 36.220011 H 101.87182 V 31.672485 H 84.450659 v -10.85205 h 20.275251 v -4.547526 z m 31.691608,0 v 38.473103 h 25.36434 V 50.198486 H 116.14226 V 16.272909 Z m 30.10359,0 v 23.02185 c 0,2.911107 0.31379,5.365736 0.94206,7.363892 0.64622,1.998156 1.69671,3.703477 3.15071,5.115967 1.27449,1.240234 2.84499,2.179539 4.71186,2.816882 1.86686,0.637342 4.05705,0.956014 6.57014,0.956014 2.45924,0 4.61323,-0.301962 6.46214,-0.904854 1.84891,-0.602892 3.46453,-1.558906 4.84673,-2.868042 1.454,-1.378039 2.49505,-3.100586 3.12332,-5.167644 0.64622,-2.084283 0.96894,-4.521687 0.96894,-7.312215 v -23.02185 h -5.33095 v 23.409423 c 0,1.877578 -0.15269,3.453709 -0.45785,4.728394 -0.28721,1.25746 -0.78097,2.377115 -1.48105,3.358968 -0.80777,1.136881 -1.88451,1.989542 -3.23081,2.557983 -1.3463,0.551216 -2.97976,0.826823 -4.90047,0.826823 -1.90277,0 -3.53675,-0.28422 -4.90099,-0.852661 -1.3463,-0.56844 -2.41411,-1.412489 -3.20394,-2.532145 -0.70008,-0.981853 -1.20276,-2.07567 -1.50792,-3.281453 -0.28721,-1.205784 -0.43098,-2.850817 -0.43098,-4.9351 V 16.272909 Z m 37.72327,0 13.65137,19.249471 -13.97486,19.223632 h 5.81618 l 11.20139,-15.838826 10.93163,15.838826 h 6.16603 L 198.6163,35.289836 212.45628,16.272909 h -5.84305 l -11.03964,15.63212 -10.79727,-15.63212 z"
|
||||
style="font-size:54.019px;font-family:Roboto;-inkscape-font-specification:'Roboto, @wght=600';font-variation-settings:'wght' 600;stroke-width:0.270095"
|
||||
id="path10" />
|
||||
<path
|
||||
d="m 18.746659,32.35048 v 35.012333 l 7.483265,0.01602 -0.0078,-15.15153 -0.444417,0.0088 -0.283187,-5.574853 0.724503,-0.09353 -0.0052,-10.30273 c -2.477109,-1.576343 -4.681183,-2.913234 -7.467245,-3.91449 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path4" />
|
||||
<path
|
||||
d="m 34.188094,44.204537 -2.362646,1.228349 -3.40186,0.850077 -2.92902,0.378272 0.283187,5.574853 4.819344,-0.09405 3.024105,-1.03973 2.362129,-1.417484 1.512053,-0.756027 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path3" />
|
||||
<path
|
||||
d="m 30.789852,3.3827393 c -2.718649,-0.031966 -5.436525,0.014505 -8.153508,0.092501 -1.657421,0.047579 -3.410165,1.1618896 -3.915523,2.4758178 -0.117943,1.3009842 -0.120443,2.6260493 -0.194303,3.9361939 -0.03417,4.6029962 0.05579,9.2082292 0.06976,13.8120772 l 8.031551,2.645316 V 15.482776 c -0.06845,-1.616367 -0.186384,-3.220801 5.17e-4,-4.823995 1.450909,-0.02681 2.901798,-0.0533 4.352706,-0.0801 0.05294,-7.58e-4 0.101815,-0.0019 0.146761,-0.0026 -0.133325,0.0041 -0.29154,0.0097 -0.465088,0.01705 5.402012,0.128802 10.810722,0.09637 16.214514,0.01395 1.312459,0.137599 2.534326,-0.34712 3.780648,-0.6609411 0.688414,-0.375834 1.230544,-1.0271554 1.861385,-1.5115356 0.530757,-0.2588779 0.43123,-0.8718681 0.550871,-1.361674 0.317571,-1.2121917 0.137814,-2.4561815 0.111104,-3.690214 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path2" />
|
||||
<path
|
||||
d="m 56.166081,18.073315 c -1.612095,0.517615 -3.326896,0.856005 -4.876705,1.482597 -1.672317,1.636751 -3.569999,3.080027 -4.731494,5.154724 -1.760645,2.382939 -3.026169,5.086524 -4.280876,7.757666 -0.891629,2.073315 -1.768619,4.152921 -2.589506,6.255433 l 4.441073,4.251936 c 1.398551,-3.4772 2.668634,-7.012956 4.53719,-10.275341 0.629987,-1.555517 1.666989,-2.831823 2.828251,-4.022494 1.022671,-1.037894 1.767254,-2.482454 3.326929,-2.735233 0.889424,-0.171791 1.852674,-1.15661 2.651001,-0.326079 1.091115,0.724393 2.380755,1.270451 3.353284,2.101164 0.773793,1.805199 1.727371,3.571064 2.391068,5.400187 -0.10305,3.050467 0.318141,6.150981 -0.478523,9.13536 -0.227898,1.392226 -0.44891,2.787081 -1.327568,3.939294 -0.639724,0.878207 -0.930155,2.134421 -1.788004,2.776575 -1.441269,0.609895 -2.847747,1.462494 -4.310848,1.920296 -1.617481,-0.300784 -3.315903,-0.407844 -4.88394,-0.826823 -2.069996,-1.549653 -4.248341,-2.976127 -5.912301,-4.986259 -2.758844,-2.90603 -5.507188,-5.823363 -8.591207,-8.391735 -3.338252,-2.881492 -6.432985,-6.060987 -10.113077,-8.519377 -1.00535,-0.833342 -2.074808,-1.535604 -3.393075,-1.725476 -2.128037,-0.523545 -4.194319,-1.47308 -6.429582,-1.257805 -2.170664,0.06994 -4.409538,-0.393106 -6.482808,0.438733 -0.9003416,0.331796 -2.1359215,0.232269 -2.4158733,1.361674 -1.9123575,3.173056 -3.6177926,6.486404 -4.6400268,10.062435 -0.4008915,1.586154 -0.4139892,3.222181 -0.038241,4.817794 l 0.1400432,0.924491 c 0.8820904,-2.491562 1.2764827,-5.195371 2.8018961,-7.407299 0.6237014,-1.09468 1.1172001,-2.309336 2.3424927,-2.850472 1.0032429,-0.704794 1.9546502,-1.540401 3.2581987,-1.487765 3.00294,-0.587415 6.099427,-0.06595 9.095052,0.498161 1.4899,0.270585 2.725854,0.959381 4.081922,1.606103 2.823588,1.93021 5.578022,3.981722 8.006229,6.392375 3.658406,4.382924 6.878979,9.116624 10.426754,13.577466 1.153639,1.018099 2.201592,2.226861 3.41943,3.129008 1.866433,0.375292 3.683112,1.179818 5.582605,1.267623 2.379016,-0.109475 4.813761,-0.01813 7.158736,-0.251148 2.193684,-1.301699 4.557492,-2.436561 6.645589,-3.841626 1.382677,-2.657284 2.904182,-5.268723 4.200261,-7.954553 0.355987,-2.855588 0.956499,-5.711351 1.159619,-8.566919 -0.441278,-2.56316 -0.629473,-5.204579 -1.227832,-7.718909 -1.026057,-1.96421 -1.887153,-4.070949 -3.014287,-5.947957 -1.857041,-1.18145 -3.561937,-2.667789 -5.518009,-3.65094 -1.601938,-0.471008 -3.198698,-1.192578 -4.803841,-1.506885 z"
|
||||
style="fill:url(#linearGradient5);stroke-width:0.264583"
|
||||
id="path1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.7 KiB |
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="220mm"
|
||||
height="70mm"
|
||||
viewBox="0 0 220 70"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="linearGradient4">
|
||||
<stop
|
||||
style="stop-color:#0467a8;stop-opacity:1;"
|
||||
offset="0.17659575"
|
||||
id="stop6" />
|
||||
<stop
|
||||
style="stop-color:#09a8bd;stop-opacity:1;"
|
||||
offset="1"
|
||||
id="stop7" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
xlink:href="#linearGradient4"
|
||||
id="linearGradient5"
|
||||
x1="2.1388452"
|
||||
y1="38.851192"
|
||||
x2="70.730141"
|
||||
y2="38.851192"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="translate(0,-1.0583333)" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata1">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<path
|
||||
d="m 79.119202,16.272909 v 38.473103 h 5.331457 V 36.220011 H 101.87182 V 31.672485 H 84.450659 v -10.85205 h 20.275251 v -4.547526 z m 31.691608,0 v 38.473103 h 25.36434 V 50.198486 H 116.14226 V 16.272909 Z m 30.10359,0 v 23.02185 c 0,2.911107 0.31379,5.365736 0.94206,7.363892 0.64622,1.998156 1.69671,3.703477 3.15071,5.115967 1.27449,1.240234 2.84499,2.179539 4.71186,2.816882 1.86686,0.637342 4.05705,0.956014 6.57014,0.956014 2.45924,0 4.61323,-0.301962 6.46214,-0.904854 1.84891,-0.602892 3.46453,-1.558906 4.84673,-2.868042 1.454,-1.378039 2.49505,-3.100586 3.12332,-5.167644 0.64622,-2.084283 0.96894,-4.521687 0.96894,-7.312215 v -23.02185 h -5.33095 v 23.409423 c 0,1.877578 -0.15269,3.453709 -0.45785,4.728394 -0.28721,1.25746 -0.78097,2.377115 -1.48105,3.358968 -0.80777,1.136881 -1.88451,1.989542 -3.23081,2.557983 -1.3463,0.551216 -2.97976,0.826823 -4.90047,0.826823 -1.90277,0 -3.53675,-0.28422 -4.90099,-0.852661 -1.3463,-0.56844 -2.41411,-1.412489 -3.20394,-2.532145 -0.70008,-0.981853 -1.20276,-2.07567 -1.50792,-3.281453 -0.28721,-1.205784 -0.43098,-2.850817 -0.43098,-4.9351 V 16.272909 Z m 37.72327,0 13.65137,19.249471 -13.97486,19.223632 h 5.81618 l 11.20139,-15.838826 10.93163,15.838826 h 6.16603 L 198.6163,35.289836 212.45628,16.272909 h -5.84305 l -11.03964,15.63212 -10.79727,-15.63212 z"
|
||||
style="font-size:54.019px;font-family:Roboto;-inkscape-font-specification:'Roboto, @wght=600';font-variation-settings:'wght' 600;stroke-width:0.270095;fill:#ffffff;fill-opacity:1"
|
||||
id="path10" />
|
||||
<path
|
||||
d="m 18.746659,32.35048 v 35.012333 l 7.483265,0.01602 -0.0078,-15.15153 -0.444417,0.0088 -0.283187,-5.574853 0.724503,-0.09353 -0.0052,-10.30273 c -2.477109,-1.576343 -4.681183,-2.913234 -7.467245,-3.91449 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path4" />
|
||||
<path
|
||||
d="m 34.188094,44.204537 -2.362646,1.228349 -3.40186,0.850077 -2.92902,0.378272 0.283187,5.574853 4.819344,-0.09405 3.024105,-1.03973 2.362129,-1.417484 1.512053,-0.756027 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path3" />
|
||||
<path
|
||||
d="m 30.789852,3.3827393 c -2.718649,-0.031966 -5.436525,0.014505 -8.153508,0.092501 -1.657421,0.047579 -3.410165,1.1618896 -3.915523,2.4758178 -0.117943,1.3009842 -0.120443,2.6260493 -0.194303,3.9361939 -0.03417,4.6029962 0.05579,9.2082292 0.06976,13.8120772 l 8.031551,2.645316 V 15.482776 c -0.06845,-1.616367 -0.186384,-3.220801 5.17e-4,-4.823995 1.450909,-0.02681 2.901798,-0.0533 4.352706,-0.0801 0.05294,-7.58e-4 0.101815,-0.0019 0.146761,-0.0026 -0.133325,0.0041 -0.29154,0.0097 -0.465088,0.01705 5.402012,0.128802 10.810722,0.09637 16.214514,0.01395 1.312459,0.137599 2.534326,-0.34712 3.780648,-0.6609411 0.688414,-0.375834 1.230544,-1.0271554 1.861385,-1.5115356 0.530757,-0.2588779 0.43123,-0.8718681 0.550871,-1.361674 0.317571,-1.2121917 0.137814,-2.4561815 0.111104,-3.690214 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path2" />
|
||||
<path
|
||||
d="m 56.166081,18.073315 c -1.612095,0.517615 -3.326896,0.856005 -4.876705,1.482597 -1.672317,1.636751 -3.569999,3.080027 -4.731494,5.154724 -1.760645,2.382939 -3.026169,5.086524 -4.280876,7.757666 -0.891629,2.073315 -1.768619,4.152921 -2.589506,6.255433 l 4.441073,4.251936 c 1.398551,-3.4772 2.668634,-7.012956 4.53719,-10.275341 0.629987,-1.555517 1.666989,-2.831823 2.828251,-4.022494 1.022671,-1.037894 1.767254,-2.482454 3.326929,-2.735233 0.889424,-0.171791 1.852674,-1.15661 2.651001,-0.326079 1.091115,0.724393 2.380755,1.270451 3.353284,2.101164 0.773793,1.805199 1.727371,3.571064 2.391068,5.400187 -0.10305,3.050467 0.318141,6.150981 -0.478523,9.13536 -0.227898,1.392226 -0.44891,2.787081 -1.327568,3.939294 -0.639724,0.878207 -0.930155,2.134421 -1.788004,2.776575 -1.441269,0.609895 -2.847747,1.462494 -4.310848,1.920296 -1.617481,-0.300784 -3.315903,-0.407844 -4.88394,-0.826823 -2.069996,-1.549653 -4.248341,-2.976127 -5.912301,-4.986259 -2.758844,-2.90603 -5.507188,-5.823363 -8.591207,-8.391735 -3.338252,-2.881492 -6.432985,-6.060987 -10.113077,-8.519377 -1.00535,-0.833342 -2.074808,-1.535604 -3.393075,-1.725476 -2.128037,-0.523545 -4.194319,-1.47308 -6.429582,-1.257805 -2.170664,0.06994 -4.409538,-0.393106 -6.482808,0.438733 -0.9003416,0.331796 -2.1359215,0.232269 -2.4158733,1.361674 -1.9123575,3.173056 -3.6177926,6.486404 -4.6400268,10.062435 -0.4008915,1.586154 -0.4139892,3.222181 -0.038241,4.817794 l 0.1400432,0.924491 c 0.8820904,-2.491562 1.2764827,-5.195371 2.8018961,-7.407299 0.6237014,-1.09468 1.1172001,-2.309336 2.3424927,-2.850472 1.0032429,-0.704794 1.9546502,-1.540401 3.2581987,-1.487765 3.00294,-0.587415 6.099427,-0.06595 9.095052,0.498161 1.4899,0.270585 2.725854,0.959381 4.081922,1.606103 2.823588,1.93021 5.578022,3.981722 8.006229,6.392375 3.658406,4.382924 6.878979,9.116624 10.426754,13.577466 1.153639,1.018099 2.201592,2.226861 3.41943,3.129008 1.866433,0.375292 3.683112,1.179818 5.582605,1.267623 2.379016,-0.109475 4.813761,-0.01813 7.158736,-0.251148 2.193684,-1.301699 4.557492,-2.436561 6.645589,-3.841626 1.382677,-2.657284 2.904182,-5.268723 4.200261,-7.954553 0.355987,-2.855588 0.956499,-5.711351 1.159619,-8.566919 -0.441278,-2.56316 -0.629473,-5.204579 -1.227832,-7.718909 -1.026057,-1.96421 -1.887153,-4.070949 -3.014287,-5.947957 -1.857041,-1.18145 -3.561937,-2.667789 -5.518009,-3.65094 -1.601938,-0.471008 -3.198698,-1.192578 -4.803841,-1.506885 z"
|
||||
style="fill:url(#linearGradient5);stroke-width:0.264583"
|
||||
id="path1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"app_name":"flux","version":"1.3.1","build_number":"47","package_name":"flux"}
|
||||
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -28,14 +28,19 @@ class SessionCubit extends Cubit<SessionState> {
|
||||
: super(const SessionState(status: SessionStatus.initial)) {
|
||||
initializeSession();
|
||||
// Possiamo metterci in ascolto dei cambiamenti di Auth (Login/Logout)
|
||||
_supabase.auth.onAuthStateChange.listen((data) {
|
||||
final AuthChangeEvent event = data.event;
|
||||
if (event == AuthChangeEvent.signedIn) {
|
||||
initializeSession();
|
||||
} else if (event == AuthChangeEvent.signedOut) {
|
||||
emit(const SessionState(status: SessionStatus.unauthenticated));
|
||||
}
|
||||
});
|
||||
_supabase.auth.onAuthStateChange.listen(
|
||||
(data) {
|
||||
final AuthChangeEvent event = data.event;
|
||||
if (event == AuthChangeEvent.signedIn) {
|
||||
initializeSession();
|
||||
} else if (event == AuthChangeEvent.signedOut) {
|
||||
emit(const SessionState(status: SessionStatus.unauthenticated));
|
||||
}
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
debugPrint('Auth state change error: $error');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> initializeSession() async {
|
||||
|
||||
@@ -5,11 +5,13 @@ class Tables {
|
||||
static const String campaigns = 'campaigns';
|
||||
static const String companies = 'companies';
|
||||
static const String customers = 'customers';
|
||||
static const String customerOrders = 'customer_orders';
|
||||
static const String documentSequences = 'document_sequences';
|
||||
static const String models = 'models';
|
||||
static const String notes = 'notes';
|
||||
static const String noteCollaborators = 'note_collaborators';
|
||||
static const String operations = 'operations';
|
||||
static const String operationDetails = 'operation_details';
|
||||
static const String providerLocations = 'provider_locations';
|
||||
static const String providers = 'providers';
|
||||
static const String providersInStores = 'providers_in_stores';
|
||||
@@ -17,6 +19,8 @@ class Tables {
|
||||
static const String staffInStores = 'staff_in_stores';
|
||||
static const String staffMembers = 'staff_members';
|
||||
static const String stores = 'stores';
|
||||
static const String targets = 'targets';
|
||||
static const String individualTargets = 'individual_targets';
|
||||
static const String tasks = 'tasks';
|
||||
static const String taskAssignments = 'task_assignments';
|
||||
static const String taskReminders = 'task_reminders';
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
|
||||
|
||||
/// Modalità di avviso preferita del cliente (condivisa tra Ordini Clienti e Ticket Assistenza)
|
||||
enum ContactPreference {
|
||||
whatsappPrimary(
|
||||
value: 'whatsapp_primary',
|
||||
label: 'WhatsApp (Principale)',
|
||||
shortLabel: 'WA Principale',
|
||||
materialIcon: Icons.chat_bubble_outline_rounded,
|
||||
color: Colors.green,
|
||||
usesAlternativePhone: false,
|
||||
isWhatsapp: true,
|
||||
isCall: false,
|
||||
isEmail: false,
|
||||
),
|
||||
whatsappAlternative(
|
||||
value: 'whatsapp_alternative',
|
||||
label: 'WhatsApp (Recapito Alternativo)',
|
||||
shortLabel: 'WA Alternativo',
|
||||
materialIcon: Icons.chat_bubble_outline_rounded,
|
||||
color: Colors.teal,
|
||||
usesAlternativePhone: true,
|
||||
isWhatsapp: true,
|
||||
isCall: false,
|
||||
isEmail: false,
|
||||
),
|
||||
callPrimary(
|
||||
value: 'call_primary',
|
||||
label: 'Telefonata (Principale)',
|
||||
shortLabel: 'Tel. Principale',
|
||||
materialIcon: Icons.phone_outlined,
|
||||
color: Colors.blue,
|
||||
usesAlternativePhone: false,
|
||||
isWhatsapp: false,
|
||||
isCall: true,
|
||||
isEmail: false,
|
||||
),
|
||||
callAlternative(
|
||||
value: 'call_alternative',
|
||||
label: 'Telefonata (Recapito Alternativo)',
|
||||
shortLabel: 'Tel. Alternativo',
|
||||
materialIcon: Icons.phone_forwarded_outlined,
|
||||
color: Colors.indigo,
|
||||
usesAlternativePhone: true,
|
||||
isWhatsapp: false,
|
||||
isCall: true,
|
||||
isEmail: false,
|
||||
),
|
||||
email(
|
||||
value: 'email',
|
||||
label: 'Email',
|
||||
shortLabel: 'Email',
|
||||
materialIcon: Icons.alternate_email_rounded,
|
||||
color: Colors.deepOrange,
|
||||
usesAlternativePhone: false,
|
||||
isWhatsapp: false,
|
||||
isCall: false,
|
||||
isEmail: true,
|
||||
);
|
||||
|
||||
final String value;
|
||||
final String label;
|
||||
final String shortLabel;
|
||||
final IconData materialIcon;
|
||||
final Color color;
|
||||
final bool usesAlternativePhone;
|
||||
final bool isWhatsapp;
|
||||
final bool isCall;
|
||||
final bool isEmail;
|
||||
|
||||
const ContactPreference({
|
||||
required this.value,
|
||||
required this.label,
|
||||
required this.shortLabel,
|
||||
required this.materialIcon,
|
||||
required this.color,
|
||||
required this.usesAlternativePhone,
|
||||
required this.isWhatsapp,
|
||||
required this.isCall,
|
||||
required this.isEmail,
|
||||
});
|
||||
|
||||
Widget buildIcon({double size = 16, Color? overrideColor}) {
|
||||
final c = overrideColor ?? color;
|
||||
if (isWhatsapp) {
|
||||
return FaIcon(FontAwesomeIcons.whatsapp, size: size, color: c);
|
||||
}
|
||||
return Icon(materialIcon, size: size, color: c);
|
||||
}
|
||||
|
||||
static ContactPreference fromString(
|
||||
String? val, {
|
||||
ContactPreference fallback = ContactPreference.whatsappPrimary,
|
||||
}) {
|
||||
if (val == null || val.trim().isEmpty) return fallback;
|
||||
final clean = val.trim().toLowerCase();
|
||||
for (final item in ContactPreference.values) {
|
||||
if (item.value.toLowerCase() == clean ||
|
||||
item.name.toLowerCase() == clean) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/core/widgets/app_version_label.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
// ==========================================
|
||||
@@ -142,11 +143,24 @@ class _AppMenuState extends State<AppMenu> {
|
||||
Routes.tickets,
|
||||
'/tickets',
|
||||
),
|
||||
_SubMenuItem(
|
||||
'Ordini Clienti',
|
||||
Routes.customerOrders,
|
||||
'/orders',
|
||||
),
|
||||
_SubMenuItem('Tasks', Routes.tasks, '/tasks'),
|
||||
_SubMenuItem('Sticky Notes', Routes.notes, '/notes'),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
_buildRouteItem(
|
||||
title: 'Obiettivi',
|
||||
icon: Icons.track_changes_outlined,
|
||||
routeName: Routes.targets,
|
||||
pathToCheck: '/targets',
|
||||
isCollapsed: effectivelyCollapsed,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// --- IL MENU GERARCHICO (ANAGRAFICHE) ---
|
||||
@@ -189,6 +203,12 @@ class _AppMenuState extends State<AppMenu> {
|
||||
),
|
||||
),
|
||||
|
||||
// --- VERSIONE APP CON HYPERLINK ---
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4.0),
|
||||
child: AppVersionLabel(isCollapsed: effectivelyCollapsed),
|
||||
),
|
||||
|
||||
// --- PULSANTE TOGGLE (Solo Desktop) ---
|
||||
if (!widget.isDrawer)
|
||||
Padding(
|
||||
@@ -249,7 +269,9 @@ class _AppMenuState extends State<AppMenu> {
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -262,11 +284,19 @@ class _AppMenuState extends State<AppMenu> {
|
||||
alpha: 0.4,
|
||||
),
|
||||
selected: isSelected,
|
||||
leading: Icon(icon, color: isSelected ? theme.colorScheme.primary : null),
|
||||
leading: Icon(
|
||||
icon,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
title: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurface,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.clip,
|
||||
@@ -313,7 +343,7 @@ class _AppMenuState extends State<AppMenu> {
|
||||
: FontWeight.normal,
|
||||
color: widget.currentPath == item.pathToCheck
|
||||
? theme.colorScheme.primary
|
||||
: null,
|
||||
: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -330,7 +360,9 @@ class _AppMenuState extends State<AppMenu> {
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -344,12 +376,17 @@ class _AppMenuState extends State<AppMenu> {
|
||||
tilePadding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
leading: Icon(
|
||||
icon,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
title: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurface,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.clip,
|
||||
@@ -375,7 +412,7 @@ class _AppMenuState extends State<AppMenu> {
|
||||
: FontWeight.normal,
|
||||
color: isSubSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.textTheme.bodyMedium?.color,
|
||||
: theme.colorScheme.onSurface,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.clip,
|
||||
|
||||
@@ -12,15 +12,23 @@ import 'package:flux/features/auth/ui/auth_screen.dart';
|
||||
import 'package:flux/features/auth/ui/set_password_screen.dart';
|
||||
import 'package:flux/features/company/bloc/company_settings_cubit.dart';
|
||||
import 'package:flux/features/company/ui/company_settings_screen.dart';
|
||||
import 'package:flux/features/customer_orders/blocs/customer_order_form_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/ui/customer_order_form_screen.dart';
|
||||
import 'package:flux/features/customer_orders/ui/customer_order_list_screen.dart';
|
||||
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
|
||||
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/customers/ui/customer_detail_screen.dart';
|
||||
import 'package:flux/features/customers/ui/customer_form_screen.dart';
|
||||
import 'package:flux/features/customers/ui/customers_list_screen.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_task_list/blocs/dashboard_task_list_cubit.dart';
|
||||
import 'package:flux/features/home/ui/home_screen.dart';
|
||||
import 'package:flux/features/master_data/master_data_hub_content.dart';
|
||||
@@ -42,8 +50,11 @@ import 'package:flux/features/notes/ui/notes_list_screen.dart';
|
||||
import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart';
|
||||
import 'package:flux/features/onboarding/ui/onboarding_screen.dart';
|
||||
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';
|
||||
@@ -60,8 +71,18 @@ import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/features/tickets/ui/ticket_form_screen.dart';
|
||||
import 'package:flux/features/tickets/ui/ticket_list_screen.dart';
|
||||
import 'package:flux/features/tickets/ui/ticket_workspace/ticket_workspace_screen.dart';
|
||||
import 'package:flux/features/targets/blocs/target_form_cubit.dart';
|
||||
import 'package:flux/features/targets/blocs/target_list_cubit.dart';
|
||||
import 'package:flux/features/targets/data/targets_repository.dart';
|
||||
import 'package:flux/features/targets/models/target_model.dart';
|
||||
import 'package:flux/features/targets/blocs/target_detail_cubit.dart';
|
||||
import 'package:flux/features/targets/ui/target_detail_screen.dart';
|
||||
import 'package:flux/features/targets/ui/target_form_screen.dart';
|
||||
import 'package:flux/features/targets/ui/target_list_screen.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
||||
import 'package:flux/features/tracking/models/tracking_model.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -83,8 +104,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"
|
||||
@@ -99,6 +125,9 @@ class AppRouter {
|
||||
if (sessionState.status == SessionStatus.unauthenticated) {
|
||||
// Se sta già andando alle uniche altre pagine pubbliche, lascialo andare
|
||||
if (isGoingToLogin || isGoingToSetPassword) return null;
|
||||
if (path != '/' && path.isNotEmpty) {
|
||||
pendingRoute = state.uri.toString();
|
||||
}
|
||||
// Altrimenti bloccalo e mandalo al login
|
||||
return '/login';
|
||||
}
|
||||
@@ -140,6 +169,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(
|
||||
@@ -178,6 +215,25 @@ class AppRouter {
|
||||
staffId: sessionCubit.state.currentStaffMember?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardTargetProgressCubit>(
|
||||
create: (context) => DashboardTargetProgressCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
staffId: sessionCubit.state.currentStaffMember?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardExpiringContractsCubit>(
|
||||
create: (context) => DashboardExpiringContractsCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardDailyRicontattiCubit>(
|
||||
create: (context) => DashboardDailyRicontattiCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: const HomeScreen(),
|
||||
);
|
||||
@@ -270,13 +326,30 @@ class AppRouter {
|
||||
GoRoute(
|
||||
path: '/operations',
|
||||
name: Routes.operations,
|
||||
builder: (context, state) => const OperationListScreen(),
|
||||
builder: (context, state) {
|
||||
final params = state.extra is OperationFilterParams
|
||||
? state.extra as OperationFilterParams
|
||||
: OperationFilterParams.fromQueryParams(
|
||||
state.uri.queryParameters,
|
||||
);
|
||||
return OperationListScreen(
|
||||
initialFilters: params.isNotEmpty ? params : null,
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/tickets',
|
||||
name: Routes.tickets,
|
||||
builder: (context, state) => const TicketListScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/orders',
|
||||
name: Routes.customerOrders,
|
||||
builder: (context, state) => BlocProvider(
|
||||
create: (_) => sl<CustomerOrderListCubit>(),
|
||||
child: const CustomerOrderListScreen(),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/notes',
|
||||
name: Routes.notes,
|
||||
@@ -310,10 +383,52 @@ class AppRouter {
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/targets',
|
||||
name: Routes.targets,
|
||||
builder: (context, state) => BlocProvider(
|
||||
create: (_) => sl<TargetListCubit>(),
|
||||
child: const TargetListScreen(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// --- DETTAGLI E OPERATIVITÀ (FUORI DALLA SHELL - TUTTO SCHERMO) ---
|
||||
GoRoute(
|
||||
path: '/targets/form',
|
||||
name: Routes.targetForm,
|
||||
builder: (context, state) {
|
||||
final existingTarget = state.extra as TargetModel?;
|
||||
final session = context.read<SessionCubit>().state;
|
||||
final companyId = session.company?.id ?? '';
|
||||
final defaultStoreId = session.currentStore?.id ?? '';
|
||||
|
||||
return BlocProvider<TargetFormCubit>(
|
||||
create: (context) => TargetFormCubit(
|
||||
targetsRepository: sl<TargetsRepository>(),
|
||||
staffRepository: sl<StaffRepository>(),
|
||||
staffCubit: context.read<StaffCubit>(),
|
||||
)..init(
|
||||
initialTarget: existingTarget,
|
||||
companyId: companyId,
|
||||
defaultStoreId: defaultStoreId,
|
||||
),
|
||||
child: const TargetFormScreen(),
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/targets/detail',
|
||||
name: Routes.targetDetail,
|
||||
builder: (context, state) {
|
||||
final target = state.extra as TargetModel;
|
||||
return BlocProvider<TargetDetailCubit>(
|
||||
create: (context) => TargetDetailCubit(target: target)..init(),
|
||||
child: TargetDetailScreen(target: target),
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/providers/form',
|
||||
name: Routes.providerForm,
|
||||
@@ -505,10 +620,61 @@ class AppRouter {
|
||||
existingOperation: record?.operation,
|
||||
),
|
||||
),
|
||||
BlocProvider(
|
||||
create: (context) => OperationDetailsListCubit(
|
||||
details: record?.operation?.details ?? [],
|
||||
),
|
||||
),
|
||||
],
|
||||
child: OperationFormScreen(
|
||||
operationId: realOperationId,
|
||||
existingOperation: record?.operation,
|
||||
operation: record?.operation,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
GoRoute(
|
||||
path: '/orders/form/:id',
|
||||
name: Routes.customerOrderForm,
|
||||
builder: (context, state) {
|
||||
final String pathId = state.pathParameters['id'] ?? 'new';
|
||||
final record =
|
||||
state.extra
|
||||
as ({
|
||||
StaffMemberModel? createdBy,
|
||||
CustomerOrderModel? order,
|
||||
})?;
|
||||
|
||||
final String? realOrderId;
|
||||
if (pathId == 'new') {
|
||||
realOrderId = null;
|
||||
} else if (record?.order?.id != null) {
|
||||
realOrderId = record!.order!.id;
|
||||
} else {
|
||||
realOrderId = pathId;
|
||||
}
|
||||
|
||||
context.read<CustomersListCubit>().loadCustomers();
|
||||
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider(
|
||||
create: (_) => AttachmentsBloc(
|
||||
parentId: realOrderId,
|
||||
parentType: AttachmentParentType.customerOrder,
|
||||
),
|
||||
),
|
||||
BlocProvider(
|
||||
create: (_) => CustomerOrderFormCubit(
|
||||
createdBy: record?.createdBy,
|
||||
existingOrder: record?.order,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: CustomerOrderFormScreen(
|
||||
orderId: realOrderId,
|
||||
order: record?.order,
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -27,4 +27,10 @@ class Routes {
|
||||
static const String tasks = 'tasks';
|
||||
static const String taskForm = 'task-form';
|
||||
static const String reminderSettings = 'reminder-settings';
|
||||
static const String targets = 'targets';
|
||||
static const String targetForm = 'target-form';
|
||||
static const String targetDetail = 'target-detail';
|
||||
static const String financing = 'financing';
|
||||
static const String customerOrders = 'customer-orders';
|
||||
static const String customerOrderForm = 'customer-order-form';
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class EmailResponse extends Equatable {
|
||||
final bool success;
|
||||
final String? to;
|
||||
final String? messageId;
|
||||
final String? error;
|
||||
|
||||
const EmailResponse({
|
||||
required this.success,
|
||||
this.to,
|
||||
this.messageId,
|
||||
this.error,
|
||||
});
|
||||
|
||||
static const empty = EmailResponse(success: false);
|
||||
|
||||
EmailResponse copyWith({
|
||||
bool? success,
|
||||
String? to,
|
||||
String? messageId,
|
||||
String? error,
|
||||
}) {
|
||||
return EmailResponse(
|
||||
success: success ?? this.success,
|
||||
to: to ?? this.to,
|
||||
messageId: messageId ?? this.messageId,
|
||||
error: error ?? this.error,
|
||||
);
|
||||
}
|
||||
|
||||
factory EmailResponse.fromMap(Map<String, dynamic> map) {
|
||||
return EmailResponse(
|
||||
success: map['success'] as bool? ?? false,
|
||||
to: map['to'] as String?,
|
||||
messageId: map['messageId'] as String?,
|
||||
error: map['error'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'success': success,
|
||||
if (to != null) 'to': to,
|
||||
if (messageId != null) 'messageId': messageId,
|
||||
if (error != null) 'error': error,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [success, to, messageId, error];
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/services/email/email_response_model.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
/// Account mittente configurato sulla Edge Function `send-email`.
|
||||
enum EmailSenderAccount {
|
||||
ordini('ordini'),
|
||||
assistenza('assistenza');
|
||||
|
||||
final String value;
|
||||
const EmailSenderAccount(this.value);
|
||||
}
|
||||
|
||||
class EmailService {
|
||||
static const String _functionName = 'send-email';
|
||||
static final RegExp _emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
|
||||
|
||||
final SupabaseClient _supabase;
|
||||
|
||||
EmailService(this._supabase);
|
||||
|
||||
/// Invia un'email tramite la Edge Function `send-email` (SMTP Stalwart).
|
||||
Future<EmailResponse> sendEmail({
|
||||
required String to,
|
||||
required String subject,
|
||||
required String text,
|
||||
String? html,
|
||||
String? replyTo,
|
||||
EmailSenderAccount account = EmailSenderAccount.ordini,
|
||||
}) async {
|
||||
final cleanedTo = to.trim();
|
||||
final cleanedSubject = subject.trim();
|
||||
final cleanedText = text.trim();
|
||||
|
||||
if (cleanedTo.isEmpty) {
|
||||
return const EmailResponse(
|
||||
success: false,
|
||||
error: 'Indirizzo email del cliente mancante.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!_emailRegex.hasMatch(cleanedTo)) {
|
||||
return EmailResponse(
|
||||
success: false,
|
||||
to: cleanedTo,
|
||||
error: 'Indirizzo email non valido: $cleanedTo',
|
||||
);
|
||||
}
|
||||
|
||||
if (cleanedSubject.isEmpty || (cleanedText.isEmpty && (html?.trim().isEmpty ?? true))) {
|
||||
return EmailResponse(
|
||||
success: false,
|
||||
to: cleanedTo,
|
||||
error: 'Oggetto o contenuto email mancanti.',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await _supabase.functions.invoke(
|
||||
_functionName,
|
||||
body: {
|
||||
'to': cleanedTo,
|
||||
'subject': cleanedSubject,
|
||||
'text': cleanedText,
|
||||
'account': account.value,
|
||||
if (html != null && html.trim().isNotEmpty) 'html': html.trim(),
|
||||
if (replyTo != null && replyTo.trim().isNotEmpty)
|
||||
'replyTo': replyTo.trim(),
|
||||
},
|
||||
);
|
||||
|
||||
final data = _decodeData(response.data);
|
||||
if (data != null) {
|
||||
return EmailResponse.fromMap(data);
|
||||
}
|
||||
|
||||
return EmailResponse(
|
||||
success: response.status >= 200 && response.status < 300,
|
||||
to: cleanedTo,
|
||||
error: response.status >= 200 && response.status < 300
|
||||
? null
|
||||
: 'Risposta non valida dal server email (HTTP ${response.status}).',
|
||||
);
|
||||
} on FunctionException catch (e) {
|
||||
debugPrint('EmailService FunctionException (${e.status}): ${e.details}');
|
||||
final details = _decodeData(e.details);
|
||||
if (details != null) {
|
||||
final parsed = EmailResponse.fromMap(details);
|
||||
return parsed.copyWith(
|
||||
success: false,
|
||||
to: parsed.to ?? cleanedTo,
|
||||
error: parsed.error ?? e.reasonPhrase ?? 'Errore invio email.',
|
||||
);
|
||||
}
|
||||
return EmailResponse(
|
||||
success: false,
|
||||
to: cleanedTo,
|
||||
error:
|
||||
e.reasonPhrase ??
|
||||
'Errore di comunicazione con il server email (${e.status}).',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('EmailService error: $e');
|
||||
return EmailResponse(
|
||||
success: false,
|
||||
to: cleanedTo,
|
||||
error: 'Impossibile contattare il servizio email: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic>? _decodeData(dynamic raw) {
|
||||
if (raw is Map<String, dynamic>) {
|
||||
return raw;
|
||||
}
|
||||
if (raw is Map) {
|
||||
return Map<String, dynamic>.from(raw);
|
||||
}
|
||||
if (raw is String && raw.trim().isNotEmpty) {
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
return decoded;
|
||||
}
|
||||
if (decoded is Map) {
|
||||
return Map<String, dynamic>.from(decoded);
|
||||
}
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class WhatsAppResponse extends Equatable {
|
||||
final bool success;
|
||||
final bool exists;
|
||||
final String? phone;
|
||||
final String? chatId;
|
||||
final String? session;
|
||||
final String? messageId;
|
||||
final String? error;
|
||||
|
||||
const WhatsAppResponse({
|
||||
required this.success,
|
||||
required this.exists,
|
||||
this.phone,
|
||||
this.chatId,
|
||||
this.session,
|
||||
this.messageId,
|
||||
this.error,
|
||||
});
|
||||
|
||||
static const empty = WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
);
|
||||
|
||||
WhatsAppResponse copyWith({
|
||||
bool? success,
|
||||
bool? exists,
|
||||
String? phone,
|
||||
String? chatId,
|
||||
String? session,
|
||||
String? messageId,
|
||||
String? error,
|
||||
}) {
|
||||
return WhatsAppResponse(
|
||||
success: success ?? this.success,
|
||||
exists: exists ?? this.exists,
|
||||
phone: phone ?? this.phone,
|
||||
chatId: chatId ?? this.chatId,
|
||||
session: session ?? this.session,
|
||||
messageId: messageId ?? this.messageId,
|
||||
error: error ?? this.error,
|
||||
);
|
||||
}
|
||||
|
||||
factory WhatsAppResponse.fromMap(Map<String, dynamic> map) {
|
||||
return WhatsAppResponse(
|
||||
success: map['success'] as bool? ?? false,
|
||||
exists: map['exists'] as bool? ?? false,
|
||||
phone: map['phone'] as String?,
|
||||
chatId: map['chatId'] as String?,
|
||||
session: map['session'] as String?,
|
||||
messageId: map['messageId'] as String?,
|
||||
error: map['error'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'success': success,
|
||||
'exists': exists,
|
||||
if (phone != null) 'phone': phone,
|
||||
if (chatId != null) 'chatId': chatId,
|
||||
if (session != null) 'session': session,
|
||||
if (messageId != null) 'messageId': messageId,
|
||||
if (error != null) 'error': error,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
success,
|
||||
exists,
|
||||
phone,
|
||||
chatId,
|
||||
session,
|
||||
messageId,
|
||||
error,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/services/whatsapp/whatsapp_response_model.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class WhatsAppService {
|
||||
static const String _functionName = 'send-whatsapp';
|
||||
|
||||
final SupabaseClient _supabase;
|
||||
|
||||
WhatsAppService(this._supabase);
|
||||
|
||||
/// Invia un messaggio WhatsApp tramite la Edge Function `send-whatsapp`.
|
||||
Future<WhatsAppResponse> sendMessage({
|
||||
required String phone,
|
||||
required String message,
|
||||
bool linkPreview = true,
|
||||
}) async {
|
||||
final cleanedPhone = phone.trim();
|
||||
final cleanedMessage = message.trim();
|
||||
|
||||
if (cleanedPhone.isEmpty) {
|
||||
return const WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
error: 'Numero di telefono mancante.',
|
||||
);
|
||||
}
|
||||
|
||||
if (cleanedMessage.isEmpty) {
|
||||
return const WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
error: 'Il messaggio non può essere vuoto.',
|
||||
);
|
||||
}
|
||||
|
||||
return _invoke({
|
||||
'phone': cleanedPhone,
|
||||
'message': cleanedMessage,
|
||||
'linkPreview': linkPreview,
|
||||
});
|
||||
}
|
||||
|
||||
/// Verifica se il numero è registrato su WhatsApp senza inviare alcun messaggio.
|
||||
Future<WhatsAppResponse> checkNumber(String phone) async {
|
||||
final cleanedPhone = phone.trim();
|
||||
|
||||
if (cleanedPhone.isEmpty) {
|
||||
return const WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
error: 'Numero di telefono mancante.',
|
||||
);
|
||||
}
|
||||
|
||||
return _invoke({
|
||||
'phone': cleanedPhone,
|
||||
'checkOnly': true,
|
||||
});
|
||||
}
|
||||
|
||||
/// Scorciatoia booleana per verificare se un numero ha WhatsApp attivo.
|
||||
Future<bool> hasWhatsApp(String phone) async {
|
||||
final result = await checkNumber(phone);
|
||||
return result.exists;
|
||||
}
|
||||
|
||||
Future<WhatsAppResponse> _invoke(Map<String, dynamic> body) async {
|
||||
try {
|
||||
final response = await _supabase.functions.invoke(
|
||||
_functionName,
|
||||
body: body,
|
||||
);
|
||||
|
||||
final data = _decodeData(response.data);
|
||||
if (data != null) {
|
||||
return WhatsAppResponse.fromMap(data);
|
||||
}
|
||||
|
||||
return WhatsAppResponse(
|
||||
success: response.status >= 200 && response.status < 300,
|
||||
exists: false,
|
||||
error: response.status >= 200 && response.status < 300
|
||||
? null
|
||||
: 'Risposta non valida dal server (HTTP ${response.status}).',
|
||||
);
|
||||
} on FunctionException catch (e) {
|
||||
debugPrint('WhatsAppService FunctionException (${e.status}): ${e.details}');
|
||||
final details = _decodeData(e.details);
|
||||
if (details != null) {
|
||||
final parsed = WhatsAppResponse.fromMap(details);
|
||||
return parsed.copyWith(
|
||||
success: false,
|
||||
error: parsed.error ?? e.reasonPhrase ?? 'Errore invio WhatsApp.',
|
||||
);
|
||||
}
|
||||
return WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
error: e.reasonPhrase ?? 'Errore di comunicazione con il server (${e.status}).',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('WhatsAppService error: $e');
|
||||
return WhatsAppResponse(
|
||||
success: false,
|
||||
exists: false,
|
||||
error: 'Impossibile contattare il servizio WhatsApp: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic>? _decodeData(dynamic raw) {
|
||||
if (raw is Map<String, dynamic>) {
|
||||
return raw;
|
||||
}
|
||||
if (raw is Map) {
|
||||
return Map<String, dynamic>.from(raw);
|
||||
}
|
||||
if (raw is String && raw.trim().isNotEmpty) {
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
return decoded;
|
||||
}
|
||||
if (decoded is Map) {
|
||||
return Map<String, dynamic>.from(decoded);
|
||||
}
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+36
-12
@@ -104,11 +104,25 @@ ThemeData fluxDarkTheme = ThemeData(
|
||||
),
|
||||
),
|
||||
|
||||
drawerTheme: const DrawerThemeData(
|
||||
backgroundColor: FluxColors.darkSurface,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
),
|
||||
|
||||
expansionTileTheme: const ExpansionTileThemeData(
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
collapsedIconColor: FluxColors.darkTextSecondary,
|
||||
textColor: FluxColors.darkTextPrimary,
|
||||
collapsedTextColor: FluxColors.darkTextPrimary,
|
||||
),
|
||||
|
||||
listTileTheme: ListTileThemeData(
|
||||
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
// Colore dell'icona (Turchese Flux)
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
selectedColor: FluxColors.primaryBlue,
|
||||
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.15),
|
||||
// Colore del testo
|
||||
titleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextPrimary,
|
||||
@@ -121,9 +135,6 @@ ThemeData fluxDarkTheme = ThemeData(
|
||||
),
|
||||
// Per far apparire la "manina" su Web/Desktop
|
||||
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
|
||||
|
||||
// NOTA: Se overlayColor non esiste, Flutter userà i colori
|
||||
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
|
||||
),
|
||||
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
@@ -189,26 +200,37 @@ ThemeData fluxLightTheme = ThemeData(
|
||||
),
|
||||
),
|
||||
|
||||
drawerTheme: const DrawerThemeData(
|
||||
backgroundColor: FluxColors.lightSurface,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
),
|
||||
|
||||
expansionTileTheme: const ExpansionTileThemeData(
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
collapsedIconColor: FluxColors.lightTextSecondary,
|
||||
textColor: FluxColors.lightTextPrimary,
|
||||
collapsedTextColor: FluxColors.lightTextPrimary,
|
||||
),
|
||||
|
||||
listTileTheme: ListTileThemeData(
|
||||
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
// Colore dell'icona (Turchese Flux)
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
// Colore del testo
|
||||
selectedColor: FluxColors.primaryBlue,
|
||||
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.1),
|
||||
// Colore del testo per il tema chiaro
|
||||
titleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextPrimary,
|
||||
color: FluxColors.lightTextPrimary,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
subtitleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextSecondary,
|
||||
color: FluxColors.lightTextSecondary,
|
||||
fontSize: 13,
|
||||
),
|
||||
// Per far apparire la "manina" su Web/Desktop
|
||||
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
|
||||
|
||||
// NOTA: Se overlayColor non esiste, Flutter userà i colori
|
||||
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
|
||||
),
|
||||
|
||||
// Il pulsante principale rimane Blu Elettrico, molto visibile
|
||||
@@ -260,12 +282,14 @@ extension FluxThemeContext on BuildContext {
|
||||
// --- Testi (La parte mancante) ---
|
||||
// Mappiamo primaryText sul colore del titolo e secondaryText su quello del corpo
|
||||
Color get primaryText =>
|
||||
Theme.of(this).textTheme.titleLarge?.color ?? Colors.white;
|
||||
Theme.of(this).textTheme.titleLarge?.color ??
|
||||
Theme.of(this).colorScheme.onSurface;
|
||||
Color get secondaryText =>
|
||||
Theme.of(this).textTheme.bodyMedium?.color ?? Colors.grey;
|
||||
Theme.of(this).textTheme.bodyMedium?.color ??
|
||||
Theme.of(this).colorScheme.onSurfaceVariant;
|
||||
|
||||
// Opzionale: un colore ancora più tenue per suggerimenti o icone disabilitate
|
||||
Color get hintText =>
|
||||
Theme.of(this).textTheme.bodySmall?.color ??
|
||||
Colors.grey.withValues(alpha: 0.5);
|
||||
Theme.of(this).colorScheme.onSurface.withValues(alpha: 0.5);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
class AutoUpdateService {
|
||||
/// Verifica se la piattaforma corrente supporta l'aggiornamento automatico trasparente
|
||||
static bool get isAutoUpdateSupported {
|
||||
if (kIsWeb) return false;
|
||||
if (Platform.isWindows) return true;
|
||||
if (Platform.isLinux && Platform.environment['APPIMAGE'] != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Scarica l'aggiornamento e lo applica in modo silenzioso
|
||||
static Future<void> downloadAndApplyUpdate({
|
||||
required String downloadUrl,
|
||||
required void Function(double progress, String status) onProgress,
|
||||
}) async {
|
||||
if (kIsWeb) {
|
||||
throw UnsupportedError("L'auto-update non è supportato su Web.");
|
||||
}
|
||||
|
||||
if (Platform.isWindows) {
|
||||
await _updateWindows(downloadUrl, onProgress);
|
||||
} else if (Platform.isLinux) {
|
||||
await _updateLinux(downloadUrl, onProgress);
|
||||
} else {
|
||||
throw UnsupportedError("Piattaforma non supportata per l'auto-update.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gestione aggiornamento Windows
|
||||
static Future<void> _updateWindows(
|
||||
String downloadUrl,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final tempDir = Directory.systemTemp;
|
||||
final installerFile = File('${tempDir.path}\\FluxInstaller_Update.exe');
|
||||
|
||||
if (installerFile.existsSync()) {
|
||||
try {
|
||||
installerFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
onProgress(0.0, "Download aggiornamento in corso...");
|
||||
await _downloadFile(downloadUrl, installerFile, onProgress);
|
||||
|
||||
onProgress(1.0, "Installazione e riavvio in corso...");
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
// Lancia l'installer in modalità silenziosa per utente singolo
|
||||
// /VERYSILENT: nessuna interfaccia
|
||||
// /SUPPRESSMSGBOXES: nessun popup
|
||||
// /NORESTART: non riavvia il PC
|
||||
await Process.start(
|
||||
installerFile.path,
|
||||
['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
|
||||
// Chiude l'applicazione per consentire la sostituzione dei file
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/// Gestione aggiornamento Linux (AppImage in-place)
|
||||
static Future<void> _updateLinux(
|
||||
String downloadUrl,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final currentAppImagePath = Platform.environment['APPIMAGE'];
|
||||
if (currentAppImagePath == null) {
|
||||
throw StateError(
|
||||
"L'applicazione non è in esecuzione come AppImage.",
|
||||
);
|
||||
}
|
||||
|
||||
final newAppImageFile = File('$currentAppImagePath.new');
|
||||
if (newAppImageFile.existsSync()) {
|
||||
try {
|
||||
newAppImageFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
onProgress(0.0, "Download nuova versione in corso...");
|
||||
await _downloadFile(downloadUrl, newAppImageFile, onProgress);
|
||||
|
||||
onProgress(1.0, "Finalizzazione e riavvio...");
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
|
||||
// Assegna il permesso di esecuzione
|
||||
await Process.run('chmod', ['+x', newAppImageFile.path]);
|
||||
|
||||
// Sostituzione atomica del vecchio file AppImage con il nuovo
|
||||
newAppImageFile.renameSync(currentAppImagePath);
|
||||
|
||||
// Rilancia la nuova versione
|
||||
await Process.start(
|
||||
currentAppImagePath,
|
||||
[],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
|
||||
// Termina il processo attuale
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/// Download in streaming con tracciamento del progresso
|
||||
static Future<void> _downloadFile(
|
||||
String url,
|
||||
File destinationFile,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final client = HttpClient();
|
||||
client.autoUncompress = true;
|
||||
|
||||
try {
|
||||
final uri = Uri.parse(url);
|
||||
final request = await client.getUrl(uri);
|
||||
final response = await request.close();
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw HttpException(
|
||||
'Download fallito con codice di stato ${response.statusCode}',
|
||||
uri: uri,
|
||||
);
|
||||
}
|
||||
|
||||
final contentLength = response.contentLength;
|
||||
int downloadedBytes = 0;
|
||||
|
||||
final sink = destinationFile.openWrite();
|
||||
|
||||
await for (final chunk in response) {
|
||||
sink.add(chunk);
|
||||
downloadedBytes += chunk.length;
|
||||
|
||||
if (contentLength > 0) {
|
||||
final progress = (downloadedBytes / contentLength).clamp(0.0, 1.0);
|
||||
final percent = (progress * 100).toStringAsFixed(0);
|
||||
final downloadedMb =
|
||||
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
|
||||
final totalMb = (contentLength / (1024 * 1024)).toStringAsFixed(1);
|
||||
|
||||
onProgress(
|
||||
progress,
|
||||
'Scaricamento: $percent% ($downloadedMb MB di $totalMb MB)',
|
||||
);
|
||||
} else {
|
||||
final downloadedMb =
|
||||
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
|
||||
onProgress(0.5, 'Scaricamento in corso ($downloadedMb MB)...');
|
||||
}
|
||||
}
|
||||
|
||||
await sink.flush();
|
||||
await sink.close();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
/// Utilità per la gestione delle immagini e normalizzazione dell'orientamento EXIF.
|
||||
class ImageUtils {
|
||||
/// Verifica se l'estensione corrisponde a un'immagine supportata.
|
||||
static bool isImageExtension(String? extension) {
|
||||
if (extension == null) return false;
|
||||
final ext = extension.toLowerCase().replaceAll('.', '');
|
||||
return ['jpg', 'jpeg', 'png', 'webp', 'bmp'].contains(ext);
|
||||
}
|
||||
|
||||
/// Verifica se un nome file o percorso è un'immagine supportata.
|
||||
static bool isImagePath(String path) {
|
||||
final dotIndex = path.lastIndexOf('.');
|
||||
if (dotIndex == -1 || dotIndex == path.length - 1) return false;
|
||||
return isImageExtension(path.substring(dotIndex + 1));
|
||||
}
|
||||
|
||||
/// Ruota fisicamente i pixel dell'immagine se contiene metadati EXIF di orientamento
|
||||
/// (tipico delle fotocamere degli smartphone), resettando l'orientamento a 1 (normale).
|
||||
/// Se l'immagine è già dritta o non possiede metadati EXIF, restituisce i byte originali.
|
||||
static Uint8List normalizeOrientation(Uint8List bytes, {String? extension}) {
|
||||
try {
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) return bytes;
|
||||
|
||||
// Se non ha tag di orientamento o è già orientata dritta (1)
|
||||
if (!image.exif.imageIfd.hasOrientation || image.exif.imageIfd.orientation == 1) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Applica la rotazione fisica dei pixel e resetta il tag EXIF
|
||||
final baked = img.bakeOrientation(image);
|
||||
|
||||
final ext = extension?.toLowerCase().replaceAll('.', '');
|
||||
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
|
||||
|
||||
if (isPng) {
|
||||
return Uint8List.fromList(img.encodePng(baked));
|
||||
} else {
|
||||
return Uint8List.fromList(img.encodeJpg(baked, quality: 92));
|
||||
}
|
||||
} catch (_) {
|
||||
// In caso di errore di parsing/decodifica, restituisce i byte inalterati
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/utils/auto_update_service.dart';
|
||||
import 'package:flux/core/utils/version_check_service.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class UpdatePromptHelper {
|
||||
/// Avvia una verifica manuale degli aggiornamenti con feedback visivo immediato
|
||||
static Future<void> showManualUpdateCheck(BuildContext context) async {
|
||||
// Feedback immediato tramite SnackBar
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
messenger.hideCurrentSnackBar();
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Text("Verifica aggiornamenti in corso..."),
|
||||
],
|
||||
),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final currentVersion = await VersionCheckService.getShortVersionString();
|
||||
final updateInfo = await VersionCheckService().checkUpdate();
|
||||
|
||||
if (!context.mounted) return;
|
||||
messenger.hideCurrentSnackBar();
|
||||
|
||||
if (updateInfo != null && updateInfo.hasUpdate) {
|
||||
// Nuova versione disponibile: mostra il dialog informativo e di azione
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: !updateInfo.isMandatory,
|
||||
builder: (dialogContext) => _ManualUpdateDialog(
|
||||
updateInfo: updateInfo,
|
||||
currentVersion: currentVersion,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Nessun aggiornamento: l'app è già all'ultima versione
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: Colors.green.shade700,
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle_outline, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
"Flux è aggiornato all'ultima versione disponibile ($currentVersion).",
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
duration: const Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!context.mounted) return;
|
||||
messenger.hideCurrentSnackBar();
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: Colors.red.shade700,
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
"Impossibile verificare gli aggiornamenti: $e",
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
duration: const Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ManualUpdateDialog extends StatefulWidget {
|
||||
final UpdateInfo updateInfo;
|
||||
final String currentVersion;
|
||||
|
||||
const _ManualUpdateDialog({
|
||||
required this.updateInfo,
|
||||
required this.currentVersion,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_ManualUpdateDialog> createState() => _ManualUpdateDialogState();
|
||||
}
|
||||
|
||||
class _ManualUpdateDialogState extends State<_ManualUpdateDialog> {
|
||||
bool _isUpdating = false;
|
||||
double _downloadProgress = 0.0;
|
||||
String _statusMessage = "";
|
||||
String? _errorMessage;
|
||||
|
||||
Future<void> _startUpdate() async {
|
||||
setState(() {
|
||||
_isUpdating = true;
|
||||
_errorMessage = null;
|
||||
_downloadProgress = 0.0;
|
||||
_statusMessage = "Avvio aggiornamento...";
|
||||
});
|
||||
|
||||
try {
|
||||
await AutoUpdateService.downloadAndApplyUpdate(
|
||||
downloadUrl: widget.updateInfo.downloadUrl,
|
||||
onProgress: (progress, status) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_downloadProgress = progress;
|
||||
_statusMessage = status;
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isUpdating = false;
|
||||
_errorMessage = "Errore durante l'aggiornamento: $e";
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final updateInfo = widget.updateInfo;
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(
|
||||
updateInfo.isMandatory
|
||||
? Icons.warning_amber_rounded
|
||||
: (kIsWeb ? Icons.cached : Icons.system_update),
|
||||
color: updateInfo.isMandatory ? Colors.amber[700] : Colors.blue,
|
||||
size: 28,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
updateInfo.isMandatory
|
||||
? "Aggiornamento Obbligatorio"
|
||||
: "Nuova Versione Disponibile",
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 400),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text.rich(
|
||||
TextSpan(
|
||||
style: const TextStyle(fontSize: 14),
|
||||
children: [
|
||||
const TextSpan(text: "Versione installata: "),
|
||||
TextSpan(
|
||||
text: widget.currentVersion,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const TextSpan(text: "\nNuova versione disponibile: "),
|
||||
TextSpan(
|
||||
text: "v${updateInfo.latestVersion}",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
kIsWeb
|
||||
? "È stata rilasciata una nuova versione. Ricarica la pagina per applicarla."
|
||||
: (updateInfo.isMandatory
|
||||
? "La versione attuale non è più supportata. Aggiorna all'ultima versione per continuare a lavorare."
|
||||
: "Vuoi scaricare e installare l'aggiornamento adesso?"),
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.8),
|
||||
),
|
||||
),
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: const TextStyle(color: Colors.red, fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (_isUpdating) ...[
|
||||
const SizedBox(height: 16),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: LinearProgressIndicator(
|
||||
value: _downloadProgress > 0 ? _downloadProgress : null,
|
||||
minHeight: 8,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_statusMessage,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.7),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: _isUpdating
|
||||
? []
|
||||
: [
|
||||
if (!updateInfo.isMandatory)
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text("PIÙ TARDI"),
|
||||
),
|
||||
if (kIsWeb)
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text("RICARICA ORA"),
|
||||
onPressed: () {
|
||||
html.window.location.reload();
|
||||
},
|
||||
)
|
||||
else if (AutoUpdateService.isAutoUpdateSupported)
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.system_update_alt),
|
||||
label: const Text("AGGIORNA ORA"),
|
||||
onPressed: _startUpdate,
|
||||
)
|
||||
else
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.open_in_browser),
|
||||
label: const Text("SCARICA"),
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo.downloadUrl);
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
if (context.mounted) Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,46 +3,86 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
enum UpdateType {
|
||||
none,
|
||||
optional,
|
||||
mandatory,
|
||||
}
|
||||
|
||||
class UpdateInfo {
|
||||
final UpdateType type;
|
||||
final String latestVersion;
|
||||
final String minVersion;
|
||||
final String downloadUrl;
|
||||
|
||||
const UpdateInfo({
|
||||
required this.type,
|
||||
required this.latestVersion,
|
||||
required this.minVersion,
|
||||
required this.downloadUrl,
|
||||
});
|
||||
|
||||
bool get isMandatory => type == UpdateType.mandatory;
|
||||
bool get isOptional => type == UpdateType.optional;
|
||||
bool get hasUpdate => type != UpdateType.none;
|
||||
}
|
||||
|
||||
class VersionCheckService {
|
||||
Future<String?> checkForceUpdate() async {
|
||||
Future<UpdateInfo?> checkUpdate() async {
|
||||
try {
|
||||
// 1. Capiamo su che piattaforma sta girando l'app in questo istante
|
||||
String currentPlatform = _getCurrentPlatform();
|
||||
final platformAliases = _getPlatformAliases();
|
||||
|
||||
// 2. Recuperiamo SOLO la riga corrispondente alla nostra piattaforma
|
||||
final dbResponse = await Supabase.instance.client
|
||||
.from('app_config')
|
||||
.select('min_version, download_url')
|
||||
.eq('platform', currentPlatform)
|
||||
.maybeSingle(); // Usiamo maybeSingle così se non c'è la riga non crasha
|
||||
.select('platform, min_version, latest_version, download_url');
|
||||
|
||||
if (dbResponse == null) {
|
||||
return null; // Nessuna regola per questa piattaforma
|
||||
if (dbResponse.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String minVersionFromDb = dbResponse['min_version'] as String;
|
||||
String downloadUrl = dbResponse['download_url'] as String;
|
||||
final rows = List<Map<String, dynamic>>.from(dbResponse);
|
||||
final config = rows.firstWhere(
|
||||
(r) {
|
||||
final p = (r['platform'] as String?)?.toLowerCase().trim() ?? '';
|
||||
return platformAliases.any((alias) => alias.toLowerCase() == p);
|
||||
},
|
||||
orElse: () => {},
|
||||
);
|
||||
|
||||
// 3. Recuperiamo la versione locale di Flutter
|
||||
PackageInfo packageInfo = await PackageInfo.fromPlatform();
|
||||
String localVersionRaw = packageInfo.version;
|
||||
if (config.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 🥷 TRUCCO 1: Pulizia totale dai build number (+37) o tag "v"
|
||||
String cleanLocal = localVersionRaw
|
||||
.split('+')
|
||||
.first
|
||||
.replaceAll('v', '')
|
||||
.trim();
|
||||
String cleanDb = minVersionFromDb
|
||||
.split('+')
|
||||
.first
|
||||
.replaceAll('v', '')
|
||||
.trim();
|
||||
final minVersionRaw = (config['min_version'] as String?) ?? '0.0.0';
|
||||
final latestVersionRaw =
|
||||
(config['latest_version'] as String?) ?? minVersionRaw;
|
||||
final downloadUrl = (config['download_url'] as String?) ?? '';
|
||||
|
||||
// 🥷 TRUCCO 2: Confronto Semantico Reale
|
||||
if (_isVersionLower(current: cleanLocal, minimum: cleanDb)) {
|
||||
// Ritorna il link VERO per questa specifica piattaforma preso dal CSV!
|
||||
return downloadUrl;
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
final localVersionRaw = packageInfo.version;
|
||||
|
||||
final cleanLocal = _cleanVersion(localVersionRaw);
|
||||
final cleanMin = _cleanVersion(minVersionRaw);
|
||||
final cleanLatest = _cleanVersion(latestVersionRaw);
|
||||
|
||||
// Se la versione locale è inferiore alla minima ammessa -> obbligatorio
|
||||
if (_isVersionLower(current: cleanLocal, target: cleanMin)) {
|
||||
return UpdateInfo(
|
||||
type: UpdateType.mandatory,
|
||||
latestVersion: latestVersionRaw,
|
||||
minVersion: minVersionRaw,
|
||||
downloadUrl: downloadUrl,
|
||||
);
|
||||
}
|
||||
|
||||
// Se è >= della minima ma inferiore all'ultima disponibile -> facoltativo
|
||||
if (_isVersionLower(current: cleanLocal, target: cleanLatest)) {
|
||||
return UpdateInfo(
|
||||
type: UpdateType.optional,
|
||||
latestVersion: latestVersionRaw,
|
||||
minVersion: minVersionRaw,
|
||||
downloadUrl: downloadUrl,
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -52,43 +92,70 @@ class VersionCheckService {
|
||||
}
|
||||
}
|
||||
|
||||
// Helper ninja per mappare le piattaforme in base alle stringhe del tuo DB
|
||||
String _getCurrentPlatform() {
|
||||
if (kIsWeb) return 'web';
|
||||
if (Platform.isAndroid) return 'android';
|
||||
if (Platform.isIOS) return 'ios';
|
||||
if (Platform.isWindows) return 'windows';
|
||||
if (Platform.isMacOS) return 'macos';
|
||||
if (Platform.isLinux) return 'linux';
|
||||
return 'unknown';
|
||||
Future<String?> checkForceUpdate() async {
|
||||
final info = await checkUpdate();
|
||||
return info?.isMandatory == true ? info?.downloadUrl : null;
|
||||
}
|
||||
|
||||
// Il motore matematico (resta invariato)
|
||||
bool _isVersionLower({required String current, required String minimum}) {
|
||||
if (current == minimum) return false;
|
||||
static Future<String> getAppVersionString() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
return info.buildNumber.isNotEmpty
|
||||
? 'v${info.version}+${info.buildNumber}'
|
||||
: 'v${info.version}';
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
List<int> currentParts = current
|
||||
static Future<String> getFullVersionString() => getAppVersionString();
|
||||
|
||||
static Future<String> getShortVersionString() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
return 'v${info.version}';
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
String _cleanVersion(String raw) {
|
||||
return raw.split('+').first.replaceAll('v', '').trim();
|
||||
}
|
||||
|
||||
List<String> _getPlatformAliases() {
|
||||
if (kIsWeb) return const ['web'];
|
||||
if (Platform.isAndroid) return const ['android'];
|
||||
if (Platform.isIOS) return const ['ios'];
|
||||
if (Platform.isWindows) return const ['windows'];
|
||||
if (Platform.isMacOS) return const ['macos'];
|
||||
if (Platform.isLinux) return const ['AppImage', 'linux'];
|
||||
return const ['unknown'];
|
||||
}
|
||||
|
||||
bool _isVersionLower({required String current, required String target}) {
|
||||
if (current == target) return false;
|
||||
|
||||
final currentParts = current
|
||||
.split('.')
|
||||
.map((e) => int.tryParse(e) ?? 0)
|
||||
.toList();
|
||||
List<int> minParts = minimum
|
||||
final targetParts = target
|
||||
.split('.')
|
||||
.map((e) => int.tryParse(e) ?? 0)
|
||||
.toList();
|
||||
|
||||
while (currentParts.length < 3) {
|
||||
currentParts.add(0);
|
||||
}
|
||||
while (minParts.length < 3) {
|
||||
minParts.add(0);
|
||||
}
|
||||
final maxLength = currentParts.length > targetParts.length
|
||||
? currentParts.length
|
||||
: targetParts.length;
|
||||
|
||||
if (currentParts[0] != minParts[0]) {
|
||||
return currentParts[0] < minParts[0];
|
||||
for (int i = 0; i < maxLength; i++) {
|
||||
final c = i < currentParts.length ? currentParts[i] : 0;
|
||||
final t = i < targetParts.length ? targetParts[i] : 0;
|
||||
if (c != t) {
|
||||
return c < t;
|
||||
}
|
||||
}
|
||||
if (currentParts[1] != minParts[1]) {
|
||||
return currentParts[1] < minParts[1];
|
||||
}
|
||||
return currentParts[2] < minParts[2];
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/// Enum con le festività nazionali italiane
|
||||
enum ItalianHoliday {
|
||||
capodanno(day: 1, month: 1, label: 'Capodanno'),
|
||||
epifania(day: 6, month: 1, label: 'Epifania'),
|
||||
liberazione(day: 25, month: 4, label: 'Festa della Liberazione'),
|
||||
lavoro(day: 1, month: 5, label: 'Festa dei Lavoratori'),
|
||||
repubblica(day: 2, month: 6, label: 'Festa della Repubblica'),
|
||||
ferragosto(day: 15, month: 8, label: 'Ferragosto'),
|
||||
ognissanti(day: 1, month: 11, label: 'Tutti i Santi'),
|
||||
immacolata(day: 8, month: 12, label: 'Immacolata Concezione'),
|
||||
natale(day: 25, month: 12, label: 'Natale'),
|
||||
santoStefano(day: 26, month: 12, label: 'Santo Stefano');
|
||||
|
||||
final int day;
|
||||
final int month;
|
||||
final String label;
|
||||
|
||||
const ItalianHoliday({
|
||||
required this.day,
|
||||
required this.month,
|
||||
required this.label,
|
||||
});
|
||||
|
||||
/// Verifica se una determinata data corrisponde alla festività fissa
|
||||
bool matches(DateTime date) => date.day == day && date.month == month;
|
||||
}
|
||||
|
||||
/// Helper per determinare se un giorno è lavorativo ed effettuare il conteggio dei giorni
|
||||
class WorkingDaysHelper {
|
||||
WorkingDaysHelper._();
|
||||
|
||||
/// Verifica se la data è domenica o festività nazionale italiana (fissa o Pasquetta)
|
||||
static bool isWorkingDay(DateTime date) {
|
||||
// 1. Domenica esclusa
|
||||
if (date.weekday == DateTime.sunday) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. Festività fisse
|
||||
for (final holiday in ItalianHoliday.values) {
|
||||
if (holiday.matches(date)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pasquetta (Lunedì dell'Angelo)
|
||||
final easterMonday = calculateEasterMonday(date.year);
|
||||
if (date.year == easterMonday.year &&
|
||||
date.month == easterMonday.month &&
|
||||
date.day == easterMonday.day) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Calcola la data del Lunedì dell'Angelo (Pasquetta) tramite l'algoritmo di Meeus/Jones/Butcher
|
||||
static DateTime calculateEasterMonday(int year) {
|
||||
final a = year % 19;
|
||||
final b = year ~/ 100;
|
||||
final c = year % 100;
|
||||
final d = b ~/ 4;
|
||||
final e = b % 4;
|
||||
final f = (b + 8) ~/ 25;
|
||||
final g = (b - f + 1) ~/ 3;
|
||||
final h = (19 * a + b - d - g + 15) % 30;
|
||||
final i = c ~/ 4;
|
||||
final k = c % 4;
|
||||
final l = (32 + 2 * e + 2 * i - h - k) % 7;
|
||||
final m = (a + 11 * h + 22 * l) ~/ 451;
|
||||
final month = (h + l - 7 * m + 114) ~/ 31;
|
||||
final day = ((h + l - 7 * m + 114) % 31) + 1;
|
||||
|
||||
final easterSunday = DateTime(year, month, day);
|
||||
// Pasquetta è il giorno successivo a Pasqua
|
||||
return easterSunday.add(const Duration(days: 1));
|
||||
}
|
||||
|
||||
/// Conta i giorni lavorativi compresi tra [start] e [end] (inclusi)
|
||||
static int countWorkingDays(DateTime start, DateTime end) {
|
||||
if (start.isAfter(end)) return 0;
|
||||
|
||||
int count = 0;
|
||||
DateTime current = DateTime(start.year, start.month, start.day);
|
||||
final targetEnd = DateTime(end.year, end.month, end.day);
|
||||
|
||||
while (!current.isAfter(targetEnd)) {
|
||||
if (isWorkingDay(current)) {
|
||||
count++;
|
||||
}
|
||||
current = current.add(const Duration(days: 1));
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// Calcola la ripartizione dei giorni lavorativi per un periodo target:
|
||||
/// - [total]: giorni lavorativi totali del periodo
|
||||
/// - [elapsed]: giorni lavorativi trascorsi fino ad oggi (minimo 1 se il periodo è iniziato)
|
||||
/// - [remaining]: giorni lavorativi rimanenti da oggi (incluso oggi se è giorno lavorativo) a fine periodo
|
||||
static ({int total, int elapsed, int remaining}) calculateWorkingDaysPeriod({
|
||||
required DateTime start,
|
||||
required DateTime end,
|
||||
DateTime? now,
|
||||
}) {
|
||||
final today = now ?? DateTime.now();
|
||||
final cleanToday = DateTime(today.year, today.month, today.day);
|
||||
final cleanStart = DateTime(start.year, start.month, start.day);
|
||||
final cleanEnd = DateTime(end.year, end.month, end.day);
|
||||
|
||||
final total = countWorkingDays(cleanStart, cleanEnd);
|
||||
|
||||
// Se siamo prima dell'inizio del periodo
|
||||
if (cleanToday.isBefore(cleanStart)) {
|
||||
return (total: total, elapsed: 0, remaining: total);
|
||||
}
|
||||
|
||||
// Se siamo oltre la fine del periodo
|
||||
if (cleanToday.isAfter(cleanEnd)) {
|
||||
return (total: total, elapsed: total, remaining: 0);
|
||||
}
|
||||
|
||||
// Siamo all'interno del periodo
|
||||
// Giorni trascorsi: dall'inizio fino a oggi
|
||||
final elapsedDays = countWorkingDays(cleanStart, cleanToday);
|
||||
final remainingDays = countWorkingDays(cleanToday, cleanEnd);
|
||||
|
||||
return (
|
||||
total: total > 0 ? total : 1,
|
||||
elapsed: elapsedDays > 0 ? elapsedDays : 1,
|
||||
remaining: remainingDays > 0 ? remainingDays : 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/utils/update_prompt_helper.dart';
|
||||
import 'package:flux/core/utils/version_check_service.dart';
|
||||
|
||||
class AppVersionLabel extends StatefulWidget {
|
||||
final bool isCollapsed;
|
||||
final bool showIcon;
|
||||
|
||||
const AppVersionLabel({
|
||||
super.key,
|
||||
this.isCollapsed = false,
|
||||
this.showIcon = true,
|
||||
});
|
||||
|
||||
@override
|
||||
State<AppVersionLabel> createState() => _AppVersionLabelState();
|
||||
}
|
||||
|
||||
class _AppVersionLabelState extends State<AppVersionLabel> {
|
||||
String _version = "";
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadVersion();
|
||||
}
|
||||
|
||||
Future<void> _loadVersion() async {
|
||||
final v = await VersionCheckService.getShortVersionString();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_version = v;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_version.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final textMuted = theme.colorScheme.onSurface.withValues(alpha: 0.5);
|
||||
|
||||
if (widget.isCollapsed) {
|
||||
return Tooltip(
|
||||
message: "Flux $_version\nClicca per verificare aggiornamenti",
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
|
||||
child: Container(
|
||||
height: 36,
|
||||
width: 36,
|
||||
alignment: Alignment.center,
|
||||
child: Icon(
|
||||
Icons.info_outline,
|
||||
size: 16,
|
||||
color: textMuted,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Tooltip(
|
||||
message: "Clicca per verificare se ci sono aggiornamenti",
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (widget.showIcon) ...[
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 13,
|
||||
color: textMuted,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
],
|
||||
Text(
|
||||
"Flux $_version",
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: textMuted,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: textMuted.withValues(alpha: 0.4),
|
||||
decorationStyle: TextDecorationStyle.dotted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
|
||||
part 'image_upload_state.dart';
|
||||
@@ -18,9 +19,29 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
|
||||
);
|
||||
}
|
||||
|
||||
void clearFiles() {
|
||||
emit(state.copyWith(status: ImageUploadStatus.initial, stagedFiles: []));
|
||||
}
|
||||
|
||||
void addFiles(List<PlatformFile> files) {
|
||||
final List<PlatformFile> processedFiles = files.map((file) {
|
||||
if (file.bytes != null && ImageUtils.isImagePath(file.name)) {
|
||||
final normalizedBytes = ImageUtils.normalizeOrientation(
|
||||
file.bytes!,
|
||||
extension: file.extension,
|
||||
);
|
||||
return PlatformFile(
|
||||
name: file.name,
|
||||
size: normalizedBytes.length,
|
||||
bytes: normalizedBytes,
|
||||
path: file.path,
|
||||
);
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
|
||||
List<PlatformFile> newFiles = List.from(state.stagedFiles);
|
||||
newFiles.addAll(files);
|
||||
newFiles.addAll(processedFiles);
|
||||
emit(
|
||||
state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
|
||||
);
|
||||
@@ -43,12 +64,19 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
|
||||
stagedFiles: files,
|
||||
),
|
||||
);
|
||||
|
||||
final rawBytes = await photo.readAsBytes();
|
||||
final normalizedBytes = ImageUtils.normalizeOrientation(
|
||||
rawBytes,
|
||||
extension: 'jpg',
|
||||
);
|
||||
|
||||
final List<PlatformFile> newFiles = List.from(files);
|
||||
newFiles.removeLast();
|
||||
final PlatformFile loadedFile = PlatformFile(
|
||||
name: photo.name,
|
||||
size: await photo.length(),
|
||||
bytes: await photo.readAsBytes(),
|
||||
size: normalizedBytes.length,
|
||||
bytes: normalizedBytes,
|
||||
path: photo.path,
|
||||
);
|
||||
newFiles.add(loadedFile);
|
||||
|
||||
@@ -49,45 +49,77 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Upload: $title'),
|
||||
automaticallyImplyLeading:
|
||||
state.status != ImageUploadStatus.uploading,
|
||||
title: Text(title),
|
||||
centerTitle: true,
|
||||
automaticallyImplyLeading: false,
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
// --- SEZIONE PULSANTI (Fotocamera / Galleria) ---
|
||||
// --- BARRA SUPERIORE: ANNULLA / INVIA ---
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 10.0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// ANNULLA
|
||||
Expanded(
|
||||
child: ElevatedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCamera(context),
|
||||
icon: const Icon(Icons.camera_alt),
|
||||
label: const Text('SCATTA'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 16,
|
||||
flex: 2,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCancel(context),
|
||||
icon: const Icon(Icons.close, size: 20),
|
||||
label: const Text(
|
||||
'Annulla',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.red.shade700,
|
||||
side: BorderSide(color: Colors.red.shade300),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// INVIA
|
||||
Expanded(
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleFilePicker(context),
|
||||
icon: const Icon(Icons.folder),
|
||||
label: const Text("GALLERIA"),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 16,
|
||||
flex: 3,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: FilledButton.icon(
|
||||
onPressed:
|
||||
state.stagedFiles.isEmpty ||
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _submitAllFiles(context),
|
||||
icon: const Icon(Icons.cloud_upload, size: 20),
|
||||
label: Text(
|
||||
state.stagedFiles.isEmpty
|
||||
? 'Invia'
|
||||
: 'Invia (${state.stagedFiles.length})',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -96,27 +128,52 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(),
|
||||
const Divider(height: 1),
|
||||
|
||||
// --- SEZIONE ANTEPRIME (La GridView Magica) ---
|
||||
// --- SEZIONE ANTEPRIME ---
|
||||
Expanded(
|
||||
child: state.stagedFiles.isEmpty
|
||||
? const Center(
|
||||
child: Text(
|
||||
"Nessun file selezionato.\nScatta una foto o scegli dalla galleria.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.grey),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.add_photo_alternate_outlined,
|
||||
size: 64,
|
||||
color: Colors.grey,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
"Nessun file selezionato",
|
||||
style: TextStyle(
|
||||
fontSize: 17,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
"Tocca 'Scatta' o 'Galleria' in basso per aggiungere foto o documenti.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: GridView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate:
|
||||
const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount:
|
||||
3, // 3 colonne stile galleria
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
),
|
||||
crossAxisCount: 3,
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
),
|
||||
itemCount: state.stagedFiles.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = state.stagedFiles[index];
|
||||
@@ -145,7 +202,6 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// L'ANTEPRIMA
|
||||
Container(
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
@@ -159,19 +215,10 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: isImg
|
||||
? (file.bytes != null
|
||||
// Se abbiamo i bytes (es. scatto da fotocamera) usiamo quelli (a prova di Web!)
|
||||
? Image.memory(
|
||||
file.bytes!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
// Altrimenti andiamo di file fisico
|
||||
: const Center(
|
||||
child:
|
||||
CircularProgressIndicator(
|
||||
color: Colors.blue,
|
||||
),
|
||||
))
|
||||
? Image.memory(
|
||||
file.bytes!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
: const Column(
|
||||
mainAxisAlignment:
|
||||
MainAxisAlignment.center,
|
||||
@@ -194,11 +241,9 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// IL PULSANTE CESTINO (In alto a destra)
|
||||
Positioned(
|
||||
top: -8,
|
||||
right: -8,
|
||||
top: -6,
|
||||
right: -6,
|
||||
child: GestureDetector(
|
||||
onTap: () => context
|
||||
.read<ImageUploadCubit>()
|
||||
@@ -222,42 +267,113 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
),
|
||||
// --- SEZIONE INVIA E CHIUDI ---
|
||||
|
||||
// --- SEZIONE INFERIORE (A portata di pollice: Scatta e Galleria) ---
|
||||
SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
height: 56,
|
||||
child: ElevatedButton.icon(
|
||||
// Il pulsante si accende SOLO se ci sono file nel carrello
|
||||
onPressed:
|
||||
state.stagedFiles.isEmpty ||
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _submitAllFiles(context),
|
||||
icon: const Icon(Icons.cloud_upload),
|
||||
label: Text(
|
||||
"INVIA ${state.stagedFiles.length} FILE E CHIUDI",
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 12.0,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.06),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, -2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// SCATTA
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
height: 56,
|
||||
child: FilledButton.icon(
|
||||
onPressed:
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCamera(context),
|
||||
icon: const Icon(Icons.camera_alt, size: 24),
|
||||
label: const Text(
|
||||
'Scatta',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
foregroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.onPrimary,
|
||||
const SizedBox(width: 12),
|
||||
// GALLERIA
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
height: 56,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleFilePicker(context),
|
||||
icon: const Icon(
|
||||
Icons.photo_library,
|
||||
size: 24,
|
||||
),
|
||||
label: const Text(
|
||||
'Galleria',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (state.status == ImageUploadStatus.uploading)
|
||||
Container(
|
||||
color: Colors.black45,
|
||||
child: const Center(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Caricamento in corso...',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -266,6 +382,40 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
void _handleCancel(BuildContext context) {
|
||||
final cubit = context.read<ImageUploadCubit>();
|
||||
if (cubit.state.stagedFiles.isNotEmpty) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Annullare caricamento?'),
|
||||
content: const Text('I file selezionati verranno rimossi.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('No, continua'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
|
||||
onPressed: () {
|
||||
Navigator.pop(ctx);
|
||||
cubit.clearFiles();
|
||||
if (Navigator.of(context).canPop()) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
},
|
||||
child: const Text('Sì, annulla'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
if (Navigator.of(context).canPop()) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- LOGICA FOTOCAMERA E LIBRERIA ---
|
||||
Future<void> _handleCamera(BuildContext context) async {
|
||||
final ImageUploadCubit imageUploadCubit = context.read<ImageUploadCubit>();
|
||||
|
||||
@@ -43,6 +43,21 @@ class UploadSuccessScreen extends StatelessWidget {
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 16, color: Colors.black54),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
if (Navigator.of(context).canPop())
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.add_photo_alternate),
|
||||
label: const Text('Carica altri file per questa pratica'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.green.shade800,
|
||||
side: BorderSide(color: Colors.green.shade600),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 20,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,7 +2,7 @@ import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/core/utils/functions.dart';
|
||||
import 'package:pdfx/pdfx.dart';
|
||||
import 'package:pdfrx/pdfrx.dart';
|
||||
import 'package:internet_file/internet_file.dart';
|
||||
|
||||
class PdfViewerWidget extends StatefulWidget {
|
||||
@@ -20,7 +20,7 @@ class PdfViewerWidget extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
late PdfControllerPinch _pdfController;
|
||||
Uint8List? _pdfData;
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
|
||||
@@ -45,11 +45,12 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
throw Exception("Nessun documento trovato");
|
||||
}
|
||||
|
||||
_pdfController = PdfControllerPinch(
|
||||
document: PdfDocument.openData(pdfData),
|
||||
);
|
||||
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_pdfData = pdfData;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
@@ -60,12 +61,6 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pdfController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
@@ -87,7 +82,10 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
body: PdfViewPinch(controller: _pdfController),
|
||||
body: PdfViewer.data(
|
||||
_pdfData!,
|
||||
sourceName: widget.storagePath ?? 'document.pdf',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
class QrUploadDialog extends StatelessWidget {
|
||||
class QrUploadDialog extends StatefulWidget {
|
||||
final String deepLinkUrl;
|
||||
final String title;
|
||||
|
||||
@@ -14,89 +14,143 @@ class QrUploadDialog extends StatelessWidget {
|
||||
required this.title,
|
||||
});
|
||||
|
||||
@override
|
||||
State<QrUploadDialog> createState() => _QrUploadDialogState();
|
||||
}
|
||||
|
||||
class _QrUploadDialogState extends State<QrUploadDialog> {
|
||||
int _initialFileCount = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Memorizziamo quanti file c'erano al momento dell'apertura per contare solo i nuovi ricevuti
|
||||
_initialFileCount = context.read<AttachmentsBloc>().state.allFiles.length;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Usiamo i colori del tema per renderlo coerente col tuo design
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocListener<AttachmentsBloc, AttachmentsState>(
|
||||
listener: (context, state) {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
|
||||
listenWhen: (previous, current) =>
|
||||
previous.allFiles.length < current.allFiles.length,
|
||||
child: AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.qr_code_scanner,
|
||||
size: 48,
|
||||
color: theme.colorScheme.primary,
|
||||
current.allFiles.length > previous.allFiles.length,
|
||||
listener: (context, state) {
|
||||
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Nuovo file ricevuto via QR Code! 📄 ($sessionReceived in questa sessione)',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
height: 400,
|
||||
width: 350,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min, // Fondamentale per i dialog
|
||||
children: [
|
||||
const Text(
|
||||
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors
|
||||
.white, // Lo sfondo bianco salva la vita sui temi scuri
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
duration: const Duration(seconds: 2),
|
||||
backgroundColor: Colors.green.shade700,
|
||||
),
|
||||
);
|
||||
},
|
||||
builder: (context, state) {
|
||||
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.qr_code_scanner,
|
||||
size: 48,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
widget.title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
height: 400,
|
||||
width: 350,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
child: QrImageView(
|
||||
data: deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 200.0,
|
||||
//Opzionale: puoi metterci il logo di FLUX in mezzo!
|
||||
embeddedImage: const AssetImage('assets/images/logo.png'),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: QrImageView(
|
||||
data: widget.deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 200.0,
|
||||
embeddedImage: const AssetImage(
|
||||
'assets/images/logo.png',
|
||||
),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
"In attesa di file...",
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
sessionReceived > 0
|
||||
? Icons.check_circle_outline
|
||||
: Icons.hourglass_empty,
|
||||
size: 18,
|
||||
color: sessionReceived > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
sessionReceived > 0
|
||||
? "$sessionReceived file ricevuti! (In ascolto...)"
|
||||
: "In attesa di file...",
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: sessionReceived > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
|
||||
],
|
||||
if (_initialFileCount > 0 && sessionReceived == 0) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"($_initialFileCount file già presenti nella pratica)",
|
||||
style: const TextStyle(fontSize: 11, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.commonClose),
|
||||
),
|
||||
],
|
||||
actionsAlignment: MainAxisAlignment.center,
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.commonClose),
|
||||
),
|
||||
],
|
||||
actionsAlignment: MainAxisAlignment.center,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,141 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/enums_and_consts/contact_preference.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
|
||||
class ContactPreferenceSection extends StatelessWidget {
|
||||
final ContactPreference selectedPreference;
|
||||
final ValueChanged<ContactPreference> onPreferenceChanged;
|
||||
final CustomerModel? customer;
|
||||
final TextEditingController? alternativePhoneController;
|
||||
final bool alwaysShowAlternativePhone;
|
||||
|
||||
const ContactPreferenceSection({
|
||||
super.key,
|
||||
required this.selectedPreference,
|
||||
required this.onPreferenceChanged,
|
||||
this.customer,
|
||||
this.alternativePhoneController,
|
||||
this.alwaysShowAlternativePhone = false,
|
||||
});
|
||||
|
||||
String _resolveTargetDestination() {
|
||||
final altText =
|
||||
alternativePhoneController?.text.trim().isNotEmpty == true
|
||||
? alternativePhoneController!.text.trim()
|
||||
: (customer?.alternativePhoneNumber.trim() ?? '');
|
||||
|
||||
if (selectedPreference.isEmail) {
|
||||
return customer?.email.trim() ?? '';
|
||||
}
|
||||
if (selectedPreference.usesAlternativePhone) {
|
||||
return altText;
|
||||
}
|
||||
return customer?.phoneNumber.trim() ?? '';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final showAltField =
|
||||
alwaysShowAlternativePhone || selectedPreference.usesAlternativePhone;
|
||||
final destination = _resolveTargetDestination();
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Modalità di Avviso Cliente',
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: ContactPreference.values.map((pref) {
|
||||
final isSelected = pref == selectedPreference;
|
||||
return ChoiceChip(
|
||||
selected: isSelected,
|
||||
showCheckmark: false,
|
||||
avatar: pref.buildIcon(
|
||||
size: 15,
|
||||
overrideColor: isSelected ? pref.color : Colors.grey.shade600,
|
||||
),
|
||||
label: Text(
|
||||
pref.shortLabel,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
|
||||
color: isSelected ? pref.color : null,
|
||||
),
|
||||
),
|
||||
selectedColor: pref.color.withValues(alpha: 0.15),
|
||||
side: BorderSide(
|
||||
color: isSelected
|
||||
? pref.color.withValues(alpha: 0.6)
|
||||
: theme.dividerColor.withValues(alpha: 0.35),
|
||||
),
|
||||
onSelected: (_) => onPreferenceChanged(pref),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
if (customer != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
destination.isNotEmpty
|
||||
? Icons.check_circle_outline_rounded
|
||||
: Icons.warning_amber_rounded,
|
||||
size: 15,
|
||||
color: destination.isNotEmpty ? Colors.green : Colors.orange,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
destination.isNotEmpty
|
||||
? 'Verrà avvisato su: $destination (${selectedPreference.label})'
|
||||
: 'Attenzione: nessun recapito impostato per "${selectedPreference.label}"',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: destination.isNotEmpty
|
||||
? theme.colorScheme.onSurfaceVariant
|
||||
: Colors.orange.shade800,
|
||||
fontWeight: destination.isNotEmpty
|
||||
? FontWeight.normal
|
||||
: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
if (showAltField && alternativePhoneController != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: alternativePhoneController,
|
||||
keyboardType: TextInputType.phone,
|
||||
decoration: InputDecoration(
|
||||
labelText: selectedPreference.usesAlternativePhone
|
||||
? 'Recapito Alternativo *'
|
||||
: 'Recapito Alternativo (opzionale)',
|
||||
hintText: 'Es. telefono coniuge / ufficio...',
|
||||
prefixIcon: const Icon(Icons.phone_forwarded_outlined),
|
||||
helperText: customer != null
|
||||
? 'Se compilato, verrà salvato anche sull\'anagrafica del cliente'
|
||||
: null,
|
||||
),
|
||||
validator: (val) {
|
||||
if (selectedPreference.usesAlternativePhone &&
|
||||
(val == null || val.trim().isEmpty)) {
|
||||
return 'Inserisci il recapito alternativo per avvisare il cliente';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,7 @@ class SharedCustomerSection extends StatelessWidget {
|
||||
),
|
||||
if (hasCustomer &&
|
||||
(customer!.phoneNumber.isNotEmpty ||
|
||||
customer!.alternativePhoneNumber.isNotEmpty ||
|
||||
customer!.email.isNotEmpty)) ...[
|
||||
const SizedBox(height: 12), // Un po' più di respiro dal box sopra
|
||||
// Mettiamo i contatti in un Container con un po' di stile per farli sembrare una "Contact Card" integrata
|
||||
@@ -148,8 +149,79 @@ class SharedCustomerSection extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
|
||||
// Sezione divisoria se ci sono entrambi
|
||||
// --- RIGA RECAPITO ALTERNATIVO ---
|
||||
if (customer!.phoneNumber.isNotEmpty &&
|
||||
customer!.alternativePhoneNumber.isNotEmpty)
|
||||
const Divider(height: 8, thickness: 0.5),
|
||||
|
||||
if (customer!.alternativePhoneNumber.isNotEmpty)
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () => launchUrl(
|
||||
Uri.parse(
|
||||
'https://wa.me/39${customer!.alternativePhoneNumber}',
|
||||
),
|
||||
),
|
||||
icon: const FaIcon(
|
||||
FontAwesomeIcons.whatsapp,
|
||||
color: Colors.teal,
|
||||
size: 20,
|
||||
),
|
||||
tooltip: 'WhatsApp su recapito alternativo',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SelectableText(
|
||||
customer!.alternativePhoneNumber,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Recapito alternativo',
|
||||
style: TextStyle(
|
||||
fontSize: 10.5,
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () {
|
||||
Clipboard.setData(
|
||||
ClipboardData(
|
||||
text: customer!.alternativePhoneNumber,
|
||||
),
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Recapito alternativo copiato!'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.copy,
|
||||
size: 18,
|
||||
color: Colors.grey,
|
||||
),
|
||||
tooltip: 'Copia',
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// Sezione divisoria se c'è email dopo un telefono
|
||||
if ((customer!.phoneNumber.isNotEmpty ||
|
||||
customer!.alternativePhoneNumber.isNotEmpty) &&
|
||||
customer!.email.isNotEmpty)
|
||||
const Divider(height: 8, thickness: 0.5),
|
||||
|
||||
@@ -202,6 +274,57 @@ class SharedCustomerSection extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
// --- RIGA CODICE FISCALE ---
|
||||
if (customer!.fiscalCode != null &&
|
||||
customer!.fiscalCode!.isNotEmpty) ...[
|
||||
const Divider(height: 8, thickness: 0.5),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed:
|
||||
null, // Rimosso il // dopo mailto:, è più sicuro
|
||||
icon: const Icon(
|
||||
Icons.person_outline,
|
||||
color: Colors.green,
|
||||
size: 20,
|
||||
),
|
||||
tooltip: 'Codice Fiscale',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
// L'Expanded è vitale per le email che possono essere lunghissime
|
||||
child: SelectableText(
|
||||
customer!.fiscalCode!,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () {
|
||||
Clipboard.setData(
|
||||
ClipboardData(text: customer!.fiscalCode!),
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Codice Fiscale copiato!'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.copy,
|
||||
size: 18,
|
||||
color: Colors.grey,
|
||||
),
|
||||
tooltip: 'Copia',
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -27,13 +27,26 @@ class SharedModelSection extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final hasModel = modelId != null && modelId!.isNotEmpty;
|
||||
final currentModelId = modelId;
|
||||
final currentModelName = modelName;
|
||||
final hasModelId = currentModelId != null && currentModelId.isNotEmpty;
|
||||
final hasModelName = currentModelName != null && currentModelName.isNotEmpty;
|
||||
final hasModel = hasModelId || hasModelName;
|
||||
|
||||
final String subtitleText;
|
||||
if (hasModelName) {
|
||||
subtitleText = currentModelName;
|
||||
} else if (hasModelId) {
|
||||
subtitleText = 'Modello selezionato';
|
||||
} else {
|
||||
subtitleText = 'Nessun modello selezionato';
|
||||
}
|
||||
|
||||
return ListTile(
|
||||
tileColor: backgroundColor,
|
||||
title: Text(label),
|
||||
subtitle: Text(
|
||||
hasModel ? modelName! : 'Nessun modello selezionato',
|
||||
subtitleText,
|
||||
style: TextStyle(
|
||||
color: hasModel ? null : Colors.grey,
|
||||
fontWeight: hasModel ? FontWeight.bold : FontWeight.normal,
|
||||
@@ -124,8 +137,12 @@ class SharedModelSection extends StatelessWidget {
|
||||
);
|
||||
|
||||
if (newModel != null) {
|
||||
// CHIAMIAMO LA CALLBACK!
|
||||
onModelSelected(newModel.id, newModel.nameWithBrand);
|
||||
final selectedId = newModel.id ?? '';
|
||||
final selectedName =
|
||||
newModel.nameWithBrand.isNotEmpty
|
||||
? newModel.nameWithBrand
|
||||
: newModel.name;
|
||||
onModelSelected(selectedId, selectedName);
|
||||
if (context.mounted) Navigator.pop(modalContext);
|
||||
}
|
||||
},
|
||||
@@ -149,11 +166,12 @@ class SharedModelSection extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
// CHIAMIAMO LA CALLBACK!
|
||||
onModelSelected(
|
||||
deviceModel.id!,
|
||||
deviceModel.nameWithBrand,
|
||||
);
|
||||
final selectedId = deviceModel.id ?? '';
|
||||
final selectedName =
|
||||
deviceModel.nameWithBrand.isNotEmpty
|
||||
? deviceModel.nameWithBrand
|
||||
: deviceModel.name;
|
||||
onModelSelected(selectedId, selectedName);
|
||||
Navigator.pop(modalContext);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -76,11 +76,16 @@ class SharedFilesSection extends StatelessWidget {
|
||||
'https://flux.catelli.it/upload/${state.parentType.name}/$targetId?companyId=$companyId';
|
||||
|
||||
if (context.mounted) {
|
||||
final attachmentBloc =
|
||||
context.read<AttachmentsBloc>();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (_) => QrUploadDialog(
|
||||
deepLinkUrl: deepLink,
|
||||
title: 'Carica File: $titleNameForUpload',
|
||||
builder: (_) => BlocProvider.value(
|
||||
value: attachmentBloc,
|
||||
child: QrUploadDialog(
|
||||
deepLinkUrl: deepLink,
|
||||
title: 'Carica File: $titleNameForUpload',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,9 @@ class StaffSection extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
final staffMembers = state.storeStaff;
|
||||
final staffMembers = state.storeStaff
|
||||
.where((staff) => staff.isActive || staff.id == selectedStaffId)
|
||||
.toList();
|
||||
|
||||
// FIX: Feedback visivo se la lista è vuota
|
||||
if (staffMembers.isEmpty) {
|
||||
|
||||
@@ -61,7 +61,21 @@ class StaffSelectorModal extends StatelessWidget {
|
||||
if (state.status == StaffStatus.loading) {
|
||||
return const CircularProgressIndicator();
|
||||
}
|
||||
final staffList = state.storeStaff;
|
||||
final rawList = state.storeStaff.isNotEmpty
|
||||
? state.storeStaff
|
||||
: state.allStaff;
|
||||
final staffList = rawList.where((s) => s.isActive).toList();
|
||||
|
||||
if (staffList.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24.0),
|
||||
child: Text(
|
||||
'Nessun collaboratore attivo trovato.',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return _buildStaffGrid(context, staffList);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -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,52 @@ 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,
|
||||
customerOrderId:
|
||||
state.parentType == AttachmentParentType.customerOrder
|
||||
? ''
|
||||
: null,
|
||||
name: file.name.fileNameWithoutExtension(),
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: file.bytes,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -171,18 +249,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 +314,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 +336,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 +366,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 +406,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 +413,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
ClearAttachmentSelectionEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
// Svuotiamo brutalmente la lista
|
||||
emit(state.copyWith(selectedFiles: []));
|
||||
}
|
||||
|
||||
@@ -311,38 +422,38 @@ 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);
|
||||
case AttachmentParentType.customerOrder:
|
||||
return file.copyWith(customerOrderId: 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 +472,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 +497,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 +541,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:
|
||||
@@ -428,6 +615,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
return Bucket.companyDocuments;
|
||||
case AttachmentParentType.note:
|
||||
return Bucket.documents;
|
||||
case AttachmentParentType.customerOrder:
|
||||
return Bucket.documents;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -7,7 +7,8 @@ enum AttachmentParentType {
|
||||
ticket('ticket_id'),
|
||||
customer('customer_id'),
|
||||
shippingDocument('shipping_document_id'),
|
||||
note('note_id');
|
||||
note('note_id'),
|
||||
customerOrder('customer_order_id');
|
||||
|
||||
final String dbColumn;
|
||||
const AttachmentParentType(this.dbColumn);
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -44,6 +46,30 @@ class AttachmentsRepository {
|
||||
return 'shipping_document_id';
|
||||
case AttachmentParentType.note:
|
||||
return 'note_id';
|
||||
case AttachmentParentType.customerOrder:
|
||||
return 'customer_order_id';
|
||||
}
|
||||
}
|
||||
|
||||
/// 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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +101,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 +113,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 +158,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
|
||||
@@ -164,6 +202,8 @@ class AttachmentsRepository {
|
||||
AttachmentParentType.ticket: file.ticketId,
|
||||
AttachmentParentType.customer: file.customerId,
|
||||
AttachmentParentType.shippingDocument: file.shippingDocumentId,
|
||||
AttachmentParentType.note: file.noteId,
|
||||
AttachmentParentType.customerOrder: file.customerOrderId,
|
||||
};
|
||||
|
||||
// 2. Simuliamo la rimozione del collegamento per il contesto attuale
|
||||
@@ -185,10 +225,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 +263,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 +272,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 +380,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;
|
||||
@@ -10,9 +26,13 @@ class AttachmentModel extends Equatable {
|
||||
final String? ticketId;
|
||||
final String? shippingDocumentId;
|
||||
final String? noteId;
|
||||
final String? customerOrderId;
|
||||
final String name;
|
||||
final String extension;
|
||||
final String? storagePath;
|
||||
final String? thumbnailPath;
|
||||
final String? croppedStoragePath;
|
||||
final AttachmentViewMode? viewMode;
|
||||
final int fileSize;
|
||||
final Uint8List? localBytes;
|
||||
final String companyId;
|
||||
@@ -25,14 +45,25 @@ class AttachmentModel extends Equatable {
|
||||
this.ticketId,
|
||||
this.shippingDocumentId,
|
||||
this.noteId,
|
||||
this.customerOrderId,
|
||||
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,
|
||||
@@ -42,9 +73,13 @@ class AttachmentModel extends Equatable {
|
||||
ticketId,
|
||||
shippingDocumentId,
|
||||
noteId,
|
||||
customerOrderId,
|
||||
name,
|
||||
extension,
|
||||
storagePath,
|
||||
thumbnailPath,
|
||||
croppedStoragePath,
|
||||
viewMode,
|
||||
fileSize,
|
||||
localBytes,
|
||||
companyId,
|
||||
@@ -54,6 +89,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"];
|
||||
@@ -71,9 +125,13 @@ class AttachmentModel extends Equatable {
|
||||
String? ticketId,
|
||||
String? shippingDocumentId,
|
||||
String? noteId,
|
||||
String? customerOrderId,
|
||||
String? name,
|
||||
String? extension,
|
||||
String? storagePath,
|
||||
String? thumbnailPath,
|
||||
String? croppedStoragePath,
|
||||
AttachmentViewMode? viewMode,
|
||||
int? fileSize,
|
||||
Uint8List? localBytes,
|
||||
String? companyId,
|
||||
@@ -85,9 +143,13 @@ class AttachmentModel extends Equatable {
|
||||
ticketId: ticketId ?? this.ticketId,
|
||||
shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId,
|
||||
noteId: noteId ?? this.noteId,
|
||||
customerOrderId: customerOrderId ?? this.customerOrderId,
|
||||
name: name ?? this.name,
|
||||
extension: extension ?? this.extension,
|
||||
storagePath: storagePath ?? this.storagePath,
|
||||
thumbnailPath: thumbnailPath ?? this.thumbnailPath,
|
||||
croppedStoragePath: croppedStoragePath ?? this.croppedStoragePath,
|
||||
viewMode: viewMode ?? this.viewMode,
|
||||
fileSize: fileSize ?? this.fileSize,
|
||||
localBytes: localBytes ?? this.localBytes,
|
||||
companyId: companyId ?? this.companyId,
|
||||
@@ -104,9 +166,13 @@ class AttachmentModel extends Equatable {
|
||||
ticketId: map['ticket_id'] as String?,
|
||||
shippingDocumentId: map['shipping_document_id'] as String?,
|
||||
noteId: map['note_id'] as String?,
|
||||
customerOrderId: map['customer_order_id'] as String?,
|
||||
name: map['name'] as String,
|
||||
extension: map['extension'] as String,
|
||||
storagePath: map['storage_path'] as String?,
|
||||
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,
|
||||
@@ -125,8 +191,12 @@ class AttachmentModel extends Equatable {
|
||||
'ticket_id': ticketId,
|
||||
'shipping_document_id': shippingDocumentId,
|
||||
'note_id': noteId,
|
||||
'customer_order_id': customerOrderId,
|
||||
'file_size': fileSize,
|
||||
'company_id': companyId,
|
||||
'thumbnail_path': thumbnailPath,
|
||||
'cropped_storage_path': croppedStoragePath,
|
||||
'view_mode': (viewMode ?? AttachmentViewMode.original).value,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,110 +1,360 @@
|
||||
import 'dart:typed_data';
|
||||
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:pdfx/pdfx.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';
|
||||
|
||||
class AttachmentViewerScreen extends StatefulWidget {
|
||||
final AttachmentModel attachment;
|
||||
final AttachmentModel? attachment;
|
||||
final List<AttachmentModel>? attachments;
|
||||
final int initialIndex;
|
||||
final Function(String newName)? onRename;
|
||||
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,
|
||||
required this.attachment,
|
||||
this.attachment,
|
||||
this.attachments,
|
||||
this.initialIndex = 0,
|
||||
this.onRename,
|
||||
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.',
|
||||
);
|
||||
|
||||
@override
|
||||
State<AttachmentViewerScreen> createState() => _AttachmentViewerScreenState();
|
||||
}
|
||||
|
||||
class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
PdfControllerPinch? _pdfController;
|
||||
late List<AttachmentModel> _items;
|
||||
late int _currentIndex;
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
bool _isLoading = true;
|
||||
bool _isSavingRotation = false;
|
||||
String? _errorMessage;
|
||||
Uint8List? _fileBytes;
|
||||
late String _fileName;
|
||||
int _loadToken = 0;
|
||||
int _rotationTurns = 0;
|
||||
bool _showCropped = true;
|
||||
final Map<String, Uint8List> _bytesCache = {};
|
||||
|
||||
bool get isPdf => widget.attachment.extension.toLowerCase() == 'pdf';
|
||||
AttachmentModel get _currentAttachment => _items[_currentIndex];
|
||||
bool get isPdf =>
|
||||
_currentAttachment.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
bool get hasMultipleFiles => _items.length > 1;
|
||||
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();
|
||||
_fileName = widget.attachment.name;
|
||||
_loadFile();
|
||||
}
|
||||
|
||||
Future<void> _loadFile() async {
|
||||
try {
|
||||
// 1. Capiamo da dove prendere i dati
|
||||
if (widget.attachment.localBytes != null) {
|
||||
_fileBytes = widget.attachment.localBytes;
|
||||
} else if (widget.attachment.storagePath != null &&
|
||||
widget.attachment.storagePath!.isNotEmpty) {
|
||||
final signedUrl = await getSignedUrl(widget.attachment.storagePath!);
|
||||
_fileBytes = await InternetFile.get(signedUrl);
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
}
|
||||
|
||||
// 2. Se è PDF, inizializziamo il controller
|
||||
if (isPdf && _fileBytes != null) {
|
||||
_pdfController = PdfControllerPinch(
|
||||
document: PdfDocument.openData(_fileBytes!),
|
||||
);
|
||||
}
|
||||
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
}
|
||||
if (widget.attachments != null && widget.attachments!.isNotEmpty) {
|
||||
_items = List<AttachmentModel>.from(widget.attachments!);
|
||||
_currentIndex = widget.initialIndex.clamp(0, _items.length - 1);
|
||||
} else if (widget.attachment != null) {
|
||||
_items = [widget.attachment!];
|
||||
_currentIndex = 0;
|
||||
} else {
|
||||
_items = [];
|
||||
_currentIndex = 0;
|
||||
}
|
||||
|
||||
if (_items.isNotEmpty) {
|
||||
_showCropped = _computeInitialShowCropped(_currentAttachment);
|
||||
}
|
||||
|
||||
_loadFile();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
_focusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pdfController?.dispose();
|
||||
_focusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _goToPrevious() {
|
||||
if (!canGoPrevious) return;
|
||||
_changeFile(_currentIndex - 1);
|
||||
}
|
||||
|
||||
void _goToNext() {
|
||||
if (!canGoNext) return;
|
||||
_changeFile(_currentIndex + 1);
|
||||
}
|
||||
|
||||
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;
|
||||
_rotationTurns = 0;
|
||||
});
|
||||
_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) {
|
||||
if (canGoPrevious) {
|
||||
_goToPrevious();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
|
||||
if (canGoNext) {
|
||||
_goToNext();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Future<void> _loadFile() async {
|
||||
final token = ++_loadToken;
|
||||
final item = _currentAttachment;
|
||||
|
||||
try {
|
||||
Uint8List? bytes;
|
||||
if (item.localBytes != null) {
|
||||
bytes = item.localBytes;
|
||||
} else {
|
||||
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 && item.localBytes != null) {
|
||||
bytes = ImageUtils.normalizeOrientation(
|
||||
bytes,
|
||||
extension: item.extension,
|
||||
);
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_fileBytes = bytes;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (token != _loadToken || !mounted) return;
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _showRenameDialog() {
|
||||
final ctrl = TextEditingController(text: _fileName);
|
||||
final current = _currentAttachment;
|
||||
final ctrl = TextEditingController(text: current.name);
|
||||
ctrl.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: ctrl.text.length,
|
||||
);
|
||||
final focusNode = FocusNode();
|
||||
final dialogFocusNode = FocusNode();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => focusNode.requestFocus(),
|
||||
(_) => dialogFocusNode.requestFocus(),
|
||||
);
|
||||
return AlertDialog(
|
||||
title: const Text('Rinomina File'),
|
||||
content: TextField(
|
||||
controller: ctrl,
|
||||
focusNode: focusNode,
|
||||
focusNode: dialogFocusNode,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nuovo nome',
|
||||
suffixText: '.${widget.attachment.extension}',
|
||||
suffixText: '.${current.extension}',
|
||||
),
|
||||
onSubmitted: (val) {
|
||||
Navigator.pop(context);
|
||||
if (val.trim().isNotEmpty && widget.onRename != null) {
|
||||
setState(() {
|
||||
_fileName = val.trim();
|
||||
});
|
||||
widget.onRename!(val.trim());
|
||||
}
|
||||
_applyRename(val);
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
@@ -115,73 +365,288 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
if (ctrl.text.trim().isNotEmpty && widget.onRename != null) {
|
||||
setState(() {
|
||||
_fileName = ctrl.text.trim();
|
||||
});
|
||||
widget.onRename!(ctrl.text.trim());
|
||||
}
|
||||
_applyRename(ctrl.text);
|
||||
},
|
||||
child: const Text('Salva'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
).then((_) {
|
||||
if (mounted) {
|
||||
_focusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _applyRename(String val) {
|
||||
final trimmed = val.trim();
|
||||
if (trimmed.isEmpty) return;
|
||||
final current = _currentAttachment;
|
||||
final updated = current.copyWith(name: trimmed);
|
||||
setState(() {
|
||||
_items[_currentIndex] = updated;
|
||||
});
|
||||
widget.onRenameAttachment?.call(current, trimmed);
|
||||
widget.onRename?.call(trimmed);
|
||||
}
|
||||
|
||||
void _confirmDelete() {
|
||||
final current = _currentAttachment;
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Eliminare file?'),
|
||||
content: const Text(
|
||||
'Sei sicuro di voler eliminare questo allegato?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(c); // Chiude dialog
|
||||
widget.onDeleteAttachment?.call(current);
|
||||
widget.onDelete?.call();
|
||||
Navigator.pop(context); // Chiude il viewer
|
||||
},
|
||||
child: const Text('Elimina'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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 Scaffold(
|
||||
backgroundColor: Colors.black87, // Sfondo scuro per i viewer è il top
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
title: Text(_fileName, style: const TextStyle(fontSize: 16)),
|
||||
actions: [
|
||||
if (widget.onRename != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
tooltip: 'Rinomina',
|
||||
onPressed: _showRenameDialog,
|
||||
),
|
||||
if (widget.onDelete != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.redAccent),
|
||||
tooltip: 'Elimina',
|
||||
onPressed: () {
|
||||
// Chiediamo conferma
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Eliminare file?'),
|
||||
content: const Text(
|
||||
'Sei sicuro di voler eliminare questo allegato?',
|
||||
return Focus(
|
||||
focusNode: _focusNode,
|
||||
autofocus: true,
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.black87,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_currentAttachment.name,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (hasMultipleFiles) ...[
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c),
|
||||
child: const Text('Annulla'),
|
||||
if (canToggleCrop)
|
||||
const Text(
|
||||
' • ',
|
||||
style: TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
],
|
||||
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,
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(c); // Chiude dialog
|
||||
widget.onDelete!(); // Lancia eliminazione
|
||||
Navigator.pop(context); // Chiude il viewer
|
||||
},
|
||||
child: const Text('Elimina'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
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),
|
||||
tooltip: 'Ruota',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_rotationTurns = (_rotationTurns + 1) % 4;
|
||||
});
|
||||
},
|
||||
),
|
||||
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),
|
||||
tooltip: 'Rinomina',
|
||||
onPressed: _showRenameDialog,
|
||||
),
|
||||
if (widget.onDelete != null || widget.onDeleteAttachment != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.redAccent),
|
||||
tooltip: 'Elimina',
|
||||
onPressed: _confirmDelete,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: _buildBody(),
|
||||
),
|
||||
// Freccia Precedente
|
||||
if (hasMultipleFiles && canGoPrevious)
|
||||
Positioned(
|
||||
left: 16,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: _NavigationArrowButton(
|
||||
icon: Icons.arrow_back_ios_new_rounded,
|
||||
tooltip: 'File precedente (←)',
|
||||
onPressed: _goToPrevious,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Freccia Successivo
|
||||
if (hasMultipleFiles && canGoNext)
|
||||
Positioned(
|
||||
right: 16,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: _NavigationArrowButton(
|
||||
icon: Icons.arrow_forward_ios_rounded,
|
||||
tooltip: 'File successivo (→)',
|
||||
onPressed: _goToNext,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: _buildBody(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -208,13 +673,63 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
if (isPdf && _pdfController != null) {
|
||||
return PdfViewPinch(controller: _pdfController!);
|
||||
if (isPdf && _fileBytes != null) {
|
||||
return PdfViewer.data(
|
||||
_fileBytes!,
|
||||
sourceName: '${_currentAttachment.id}_${_currentAttachment.name}.pdf',
|
||||
params: const PdfViewerParams(
|
||||
backgroundColor: Colors.transparent,
|
||||
enableKeyboardNavigation: false,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return InteractiveViewer(
|
||||
maxScale: 5.0,
|
||||
child: Center(child: Image.memory(_fileBytes!)),
|
||||
child: Center(
|
||||
child: RotatedBox(
|
||||
quarterTurns: _rotationTurns,
|
||||
child: Image.memory(_fileBytes!),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _NavigationArrowButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String tooltip;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
const _NavigationArrowButton({
|
||||
required this.icon,
|
||||
required this.tooltip,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Tooltip(
|
||||
message: tooltip,
|
||||
child: Material(
|
||||
color: Colors.black.withValues(alpha: 0.55),
|
||||
shape: const CircleBorder(),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
elevation: 6,
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
hoverColor: Colors.white.withValues(alpha: 0.2),
|
||||
splashColor: Colors.white.withValues(alpha: 0.3),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: Colors.white,
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,17 @@ import 'package:flutter/material.dart';
|
||||
class QuickRenameDialog extends StatefulWidget {
|
||||
final String suggestedName;
|
||||
final Widget previewWidget; // Può essere Image.memory o un'icona PDF
|
||||
final String title;
|
||||
final String? suffixText;
|
||||
final String confirmButtonText;
|
||||
|
||||
const QuickRenameDialog({
|
||||
super.key,
|
||||
required this.suggestedName,
|
||||
required this.previewWidget,
|
||||
this.title = 'Rinomina File',
|
||||
this.suffixText = '.pdf',
|
||||
this.confirmButtonText = 'Conferma (Invio)',
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -45,7 +51,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Rinomina per Export'),
|
||||
title: Text(widget.title),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -60,10 +66,10 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
TextField(
|
||||
controller: _nameCtrl,
|
||||
focusNode: _focusNode,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nome del file',
|
||||
suffixText: '.pdf', // Facciamo capire che sarà un PDF
|
||||
border: OutlineInputBorder(),
|
||||
suffixText: widget.suffixText,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
// MAGIA UX 2: Se preme invio sulla tastiera, salva e chiude!
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
@@ -77,7 +83,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.of(context).pop(_nameCtrl.text),
|
||||
child: const Text('Esporta (Invio)'),
|
||||
child: Text(widget.confirmButtonText),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/contact_preference.dart';
|
||||
import 'package:flux/core/services/email/email_service.dart';
|
||||
import 'package:flux/core/services/whatsapp/whatsapp_service.dart';
|
||||
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/features/customer_orders/models/order_notification_result.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_email_helper.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_whatsapp_helper.dart';
|
||||
import 'package:flux/features/customers/data/customer_repository.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'customer_order_form_state.dart';
|
||||
|
||||
class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
|
||||
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
|
||||
final CustomerRepository _customerRepository = sl<CustomerRepository>();
|
||||
final SessionCubit _sessionCubit = sl<SessionCubit>();
|
||||
final WhatsAppService _whatsAppService = sl<WhatsAppService>();
|
||||
final EmailService _emailService = sl<EmailService>();
|
||||
|
||||
bool _pendingReceiptForDraft = false;
|
||||
|
||||
CustomerOrderFormCubit({
|
||||
StaffMemberModel? createdBy,
|
||||
CustomerOrderModel? existingOrder,
|
||||
}) : super(
|
||||
CustomerOrderFormState(
|
||||
order:
|
||||
existingOrder ??
|
||||
CustomerOrderModel.empty().copyWith(
|
||||
createdById: createdBy?.id,
|
||||
createdByName: createdBy?.name,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> initForm({
|
||||
String? orderId,
|
||||
CustomerOrderModel? existingOrder,
|
||||
}) async {
|
||||
final companyId = _sessionCubit.state.company?.id ?? '';
|
||||
|
||||
if (existingOrder != null && existingOrder.id != null) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: existingOrder,
|
||||
status: CustomerOrderFormStatus.ready,
|
||||
),
|
||||
);
|
||||
_loadAvailableTags(companyId);
|
||||
// Aggiorniamo anche in background con i dettagli freschi (es. da scansione o relazioni)
|
||||
final fresh = await _repository.getOrderById(existingOrder.id!);
|
||||
if (fresh != null && !isClosed) {
|
||||
emit(state.copyWith(order: fresh));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (orderId != null && orderId.isNotEmpty) {
|
||||
emit(state.copyWith(status: CustomerOrderFormStatus.loading));
|
||||
final fetched = await _repository.getOrderById(orderId);
|
||||
if (fetched == null) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderFormStatus.failure,
|
||||
errorMessage: 'Ordine non trovato.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: fetched,
|
||||
status: CustomerOrderFormStatus.ready,
|
||||
),
|
||||
);
|
||||
_loadAvailableTags(companyId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Nuovo ordine
|
||||
final currentStore = _sessionCubit.state.currentStore;
|
||||
final currentStaff = _sessionCubit.state.currentStaffMember;
|
||||
final newOrder = state.order.copyWith(
|
||||
companyId: companyId,
|
||||
storeId: currentStore?.id,
|
||||
storeDisplayName: currentStore?.name,
|
||||
createdById: state.order.createdById ?? currentStaff?.id,
|
||||
createdByName: state.order.createdByName ?? currentStaff?.name,
|
||||
orderDate: DateTime.now(),
|
||||
status: CustomerOrderStatus.toOrder,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: newOrder,
|
||||
status: CustomerOrderFormStatus.ready,
|
||||
),
|
||||
);
|
||||
_loadAvailableTags(companyId);
|
||||
}
|
||||
|
||||
Future<void> _loadAvailableTags(String companyId) async {
|
||||
if (companyId.isEmpty) return;
|
||||
final tags = await _repository.fetchDistinctTags(companyId);
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(availableTags: tags));
|
||||
}
|
||||
}
|
||||
|
||||
void updateCustomer(CustomerModel customer) {
|
||||
final currentAlt = state.order.alternativePhoneNumber?.trim() ?? '';
|
||||
final resolvedAlt = currentAlt.isNotEmpty
|
||||
? currentAlt
|
||||
: (customer.alternativePhoneNumber.trim().isNotEmpty
|
||||
? customer.alternativePhoneNumber.trim()
|
||||
: null);
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: state.order.copyWith(
|
||||
customerId: customer.id,
|
||||
customer: customer,
|
||||
alternativePhoneNumber: resolvedAlt,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void updateFields({
|
||||
DateTime? orderDate,
|
||||
String? storeId,
|
||||
String? storeDisplayName,
|
||||
String? productDescription,
|
||||
int? quantity,
|
||||
String? notes,
|
||||
double? price,
|
||||
double? deposit,
|
||||
String? externalCode,
|
||||
CustomerOrderStatus? status,
|
||||
ContactPreference? contactPreference,
|
||||
String? alternativePhoneNumber,
|
||||
bool? customerNotified,
|
||||
}) {
|
||||
DateTime? notifiedAt = state.order.customerNotifiedAt;
|
||||
bool clearNotifiedAt = false;
|
||||
if (customerNotified != null) {
|
||||
if (customerNotified && !state.order.customerNotified) {
|
||||
notifiedAt = DateTime.now();
|
||||
} else if (!customerNotified) {
|
||||
clearNotifiedAt = true;
|
||||
}
|
||||
}
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: state.order.copyWith(
|
||||
orderDate: orderDate ?? state.order.orderDate,
|
||||
storeId: storeId ?? state.order.storeId,
|
||||
storeDisplayName: storeDisplayName ?? state.order.storeDisplayName,
|
||||
productDescription:
|
||||
productDescription ?? state.order.productDescription,
|
||||
quantity: quantity ?? state.order.quantity,
|
||||
notes: notes ?? state.order.notes,
|
||||
price: price ?? state.order.price,
|
||||
deposit: deposit ?? state.order.deposit,
|
||||
externalCode: externalCode ?? state.order.externalCode,
|
||||
status: status ?? state.order.status,
|
||||
contactPreference: contactPreference ?? state.order.contactPreference,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? state.order.alternativePhoneNumber,
|
||||
customerNotified: customerNotified ?? state.order.customerNotified,
|
||||
customerNotifiedAt: notifiedAt,
|
||||
clearCustomerNotifiedAt: clearNotifiedAt,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void addTag(String rawTag) {
|
||||
final clean = rawTag.trim();
|
||||
if (clean.isEmpty) return;
|
||||
final exists = state.order.tags.any(
|
||||
(t) => t.toLowerCase() == clean.toLowerCase(),
|
||||
);
|
||||
if (exists) return;
|
||||
|
||||
final updatedTags = [...state.order.tags, clean];
|
||||
final updatedAvailable = state.availableTags.any(
|
||||
(t) => t.toLowerCase() == clean.toLowerCase(),
|
||||
)
|
||||
? state.availableTags
|
||||
: ([...state.availableTags, clean]
|
||||
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase())));
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
order: state.order.copyWith(tags: updatedTags),
|
||||
availableTags: updatedAvailable,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void removeTag(String tag) {
|
||||
final updatedTags = state.order.tags.where((t) => t != tag).toList();
|
||||
emit(state.copyWith(order: state.order.copyWith(tags: updatedTags)));
|
||||
}
|
||||
|
||||
/// Salva l'ordine (o crea bozza per allegati / QR)
|
||||
Future<CustomerOrderModel?> saveOrder({
|
||||
CustomerOrderStatus? overrideStatus,
|
||||
bool silentForAttachment = false,
|
||||
}) async {
|
||||
final previousStatus = state.order.status;
|
||||
final orderToSave = overrideStatus != null
|
||||
? state.order.copyWith(status: overrideStatus)
|
||||
: state.order;
|
||||
|
||||
if (orderToSave.customerId == null || orderToSave.customerId!.isEmpty) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderFormStatus.failure,
|
||||
errorMessage: 'Seleziona un cliente prima di salvare.',
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (orderToSave.productDescription.trim().isEmpty) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderFormStatus.failure,
|
||||
errorMessage: 'Inserisci il prodotto richiesto dal cliente.',
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!silentForAttachment) {
|
||||
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
|
||||
}
|
||||
|
||||
try {
|
||||
final isBrandNew = orderToSave.id == null || orderToSave.id!.isEmpty;
|
||||
final CustomerOrderModel saved;
|
||||
if (isBrandNew) {
|
||||
saved = await _repository.insertOrder(orderToSave);
|
||||
if (silentForAttachment) {
|
||||
_pendingReceiptForDraft = true;
|
||||
}
|
||||
} else {
|
||||
saved = await _repository.updateOrder(orderToSave);
|
||||
}
|
||||
|
||||
await _syncCustomerAlternativePhone(orderToSave);
|
||||
|
||||
OrderNotificationResult? receiptNotificationResult;
|
||||
final shouldSendReceipt =
|
||||
!silentForAttachment && (isBrandNew || _pendingReceiptForDraft);
|
||||
if (shouldSendReceipt) {
|
||||
_pendingReceiptForDraft = false;
|
||||
if (saved.contactPreference.isWhatsapp) {
|
||||
final phone = saved.effectiveContactDestination;
|
||||
final message = CustomerOrderWhatsAppHelper.buildOrderReceiptMessage(
|
||||
saved,
|
||||
);
|
||||
final waRes = await _whatsAppService.sendMessage(
|
||||
phone: phone,
|
||||
message: message,
|
||||
linkPreview: false,
|
||||
);
|
||||
receiptNotificationResult = OrderNotificationResult.fromWhatsApp(
|
||||
waRes,
|
||||
fallbackDestination: phone,
|
||||
);
|
||||
} else if (saved.contactPreference.isEmail) {
|
||||
final email = saved.effectiveContactDestination;
|
||||
final payload = CustomerOrderEmailHelper.buildOrderReceiptEmail(
|
||||
saved,
|
||||
);
|
||||
final emailRes = await _emailService.sendEmail(
|
||||
to: email,
|
||||
subject: payload.subject,
|
||||
text: payload.text,
|
||||
html: payload.html,
|
||||
);
|
||||
receiptNotificationResult = OrderNotificationResult.fromEmail(
|
||||
emailRes,
|
||||
fallbackDestination: email,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final transitionedToArrived =
|
||||
saved.status == CustomerOrderStatus.arrived &&
|
||||
previousStatus != CustomerOrderStatus.arrived;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: silentForAttachment
|
||||
? CustomerOrderFormStatus.ready
|
||||
: CustomerOrderFormStatus.saved,
|
||||
order: saved,
|
||||
justMarkedArrived: transitionedToArrived,
|
||||
receiptNotificationResult: receiptNotificationResult,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
return saved;
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> markCustomerNotified(bool notified) async {
|
||||
final now = DateTime.now();
|
||||
final updated = state.order.copyWith(
|
||||
customerNotified: notified,
|
||||
customerNotifiedAt: notified ? now : null,
|
||||
clearCustomerNotifiedAt: !notified,
|
||||
);
|
||||
emit(state.copyWith(order: updated));
|
||||
if (updated.id != null && updated.id!.isNotEmpty) {
|
||||
try {
|
||||
final saved = await _repository.updateOrder(updated);
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(order: saved));
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteOrder() async {
|
||||
final id = state.order.id;
|
||||
if (id == null || id.isEmpty) return;
|
||||
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
|
||||
try {
|
||||
await _repository.deleteOrder(id);
|
||||
emit(state.copyWith(status: CustomerOrderFormStatus.deleted));
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _syncCustomerAlternativePhone(CustomerOrderModel order) async {
|
||||
final customer = order.customer;
|
||||
final newAlt = order.alternativePhoneNumber?.trim() ?? '';
|
||||
if (customer == null || customer.id == null || newAlt.isEmpty) return;
|
||||
if (customer.alternativePhoneNumber.trim() == newAlt) return;
|
||||
try {
|
||||
await _customerRepository.updateCustomer(
|
||||
customer.copyWith(alternativePhoneNumber: newAlt),
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
part of 'customer_order_form_cubit.dart';
|
||||
|
||||
enum CustomerOrderFormStatus {
|
||||
initial,
|
||||
loading,
|
||||
ready,
|
||||
saving,
|
||||
saved,
|
||||
deleted,
|
||||
failure,
|
||||
}
|
||||
|
||||
class CustomerOrderFormState extends Equatable {
|
||||
final CustomerOrderFormStatus status;
|
||||
final CustomerOrderModel order;
|
||||
final List<String> availableTags;
|
||||
final String? errorMessage;
|
||||
final bool justMarkedArrived;
|
||||
final OrderNotificationResult? receiptNotificationResult;
|
||||
|
||||
const CustomerOrderFormState({
|
||||
this.status = CustomerOrderFormStatus.initial,
|
||||
required this.order,
|
||||
this.availableTags = const [],
|
||||
this.errorMessage,
|
||||
this.justMarkedArrived = false,
|
||||
this.receiptNotificationResult,
|
||||
});
|
||||
|
||||
CustomerOrderFormState copyWith({
|
||||
CustomerOrderFormStatus? status,
|
||||
CustomerOrderModel? order,
|
||||
List<String>? availableTags,
|
||||
String? errorMessage,
|
||||
bool? justMarkedArrived,
|
||||
OrderNotificationResult? receiptNotificationResult,
|
||||
}) {
|
||||
return CustomerOrderFormState(
|
||||
status: status ?? this.status,
|
||||
order: order ?? this.order,
|
||||
availableTags: availableTags ?? this.availableTags,
|
||||
errorMessage: errorMessage,
|
||||
justMarkedArrived: justMarkedArrived ?? false,
|
||||
receiptNotificationResult: receiptNotificationResult,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
order,
|
||||
availableTags,
|
||||
errorMessage,
|
||||
justMarkedArrived,
|
||||
receiptNotificationResult,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'dart:async';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'customer_order_list_state.dart';
|
||||
|
||||
class CustomerOrderListCubit extends Cubit<CustomerOrderListState> {
|
||||
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
|
||||
final SessionCubit _sessionCubit = sl<SessionCubit>();
|
||||
StreamSubscription<void>? _ordersSubscription;
|
||||
Timer? _searchDebounce;
|
||||
|
||||
CustomerOrderListCubit() : super(const CustomerOrderListState()) {
|
||||
_ordersSubscription = _repository.onOrdersChanged.listen((_) {
|
||||
loadOrders(silent: true);
|
||||
loadTags();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await Future.wait([loadOrders(), loadTags()]);
|
||||
}
|
||||
|
||||
Future<void> loadTags() async {
|
||||
final companyId = _sessionCubit.state.company?.id;
|
||||
if (companyId == null || companyId.isEmpty) return;
|
||||
final tags = await _repository.fetchDistinctTags(companyId);
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(availableTags: tags));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> loadOrders({bool silent = false}) async {
|
||||
final companyId = _sessionCubit.state.company?.id;
|
||||
if (companyId == null || companyId.isEmpty) return;
|
||||
|
||||
if (!silent) {
|
||||
emit(state.copyWith(status: CustomerOrderListStatus.loading));
|
||||
}
|
||||
|
||||
try {
|
||||
final orders = await _repository.fetchOrders(
|
||||
companyId: companyId,
|
||||
quickFilter: state.quickFilter,
|
||||
storeId: state.storeIdFilter,
|
||||
searchTerm: state.searchTerm,
|
||||
dateRange: state.dateRange,
|
||||
selectedTags: state.selectedTags,
|
||||
);
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderListStatus.success,
|
||||
orders: orders,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: CustomerOrderListStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setQuickFilter(CustomerOrderQuickFilter filter) {
|
||||
if (state.quickFilter == filter) return;
|
||||
emit(state.copyWith(quickFilter: filter));
|
||||
loadOrders();
|
||||
}
|
||||
|
||||
void setSearchTerm(String query) {
|
||||
_searchDebounce?.cancel();
|
||||
emit(
|
||||
state.copyWith(
|
||||
searchTerm: query,
|
||||
clearSearchTerm: query.trim().isEmpty,
|
||||
),
|
||||
);
|
||||
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
|
||||
loadOrders();
|
||||
});
|
||||
}
|
||||
|
||||
void setStoreFilter(String? storeId) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
storeIdFilter: storeId,
|
||||
clearStoreFilter: storeId == null || storeId.isEmpty,
|
||||
),
|
||||
);
|
||||
loadOrders();
|
||||
}
|
||||
|
||||
void setDateRange(DateTimeRange? range) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
dateRange: range,
|
||||
clearDateRange: range == null,
|
||||
),
|
||||
);
|
||||
loadOrders();
|
||||
}
|
||||
|
||||
void toggleTagFilter(String tag) {
|
||||
final updated = List<String>.from(state.selectedTags);
|
||||
if (updated.contains(tag)) {
|
||||
updated.remove(tag);
|
||||
} else {
|
||||
updated.add(tag);
|
||||
}
|
||||
emit(state.copyWith(selectedTags: updated));
|
||||
loadOrders();
|
||||
}
|
||||
|
||||
void resetFilters() {
|
||||
emit(
|
||||
state.copyWith(
|
||||
quickFilter: CustomerOrderQuickFilter.active,
|
||||
clearStoreFilter: true,
|
||||
clearSearchTerm: true,
|
||||
clearDateRange: true,
|
||||
selectedTags: const [],
|
||||
),
|
||||
);
|
||||
loadOrders();
|
||||
}
|
||||
|
||||
Future<void> quickUpdateStatus(
|
||||
CustomerOrderModel order,
|
||||
CustomerOrderStatus newStatus,
|
||||
) async {
|
||||
try {
|
||||
await _repository.updateOrder(order.copyWith(status: newStatus));
|
||||
} catch (e) {
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_ordersSubscription?.cancel();
|
||||
_searchDebounce?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
part of 'customer_order_list_cubit.dart';
|
||||
|
||||
enum CustomerOrderListStatus { initial, loading, success, failure }
|
||||
|
||||
class CustomerOrderListState extends Equatable {
|
||||
final CustomerOrderListStatus status;
|
||||
final List<CustomerOrderModel> orders;
|
||||
final List<String> availableTags;
|
||||
final CustomerOrderQuickFilter quickFilter;
|
||||
final String? storeIdFilter;
|
||||
final String? searchTerm;
|
||||
final DateTimeRange? dateRange;
|
||||
final List<String> selectedTags;
|
||||
final String? errorMessage;
|
||||
|
||||
const CustomerOrderListState({
|
||||
this.status = CustomerOrderListStatus.initial,
|
||||
this.orders = const [],
|
||||
this.availableTags = const [],
|
||||
this.quickFilter = CustomerOrderQuickFilter.active,
|
||||
this.storeIdFilter,
|
||||
this.searchTerm,
|
||||
this.dateRange,
|
||||
this.selectedTags = const [],
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
bool get hasAdvancedFilters =>
|
||||
(storeIdFilter != null && storeIdFilter!.isNotEmpty) ||
|
||||
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
|
||||
dateRange != null ||
|
||||
selectedTags.isNotEmpty;
|
||||
|
||||
CustomerOrderListState copyWith({
|
||||
CustomerOrderListStatus? status,
|
||||
List<CustomerOrderModel>? orders,
|
||||
List<String>? availableTags,
|
||||
CustomerOrderQuickFilter? quickFilter,
|
||||
String? storeIdFilter,
|
||||
bool clearStoreFilter = false,
|
||||
String? searchTerm,
|
||||
bool clearSearchTerm = false,
|
||||
DateTimeRange? dateRange,
|
||||
bool clearDateRange = false,
|
||||
List<String>? selectedTags,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return CustomerOrderListState(
|
||||
status: status ?? this.status,
|
||||
orders: orders ?? this.orders,
|
||||
availableTags: availableTags ?? this.availableTags,
|
||||
quickFilter: quickFilter ?? this.quickFilter,
|
||||
storeIdFilter: clearStoreFilter
|
||||
? null
|
||||
: (storeIdFilter ?? this.storeIdFilter),
|
||||
searchTerm: clearSearchTerm ? null : (searchTerm ?? this.searchTerm),
|
||||
dateRange: clearDateRange ? null : (dateRange ?? this.dateRange),
|
||||
selectedTags: selectedTags ?? this.selectedTags,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
orders,
|
||||
availableTags,
|
||||
quickFilter,
|
||||
storeIdFilter,
|
||||
searchTerm,
|
||||
dateRange,
|
||||
selectedTags,
|
||||
errorMessage,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/services/email/email_service.dart';
|
||||
import 'package:flux/core/services/whatsapp/whatsapp_service.dart';
|
||||
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/features/customer_orders/models/order_notification_result.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_email_helper.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_whatsapp_helper.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'mark_order_arrived_state.dart';
|
||||
|
||||
class MarkOrderArrivedCubit extends Cubit<MarkOrderArrivedState> {
|
||||
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
|
||||
final WhatsAppService _whatsAppService = sl<WhatsAppService>();
|
||||
final EmailService _emailService = sl<EmailService>();
|
||||
|
||||
MarkOrderArrivedCubit(CustomerOrderModel order)
|
||||
: super(
|
||||
MarkOrderArrivedState(
|
||||
order: order,
|
||||
sendAutoNotification:
|
||||
order.contactPreference.isWhatsapp ||
|
||||
order.contactPreference.isEmail,
|
||||
),
|
||||
);
|
||||
|
||||
void toggleSendAutoNotification(bool enabled) {
|
||||
emit(state.copyWith(sendAutoNotification: enabled));
|
||||
}
|
||||
|
||||
Future<void> confirmArrival({
|
||||
required String externalCode,
|
||||
required double price,
|
||||
}) async {
|
||||
emit(
|
||||
state.copyWith(
|
||||
step: MarkOrderArrivedStep.submitting,
|
||||
clearErrorMessage: true,
|
||||
clearNotificationResult: true,
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final updatedOrder = state.order.copyWith(
|
||||
status: CustomerOrderStatus.arrived,
|
||||
externalCode: externalCode.trim(),
|
||||
price: price,
|
||||
);
|
||||
|
||||
var saved = await _repository.updateOrder(updatedOrder);
|
||||
OrderNotificationResult? notificationResult;
|
||||
|
||||
if (state.sendAutoNotification && state.supportsAutoNotification) {
|
||||
notificationResult = await _sendArrivalNotification(saved);
|
||||
if (notificationResult != null && notificationResult.success) {
|
||||
saved = await _markNotifiedSafely(saved);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
step: MarkOrderArrivedStep.completed,
|
||||
order: saved,
|
||||
notificationResult: notificationResult,
|
||||
clearErrorMessage: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
step: MarkOrderArrivedStep.editing,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> retryNotification() async {
|
||||
if (state.isBusy || !state.supportsAutoNotification) return;
|
||||
emit(state.copyWith(step: MarkOrderArrivedStep.retryingNotification));
|
||||
|
||||
var currentOrder = state.order;
|
||||
final notificationResult = await _sendArrivalNotification(currentOrder);
|
||||
if (notificationResult != null && notificationResult.success) {
|
||||
currentOrder = await _markNotifiedSafely(currentOrder);
|
||||
}
|
||||
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
step: MarkOrderArrivedStep.completed,
|
||||
order: currentOrder,
|
||||
notificationResult: notificationResult,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<OrderNotificationResult?> _sendArrivalNotification(
|
||||
CustomerOrderModel order,
|
||||
) async {
|
||||
if (order.contactPreference.isWhatsapp) {
|
||||
final phone = order.effectiveContactDestination;
|
||||
final message = CustomerOrderWhatsAppHelper.buildOrderArrivedMessage(
|
||||
order,
|
||||
);
|
||||
final waRes = await _whatsAppService.sendMessage(
|
||||
phone: phone,
|
||||
message: message,
|
||||
linkPreview: false,
|
||||
);
|
||||
return OrderNotificationResult.fromWhatsApp(
|
||||
waRes,
|
||||
fallbackDestination: phone,
|
||||
);
|
||||
}
|
||||
|
||||
if (order.contactPreference.isEmail) {
|
||||
final email = order.effectiveContactDestination;
|
||||
final payload = CustomerOrderEmailHelper.buildOrderArrivedEmail(order);
|
||||
final emailRes = await _emailService.sendEmail(
|
||||
to: email,
|
||||
subject: payload.subject,
|
||||
text: payload.text,
|
||||
html: payload.html,
|
||||
);
|
||||
return OrderNotificationResult.fromEmail(
|
||||
emailRes,
|
||||
fallbackDestination: email,
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<CustomerOrderModel> _markNotifiedSafely(
|
||||
CustomerOrderModel order,
|
||||
) async {
|
||||
try {
|
||||
return await _repository.updateOrder(
|
||||
order.copyWith(
|
||||
customerNotified: true,
|
||||
customerNotifiedAt: DateTime.now(),
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
return order.copyWith(
|
||||
customerNotified: true,
|
||||
customerNotifiedAt: DateTime.now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
part of 'mark_order_arrived_cubit.dart';
|
||||
|
||||
enum MarkOrderArrivedStep {
|
||||
editing,
|
||||
submitting,
|
||||
retryingNotification,
|
||||
completed,
|
||||
}
|
||||
|
||||
class MarkOrderArrivedState extends Equatable {
|
||||
final MarkOrderArrivedStep step;
|
||||
final CustomerOrderModel order;
|
||||
final bool sendAutoNotification;
|
||||
final OrderNotificationResult? notificationResult;
|
||||
final String? errorMessage;
|
||||
|
||||
const MarkOrderArrivedState({
|
||||
this.step = MarkOrderArrivedStep.editing,
|
||||
required this.order,
|
||||
required this.sendAutoNotification,
|
||||
this.notificationResult,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
bool get supportsAutoNotification =>
|
||||
order.contactPreference.isWhatsapp || order.contactPreference.isEmail;
|
||||
|
||||
bool get isBusy =>
|
||||
step == MarkOrderArrivedStep.submitting ||
|
||||
step == MarkOrderArrivedStep.retryingNotification;
|
||||
|
||||
MarkOrderArrivedState copyWith({
|
||||
MarkOrderArrivedStep? step,
|
||||
CustomerOrderModel? order,
|
||||
bool? sendAutoNotification,
|
||||
OrderNotificationResult? notificationResult,
|
||||
bool clearNotificationResult = false,
|
||||
String? errorMessage,
|
||||
bool clearErrorMessage = false,
|
||||
}) {
|
||||
return MarkOrderArrivedState(
|
||||
step: step ?? this.step,
|
||||
order: order ?? this.order,
|
||||
sendAutoNotification: sendAutoNotification ?? this.sendAutoNotification,
|
||||
notificationResult: clearNotificationResult
|
||||
? null
|
||||
: (notificationResult ?? this.notificationResult),
|
||||
errorMessage: clearErrorMessage
|
||||
? null
|
||||
: (errorMessage ?? this.errorMessage),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
step,
|
||||
order,
|
||||
sendAutoNotification,
|
||||
notificationResult,
|
||||
errorMessage,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class CustomerOrdersRepository {
|
||||
final SupabaseClient _supabase = sl<SupabaseClient>();
|
||||
|
||||
final StreamController<void> _ordersChangedController =
|
||||
StreamController<void>.broadcast();
|
||||
|
||||
Stream<void> get onOrdersChanged => _ordersChangedController.stream;
|
||||
|
||||
void notifyOrdersChanged() {
|
||||
if (!_ordersChangedController.isClosed) {
|
||||
_ordersChangedController.add(null);
|
||||
}
|
||||
}
|
||||
|
||||
static const String _selectRelations = '''
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*)
|
||||
''';
|
||||
|
||||
Future<CustomerOrderModel?> getOrderById(String id) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(Tables.customerOrders)
|
||||
.select(_selectRelations)
|
||||
.eq('id', id)
|
||||
.single();
|
||||
return CustomerOrderModel.fromMap(response);
|
||||
} catch (e) {
|
||||
debugPrint('Errore getOrderById ($id): $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<CustomerOrderModel>> fetchOrders({
|
||||
required String companyId,
|
||||
CustomerOrderQuickFilter quickFilter = CustomerOrderQuickFilter.active,
|
||||
String? storeId,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
List<String> selectedTags = const [],
|
||||
}) async {
|
||||
try {
|
||||
var query = _supabase
|
||||
.from(Tables.customerOrders)
|
||||
.select(_selectRelations)
|
||||
.eq('company_id', companyId);
|
||||
|
||||
final statuses = quickFilter.dbStatuses;
|
||||
if (statuses != null && statuses.isNotEmpty) {
|
||||
query = query.inFilter('status', statuses);
|
||||
}
|
||||
|
||||
if (storeId != null && storeId.isNotEmpty) {
|
||||
query = query.eq('store_id', storeId);
|
||||
}
|
||||
|
||||
if (dateRange != null) {
|
||||
final start = DateTime(
|
||||
dateRange.start.year,
|
||||
dateRange.start.month,
|
||||
dateRange.start.day,
|
||||
);
|
||||
final end = DateTime(
|
||||
dateRange.end.year,
|
||||
dateRange.end.month,
|
||||
dateRange.end.day,
|
||||
23,
|
||||
59,
|
||||
59,
|
||||
999,
|
||||
);
|
||||
query = query
|
||||
.gte('order_date', start.toUtc().toIso8601String())
|
||||
.lte('order_date', end.toUtc().toIso8601String());
|
||||
}
|
||||
|
||||
if (selectedTags.isNotEmpty) {
|
||||
query = query.overlaps('tags', selectedTags);
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
|
||||
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
|
||||
List<String> matchingCustomerIds = [];
|
||||
|
||||
try {
|
||||
final custRes = await _supabase
|
||||
.from(Tables.customers)
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%,alternative_phone_number.ilike.%$cleanTerm%');
|
||||
matchingCustomerIds = (custRes as List)
|
||||
.map((row) => row['id'].toString())
|
||||
.toList();
|
||||
} catch (_) {}
|
||||
|
||||
if (matchingCustomerIds.isNotEmpty) {
|
||||
final idsJoined = matchingCustomerIds.join(',');
|
||||
query = query.or(
|
||||
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%,customer_id.in.($idsJoined)',
|
||||
);
|
||||
} else {
|
||||
query = query.or(
|
||||
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final response = await query.order('order_date', ascending: false);
|
||||
|
||||
return (response as List)
|
||||
.map((map) => CustomerOrderModel.fromMap(map as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
debugPrint('Errore fetchOrders: $e');
|
||||
throw Exception('Impossibile caricare gli ordini: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Recupera l'elenco ordinato di tutte le etichette (tags) già usate nell'azienda per l'autocomplete
|
||||
Future<List<String>> fetchDistinctTags(String companyId) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(Tables.customerOrders)
|
||||
.select('tags')
|
||||
.eq('company_id', companyId)
|
||||
.not('tags', 'is', null);
|
||||
|
||||
final Set<String> distinct = {};
|
||||
for (final row in (response as List)) {
|
||||
final rawList = row['tags'] as List?;
|
||||
if (rawList != null) {
|
||||
for (final tag in rawList) {
|
||||
final clean = tag.toString().trim();
|
||||
if (clean.isNotEmpty) distinct.add(clean);
|
||||
}
|
||||
}
|
||||
}
|
||||
final sorted = distinct.toList()
|
||||
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
|
||||
return sorted;
|
||||
} catch (e) {
|
||||
debugPrint('Errore fetchDistinctTags: $e');
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<CustomerOrderModel> insertOrder(CustomerOrderModel order) async {
|
||||
try {
|
||||
final res = await _supabase
|
||||
.from(Tables.customerOrders)
|
||||
.insert(order.toMap())
|
||||
.select(_selectRelations)
|
||||
.single();
|
||||
notifyOrdersChanged();
|
||||
return CustomerOrderModel.fromMap(res);
|
||||
} catch (e) {
|
||||
debugPrint('Errore insertOrder: $e');
|
||||
throw Exception('Errore nella creazione dell\'ordine: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<CustomerOrderModel> updateOrder(CustomerOrderModel order) async {
|
||||
try {
|
||||
final res = await _supabase
|
||||
.from(Tables.customerOrders)
|
||||
.update(order.toMap())
|
||||
.eq('id', order.id!)
|
||||
.select(_selectRelations)
|
||||
.single();
|
||||
notifyOrdersChanged();
|
||||
return CustomerOrderModel.fromMap(res);
|
||||
} catch (e) {
|
||||
debugPrint('Errore updateOrder: $e');
|
||||
throw Exception('Errore nell\'aggiornamento dell\'ordine: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteOrder(String id) async {
|
||||
try {
|
||||
await _supabase.from(Tables.customerOrders).delete().eq('id', id);
|
||||
notifyOrdersChanged();
|
||||
} catch (e) {
|
||||
debugPrint('Errore deleteOrder: $e');
|
||||
throw Exception('Errore nell\'eliminazione dell\'ordine: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/core/enums_and_consts/contact_preference.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
|
||||
class CustomerOrderModel extends Equatable {
|
||||
final String? id;
|
||||
final DateTime? createdAt;
|
||||
final DateTime? updatedAt;
|
||||
final DateTime orderDate;
|
||||
final String companyId;
|
||||
final String? storeId;
|
||||
final String? storeDisplayName;
|
||||
final String? createdById;
|
||||
final String? createdByName;
|
||||
final String? customerId;
|
||||
final CustomerModel? customer;
|
||||
final String productDescription;
|
||||
final int quantity;
|
||||
final String notes;
|
||||
final double price;
|
||||
final double deposit;
|
||||
final String externalCode;
|
||||
final CustomerOrderStatus status;
|
||||
final List<String> tags;
|
||||
final ContactPreference contactPreference;
|
||||
final String? alternativePhoneNumber;
|
||||
final bool customerNotified;
|
||||
final DateTime? customerNotifiedAt;
|
||||
final List<AttachmentModel> attachments;
|
||||
|
||||
const CustomerOrderModel({
|
||||
this.id,
|
||||
this.createdAt,
|
||||
this.updatedAt,
|
||||
required this.orderDate,
|
||||
required this.companyId,
|
||||
this.storeId,
|
||||
this.storeDisplayName,
|
||||
this.createdById,
|
||||
this.createdByName,
|
||||
this.customerId,
|
||||
this.customer,
|
||||
this.productDescription = '',
|
||||
this.quantity = 1,
|
||||
this.notes = '',
|
||||
this.price = 0.0,
|
||||
this.deposit = 0.0,
|
||||
this.externalCode = '',
|
||||
this.status = CustomerOrderStatus.toOrder,
|
||||
this.tags = const [],
|
||||
this.contactPreference = ContactPreference.whatsappPrimary,
|
||||
this.alternativePhoneNumber,
|
||||
this.customerNotified = false,
|
||||
this.customerNotifiedAt,
|
||||
this.attachments = const [],
|
||||
});
|
||||
|
||||
/// Importo residuo da incassare in cassa al netto dell'eventuale acconto
|
||||
double get remainingAmount =>
|
||||
(price - deposit) > 0 ? (price - deposit) : 0.0;
|
||||
|
||||
/// URL deep link codificato nel QR dell'etichetta prodotto
|
||||
String get deepLinkUrl =>
|
||||
id != null && id!.isNotEmpty ? 'https://flux.catelli.it/orders/form/$id' : '';
|
||||
|
||||
/// Recapito effettivo da usare in base alla preferenza scelta
|
||||
String get effectiveContactDestination {
|
||||
if (contactPreference.isEmail) {
|
||||
return customer?.email.trim() ?? '';
|
||||
}
|
||||
if (contactPreference.usesAlternativePhone) {
|
||||
final orderAlt = alternativePhoneNumber?.trim() ?? '';
|
||||
if (orderAlt.isNotEmpty) return orderAlt;
|
||||
return customer?.alternativePhoneNumber.trim() ?? '';
|
||||
}
|
||||
return customer?.phoneNumber.trim() ?? '';
|
||||
}
|
||||
|
||||
factory CustomerOrderModel.empty() => CustomerOrderModel(
|
||||
orderDate: DateTime.now(),
|
||||
companyId: '',
|
||||
);
|
||||
|
||||
CustomerOrderModel copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
DateTime? orderDate,
|
||||
String? companyId,
|
||||
String? storeId,
|
||||
String? storeDisplayName,
|
||||
String? createdById,
|
||||
String? createdByName,
|
||||
String? customerId,
|
||||
CustomerModel? customer,
|
||||
String? productDescription,
|
||||
int? quantity,
|
||||
String? notes,
|
||||
double? price,
|
||||
double? deposit,
|
||||
String? externalCode,
|
||||
CustomerOrderStatus? status,
|
||||
List<String>? tags,
|
||||
ContactPreference? contactPreference,
|
||||
String? alternativePhoneNumber,
|
||||
bool? customerNotified,
|
||||
DateTime? customerNotifiedAt,
|
||||
bool clearCustomerNotifiedAt = false,
|
||||
List<AttachmentModel>? attachments,
|
||||
}) {
|
||||
return CustomerOrderModel(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
orderDate: orderDate ?? this.orderDate,
|
||||
companyId: companyId ?? this.companyId,
|
||||
storeId: storeId ?? this.storeId,
|
||||
storeDisplayName: storeDisplayName ?? this.storeDisplayName,
|
||||
createdById: createdById ?? this.createdById,
|
||||
createdByName: createdByName ?? this.createdByName,
|
||||
customerId: customerId ?? this.customerId,
|
||||
customer: customer ?? this.customer,
|
||||
productDescription: productDescription ?? this.productDescription,
|
||||
quantity: quantity != null ? (quantity < 1 ? 1 : quantity) : this.quantity,
|
||||
notes: notes ?? this.notes,
|
||||
price: price ?? this.price,
|
||||
deposit: deposit ?? this.deposit,
|
||||
externalCode: externalCode ?? this.externalCode,
|
||||
status: status ?? this.status,
|
||||
tags: tags ?? this.tags,
|
||||
contactPreference: contactPreference ?? this.contactPreference,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? this.alternativePhoneNumber,
|
||||
customerNotified: customerNotified ?? this.customerNotified,
|
||||
customerNotifiedAt: clearCustomerNotifiedAt
|
||||
? null
|
||||
: (customerNotifiedAt ?? this.customerNotifiedAt),
|
||||
attachments: attachments ?? this.attachments,
|
||||
);
|
||||
}
|
||||
|
||||
factory CustomerOrderModel.fromMap(Map<String, dynamic> map) {
|
||||
final rawQty = (map['quantity'] as num?)?.toInt() ?? 1;
|
||||
final rawTags = (map['tags'] as List?)
|
||||
?.map((e) => e.toString().trim())
|
||||
.where((e) => e.isNotEmpty)
|
||||
.toList() ??
|
||||
const <String>[];
|
||||
|
||||
final createdAtLocal = map['created_at'] != null
|
||||
? DateTime.parse(map['created_at'] as String).toLocal()
|
||||
: null;
|
||||
|
||||
return CustomerOrderModel(
|
||||
id: map['id'] as String?,
|
||||
createdAt: createdAtLocal,
|
||||
updatedAt: map['updated_at'] != null
|
||||
? DateTime.parse(map['updated_at'] as String).toLocal()
|
||||
: null,
|
||||
orderDate: map['order_date'] != null
|
||||
? DateTime.parse(map['order_date'] as String).toLocal()
|
||||
: (createdAtLocal ?? DateTime.now()),
|
||||
companyId: map['company_id'] as String? ?? '',
|
||||
storeId: map['store_id'] as String?,
|
||||
storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(),
|
||||
createdById: map['created_by_id'] as String?,
|
||||
createdByName: (map[Tables.staffMembers]?['name'] as String?)?.myFormat(),
|
||||
customerId: map['customer_id'] as String?,
|
||||
customer: map[Tables.customers] != null
|
||||
? CustomerModel.fromMap(
|
||||
map[Tables.customers] as Map<String, dynamic>,
|
||||
)
|
||||
: null,
|
||||
productDescription: map['product_description'] as String? ?? '',
|
||||
quantity: rawQty < 1 ? 1 : rawQty,
|
||||
notes: map['notes'] as String? ?? '',
|
||||
price: (map['price'] as num?)?.toDouble() ?? 0.0,
|
||||
deposit: (map['deposit'] as num?)?.toDouble() ?? 0.0,
|
||||
externalCode: map['external_code'] as String? ?? '',
|
||||
status: CustomerOrderStatus.fromString(map['status'] as String?),
|
||||
tags: rawTags,
|
||||
contactPreference: ContactPreference.fromString(
|
||||
map['contact_preference'] as String?,
|
||||
),
|
||||
alternativePhoneNumber: map['alternative_phone_number'] as String?,
|
||||
customerNotified: map['customer_notified'] as bool? ?? false,
|
||||
customerNotifiedAt: map['customer_notified_at'] != null
|
||||
? DateTime.parse(map['customer_notified_at'] as String).toLocal()
|
||||
: null,
|
||||
attachments: (map[Tables.attachments] as List?)
|
||||
?.map(
|
||||
(x) => AttachmentModel.fromMap(x as Map<String, dynamic>),
|
||||
)
|
||||
.toList() ??
|
||||
const [],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
if (id != null && id!.isNotEmpty) 'id': id,
|
||||
'order_date': orderDate.toUtc().toIso8601String(),
|
||||
'company_id': companyId,
|
||||
'store_id': storeId,
|
||||
if (createdById != null && createdById!.isNotEmpty)
|
||||
'created_by_id': createdById,
|
||||
'customer_id': customerId,
|
||||
'product_description': productDescription.trim(),
|
||||
'quantity': quantity < 1 ? 1 : quantity,
|
||||
'notes': notes.trim(),
|
||||
'price': price,
|
||||
'deposit': deposit,
|
||||
'external_code': externalCode.trim(),
|
||||
'status': status.value,
|
||||
'tags': tags.map((t) => t.trim()).where((t) => t.isNotEmpty).toList(),
|
||||
'contact_preference': contactPreference.value,
|
||||
'alternative_phone_number': alternativePhoneNumber?.trim(),
|
||||
'customer_notified': customerNotified,
|
||||
'customer_notified_at': customerNotifiedAt?.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
orderDate,
|
||||
companyId,
|
||||
storeId,
|
||||
storeDisplayName,
|
||||
createdById,
|
||||
createdByName,
|
||||
customerId,
|
||||
customer,
|
||||
productDescription,
|
||||
quantity,
|
||||
notes,
|
||||
price,
|
||||
deposit,
|
||||
externalCode,
|
||||
status,
|
||||
tags,
|
||||
contactPreference,
|
||||
alternativePhoneNumber,
|
||||
customerNotified,
|
||||
customerNotifiedAt,
|
||||
attachments,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Stato del ciclo di vita di un Ordine Cliente
|
||||
enum CustomerOrderStatus {
|
||||
toOrder(
|
||||
value: 'to_order',
|
||||
label: 'Da ordinare',
|
||||
icon: Icons.shopping_cart_checkout_rounded,
|
||||
color: Colors.deepOrange,
|
||||
isActive: true,
|
||||
),
|
||||
ordered(
|
||||
value: 'ordered',
|
||||
label: 'Ordinato',
|
||||
icon: Icons.local_shipping_outlined,
|
||||
color: Colors.blue,
|
||||
isActive: true,
|
||||
),
|
||||
arrived(
|
||||
value: 'arrived',
|
||||
label: 'Arrivato',
|
||||
icon: Icons.inventory_2_rounded,
|
||||
color: Colors.teal,
|
||||
isActive: true,
|
||||
),
|
||||
delivered(
|
||||
value: 'delivered',
|
||||
label: 'Consegnato',
|
||||
icon: Icons.check_circle_rounded,
|
||||
color: Colors.green,
|
||||
isActive: false,
|
||||
),
|
||||
cancelled(
|
||||
value: 'cancelled',
|
||||
label: 'Annullato',
|
||||
icon: Icons.cancel_outlined,
|
||||
color: Colors.grey,
|
||||
isActive: false,
|
||||
);
|
||||
|
||||
final String value;
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final bool isActive;
|
||||
|
||||
const CustomerOrderStatus({
|
||||
required this.value,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
required this.isActive,
|
||||
});
|
||||
|
||||
static CustomerOrderStatus fromString(String? val) {
|
||||
if (val == null || val.trim().isEmpty) return CustomerOrderStatus.toOrder;
|
||||
final clean = val.trim().toLowerCase();
|
||||
for (final s in CustomerOrderStatus.values) {
|
||||
if (s.value == clean || s.name.toLowerCase() == clean) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return CustomerOrderStatus.toOrder;
|
||||
}
|
||||
}
|
||||
|
||||
/// Filtro rapido di stato nella lista Ordini Clienti
|
||||
enum CustomerOrderQuickFilter {
|
||||
active('Da ultimare'),
|
||||
toOrder('Da ordinare'),
|
||||
ordered('Ordinati'),
|
||||
arrived('Arrivati'),
|
||||
delivered('Consegnati'),
|
||||
all('Tutti');
|
||||
|
||||
final String label;
|
||||
const CustomerOrderQuickFilter(this.label);
|
||||
|
||||
List<String>? get dbStatuses {
|
||||
switch (this) {
|
||||
case CustomerOrderQuickFilter.active:
|
||||
return [
|
||||
CustomerOrderStatus.toOrder.value,
|
||||
CustomerOrderStatus.ordered.value,
|
||||
CustomerOrderStatus.arrived.value,
|
||||
];
|
||||
case CustomerOrderQuickFilter.toOrder:
|
||||
return [CustomerOrderStatus.toOrder.value];
|
||||
case CustomerOrderQuickFilter.ordered:
|
||||
return [CustomerOrderStatus.ordered.value];
|
||||
case CustomerOrderQuickFilter.arrived:
|
||||
return [CustomerOrderStatus.arrived.value];
|
||||
case CustomerOrderQuickFilter.delivered:
|
||||
return [CustomerOrderStatus.delivered.value];
|
||||
case CustomerOrderQuickFilter.all:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/services/email/email_response_model.dart';
|
||||
import 'package:flux/core/services/whatsapp/whatsapp_response_model.dart';
|
||||
|
||||
enum OrderNotificationChannel {
|
||||
whatsapp('WhatsApp'),
|
||||
email('Email');
|
||||
|
||||
final String label;
|
||||
const OrderNotificationChannel(this.label);
|
||||
}
|
||||
|
||||
class OrderNotificationResult extends Equatable {
|
||||
final OrderNotificationChannel channel;
|
||||
final bool success;
|
||||
final bool? whatsappExists;
|
||||
final String? destination;
|
||||
final String? error;
|
||||
|
||||
const OrderNotificationResult({
|
||||
required this.channel,
|
||||
required this.success,
|
||||
this.whatsappExists,
|
||||
this.destination,
|
||||
this.error,
|
||||
});
|
||||
|
||||
static const empty = OrderNotificationResult(
|
||||
channel: OrderNotificationChannel.whatsapp,
|
||||
success: false,
|
||||
);
|
||||
|
||||
bool get isNumberNotOnWhatsApp =>
|
||||
channel == OrderNotificationChannel.whatsapp &&
|
||||
whatsappExists == false &&
|
||||
(error?.toLowerCase().contains('whatsapp') ?? false);
|
||||
|
||||
factory OrderNotificationResult.fromWhatsApp(
|
||||
WhatsAppResponse response, {
|
||||
String? fallbackDestination,
|
||||
}) {
|
||||
return OrderNotificationResult(
|
||||
channel: OrderNotificationChannel.whatsapp,
|
||||
success: response.success,
|
||||
whatsappExists: response.exists,
|
||||
destination: response.phone ?? fallbackDestination,
|
||||
error: response.error,
|
||||
);
|
||||
}
|
||||
|
||||
factory OrderNotificationResult.fromEmail(
|
||||
EmailResponse response, {
|
||||
String? fallbackDestination,
|
||||
}) {
|
||||
return OrderNotificationResult(
|
||||
channel: OrderNotificationChannel.email,
|
||||
success: response.success,
|
||||
destination: response.to ?? fallbackDestination,
|
||||
error: response.error,
|
||||
);
|
||||
}
|
||||
|
||||
OrderNotificationResult copyWith({
|
||||
OrderNotificationChannel? channel,
|
||||
bool? success,
|
||||
bool? whatsappExists,
|
||||
String? destination,
|
||||
String? error,
|
||||
}) {
|
||||
return OrderNotificationResult(
|
||||
channel: channel ?? this.channel,
|
||||
success: success ?? this.success,
|
||||
whatsappExists: whatsappExists ?? this.whatsappExists,
|
||||
destination: destination ?? this.destination,
|
||||
error: error ?? this.error,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
channel,
|
||||
success,
|
||||
whatsappExists,
|
||||
destination,
|
||||
error,
|
||||
];
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,802 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/core/widgets/staff_selector_modal.dart';
|
||||
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
|
||||
import 'package:flux/features/customer_orders/ui/mark_order_arrived_sheet.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart';
|
||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:printing/printing.dart';
|
||||
|
||||
class CustomerOrderListScreen extends StatefulWidget {
|
||||
const CustomerOrderListScreen({super.key});
|
||||
|
||||
@override
|
||||
State<CustomerOrderListScreen> createState() =>
|
||||
_CustomerOrderListScreenState();
|
||||
}
|
||||
|
||||
class _CustomerOrderListScreenState extends State<CustomerOrderListScreen> {
|
||||
final TextEditingController _searchCtrl = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<CustomerOrderListCubit>().init();
|
||||
context.read<StoreCubit>().loadStores();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _createNewOrder(BuildContext context) async {
|
||||
final createdBy = await getStaffMember(context);
|
||||
if (createdBy == null || !context.mounted) return;
|
||||
context.pushNamed(
|
||||
Routes.customerOrderForm,
|
||||
pathParameters: {'id': 'new'},
|
||||
extra: (createdBy: createdBy, order: null),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickDateRange(
|
||||
BuildContext context,
|
||||
DateTimeRange? current,
|
||||
) async {
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2023),
|
||||
lastDate: DateTime.now().add(const Duration(days: 365)),
|
||||
initialDateRange: current,
|
||||
);
|
||||
if (picked != null && context.mounted) {
|
||||
context.read<CustomerOrderListCubit>().setDateRange(picked);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _printLabel(BuildContext context, CustomerOrderModel order) async {
|
||||
final service = CustomerOrderLabelPdfService();
|
||||
await Printing.layoutPdf(
|
||||
name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}',
|
||||
onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final dateFmt = DateFormat('dd/MM/yyyy');
|
||||
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
|
||||
|
||||
return BlocBuilder<CustomerOrderListCubit, CustomerOrderListState>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: () => _createNewOrder(context),
|
||||
icon: const Icon(Icons.add_shopping_cart_rounded),
|
||||
label: const Text('Nuovo Ordine'),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isMobile = constraints.maxWidth < 650;
|
||||
final hPad = isMobile ? 16.0 : 24.0;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// --- HEADER & FILTRI ---
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(hPad, 16, hPad, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Ordini Clienti',
|
||||
style: (isMobile
|
||||
? theme.textTheme.titleLarge
|
||||
: theme.textTheme.headlineSmall)
|
||||
?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Richieste prodotti, etichette acquisti e ritiri in cassa',
|
||||
style: theme.textTheme.bodySmall
|
||||
?.copyWith(
|
||||
color: theme
|
||||
.colorScheme
|
||||
.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Aggiorna lista',
|
||||
onPressed: () => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.init(),
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Barra ricerca + Data + Negozio
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: isMobile ? double.infinity : 320,
|
||||
child: TextField(
|
||||
controller: _searchCtrl,
|
||||
onChanged: (val) => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.setSearchTerm(val),
|
||||
decoration: InputDecoration(
|
||||
hintText:
|
||||
'Cerca cliente, prodotto, codice cassa...',
|
||||
prefixIcon: const Icon(
|
||||
Icons.search,
|
||||
size: 20,
|
||||
),
|
||||
isDense: true,
|
||||
suffixIcon:
|
||||
_searchCtrl.text.trim().isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(
|
||||
Icons.clear,
|
||||
size: 18,
|
||||
),
|
||||
onPressed: () {
|
||||
_searchCtrl.clear();
|
||||
context
|
||||
.read<
|
||||
CustomerOrderListCubit
|
||||
>()
|
||||
.setSearchTerm('');
|
||||
},
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Filtro Date
|
||||
OutlinedButton.icon(
|
||||
icon: Icon(
|
||||
Icons.date_range_outlined,
|
||||
size: 18,
|
||||
color: state.dateRange != null
|
||||
? theme.colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
label: Text(
|
||||
state.dateRange != null
|
||||
? '${dateFmt.format(state.dateRange!.start)} - ${dateFmt.format(state.dateRange!.end)}'
|
||||
: 'Filtra Date',
|
||||
),
|
||||
onPressed: () =>
|
||||
_pickDateRange(context, state.dateRange),
|
||||
),
|
||||
if (state.dateRange != null)
|
||||
IconButton(
|
||||
tooltip: 'Rimuovi filtro date',
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.setDateRange(null),
|
||||
icon: const Icon(Icons.close, size: 18),
|
||||
),
|
||||
|
||||
// Filtro Negozio
|
||||
BlocBuilder<StoreCubit, StoreState>(
|
||||
builder: (context, storeState) {
|
||||
if (storeState.stores.length <= 1) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return DropdownButtonHideUnderline(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: theme.dividerColor.withValues(
|
||||
alpha: 0.5,
|
||||
),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: DropdownButton<String?>(
|
||||
value: state.storeIdFilter,
|
||||
hint: const Text('Tutti i negozi'),
|
||||
isDense: true,
|
||||
items: [
|
||||
const DropdownMenuItem<String?>(
|
||||
value: null,
|
||||
child: Text('Tutti i negozi'),
|
||||
),
|
||||
...storeState.stores.map(
|
||||
(s) => DropdownMenuItem<String?>(
|
||||
value: s.id,
|
||||
child: Text(s.name),
|
||||
),
|
||||
),
|
||||
],
|
||||
onChanged: (val) => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.setStoreFilter(val),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
if (state.hasAdvancedFilters)
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
_searchCtrl.clear();
|
||||
context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.resetFilters();
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.filter_alt_off_outlined,
|
||||
size: 18,
|
||||
),
|
||||
label: const Text('Azzera filtri'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// Quick Status Filters (Default: "Da ultimare")
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: CustomerOrderQuickFilter.values.map((
|
||||
f,
|
||||
) {
|
||||
final selected = state.quickFilter == f;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: ChoiceChip(
|
||||
label: Text(f.label),
|
||||
selected: selected,
|
||||
onSelected: (_) => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.setQuickFilter(f),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
|
||||
// Filtro Etichette (se presenti)
|
||||
if (state.availableTags.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.label_outline_rounded,
|
||||
size: 16,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
...state.availableTags.map((tag) {
|
||||
final isSelected = state.selectedTags
|
||||
.contains(tag);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 6),
|
||||
child: FilterChip(
|
||||
visualDensity: VisualDensity.compact,
|
||||
label: Text(
|
||||
tag,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
selected: isSelected,
|
||||
onSelected: (_) => context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.toggleTagFilter(tag),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(height: 1),
|
||||
|
||||
// --- CORPO LISTA ---
|
||||
Expanded(
|
||||
child: _buildListBody(
|
||||
context,
|
||||
theme,
|
||||
state,
|
||||
hPad: hPad,
|
||||
dateFmt: dateFmt,
|
||||
currencyFmt: currencyFmt,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildListBody(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
CustomerOrderListState state, {
|
||||
required double hPad,
|
||||
required DateFormat dateFmt,
|
||||
required NumberFormat currencyFmt,
|
||||
}) {
|
||||
if (state.status == CustomerOrderListStatus.loading &&
|
||||
state.orders.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (state.status == CustomerOrderListStatus.failure) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Text(
|
||||
'Errore nel caricamento ordini:\n${state.errorMessage}',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.orders.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.inventory_2_outlined,
|
||||
size: 56,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Nessun ordine trovato per i filtri selezionati.',
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
padding: EdgeInsets.fromLTRB(hPad, 14, hPad, 96),
|
||||
itemCount: state.orders.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
final order = state.orders[index];
|
||||
return _buildOrderCard(
|
||||
context,
|
||||
theme,
|
||||
order,
|
||||
dateFmt: dateFmt,
|
||||
currencyFmt: currencyFmt,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildOrderCard(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
CustomerOrderModel order, {
|
||||
required DateFormat dateFmt,
|
||||
required NumberFormat currencyFmt,
|
||||
}) {
|
||||
final status = order.status;
|
||||
final pref = order.contactPreference;
|
||||
final needsCustomerAlert =
|
||||
status == CustomerOrderStatus.arrived && !order.customerNotified;
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
margin: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
side: BorderSide(
|
||||
color: status == CustomerOrderStatus.arrived
|
||||
? Colors.teal.withValues(alpha: 0.5)
|
||||
: theme.dividerColor.withValues(alpha: 0.35),
|
||||
width: status == CustomerOrderStatus.arrived ? 1.4 : 1,
|
||||
),
|
||||
),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
onTap: () => context.pushNamed(
|
||||
Routes.customerOrderForm,
|
||||
pathParameters: {'id': order.id!},
|
||||
extra: (createdBy: null, order: order),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Riga 1: Data + Negozio + Stato cliccabile + Stampa QR rapida
|
||||
Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.calendar_today_outlined,
|
||||
size: 13,
|
||||
color: context.secondaryText,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
dateFmt.format(order.orderDate),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: context.secondaryText,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (order.storeDisplayName != null &&
|
||||
order.storeDisplayName!.isNotEmpty) ...[
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(
|
||||
alpha: 0.08,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
order.storeDisplayName!,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (needsCustomerAlert)
|
||||
Container(
|
||||
margin: const EdgeInsets.only(right: 6),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 3,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: Colors.amber.shade600),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.notifications_active_outlined,
|
||||
size: 13,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'Da avvisare',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (order.customerNotified)
|
||||
Container(
|
||||
margin: const EdgeInsets.only(right: 6),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 7,
|
||||
vertical: 3,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: const Text(
|
||||
'Avvisato ✓',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.green,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Menu rapido cambio stato
|
||||
PopupMenuButton<CustomerOrderStatus>(
|
||||
tooltip: 'Cambia stato rapidamente',
|
||||
onSelected: (newStatus) {
|
||||
if (newStatus == CustomerOrderStatus.arrived &&
|
||||
order.status != CustomerOrderStatus.arrived) {
|
||||
showMarkOrderArrivedSheet(context, order);
|
||||
return;
|
||||
}
|
||||
context
|
||||
.read<CustomerOrderListCubit>()
|
||||
.quickUpdateStatus(order, newStatus);
|
||||
},
|
||||
itemBuilder: (_) => CustomerOrderStatus.values
|
||||
.map(
|
||||
(s) => PopupMenuItem(
|
||||
value: s,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(s.icon, size: 18, color: s.color),
|
||||
const SizedBox(width: 8),
|
||||
Text(s.label),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 9,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: status.color.withValues(alpha: 0.14),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: status.color.withValues(alpha: 0.45),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(status.icon, size: 14, color: status.color),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
status.label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: status.color,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
Icon(
|
||||
Icons.arrow_drop_down,
|
||||
size: 16,
|
||||
color: status.color,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
if (order.id != null) ...[
|
||||
const SizedBox(width: 4),
|
||||
IconButton(
|
||||
tooltip: 'Stampa etichetta QR',
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () => _printLabel(context, order),
|
||||
icon: const Icon(Icons.qr_code_2_rounded, size: 20),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// Riga 2: Prodotto + Quantità
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
order.quantity > 1
|
||||
? '${order.productDescription} ×${order.quantity}'
|
||||
: order.productDescription,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (order.price > 0) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
currencyFmt.format(order.price),
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 6),
|
||||
|
||||
// Riga 3: Cliente + Canale di avviso + Codice Cassa / Acconto
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 6,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.person_outline, size: 15),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
order.customer?.name ?? 'Cliente sconosciuto',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
pref.buildIcon(size: 14),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
pref.shortLabel,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: pref.color,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (order.externalCode.isNotEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
),
|
||||
child: Text(
|
||||
'Cod. Cassa: ${order.externalCode}',
|
||||
style: const TextStyle(
|
||||
fontSize: 11.5,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (order.deposit > 0)
|
||||
Text(
|
||||
'Acconto: ${currencyFmt.format(order.deposit)}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.teal.shade700,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// Riga 4: Etichette (se presenti)
|
||||
if (order.tags.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: order.tags
|
||||
.map(
|
||||
(tag) => Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.deepPurple.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Colors.deepPurple.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
'#$tag',
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.deepPurple,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
|
||||
// Riga 5: Azione rapida "Segna arrivato" per ordini da ordinare / ordinati
|
||||
if (status == CustomerOrderStatus.toOrder ||
|
||||
status == CustomerOrderStatus.ordered) ...[
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FilledButton.tonalIcon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.teal.withValues(alpha: 0.14),
|
||||
foregroundColor: Colors.teal.shade800,
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
),
|
||||
onPressed: () => showMarkOrderArrivedSheet(context, order),
|
||||
icon: const Icon(Icons.inventory_2_rounded, size: 17),
|
||||
label: const Text(
|
||||
'Segna arrivato',
|
||||
style: TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/customer_orders/blocs/mark_order_arrived_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:printing/printing.dart';
|
||||
|
||||
/// Apre la BottomSheet per confermare l'arrivo di un ordine cliente,
|
||||
/// aggiornare codice cassa e prezzo, inviare l'avviso WhatsApp e stampare l'etichetta QR.
|
||||
Future<void> showMarkOrderArrivedSheet(
|
||||
BuildContext context,
|
||||
CustomerOrderModel order,
|
||||
) {
|
||||
return showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
showDragHandle: true,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (_) => BlocProvider(
|
||||
create: (_) => MarkOrderArrivedCubit(order),
|
||||
child: _MarkOrderArrivedSheetBody(initialOrder: order),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _MarkOrderArrivedSheetBody extends StatefulWidget {
|
||||
final CustomerOrderModel initialOrder;
|
||||
|
||||
const _MarkOrderArrivedSheetBody({required this.initialOrder});
|
||||
|
||||
@override
|
||||
State<_MarkOrderArrivedSheetBody> createState() =>
|
||||
_MarkOrderArrivedSheetBodyState();
|
||||
}
|
||||
|
||||
class _MarkOrderArrivedSheetBodyState
|
||||
extends State<_MarkOrderArrivedSheetBody> {
|
||||
late final TextEditingController _externalCodeCtrl;
|
||||
late final TextEditingController _priceCtrl;
|
||||
|
||||
final NumberFormat _currencyFmt = NumberFormat.currency(
|
||||
locale: 'it_IT',
|
||||
symbol: '€',
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_externalCodeCtrl = TextEditingController(
|
||||
text: widget.initialOrder.externalCode,
|
||||
);
|
||||
_priceCtrl = TextEditingController(
|
||||
text: widget.initialOrder.price > 0
|
||||
? widget.initialOrder.price.toStringAsFixed(2)
|
||||
: '',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_externalCodeCtrl.dispose();
|
||||
_priceCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
double _parsePrice() {
|
||||
final normalized = _priceCtrl.text.trim().replaceAll(',', '.');
|
||||
return double.tryParse(normalized) ?? 0.0;
|
||||
}
|
||||
|
||||
Future<void> _printQrLabel(CustomerOrderModel order) async {
|
||||
if (order.id == null || order.id!.isEmpty) return;
|
||||
final service = CustomerOrderLabelPdfService();
|
||||
await Printing.layoutPdf(
|
||||
name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}',
|
||||
onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
|
||||
|
||||
return BlocBuilder<MarkOrderArrivedCubit, MarkOrderArrivedState>(
|
||||
builder: (context, state) {
|
||||
final isCompleted =
|
||||
state.step == MarkOrderArrivedStep.completed ||
|
||||
state.step == MarkOrderArrivedStep.retryingNotification;
|
||||
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(20, 4, 20, 20 + bottomInset),
|
||||
child: SingleChildScrollView(
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 540),
|
||||
child: isCompleted
|
||||
? _buildCompletedView(context, theme, state)
|
||||
: _buildEditingView(context, theme, state),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEditingView(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
MarkOrderArrivedState state,
|
||||
) {
|
||||
final order = state.order;
|
||||
final pref = order.contactPreference;
|
||||
final dest = order.effectiveContactDestination;
|
||||
final currentPrice = _parsePrice();
|
||||
final remaining = (currentPrice - order.deposit) > 0
|
||||
? (currentPrice - order.deposit)
|
||||
: 0.0;
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Header
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha: 0.14),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.inventory_2_rounded,
|
||||
color: Colors.teal,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Segna ordine come Arrivato',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'${order.customer?.name ?? 'Cliente'} • ${order.productDescription}${order.quantity > 1 ? ' ×${order.quantity}' : ''}',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
|
||||
// Codice Cassa
|
||||
TextField(
|
||||
controller: _externalCodeCtrl,
|
||||
enabled: !state.isBusy,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Codice Cassa / Articolo',
|
||||
hintText: 'Es. COD-12345',
|
||||
prefixIcon: Icon(Icons.qr_code_scanner_rounded),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
|
||||
// Prezzo di vendita
|
||||
TextField(
|
||||
controller: _priceCtrl,
|
||||
enabled: !state.isBusy,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
|
||||
],
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prezzo di vendita (€)',
|
||||
hintText: '0.00',
|
||||
prefixIcon: Icon(Icons.euro_rounded),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
|
||||
// Riepilogo acconto / residuo live
|
||||
if (order.deposit > 0 || currentPrice > 0) ...[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(
|
||||
alpha: 0.55,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
if (order.deposit > 0)
|
||||
Text(
|
||||
'Acconto: ${_currencyFmt.format(order.deposit)}',
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.teal.shade700,
|
||||
),
|
||||
),
|
||||
if (currentPrice > 0)
|
||||
Text(
|
||||
remaining > 0
|
||||
? 'Residuo al ritiro: ${_currencyFmt.format(remaining)}'
|
||||
: 'Già saldato',
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: remaining > 0
|
||||
? theme.colorScheme.primary
|
||||
: Colors.green.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Sezione Avviso Cliente
|
||||
if (state.supportsAutoNotification)
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: pref.color.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: pref.color.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: SwitchListTile(
|
||||
value: state.sendAutoNotification,
|
||||
onChanged: state.isBusy
|
||||
? null
|
||||
: (val) => context
|
||||
.read<MarkOrderArrivedCubit>()
|
||||
.toggleSendAutoNotification(val),
|
||||
secondary: pref.buildIcon(size: 20),
|
||||
title: Text(
|
||||
pref.isEmail
|
||||
? 'Invia avviso Email al cliente'
|
||||
: 'Invia avviso WhatsApp al cliente',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
dest.isNotEmpty
|
||||
? 'Destinatario: $dest'
|
||||
: (pref.isEmail
|
||||
? 'Attenzione: indirizzo email mancante'
|
||||
: 'Attenzione: numero di telefono mancante'),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: dest.isNotEmpty ? null : theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: pref.color.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: pref.color.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
pref.buildIcon(size: 18),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Preferenza cliente: ${pref.label}${dest.isNotEmpty ? ' ($dest)' : ''}. L\'avviso andrà effettuato manualmente.',
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
if (state.errorMessage != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.errorContainer,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Text(
|
||||
state.errorMessage!,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onErrorContainer,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Pulsanti Azione
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: state.isBusy ? null : () => Navigator.pop(context),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.teal,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
onPressed: state.isBusy
|
||||
? null
|
||||
: () => context
|
||||
.read<MarkOrderArrivedCubit>()
|
||||
.confirmArrival(
|
||||
externalCode: _externalCodeCtrl.text,
|
||||
price: _parsePrice(),
|
||||
),
|
||||
icon: state.isBusy
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.check_rounded),
|
||||
label: Text(
|
||||
state.isBusy ? 'Salvataggio...' : 'Conferma Arrivo',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCompletedView(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
MarkOrderArrivedState state,
|
||||
) {
|
||||
final order = state.order;
|
||||
final result = state.notificationResult;
|
||||
final isRetrying = state.step == MarkOrderArrivedStep.retryingNotification;
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Header Conferma
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha: 0.14),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.check_circle_rounded,
|
||||
color: Colors.teal,
|
||||
size: 26,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Ordine segnato come Arrivato!',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
[
|
||||
if (order.externalCode.isNotEmpty)
|
||||
'Cod. Cassa: ${order.externalCode}',
|
||||
if (order.price > 0)
|
||||
'Prezzo: ${_currencyFmt.format(order.price)}',
|
||||
].join(' • '),
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Esito Avviso Automatico (WhatsApp o Email)
|
||||
if (result != null && result.success)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.green.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
order.contactPreference.isEmail
|
||||
? Icons.mark_email_read_rounded
|
||||
: Icons.mark_chat_read_rounded,
|
||||
color: Colors.green,
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Avviso ${result.channel.label} inviato con successo',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.green,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'Cliente avvisato su ${result.destination ?? order.effectiveContactDestination}.',
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (result != null && !result.success)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.red.withValues(alpha: 0.45)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline_rounded,
|
||||
color: Colors.red,
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
result.isNumberNotOnWhatsApp
|
||||
? 'Numero non registrato su WhatsApp'
|
||||
: 'Avviso ${result.channel.label} non riuscito',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
result.error ??
|
||||
'Impossibile inviare l\'avviso al cliente.',
|
||||
style: const TextStyle(fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'L\'ordine rimane segnato "Da avvisare" così puoi contattare il cliente manualmente.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: isRetrying
|
||||
? null
|
||||
: () => context
|
||||
.read<MarkOrderArrivedCubit>()
|
||||
.retryNotification(),
|
||||
icon: isRetrying
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded, size: 18),
|
||||
label: Text(
|
||||
isRetrying ? 'Invio in corso...' : 'Riprova invio',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.withValues(alpha: 0.14),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.amber.shade700),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.notifications_active_outlined,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Ricordati di avvisare il cliente (${order.contactPreference.label}${order.effectiveContactDestination.isNotEmpty ? ': ${order.effectiveContactDestination}' : ''}).',
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Proposta stampa etichetta QR
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
onPressed: isRetrying ? null : () => _printQrLabel(order),
|
||||
icon: const Icon(Icons.print_rounded),
|
||||
label: const Text('Stampa Etichetta QR'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
OutlinedButton(
|
||||
onPressed: isRetrying ? null : () => Navigator.pop(context),
|
||||
child: const Text('Chiudi'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
typedef OrderEmailPayload = ({String subject, String text, String html});
|
||||
|
||||
/// Costruisce oggetto, testo semplice e HTML per le email degli Ordini Clienti.
|
||||
class CustomerOrderEmailHelper {
|
||||
CustomerOrderEmailHelper._();
|
||||
|
||||
static final NumberFormat _currencyFmt = NumberFormat.currency(
|
||||
locale: 'it_IT',
|
||||
symbol: '€',
|
||||
);
|
||||
|
||||
static String _escapeHtml(String input) {
|
||||
return input
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
static String _formatProduct(CustomerOrderModel order) {
|
||||
final desc = order.productDescription.trim();
|
||||
if (order.quantity > 1) {
|
||||
return '$desc (x${order.quantity})';
|
||||
}
|
||||
return desc;
|
||||
}
|
||||
|
||||
static List<({String label, String value, bool highlight})> _buildPriceRows(
|
||||
CustomerOrderModel order, {
|
||||
required bool isArrived,
|
||||
}) {
|
||||
final rows = <({String label, String value, bool highlight})>[];
|
||||
|
||||
if (order.price > 0) {
|
||||
rows.add((
|
||||
label: 'Prezzo di vendita',
|
||||
value: _currencyFmt.format(order.price),
|
||||
highlight: false,
|
||||
));
|
||||
if (order.deposit > 0) {
|
||||
rows.add((
|
||||
label: isArrived ? 'Acconto già versato' : 'Acconto versato',
|
||||
value: _currencyFmt.format(order.deposit),
|
||||
highlight: false,
|
||||
));
|
||||
if (order.remainingAmount > 0) {
|
||||
rows.add((
|
||||
label: isArrived
|
||||
? 'Importo residuo al ritiro'
|
||||
: 'Importo residuo da pagare',
|
||||
value: _currencyFmt.format(order.remainingAmount),
|
||||
highlight: true,
|
||||
));
|
||||
} else {
|
||||
rows.add((
|
||||
label: 'Stato pagamento',
|
||||
value: 'Già saldato',
|
||||
highlight: true,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
rows.add((
|
||||
label: isArrived ? 'Importo al ritiro' : 'Importo da pagare al ritiro',
|
||||
value: _currencyFmt.format(order.price),
|
||||
highlight: true,
|
||||
));
|
||||
}
|
||||
} else if (order.deposit > 0) {
|
||||
rows.add((
|
||||
label: isArrived ? 'Acconto già versato' : 'Acconto versato',
|
||||
value: _currencyFmt.format(order.deposit),
|
||||
highlight: false,
|
||||
));
|
||||
if (!isArrived) {
|
||||
rows.add((
|
||||
label: 'Prezzo di vendita',
|
||||
value: 'Da definire',
|
||||
highlight: false,
|
||||
));
|
||||
}
|
||||
} else if (!isArrived) {
|
||||
rows.add((
|
||||
label: 'Prezzo di vendita',
|
||||
value: 'Da definire',
|
||||
highlight: false,
|
||||
));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// Email di ricevuta inviata alla creazione di un nuovo ordine cliente.
|
||||
static OrderEmailPayload buildOrderReceiptEmail(CustomerOrderModel order) {
|
||||
final customerName = order.customer?.name.trim() ?? '';
|
||||
final greetingText = customerName.isNotEmpty
|
||||
? 'Ciao $customerName,'
|
||||
: 'Ciao,';
|
||||
final greetingHtml = customerName.isNotEmpty
|
||||
? 'Ciao <strong>${_escapeHtml(customerName)}</strong>,'
|
||||
: 'Ciao,';
|
||||
final product = _formatProduct(order);
|
||||
final store = order.storeDisplayName?.trim() ?? '';
|
||||
final storeSuffix = store.isNotEmpty
|
||||
? ' presso il punto vendita $store'
|
||||
: '';
|
||||
final priceRows = _buildPriceRows(order, isArrived: false);
|
||||
|
||||
final subject = 'Conferma ordine: $product';
|
||||
|
||||
final textBuffer = StringBuffer()
|
||||
..writeln(greetingText)
|
||||
..writeln()
|
||||
..writeln('Grazie per il tuo ordine di $product!')
|
||||
..writeln();
|
||||
for (final row in priceRows) {
|
||||
textBuffer.writeln('- ${row.label}: ${row.value}');
|
||||
}
|
||||
textBuffer
|
||||
..writeln()
|
||||
..write(
|
||||
'Ti avviseremo non appena sarà arrivato$storeSuffix e pronto per il ritiro.',
|
||||
);
|
||||
|
||||
final html = _wrapHtmlEmail(
|
||||
title: 'Conferma del tuo ordine',
|
||||
accentColor: '#0f766e',
|
||||
greetingHtml: greetingHtml,
|
||||
introHtml:
|
||||
'Grazie per il tuo ordine di <strong>${_escapeHtml(product)}</strong>!',
|
||||
rows: [
|
||||
(label: 'Prodotto', value: product, highlight: false),
|
||||
...priceRows,
|
||||
],
|
||||
footerHtml:
|
||||
'Ti avviseremo non appena il prodotto sarà arrivato${store.isNotEmpty ? ' presso il punto vendita <strong>${_escapeHtml(store)}</strong>' : ''} e pronto per il ritiro.',
|
||||
);
|
||||
|
||||
return (subject: subject, text: textBuffer.toString(), html: html);
|
||||
}
|
||||
|
||||
/// Email di avviso ritiro inviata quando il prodotto viene segnato come Arrivato.
|
||||
static OrderEmailPayload buildOrderArrivedEmail(CustomerOrderModel order) {
|
||||
final customerName = order.customer?.name.trim() ?? '';
|
||||
final greetingText = customerName.isNotEmpty
|
||||
? 'Ciao $customerName,'
|
||||
: 'Ciao,';
|
||||
final greetingHtml = customerName.isNotEmpty
|
||||
? 'Ciao <strong>${_escapeHtml(customerName)}</strong>,'
|
||||
: 'Ciao,';
|
||||
final product = _formatProduct(order);
|
||||
final store = order.storeDisplayName?.trim() ?? '';
|
||||
final storeSuffix = store.isNotEmpty
|
||||
? ' presso il punto vendita $store'
|
||||
: '';
|
||||
final priceRows = _buildPriceRows(order, isArrived: true);
|
||||
|
||||
final subject = 'Il tuo ordine è arrivato: $product';
|
||||
|
||||
final textBuffer = StringBuffer()
|
||||
..writeln(greetingText)
|
||||
..writeln()
|
||||
..writeln('Il prodotto che hai ordinato ($product) è arrivato ed è pronto per il ritiro!')
|
||||
..writeln();
|
||||
for (final row in priceRows) {
|
||||
textBuffer.writeln('- ${row.label}: ${row.value}');
|
||||
}
|
||||
textBuffer
|
||||
..writeln()
|
||||
..write('Ti aspettiamo$storeSuffix per il ritiro!');
|
||||
|
||||
final html = _wrapHtmlEmail(
|
||||
title: 'Il tuo ordine è arrivato!',
|
||||
accentColor: '#0d9488',
|
||||
greetingHtml: greetingHtml,
|
||||
introHtml:
|
||||
'Ottime notizie: il prodotto che hai ordinato (<strong>${_escapeHtml(product)}</strong>) è arrivato ed è pronto per il ritiro.',
|
||||
rows: [
|
||||
(label: 'Prodotto', value: product, highlight: false),
|
||||
...priceRows,
|
||||
],
|
||||
footerHtml:
|
||||
'Ti aspettiamo${store.isNotEmpty ? ' presso il punto vendita <strong>${_escapeHtml(store)}</strong>' : ' in negozio'} per il ritiro!',
|
||||
);
|
||||
|
||||
return (subject: subject, text: textBuffer.toString(), html: html);
|
||||
}
|
||||
|
||||
static String _wrapHtmlEmail({
|
||||
required String title,
|
||||
required String accentColor,
|
||||
required String greetingHtml,
|
||||
required String introHtml,
|
||||
required List<({String label, String value, bool highlight})> rows,
|
||||
required String footerHtml,
|
||||
}) {
|
||||
final rowsHtml = rows.map((row) {
|
||||
final valueStyle = row.highlight
|
||||
? 'color: $accentColor; font-weight: 700; font-size: 15px;'
|
||||
: 'color: #0f172a; font-weight: 600; font-size: 14px;';
|
||||
return '''
|
||||
<tr>
|
||||
<td style="padding: 8px 0; color: #64748b; font-size: 14px; border-bottom: 1px solid #f1f5f9;">${_escapeHtml(row.label)}</td>
|
||||
<td style="padding: 8px 0; text-align: right; $valueStyle border-bottom: 1px solid #f1f5f9;">${_escapeHtml(row.value)}</td>
|
||||
</tr>
|
||||
''';
|
||||
}).join();
|
||||
|
||||
return '''
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 560px; margin: 24px auto; padding: 28px; border: 1px solid #e2e8f0; border-radius: 16px; background-color: #ffffff;">
|
||||
<h2 style="color: $accentColor; font-size: 21px; font-weight: 700; margin: 0 0 16px 0;">
|
||||
${_escapeHtml(title)}
|
||||
</h2>
|
||||
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0 0 12px 0;">
|
||||
$greetingHtml
|
||||
</p>
|
||||
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0 0 20px 0;">
|
||||
$introHtml
|
||||
</p>
|
||||
<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px; background-color: #f8fafc; border-radius: 10px; padding: 12px;">
|
||||
<tbody>
|
||||
$rowsHtml
|
||||
</tbody>
|
||||
</table>
|
||||
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0;">
|
||||
$footerHtml
|
||||
</p>
|
||||
</div>
|
||||
''';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:pdf/pdf.dart';
|
||||
import 'package:pdf/widgets.dart' as pw;
|
||||
import 'package:printing/printing.dart';
|
||||
|
||||
class CustomerOrderLabelPdfService {
|
||||
/// Genera il PDF dell'etichetta prodotto con QR code, leggendo le misure
|
||||
/// configurate nelle Impostazioni Azienda (fallback 40 x 30 mm).
|
||||
Future<pw.Document> generateOrderLabelPdf(CustomerOrderModel order) async {
|
||||
final pdf = pw.Document();
|
||||
final font = await PdfGoogleFonts.robotoRegular();
|
||||
final boldFont = await PdfGoogleFonts.robotoBold();
|
||||
|
||||
final company = GetIt.I.get<SessionCubit>().state.company;
|
||||
final widthMm = company?.labelWidth ?? 40.0;
|
||||
final heightMm = company?.labelHeight ?? 30.0;
|
||||
final isVertical = company?.isLabelVertical ?? false;
|
||||
|
||||
final pageFormat = isVertical
|
||||
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
|
||||
: PdfPageFormat(widthMm * PdfPageFormat.mm, heightMm * PdfPageFormat.mm);
|
||||
|
||||
final effectiveW = pageFormat.width;
|
||||
final effectiveH = pageFormat.height;
|
||||
final minSide = effectiveW < effectiveH ? effectiveW : effectiveH;
|
||||
final qrSize = (minSide * 0.45).clamp(
|
||||
10 * PdfPageFormat.mm,
|
||||
16 * PdfPageFormat.mm,
|
||||
);
|
||||
|
||||
final customerName = order.customer?.name ?? 'Cliente';
|
||||
final qtySuffix = order.quantity > 1 ? ' (x${order.quantity})' : '';
|
||||
final productLine = '${order.productDescription}$qtySuffix';
|
||||
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
|
||||
final priceStr = order.price > 0 ? currencyFmt.format(order.price) : '';
|
||||
final codeStr = order.externalCode.trim();
|
||||
final qrData = order.deepLinkUrl.isNotEmpty
|
||||
? order.deepLinkUrl
|
||||
: (order.id ?? '');
|
||||
|
||||
pdf.addPage(
|
||||
pw.Page(
|
||||
pageFormat: pageFormat,
|
||||
margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm),
|
||||
build: (context) {
|
||||
final headerName = pw.Container(
|
||||
width: double.infinity,
|
||||
padding: const pw.EdgeInsets.only(bottom: 1.5),
|
||||
decoration: const pw.BoxDecoration(
|
||||
border: pw.Border(
|
||||
bottom: pw.BorderSide(width: 0.5, color: PdfColors.grey600),
|
||||
),
|
||||
),
|
||||
child: pw.FittedBox(
|
||||
fit: pw.BoxFit.scaleDown,
|
||||
alignment: pw.Alignment.centerLeft,
|
||||
child: pw.Text(
|
||||
customerName,
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 11.5),
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final detailsBlock = pw.Column(
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||
mainAxisAlignment: pw.MainAxisAlignment.center,
|
||||
mainAxisSize: pw.MainAxisSize.min,
|
||||
children: [
|
||||
pw.Text(
|
||||
productLine,
|
||||
style: pw.TextStyle(font: font, fontSize: 7.5),
|
||||
maxLines: 2,
|
||||
overflow: pw.TextOverflow.clip,
|
||||
),
|
||||
if (codeStr.isNotEmpty) ...[
|
||||
pw.SizedBox(height: 1.5),
|
||||
pw.Text(
|
||||
'Cod: $codeStr',
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 7.2),
|
||||
maxLines: 1,
|
||||
overflow: pw.TextOverflow.clip,
|
||||
),
|
||||
],
|
||||
if (priceStr.isNotEmpty) ...[
|
||||
pw.SizedBox(height: 2),
|
||||
pw.FittedBox(
|
||||
fit: pw.BoxFit.scaleDown,
|
||||
alignment: pw.Alignment.centerLeft,
|
||||
child: pw.Text(
|
||||
priceStr,
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 11.5),
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
final qrWidget = pw.BarcodeWidget(
|
||||
barcode: pw.Barcode.qrCode(),
|
||||
data: qrData,
|
||||
width: qrSize,
|
||||
height: qrSize,
|
||||
);
|
||||
|
||||
if (effectiveH > effectiveW) {
|
||||
return pw.Column(
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
headerName,
|
||||
pw.SizedBox(height: 2),
|
||||
pw.Expanded(child: detailsBlock),
|
||||
pw.SizedBox(height: 2),
|
||||
pw.Center(child: qrWidget),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return pw.Column(
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
headerName,
|
||||
pw.SizedBox(height: 2),
|
||||
pw.Expanded(
|
||||
child: pw.Row(
|
||||
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||
children: [
|
||||
pw.Expanded(child: detailsBlock),
|
||||
pw.SizedBox(width: 2 * PdfPageFormat.mm),
|
||||
qrWidget,
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return pdf;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
/// Costruisce i messaggi WhatsApp formattati per gli Ordini Clienti.
|
||||
class CustomerOrderWhatsAppHelper {
|
||||
CustomerOrderWhatsAppHelper._();
|
||||
|
||||
static final NumberFormat _currencyFmt = NumberFormat.currency(
|
||||
locale: 'it_IT',
|
||||
symbol: '€',
|
||||
);
|
||||
|
||||
static String _formatCustomerName(CustomerOrderModel order) {
|
||||
final fullName = order.customer?.name.trim() ?? '';
|
||||
if (fullName.isEmpty) return '';
|
||||
return ' $fullName';
|
||||
}
|
||||
|
||||
static String _formatProduct(CustomerOrderModel order) {
|
||||
final desc = order.productDescription.trim();
|
||||
if (order.quantity > 1) {
|
||||
return '$desc (x${order.quantity})';
|
||||
}
|
||||
return desc;
|
||||
}
|
||||
|
||||
static String _formatStoreSuffix(CustomerOrderModel order) {
|
||||
final store = order.storeDisplayName?.trim() ?? '';
|
||||
if (store.isEmpty) return '';
|
||||
return ' presso il punto vendita *$store*';
|
||||
}
|
||||
|
||||
/// Messaggio di ricevuta inviato alla creazione di un nuovo ordine cliente.
|
||||
static String buildOrderReceiptMessage(CustomerOrderModel order) {
|
||||
final namePart = _formatCustomerName(order);
|
||||
final product = _formatProduct(order);
|
||||
final storeSuffix = _formatStoreSuffix(order);
|
||||
|
||||
final buffer = StringBuffer()
|
||||
..writeln('Ciao$namePart, grazie per il tuo ordine di *$product*!')
|
||||
..writeln();
|
||||
|
||||
if (order.price > 0) {
|
||||
buffer.writeln('• *Prezzo:* ${_currencyFmt.format(order.price)}');
|
||||
if (order.deposit > 0) {
|
||||
buffer.writeln(
|
||||
'• *Acconto versato:* ${_currencyFmt.format(order.deposit)}',
|
||||
);
|
||||
if (order.remainingAmount > 0) {
|
||||
buffer.writeln(
|
||||
'• *Importo residuo da pagare:* ${_currencyFmt.format(order.remainingAmount)}',
|
||||
);
|
||||
} else {
|
||||
buffer.writeln('• *Stato pagamento:* Già saldato');
|
||||
}
|
||||
} else {
|
||||
buffer.writeln(
|
||||
'• *Importo da pagare al ritiro:* ${_currencyFmt.format(order.price)}',
|
||||
);
|
||||
}
|
||||
} else if (order.deposit > 0) {
|
||||
buffer.writeln(
|
||||
'• *Acconto versato:* ${_currencyFmt.format(order.deposit)}',
|
||||
);
|
||||
buffer.writeln('• *Prezzo di vendita:* da definire');
|
||||
} else {
|
||||
buffer.writeln('• *Prezzo di vendita:* da definire');
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln()
|
||||
..write(
|
||||
'Ti avviseremo non appena sarà arrivato$storeSuffix e pronto per il ritiro.',
|
||||
);
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Messaggio di avviso ritiro inviato quando il prodotto viene segnato come Arrivato.
|
||||
static String buildOrderArrivedMessage(CustomerOrderModel order) {
|
||||
final namePart = _formatCustomerName(order);
|
||||
final product = _formatProduct(order);
|
||||
final storeSuffix = _formatStoreSuffix(order);
|
||||
|
||||
final buffer = StringBuffer()
|
||||
..writeln('Ciao$namePart, il prodotto che hai ordinato è arrivato!')
|
||||
..writeln()
|
||||
..writeln('• *Prodotto:* $product');
|
||||
|
||||
if (order.price > 0) {
|
||||
buffer.writeln('• *Prezzo:* ${_currencyFmt.format(order.price)}');
|
||||
if (order.deposit > 0) {
|
||||
buffer.writeln(
|
||||
'• *Acconto già versato:* ${_currencyFmt.format(order.deposit)}',
|
||||
);
|
||||
if (order.remainingAmount > 0) {
|
||||
buffer.writeln(
|
||||
'• *Importo residuo al ritiro:* ${_currencyFmt.format(order.remainingAmount)}',
|
||||
);
|
||||
} else {
|
||||
buffer.writeln('• *Stato pagamento:* Già saldato');
|
||||
}
|
||||
} else {
|
||||
buffer.writeln(
|
||||
'• *Importo al ritiro:* ${_currencyFmt.format(order.price)}',
|
||||
);
|
||||
}
|
||||
} else if (order.deposit > 0) {
|
||||
buffer.writeln(
|
||||
'• *Acconto già versato:* ${_currencyFmt.format(order.deposit)}',
|
||||
);
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln()
|
||||
..write('Ti aspettiamo$storeSuffix per il ritiro!');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
@@ -65,20 +65,26 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
void updateFields({
|
||||
String? name,
|
||||
String? phoneNumber,
|
||||
String? alternativePhoneNumber,
|
||||
String? email,
|
||||
String? note,
|
||||
bool? doNotDisturb,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
customer: state.customer.copyWith(
|
||||
name: name ?? state.customer.name,
|
||||
phoneNumber: phoneNumber ?? state.customer.phoneNumber,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? state.customer.alternativePhoneNumber,
|
||||
email: email ?? state.customer.email,
|
||||
note: note ?? state.customer.note,
|
||||
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
|
||||
isBusiness: isBusiness ?? state.customer.isBusiness,
|
||||
fiscalCode:
|
||||
fiscalCode?.trim().toUpperCase() ?? state.customer.fiscalCode,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -109,16 +115,21 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
Future<CustomerModel?> quickCreateCustomer({
|
||||
required String name,
|
||||
String? phone,
|
||||
String? alternativePhone,
|
||||
String? email,
|
||||
String? note,
|
||||
required bool isBusiness,
|
||||
String? fiscalCode,
|
||||
}) async {
|
||||
final newCustomer = CustomerModel(
|
||||
name: name,
|
||||
phoneNumber: phone ?? '',
|
||||
alternativePhoneNumber: alternativePhone ?? '',
|
||||
email: email ?? '',
|
||||
companyId: _sessionCubit.state.company!.id!,
|
||||
note: '',
|
||||
note: note ?? '',
|
||||
isBusiness: isBusiness,
|
||||
fiscalCode: fiscalCode?.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
try {
|
||||
|
||||
@@ -7,6 +7,7 @@ class CustomerModel extends Equatable {
|
||||
final DateTime? createdAt;
|
||||
final String name;
|
||||
final String phoneNumber;
|
||||
final String alternativePhoneNumber;
|
||||
final String email;
|
||||
final String note;
|
||||
final DateTime? lastContactDate;
|
||||
@@ -15,12 +16,14 @@ class CustomerModel extends Equatable {
|
||||
final bool isActive;
|
||||
final List<AttachmentModel> attachments;
|
||||
final bool isBusiness;
|
||||
final String? fiscalCode;
|
||||
|
||||
const CustomerModel({
|
||||
this.id,
|
||||
this.createdAt,
|
||||
required this.name,
|
||||
required this.phoneNumber,
|
||||
this.alternativePhoneNumber = '',
|
||||
required this.email,
|
||||
required this.note,
|
||||
this.lastContactDate,
|
||||
@@ -29,6 +32,7 @@ class CustomerModel extends Equatable {
|
||||
this.isActive = true,
|
||||
this.attachments = const [],
|
||||
this.isBusiness = false,
|
||||
this.fiscalCode,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -37,6 +41,7 @@ class CustomerModel extends Equatable {
|
||||
createdAt,
|
||||
name,
|
||||
phoneNumber,
|
||||
alternativePhoneNumber,
|
||||
email,
|
||||
note,
|
||||
lastContactDate,
|
||||
@@ -45,15 +50,16 @@ class CustomerModel extends Equatable {
|
||||
isActive,
|
||||
attachments,
|
||||
isBusiness,
|
||||
fiscalCode,
|
||||
];
|
||||
|
||||
factory CustomerModel.empty() => CustomerModel(
|
||||
factory CustomerModel.empty() => const CustomerModel(
|
||||
name: '',
|
||||
phoneNumber: '',
|
||||
alternativePhoneNumber: '',
|
||||
email: '',
|
||||
note: '',
|
||||
companyId:
|
||||
'', // Dovrebbe essere sempre fornito, ma lasciamo vuoto per sicurezza
|
||||
companyId: '',
|
||||
);
|
||||
|
||||
CustomerModel copyWith({
|
||||
@@ -61,6 +67,7 @@ class CustomerModel extends Equatable {
|
||||
DateTime? createdAt,
|
||||
String? name,
|
||||
String? phoneNumber,
|
||||
String? alternativePhoneNumber,
|
||||
String? email,
|
||||
String? note,
|
||||
DateTime? lastContactDate,
|
||||
@@ -69,12 +76,15 @@ class CustomerModel extends Equatable {
|
||||
bool? isActive,
|
||||
List<AttachmentModel>? attachments,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
return CustomerModel(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
name: name ?? this.name,
|
||||
phoneNumber: phoneNumber ?? this.phoneNumber,
|
||||
alternativePhoneNumber:
|
||||
alternativePhoneNumber ?? this.alternativePhoneNumber,
|
||||
email: email ?? this.email,
|
||||
note: note ?? this.note,
|
||||
lastContactDate: lastContactDate ?? this.lastContactDate,
|
||||
@@ -83,6 +93,7 @@ class CustomerModel extends Equatable {
|
||||
isActive: isActive ?? this.isActive,
|
||||
attachments: attachments ?? this.attachments,
|
||||
isBusiness: isBusiness ?? this.isBusiness,
|
||||
fiscalCode: fiscalCode ?? this.fiscalCode,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,8 +104,9 @@ class CustomerModel extends Equatable {
|
||||
? DateTime.parse(map['created_at'])
|
||||
: null,
|
||||
name: (map['name'] as String).myFormat(),
|
||||
phoneNumber: map['phone_number'],
|
||||
email: map['email'],
|
||||
phoneNumber: map['phone_number'] as String? ?? '',
|
||||
alternativePhoneNumber: map['alternative_phone_number'] as String? ?? '',
|
||||
email: map['email'] as String? ?? '',
|
||||
note: map['note'] ?? '',
|
||||
lastContactDate: map['last_contact_date'] != null
|
||||
? DateTime.parse(map['last_contact_date'])
|
||||
@@ -108,14 +120,18 @@ class CustomerModel extends Equatable {
|
||||
.toList() ??
|
||||
const [],
|
||||
isBusiness: map['is_business'] as bool? ?? false,
|
||||
fiscalCode: map['fiscal_code'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() => toJson();
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (id != null) 'id': id,
|
||||
'name': name.toLowerCase().trim(),
|
||||
'phone_number': phoneNumber,
|
||||
'phone_number': phoneNumber.trim(),
|
||||
'alternative_phone_number': alternativePhoneNumber.trim(),
|
||||
'email': email.toLowerCase().trim(),
|
||||
'note': note,
|
||||
if (lastContactDate != null)
|
||||
@@ -124,6 +140,7 @@ class CustomerModel extends Equatable {
|
||||
'company_id': companyId,
|
||||
'is_active': isActive,
|
||||
'is_business': isBusiness,
|
||||
'fiscal_code': fiscalCode?.trim().toUpperCase(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/widgets/flux_text_field.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/attachments_section.dart';
|
||||
@@ -22,8 +23,10 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
// Controller inizializzati con i dati del cliente (se presenti)
|
||||
final TextEditingController _nomeController = TextEditingController();
|
||||
final TextEditingController _telefonoController = TextEditingController();
|
||||
final TextEditingController _telefonoAltController = TextEditingController();
|
||||
final TextEditingController _emailController = TextEditingController();
|
||||
final TextEditingController _noteController = TextEditingController();
|
||||
final TextEditingController _fiscalCodeController = TextEditingController();
|
||||
bool _isInitialized = false;
|
||||
|
||||
@override
|
||||
@@ -47,8 +50,10 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
void dispose() {
|
||||
_nomeController.dispose();
|
||||
_telefonoController.dispose();
|
||||
_telefonoAltController.dispose();
|
||||
_emailController.dispose();
|
||||
_noteController.dispose();
|
||||
_fiscalCodeController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -59,12 +64,18 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
if (_telefonoController.text.isEmpty) {
|
||||
_telefonoController.text = customer.phoneNumber;
|
||||
}
|
||||
if (_telefonoAltController.text.isEmpty) {
|
||||
_telefonoAltController.text = customer.alternativePhoneNumber;
|
||||
}
|
||||
if (_emailController.text.isEmpty) {
|
||||
_emailController.text = customer.email;
|
||||
}
|
||||
if (_noteController.text.isEmpty) {
|
||||
_noteController.text = customer.note;
|
||||
}
|
||||
if (_fiscalCodeController.text.isEmpty && customer.fiscalCode != null) {
|
||||
_fiscalCodeController.text = customer.fiscalCode!;
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
@@ -72,8 +83,10 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
context.read<CustomerFormCubit>().updateFields(
|
||||
name: _nomeController.text.trim(),
|
||||
phoneNumber: _telefonoController.text.trim(),
|
||||
alternativePhoneNumber: _telefonoAltController.text.trim(),
|
||||
email: _emailController.text.trim(),
|
||||
note: _noteController.text.trim(),
|
||||
fiscalCode: _fiscalCodeController.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -159,12 +172,19 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Telefono',
|
||||
label: 'Telefono Principale',
|
||||
icon: Icons.phone_android_outlined,
|
||||
controller: _telefonoController,
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Recapito Alternativo',
|
||||
icon: Icons.phone_forwarded_outlined,
|
||||
controller: _telefonoAltController,
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Email',
|
||||
icon: Icons.alternate_email_outlined,
|
||||
@@ -172,6 +192,20 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Partita IVA / Codice Fiscale',
|
||||
icon: Icons.person_outline,
|
||||
controller: _fiscalCodeController,
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(
|
||||
RegExp(r'[a-zA-Z0-9]'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Note',
|
||||
icon: Icons.notes_outlined,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
|
||||
|
||||
@@ -14,9 +15,11 @@ class QuickCustomerDialog extends StatefulWidget {
|
||||
class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
late final TextEditingController _nameCtrl;
|
||||
final _phoneCtrl = TextEditingController();
|
||||
final _altPhoneCtrl = TextEditingController();
|
||||
final _emailCtrl = TextEditingController();
|
||||
final _noteCtrl = TextEditingController();
|
||||
bool _isBusiness = false; // Aggiungiamo un campo per il tipo di cliente
|
||||
bool _isBusiness = false;
|
||||
final _fiscalCodeCtrl = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
@@ -31,8 +34,10 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
void dispose() {
|
||||
_nameCtrl.dispose();
|
||||
_phoneCtrl.dispose();
|
||||
_altPhoneCtrl.dispose();
|
||||
_emailCtrl.dispose();
|
||||
_noteCtrl.dispose();
|
||||
_fiscalCodeCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -49,7 +54,10 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
isBusiness: _isBusiness,
|
||||
name: _nameCtrl.text.trim(),
|
||||
phone: _phoneCtrl.text.trim(),
|
||||
alternativePhone: _altPhoneCtrl.text.trim(),
|
||||
email: _emailCtrl.text.trim(),
|
||||
note: _noteCtrl.text.trim(),
|
||||
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
setState(() => _isLoading = false);
|
||||
@@ -113,7 +121,18 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _phoneCtrl,
|
||||
decoration: const InputDecoration(labelText: "Telefono"),
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Telefono Principale",
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _altPhoneCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Recapito Alternativo (opzionale)",
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
@@ -125,6 +144,20 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _fiscalCodeCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Codice Fiscale / Partita IVA",
|
||||
),
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
|
||||
],
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _noteCtrl,
|
||||
decoration: const InputDecoration(labelText: "Note rapide"),
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import 'dashboard_daily_ricontatti_state.dart';
|
||||
|
||||
class DashboardDailyRicontattiCubit extends Cubit<DashboardDailyRicontattiState> {
|
||||
final OperationsRepository _operationsRepository;
|
||||
final StaffRepository _staffRepository;
|
||||
|
||||
String? companyId;
|
||||
String? storeId;
|
||||
|
||||
StreamSubscription<void>? _operationsSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardDailyRicontattiCubit({
|
||||
this.companyId,
|
||||
this.storeId,
|
||||
OperationsRepository? operationsRepository,
|
||||
StaffRepository? staffRepository,
|
||||
}) : _operationsRepository =
|
||||
operationsRepository ?? GetIt.I.get<OperationsRepository>(),
|
||||
_staffRepository = staffRepository ?? GetIt.I.get<StaffRepository>(),
|
||||
super(
|
||||
DashboardDailyRicontattiState(
|
||||
date: DateTime.now(),
|
||||
),
|
||||
);
|
||||
|
||||
void updateContext({
|
||||
String? newCompanyId,
|
||||
String? newStoreId,
|
||||
}) {
|
||||
bool changed = false;
|
||||
if (newCompanyId != null && newCompanyId != companyId) {
|
||||
companyId = newCompanyId;
|
||||
changed = true;
|
||||
}
|
||||
if (newStoreId != null && newStoreId != storeId) {
|
||||
storeId = newStoreId;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
void startListening() {
|
||||
emit(state.copyWith(status: DashboardDailyRicontattiStatus.loading));
|
||||
stopListening();
|
||||
|
||||
_loadDailyRicontattiSilently();
|
||||
|
||||
// 1. Ascolto notifiche di creazione/modifica operazioni in real-time
|
||||
_operationsSubscription =
|
||||
_operationsRepository.onOperationsChanged.listen((_) {
|
||||
_loadDailyRicontattiSilently();
|
||||
});
|
||||
|
||||
// 2. Polling periodico ogni 30 secondi
|
||||
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
_loadDailyRicontattiSilently();
|
||||
});
|
||||
}
|
||||
|
||||
void stopListening() {
|
||||
_operationsSubscription?.cancel();
|
||||
_operationsSubscription = null;
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
void refresh() {
|
||||
_loadDailyRicontattiSilently();
|
||||
}
|
||||
|
||||
Future<void> _loadDailyRicontattiSilently() async {
|
||||
if (companyId == null || storeId == null) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.initial,
|
||||
summaries: [],
|
||||
totalRicontattiToday: 0,
|
||||
totalRicontattiMonth: 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final now = DateTime.now();
|
||||
final todayStart = DateTime(now.year, now.month, now.day, 0, 0, 0);
|
||||
final todayEnd = DateTime(now.year, now.month, now.day, 23, 59, 59, 999);
|
||||
|
||||
// 1. Recupero staff del negozio
|
||||
final allStaff = await _staffRepository.getStaffMembers(
|
||||
companyId!,
|
||||
storeId: storeId,
|
||||
);
|
||||
|
||||
// 1. Escludiamo i collaboratori con qualifica Manager o Tester, o disattivati
|
||||
final Set<String> excludedStaffIds = {};
|
||||
for (final s in allStaff) {
|
||||
if (s.isExcludedFromRicontattiFocus && s.id != null) {
|
||||
excludedStaffIds.add(s.id!);
|
||||
}
|
||||
}
|
||||
|
||||
final activeEligibleStaff = allStaff
|
||||
.where((s) => !s.isExcludedFromRicontattiFocus)
|
||||
.toList();
|
||||
|
||||
// 2. Recupero conteggi mensili per addetto del negozio
|
||||
final monthlyCountsByStaff =
|
||||
await _operationsRepository.getMonthlyRicontattiCountsByStaff(
|
||||
companyId: companyId!,
|
||||
storeId: storeId!,
|
||||
month: now,
|
||||
);
|
||||
|
||||
// 3. Recupero operazioni create oggi nel negozio
|
||||
final paginatedOps = await _operationsRepository.fetchPaginatedOperations(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
dateRange: DateTimeRange(start: todayStart, end: todayEnd),
|
||||
page: 1,
|
||||
itemsPerPage: 150,
|
||||
onlyShowInDashboard: false,
|
||||
);
|
||||
|
||||
// 4. Filtro per tipo Ricontatto
|
||||
final ricontattiOps = paginatedOps.operations.where((op) {
|
||||
return op.details.any((d) => d.type == OperationType.ricontatto);
|
||||
}).toList();
|
||||
|
||||
// 5. Raggruppamento per addetto ammissibile
|
||||
final List<StaffDailyRicontattiSummary> summaries = [];
|
||||
final Set<String> processedStaffIds = Set<String>.from(excludedStaffIds);
|
||||
|
||||
for (final staff in activeEligibleStaff) {
|
||||
final staffId = staff.id ?? '';
|
||||
processedStaffIds.add(staffId);
|
||||
|
||||
final staffOps = ricontattiOps.where((op) => op.staffId == staffId).toList();
|
||||
|
||||
int staffCount = 0;
|
||||
for (final op in staffOps) {
|
||||
final countInOp = op.details.where((d) => d.type == OperationType.ricontatto).length;
|
||||
staffCount += countInOp > 0 ? countInOp : 1;
|
||||
}
|
||||
|
||||
final staffMonthCount = monthlyCountsByStaff[staffId] ?? 0;
|
||||
|
||||
summaries.add(
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: staffId,
|
||||
staffName: staff.name,
|
||||
jobTitle: staff.jobTitle,
|
||||
systemRole: staff.systemRole,
|
||||
count: staffCount,
|
||||
monthCount: staffMonthCount,
|
||||
operations: staffOps,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Verifica se ci sono operazioni attribuite a staff non presente nella lista
|
||||
for (final op in ricontattiOps) {
|
||||
final opStaffId = op.staffId ?? '';
|
||||
if (opStaffId.isNotEmpty && !processedStaffIds.contains(opStaffId)) {
|
||||
processedStaffIds.add(opStaffId);
|
||||
final staffOps = ricontattiOps.where((o) => o.staffId == opStaffId).toList();
|
||||
|
||||
int staffCount = 0;
|
||||
for (final o in staffOps) {
|
||||
final countInOp = o.details.where((d) => d.type == OperationType.ricontatto).length;
|
||||
staffCount += countInOp > 0 ? countInOp : 1;
|
||||
}
|
||||
final staffMonthCount = monthlyCountsByStaff[opStaffId] ?? 0;
|
||||
|
||||
summaries.add(
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: opStaffId,
|
||||
staffName: op.staffDisplayName ?? 'Operatore',
|
||||
count: staffCount,
|
||||
monthCount: staffMonthCount,
|
||||
operations: staffOps,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Calcolo totali coerenti con gli addetti visibili
|
||||
int grandTotal = 0;
|
||||
int grandMonthTotal = 0;
|
||||
for (final s in summaries) {
|
||||
grandTotal += s.count;
|
||||
grandMonthTotal += s.monthCount;
|
||||
}
|
||||
|
||||
// 8. Ordinamento: per numero di ricontatti oggi decrescente, poi per mese decrescente, poi per nome
|
||||
summaries.sort((a, b) {
|
||||
final countCmp = b.count.compareTo(a.count);
|
||||
if (countCmp != 0) return countCmp;
|
||||
final monthCmp = b.monthCount.compareTo(a.monthCount);
|
||||
if (monthCmp != 0) return monthCmp;
|
||||
return a.staffName.toLowerCase().compareTo(b.staffName.toLowerCase());
|
||||
});
|
||||
|
||||
if (isClosed) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.success,
|
||||
summaries: summaries,
|
||||
totalRicontattiToday: grandTotal,
|
||||
totalRicontattiMonth: grandMonthTotal,
|
||||
date: now,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} catch (e, stack) {
|
||||
debugPrint('Errore in DashboardDailyRicontattiCubit: $e\n$stack');
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
|
||||
enum DashboardDailyRicontattiStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardDailyRicontattiState extends Equatable {
|
||||
final DashboardDailyRicontattiStatus status;
|
||||
final List<StaffDailyRicontattiSummary> summaries;
|
||||
final int totalRicontattiToday;
|
||||
final int totalRicontattiMonth;
|
||||
final DateTime date;
|
||||
final String? errorMessage;
|
||||
|
||||
const DashboardDailyRicontattiState({
|
||||
this.status = DashboardDailyRicontattiStatus.initial,
|
||||
this.summaries = const [],
|
||||
this.totalRicontattiToday = 0,
|
||||
this.totalRicontattiMonth = 0,
|
||||
required this.date,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
/// Numero di addetti che hanno raggiunto l'obiettivo (>= 2)
|
||||
int get staffWithGoal => summaries.where((s) => s.hasReachedGoal).length;
|
||||
|
||||
/// Numero di addetti che hanno registrato almeno 1 ricontatto (= 1)
|
||||
int get staffWithOne => summaries.where((s) => s.hasStarted).length;
|
||||
|
||||
/// Numero di addetti a 0
|
||||
int get staffAtZero => summaries.where((s) => s.isZero).length;
|
||||
|
||||
/// Totale addetti monitorati
|
||||
int get activeStaffCount => summaries.length;
|
||||
|
||||
DashboardDailyRicontattiState copyWith({
|
||||
DashboardDailyRicontattiStatus? status,
|
||||
List<StaffDailyRicontattiSummary>? summaries,
|
||||
int? totalRicontattiToday,
|
||||
int? totalRicontattiMonth,
|
||||
DateTime? date,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DashboardDailyRicontattiState(
|
||||
status: status ?? this.status,
|
||||
summaries: summaries ?? this.summaries,
|
||||
totalRicontattiToday:
|
||||
totalRicontattiToday ?? this.totalRicontattiToday,
|
||||
totalRicontattiMonth:
|
||||
totalRicontattiMonth ?? this.totalRicontattiMonth,
|
||||
date: date ?? this.date,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
summaries,
|
||||
totalRicontattiToday,
|
||||
totalRicontattiMonth,
|
||||
date,
|
||||
errorMessage,
|
||||
];
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
/// Modello di riepilogo giornaliero dei ricontatti per singolo addetto.
|
||||
class StaffDailyRicontattiSummary extends Equatable {
|
||||
final String staffId;
|
||||
final String staffName;
|
||||
final String? jobTitle;
|
||||
final SystemRole systemRole;
|
||||
final int count;
|
||||
final int monthCount;
|
||||
final List<OperationModel> operations;
|
||||
|
||||
const StaffDailyRicontattiSummary({
|
||||
required this.staffId,
|
||||
required this.staffName,
|
||||
this.jobTitle,
|
||||
this.systemRole = SystemRole.user,
|
||||
required this.count,
|
||||
this.monthCount = 0,
|
||||
this.operations = const [],
|
||||
});
|
||||
|
||||
/// Ha raggiunto l'obiettivo consigliato (almeno 2 ricontatti al giorno)
|
||||
bool get hasReachedGoal => count >= 2;
|
||||
|
||||
/// Ha iniziato la raccolta (1 ricontatto preso)
|
||||
bool get hasStarted => count == 1;
|
||||
|
||||
/// Non ha ancora registrato alcun ricontatto oggi
|
||||
bool get isZero => count == 0;
|
||||
|
||||
StaffDailyRicontattiSummary copyWith({
|
||||
String? staffId,
|
||||
String? staffName,
|
||||
String? jobTitle,
|
||||
SystemRole? systemRole,
|
||||
int? count,
|
||||
int? monthCount,
|
||||
List<OperationModel>? operations,
|
||||
}) {
|
||||
return StaffDailyRicontattiSummary(
|
||||
staffId: staffId ?? this.staffId,
|
||||
staffName: staffName ?? this.staffName,
|
||||
jobTitle: jobTitle ?? this.jobTitle,
|
||||
systemRole: systemRole ?? this.systemRole,
|
||||
count: count ?? this.count,
|
||||
monthCount: monthCount ?? this.monthCount,
|
||||
operations: operations ?? this.operations,
|
||||
);
|
||||
}
|
||||
|
||||
factory StaffDailyRicontattiSummary.empty() {
|
||||
return const StaffDailyRicontattiSummary(
|
||||
staffId: '',
|
||||
staffName: '',
|
||||
count: 0,
|
||||
monthCount: 0,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
staffId,
|
||||
staffName,
|
||||
jobTitle,
|
||||
systemRole,
|
||||
count,
|
||||
monthCount,
|
||||
operations,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class DashboardDailyRicontattiCard extends StatelessWidget {
|
||||
const DashboardDailyRicontattiCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Visibile a chi ha qualifica Manager o Titolare (o Admin di sistema)
|
||||
final staff = context.watch<SessionCubit>().state.currentStaffMember;
|
||||
final canView = staff?.canViewRicontattiFocus ?? false;
|
||||
|
||||
if (!canView) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return BlocBuilder<DashboardDailyRicontattiCubit,
|
||||
DashboardDailyRicontattiState>(
|
||||
builder: (context, state) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, outerConstraints) {
|
||||
final isMobile = outerConstraints.maxWidth < 600;
|
||||
final hPad = isMobile ? 16.0 : 24.0;
|
||||
final vGap = isMobile ? 16.0 : 24.0;
|
||||
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: Colors.amber.shade600.withValues(alpha: 0.35),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.amber.shade700.withValues(alpha: 0.06),
|
||||
blurRadius: 18,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context, theme, state, isCompact: isMobile),
|
||||
Divider(
|
||||
height: 1,
|
||||
color: theme.dividerColor.withValues(alpha: 0.15),
|
||||
),
|
||||
if (state.status == DashboardDailyRicontattiStatus.loading &&
|
||||
state.summaries.isEmpty)
|
||||
_buildLoading(theme)
|
||||
else if (state.status ==
|
||||
DashboardDailyRicontattiStatus.failure)
|
||||
_buildError(context, theme, state)
|
||||
else if (state.summaries.isEmpty)
|
||||
_buildEmpty(theme)
|
||||
else ...[
|
||||
_buildOverviewStats(
|
||||
context,
|
||||
theme,
|
||||
state,
|
||||
isCompact: isMobile,
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
isMobile ? 14 : 18,
|
||||
0,
|
||||
isMobile ? 14 : 18,
|
||||
isMobile ? 14 : 18,
|
||||
),
|
||||
child: _buildStaffGrid(context, theme, state.summaries),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTotalPillBadge(DashboardDailyRicontattiState state) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade500.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Colors.amber.shade600.withValues(alpha: 0.4),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'${state.totalRicontattiToday}',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
'oggi',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.amber.shade800,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'(mese: ${state.totalRicontattiMonth})',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.amber.shade900.withValues(alpha: 0.85),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state, {
|
||||
bool isCompact = false,
|
||||
}) {
|
||||
if (isCompact) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(14.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(9),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
Colors.amber.shade600,
|
||||
Colors.orange.shade700,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.event_repeat_rounded,
|
||||
color: Colors.white,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
'FOCUS RICONTATTI DI OGGI',
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
letterSpacing: 0.3,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'MANAGER',
|
||||
style: TextStyle(
|
||||
fontSize: 9.5,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.amber.shade900,
|
||||
letterSpacing: 0.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Aggiorna ora',
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 20),
|
||||
onPressed: () =>
|
||||
context.read<DashboardDailyRicontattiCubit>().refresh(),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Raccolta situazioni da ricontattare & bollette',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildTotalPillBadge(state),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(18.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
Colors.amber.shade600,
|
||||
Colors.orange.shade700,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.amber.shade700.withValues(alpha: 0.3),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.event_repeat_rounded,
|
||||
color: Colors.white,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
'FOCUS RICONTATTI DI OGGI',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 3,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'MANAGER',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.amber.shade900,
|
||||
letterSpacing: 0.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
'Raccolta situazioni da ricontattare & bollette (chi sta facendo e chi no)',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
_buildTotalPillBadge(state),
|
||||
const SizedBox(width: 6),
|
||||
IconButton(
|
||||
tooltip: 'Aggiorna ora',
|
||||
icon: const Icon(Icons.refresh_rounded, size: 20),
|
||||
onPressed: () =>
|
||||
context.read<DashboardDailyRicontattiCubit>().refresh(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildOverviewStats(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state, {
|
||||
bool isCompact = false,
|
||||
}) {
|
||||
final hasZeros = state.staffAtZero > 0;
|
||||
final pad = isCompact ? 14.0 : 18.0;
|
||||
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(pad, 12, pad, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: isCompact ? 8 : 12,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_buildStatChip(
|
||||
icon: Icons.check_circle_rounded,
|
||||
color: Colors.green.shade600,
|
||||
bgColor: Colors.green.shade50,
|
||||
label: '>= 2 Ricontatti',
|
||||
count: state.staffWithGoal,
|
||||
),
|
||||
_buildStatChip(
|
||||
icon: Icons.hourglass_top_rounded,
|
||||
color: Colors.blue.shade600,
|
||||
bgColor: Colors.blue.shade50,
|
||||
label: '1 Ricontatto',
|
||||
count: state.staffWithOne,
|
||||
),
|
||||
_buildStatChip(
|
||||
icon: Icons.warning_amber_rounded,
|
||||
color: Colors.deepOrange.shade600,
|
||||
bgColor: Colors.deepOrange.shade50,
|
||||
label: '0 Ricontatti',
|
||||
count: state.staffAtZero,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (hasZeros) ...[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.deepOrange.shade50.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: Colors.deepOrange.shade200,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline_rounded,
|
||||
size: 16,
|
||||
color: Colors.deepOrange.shade800,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${state.staffAtZero} ${state.staffAtZero == 1 ? "addetto non ha" : "addetti non hanno"} ancora raccolto alcun ricontatto oggi.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.deepOrange.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatChip({
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required Color bgColor,
|
||||
required String label,
|
||||
required int count,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: color),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'$count',
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStaffGrid(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
List<StaffDailyRicontattiSummary> summaries,
|
||||
) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Calcola quante colonne in base alla larghezza disponibile
|
||||
final double width = constraints.maxWidth;
|
||||
final int crossAxisCount = width > 1100
|
||||
? 4
|
||||
: width > 750
|
||||
? 3
|
||||
: width > 480
|
||||
? 2
|
||||
: 1;
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: summaries.length,
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: crossAxisCount,
|
||||
mainAxisSpacing: 10,
|
||||
crossAxisSpacing: 10,
|
||||
mainAxisExtent: crossAxisCount == 1 ? 86 : 104,
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final summary = summaries[index];
|
||||
return _StaffItemCard(summary: summary);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoading(ThemeData theme) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(32.0),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildError(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: theme.colorScheme.error, size: 32),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Impossibile caricare i dati dei ricontatti',
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextButton.icon(
|
||||
onPressed: () =>
|
||||
context.read<DashboardDailyRicontattiCubit>().refresh(),
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Riprova'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmpty(ThemeData theme) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Nessun addetto attivo registrato per questo negozio.',
|
||||
style: TextStyle(fontStyle: FontStyle.italic),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffItemCard extends StatelessWidget {
|
||||
final StaffDailyRicontattiSummary summary;
|
||||
|
||||
const _StaffItemCard({required this.summary});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
// Stile in base al conteggio
|
||||
final bool hasGoal = summary.hasReachedGoal;
|
||||
final bool hasOne = summary.hasStarted;
|
||||
final bool isZero = summary.isZero;
|
||||
|
||||
final Color primaryColor = hasGoal
|
||||
? Colors.green.shade600
|
||||
: hasOne
|
||||
? Colors.blue.shade600
|
||||
: Colors.grey.shade500;
|
||||
|
||||
final Color cardBg = hasGoal
|
||||
? Colors.green.shade50.withValues(alpha: 0.3)
|
||||
: hasOne
|
||||
? Colors.blue.shade50.withValues(alpha: 0.3)
|
||||
: theme.colorScheme.surface;
|
||||
|
||||
final Color borderColor = hasGoal
|
||||
? Colors.green.shade400
|
||||
: hasOne
|
||||
? Colors.blue.shade300
|
||||
: theme.dividerColor.withValues(alpha: 0.25);
|
||||
|
||||
final String initials = _getInitials(summary.staffName);
|
||||
|
||||
return InkWell(
|
||||
onTap: () => _handleTap(context),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: cardBg,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(
|
||||
color: borderColor,
|
||||
width: isZero ? 1.0 : 1.5,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// Avatar con iniziali
|
||||
CircleAvatar(
|
||||
radius: 20,
|
||||
backgroundColor: primaryColor.withValues(alpha: 0.15),
|
||||
child: Text(
|
||||
initials,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: primaryColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Nome e stato
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
summary.staffName,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: isZero
|
||||
? context.primaryText.withValues(alpha: 0.75)
|
||||
: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
_buildStatusChip(hasGoal, hasOne, isZero),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Grande numero conteggio e riepilogo mese tra parentesi
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
children: [
|
||||
Text(
|
||||
'${summary.count}',
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
height: 1.0,
|
||||
color: hasGoal
|
||||
? Colors.green.shade700
|
||||
: hasOne
|
||||
? Colors.blue.shade700
|
||||
: Colors.grey.shade400,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'oggi',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: hasGoal
|
||||
? Colors.green.shade700
|
||||
: hasOne
|
||||
? Colors.blue.shade700
|
||||
: Colors.grey.shade500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.6),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'(mese: ${summary.monthCount})',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.85),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(bool hasGoal, bool hasOne, bool isZero) {
|
||||
if (hasGoal) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.star_rounded, size: 13, color: Colors.green.shade700),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
'Obiettivo preso',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.green.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (hasOne) {
|
||||
return Text(
|
||||
'1 raccolto',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.blue.shade700,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Text(
|
||||
'0 ricontatti',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.deepOrange.shade600,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _getInitials(String name) {
|
||||
final parts = name.trim().split(RegExp(r'\s+'));
|
||||
if (parts.isEmpty || parts[0].isEmpty) return '?';
|
||||
if (parts.length == 1) return parts[0][0].toUpperCase();
|
||||
return '${parts[0][0]}${parts[1][0]}'.toUpperCase();
|
||||
}
|
||||
|
||||
void _handleTap(BuildContext context) {
|
||||
if (summary.operations.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${summary.staffName} non ha ancora registrato ricontatti oggi (${summary.monthCount} nel mese).',
|
||||
),
|
||||
duration: const Duration(seconds: 2),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mostra bottom sheet di dettaglio con le operazioni prese oggi dall'addetto
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (sheetContext) => _StaffOperationsSheet(summary: summary),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffOperationsSheet extends StatelessWidget {
|
||||
final StaffDailyRicontattiSummary summary;
|
||||
|
||||
const _StaffOperationsSheet({required this.summary});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final timeFormat = DateFormat('HH:mm');
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
padding: EdgeInsets.only(
|
||||
top: 16,
|
||||
left: 20,
|
||||
right: 20,
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
||||
),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.75,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 4,
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.dividerColor.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.person_rounded,
|
||||
color: Colors.amber.shade900,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
summary.staffName,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${summary.count} ${summary.count == 1 ? "ricontatto oggi" : "ricontatti oggi"} • (${summary.monthCount} nel mese)',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Divider(height: 1, color: theme.dividerColor.withValues(alpha: 0.2)),
|
||||
const SizedBox(height: 12),
|
||||
Flexible(
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
itemCount: summary.operations.length,
|
||||
separatorBuilder: (context, _) => Divider(
|
||||
height: 16,
|
||||
color: theme.dividerColor.withValues(alpha: 0.1),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final op = summary.operations[index];
|
||||
final ricontattoDetails = op.details
|
||||
.where((d) => d.type == OperationType.ricontatto)
|
||||
.toList();
|
||||
|
||||
final timeStr = op.createdAt != null
|
||||
? timeFormat.format(op.createdAt!)
|
||||
: '--:--';
|
||||
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: op),
|
||||
pathParameters: {'id': op.id!},
|
||||
);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 8.0,
|
||||
horizontal: 4.0,
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
timeStr,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
op.customer?.name ?? 'Cliente non specificato',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: ricontattoDetails.map((detail) {
|
||||
final label = detail.subType != null &&
|
||||
detail.subType!.isNotEmpty
|
||||
? detail.subType!
|
||||
: 'Ricontatto';
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
if (op.note.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
op.note,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Icon(
|
||||
Icons.chevron_right_rounded,
|
||||
size: 20,
|
||||
color: Colors.grey,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_state.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
class DashboardExpiringContractsCubit
|
||||
extends Cubit<DashboardExpiringContractsState> {
|
||||
final OperationsRepository _repository =
|
||||
GetIt.I.get<OperationsRepository>();
|
||||
final String? companyId;
|
||||
final String? storeId;
|
||||
StreamSubscription<void>? _operationsSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardExpiringContractsCubit({
|
||||
required this.companyId,
|
||||
required this.storeId,
|
||||
}) : super(const DashboardExpiringContractsState());
|
||||
|
||||
void startListening() {
|
||||
emit(state.copyWith(status: DashboardExpiringContractsStatus.loading));
|
||||
stopListening();
|
||||
|
||||
_loadExpiringSilently();
|
||||
|
||||
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
|
||||
_loadExpiringSilently();
|
||||
});
|
||||
|
||||
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
_loadExpiringSilently();
|
||||
});
|
||||
}
|
||||
|
||||
void stopListening() {
|
||||
_operationsSubscription?.cancel();
|
||||
_operationsSubscription = null;
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
void refresh() {
|
||||
_loadExpiringSilently();
|
||||
}
|
||||
|
||||
void _loadExpiringSilently() async {
|
||||
try {
|
||||
if (companyId == null || companyId!.isEmpty) return;
|
||||
final expiringOps = await _repository.fetchExpiringOperations(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
limit: 20,
|
||||
);
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardExpiringContractsStatus.success,
|
||||
operations: expiringOps,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardExpiringContractsStatus.failure,
|
||||
error: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
enum DashboardExpiringContractsStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardExpiringContractsState extends Equatable {
|
||||
final DashboardExpiringContractsStatus status;
|
||||
final List<OperationModel> operations;
|
||||
final String? error;
|
||||
|
||||
const DashboardExpiringContractsState({
|
||||
this.status = DashboardExpiringContractsStatus.initial,
|
||||
this.operations = const [],
|
||||
this.error,
|
||||
});
|
||||
|
||||
DashboardExpiringContractsState copyWith({
|
||||
DashboardExpiringContractsStatus? status,
|
||||
List<OperationModel>? operations,
|
||||
String? error,
|
||||
}) {
|
||||
return DashboardExpiringContractsState(
|
||||
status: status ?? this.status,
|
||||
operations: operations ?? this.operations,
|
||||
error: error,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, operations, error];
|
||||
}
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_state.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class DashboardExpiringContractsCard extends StatelessWidget {
|
||||
const DashboardExpiringContractsCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _ExpiringContractsCardContent();
|
||||
}
|
||||
}
|
||||
|
||||
class _ExpiringContractsCardContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
const color = Colors.orange;
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: () => context.pushNamed(Routes.operations),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// --- HEADER DELLA CARD ---
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.event_repeat_outlined,
|
||||
color: color,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.homeExpiringContracts,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// --- LISTA OPERAZIONI IN SCADENZA ---
|
||||
Expanded(
|
||||
child: BlocBuilder<DashboardExpiringContractsCubit,
|
||||
DashboardExpiringContractsState>(
|
||||
builder: (context, state) {
|
||||
if (state.status ==
|
||||
DashboardExpiringContractsStatus.loading ||
|
||||
state.status ==
|
||||
DashboardExpiringContractsStatus.initial) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status ==
|
||||
DashboardExpiringContractsStatus.failure) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Errore di caricamento",
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.operations.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Nessun contratto in scadenza.",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
itemCount: state.operations.length,
|
||||
separatorBuilder: (context, index) => Divider(
|
||||
height: 1,
|
||||
color: theme.dividerColor.withValues(alpha: 0.3),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final operation = state.operations[index];
|
||||
final earliestExp =
|
||||
OperationsRepository.getEarliestExpiration(operation);
|
||||
final phone = operation.customer?.phoneNumber;
|
||||
|
||||
return InkWell(
|
||||
onTap: () => context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: operation),
|
||||
pathParameters: {'id': operation.id!},
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
operation.customer?.name ??
|
||||
'Cliente sconosciuto',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (operation
|
||||
.attachments
|
||||
.isNotEmpty) ...[
|
||||
const SizedBox(width: 4),
|
||||
Icon(
|
||||
Icons.attach_file,
|
||||
size: 14,
|
||||
color: context.secondaryText,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_buildExpiryBadge(context, earliestExp),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
if (phone != null && phone.isNotEmpty) ...[
|
||||
Text(
|
||||
phone,
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontSize: 11,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
Expanded(child: _buildBadges(operation)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBadges(OperationModel op) {
|
||||
final labels = op.details
|
||||
.map((d) {
|
||||
final tLabel = d.type?.shortLabel ?? d.type?.value ?? '';
|
||||
final sub = d.subType?.trim() ?? '';
|
||||
final base = sub.isNotEmpty ? '$tLabel: $sub' : tLabel;
|
||||
if (base.isEmpty) return '';
|
||||
return d.quantity > 1 ? '$base ×${d.quantity}' : base;
|
||||
})
|
||||
.where((l) => l.isNotEmpty)
|
||||
.toList();
|
||||
|
||||
if (labels.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: labels
|
||||
.map(
|
||||
(label) => Container(
|
||||
margin: const EdgeInsets.only(right: 4),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(
|
||||
color: Colors.amber.withValues(alpha: 0.3),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: Colors.amber.shade800,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildExpiryBadge(BuildContext context, DateTime? expiry) {
|
||||
if (expiry == null) return const SizedBox.shrink();
|
||||
|
||||
final now = DateTime.now();
|
||||
final differenceDays = expiry.difference(now).inDays;
|
||||
final isExpired = expiry.isBefore(now);
|
||||
|
||||
Color badgeColor = Colors.orange;
|
||||
String text = "${expiry.day}/${expiry.month}/${expiry.year}";
|
||||
|
||||
if (isExpired) {
|
||||
badgeColor = Colors.red;
|
||||
text = "Scaduto ($text)";
|
||||
} else if (differenceDays <= 30) {
|
||||
badgeColor = Colors.redAccent;
|
||||
text = "Tra $differenceDays gg";
|
||||
} else if (differenceDays <= 60) {
|
||||
badgeColor = Colors.orange;
|
||||
text = "Tra ~${(differenceDays / 30).round()} mesi";
|
||||
} else {
|
||||
badgeColor = Colors.blue;
|
||||
text = "${expiry.day}/${expiry.month}/${expiry.year}";
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeColor.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: badgeColor.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: badgeColor,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,15 @@ class DashboardNoteListCubit extends Cubit<DashboardNoteListState> {
|
||||
try {
|
||||
_subscription = _repository
|
||||
.notesStream(companyId: companyId!, currentStaffId: staffId!)
|
||||
.listen((_) {
|
||||
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
|
||||
_loadNotesSilently();
|
||||
});
|
||||
.listen(
|
||||
(_) {
|
||||
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
|
||||
_loadNotesSilently();
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
debugPrint('Dashboard notes stream error: $error');
|
||||
},
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
debugPrint(e.toString());
|
||||
}
|
||||
|
||||
@@ -1,14 +1,36 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/notes/models/note_model.dart';
|
||||
import 'package:go_router/go_router.dart'; // Supponendo tu usi GoRouter per la navigazione
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class DashboardNoteListCard extends StatelessWidget {
|
||||
const DashboardNoteListCard({super.key});
|
||||
|
||||
Future<void> _createNewNote(BuildContext context) async {
|
||||
final sessionState = context.read<SessionCubit>().state;
|
||||
final companyId = sessionState.company?.id;
|
||||
final currentStaffId = sessionState.currentStaffMember?.id;
|
||||
if (companyId == null || currentStaffId == null) return;
|
||||
|
||||
final emptyNote = NoteModel.empty(
|
||||
createdBy: currentStaffId,
|
||||
companyId: companyId,
|
||||
);
|
||||
final noteId = await GetIt.I.get<NotesRepository>().saveNote(emptyNote);
|
||||
if (!context.mounted) return;
|
||||
context.pushNamed(
|
||||
Routes.noteForm,
|
||||
pathParameters: {'id': noteId},
|
||||
extra: emptyNote.copyWith(id: noteId),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
@@ -44,55 +66,59 @@ class DashboardNoteListCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
'Le mie Note',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: context.primaryText,
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Le mie Note',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Il corpo del widget collegato al Bloc
|
||||
BlocBuilder<DashboardNoteListCubit, DashboardNoteListState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == DashboardNoteListStatus.loading &&
|
||||
state.notes.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
Expanded(
|
||||
child: BlocBuilder<
|
||||
DashboardNoteListCubit,
|
||||
DashboardNoteListState
|
||||
>(
|
||||
builder: (context, state) {
|
||||
if (state.status == DashboardNoteListStatus.loading &&
|
||||
state.notes.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (state.status == DashboardNoteListStatus.failure) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Errore nel caricamento delle note.',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (state.status == DashboardNoteListStatus.failure) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Errore nel caricamento delle note.',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.notes.isEmpty) {
|
||||
return _buildEmptyState(context);
|
||||
}
|
||||
if (state.notes.isEmpty) {
|
||||
return _buildEmptyState(context);
|
||||
}
|
||||
|
||||
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
|
||||
final displayNotes = state.notes.take(4).toList();
|
||||
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
|
||||
final displayNotes = state.notes.take(4).toList();
|
||||
|
||||
return SizedBox(
|
||||
height: 140, // Altezza fissa per lo scroll orizzontale
|
||||
child: ListView.builder(
|
||||
return ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: displayNotes.length,
|
||||
itemBuilder: (context, index) {
|
||||
return _buildMiniPostIt(context, displayNotes[index]);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -168,7 +194,7 @@ class DashboardNoteListCard extends StatelessWidget {
|
||||
Widget _buildEmptyState(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(24),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -178,16 +204,18 @@ class DashboardNoteListCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.sticky_note_2_outlined,
|
||||
size: 32,
|
||||
size: 28,
|
||||
color: Colors.grey,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const SizedBox(height: 6),
|
||||
const Text('Nessuna nota presente.'),
|
||||
TextButton(
|
||||
onPressed: () => context.push('/notes/create'),
|
||||
style: TextButton.styleFrom(visualDensity: VisualDensity.compact),
|
||||
onPressed: () => _createNewNote(context),
|
||||
child: const Text('Creane una ora'),
|
||||
),
|
||||
],
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user