Compare commits

...
50 Commits
Author SHA1 Message Date
brontomark 6ad0aa3e23 v
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 38s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m1s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m17s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 4m59s
Build and Release FLUX (Multi-Platform) / build-macos (push) Has been cancelled
2026-09-19 16:33:50 +02:00
brontomark 11c5352555 ritmo singolo addetto
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m40s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m53s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 3m8s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 4m4s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m16s
2026-09-19 14:05:29 +02:00
brontomark a0bdb9a535 fix titolo hero target widget su mobile
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m49s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m58s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m46s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 4m5s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m17s
2026-09-19 13:49:14 +02:00
brontomark 37d69e3ddc aggiunta navigazione al file viewer
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 3m26s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m41s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 3m3s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 6m14s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m16s
2026-09-19 13:34:54 +02:00
brontomark 524da71a45 gestione obiettivi
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 4m24s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m42s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m33s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 10m44s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m53s
2026-09-18 11:41:26 +02:00
brontomark 3949d6d13c cambiate metriche, tolti totali aggregati e messo a posto lista obiettivi 2026-09-17 14:02:34 +02:00
brontomark d5591b2c91 a 2026-09-07 07:43:31 +02:00
brontomark 97d19f1d17 targets 2026-09-06 11:21:06 +02:00
brontomark 282a959f88 a 2026-09-06 10:03:27 +02:00
brontomark aaa6cdf704 fix attachments
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 3m39s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m14s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m57s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m48s
2026-08-19 12:43:01 +02:00
brontomark bc1614c71b fix attachments 2026-08-19 12:42:35 +02:00
brontomark b71656d0a6 controllo versione su linux
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 4m51s
Build and Release FLUX (Multi-Platform) / build-windows (push) Has been cancelled
Build and Release FLUX (Multi-Platform) / build-linux (push) Has been cancelled
Build and Release FLUX (Multi-Platform) / build-web (push) Has been cancelled
2026-08-18 19:31:58 +02:00
brontomark 9374f4ab46 nuova strategia per le liste delle operazioni e correzione bug indirizzo predefinito di spedizione dei provider
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 4m30s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m21s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 2m29s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m17s
2026-08-18 19:24:53 +02:00
brontomark 3b3e65bd1c v
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 4m39s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m15s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 7m32s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 2m0s
2026-08-18 15:24:16 +02:00
brontomark ce035e2204 a 2026-08-18 12:42:46 +02:00
brontomark 70c0c25521 a
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m18s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 2m47s
Build and Release FLUX (Multi-Platform) / build-android (push) Has been cancelled
Build and Release FLUX (Multi-Platform) / build-web (push) Has been cancelled
2026-08-17 19:30:07 +02:00
brontomark 8cd55f53f7 v fix ticket shipping
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m55s
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 12m32s
Build and Release FLUX (Multi-Platform) / build-web (push) Failing after 15m3s
2026-08-17 19:09:50 +02:00
brontomark 6e01729bf5 fix ticket shipping 2026-08-17 19:08:59 +02:00
brontomark 4b4d0c5cb6 a 2026-08-17 12:13:50 +02:00
brontomark ff27727f10 appdir 2026-08-17 11:55:39 +02:00
brontomark 8f0ad23c0b v 2026-08-17 10:55:21 +02:00
brontomark 729c893463 v
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m5s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m11s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 7m21s
2026-08-16 19:35:20 +02:00
brontomark eb31ad7173 si
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m43s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m22s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 26s
2026-08-16 19:12:51 +02:00
brontomark a652232b25 v
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 5m5s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m16s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 12m10s
2026-08-16 13:43:21 +02:00
brontomark b8f752d246 molto bene 2026-08-16 12:01:43 +02:00
brontomark b837a5fa1e Merge branch 'operation_details' of ssh://vps.catelli.it:2222/brontomark/flux into operation_details 2026-08-15 10:20:19 +02:00
brontomark 9154a16fe1 a 2026-08-15 10:20:03 +02:00
brontomark 48f6f92f9c a 2026-08-14 18:54:37 +02:00
brontomark c6e3594850 a 2026-08-11 08:36:44 +02:00
brontomark c6a1b203ce b 2026-08-08 08:29:59 +02:00
brontomark 1c96ff9516 b 2026-08-08 08:29:07 +02:00
brontomark 409c064902 b 2026-08-07 08:40:24 +02:00
brontomark 66667fb440 a 2026-08-05 19:28:30 +02:00
brontomark c41fcd37b3 operation details 2026-08-05 09:10:27 +02:00
brontomark 9cd0b98a16 feat: add fiscal code field to customer model and UI forms with support for viewing and copying
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m19s
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 10m18s
Build and Release FLUX (Multi-Platform) / build-web (push) Failing after 15m6s
2026-07-14 17:13:31 +02:00
brontomark 8951bff083 F
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 6m19s
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 11m39s
Build and Release FLUX (Multi-Platform) / build-web (push) Failing after 14m9s
2026-07-11 17:20:43 +02:00
brontomark a514bba8b2 fix search
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 12m18s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m45s
Build and Release FLUX (Multi-Platform) / build-web (push) Has been cancelled
2026-07-11 16:41:21 +02:00
brontomark f8504d466a fix attachments
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 1m44s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m5s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m7s
2026-06-08 14:36:31 +02:00
brontomark 22bb86f052 Merge branch 'main' of ssh.catelli.it:brontomark/flux 2026-06-08 13:20:52 +02:00
brontomark fc850795c9 fix attachments with no parentId 2026-06-08 13:17:33 +02:00
brontomark b60ce96dd7 fix uploads
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m14s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m3s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m48s
2026-06-08 13:15:29 +02:00
brontomark 6582da60d4 edge function per interrogare openai, capire quali immagini sono di documenti d'identità e assegnarli al cliente 2026-06-05 07:50:07 +02:00
brontomark d42cc5af1d v check fix
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-android (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 0s
2026-06-04 15:21:11 +02:00
brontomark 7ea0e2ac10 changed version check
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-android (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 0s
2026-06-04 14:21:27 +02:00
brontomark 5ce0110197 fix operations e tasks
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 6m20s
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 11m52s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m0s
2026-06-04 13:42:29 +02:00
brontomark 4efc3ce182 mmmh
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 2m11s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m1s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m5s
2026-06-04 12:34:38 +02:00
brontomark 01515910b6 mah....volare 2026-06-03 19:16:15 +02:00
brontomark f27ede7625 v - changed operation list
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-android (push) Canceled after 32s
2026-06-03 13:22:47 +02:00
brontomark 99ab7abf6e adfadsf 2026-06-03 13:20:22 +02:00
brontomark a7fd37a894 buono 2026-06-03 12:08:59 +02:00
120 changed files with 13042 additions and 2534 deletions

No files matched your search

+114 -11
View File
@@ -54,34 +54,34 @@ jobs:
run: Remove-Item -Recurse -Force ./*
# -----------------------------------------------------------------
# JOB 2: ANDROID APK (Gira sul tuo MacBook)
# JOB 2: ANDROID APPBUNDLE (Gira sul runner Fedora o Mac)
# -----------------------------------------------------------------
build-android:
runs-on: macos-runner # <--- Etichetta del tuo Mac
runs-on: cross-runner
steps:
- name: Checkout del codice
uses: actions/checkout@v3
# Logica Bash per Mac: usiamo le virgolette singole forti per evitare escape strani
# Logica Bash per Mac/Linux: 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
- name: Build Flutter AppBundle
run: flutter build appbundle --release
# Carichiamo l'APK universale o quelli splittati nelle release di Gitea
# Carichiamo l'AAB nelle release di Gitea per poi caricarlo su Google Play Console
- name: Upload Android Asset
uses: https://gitea.com/actions/release-action@main
with:
files: "build/app/outputs/flutter-apk/app-release.apk"
files: "build/app/outputs/bundle/release/app-release.aab"
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\"}"
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.aab\"}"
- name: Aggiorna Link Windows su Supabase
run: |
@@ -89,10 +89,10 @@ jobs:
# -----------------------------------------------------------------
# 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
@@ -112,4 +112,107 @@ 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"
# -----------------------------------------------------------------
# JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner)
# -----------------------------------------------------------------
build-linux:
runs-on: linux-runner # <--- Etichetta del tuo runner Linux / Fedora 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: Build Flutter Linux
run: flutter build linux --release
- name: Prepara AppDir per AppImage
run: |
mkdir -p build/Flux.AppDir
cp -r build/linux/x64/release/bundle/* build/Flux.AppDir/
cp assets/icon/icon.png build/Flux.AppDir/flux.png
cat << 'EOF' > build/Flux.AppDir/AppRun
#!/bin/sh
cd "$(dirname "$0")"
exec ./flux "$@"
EOF
chmod +x build/Flux.AppDir/AppRun
cat << 'EOF' > build/Flux.AppDir/Flux.desktop
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Flux
Exec=flux %u
Icon=flux
Categories=Utility;
EOF
- name: Scarica appimagetool se non presente
run: |
if [ ! -f ./appimagetool-x86_64.AppImage ]; then
curl -L -o appimagetool-x86_64.AppImage https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 ./appimagetool-x86_64.AppImage build/Flux.AppDir Flux-x86_64.AppImage
- 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: |
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.linux" -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 }}/Flux-x86_64.AppImage\"}"
# -----------------------------------------------------------------
# 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: 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: |
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\"}"
+4
View File
@@ -46,3 +46,7 @@ app.*.map.json
/android/app/release
.env
appimagetool*
*.AppDir
*.AppImage
+4
View File
@@ -11,6 +11,10 @@ analyzer:
- "ios/**"
- "macos/**"
- ".dart_tool/**"
- android/**
- web/**
- windows/**
- linux/**
linter:
rules:
+24 -4
View File
@@ -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")
}
}
}
}
BIN
View File
Binary file not shown.
@@ -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.
@@ -0,0 +1 @@
{"app_name":"flux","version":"1.3.1","build_number":"47","package_name":"flux"}
Binary file not shown.
BIN
View File
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.
+5
View File
@@ -1,4 +1,5 @@
class Tables {
static const String appConfig = 'app_config';
static const String attachments = 'attachments';
static const String brands = 'brands';
static const String campaigns = 'campaigns';
@@ -9,6 +10,7 @@ class Tables {
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';
@@ -16,8 +18,11 @@ 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';
static const String tickets = 'tickets';
static const String trackings = 'trackings';
}
+46 -7
View File
@@ -89,10 +89,16 @@ class _AppMenuState extends State<AppMenu> {
Icon(Icons.bolt, color: theme.colorScheme.primary, size: 32),
if (!effectivelyCollapsed) ...[
const SizedBox(width: 12),
Text(
"FLUX",
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
TextButton(
onPressed: () {
if (widget.isDrawer) Navigator.pop(context);
context.goNamed(Routes.home);
},
child: Text(
"FLUX",
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
],
@@ -111,14 +117,45 @@ class _AppMenuState extends State<AppMenu> {
padding: const EdgeInsets.symmetric(horizontal: 8.0),
children: [
_buildRouteItem(
title: context.l10n.commonDashboard,
title: 'Dashboard',
icon: Icons.dashboard_outlined,
routeName: Routes.home, // <--- Usiamo la tua costante!
routeName: Routes.home,
pathToCheck:
'/', // Il path da controllare per colorarlo
isCollapsed: effectivelyCollapsed,
),
const SizedBox(height: 8),
// --- SEZIONE OPERATIVA ---
_buildHierarchicalItem(
title: 'Operatività',
icon: Icons.work_outline,
basePathToCheck: '/',
isCollapsed: effectivelyCollapsed,
subItems: [
_SubMenuItem(
'Operazioni',
Routes.operations,
'/operations',
),
_SubMenuItem(
'Assistenza',
Routes.tickets,
'/tickets',
),
_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) ---
_buildHierarchicalItem(
@@ -256,7 +293,9 @@ class _AppMenuState extends State<AppMenu> {
required bool isCollapsed,
required List<_SubMenuItem> subItems,
}) {
final isSelected = widget.currentPath.startsWith(basePathToCheck);
final isSelected = subItems.any(
(item) => widget.currentPath.startsWith(item.pathToCheck),
);
final theme = Theme.of(context);
if (isCollapsed) {
+67 -1
View File
@@ -21,6 +21,7 @@ import 'package:flux/features/customers/ui/customers_list_screen.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,6 +43,7 @@ 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/ui/operation_form_screen.dart';
@@ -60,8 +62,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';
@@ -178,6 +190,13 @@ 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,
),
),
],
child: const HomeScreen(),
);
@@ -310,10 +329,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 +566,15 @@ class AppRouter {
existingOperation: record?.operation,
),
),
BlocProvider(
create: (context) => OperationDetailsListCubit(
details: record?.operation?.details ?? [],
),
),
],
child: OperationFormScreen(
operationId: realOperationId,
existingOperation: record?.operation,
operation: record?.operation,
),
);
},
+3
View File
@@ -27,4 +27,7 @@ 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';
}
+64 -37
View File
@@ -1,67 +1,94 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'dart:io' show Platform;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class VersionCheckService {
final _supabase = Supabase.instance.client;
/// Controlla se l'app corrente deve essere bloccata o aggiornata.
/// Ritorna il link di download se l'aggiornamento è obbligatorio, altrimenti null.
Future<String?> checkForceUpdate() async {
try {
// 1. Determiniamo la piattaforma corrente
String platformKey = 'web';
if (!kIsWeb) {
if (Platform.isAndroid) platformKey = 'android';
if (Platform.isWindows) platformKey = 'windows';
// 1. Capiamo su che piattaforma sta girando l'app in questo istante
String currentPlatform = _getCurrentPlatform();
// 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
if (dbResponse == null) {
return null; // Nessuna regola per questa piattaforma
}
// 2. Recuperiamo la configurazione minima da Supabase
final data = await _supabase
.from('app_config')
.select()
.eq('platform', platformKey)
.maybeSingle();
String minVersionFromDb = dbResponse['min_version'] as String;
String downloadUrl = dbResponse['download_url'] as String;
if (data == null) return null;
// 3. Recuperiamo la versione locale di Flutter
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String localVersionRaw = packageInfo.version;
final String minVersion = data['min_version'];
final String downloadUrl = data['download_url'];
// 🥷 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();
// 3. Recuperiamo la versione attuale dell'app dal pubspec.yaml
final packageInfo = await PackageInfo.fromPlatform();
final String currentVersion = packageInfo.version;
// 4. Confronto matematico semantico (es. 1.2.3 vs 1.1.9)
if (_isVersionLower(currentVersion, minVersion)) {
return downloadUrl; // Aggiornamento obbligatorio richiesto!
// 🥷 TRUCCO 2: Confronto Semantico Reale
if (_isVersionLower(current: cleanLocal, minimum: cleanDb)) {
// Ritorna il link VERO per questa specifica piattaforma preso dal CSV!
return downloadUrl;
}
return null;
} catch (e) {
debugPrint('Errore controllo versione: $e');
return null; // In caso di errore non blocchiamo l'utente
debugPrint("Errore durante il check versione: $e");
return null;
}
}
bool _isVersionLower(String current, String min) {
// 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';
}
// Il motore matematico (resta invariato)
bool _isVersionLower({required String current, required String minimum}) {
if (current == minimum) return false;
List<int> currentParts = current
.split('.')
.map((e) => int.tryParse(e) ?? 0)
.toList();
List<int> minParts = min
List<int> minParts = minimum
.split('.')
.map((e) => int.tryParse(e) ?? 0)
.toList();
for (int i = 0; i < 3; i++) {
int currentPart = currentParts.length > i ? currentParts[i] : 0;
int minPart = minParts.length > i ? minParts[i] : 0;
if (currentPart < minPart) return true;
if (currentPart > minPart) return false;
while (currentParts.length < 3) {
currentParts.add(0);
}
return false;
while (minParts.length < 3) {
minParts.add(0);
}
if (currentParts[0] != minParts[0]) {
return currentParts[0] < minParts[0];
}
if (currentParts[1] != minParts[1]) {
return currentParts[1] < minParts[1];
}
return currentParts[2] < minParts[2];
}
}
+134
View File
@@ -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,
);
}
}
+104 -69
View File
@@ -19,84 +19,119 @@ class QrUploadDialog extends StatelessWidget {
// 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,
listener: (context, state) {
final newCount = state.allFiles.length;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'File caricato con successo via QR Code! 📄 ($newCount allegati in totale)',
),
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 fileCount = state.allFiles.length;
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(
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),
),
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, // Lo sfondo bianco salva la vita sui temi scuri
borderRadius: BorderRadius.circular(16),
),
child: QrImageView(
data: 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(
fileCount > 0
? Icons.check_circle_outline
: Icons.hourglass_empty,
size: 18,
color: fileCount > 0
? Colors.green
: theme.colorScheme.primary,
),
const SizedBox(width: 8),
Text(
fileCount > 0
? "$fileCount file ricevuti! (In ascolto...)"
: "In attesa di file...",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: fileCount > 0
? Colors.green
: theme.colorScheme.primary,
),
),
],
),
),
const SizedBox(height: 8),
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
],
const SizedBox(height: 8),
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
],
),
),
),
),
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,
);
},
);
}
}
@@ -34,14 +34,14 @@ class SharedAttachmentsSection extends StatefulWidget {
final String? parentId;
final String titleForUpload;
final AttachmentParentType parentType;
final Future<String?> Function()? onGenerateIdForQr;
final Future<String?> Function()? onEnsureEntitySaved;
const SharedAttachmentsSection({
super.key,
this.parentId,
this.titleForUpload = 'Cliente_sconosciuto',
required this.parentType,
this.onGenerateIdForQr,
this.onEnsureEntitySaved,
});
@override
@@ -56,6 +56,24 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
void initState() {
super.initState();
_loadExportDirectory();
_syncParentIdIfNeeded();
}
@override
void didUpdateWidget(covariant SharedAttachmentsSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.parentId != oldWidget.parentId) {
_syncParentIdIfNeeded();
}
}
void _syncParentIdIfNeeded() {
if (widget.parentId != null && widget.parentId!.isNotEmpty) {
final attachmentsBloc = context.read<AttachmentsBloc>();
if (attachmentsBloc.state.parentId != widget.parentId) {
attachmentsBloc.add(ParentEntitySavedEvent(widget.parentId!));
}
}
}
// --- GESTIONE CARTELLA CITRIX (SOLO DESKTOP) ---
@@ -90,6 +108,29 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
// --- SELEZIONE FILE DAL PC/TELEFONO ---
Future<void> _pickFiles() async {
final attachmentsBloc = context.read<AttachmentsBloc>();
String? targetId = attachmentsBloc.state.parentId ?? widget.parentId;
// 🥷 SE L'ID NON C'È (Nuova Operazione), PROVIAMO IL SALVATAGGIO PREVENTIVO
if (targetId == null || targetId.isEmpty) {
if (widget.onEnsureEntitySaved != null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Salvataggio rapido scheda per allegati... ⏳'),
duration: Duration(seconds: 1),
),
);
targetId = await widget.onEnsureEntitySaved!();
}
}
if (targetId != null &&
targetId.isNotEmpty &&
attachmentsBloc.state.parentId != targetId) {
attachmentsBloc.add(ParentEntitySavedEvent(targetId));
}
final result = await FilePicker.pickFiles(
allowMultiple: true,
type: FileType.custom,
@@ -97,29 +138,180 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
withData: true,
);
if (result != null && mounted) {
// MAGIA: Passiamo direttamente la lista di PlatformFile al tuo BLoC!
context.read<AttachmentsBloc>().add(AddAttachmentsEvent(result.files));
if (result == null || result.files.isEmpty || !mounted) return;
final List<PlatformFile> processedFiles = [];
for (int i = 0; i < result.files.length; i++) {
final file = result.files[i];
Widget previewWidget;
final ext = file.extension?.toLowerCase() ?? '';
if ((ext == 'jpg' || ext == 'jpeg' || ext == 'png') &&
file.bytes != null) {
previewWidget = Image.memory(file.bytes!, fit: BoxFit.contain);
} else if (ext == 'pdf') {
previewWidget = const Center(
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
);
} else {
previewWidget = const Center(
child: Icon(Icons.insert_drive_file, size: 80, color: Colors.blue),
);
}
final rawOriginalName =
file.name.contains('.')
? file.name.substring(0, file.name.lastIndexOf('.'))
: file.name;
final defaultSuggested =
result.files.length == 1
? widget.titleForUpload
: '${widget.titleForUpload}_${i + 1}';
final finalName = await showDialog<String>(
context: context,
barrierDismissible: false,
builder:
(_) => QuickRenameDialog(
title:
result.files.length == 1
? 'Nome Allegato'
: 'Nome Allegato (${i + 1}/${result.files.length})',
suggestedName:
defaultSuggested.isNotEmpty
? defaultSuggested
: rawOriginalName,
suffixText: ext.isNotEmpty ? '.$ext' : null,
confirmButtonText: 'Importa (Invio)',
previewWidget: previewWidget,
),
);
if (finalName != null && finalName.trim().isNotEmpty) {
final cleanName = finalName.trim();
final extString = ext.isNotEmpty ? '.$ext' : '';
final fullNewName =
cleanName.endsWith(extString) ? cleanName : '$cleanName$extString';
final updatedFile = PlatformFile(
name: fullNewName,
size: file.size,
path: file.path,
bytes: file.bytes,
readStream: file.readStream,
);
processedFiles.add(updatedFile);
} else {
processedFiles.add(file);
}
}
if (processedFiles.isEmpty || !mounted) return;
// 1. Aggiungiamo i file rinominati al BLoC
attachmentsBloc.add(AddAttachmentsEvent(processedFiles));
// 2. Chiediamo se cancellare i file fisici dal computer
if (!kIsWeb) {
final filesOnDisk =
processedFiles
.where((f) => f.path != null && File(f.path!).existsSync())
.toList();
if (filesOnDisk.isNotEmpty && mounted) {
final shouldDelete = await showDialog<bool>(
context: context,
builder:
(dialogContext) => AlertDialog(
title: const Row(
children: [
Icon(Icons.delete_forever, color: Colors.red),
SizedBox(width: 8),
Text('Eliminare file dal computer?'),
],
),
content: Text(
'I file (${filesOnDisk.length}) sono stati importati in Flux.\n\nVuoi cancellare i file originali dal tuo computer per liberare spazio?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('No, mantieni sul PC'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Sì, elimina dal PC'),
),
],
),
);
if (shouldDelete == true) {
int deletedCount = 0;
for (var f in filesOnDisk) {
try {
final fileObj = File(f.path!);
if (fileObj.existsSync()) {
await fileObj.delete();
deletedCount++;
}
} catch (e) {
debugPrint('Errore durante l\'eliminazione del file locale: $e');
}
}
if (mounted && deletedCount > 0) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'$deletedCount file fisici eliminati dal computer.',
),
backgroundColor: Colors.orange.shade800,
),
);
}
}
}
}
}
// --- APERTURA VIEWER ---
void _openFile(AttachmentModel file) {
void _openFile(
AttachmentModel file, {
List<AttachmentModel>? files,
int? initialIndex,
}) {
// 1. Catturiamo il BLoC dalla pagina corrente prima di navigare
final operationFilesBloc = context.read<AttachmentsBloc>();
final allFilesList = files ?? operationFilesBloc.state.allFiles;
final index = initialIndex ??
(allFilesList.isNotEmpty ? allFilesList.indexOf(file) : 0);
Navigator.push(
context,
MaterialPageRoute(
builder: (viewerContext) => BlocProvider.value(
value: operationFilesBloc,
child: AttachmentViewerScreen(
attachment: file,
onRename: (newName) {
attachments: allFilesList.isNotEmpty ? allFilesList : [file],
initialIndex: index >= 0 ? index : 0,
onRenameAttachment: (targetFile, newName) {
// Spara l'evento al BLoC e lui farà il resto!
operationFilesBloc.add(RenameAttachmentEvent(file, newName));
operationFilesBloc.add(
RenameAttachmentEvent(targetFile, newName),
);
},
onDelete: () {
operationFilesBloc.add(DeleteSpecificAttachmentEvent(file));
onDeleteAttachment: (targetFile) {
operationFilesBloc.add(
DeleteSpecificAttachmentEvent(targetFile),
);
},
),
),
@@ -477,11 +669,11 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
icon: const Icon(Icons.qr_code_scanner),
color: theme.colorScheme.primary, // Sempre colorato!
onPressed: () async {
String? targetId = state.parentId;
String? targetId = state.parentId ?? widget.parentId;
// SE L'ID NON C'È, CHIAMIAMO IL SALVATAGGIO IN BACKGROUND!
if (targetId == null) {
if (widget.onGenerateIdForQr != null) {
if (targetId == null || targetId.isEmpty) {
if (widget.onEnsureEntitySaved != null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
@@ -491,12 +683,29 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
),
);
// Aspettiamo che il TicketFormCubit faccia il suo lavoro
targetId = await widget.onGenerateIdForQr!();
targetId = await widget.onEnsureEntitySaved!();
}
}
// Se fallisce (es. validazione form non passata), ci fermiamo
if (targetId == null) return;
if (targetId == null || targetId.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Salva la scheda prima di generare il QR Code per gli allegati.',
),
backgroundColor: Colors.orange,
),
);
}
return;
}
if (!context.mounted) return;
final attachmentBloc = context.read<AttachmentsBloc>();
if (attachmentBloc.state.parentId != targetId) {
attachmentBloc.add(ParentEntitySavedEvent(targetId));
}
// GENERAZIONE DEL DEEP LINK AGNOSTICO
@@ -509,8 +718,6 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
'https://flux.catelli.it/upload/${state.parentType.name}/$targetId?companyId=$companyId';
if (context.mounted) {
final attachmentBloc = context.read<AttachmentsBloc>();
showDialog(
context: context,
builder: (_) => BlocProvider.value(
@@ -696,7 +903,11 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
children: [
// CARD DEL FILE
InkWell(
onTap: () => _openFile(file),
onTap: () => _openFile(
file,
files: allFiles,
initialIndex: index,
),
onLongPress: () {
// Selezione rapida con long press!
context.read<AttachmentsBloc>().add(
@@ -202,6 +202,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',
),
],
),
],
],
),
),
@@ -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',
),
),
);
}
@@ -1,110 +1,191 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flux/core/utils/functions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:pdfx/pdfx.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;
const AttachmentViewerScreen({
super.key,
required this.attachment,
this.attachment,
this.attachments,
this.initialIndex = 0,
this.onRename,
this.onRenameAttachment,
this.onDelete,
});
this.onDeleteAttachment,
}) : 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> {
late List<AttachmentModel> _items;
late int _currentIndex;
final FocusNode _focusNode = FocusNode();
PdfControllerPinch? _pdfController;
bool _isLoading = true;
String? _errorMessage;
Uint8List? _fileBytes;
late String _fileName;
int _loadToken = 0;
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;
@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;
}
_loadFile();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_focusNode.requestFocus();
}
});
}
@override
void dispose() {
_focusNode.dispose();
_pdfController?.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;
_pdfController?.dispose();
_pdfController = null;
setState(() {
_currentIndex = newIndex;
_isLoading = true;
_errorMessage = null;
_fileBytes = null;
});
_loadFile();
}
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 if (item.storagePath != null &&
item.storagePath!.isNotEmpty) {
final signedUrl = await getSignedUrl(item.storagePath!);
bytes = await InternetFile.get(signedUrl);
} else {
throw Exception("Nessun documento trovato o byte mancanti.");
}
if (token != _loadToken || !mounted) return;
PdfControllerPinch? controller;
if (isPdf && bytes != null) {
controller = PdfControllerPinch(
document: PdfDocument.openData(bytes),
);
}
setState(() {
_fileBytes = bytes;
_pdfController = controller;
_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 +196,141 @@ 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'),
),
],
),
);
}
@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,
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,
),
if (hasMultipleFiles)
Text(
'${_currentIndex + 1} di ${_items.length}',
style: const TextStyle(fontSize: 12, color: Colors.white70),
),
],
),
actions: [
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(),
),
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?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(c),
child: const Text('Annulla'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
Navigator.pop(c); // Chiude dialog
widget.onDelete!(); // Lancia eliminazione
Navigator.pop(context); // Chiude il viewer
},
child: const Text('Elimina'),
),
],
// 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(),
);
}
@@ -218,3 +367,41 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
}
}
}
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),
),
],
);
@@ -69,6 +69,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
String? note,
bool? doNotDisturb,
bool? isBusiness,
String? fiscalCode,
}) {
emit(
state.copyWith(
@@ -79,6 +80,8 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
note: note ?? state.customer.note,
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
isBusiness: isBusiness ?? state.customer.isBusiness,
fiscalCode:
fiscalCode?.trim().toUpperCase() ?? state.customer.fiscalCode,
),
),
);
@@ -111,6 +114,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
String? phone,
String? email,
required bool isBusiness,
String? fiscalCode,
}) async {
final newCustomer = CustomerModel(
name: name,
@@ -119,6 +123,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
companyId: _sessionCubit.state.company!.id!,
note: '',
isBusiness: isBusiness,
fiscalCode: fiscalCode?.trim().toUpperCase(),
);
try {
@@ -15,6 +15,7 @@ class CustomerModel extends Equatable {
final bool isActive;
final List<AttachmentModel> attachments;
final bool isBusiness;
final String? fiscalCode;
const CustomerModel({
this.id,
@@ -29,6 +30,7 @@ class CustomerModel extends Equatable {
this.isActive = true,
this.attachments = const [],
this.isBusiness = false,
this.fiscalCode,
});
@override
@@ -45,6 +47,7 @@ class CustomerModel extends Equatable {
isActive,
attachments,
isBusiness,
fiscalCode,
];
factory CustomerModel.empty() => CustomerModel(
@@ -69,6 +72,7 @@ class CustomerModel extends Equatable {
bool? isActive,
List<AttachmentModel>? attachments,
bool? isBusiness,
String? fiscalCode,
}) {
return CustomerModel(
id: id ?? this.id,
@@ -83,6 +87,7 @@ class CustomerModel extends Equatable {
isActive: isActive ?? this.isActive,
attachments: attachments ?? this.attachments,
isBusiness: isBusiness ?? this.isBusiness,
fiscalCode: fiscalCode ?? this.fiscalCode,
);
}
@@ -108,6 +113,7 @@ class CustomerModel extends Equatable {
.toList() ??
const [],
isBusiness: map['is_business'] as bool? ?? false,
fiscalCode: map['fiscal_code'] as String?,
);
}
@@ -124,6 +130,7 @@ class CustomerModel extends Equatable {
'company_id': companyId,
'is_active': isActive,
'is_business': isBusiness,
'fiscal_code': fiscalCode?.trim().toUpperCase(),
};
}
}
@@ -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';
@@ -24,6 +25,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
final TextEditingController _telefonoController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _noteController = TextEditingController();
final TextEditingController _fiscalCodeController = TextEditingController();
bool _isInitialized = false;
@override
@@ -49,6 +51,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
_telefonoController.dispose();
_emailController.dispose();
_noteController.dispose();
_fiscalCodeController.dispose();
super.dispose();
}
@@ -65,6 +68,9 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
if (_noteController.text.isEmpty) {
_noteController.text = customer.note;
}
if (_fiscalCodeController.text.isEmpty && customer.fiscalCode != null) {
_fiscalCodeController.text = customer.fiscalCode!;
}
_isInitialized = true;
}
@@ -74,6 +80,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
phoneNumber: _telefonoController.text.trim(),
email: _emailController.text.trim(),
note: _noteController.text.trim(),
fiscalCode: _fiscalCodeController.text.trim(),
);
}
@@ -172,6 +179,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';
@@ -16,7 +17,8 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
final _phoneCtrl = 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;
@@ -33,6 +35,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
_phoneCtrl.dispose();
_emailCtrl.dispose();
_noteCtrl.dispose();
_fiscalCodeCtrl.dispose();
super.dispose();
}
@@ -50,6 +53,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
name: _nameCtrl.text.trim(),
phone: _phoneCtrl.text.trim(),
email: _emailCtrl.text.trim(),
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
);
setState(() => _isLoading = false);
@@ -125,6 +129,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"),
@@ -1,7 +1,6 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_model.dart';
@@ -15,6 +14,8 @@ class DashboardStoreOperationListCubit
final String? companyId;
final String? storeId;
StreamSubscription<void>? _operationsSubscription;
Timer? _pollingTimer;
DashboardStoreOperationListCubit({
required this.companyId,
required this.storeId,
@@ -31,37 +32,43 @@ class DashboardStoreOperationListCubit
// Primo caricamento
_loadOperationsSilently();
// Inizio ascolto campanello
try {
_operationsSubscription = _repository
.watchStoreOperations(storeId: storeId!, limit: 10)
.listen((_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadOperationsSilently();
});
} on Exception catch (e) {
debugPrint(e.toString());
}
// 1. Ascolto notifiche locali di mutazione in memoria (reattività istantanea)
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
_loadOperationsSilently();
});
// 2. Polling programmato ogni 30 secondi per sincronizzazione di fondo
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
_loadOperationsSilently();
});
}
void stopListening() {
_operationsSubscription?.cancel();
_operationsSubscription = null;
_pollingTimer?.cancel();
_pollingTimer = null;
}
void refresh() {
_loadOperationsSilently();
}
void _loadOperationsSilently() async {
try {
final operations = await _repository.fetchOperations(
if (companyId == null || storeId == null) return;
final paginatedData = await _repository.fetchPaginatedOperations(
companyId: companyId!,
storeId: storeId!,
limit: 10,
offset: 0,
page: 1,
itemsPerPage: 20,
onlyShowInDashboard: true,
);
if (isClosed) return;
emit(
state.copyWith(
status: DashboardStoreOperationListStatus.success,
operations: operations,
operations: paginatedData.operations,
error: null,
),
);
@@ -140,14 +140,19 @@ class _LatestOperationsCardContent extends StatelessWidget {
),
Expanded(
flex: 5,
child: Text(
operation.type,
style: TextStyle(
fontWeight: FontWeight.w600,
color: context.primaryText,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
),
child: _buildBadgeList(
operation.details
.map((d) => d.type)
.whereType<String>()
.where(
(t) => t.trim().isNotEmpty,
)
.toList(),
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
@@ -172,4 +177,74 @@ class _LatestOperationsCardContent extends StatelessWidget {
),
);
}
Widget _buildBadgeList(List<String> types) {
if (types.isEmpty) {
return const Align(
alignment: Alignment.centerLeft,
child: _OperationTypeBadge(label: 'N/A'),
);
}
return Wrap(
spacing: 4,
runSpacing: 4,
children: types.map((t) => _OperationTypeBadge(label: t)).toList(),
);
}
}
class _OperationTypeBadge extends StatelessWidget {
final String label;
const _OperationTypeBadge({required this.label});
Color _getBadgeColor(String type) {
switch (type.toUpperCase()) {
case 'FIN':
case 'FINANZIAMENTO':
return Colors.deepPurple;
case 'TELEPASS':
return Colors.amber.shade800;
case 'ENERGY':
case 'ENERGIA':
return Colors.orange.shade800;
case 'ENTERTAINMENT':
return Colors.pinkAccent.shade700;
case 'AL':
case 'MNP':
return Colors.indigo;
case 'NIP':
case 'FWA':
return Colors.cyan.shade800;
case 'FIBRA':
case 'MOBILE':
return Colors.blue.shade700;
default:
return Colors.blueGrey;
}
}
@override
Widget build(BuildContext context) {
final color = _getBadgeColor(label);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
),
child: Text(
label,
style: TextStyle(
color: color,
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 0.2,
),
),
);
}
}
@@ -0,0 +1,155 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/targets/data/target_progress_service.dart';
import 'package:flux/features/targets/data/targets_repository.dart';
import 'package:flux/service_locator.dart';
import 'dashboard_target_progress_state.dart';
class DashboardTargetProgressCubit extends Cubit<DashboardTargetProgressState> {
final TargetsRepository _targetsRepository = sl<TargetsRepository>();
final OperationsRepository _operationsRepository = sl<OperationsRepository>();
final TargetProgressService _progressService = sl<TargetProgressService>();
String? companyId;
String? storeId;
String? staffId;
StreamSubscription<void>? _operationsSubscription;
StreamSubscription<void>? _targetsSubscription;
Timer? _pollingTimer;
DashboardTargetProgressCubit({
this.companyId,
this.storeId,
this.staffId,
}) : super(
DashboardTargetProgressState(
currentStaffId: staffId,
),
);
void updateContext({
String? newCompanyId,
String? newStoreId,
String? newStaffId,
}) {
bool changed = false;
if (newCompanyId != null && newCompanyId != companyId) {
companyId = newCompanyId;
changed = true;
}
if (newStoreId != null && newStoreId != storeId) {
storeId = newStoreId;
changed = true;
}
if (newStaffId != null && newStaffId != staffId) {
staffId = newStaffId;
changed = true;
}
if (changed) {
emit(state.copyWith(currentStaffId: staffId));
refresh();
}
}
void startListening() {
emit(state.copyWith(status: DashboardTargetProgressStatus.loading));
stopListening();
_loadProgressSilently();
// 1. Ascolto modifiche delle operazioni in real-time
_operationsSubscription =
_operationsRepository.onOperationsChanged.listen((_) {
_loadProgressSilently();
});
// 2. Ascolto modifiche ai target
_targetsSubscription = _targetsRepository.onTargetsChanged.listen((_) {
_loadProgressSilently();
});
// 3. Polling leggero ogni 45 secondi
_pollingTimer = Timer.periodic(const Duration(seconds: 45), (_) {
_loadProgressSilently();
});
}
void stopListening() {
_operationsSubscription?.cancel();
_operationsSubscription = null;
_targetsSubscription?.cancel();
_targetsSubscription = null;
_pollingTimer?.cancel();
_pollingTimer = null;
}
void refresh() {
_loadProgressSilently();
}
Future<void> _loadProgressSilently() async {
if (companyId == null || storeId == null) {
if (!isClosed) {
emit(state.copyWith(status: DashboardTargetProgressStatus.noTarget));
}
return;
}
try {
final now = DateTime.now();
final target = await _targetsRepository.getStoreTargetForMonth(
companyId: companyId!,
storeId: storeId!,
month: now,
);
if (isClosed) return;
if (target == null) {
emit(
state.copyWith(
status: DashboardTargetProgressStatus.noTarget,
target: null,
progress: null,
currentStaffId: staffId,
),
);
return;
}
final progress = await _progressService.calculateTargetProgress(
target: target,
now: now,
);
if (isClosed) return;
emit(
state.copyWith(
status: DashboardTargetProgressStatus.success,
target: target,
progress: progress,
currentStaffId: staffId,
errorMessage: null,
),
);
} catch (e) {
if (isClosed) return;
emit(
state.copyWith(
status: DashboardTargetProgressStatus.failure,
errorMessage: e.toString(),
),
);
}
}
@override
Future<void> close() {
stopListening();
return super.close();
}
}
@@ -0,0 +1,131 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
enum DashboardTargetProgressStatus {
initial,
loading,
success,
noTarget,
failure,
}
class DashboardTargetProgressState extends Equatable {
final DashboardTargetProgressStatus status;
final TargetModel? target;
final TargetProgressModel? progress;
final String? currentStaffId;
final String? errorMessage;
const DashboardTargetProgressState({
this.status = DashboardTargetProgressStatus.initial,
this.target,
this.progress,
this.currentStaffId,
this.errorMessage,
});
DashboardTargetProgressState copyWith({
DashboardTargetProgressStatus? status,
TargetModel? target,
TargetProgressModel? progress,
String? currentStaffId,
String? errorMessage,
}) {
return DashboardTargetProgressState(
status: status ?? this.status,
target: target ?? this.target,
progress: progress ?? this.progress,
currentStaffId: currentStaffId ?? this.currentStaffId,
errorMessage: errorMessage,
);
}
/// Avanzamento specifico del membro dello staff indicato o correntemente connesso
TargetProgressModel? getStaffProgress([String? staffId]) {
final curProgress = progress;
final id = staffId ?? currentStaffId;
if (curProgress == null || id == null) return null;
return curProgress.staffProgress[id];
}
/// True se lo staff connesso o specificato ha almeno un target individuale attivo impostato
bool hasStaffTargets([String? staffId]) {
final sp = getStaffProgress(staffId);
if (sp == null) return false;
return sp.categories.values.any((c) => c.hasTarget);
}
/// Lista delle categorie con target attivo per l'addetto indicato o connesso
List<CategoryProgress> activeStaffCategories([String? staffId]) {
final sp = getStaffProgress(staffId);
if (sp == null) return const [];
return sp.categories.values.where((c) => c.hasTarget).toList();
}
/// Restituisce sempre l'avanzamento personalizzato per lo staff
TargetProgressModel getEffectiveStaffProgress({
required String? staffId,
required String? staffName,
}) {
final sp = getStaffProgress(staffId);
if (sp != null) {
return sp;
}
final curProgress = progress;
if (curProgress == null) {
return TargetProgressModel.empty();
}
// Se l'addetto non è mappato nella lista (es. nuovo addetto senza operazioni),
// creiamo una scheda personale con le categorie attive del negozio
final staffCount = target?.individualTargets.length ?? 1;
final divisor = staffCount > 0 ? staffCount : 1;
final userCategories = <String, CategoryProgress>{};
for (final entry in curProgress.categories.entries) {
final storeCat = entry.value;
userCategories[entry.key] = CategoryProgress.calculate(
key: storeCat.key,
label: storeCat.label,
actual: 0,
s1: (storeCat.targetS1 / divisor).round(),
s2: (storeCat.targetS2 / divisor).round(),
elapsedDays: curProgress.elapsedWorkingDays,
remainingDays: curProgress.remainingWorkingDays,
totalDays: curProgress.totalWorkingDays,
);
}
return TargetProgressModel(
targetId: curProgress.targetId,
storeId: curProgress.storeId,
staffId: staffId,
staffName: staffName,
totalWorkingDays: curProgress.totalWorkingDays,
elapsedWorkingDays: curProgress.elapsedWorkingDays,
remainingWorkingDays: curProgress.remainingWorkingDays,
categories: userCategories,
);
}
/// Avanzamento specifico del membro dello staff correntemente connesso
TargetProgressModel? get currentStaffProgress => getStaffProgress();
/// Lista delle categorie con target attivo per il negozio
List<CategoryProgress> get activeStoreCategories {
final curProgress = progress;
if (curProgress == null) return const [];
return curProgress.categories.values.where((c) => c.hasTarget).toList();
}
@override
List<Object?> get props => [
status,
target,
progress,
currentStaffId,
errorMessage,
];
}
@@ -0,0 +1,719 @@
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/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
import 'package:go_router/go_router.dart';
class DashboardTargetHeroCard extends StatelessWidget {
const DashboardTargetHeroCard({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<DashboardTargetProgressCubit, DashboardTargetProgressState>(
builder: (context, state) {
final theme = Theme.of(context);
if (state.status == DashboardTargetProgressStatus.loading ||
state.status == DashboardTargetProgressStatus.initial) {
return _buildLoadingCard(theme);
}
if (state.status == DashboardTargetProgressStatus.noTarget ||
state.target == null ||
state.progress == null) {
return _buildNoTargetCard(context, theme);
}
return _buildHeroContent(context, theme, state);
},
);
}
Widget _buildLoadingCard(ThemeData theme) {
return Container(
height: 160,
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.2)),
),
child: const Center(
child: SizedBox(
width: 28,
height: 28,
child: CircularProgressIndicator(strokeWidth: 2.5),
),
),
);
}
Widget _buildNoTargetCard(BuildContext context, ThemeData theme) {
final currentStore = context.watch<SessionCubit>().state.currentStore;
final now = DateTime.now();
final months = [
'Gennaio',
'Febbraio',
'Marzo',
'Aprile',
'Maggio',
'Giugno',
'Luglio',
'Agosto',
'Settembre',
'Ottobre',
'Novembre',
'Dicembre'
];
final monthLabel = '${months[now.month - 1]} ${now.year}';
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: theme.colorScheme.primary.withValues(alpha: 0.2),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: theme.colorScheme.primary.withValues(alpha: 0.04),
blurRadius: 16,
offset: const Offset(0, 4),
),
],
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(14),
),
child: Icon(
Icons.flag_outlined,
color: theme.colorScheme.primary,
size: 28,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Nessun obiettivo per $monthLabel',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'Imposta i target di ${currentStore?.name ?? "questo negozio"} per monitorare le medie giornaliere richieste e il ritmo di vendita.',
style: TextStyle(
fontSize: 13,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 16),
FilledButton.icon(
onPressed: () => context.pushNamed(Routes.targets),
icon: const Icon(Icons.add, size: 18),
label: const Text('Imposta Target'),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
],
),
);
}
Widget _buildHeroContent(
BuildContext context,
ThemeData theme,
DashboardTargetProgressState state,
) {
final progress = state.progress!;
final target = state.target!;
final staffMember =
context.watch<SessionCubit>().state.currentStaffMember;
final staffName = staffMember?.name ?? 'Ospite';
final staffId = staffMember?.id;
final staffProgress = state.getEffectiveStaffProgress(
staffId: staffId,
staffName: staffName,
);
final displayCategories = staffProgress.categories.values
.where((c) => c.hasTarget)
.toList();
final remainingDays = progress.remainingWorkingDays;
return LayoutBuilder(
builder: (context, constraints) {
final isCompact = constraints.maxWidth < 600;
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: theme.colorScheme.primary.withValues(alpha: 0.25),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: theme.colorScheme.primary.withValues(alpha: 0.06),
blurRadius: 20,
offset: const Offset(0, 6),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ==========================================
// 1. HEADER DELLA CARD (TITOLO & GIORNI)
// ==========================================
Padding(
padding: EdgeInsets.fromLTRB(
isCompact ? 14 : 20,
isCompact ? 14 : 18,
isCompact ? 14 : 20,
isCompact ? 10 : 14,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.all(isCompact ? 8 : 10),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
theme.colorScheme.primary,
theme.colorScheme.primary.withValues(alpha: 0.8),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: theme.colorScheme.primary
.withValues(alpha: 0.25),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Icon(
Icons.trending_up_rounded,
color: Colors.white,
size: isCompact ? 20 : 22,
),
),
SizedBox(width: isCompact ? 10 : 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
Text(
'IL TUO RITMO PER OGGI',
style: TextStyle(
fontSize: isCompact ? 10.5 : 11,
fontWeight: FontWeight.w800,
letterSpacing: 0.6,
color: theme.colorScheme.primary,
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2,
),
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer
.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(6),
),
child: Text(
remainingDays > 1
? 'Mancano $remainingDays gg'
: (remainingDays == 1
? 'Ultimo giorno!'
: 'Mese concluso'),
style: TextStyle(
fontSize: isCompact ? 10 : 11,
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
),
],
),
const SizedBox(height: 3),
Text(
staffMember != null
? 'Cosa portare a casa oggi, $staffName'
: 'Obiettivi personali per oggi',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w900,
fontSize: isCompact ? 15 : 17,
),
),
],
),
),
const SizedBox(width: 4),
// Tasto rapido dettaglio
if (isCompact)
IconButton(
onPressed: () => context.pushNamed(
Routes.targetDetail,
extra: target,
),
icon: const Icon(Icons.analytics_outlined),
tooltip: 'Dettagli target',
color: theme.colorScheme.primary,
visualDensity: VisualDensity.compact,
)
else
TextButton.icon(
onPressed: () => context.pushNamed(
Routes.targetDetail,
extra: target,
),
icon: const Icon(Icons.analytics_outlined, size: 18),
label: const Text('Dettagli'),
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
foregroundColor: theme.colorScheme.primary,
textStyle: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
),
// ==========================================
// 2. FOCUS METRICHE: MEDIE RICHIESTE PER OGGI
// ==========================================
if (displayCategories.isEmpty)
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
child: Text(
'Nessun obiettivo attivo configurato per questo mese.',
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: 13,
),
),
)
else
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: displayCategories.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
constraints.maxWidth > 700 ? 260 : 200,
mainAxisExtent: 168,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (context, index) {
final category = displayCategories[index];
final storeCategory = progress.categories[category.key];
return _buildCategoryDailyPacingCard(
theme,
category,
storeCategory: storeCategory,
);
},
),
),
const SizedBox(height: 14),
// ==========================================
// 3. SEZIONE INFERIORE: RIEPILOGO NEGOZIO
// ==========================================
Container(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.35),
borderRadius: const BorderRadius.vertical(
bottom: Radius.circular(19),
),
border: Border(
top: BorderSide(
color: theme.dividerColor.withValues(alpha: 0.2),
),
),
),
padding: EdgeInsets.symmetric(
horizontal: isCompact ? 14 : 20,
vertical: 10,
),
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 10,
runSpacing: 8,
children: [
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 6,
runSpacing: 4,
children: [
Icon(
Icons.storefront_outlined,
size: 17,
color: theme.colorScheme.primary,
),
Text(
'Negozio:',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w800,
color: theme.colorScheme.primary,
letterSpacing: 0.5,
),
),
const SizedBox(width: 2),
// Badge sintetici del negozio
_buildMiniBadge(
label:
'${progress.countAchieved}/${progress.countTotalActive} Presi',
color: const Color(0xFF15803D),
bgColor: const Color(0xFFDCFCE7),
),
_buildMiniBadge(
label: '${progress.countInLineOnly} In linea',
color: const Color(0xFF0D9488),
bgColor: const Color(0xFFCCFBF1),
),
if (progress.countBehind > 0)
_buildMiniBadge(
label: '${progress.countBehind} Sotto ritmo',
color: const Color(0xFFDC2626),
bgColor: const Color(0xFFFEE2E2),
),
],
),
InkWell(
onTap: () => context.pushNamed(
Routes.targetDetail,
extra: target,
),
borderRadius: BorderRadius.circular(6),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Apri analisi completa',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
const SizedBox(width: 4),
Icon(
Icons.arrow_forward_rounded,
size: 14,
color: theme.colorScheme.primary,
),
],
),
),
),
],
),
),
],
),
);
},
);
}
Widget _buildCategoryDailyPacingCard(
ThemeData theme,
CategoryProgress category, {
CategoryProgress? storeCategory,
}) {
final pacingTheme = PacingTheme.of(category.status);
final isAchieved = category.isAchieved;
final hasS2 = category.targetS2 > 0;
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: pacingTheme.border.withValues(alpha: 0.7),
width: 1.2,
),
boxShadow: [
BoxShadow(
color: pacingTheme.primary.withValues(alpha: 0.04),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header tessera: Nome metrica + Pillola di stato
Row(
children: [
Expanded(
child: Text(
category.label.toUpperCase(),
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w800,
letterSpacing: 0.3,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: pacingTheme.background,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: pacingTheme.border, width: 0.8),
),
child: Text(
isAchieved
? 'Preso! 🎉'
: (category.status == TargetPacingStatus.inLineS1 ||
category.status == TargetPacingStatus.inLineS2
? 'In linea ✅'
: (category.status == TargetPacingStatus.recoverable
? 'Da spingere ⚡'
: 'In ritardo 🔴')),
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w900,
color: pacingTheme.text,
),
),
),
],
),
const Spacer(),
// Centro: Numero gigante MEDIA GIORNALIERA RICHIESTA PER OGGI
if (isAchieved)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'RAGGIUNTO',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: pacingTheme.primary,
letterSpacing: -0.5,
),
),
const SizedBox(width: 4),
const Text('🏆', style: TextStyle(fontSize: 16)),
],
),
if (hasS2 && !category.isAchievedS2)
Text(
'Sfida (S2): ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.purple.shade700,
),
)
else
Text(
'Obiettivo personale centrato!',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
)
else
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
category.requiredDailyRateS1.toStringAsFixed(1),
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w900,
color: pacingTheme.text,
letterSpacing: -0.5,
),
),
const SizedBox(width: 4),
Text(
'/ giorno',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w800,
color: pacingTheme.text.withValues(alpha: 0.8),
),
),
],
),
if (hasS2)
Text(
'Sfida S2: ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
)
else
Text(
'Target: ${category.targetS1} pz',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
const Spacer(),
// Footer: Avanzamento personale e ritmo
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'I tuoi: ${category.actualPieces} / ${category.targetS1}',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
),
Text(
'ritmo: ${category.actualDailyRate.toStringAsFixed(1)}/gg',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
const SizedBox(height: 4),
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: category.targetS1 > 0
? (category.actualPieces / category.targetS1).clamp(0.0, 1.0)
: 0.0,
minHeight: 4,
backgroundColor: pacingTheme.background,
color: pacingTheme.primary,
),
),
if (storeCategory != null && storeCategory.targetS1 > 0) ...[
const SizedBox(height: 4),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Negozio: ${storeCategory.actualPieces}/${storeCategory.targetS1}',
style: TextStyle(
fontSize: 9.5,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75),
fontWeight: FontWeight.w600,
),
),
Text(
'ritmo: ${storeCategory.actualDailyRate.toStringAsFixed(1)}/gg',
style: TextStyle(
fontSize: 9.5,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75),
fontWeight: FontWeight.w600,
),
),
],
),
],
],
),
);
}
Widget _buildMiniBadge({
required String label,
required Color color,
required Color bgColor,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(6),
),
child: Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: color,
),
),
);
}
}
+68 -37
View File
@@ -19,6 +19,8 @@ import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/notes/data/notes_repository.dart';
import 'package:flux/features/notes/models/note_model.dart';
import 'package:flux/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart';
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
import 'package:flux/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
@@ -73,13 +75,21 @@ class _HomeScreenState extends State<HomeScreen> {
context.read<DashboardTaskListCubit>().stopListening();
context.read<DashboardStoreTicketListCubit>().stopListening();
context.read<DashboardNoteListCubit>().stopListening();
context.read<DashboardTargetProgressCubit>().stopListening();
}
void _startListeners() {
final sessionState = context.read<SessionCubit>().state;
context.read<DashboardTargetProgressCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
newStaffId: sessionState.currentStaffMember?.id,
);
context.read<DashboardStoreOperationListCubit>().startListening();
context.read<DashboardTaskListCubit>().startListening();
context.read<DashboardStoreTicketListCubit>().startListening();
context.read<DashboardNoteListCubit>().startListening();
context.read<DashboardTargetProgressCubit>().startListening();
}
@override
@@ -112,47 +122,68 @@ class _HomeScreenState extends State<HomeScreen> {
// 2. CORPO DELLA DASHBOARD (Scrollabile)
// ==========================================
Expanded(
child: CustomScrollView(
slivers: [
// --- QUICK ACTIONS: AZIONI RAPIDE ---
SliverToBoxAdapter(
child: Padding(
child: BlocListener<SessionCubit, SessionState>(
listenWhen: (prev, curr) =>
prev.currentStore?.id != curr.currentStore?.id ||
prev.currentStaffMember?.id != curr.currentStaffMember?.id ||
prev.company?.id != curr.company?.id,
listener: (context, sessionState) {
context.read<DashboardTargetProgressCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
newStaffId: sessionState.currentStaffMember?.id,
);
},
child: CustomScrollView(
slivers: [
// --- HERO TARGET DEL GIORNO (TUTTA LARGHEZZA IN CIMA) ---
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
child: DashboardTargetHeroCard(),
),
),
// --- QUICK ACTIONS: AZIONI RAPIDE ---
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: _buildQuickActions(context),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 32)),
// --- I WIDGET DELLA DASHBOARD (Responsive Grid) ---
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: _buildQuickActions(context),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 32)),
// --- I WIDGET DELLA DASHBOARD (Responsive Grid) ---
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
sliver: SliverGrid(
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 500,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
childAspectRatio: 1.3,
sliver: SliverGrid(
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 500,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
childAspectRatio: 1.3,
),
delegate: SliverChildListDelegate([
DashboardStoreOperationListCard(),
DashboardStoreTicketListCard(),
_buildDashboardWidget(
title: context.l10n.homeExpiringContracts,
icon: Icons.assignment_late_outlined,
color: Colors.orange,
context: context,
),
delegate: SliverChildListDelegate([
DashboardStoreOperationListCard(),
DashboardStoreTicketListCard(),
_buildDashboardWidget(
title: context.l10n.homeExpiringContracts,
icon: Icons.assignment_late_outlined,
color: Colors.orange,
context: context,
),
DashboardNoteListCard(),
DashboardTaskListCard(),
]),
DashboardNoteListCard(),
DashboardTaskListCard(),
]),
),
),
),
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
),
),
),
],
@@ -1,6 +1,7 @@
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/consts.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; // Per estrarre gli store
import '../models/provider_model.dart';
@@ -32,7 +33,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
try {
// 1. Scarichiamo tutti i negozi dell'azienda
final storesResponse = await _client
.from('store')
.from(Tables.stores)
.select('id, name')
.eq('company_id', companyId);
@@ -41,7 +42,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
if (existingProvider != null && existingProvider.id != null) {
// ... (Vecchio codice di recupero)
final links = await _client
.from('providers_in_stores')
.from(Tables.providersInStores)
.select('store_id')
.eq('provider_id', existingProvider.id!);
linkedStoreIds = (links as List)
@@ -83,6 +84,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
String? fiscalCode,
String? sdiCode,
String? emailPec,
String? Function()? colorHex,
}) {
emit(
state.copyWith(
@@ -93,6 +95,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
fiscalCode: fiscalCode,
sdiCode: sdiCode,
emailPec: emailPec,
colorHex: colorHex,
),
),
);
@@ -123,11 +126,61 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
}
Future<void> addLocationLocal(ProviderLocationModel location) async {
List<ProviderLocationModel> currentLocations = List<ProviderLocationModel>.from(
state.localLocations,
);
final bool shouldBeMain = location.isMain || currentLocations.isEmpty;
if (shouldBeMain) {
currentLocations = currentLocations
.map((loc) => loc.copyWith(isMain: false))
.toList();
}
currentLocations.add(location.copyWith(isMain: shouldBeMain));
emit(state.copyWith(localLocations: currentLocations));
}
void updateLocationLocal(int index, ProviderLocationModel location) {
final currentLocations = List<ProviderLocationModel>.from(
state.localLocations,
);
currentLocations.add(location);
emit(state.copyWith(localLocations: currentLocations));
if (index < 0 || index >= currentLocations.length) return;
bool shouldBeMain = location.isMain;
if (!shouldBeMain && currentLocations.length == 1) {
shouldBeMain = true;
}
final List<ProviderLocationModel> updatedList = [];
for (int i = 0; i < currentLocations.length; i++) {
if (i == index) {
updatedList.add(location.copyWith(isMain: shouldBeMain));
} else {
updatedList.add(
shouldBeMain
? currentLocations[i].copyWith(isMain: false)
: currentLocations[i],
);
}
}
emit(state.copyWith(localLocations: updatedList));
}
void setMainLocationLocal(int index) {
final currentLocations = List<ProviderLocationModel>.from(
state.localLocations,
);
if (index < 0 || index >= currentLocations.length) return;
final updatedList = currentLocations.asMap().entries.map((entry) {
final idx = entry.key;
final loc = entry.value;
return loc.copyWith(isMain: idx == index);
}).toList();
emit(state.copyWith(localLocations: updatedList));
}
void removeLocationLocal(int index) {
@@ -135,7 +188,13 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
state.localLocations,
);
if (index >= 0 && index < currentLocations.length) {
currentLocations.removeAt(index);
final removedLoc = currentLocations.removeAt(index);
if (removedLoc.id != null && removedLoc.id!.isNotEmpty) {
_repository.deleteLocation(removedLoc.id!);
}
if (removedLoc.isMain && currentLocations.isNotEmpty) {
currentLocations[0] = currentLocations[0].copyWith(isMain: true);
}
emit(state.copyWith(localLocations: currentLocations));
}
}
@@ -76,6 +76,12 @@ class ProviderRepository {
// 4. Gestione Sedi (Locations)
Future<void> saveLocation(ProviderLocationModel location) async {
if (location.isMain && location.providerId.isNotEmpty) {
await _supabase
.from(Tables.providerLocations)
.update({'is_main': false})
.eq('provider_id', location.providerId);
}
await _supabase.from(Tables.providerLocations).upsert(location.toMap());
}
@@ -1,4 +1,5 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'provider_location_model.dart';
import 'provider_role.dart';
@@ -8,6 +9,7 @@ class ProviderModel extends Equatable {
final String companyId;
final String name; // Nome "commerciale" per riconoscerlo velocemente
final bool isActive;
final String? colorHex;
// Dati fiscali e legali
final String? businessName; // Ragione Sociale
@@ -29,6 +31,7 @@ class ProviderModel extends Equatable {
required this.companyId,
required this.name,
this.isActive = true,
this.colorHex,
this.businessName,
this.vatNumber,
this.fiscalCode,
@@ -42,6 +45,17 @@ class ProviderModel extends Equatable {
this.locations,
});
// 🥷 IL GETTER MAGICO: Converte l'esadecimale in un Color di Flutter
Color get displayColor {
if (colorHex == null || colorHex!.isEmpty) {
return Colors.blueGrey; // Colore di default
}
// Rimuove l'eventuale '#' e aggiunge 'FF' per l'opacità (Alpha)
final hex = colorHex!.replaceAll('#', '');
return Color(int.parse('FF$hex', radix: 16));
}
factory ProviderModel.empty({required String companyId}) {
return ProviderModel(
companyId: companyId,
@@ -56,6 +70,7 @@ class ProviderModel extends Equatable {
String? companyId,
String? name,
bool? isActive,
String? Function()? colorHex,
String? businessName,
String? vatNumber,
String? fiscalCode,
@@ -73,6 +88,7 @@ class ProviderModel extends Equatable {
companyId: companyId ?? this.companyId,
name: name ?? this.name,
isActive: isActive ?? this.isActive,
colorHex: colorHex != null ? colorHex() : this.colorHex,
businessName: businessName ?? this.businessName,
vatNumber: vatNumber ?? this.vatNumber,
fiscalCode: fiscalCode ?? this.fiscalCode,
@@ -114,6 +130,7 @@ class ProviderModel extends Equatable {
companyId: map['company_id'] as String,
name: map['name'] as String,
isActive: map['is_active'] as bool? ?? true,
colorHex: map['color_hex'] as String?,
businessName: map['business_name'] as String?,
vatNumber: map['vat_number'] as String?,
fiscalCode: map['fiscal_code'] as String?,
@@ -134,6 +151,7 @@ class ProviderModel extends Equatable {
'company_id': companyId,
'name': name,
'is_active': isActive,
'color_hex': colorHex,
'business_name': businessName,
'vat_number': vatNumber,
'fiscal_code': fiscalCode,
@@ -155,6 +173,7 @@ class ProviderModel extends Equatable {
companyId,
name,
isActive,
colorHex,
businessName,
vatNumber,
fiscalCode,
@@ -1,28 +1,42 @@
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/providers/models/provider_role.dart';
import 'package:flux/features/operations/models/operation_type.dart';
extension ProviderCompatibility on ProviderModel {
bool supportsOperation(String operationType) {
if (operationType == 'Altro') return true;
bool supportsOperationType(OperationType? operationType) {
if (operationType == null || operationType == OperationType.altro) {
return true;
}
switch (operationType) {
case 'AL' || 'MNP':
case OperationType.al ||
OperationType.mnp ||
OperationType.cb ||
OperationType.upselling:
return roles.contains(ProviderRole.mobile);
case 'NIP' || 'FWA':
case OperationType.nip || OperationType.fwa:
return roles.contains(ProviderRole.landline);
case 'UNICA':
case OperationType.unica:
return roles.contains(ProviderRole.landline) ||
roles.contains(ProviderRole.mobile);
case 'Energy':
case OperationType.energy:
return roles.contains(ProviderRole.energy);
case 'Fin':
case OperationType.fin:
return roles.contains(ProviderRole.financing);
case 'Entertainment':
case OperationType.entertainment:
return roles.contains(ProviderRole.entertainment);
case 'TELEPASS':
case OperationType.telepass:
return roles.contains(ProviderRole.telepass);
case OperationType.business:
return roles.contains(ProviderRole.mobile) ||
roles.contains(ProviderRole.landline);
default:
return true;
}
}
bool supportsOperation(String operationType) {
final type = OperationType.fromValue(operationType);
return supportsOperationType(type);
}
}
@@ -66,6 +66,17 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
super.dispose();
}
final List<String> _brandColors = [
'#E60000', // Vodafone/Iliad (Rosso scuro)
'#0047BB', // TIM (Blu)
'#F4811F', // WINDTRE (Arancione)
'#FFCC00', // Fastweb (Giallo)
'#00A859', // Verde generico
'#8E44AD', // Viola
'#2C3E50', // Blu scuro/Nero
'#607D8B', // BlueGrey (Default)
];
void _flushControllers() {
context.read<ProviderFormCubit>().updateFields(
name: _nameCtrl.text.trim(),
@@ -132,6 +143,8 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
children: [
_buildGeneralCard(context, state),
const SizedBox(height: 24),
_buildColorPicker(),
const SizedBox(height: 24),
_buildRolesCard(context, state),
const SizedBox(height: 24),
_buildFiscalCard(context),
@@ -370,11 +383,47 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
itemBuilder: (context, index) {
final loc = state.localLocations[index];
return ListTile(
leading: Icon(
loc.isMain ? Icons.star : Icons.location_on,
color: loc.isMain ? Colors.amber : null,
onTap: () async {
final providerFormCubit = context.read<ProviderFormCubit>();
final res = await showDialog<ProviderLocationModel?>(
context: context,
builder: (context) => ProviderLocationDialog(initialLocation: loc),
);
if (res != null) {
providerFormCubit.updateLocationLocal(index, res);
}
},
leading: IconButton(
tooltip: loc.isMain ? 'Sede predefinita' : 'Imposta come predefinita',
icon: Icon(
loc.isMain ? Icons.star : Icons.star_border,
color: loc.isMain ? Colors.amber : Colors.grey,
),
onPressed: () => context
.read<ProviderFormCubit>()
.setMainLocationLocal(index),
),
title: Row(
children: [
Expanded(child: Text(loc.name)),
if (loc.isMain)
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.amber.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(4),
),
child: const Text(
'Predefinita',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.amber,
),
),
),
],
),
title: Text(loc.name),
subtitle: Text(
'${loc.address}, ${loc.city} (${loc.province})',
),
@@ -392,4 +441,70 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
),
);
}
Widget _buildColorPicker() {
return Column(
children: [
const Text(
'Colore Riconoscitivo',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
const SizedBox(height: 12),
BlocBuilder<ProviderFormCubit, ProviderFormState>(
builder: (context, state) {
// Se non ha un colore, usiamo il BlueGrey di default
final currentColorHex = state.provider.colorHex ?? '#607D8B';
return Wrap(
spacing: 12,
runSpacing: 12,
children: _brandColors.map((hexCode) {
final isSelected =
currentColorHex.toUpperCase() == hexCode.toUpperCase();
// Conversione rapida per disegnare il cerchio
final colorValue = Color(
int.parse('FF${hexCode.replaceAll('#', '')}', radix: 16),
);
return InkWell(
borderRadius: BorderRadius.circular(24),
onTap: () {
// Aggiorniamo il Cubit con il nuovo colore
context.read<ProviderFormCubit>().updateFields(
colorHex: () => hexCode,
);
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 42,
height: 42,
decoration: BoxDecoration(
color: colorValue,
shape: BoxShape.circle,
border: Border.all(
color: isSelected ? Colors.black : Colors.transparent,
width: isSelected ? 3 : 0,
),
boxShadow: [
if (isSelected)
BoxShadow(
color: colorValue.withValues(alpha: 0.4),
blurRadius: 8,
spreadRadius: 2,
),
],
),
child: isSelected
? const Icon(Icons.check, color: Colors.white, size: 24)
: null,
),
);
}).toList(),
);
},
),
],
);
}
}
@@ -0,0 +1,125 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/products/models/model_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
part 'operation_details_form_state.dart';
class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
OperationDetailsFormCubit({
OperationDetailModel? initialDetail,
int? editingIndex,
List<ProviderModel>? allProviders,
String? defaultProviderId,
}) : super(
OperationDetailsFormState(
operationDetail: initialDetail ?? const OperationDetailModel(),
editingIndex: editingIndex,
),
) {
if (initialDetail == null &&
allProviders != null &&
allProviders.isNotEmpty) {
const defaultType = OperationType.al;
setTypeWithSmartDefaults(
newType: defaultType,
allProviders: allProviders,
defaultProviderId: defaultProviderId,
);
}
}
void updateFields({
OperationType? type,
String? subType,
ProviderModel? provider,
ModelModel? model,
String? modelId,
String? description,
DateTime? expirationDate,
}) {
final current = state.operationDetail;
final updated = current.copyWith(
type: type ?? current.type,
subType: subType ?? current.subType,
provider:
provider != null
? () => provider
: (current.provider != null ? () => current.provider : null),
model:
model != null
? () => model
: (current.model != null ? () => current.model : null),
modelId: modelId ?? current.modelId,
description: description ?? current.description,
expirationDate: expirationDate ?? current.expirationDate,
);
emit(
state.copyWith(
operationDetail: updated,
status: OperationDetailsFormStatus.ready,
),
);
}
void setProvider(ProviderModel provider) {
final updated = state.operationDetail.copyWith(
provider: () => provider,
providerId: provider.id,
);
emit(
state.copyWith(
operationDetail: updated,
status: OperationDetailsFormStatus.ready,
),
);
}
void setTypeWithSmartDefaults({
required OperationType newType,
required List<ProviderModel> allProviders,
String? defaultProviderId,
}) {
ProviderModel? selectedProvider;
if (defaultProviderId != null) {
final foundDefault = allProviders.firstWhere(
(p) =>
p.id == defaultProviderId &&
p.supportsOperationType(newType) &&
p.isActive,
orElse: () => const ProviderModel(companyId: '', name: ''),
);
if (foundDefault.id != null) {
selectedProvider = foundDefault;
}
}
if (selectedProvider == null) {
final foundCompatible = allProviders.firstWhere(
(p) => p.supportsOperationType(newType) && p.isActive,
orElse: () => const ProviderModel(companyId: '', name: ''),
);
if (foundCompatible.id != null) {
selectedProvider = foundCompatible;
}
}
final current = state.operationDetail;
final updated = current.copyWith(
type: newType,
subType: newType == OperationType.energy ? EnergySubtypes.luce : null,
provider: selectedProvider != null ? () => selectedProvider : null,
providerId: selectedProvider?.id,
);
emit(
state.copyWith(
operationDetail: updated,
status: OperationDetailsFormStatus.ready,
),
);
}
}
@@ -0,0 +1,41 @@
part of 'operation_details_form_cubit.dart';
enum OperationDetailsFormStatus { ready, updated, failure }
class OperationDetailsFormState extends Equatable {
final OperationDetailModel operationDetail;
final String? errorMessage;
final OperationDetailsFormStatus status;
final int? editingIndex;
const OperationDetailsFormState({
required this.operationDetail,
this.errorMessage,
this.status = OperationDetailsFormStatus.ready,
this.editingIndex,
});
bool get isEditing => editingIndex != null;
OperationDetailsFormState copyWith({
OperationDetailModel? operationDetail,
String? errorMessage,
OperationDetailsFormStatus? status,
int? Function()? editingIndex,
}) {
return OperationDetailsFormState(
operationDetail: operationDetail ?? this.operationDetail,
errorMessage: errorMessage ?? this.errorMessage,
status: status ?? this.status,
editingIndex: editingIndex != null ? editingIndex() : this.editingIndex,
);
}
@override
List<Object?> get props => [
operationDetail,
errorMessage,
status,
editingIndex,
];
}
@@ -0,0 +1,97 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
part 'operation_details_list_state.dart';
class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
OperationDetailsListCubit({required List<OperationDetailModel> details})
: super(OperationDetailsListState(details: details));
void addOperationDetail(OperationDetailModel operationDetail) {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails.add(operationDetail);
emit(
OperationDetailsListState(
details: updatedDetails,
status: OperationDetailsListStatus.updated,
),
);
}
void deleteOperationDetail(int index) {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails.removeAt(index);
emit(
OperationDetailsListState(
details: updatedDetails,
status: OperationDetailsListStatus.updated,
),
);
}
void toggleOperationDetailsSelection(int index) {
final updatedSelectedIds = List<int>.from(state.selectedIds);
if (updatedSelectedIds.contains(index)) {
updatedSelectedIds.remove(index);
} else {
updatedSelectedIds.add(index);
}
emit(
OperationDetailsListState(
details: state.details,
selectedIds: updatedSelectedIds,
),
);
}
void selectAllOperationDetails() {
final updatedSelectedIds = List<int>.from(state.selectedIds);
for (int i = 0; i < state.details.length; i++) {
if (!updatedSelectedIds.contains(i)) {
updatedSelectedIds.add(i);
}
}
emit(
OperationDetailsListState(
details: state.details,
selectedIds: updatedSelectedIds,
),
);
}
void clearOperationDetailsSelection() {
emit(OperationDetailsListState(details: state.details, selectedIds: []));
}
void deleteSelectedOperationDetails() {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
final updatedSelectedIds = List<int>.from(state.selectedIds);
for (int i = updatedSelectedIds.length - 1; i >= 0; i--) {
final index = updatedSelectedIds[i];
updatedDetails.removeAt(index);
}
emit(
OperationDetailsListState(
details: updatedDetails,
selectedIds: [],
status: OperationDetailsListStatus.updated,
),
);
}
void updateOperationDetail(int index, OperationDetailModel operationDetail) {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails[index] = operationDetail;
emit(
OperationDetailsListState(
details: updatedDetails,
status: OperationDetailsListStatus.updated,
),
);
}
}
@@ -0,0 +1,34 @@
part of 'operation_details_list_cubit.dart';
enum OperationDetailsListStatus { ready, updated, failure }
class OperationDetailsListState extends Equatable {
final List<OperationDetailModel> details;
final String? errorMessage;
final List<int> selectedIds;
final OperationDetailsListStatus status;
const OperationDetailsListState({
this.details = const [],
this.errorMessage,
this.selectedIds = const [],
this.status = OperationDetailsListStatus.ready,
});
OperationDetailsListState copyWith({
List<OperationDetailModel>? details,
String? errorMessage,
List<int>? selectedIds,
OperationDetailsListStatus? status,
}) {
return OperationDetailsListState(
details: details ?? this.details,
errorMessage: errorMessage,
selectedIds: selectedIds ?? this.selectedIds,
status: status ?? this.status,
);
}
@override
List<Object?> get props => [details, errorMessage, selectedIds, status];
}
@@ -2,20 +2,17 @@ import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:get_it/get_it.dart';
import 'package:uuid/uuid.dart';
import 'package:flux/service_locator.dart';
part 'operation_form_state.dart';
class OperationFormCubit extends Cubit<OperationFormState> {
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
final Uuid _uuid = const Uuid();
final OperationsRepository _repository = sl<OperationsRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
OperationFormCubit({
StaffMemberModel? createdBy,
@@ -43,16 +40,20 @@ class OperationFormCubit extends Cubit<OperationFormState> {
state.copyWith(
operation: existingOperation,
status: OperationFormStatus.ready,
isNew: false,
hasUnsavedChanges: false,
),
);
} else if (operationId != null) {
emit(state.copyWith(status: OperationFormStatus.loading));
try {
final operation = await _repository.fetchOperationById(operationId);
final operation = await _repository.getOperationById(operationId);
emit(
state.copyWith(
operation: operation,
status: OperationFormStatus.ready,
isNew: false,
hasUnsavedChanges: false,
),
);
} on Exception catch (e) {
@@ -64,20 +65,22 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
}
} else {
// NUOVA PRATICA: Creiamo un nuovo Batch UUID
// NUOVA PRATICA
final currentStore = _sessionCubit.state.currentStore;
final companyId = _sessionCubit.state.company?.id ?? '';
final newOperation = state.operation.copyWith(
companyId: companyId,
storeId: currentStore?.id,
status: OperationStatus.success,
reference: '',
batchUuid: _uuid.v4(),
final initialStaffDisplayName = state.operation.staffDisplayName;
final newOperation = await _repository.createNewOperation(
currentStore: currentStore!,
createdById: state.operation.staffId!,
);
emit(
state.copyWith(
operation: newOperation,
operation: newOperation.copyWith(
staffDisplayName:
newOperation.staffDisplayName ?? initialStaffDisplayName,
),
status: OperationFormStatus.ready,
isNew: true,
hasUnsavedChanges: true,
),
);
}
@@ -91,35 +94,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
}
}
// --- LOGICA BATCH ---
void _prepareNextOperationInBatch() {
final current = state.operation;
emit(
state.copyWith(
status: OperationFormStatus.ready, // Torna ready per il nuovo form
operation: OperationModel(
companyId: current.companyId,
storeId: current.storeId,
storeDisplayName: current.storeDisplayName,
batchUuid: current.batchUuid, // MANTIENE IL COLLEGAMENTO
customerId: current.customerId, // MANTIENE IL CLIENTE
customer: current.customer,
reference: current.reference,
status: OperationStatus.draft,
createdAt: DateTime.now(),
),
),
);
}
// --- SALVATAGGIO ---
Future<void> saveOperation({
required OperationStatus targetStatus,
required bool keepAdding,
}) async {
Future<void> saveOperation({required OperationStatus targetStatus}) async {
emit(
state.copyWith(status: OperationFormStatus.saving, errorMessage: null),
);
@@ -127,6 +104,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
try {
OperationModel operationToSave = state.operation.copyWith(
status: targetStatus,
showInDashboard: true,
);
if (operationToSave.reference.isEmpty) {
if (operationToSave.customer != null &&
@@ -140,33 +118,15 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
}
}
final savedOperation = await _repository.saveFullOperation(
operation: operationToSave,
await _repository.updateOperation(operationToSave);
emit(
state.copyWith(
status: OperationFormStatus.success,
operation: operationToSave,
isNew: false,
hasUnsavedChanges: false,
),
);
if (keepAdding) {
// Salviamo nella "memoria" del batch le pratiche create finora
final updatedBatchList = List<OperationModel>.from(
state.savedBatchOperations,
)..add(savedOperation);
emit(
state.copyWith(
status: OperationFormStatus.successAndAddAnother,
savedBatchOperations: updatedBatchList,
),
);
// Pulisce i campi per la prossima operazione
_prepareNextOperationInBatch();
} else {
emit(
state.copyWith(
status: OperationFormStatus.success,
operation: savedOperation, // Aggiorniamo con l'ID restituito dal DB
),
);
}
} catch (e) {
emit(
state.copyWith(
@@ -177,95 +137,73 @@ class OperationFormCubit extends Cubit<OperationFormState> {
}
}
Future<String?> saveOperationDraft() async {
// --- ANNULLA E ELIMINA SE NUOVA ---
Future<void> discardAndExit() async {
emit(state.copyWith(status: OperationFormStatus.saving));
try {
final operationToSave = state.operation;
if (operationToSave.customerId == null ||
operationToSave.customerId!.isEmpty) {
throw Exception('Seleziona un cliente prima di poter usare il QR');
if (state.isNew && state.operation.id != null) {
await _repository.deleteOperation(state.operation.id!);
}
final savedOperation = await _repository.saveFullOperation(
operation: operationToSave,
);
emit(
state.copyWith(
operation: savedOperation,
status: OperationFormStatus.ready,
status: OperationFormStatus.discarded,
hasUnsavedChanges: false,
),
);
return savedOperation.id;
} catch (e) {
emit(
state.copyWith(
status: OperationFormStatus.failure,
errorMessage: e.toString(),
errorMessage: "Errore durante l'eliminazione dell'operazione: $e",
),
);
}
}
// --- ELIMINAZIONE DEFINITIVA PRATICA ---
Future<void> deleteCurrentOperation() async {
final id = state.operation.id;
if (id == null || id.isEmpty) return;
emit(state.copyWith(status: OperationFormStatus.saving));
try {
await _repository.deleteOperation(id);
emit(
state.copyWith(
status: OperationFormStatus.discarded,
hasUnsavedChanges: false,
),
);
} catch (e) {
emit(
state.copyWith(
status: OperationFormStatus.failure,
errorMessage: "Errore durante l'eliminazione dell'operazione: $e",
),
);
return null;
}
}
// --- GESTIONE DEI CAMPI IN TEMPO REALE ---
void updateFields({
String? reference,
String? note,
String? type,
String? providerId,
String? providerDisplayName,
String? subtype,
String? description,
DateTime? expirationDate,
int? quantity,
String? modelId,
String? modelDisplayName,
String? staffId,
String? staffDisplayName,
OperationStatus? status,
bool? isBusiness,
bool clearProvider = false,
bool clearType = false,
bool clearSubtype = false,
bool clearDescription = false,
bool clearExpiration = false,
bool clearQuantity = false,
bool clearModel = false,
}) {
final current = state.operation;
int? newQuantity;
if (clearQuantity) newQuantity = 1;
if (quantity != null && quantity <= 0) newQuantity = 0;
if (quantity != null && quantity > 0) newQuantity = quantity;
final updated = current.copyWith(
reference: reference ?? current.reference,
note: note ?? current.note,
providerId: clearProvider ? null : (providerId ?? current.providerId),
providerDisplayName: clearProvider
? null
: (providerDisplayName ?? current.providerDisplayName),
quantity: newQuantity ?? current.quantity,
type: clearType ? null : (type ?? current.type),
description: clearDescription
? null
: (description ?? current.description),
subtype: clearSubtype ? null : (subtype ?? current.subtype),
expirationDate: clearExpiration
? null
: (expirationDate ?? current.expirationDate),
modelId: clearModel ? null : (modelId ?? current.modelId),
modelDisplayName: clearModel
? null
: (modelDisplayName ?? current.modelDisplayName),
staffId: staffId ?? current.staffId,
staffDisplayName: staffDisplayName ?? current.staffDisplayName,
status: status ?? current.status,
isBusiness: isBusiness ?? current.isBusiness,
);
emit(state.copyWith(operation: updated));
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
}
void updateCustomer(CustomerModel customer) {
@@ -275,131 +213,12 @@ class OperationFormCubit extends Cubit<OperationFormState> {
customerId: customer.id,
isBusiness: isBusiness,
);
emit(state.copyWith(operation: updatedOperation));
emit(state.copyWith(operation: updatedOperation, hasUnsavedChanges: true));
}
// --- UTILS ---
void updateOperationType(
String newType, {
required List<ProviderModel> allProviders,
String? defaultProviderId,
}) {
// 1. Aggiorniamo il tipo nel modello in canna
// (Presumo tu abbia un metodo copyWith o simile)
final updatedOp = state.operation.copyWith(type: newType, subtype: '');
// 2. Prepariamoci ad auto-selezionare il provider
String? newProviderId = updatedOp.providerId;
String? newProviderName = updatedOp.providerDisplayName;
// 3. LA LOGICA DI DEFAULT
if (defaultProviderId != null) {
// Troviamo il provider di default nella lista
final defaultProvider = allProviders
.where((p) => p.id == defaultProviderId)
.firstOrNull;
if (defaultProvider != null) {
// Usiamo l'extension appena creata!
if (defaultProvider.supportsOperation(newType)) {
newProviderId = defaultProvider.id;
newProviderName = defaultProvider.name;
} else {
// Se cambi tipo (es. da Mobile a Luce) e il default non lo supporta, sbianchiamo
newProviderId = null;
newProviderName = null;
}
}
}
// Emettiamo il nuovo stato
emit(
state.copyWith(
operation: updatedOp.copyWith(
providerId: newProviderId,
providerDisplayName: newProviderName,
),
),
);
}
void setTypeWithSmartDefaults({
required String newType,
required List<ProviderModel> allProviders,
String? defaultProviderId,
}) {
final currentOp = state.operation;
// -----------------------------------------
// 1. SMART DATES: Calcolo Scadenze Default
// -----------------------------------------
DateTime? defaultDate;
final now = DateTime.now();
if (newType == 'Energy') {
defaultDate = DateTime(now.year, now.month + 24, now.day);
}
if (newType == 'Fin') {
defaultDate = DateTime(now.year, now.month + 30, now.day);
}
if (newType == 'Entertainment') {
defaultDate = DateTime(now.year, now.month + 12, now.day);
}
// -----------------------------------------
// 2. SMART PROVIDER: Filtro e Auto-Selezione
// -----------------------------------------
String? newProviderId = currentOp.providerId;
String? newProviderName = currentOp.providerDisplayName;
// A) Il provider attuale è ancora compatibile col nuovo tipo scelto?
if (newProviderId != null && newProviderId.isNotEmpty) {
final currentProvider = allProviders
.where((p) => p.id == newProviderId)
.firstOrNull;
if (currentProvider == null ||
!currentProvider.supportsOperation(newType)) {
// Non è più compatibile (es. da TIM fisso passo a Energy). Lo sbianchiamo!
newProviderId = null;
newProviderName = null;
}
}
// B) Se non c'è un provider selezionato, proviamo ad auto-inserire quello di default del negozio
if ((newProviderId == null || newProviderId.isEmpty) &&
defaultProviderId != null) {
final defaultProvider = allProviders
.where((p) => p.id == defaultProviderId)
.firstOrNull;
// Controlliamo che il default del negozio supporti questa specifica operazione
if (defaultProvider != null &&
defaultProvider.supportsOperation(newType)) {
newProviderId = defaultProvider.id;
newProviderName = defaultProvider.name;
}
}
// -----------------------------------------
// 3. EMISSIONE DELLO STATO PULITO
// -----------------------------------------
emit(
state.copyWith(
operation: currentOp.copyWith(
type: newType,
subtype:
'', // Resettiamo il sottotipo per evitare incongruenze (es. passo da Luce a DAZN)
expirationDate:
defaultDate, // Impostiamo la scadenza di default se calcolata
providerId: newProviderId,
providerDisplayName: newProviderName,
modelId: null,
modelDisplayName: null,
),
),
);
void updateOperationDetailsList(List<OperationDetailModel> details) {
final current = state.operation;
final updated = current.copyWith(details: details);
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
}
}
@@ -6,35 +6,38 @@ enum OperationFormStatus {
ready,
saving,
success,
successAndAddAnother, // Nuovo stato in stile Ticket!
failure,
discarded,
}
class OperationFormState extends Equatable {
final OperationFormStatus status;
final OperationModel operation;
final String? errorMessage;
// Teniamo traccia delle operazioni salvate in questa sessione (per UI riepilogo)
final List<OperationModel> savedBatchOperations;
final bool isNew;
final bool hasUnsavedChanges;
const OperationFormState({
this.status = OperationFormStatus.initial,
required this.operation,
this.errorMessage,
this.savedBatchOperations = const [],
this.isNew = false,
this.hasUnsavedChanges = false,
});
OperationFormState copyWith({
OperationFormStatus? status,
OperationModel? operation,
String? errorMessage,
List<OperationModel>? savedBatchOperations,
bool? isNew,
bool? hasUnsavedChanges,
}) {
return OperationFormState(
status: status ?? this.status,
operation: operation ?? this.operation,
errorMessage: errorMessage,
savedBatchOperations: savedBatchOperations ?? this.savedBatchOperations,
isNew: isNew ?? this.isNew,
hasUnsavedChanges: hasUnsavedChanges ?? this.hasUnsavedChanges,
);
}
@@ -43,6 +46,7 @@ class OperationFormState extends Equatable {
status,
operation,
errorMessage,
savedBatchOperations,
isNew,
hasUnsavedChanges,
];
}
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -12,72 +14,131 @@ class OperationListCubit extends Cubit<OperationListState> {
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
StreamSubscription<void>? _operationsSubscription;
int _fetchId = 0;
OperationListCubit() : super(const OperationListState()) {
loadOperations(refresh: true);
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
refreshCurrentPage();
});
}
Future<void> loadOperations({bool refresh = false}) async {
if (state.status == OperationListStatus.loading) return;
if (!refresh && state.hasReachedMax) return;
void refreshCurrentPage() {
loadSpecificPageDesktop(state.currentPage);
}
emit(
state.copyWith(
status: OperationListStatus.loading,
errorMessage: null,
operations: refresh ? [] : state.operations,
hasReachedMax: refresh ? false : state.hasReachedMax,
),
);
// 🥷 MOTORE 1: DESKTOP (Sostituisce la lista)
Future<void> loadSpecificPageDesktop(int page) async {
final currentFetchId = ++_fetchId;
emit(state.copyWith(status: OperationListStatus.loading));
try {
final currentOffset = refresh ? 0 : state.operations.length;
final companyId = _sessionCubit.state.company?.id;
if (companyId == null) {
throw Exception("Company ID non trovato nella sessione");
}
final newOperations = await _repository.fetchOperations(
companyId: companyId,
offset: currentOffset,
limit: 50,
searchTerm: state.query,
final paginatedData = await _repository.fetchPaginatedOperations(
companyId: companyId!,
page: page,
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
);
final bool reachedMax = newOperations.length < 50;
if (currentFetchId != _fetchId) return;
emit(
state.copyWith(
status: OperationListStatus.success,
operations: refresh
? newOperations
: [...state.operations, ...newOperations],
hasReachedMax: reachedMax,
operations: paginatedData.operations, // 🎯 SOSTITUISCE I DATI
totalItems: paginatedData.totalCount,
currentPage: page,
hasReachedMax: paginatedData.operations.length < state.itemsPerPage,
),
);
} catch (e) {
if (currentFetchId != _fetchId) return;
emit(
state.copyWith(
status: OperationListStatus.failure,
errorMessage: "Errore nel caricamento operazioni: $e",
errorMessage: e.toString(),
),
);
}
}
void updateFilters({String? query, DateTimeRange? range}) {
// 🥷 MOTORE 2: MOBILE (Accoda alla lista)
Future<void> loadNextPageMobile({bool refresh = false}) async {
if (state.hasReachedMax && !refresh) return;
final currentFetchId = ++_fetchId;
// Se stiamo pullando verso il basso (refresh), ripartiamo da pagina 1
final targetPage = refresh ? 1 : state.currentPage + 1;
// Mostriamo il loading solo se è un refresh totale, altrimenti manteniamo lo stato success
// per non far sparire la UI mentre carica in fondo
if (refresh) emit(state.copyWith(status: OperationListStatus.loading));
try {
final companyId = _sessionCubit.state.company?.id;
final paginatedData = await _repository.fetchPaginatedOperations(
companyId: companyId!,
page: targetPage,
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
);
if (currentFetchId != _fetchId) return;
emit(
state.copyWith(
status: OperationListStatus.success,
// 🎯 ACCODA I DATI SE NON È REFRESH, ALTRIMENTI SOSTITUISCE
operations:
refresh ? paginatedData.operations : List.of(state.operations)
..addAll(paginatedData.operations),
totalItems: paginatedData.totalCount,
currentPage: targetPage,
hasReachedMax: paginatedData.operations.length < state.itemsPerPage,
),
);
} catch (e) {
if (currentFetchId != _fetchId) return;
emit(
state.copyWith(
status: OperationListStatus.failure,
errorMessage: e.toString(),
),
);
}
}
void updateFilters({String? text, DateTimeRange? range}) {
emit(
state.copyWith(
query: query ?? state.query,
dateRange: range ?? state.dateRange,
// 🥷 FORZIAMO IL TIPO: Diciamo a Dart che il risultato del ternario è proprio una funzione
searchTerm: text != null ? () => text : null,
dateRange: range != null ? () => range : null,
currentPage: 1, // Reset obbligatorio alla prima pagina
hasReachedMax: false,
),
);
loadOperations(refresh: true);
// Ricarichiamo la pagina 1 con i nuovi filtri applicati
loadSpecificPageDesktop(1);
}
void clearFilters() {
emit(const OperationListState()); // Resetta tutto allo stato iniziale
loadOperations(refresh: true);
// Invece di un const vuoto che potrebbe bruciarti l'impostazione itemsPerPage,
// creiamo uno stato pulito ma manteniamo la preferenza di paginazione.
emit(OperationListState(itemsPerPage: state.itemsPerPage));
loadSpecificPageDesktop(1);
}
@override
Future<void> close() {
_operationsSubscription?.cancel();
return super.close();
}
}
@@ -5,35 +5,57 @@ enum OperationListStatus { initial, loading, success, failure }
class OperationListState extends Equatable {
final OperationListStatus status;
final List<OperationModel> operations;
final bool hasReachedMax;
final String? errorMessage;
final String query;
// Paginazione Ibrida
final int currentPage;
final int itemsPerPage;
final int totalItems;
final bool hasReachedMax;
// 🥷 I FILTRI MANCANTI (Riparati!)
final String? searchTerm;
final DateTimeRange? dateRange;
const OperationListState({
this.status = OperationListStatus.initial,
this.operations = const [],
this.hasReachedMax = false,
this.errorMessage,
this.query = '',
this.currentPage = 1,
this.itemsPerPage = 25,
this.totalItems = 0,
this.hasReachedMax = false,
this.searchTerm,
this.dateRange,
});
int get totalPages => (totalItems / itemsPerPage).ceil();
// 🥷 COPYWITH AVANZATO: Gestisce lo sbiancamento dei filtri alla perfezione
OperationListState copyWith({
OperationListStatus? status,
List<OperationModel>? operations,
bool? hasReachedMax,
String? errorMessage,
String? query,
DateTimeRange? dateRange,
int? currentPage,
int? itemsPerPage,
int? totalItems,
bool? hasReachedMax,
String? Function()? searchTerm, // Callback per gestire il null esplicito
DateTimeRange? Function()?
dateRange, // Callback per gestire il null esplicito
}) {
return OperationListState(
status: status ?? this.status,
operations: operations ?? this.operations,
errorMessage: errorMessage ?? this.errorMessage,
currentPage: currentPage ?? this.currentPage,
itemsPerPage: itemsPerPage ?? this.itemsPerPage,
totalItems: totalItems ?? this.totalItems,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
errorMessage: errorMessage,
query: query ?? this.query,
dateRange: dateRange ?? this.dateRange,
// Se passi la funzione la eseguiamo, altrimenti teniamo il valore corrente
searchTerm: searchTerm != null ? searchTerm() : this.searchTerm,
dateRange: dateRange != null ? dateRange() : this.dateRange,
);
}
@@ -41,9 +63,12 @@ class OperationListState extends Equatable {
List<Object?> get props => [
status,
operations,
hasReachedMax,
errorMessage,
query,
currentPage,
itemsPerPage,
totalItems,
hasReachedMax,
searchTerm,
dateRange,
];
}
@@ -1,65 +1,91 @@
import 'package:file_picker/file_picker.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:get_it/get_it.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/paginated_operations.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/operation_model.dart';
class OperationsRepository {
final _supabase = Supabase.instance.client;
final companyId = GetIt.I.get<SessionCubit>().state.company!.id;
final SupabaseClient _supabase = sl<SupabaseClient>();
// --- RECUPERO SINGOLO SERVIZIO CON JOIN COMPLETO ---
Future<OperationModel> fetchOperationById(String id) async {
final StreamController<void> _operationsChangedController =
StreamController<void>.broadcast();
Stream<void> get onOperationsChanged => _operationsChangedController.stream;
void notifyOperationsChanged() {
if (!_operationsChangedController.isClosed) {
_operationsChangedController.add(null);
}
}
Future<OperationModel?> getOperationById(String id) async {
try {
final response = await _supabase
.from(Tables.operations)
.select('''
*,
${Tables.customers}(*),
${Tables.stores}(name),
${Tables.staffMembers}(name),
${Tables.providers}(name),
${Tables.models}(name_with_brand),
${Tables.attachments}(*)
''')
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
*,
${Tables.providers}(*),
${Tables.models}(*)
)
''')
.eq('id', id)
.single();
debugPrint('response: $response');
return OperationModel.fromMap(response);
} catch (e) {
throw Exception('Errore nel caricamento del servizio: $e');
} on Exception catch (e) {
debugPrint('response error: $e');
return null;
}
}
// --- RECUPERO PAGINATO CON FILTRI E JOIN ---
Future<List<OperationModel>> fetchOperations({
Future<PaginatedOperations> fetchPaginatedOperations({
required String companyId,
String? storeId,
String? staffId,
String? providerId,
required int offset,
int limit = 50,
required int page,
int itemsPerPage = 20,
String? searchTerm,
DateTimeRange? dateRange,
bool onlyShowInDashboard = false,
}) async {
try {
// Calcoliamo il range di partenza e fine per Supabase
// Es. Pagina 1, 25 items -> range(0, 24)
// Es. Pagina 2, 25 items -> range(25, 49)
final from = (page - 1) * itemsPerPage;
final to = from + itemsPerPage - 1;
var query = _supabase
.from(Tables.operations)
.select('''
*,
${Tables.customers}(*),
${Tables.stores}(name),
${Tables.providers}(name),
${Tables.models}(name_with_brand),
${Tables.staffMembers}(name),
${Tables.attachments}(*)
''')
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
*,
${Tables.providers}(*),
${Tables.models}(*)
)
''')
.eq('company_id', companyId);
if (onlyShowInDashboard) {
query = query.eq('show_in_dashboard', true);
}
// Filtro Range Date
if (dateRange != null) {
query = query
@@ -79,26 +105,54 @@ class OperationsRepository {
query = query.or('provider_id.eq.$providerId,provider_id.is.null');
}
if (searchTerm != null && searchTerm.isNotEmpty) {
// Filtra sui campi della tabella principale O su quelli della tabella joinata
query = query.or(
'reference.ilike.%$searchTerm%,note.ilike.%$searchTerm%,customer.name.ilike.%$searchTerm%',
);
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
try {
final customersRes = await _supabase
.from(Tables.customers)
.select('id')
.eq('company_id', companyId)
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%')
.limit(100);
matchingCustomerIds = (customersRes as List)
.map((c) => c['id'].toString())
.toList();
} catch (_) {}
final List<String> orConditions = [
'reference.ilike.%$cleanTerm%',
'note.ilike.%$cleanTerm%',
'description.ilike.%$cleanTerm%',
];
if (matchingCustomerIds.isNotEmpty) {
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
}
query = query.or(orConditions.join(','));
}
final response = await query
.order('created_at', ascending: false)
.range(offset, offset + limit - 1);
return (response as List)
.range(from, to)
.count(CountOption.exact);
// 3. Estrazione dei dati
final List<OperationModel> operations = (response.data as List)
.map((map) => OperationModel.fromMap(map))
.toList();
final int totalCount = response.count;
return PaginatedOperations(
operations: operations,
totalCount: totalCount,
);
} catch (e) {
throw Exception('$e');
debugPrint('Errore nel recupero della pagina $page: $e');
throw Exception('Errore nel recupero della pagina $page: $e');
}
}
Stream<List<OperationModel>> watchStoreOperations({
Stream<List<Map<String, dynamic>>> watchStoreOperations({
required String storeId,
required int limit,
}) {
@@ -107,221 +161,94 @@ class OperationsRepository {
.stream(primaryKey: ['id'])
.eq('store_id', storeId)
.order('created_at', ascending: false)
.limit(limit)
.map(
(listOfMaps) =>
listOfMaps.map((map) => OperationModel.fromMap(map)).toList(),
);
.limit(limit);
}
// --- SALVATAGGIO COMPLETO (PRIMA PADRE, POI FIGLI) ---
Future<OperationModel> saveFullOperation({
required OperationModel operation,
Future<OperationModel> createNewOperation({
required StoreModel currentStore,
required String createdById,
}) async {
try {
// 1. Salvataggio classico dell'operazione corrente
final response = await _supabase
final res = await _supabase
.from(Tables.operations)
.upsert(operation.toMap())
.select(
'*, ${Tables.providers}(*), ${Tables.models}(*), ${Tables.stores}(*), ${Tables.staffMembers}(*), ${Tables.customers}(*), ${Tables.attachments}(*)',
.insert(
OperationModel.empty()
.copyWith(
storeId: currentStore.id,
staffId: createdById,
companyId: currentStore.companyId,
status: OperationStatus.success,
showInDashboard: false,
)
.toMap(),
)
.select('''
*,
${Tables.staffMembers}(*)
''')
.single();
final savedOperation = OperationModel.fromMap(response);
// 2. ALLINEAMENTO BATCH SEMPRE ATTIVO!
if (operation.batchUuid.isNotEmpty) {
await _supabase
.from(Tables.operations)
.update({'note': operation.note}) // Spalmiamo la nota attuale
.eq(
'batch_uuid',
operation.batchUuid,
); // Su tutte le pratiche di questo scontrino
}
return savedOperation;
} catch (e) {
throw Exception("Errore nel salvataggio dell'operazione: $e");
notifyOperationsChanged();
return OperationModel.fromMap(res);
} on Exception catch (e) {
debugPrint('ERRORE CREAZIONE OPERAZIONE: $e');
throw Exception('Errore nella creazione dell\'operazione: $e');
}
}
// --- ELIMINAZIONE ---
Future<void> deleteOperation(String id) async {
try {
await _supabase.from(Tables.operations).delete().eq('id', id);
notifyOperationsChanged();
} catch (e) {
throw Exception('$e');
debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e');
throw Exception('Errore nella cancellazione dell\'operazione: $e');
}
}
// --- RECUPERO TIPI CONTENUTI PIÙ FREQUENTI PER AUTOCOMPLETE ---
Future<List<String>> fetchTopEntertainmentTypes(String companyId) async {
try {
// Cerchiamo i tipi più frequenti associati ai servizi di questa company
// Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id
final response = await _supabase
.from(Tables.operations)
.select('description')
.eq('company_id', companyId)
.eq('type', 'Entertainment')
.limit(50); // Prendiamo un campione
// Logica rapida per contare le occorrenze e prendere i primi 5
final Map<String, int> counts = {};
for (var item in (response as List)) {
final description = item['description'] as String;
counts[description] = (counts[description] ?? 0) + 1;
}
var sortedKeys = counts.keys.toList()
..sort((a, b) => counts[b]!.compareTo(counts[a]!));
return sortedKeys.take(5).toList();
} catch (e) {
return [
"Netflix",
"DAZN",
"Disney+",
"Sky",
]; // Fallback se non c'è ancora storia
}
}
/// Ascolta in tempo reale i file caricati per una pratica
Stream<List<AttachmentModel>> getOperationFilesStream(String operationId) {
return _supabase
.from(Tables.attachments)
.stream(primaryKey: ['id'])
.eq('operation_id', operationId)
.order('created_at', ascending: false)
.map(
(listOfMaps) =>
listOfMaps.map((map) => AttachmentModel.fromMap(map)).toList(),
);
}
Future<AttachmentModel> uploadAndRegisterOperationFile({
required String operationId,
required PlatformFile pickedFile,
}) async {
final cleanFileName = pickedFile.name.replaceAll(
RegExp(r'[^a-zA-Z0-9\.\-]'),
'_',
);
final storagePath =
'$companyId/operations/$operationId/${DateTime.now().millisecondsSinceEpoch}_$cleanFileName';
final int fileSize = pickedFile.size;
final fileToSave = AttachmentModel(
companyId: GetIt.I.get<SessionCubit>().state.company!.id!,
operationId: operationId,
name: cleanFileName.fileNameWithoutExtension(),
extension: cleanFileName.fileExtension(),
storagePath: storagePath,
fileSize: fileSize,
);
final String mimeType = fileToSave.extension.toLowerCase() == 'pdf'
? 'application/pdf'
: 'image/${fileToSave.extension}';
try {
// Usiamo bytes invece del path per massima compatibilità
if (pickedFile.bytes == null && pickedFile.path == null) {
throw 'Impossibile leggere il contenuto del file';
}
// Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes
if (pickedFile.bytes != null) {
await _supabase.storage
.from('documents')
.uploadBinary(
storagePath,
pickedFile.bytes!,
fileOptions: FileOptions(contentType: mimeType, upsert: true),
);
}
final response = await _supabase
.from(Tables.attachments)
.insert(fileToSave.toMap())
.select()
.single();
return AttachmentModel.fromMap(response);
} catch (e) {
throw 'Errore durante l\'upload: $e';
}
}
Future<void> copyFileToCustomer({
required AttachmentModel file,
required String customerId,
}) async {
await _supabase
.from(Tables.attachments)
.update({'customer_id': customerId})
.eq('id', file.id!);
}
Future<void> renameAttachment(String id, String newName) async {
Future<void> updateOperation(OperationModel operation) async {
try {
await _supabase
.from(Tables.attachments)
.update({'name': newName})
.eq('id', id);
} catch (e) {
throw '$e';
}
}
.from(Tables.operations)
.update(operation.toMap())
.eq('id', operation.id!);
Future<void> deleteSpecificOperationFile(AttachmentModel file) async {
try {
if (file.customerId == null) {
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
await _supabase.storage.from('documents').remove([file.storagePath!]);
} else {
await _supabase
.from(Tables.attachments)
.update({'operation_id': null})
.eq('id', file.id!);
}
} catch (e) {
throw '$e';
}
}
final currentDetailIds =
operation.details
.map((d) => d.id)
.where((id) => id != null && id.isNotEmpty)
.cast<String>()
.toList();
Future<void> deleteOperationFiles(List<AttachmentModel> files) async {
if (files.isEmpty) return;
// 1. Prepariamo le liste di ID e di Percorsi
final List<String> idsToDelete = [];
final List<String> idsToEdit = [];
final List<String> storagePathsToDelete = [];
for (var file in files) {
if (file.customerId == null) {
idsToDelete.add(file.id!);
storagePathsToDelete.add(file.storagePath!);
} else {
idsToEdit.add(file.id!);
}
}
try {
if (idsToDelete.isNotEmpty) {
if (currentDetailIds.isNotEmpty) {
await _supabase
.from(Tables.attachments)
.from(Tables.operationDetails)
.delete()
.inFilter('id', idsToDelete);
await _supabase.storage.from('documents').remove(storagePathsToDelete);
}
if (idsToEdit.isNotEmpty) {
.eq('operation_id', operation.id!)
.not('id', 'in', currentDetailIds);
} else {
await _supabase
.from(Tables.attachments)
.update({'operation_id': null})
.inFilter('id', idsToEdit);
.from(Tables.operationDetails)
.delete()
.eq('operation_id', operation.id!);
}
} on PostgrestException catch (e) {
throw 'Errore database: ${e.message}';
for (OperationDetailModel detail in operation.details) {
final detailToSave = detail.copyWith(
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
}
notifyOperationsChanged();
} catch (e) {
throw 'Errore durante l\'eliminazione dei file: $e';
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
throw Exception('Errore nel salvataggio dell\'operazione: $e');
}
}
}
@@ -0,0 +1,145 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/products/models/model_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
class OperationDetailModel extends Equatable {
final String? id;
final DateTime? createdAt;
final String operationId;
final OperationType? type;
final String? providerId;
final String? modelId;
final String? description;
final DateTime? expirationDate;
final String companyId;
final String? lastCampaignId;
final String? subType;
// Aggiunte comode per relazioni
final ProviderModel? provider;
final ModelModel? model;
const OperationDetailModel({
this.id,
this.createdAt,
this.operationId = '',
this.type,
this.providerId,
this.modelId,
this.description,
this.expirationDate,
this.companyId = '',
this.lastCampaignId,
this.subType,
this.provider,
this.model,
});
@override
List<Object?> get props => [
id,
createdAt,
operationId,
type,
providerId,
modelId,
description,
expirationDate,
companyId,
lastCampaignId,
subType,
provider,
model,
];
OperationDetailModel copyWith({
String? id,
DateTime? createdAt,
String? operationId,
OperationType? type,
String? providerId,
String? modelId,
String? description,
DateTime? expirationDate,
String? companyId,
String? lastCampaignId,
String? subType,
ProviderModel? Function()? provider,
ModelModel? Function()? model,
}) => OperationDetailModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
operationId: operationId ?? this.operationId,
type: type ?? this.type,
providerId: providerId ?? this.providerId,
modelId: modelId ?? this.modelId,
description: description ?? this.description,
expirationDate: expirationDate ?? this.expirationDate,
companyId: companyId ?? this.companyId,
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
subType: subType ?? this.subType,
provider: provider != null ? provider() : this.provider,
model: model != null ? model() : this.model,
);
factory OperationDetailModel.empty() {
return const OperationDetailModel();
}
factory OperationDetailModel.fromMap(Map<String, dynamic> map) {
return OperationDetailModel(
id: map['id'] as String?,
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'])
: null,
operationId: map['operation_id'] as String? ?? '',
type: OperationType.fromValue(map['type'] as String?),
providerId: map['provider_id'] as String?,
modelId: map['model_id'] as String?,
description: map['description'] as String?,
expirationDate: map['expiration_date'] != null
? DateTime.parse(map['expiration_date'])
: null,
companyId: map['company_id'] as String? ?? '',
lastCampaignId: map['last_campaign_id'] as String?,
subType: map['sub_type'] as String?,
provider: (map[Tables.providers] != null)
? ProviderModel.fromMap(map[Tables.providers] as Map<String, dynamic>)
: null,
model: (map[Tables.models] != null)
? ModelModel.fromJson(map[Tables.models] as Map<String, dynamic>)
: null,
);
}
Map<String, dynamic> toMap() {
final String? pId =
(provider?.id != null && provider!.id!.isNotEmpty)
? provider!.id
: (providerId != null && providerId!.isNotEmpty
? providerId
: null);
final String? mId =
(model?.id != null && model!.id!.isNotEmpty)
? model!.id
: (modelId != null && modelId!.isNotEmpty ? modelId : null);
return {
if (id?.isNotEmpty == true) 'id': id,
if (operationId.isNotEmpty) 'operation_id': operationId,
if (type != null) 'type': type!.value,
if (pId?.isNotEmpty == true) 'provider_id': pId,
if (mId?.isNotEmpty == true) 'model_id': mId,
if (description?.isNotEmpty == true) 'description': description,
if (expirationDate != null)
'expiration_date': expirationDate!.toIso8601String(),
if (companyId.isNotEmpty) 'company_id': companyId,
if (lastCampaignId?.isNotEmpty == true)
'last_campaign_id': lastCampaignId,
if (subType?.isNotEmpty == true) 'sub_type': subType,
};
}
}
@@ -3,6 +3,7 @@ import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
enum OperationStatus {
success('success', 'OK'),
@@ -27,24 +28,13 @@ enum OperationStatus {
class OperationModel extends Equatable {
final String? id;
final DateTime? createdAt;
final String type;
final String? subtype;
final String? providerId;
final String? providerDisplayName;
final String? modelId;
final String? modelDisplayName;
final String? description;
final DateTime? expirationDate;
final String note;
final bool showInDashboard;
final String batchUuid;
final String companyId;
final String storeId;
final String? storeDisplayName;
final int quantity;
final String? staffId;
final String? staffDisplayName;
final String? lastCampaignId;
final OperationStatus status;
final String? customerId;
final CustomerModel? customer;
@@ -54,88 +44,61 @@ class OperationModel extends Equatable {
// ALLEGATI (Aggiunto)
final List<AttachmentModel> attachments;
// DETTAGLI OPERAZIONE (Aggiunto)
final List<OperationDetailModel> details;
const OperationModel({
this.id,
this.createdAt,
this.type = '',
this.subtype,
this.providerId,
this.providerDisplayName,
this.modelId,
this.modelDisplayName,
this.description,
this.expirationDate,
this.note = '',
this.showInDashboard = true,
this.batchUuid = '',
required this.companyId,
this.storeId = '',
this.storeDisplayName,
this.quantity = 1,
this.staffId,
this.staffDisplayName,
this.lastCampaignId,
this.status = OperationStatus.draft,
this.status = OperationStatus.success,
this.customerId,
this.customer,
this.reference = '',
this.attachments = const [],
this.details = const [],
this.isBusiness = false,
});
OperationModel copyWith({
String? id,
DateTime? createdAt,
String? type,
String? subtype,
String? providerId,
String? providerDisplayName,
String? modelId,
String? modelDisplayName,
String? description,
DateTime? expirationDate,
String? note,
bool? showInDashboard,
String? batchUuid,
String? companyId,
String? storeId,
String? storeDisplayName,
int? quantity,
String? staffId,
String? staffDisplayName,
String? lastCampaignId,
OperationStatus? status,
String? customerId,
CustomerModel? customer,
String? reference,
List<AttachmentModel>? attachments,
List<OperationDetailModel>? details,
bool? isBusiness,
}) => OperationModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
type: type ?? this.type,
subtype: subtype ?? this.subtype,
providerId: providerId ?? this.providerId,
providerDisplayName: providerDisplayName ?? this.providerDisplayName,
modelId: modelId ?? this.modelId,
modelDisplayName: modelDisplayName ?? this.modelDisplayName,
description: description ?? this.description,
expirationDate: expirationDate ?? this.expirationDate,
note: note ?? this.note,
showInDashboard: showInDashboard ?? this.showInDashboard,
batchUuid: batchUuid ?? this.batchUuid,
companyId: companyId ?? this.companyId,
storeId: storeId ?? this.storeId,
storeDisplayName: storeDisplayName ?? this.storeDisplayName,
quantity: quantity ?? this.quantity,
staffId: staffId ?? this.staffId,
staffDisplayName: staffDisplayName ?? this.staffDisplayName,
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
status: status ?? this.status,
customerId: customerId ?? this.customerId,
customer: customer ?? this.customer,
reference: reference ?? this.reference,
attachments: attachments ?? this.attachments,
details: details ?? this.details,
isBusiness: isBusiness ?? this.isBusiness,
);
@@ -143,34 +106,30 @@ class OperationModel extends Equatable {
List<Object?> get props => [
id,
createdAt,
type,
subtype,
providerId,
providerDisplayName,
modelId,
modelDisplayName,
description,
expirationDate,
note,
showInDashboard,
batchUuid,
companyId,
storeId,
storeDisplayName,
quantity,
staffId,
staffDisplayName,
lastCampaignId,
status,
customerId,
customer,
reference,
attachments,
details,
isBusiness,
];
factory OperationModel.empty() {
return OperationModel(id: null, createdAt: null, companyId: '');
return OperationModel(
id: null,
createdAt: null,
showInDashboard: false,
companyId: '',
details: const [],
);
}
factory OperationModel.fromMap(Map<String, dynamic> map) {
@@ -179,42 +138,17 @@ class OperationModel extends Equatable {
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'])
: null,
type: map['type'] as String? ?? '',
subtype: map['sub_type'] as String?,
// I campi relazionali nullabili restano rigorosamente null!
providerId: map['provider_id'] as String?,
// MAGIA ANTI-CRASH: Usiamo ?['chiave'] per non far esplodere i join vuoti
providerDisplayName: (map[Tables.providers]?['name'] as String?)
?.myFormat(),
modelId: map['model_id'] as String?,
modelDisplayName: (map[Tables.models]?['name_with_brand'] as String?)
?.myFormat(),
description: map['description'] as String?,
expirationDate: map['expiration_date'] != null
? DateTime.parse(map['expiration_date'])
: null,
note: map['note'] as String? ?? '',
showInDashboard: map['show_in_dashboard'] as bool? ?? true,
batchUuid: map['batch_uuid'] as String? ?? '',
companyId: map['company_id'] as String,
storeId:
map['store_id'] as String? ??
'', // Questo è non-nullable nella tua classe
storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(),
quantity: map['quantity'] is int
? map['quantity']
: int.tryParse(map['quantity']?.toString() ?? '1') ?? 1,
staffId: map['staff_id'] as String?,
staffDisplayName: (map[Tables.staffMembers]?['name'] as String?)
?.myFormat(),
lastCampaignId: map['last_campaign_id'] as String?,
status: OperationStatus.fromString(map['status'] ?? 'draft'),
customerId: map['customer_id'] as String?,
@@ -228,6 +162,14 @@ class OperationModel extends Equatable {
.toList() ??
const [],
details:
(map[Tables.operationDetails] as List?)
?.map(
(x) => OperationDetailModel.fromMap(x as Map<String, dynamic>),
)
.toList() ??
const [],
reference: map['reference'] as String? ?? '',
isBusiness: map['is_business'] as bool? ?? false,
);
@@ -236,21 +178,11 @@ class OperationModel extends Equatable {
Map<String, dynamic> toMap() {
return {
if (id != null) 'id': id,
'type': type,
'sub_type': subtype,
'provider_id': providerId,
'model_id': modelId,
'description': description,
if (expirationDate != null)
'expiration_date': expirationDate!.toIso8601String(),
'note': note,
'show_in_dashboard': showInDashboard,
'batch_uuid': batchUuid,
'company_id': companyId,
'store_id': storeId,
'quantity': quantity,
if (staffId != null) 'staff_id': staffId,
if (lastCampaignId != null) 'last_campaign_id': lastCampaignId,
'status': status.supabaseName,
if (customerId != null) 'customer_id': customerId,
'reference': reference,
@@ -0,0 +1,141 @@
import 'package:flutter/material.dart';
/// Enum fortemente tipizzato per i tipi di operazione/servizio nel sistema Flux
enum OperationType {
al(
value: 'AL',
label: 'Attivazione Linea',
shortLabel: 'AL',
icon: Icons.sim_card_outlined,
color: Colors.blue,
),
mnp(
value: 'MNP',
label: 'Portabilità',
shortLabel: 'MNP',
icon: Icons.phone_forwarded_outlined,
color: Colors.indigo,
),
nip(
value: 'NIP',
label: 'Nuovo Impianto',
shortLabel: 'NIP',
icon: Icons.home_repair_service_outlined,
color: Colors.cyan,
),
unica(
value: 'UNICA',
label: 'TIM Unica / Convergenza',
shortLabel: 'UNICA',
icon: Icons.merge_type_outlined,
color: Colors.orange,
),
fwa(
value: 'FWA',
label: 'Fixed Wireless Access',
shortLabel: 'FWA',
icon: Icons.router_outlined,
color: Colors.teal,
),
telepass(
value: 'TELEPASS',
label: 'Telepass',
shortLabel: 'Telepass',
icon: Icons.directions_car_outlined,
color: Colors.amber,
),
energy(
value: 'Energy',
label: 'Energia Luce & Gas',
shortLabel: 'Energy',
icon: Icons.bolt_outlined,
color: Colors.green,
),
fin(
value: 'Fin',
label: 'Finanziamento',
shortLabel: 'Fin',
icon: Icons.credit_card_outlined,
color: Colors.purple,
),
entertainment(
value: 'Entertainment',
label: 'Contenuti & Intrattenimento',
shortLabel: 'Entertainment',
icon: Icons.live_tv_outlined,
color: Colors.redAccent,
),
cb(
value: 'CB',
label: 'Customer Base',
shortLabel: 'CB',
icon: Icons.people_alt_outlined,
color: Colors.deepOrange,
),
upselling(
value: 'Upselling',
label: 'Upselling / Cambio Offerta',
shortLabel: 'Upselling',
icon: Icons.trending_up_outlined,
color: Colors.deepPurple,
),
business(
value: 'Business',
label: 'Servizio Business',
shortLabel: 'Business',
icon: Icons.business_center_outlined,
color: Colors.blueGrey,
),
altro(
value: 'Altro',
label: 'Altro Servizio',
shortLabel: 'Altro',
icon: Icons.more_horiz_outlined,
color: Colors.grey,
);
final String value;
final String label;
final String shortLabel;
final IconData icon;
final Color color;
const OperationType({
required this.value,
required this.label,
required this.shortLabel,
required this.icon,
required this.color,
});
/// Ricostruisce l'enum dal valore stringa salvato su DB in modo case-insensitive
static OperationType? fromValue(String? val) {
if (val == null || val.trim().isEmpty) return null;
final clean = val.trim().toLowerCase();
for (final t in OperationType.values) {
if (t.value.toLowerCase() == clean || t.name.toLowerCase() == clean) {
return t;
}
}
return OperationType.altro;
}
}
/// Sottotipi standard suggeriti per Entertainment
class EntertainmentSubtypes {
static const String calcio = 'Calcio';
static const String cinemaTv = 'Cinema & TV';
static const String musica = 'Musica';
static const String altro = 'Altro';
static const List<String> all = [calcio, cinemaTv, musica, altro];
}
/// Sottotipi standard per Energy
class EnergySubtypes {
static const String luce = 'Luce';
static const String gas = 'Gas';
static const String dual = 'Luce e Gas';
static const List<String> all = [luce, gas, dual];
}
@@ -0,0 +1,25 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/operations/models/operation_model.dart';
class PaginatedOperations extends Equatable {
final List<OperationModel> operations;
final int totalCount;
const PaginatedOperations({
required this.operations,
required this.totalCount,
});
@override
List<Object?> get props => [operations, totalCount];
PaginatedOperations copyWith({
List<OperationModel>? operations,
int? totalCount,
}) {
return PaginatedOperations(
operations: operations ?? this.operations,
totalCount: totalCount ?? this.totalCount,
);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,12 +1,14 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:go_router/go_router.dart';
// Importa i tuoi modelli e cubit
class OperationListScreen extends StatefulWidget {
const OperationListScreen({super.key});
@@ -17,17 +19,40 @@ class OperationListScreen extends StatefulWidget {
class _OperationListScreenState extends State<OperationListScreen> {
final ScrollController _scrollController = ScrollController();
final TextEditingController _searchController = TextEditingController();
Timer? _debounce;
// Set per gestire le Bulk Actions (Selezione multipla)
final Set<String> _selectedOperationIds = {};
bool get _isSelectionMode => _selectedOperationIds.isNotEmpty;
// Flag per mostrare/nascondere la barra di ricerca integrata nell'AppBar
bool _showSearchBar = false;
@override
void initState() {
super.initState();
// Agganciamo il listener per la paginazione (Scroll Infinito)
_scrollController.addListener(_onScroll);
// Primo caricamento: partiamo da pagina 1
// (Il Cubit deciderà se fare il boot iniziale o se c'era già roba in cache)
WidgetsBinding.instance.addPostFrameCallback((_) {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
if (isDesktop) {
context.read<OperationListCubit>().loadSpecificPageDesktop(1);
} else {
context.read<OperationListCubit>().loadNextPageMobile(refresh: true);
}
});
}
void _onScroll() {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
// 🥷 COMPORTAMENTO IBRIDO: Lo scroll infinito si attiva SOLO su mobile
if (isDesktop) return;
if (_isBottom) {
context.read<OperationListCubit>().loadOperations();
context.read<OperationListCubit>().loadNextPageMobile();
}
}
@@ -35,66 +60,178 @@ class _OperationListScreenState extends State<OperationListScreen> {
if (!_scrollController.hasClients) return false;
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.offset;
// Carica quando mancano 200px alla fine
return currentScroll >= (maxScroll * 0.9);
}
void _onSearchChanged(String text) {
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 400), () {
if (!mounted) return;
context.read<OperationListCubit>().updateFilters(
text: text,
);
});
}
@override
void dispose() {
_debounce?.cancel();
_scrollController.dispose();
_searchController.dispose();
super.dispose();
}
void _toggleSelection(String id) {
setState(() {
if (_selectedOperationIds.contains(id)) {
_selectedOperationIds.remove(id);
} else {
_selectedOperationIds.add(id);
}
});
}
void _clearSelection() {
setState(() {
_selectedOperationIds.clear();
});
}
@override
Widget build(BuildContext context) {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
return Scaffold(
appBar: AppBar(
title: const Text("Gestione Servizi"),
elevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.search),
onPressed: () {
// Qui potrai implementare una barra di ricerca
},
),
],
),
// --- APP BAR DINAMICA E INTEGRATA ---
appBar: _isSelectionMode
? AppBar(
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: _clearSelection,
),
title: Text("${_selectedOperationIds.length} selezionate"),
actions: [
IconButton(
icon: const Icon(Icons.edit_note),
tooltip: 'Cambia Stato Massivo',
onPressed: () {
// TODO: Integrare bottom sheet per azioni massive
},
),
],
)
: AppBar(
title: _showSearchBar
? TextField(
controller: _searchController,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Cerca per cliente, nota o riferimento...',
border: InputBorder.none,
),
style: const TextStyle(fontSize: 16),
onChanged: _onSearchChanged,
)
: const Text("Gestione Servizi"),
elevation: 0,
actions: [
IconButton(
icon: Icon(_showSearchBar ? Icons.close : Icons.search),
onPressed: () {
setState(() {
_showSearchBar = !_showSearchBar;
if (!_showSearchBar) {
_debounce?.cancel();
_searchController.clear();
context.read<OperationListCubit>().clearFilters();
}
});
},
),
if (!isDesktop) // Il pull-to-refresh c'è già su mobile, su desktop mettiamo un tasto manuale
IconButton(
icon: const Icon(Icons.filter_list),
onPressed: () {
// TODO: Bottone Filtri Avanzati (es. DateRange Picker)
},
),
],
),
// --- CORPO RESPONSIVO ---
body: BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
// 1. Stato di caricamento iniziale
if (state.status == OperationListStatus.loading &&
state.operations.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
// 2. Lista vuota
if (state.operations.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Nessuna pratica trovata."),
const SizedBox(height: 10),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () => context
.read<OperationListCubit>()
.loadOperations(refresh: true),
child: const Text("Riprova"),
onPressed: () => isDesktop
? context
.read<OperationListCubit>()
.loadSpecificPageDesktop(1)
: context.read<OperationListCubit>().loadNextPageMobile(
refresh: true,
),
child: const Text("Ricarica"),
),
],
),
);
}
// 3. La Lista (con Pull-to-refresh)
// 🥷 SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
if (isDesktop) {
return Column(
children: [
Expanded(
child: GridView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
420, // Larghezza bilanciata per le card su desktop
mainAxisExtent:
185, // Altezza controllata per evitare buchi bianchi
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: state.operations.length,
itemBuilder: (context, index) {
final operation = state.operations[index];
return _buildResponsiveCard(operation);
},
),
),
_buildDesktopPaginationFooter(
state,
), // La barra in fondo stile Gmail
],
);
}
// 🥷 SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
return RefreshIndicator(
onRefresh: () => context.read<OperationListCubit>().loadOperations(
refresh: true,
),
onRefresh: () => context
.read<OperationListCubit>()
.loadNextPageMobile(refresh: true),
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.only(bottom: 80), // Spazio per il FAB
padding: const EdgeInsets.only(
bottom: 80,
left: 8,
right: 8,
top: 8,
),
itemCount: state.hasReachedMax
? state.operations.length
: state.operations.length + 1,
@@ -109,98 +246,451 @@ class _OperationListScreenState extends State<OperationListScreen> {
}
final operation = state.operations[index];
return _buildOperationCard(context, operation);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: _buildResponsiveCard(operation),
);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.operationForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, operation: null),
);
},
child: const Icon(Icons.add),
),
floatingActionButton: _isSelectionMode
? null
: FloatingActionButton(
onPressed: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.operationForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, operation: null),
);
},
child: const Icon(Icons.add),
),
);
}
Widget _buildOperationCard(BuildContext context, OperationModel operation) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: ListTile(
contentPadding: const EdgeInsets.all(12),
title: Row(
children: [
Expanded(
// --- COSTRUZIONE DELLA COMPONENTISTICA DETTAGLIATA ---
Widget _buildResponsiveCard(OperationModel operation) {
final isSelected = _selectedOperationIds.contains(operation.id);
return _RichOperationCard(
operation: operation,
isSelected: isSelected,
isSelectionMode: _isSelectionMode,
onTap: () {
if (_isSelectionMode) {
_toggleSelection(operation.id!);
} else {
context.pushNamed(
Routes.operationForm,
extra: (createdBy: null, operation: operation),
pathParameters: {'id': operation.id!},
);
}
},
onLongPress: () => _toggleSelection(operation.id!),
);
}
// 🥷 LA BARRA DI PAGINAZIONE DESKTOP (Stile Gmail / Typesense)
Widget _buildDesktopPaginationFooter(OperationListState state) {
final theme = Theme.of(context);
final cubit = context.read<OperationListCubit>();
// Calcolo intervallo visualizzato (es. 1-25 di 140)
final fromItem = ((state.currentPage - 1) * state.itemsPerPage) + 1;
final toItem =
DateUtils.isSameDay(DateTime.now(), DateTime.now()) // segnaposto logico
? (fromItem + state.operations.length - 1)
: fromItem;
return Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 24),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Info totali a sinistra
Text(
"$fromItem-$toItem di ${state.totalItems} pratiche totali",
style: theme.textTheme.bodyMedium?.copyWith(
color: Colors.grey[700],
),
),
// Controlli di navigazione a destra
Row(
children: [
// Prima Pagina
IconButton(
icon: const Icon(Icons.first_page),
onPressed: state.currentPage > 1
? () => cubit.loadSpecificPageDesktop(1)
: null,
),
// Pagina Precedente
IconButton(
icon: const Icon(Icons.chevron_left),
onPressed: state.currentPage > 1
? () => cubit.loadSpecificPageDesktop(state.currentPage - 1)
: null,
),
// Indicatore numerico centrale impacchettato
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
"Pagina ${state.currentPage} di ${state.totalPages}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
// Pagina Successiva
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: state.currentPage < state.totalPages
? () => cubit.loadSpecificPageDesktop(state.currentPage + 1)
: null,
),
// Ultima Pagina
IconButton(
icon: const Icon(Icons.last_page),
onPressed: state.currentPage < state.totalPages
? () => cubit.loadSpecificPageDesktop(state.totalPages)
: null,
),
],
),
],
),
);
}
}
// =========================================================================
// 🥷 3. LA CARD RICCA, REATTIVA E DEFINITIVA (Quella revisionata insieme)
// =========================================================================
class _RichOperationCard extends StatelessWidget {
final OperationModel operation;
final bool isSelected;
final bool isSelectionMode;
final VoidCallback onTap;
final VoidCallback onLongPress;
const _RichOperationCard({
required this.operation,
required this.isSelected,
required this.isSelectionMode,
required this.onTap,
required this.onLongPress,
});
Color _getStatusColor(OperationStatus status) {
switch (status) {
case OperationStatus.success:
return Colors.green;
case OperationStatus.waitingForAction:
case OperationStatus.draft:
return Colors.orange;
case OperationStatus.waitingForSupport:
return Colors.blue;
case OperationStatus.failure:
return Colors.grey.shade800;
}
}
Color _getTypeColor(OperationType? type) {
return type?.color ?? Colors.blueGrey;
}
IconData? _getIconForType(OperationType? type, String? subtype) {
if (type == OperationType.energy) {
if (subtype?.toLowerCase() == 'luce') return Icons.bolt;
if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department;
}
if (type == OperationType.entertainment) {
if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer;
}
return type?.icon;
}
Widget _buildDetailItem(BuildContext context, OperationDetailModel detail) {
final typeColor = _getTypeColor(detail.type);
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
final icon = _getIconForType(detail.type, detail.subType);
final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty)
? '${detail.type?.shortLabel ?? ''} (${detail.subType})'
: (detail.type?.shortLabel ?? 'Dettaglio');
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: typeColor.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: typeColor.withValues(alpha: 0.25),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon, size: 12, color: typeColor),
const SizedBox(width: 4),
],
Text(
typeLabel,
style: TextStyle(
color: typeColor,
fontWeight: FontWeight.bold,
fontSize: 11,
),
),
if (detail.provider?.name != null && detail.provider!.name.isNotEmpty) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
decoration: BoxDecoration(
color: providerColor.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(4),
),
child: Text(
operation.customer?.name ?? "Cliente sconosciuto",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
detail.provider!.name,
style: TextStyle(
color: providerColor,
fontWeight: FontWeight.w600,
fontSize: 10,
),
),
),
],
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
if (detail.model?.name != null && detail.model!.name.isNotEmpty) ...[
const SizedBox(width: 4),
Text(
"Pratica: ${operation.reference} • ${operation.createdAt?.day}/${operation.createdAt?.month}/${operation.createdAt?.year}",
),
const SizedBox(height: 8),
Row(
children: [
Text(operation.type),
const SizedBox(width: 8),
_buildOperationStatus(operation.status),
],
'• ${detail.model!.name}',
style: TextStyle(
color: Colors.grey[700],
fontSize: 10,
),
),
],
),
trailing: const Icon(Icons.chevron_right),
onTap: () => context.pushNamed(
Routes.operationForm,
extra: (createdBy: null, operation: operation),
pathParameters: {'id': operation.id!},
),
],
),
);
}
Widget _buildOperationStatus(OperationStatus status) {
Color color;
switch (status) {
case OperationStatus.failure:
color = Colors.grey.shade800;
break;
case OperationStatus.waitingForAction || OperationStatus.draft:
color = Colors.orange;
break;
case OperationStatus.success:
color = Colors.green;
break;
case OperationStatus.waitingForSupport:
color = Colors.blue;
break;
}
return Chip(
label: Text("BOZZA", style: TextStyle(fontSize: 10, color: Colors.white)),
backgroundColor: color,
visualDensity: VisualDensity.compact,
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final statusColor = _getStatusColor(operation.status);
return Card(
margin: EdgeInsets.zero, // Gestito dai margini dei padri (griglia/lista)
elevation: isSelected ? 4 : 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(
color: isSelected ? theme.colorScheme.primary : Colors.transparent,
width: 2,
),
),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: onTap,
onLongPress: onLongPress,
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Container(
decoration: BoxDecoration(
color: isSelected
? theme.colorScheme.primaryContainer.withValues(alpha: 0.15)
: null,
// 🥷 COERENZA 100%: Banda laterale legata allo status per eliminare i malintesi cromatici
border: Border(left: BorderSide(color: statusColor, width: 6)),
),
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// --- RIGA 1: RIFERIMENTO E DATA ---
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (isSelectionMode)
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: SizedBox(
height: 18,
width: 18,
child: Checkbox(
value: isSelected,
onChanged: (_) => onTap(),
),
),
),
Expanded(
child: Text(
(operation.reference.isEmpty)
? 'Senza Riferimento'
: operation.reference,
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[600],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
operation.createdAt != null
? "${operation.createdAt!.day.toString().padLeft(2, '0')}/${operation.createdAt!.month.toString().padLeft(2, '0')}/${operation.createdAt!.year}"
: '',
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[600],
),
),
],
),
const SizedBox(height: 8),
// --- RIGA 2: NOME CLIENTE E CHIP PRIVATO / BUSINESS ---
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
operation.customer?.name ?? "Cliente sconosciuto",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
_MiniChip(
label: operation.isBusiness ? 'Business' : 'Privato',
icon: operation.isBusiness
? Icons.business
: Icons.person,
color: operation.isBusiness ? Colors.indigo : Colors.teal,
),
],
),
const SizedBox(height: 8),
// --- RIGA 3: LISTA DEI VARI DETTAGLI (TIPO E PROVIDER) ---
if (operation.details.isEmpty)
Text(
'Nessun dettaglio',
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[500],
fontStyle: FontStyle.italic,
),
)
else
Wrap(
spacing: 6,
runSpacing: 4,
children: operation.details
.map((detail) => _buildDetailItem(context, detail))
.toList(),
),
const Spacer(),
// --- RIGA 4: NOME ADDETTO E STATO ---
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const Icon(
Icons.support_agent,
size: 14,
color: Colors.grey,
),
const SizedBox(width: 4),
Text(
operation.staffDisplayName ?? 'Assegnato',
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[700],
),
),
],
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: statusColor,
borderRadius: BorderRadius.circular(6),
),
child: Text(
operation.status.displayName,
style: const TextStyle(
fontSize: 10,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
),
),
),
);
}
}
void startNewOperation(BuildContext context) {
context.pushNamed('operation-form', pathParameters: {'id': 'new'});
// Micro Widget di supporto per i tag interni
class _MiniChip extends StatelessWidget {
final String label;
final IconData? icon;
final Color color;
const _MiniChip({required this.label, this.icon, required this.color});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
border: Border.all(color: color.withValues(alpha: 0.25)),
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon, size: 11, color: color),
const SizedBox(width: 4),
],
Text(
label,
style: TextStyle(
fontSize: 10,
color: color,
fontWeight: FontWeight.bold,
),
),
],
),
);
}
}
@@ -1,267 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/widgets/shared_forms/model_section.dart';
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
class OperationDetailsSection extends StatelessWidget {
final OperationModel? currentOp;
final String currentType;
final TextEditingController freeTextSubtypeController;
final TextEditingController freeTextDescriptionController;
final Widget durationQuickPicks;
const OperationDetailsSection({
super.key,
required this.currentOp,
required this.currentType,
required this.freeTextSubtypeController,
required this.freeTextDescriptionController,
required this.durationQuickPicks,
});
void _showProviderModal(BuildContext context, String operationType) {
final OperationFormCubit cubit = context.read<OperationFormCubit>();
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (modalContext) {
return DraggableScrollableSheet(
initialChildSize: 0.5,
minChildSize: 0.4,
maxChildSize: 0.8,
expand: false,
builder: (_, scrollController) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Seleziona Gestore',
style: Theme.of(context).textTheme.titleLarge,
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(modalContext),
),
],
),
),
const Divider(),
Expanded(
child: BlocBuilder<ProviderListCubit, ProviderListState>(
builder: (context, state) {
if (state.status == ProviderListStatus.loading) {
return const Center(child: CircularProgressIndicator());
}
// 🥷 IL TOCCO DEL NINJA: Filtriamo usando direttamente l'Extension sul Modello!
final filteredProviders = state.providers.where((p) {
return p.supportsOperation(operationType) && p.isActive;
}).toList();
if (filteredProviders.isEmpty) {
return const Center(
child: Text(
'Nessun gestore compatibile con questo servizio.',
style: TextStyle(color: Colors.grey),
),
);
}
return BlocProvider.value(
value: cubit,
child: ListView.builder(
controller: scrollController,
itemCount: filteredProviders.length,
itemBuilder: (context, index) {
final provider = filteredProviders[index];
return ListTile(
leading: const Icon(Icons.business),
title: Text(
provider.name,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
// Facoltativo: mostra i ruoli sotto al nome
subtitle: Text(
provider.roles
.map((r) => r.displayValue)
.join(', '),
style: const TextStyle(fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
onTap: () {
context.read<OperationFormCubit>().updateFields(
providerId: provider.id,
providerDisplayName: provider.name,
);
Navigator.pop(modalContext);
},
);
},
),
);
},
),
),
],
);
},
);
},
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// PROVIDER (Mostrato quasi sempre)
ListTile(
title: const Text('Seleziona Gestore'),
subtitle: Text(
(currentOp?.providerDisplayName != null &&
currentOp!.providerDisplayName!.isNotEmpty)
? currentOp!.providerDisplayName!
: 'Nessun gestore selezionato',
style: TextStyle(
color:
(currentOp?.providerId == null ||
currentOp!.providerId!.isEmpty)
? Colors.grey
: null,
fontWeight:
(currentOp?.providerId == null ||
currentOp!.providerId!.isEmpty)
? FontWeight.normal
: FontWeight.bold,
),
),
trailing: const Icon(Icons.arrow_drop_down),
shape: RoundedRectangleBorder(
side: BorderSide(color: theme.dividerColor),
borderRadius: BorderRadius.circular(8),
),
onTap: () => _showProviderModal(context, currentType),
),
const SizedBox(height: 16),
// 1. SCENARIO ENERGY (Dropdown Fisso)
if (currentType == 'Energy') ...[
DropdownButtonFormField<String>(
initialValue:
(currentOp?.subtype != null && currentOp!.subtype!.isNotEmpty)
? currentOp!.subtype
: null,
decoration: const InputDecoration(labelText: 'Dettaglio Fornitura'),
items: [
'Luce',
'Gas',
].map((s) => DropdownMenuItem(value: s, child: Text(s))).toList(),
onChanged: (val) {
if (val != null) {
context.read<OperationFormCubit>().updateFields(subtype: val);
}
},
),
const SizedBox(height: 16),
TextFormField(
controller: freeTextDescriptionController,
decoration: InputDecoration(
labelText: currentType == 'Energy'
? 'Offerta scelta'
: 'Nome del servizio/offerta',
),
),
const SizedBox(height: 16),
],
// 2. SCENARIO FIN (Ricerca Modello/Prodotto)
if (currentType == 'Fin') ...[
SharedModelSection(
label: 'Seleziona Dispositivo/Prodotto',
modelId: currentOp?.modelId,
modelName: currentOp?.modelDisplayName,
onModelSelected: (id, name) {
context.read<OperationFormCubit>().updateFields(
modelId: id,
modelDisplayName: name,
);
},
),
const SizedBox(height: 16),
],
// 3. SCENARIO ENTERTAINMENT O CUSTOM (Testo libero)
if (currentType == 'Entertainment' || currentType == 'Altro') ...[
TextFormField(
controller: freeTextSubtypeController,
decoration: InputDecoration(
labelText: currentType == 'Entertainment'
? 'Piattaforma (es. Netflix, DAZN, Spotify...)'
: 'Specifica il servizio (es. Monopattino)',
),
),
const SizedBox(height: 16),
],
// SCADENZA (Reattivo per tipi complessi)
if ([
'Energy',
'Fin',
'Entertainment',
'Altro',
].contains(currentType)) ...[
const SizedBox(height: 8),
durationQuickPicks, // Passiamo i chips dall'esterno
const SizedBox(height: 16),
ListTile(
title: const Text('Data di Scadenza Effettiva'),
subtitle: Text(
currentOp?.expirationDate != null
? "${currentOp!.expirationDate!.day}/${currentOp!.expirationDate!.month}/${currentOp!.expirationDate!.year}"
: 'Nessuna scadenza impostata',
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
trailing: const Icon(Icons.calendar_month, color: Colors.blue),
tileColor: Colors.blue.withValues(alpha: 0.05),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: Colors.blue, width: 0.5),
),
onTap: () async {
final date = await showDatePicker(
context: context,
initialDate:
currentOp?.expirationDate ??
DateTime.now().add(const Duration(days: 365)),
firstDate: DateTime.now(),
lastDate: DateTime.now().add(const Duration(days: 3650)),
);
if (date != null && context.mounted) {
context.read<OperationFormCubit>().updateFields(
expirationDate: date,
);
}
},
),
const SizedBox(height: 16),
],
],
);
}
}
@@ -0,0 +1,808 @@
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/widgets/shared_forms/model_section.dart';
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
import 'package:flux/features/operations/blocs/operation_details_form_cubit.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
class OperationDetailsSection extends StatelessWidget {
const OperationDetailsSection({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return BlocBuilder<OperationDetailsListCubit, OperationDetailsListState>(
builder: (context, listState) {
final details = listState.details;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Dettagli Servizi (${details.length})',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
ElevatedButton.icon(
onPressed: () => _openDetailFormModal(context),
icon: const Icon(Icons.add, size: 18),
label: const Text('Aggiungi Dettaglio'),
),
],
),
const SizedBox(height: 12),
if (details.isEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.all(24.0),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(
alpha: 0.3,
),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: theme.dividerColor.withValues(alpha: 0.5),
),
),
child: Column(
children: [
Icon(
Icons.playlist_add,
size: 40,
color: Colors.grey.shade400,
),
const SizedBox(height: 8),
Text(
'Nessun dettaglio aggiunto',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.grey.shade700,
),
),
const SizedBox(height: 4),
Text(
'Premi "+ Aggiungi Dettaglio" per inserire un servizio per questa pratica.',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
),
textAlign: TextAlign.center,
),
],
),
)
else
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: details.length,
separatorBuilder: (_, _) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final detail = details[index];
return _buildDetailTile(context, detail, index);
},
),
],
);
},
);
}
Widget _buildDetailTile(
BuildContext context,
OperationDetailModel detail,
int index,
) {
final typeColor = _getTypeColor(detail.type);
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
final typeLabel = detail.type?.shortLabel ?? 'Dettaglio';
final typeText =
(detail.subType != null && detail.subType!.isNotEmpty)
? '$typeLabel (${detail.subType})'
: typeLabel;
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(color: typeColor.withValues(alpha: 0.3)),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: typeColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
_getIconForType(detail.type, detail.subType),
color: typeColor,
size: 20,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
typeText,
style: TextStyle(
fontWeight: FontWeight.bold,
color: typeColor,
fontSize: 14,
),
),
if (detail.provider?.name != null &&
detail.provider!.name.isNotEmpty) ...[
const SizedBox(width: 8),
Chip(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
label: Text(
detail.provider!.name,
style: TextStyle(
color: providerColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
backgroundColor: providerColor.withValues(
alpha: 0.15,
),
side: BorderSide(
color: providerColor.withValues(alpha: 0.3),
),
),
],
],
),
if (detail.model?.name != null &&
detail.model!.name.isNotEmpty) ...[
const SizedBox(height: 4),
Row(
children: [
const Icon(Icons.devices, size: 14, color: Colors.grey),
const SizedBox(width: 4),
Text(
detail.model!.name,
style: const TextStyle(fontSize: 12),
),
],
),
],
if (detail.description != null &&
detail.description!.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
detail.description!,
style: TextStyle(fontSize: 12, color: Colors.grey[700]),
),
],
if (detail.expirationDate != null) ...[
const SizedBox(height: 4),
Row(
children: [
const Icon(
Icons.calendar_month,
size: 14,
color: Colors.blue,
),
const SizedBox(width: 4),
Text(
'Scadenza: ${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}',
style: const TextStyle(
fontSize: 11,
color: Colors.blue,
),
),
],
),
],
],
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit, size: 18),
onPressed:
() => _openDetailFormModal(
context,
existingDetail: detail,
index: index,
),
),
IconButton(
icon: const Icon(
Icons.delete_outline,
size: 18,
color: Colors.red,
),
onPressed: () {
context
.read<OperationDetailsListCubit>()
.deleteOperationDetail(index);
},
),
],
),
],
),
),
);
}
void _openDetailFormModal(
BuildContext context, {
OperationDetailModel? existingDetail,
int? index,
}) {
final listCubit = context.read<OperationDetailsListCubit>();
final allProviders = context.read<ProviderListCubit>().state.providers;
final defaultProviderId =
context.read<SessionCubit>().state.currentStore?.defaultProviderId;
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (sheetContext) {
return BlocProvider(
create:
(_) => OperationDetailsFormCubit(
initialDetail: existingDetail,
editingIndex: index,
allProviders: allProviders,
defaultProviderId: defaultProviderId,
),
child: _OperationDetailFormSheet(listCubit: listCubit),
);
},
);
}
Color _getTypeColor(OperationType? type) {
return type?.color ?? Colors.blueGrey;
}
IconData _getIconForType(OperationType? type, String? subtype) {
if (type == OperationType.energy) {
if (subtype?.toLowerCase() == 'luce') return Icons.bolt;
if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department;
}
if (type == OperationType.entertainment) {
if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer;
}
return type?.icon ?? Icons.build;
}
}
class _OperationDetailFormSheet extends StatefulWidget {
final OperationDetailsListCubit listCubit;
const _OperationDetailFormSheet({required this.listCubit});
@override
State<_OperationDetailFormSheet> createState() =>
_OperationDetailFormSheetState();
}
class _OperationDetailFormSheetState
extends State<_OperationDetailFormSheet> {
late TextEditingController _subtypeController;
late TextEditingController _descriptionController;
@override
void initState() {
super.initState();
final initialDetail =
context.read<OperationDetailsFormCubit>().state.operationDetail;
_subtypeController = TextEditingController(
text: initialDetail.subType ?? '',
);
_descriptionController = TextEditingController(
text: initialDetail.description ?? '',
);
}
@override
void dispose() {
_subtypeController.dispose();
_descriptionController.dispose();
super.dispose();
}
void _showProviderModal(BuildContext context, OperationType? operationType) {
final formCubit = context.read<OperationDetailsFormCubit>();
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (modalContext) {
return DraggableScrollableSheet(
initialChildSize: 0.5,
minChildSize: 0.4,
maxChildSize: 0.8,
expand: false,
builder: (_, scrollController) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Seleziona Gestore',
style: Theme.of(context).textTheme.titleLarge,
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(modalContext),
),
],
),
),
const Divider(),
Expanded(
child: BlocBuilder<ProviderListCubit, ProviderListState>(
builder: (context, state) {
if (state.status == ProviderListStatus.loading) {
return const Center(child: CircularProgressIndicator());
}
final filteredProviders =
state.providers.where((p) {
return p.supportsOperationType(operationType) &&
p.isActive;
}).toList();
if (filteredProviders.isEmpty) {
return const Center(
child: Text(
'Nessun gestore compatibile con questo servizio.',
style: TextStyle(color: Colors.grey),
),
);
}
return ListView.builder(
controller: scrollController,
itemCount: filteredProviders.length,
itemBuilder: (context, index) {
final provider = filteredProviders[index];
return ListTile(
leading: const Icon(Icons.business),
title: Text(
provider.name,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
provider.roles
.map((r) => r.displayValue)
.join(', '),
style: const TextStyle(fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
onTap: () {
formCubit.setProvider(provider);
Navigator.pop(modalContext);
},
);
},
);
},
),
),
],
);
},
);
},
);
}
Widget _buildDurationQuickPicks(BuildContext context) {
final durations = [3, 6, 12, 24, 30, 36, 48];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Imposta durata rapida (mesi):",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Colors.grey,
),
),
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children:
durations.map((months) {
return Padding(
padding: const EdgeInsets.only(right: 8.0),
child: ActionChip(
label: Text("$months m"),
backgroundColor: Colors.blue.withValues(alpha: 0.05),
onPressed: () {
final now = DateTime.now();
context
.read<OperationDetailsFormCubit>()
.updateFields(
expirationDate: DateTime(
now.year,
now.month + months,
now.day,
),
);
},
),
);
}).toList(),
),
),
],
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return DraggableScrollableSheet(
initialChildSize: 0.75,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (_, scrollController) {
return BlocBuilder<
OperationDetailsFormCubit,
OperationDetailsFormState
>(
builder: (context, formState) {
final detail = formState.operationDetail;
final currentType = detail.type ?? OperationType.al;
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Column(
children: [
// Header Bottom Sheet
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
formState.isEditing
? 'Modifica Dettaglio Servizio'
: 'Nuovo Dettaglio Servizio',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(height: 1),
Expanded(
child: ListView(
controller: scrollController,
padding: const EdgeInsets.all(16.0),
children: [
// 1. Tipo Servizio (Wrap di Chips)
const Text(
'Tipo Servizio',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children:
OperationType.values.map((type) {
return ChoiceChip(
avatar: Icon(type.icon, size: 16),
label: Text(type.shortLabel),
selected: currentType == type,
onSelected: (selected) {
if (selected) {
final allProviders =
context
.read<ProviderListCubit>()
.state
.providers;
final defaultProviderId =
context
.read<SessionCubit>()
.state
.currentStore
?.defaultProviderId;
context
.read<OperationDetailsFormCubit>()
.setTypeWithSmartDefaults(
newType: type,
allProviders: allProviders,
defaultProviderId:
defaultProviderId,
);
}
},
);
}).toList(),
),
const SizedBox(height: 16),
// 2. Seleziona Gestore
ListTile(
title: const Text('Seleziona Gestore'),
subtitle: Text(
(detail.provider != null)
? detail.provider!.name
: 'Nessun gestore selezionato',
style: TextStyle(
color:
(detail.provider == null ||
detail.provider!.name.isEmpty)
? Colors.grey
: null,
fontWeight:
(detail.provider == null ||
detail.provider!.name.isEmpty)
? FontWeight.normal
: FontWeight.bold,
),
),
trailing: const Icon(Icons.arrow_drop_down),
shape: RoundedRectangleBorder(
side: BorderSide(color: theme.dividerColor),
borderRadius: BorderRadius.circular(8),
),
onTap: () => _showProviderModal(context, currentType),
),
const SizedBox(height: 16),
// 3. Scenario Energy (Dropdown Fisso)
if (currentType == OperationType.energy) ...[
DropdownButtonFormField<String>(
initialValue:
(detail.subType != null &&
detail.subType!.isNotEmpty)
? detail.subType
: EnergySubtypes.luce,
decoration: const InputDecoration(
labelText: 'Dettaglio Fornitura',
),
items:
EnergySubtypes.all
.map(
(s) => DropdownMenuItem(
value: s,
child: Text(s),
),
)
.toList(),
onChanged: (val) {
if (val != null) {
context
.read<OperationDetailsFormCubit>()
.updateFields(subType: val);
}
},
),
const SizedBox(height: 16),
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: 'Offerta scelta',
),
onChanged: (val) {
context
.read<OperationDetailsFormCubit>()
.updateFields(description: val);
},
),
const SizedBox(height: 16),
],
// 4. Scenario Fin (Ricerca Modello/Prodotto)
if (currentType == OperationType.fin) ...[
SharedModelSection(
label: 'Seleziona Dispositivo/Prodotto',
modelId: detail.modelId,
modelName: detail.model?.nameWithBrand,
onModelSelected: (id, name) {
context
.read<OperationDetailsFormCubit>()
.updateFields(modelId: id);
},
),
const SizedBox(height: 16),
],
// 5. Scenario Entertainment (Chip veloci per Calcio/DAZN, Cinema, Musica + Campo testo)
if (currentType == OperationType.entertainment) ...[
const Text(
'Categoria Contenuto / Piattaforma',
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13),
),
const SizedBox(height: 8),
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: EntertainmentSubtypes.all.map((sub) {
final isSelected = detail.subType?.toLowerCase() == sub.toLowerCase();
return ChoiceChip(
avatar: sub == EntertainmentSubtypes.calcio
? const Icon(Icons.sports_soccer, size: 16)
: (sub == EntertainmentSubtypes.cinemaTv
? const Icon(Icons.movie_outlined, size: 16)
: (sub == EntertainmentSubtypes.musica
? const Icon(Icons.music_note_outlined, size: 16)
: null)),
label: Text(sub),
selected: isSelected,
onSelected: (selected) {
final newVal = selected ? sub : null;
_subtypeController.text = newVal ?? '';
context.read<OperationDetailsFormCubit>().updateFields(subType: newVal);
},
);
}).toList(),
),
const SizedBox(height: 12),
TextFormField(
controller: _subtypeController,
decoration: const InputDecoration(
labelText: 'Specifica Piattaforma / Offerta (opzionale)',
hintText: 'Es. DAZN, TIMVISION Calcio, Netflix, Spotify...',
),
onChanged: (val) {
context.read<OperationDetailsFormCubit>().updateFields(subType: val);
},
),
const SizedBox(height: 16),
],
// Scenario Altro (Testo libero)
if (currentType == OperationType.altro) ...[
TextFormField(
controller: _subtypeController,
decoration: const InputDecoration(
labelText: 'Specifica il servizio (es. Monopattino)',
),
onChanged: (val) {
context
.read<OperationDetailsFormCubit>()
.updateFields(subType: val);
},
),
const SizedBox(height: 16),
],
// 6. Scadenza (Reattiva per tipi complessi)
if ([
OperationType.energy,
OperationType.fin,
OperationType.entertainment,
OperationType.altro,
].contains(currentType)) ...[
_buildDurationQuickPicks(context),
const SizedBox(height: 16),
ListTile(
title: const Text('Data di Scadenza Effettiva'),
subtitle: Text(
detail.expirationDate != null
? "${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}"
: 'Nessuna scadenza impostata',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
trailing: const Icon(
Icons.calendar_month,
color: Colors.blue,
),
tileColor: Colors.blue.withValues(alpha: 0.05),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(
color: Colors.blue,
width: 0.5,
),
),
onTap: () async {
final date = await showDatePicker(
context: context,
initialDate:
detail.expirationDate ??
DateTime.now().add(
const Duration(days: 365),
),
firstDate: DateTime.now(),
lastDate: DateTime.now().add(
const Duration(days: 3650),
),
);
if (date != null && context.mounted) {
context
.read<OperationDetailsFormCubit>()
.updateFields(expirationDate: date);
}
},
),
const SizedBox(height: 16),
],
// Pulsante di conferma
ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(48),
),
onPressed: () {
final finalDetail = formState.operationDetail;
if (formState.isEditing) {
widget.listCubit.updateOperationDetail(
formState.editingIndex!,
finalDetail,
);
} else {
widget.listCubit.addOperationDetail(finalDetail);
}
Navigator.pop(context);
},
child: Text(
formState.isEditing
? 'Salva Modifiche'
: 'Aggiungi Dettaglio',
),
),
],
),
),
],
),
);
},
);
},
);
}
}
@@ -0,0 +1,75 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/targets/blocs/target_detail_state.dart';
import 'package:flux/features/targets/data/target_progress_service.dart';
import 'package:flux/features/targets/data/targets_repository.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/service_locator.dart';
class TargetDetailCubit extends Cubit<TargetDetailState> {
final TargetProgressService _progressService;
final TargetsRepository _targetsRepository;
final OperationsRepository _operationsRepository;
StreamSubscription<void>? _targetsSub;
StreamSubscription<void>? _operationsSub;
TargetDetailCubit({
required TargetModel target,
TargetProgressService? progressService,
TargetsRepository? targetsRepository,
OperationsRepository? operationsRepository,
}) : _progressService = progressService ?? sl<TargetProgressService>(),
_targetsRepository = targetsRepository ?? sl<TargetsRepository>(),
_operationsRepository = operationsRepository ?? sl<OperationsRepository>(),
super(
TargetDetailState(
target: target,
status: TargetDetailStatus.initial,
),
) {
_targetsSub = _targetsRepository.onTargetsChanged.listen((_) {
refresh();
});
_operationsSub = _operationsRepository.onOperationsChanged.listen((_) {
refresh();
});
}
@override
Future<void> close() {
_targetsSub?.cancel();
_operationsSub?.cancel();
return super.close();
}
Future<void> init() async {
emit(state.copyWith(status: TargetDetailStatus.loading));
await refresh();
}
Future<void> refresh() async {
try {
final progress = await _progressService.calculateTargetProgress(
target: state.target,
);
emit(
state.copyWith(
progress: progress,
status: TargetDetailStatus.ready,
),
);
} catch (e) {
emit(
state.copyWith(
status: TargetDetailStatus.failure,
errorMessage: 'Errore durante il calcolo dell\'avanzamento: $e',
),
);
}
}
void setActiveTab(int index) {
emit(state.copyWith(activeTab: index));
}
}
@@ -0,0 +1,46 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
enum TargetDetailStatus { initial, loading, ready, failure }
class TargetDetailState extends Equatable {
final TargetDetailStatus status;
final TargetModel target;
final TargetProgressModel? progress;
final int activeTab;
final String? errorMessage;
const TargetDetailState({
this.status = TargetDetailStatus.initial,
required this.target,
this.progress,
this.activeTab = 0,
this.errorMessage,
});
TargetDetailState copyWith({
TargetDetailStatus? status,
TargetModel? target,
TargetProgressModel? progress,
int? activeTab,
String? errorMessage,
}) {
return TargetDetailState(
status: status ?? this.status,
target: target ?? this.target,
progress: progress ?? this.progress,
activeTab: activeTab ?? this.activeTab,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [
status,
target,
progress,
activeTab,
errorMessage,
];
}
@@ -0,0 +1,350 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/targets/blocs/target_form_state.dart';
import 'package:flux/features/targets/data/targets_repository.dart';
import 'package:flux/features/targets/models/individual_target_model.dart';
import 'package:flux/features/targets/models/target_metrics.dart';
import 'package:flux/features/targets/models/target_model.dart';
class TargetFormCubit extends Cubit<TargetFormState> {
final TargetsRepository _targetsRepository;
final StaffRepository _staffRepository;
final StaffCubit _staffCubit;
TargetFormCubit({
required TargetsRepository targetsRepository,
required StaffRepository staffRepository,
required StaffCubit staffCubit,
}) : _targetsRepository = targetsRepository,
_staffRepository = staffRepository,
_staffCubit = staffCubit,
super(
TargetFormState(
target: TargetModel.empty(),
status: TargetFormStatus.initial,
),
);
Future<void> init({
TargetModel? initialTarget,
required String companyId,
required String defaultStoreId,
}) async {
emit(state.copyWith(status: TargetFormStatus.loading));
try {
final now = DateTime.now();
final defaultStart = DateTime(now.year, now.month, 1);
final defaultEnd = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
final isEditing = initialTarget != null;
final target =
initialTarget ??
TargetModel(
companyId: companyId,
storeId: defaultStoreId,
startDay: defaultStart,
endDay: defaultEnd,
metrics: const TargetMetrics(),
);
final storeId = target.storeId ?? defaultStoreId;
final storeStaff = await _loadStoreStaff(companyId, storeId);
// Costruisci o allinea individualTargets per ogni membro dello staff
final List<IndividualTargetModel> individuals = [];
for (final staff in storeStaff) {
if (staff.id == null) continue;
final existing = target.individualTargets.firstWhere(
(it) => it.staffId == staff.id,
orElse:
() => IndividualTargetModel(
companyId: companyId,
targetId: target.id ?? '',
staffId: staff.id!,
staff: staff,
metrics: const TargetMetrics(),
),
);
individuals.add(
existing.copyWith(staff: staff, companyId: companyId),
);
}
emit(
state.copyWith(
target: target,
individualTargets: individuals,
storeStaff: storeStaff,
isEditing: isEditing,
status: TargetFormStatus.ready,
),
);
} catch (e) {
debugPrint('Errore init TargetFormCubit: $e');
emit(
state.copyWith(
status: TargetFormStatus.failure,
errorMessage: 'Errore nel caricamento della form: $e',
),
);
}
}
Future<List<StaffMemberModel>> _loadStoreStaff(
String companyId,
String storeId,
) async {
try {
// 1. Assicuriamoci che StaffCubit abbia caricato i dati di base
if (_staffCubit.state.allStaff.isEmpty &&
_staffCubit.state.status != StaffStatus.loading) {
await _staffCubit.loadAllStaff();
}
// 2. Chiediamo a StaffCubit di caricare lo staff per questo specifico negozio
if (storeId.isNotEmpty) {
await _staffCubit.loadStaffForStore(storeId);
}
// 3. Verifichiamo se StaffCubit ha addetti per questo negozio
List<StaffMemberModel> staff =
storeId.isNotEmpty ? (_staffCubit.state.staffByStore[storeId] ?? []) : [];
// 4. Se la lista è vuota, proviamo la query diretta sulla tabella di giunzione
if (staff.isEmpty && storeId.isNotEmpty) {
staff = await _staffRepository.getStaffMembersInStore(storeId);
}
// 5. Se trovati addetti assegnati al negozio, ritorniamo quelli attivi
final activeStoreStaff = staff.where((s) => s.isActive).toList();
if (activeStoreStaff.isNotEmpty) {
return activeStoreStaff;
}
// 6. Fallback: controlliamo se in allStaff di StaffCubit qualcuno ha questo store associato
final matchedInAllStaff = _staffCubit.state.allStaff.where((s) {
return s.isActive &&
(s.assignedStoreIds.contains(storeId) ||
s.assignedStores.any((st) => st.id == storeId));
}).toList();
if (matchedInAllStaff.isNotEmpty) {
return matchedInAllStaff;
}
// 7. Se non c'è ancora alcuna assegnazione specifica (es. singolo store aziendale),
// usiamo tutti gli addetti attivi presenti in StaffCubit
final allCompanyStaff = _staffCubit.state.allStaff.where((s) => s.isActive).toList();
if (allCompanyStaff.isNotEmpty) {
return allCompanyStaff;
}
// 8. Fallback estremo: query al repository
final repoStaff = await _staffRepository.getStaffMembers(companyId);
return repoStaff.where((s) => s.isActive).toList();
} catch (e) {
debugPrint('Errore nel recupero dello staff per store $storeId: $e');
return _staffCubit.state.allStaff.where((s) => s.isActive).toList();
}
}
Future<void> setStore(String storeId) async {
if (state.target.storeId == storeId) return;
emit(state.copyWith(status: TargetFormStatus.loading));
try {
final updatedTarget = state.target.copyWith(storeId: storeId);
final storeStaff = await _loadStoreStaff(
state.target.companyId,
storeId,
);
final List<IndividualTargetModel> individuals = [];
for (final staff in storeStaff) {
if (staff.id == null) continue;
individuals.add(
IndividualTargetModel(
companyId: state.target.companyId,
targetId: state.target.id ?? '',
staffId: staff.id!,
staff: staff,
metrics: const TargetMetrics(),
),
);
}
emit(
state.copyWith(
target: updatedTarget,
storeStaff: storeStaff,
individualTargets: individuals,
status: TargetFormStatus.ready,
),
);
} catch (e) {
emit(
state.copyWith(
status: TargetFormStatus.ready,
errorMessage: 'Errore nel caricamento dello staff del negozio',
),
);
}
}
void setDateRange(DateTime start, DateTime end) {
emit(
state.copyWith(
target: state.target.copyWith(startDay: start, endDay: end),
),
);
}
void setDescription(String description) {
emit(
state.copyWith(
target: state.target.copyWith(description: description),
),
);
}
void updateStoreMetrics(TargetMetrics metrics) {
emit(
state.copyWith(
target: state.target.copyWith(metrics: metrics),
),
);
}
void updateIndividualMetrics(String staffId, TargetMetrics metrics) {
final updated =
state.individualTargets.map((it) {
if (it.staffId == staffId) {
return it.copyWith(metrics: metrics);
}
return it;
}).toList();
emit(state.copyWith(individualTargets: updated));
}
/// Distribuisce le metriche del target di negozio tra gli addetti specificati tramite mappa dei pesi.
/// [staffWeights] mappa staffId -> peso (es. 1.0 per full-time, 0.5 per part-time).
/// Gli addetti con peso <= 0 o esclusi vengono azzerati.
void distributeMetrics({
required Map<String, double> staffWeights,
}) {
final activeEntries = staffWeights.entries.where((e) => e.value > 0).toList();
if (activeEntries.isEmpty) return;
final totalWeight = activeEntries.fold<double>(0.0, (sum, e) => sum + e.value);
if (totalWeight <= 0) return;
final m = state.target.metrics;
final updated = state.individualTargets.map((it) {
final weight = staffWeights[it.staffId] ?? 0.0;
if (weight <= 0) {
return it.copyWith(metrics: const TargetMetrics());
}
final ratio = weight / totalWeight;
int calc(int val) => (val * ratio).floor();
final distributedMetrics = TargetMetrics(
mnp1: calc(m.mnp1),
mnp2: calc(m.mnp2),
unica1: calc(m.unica1),
unica2: calc(m.unica2),
nip1: calc(m.nip1),
nip2: calc(m.nip2),
business1: calc(m.business1),
business2: calc(m.business2),
contenuti1: calc(m.contenuti1),
contenuti2: calc(m.contenuti2),
calcio1: calc(m.calcio1),
calcio2: calc(m.calcio2),
fin1: calc(m.fin1),
fin2: calc(m.fin2),
upselling1: calc(m.upselling1),
upselling2: calc(m.upselling2),
cb1: calc(m.cb1),
cb2: calc(m.cb2),
al1: calc(m.al1),
al2: calc(m.al2),
telepass1: calc(m.telepass1),
telepass2: calc(m.telepass2),
energiaTim1: calc(m.energiaTim1),
energiaTim2: calc(m.energiaTim2),
energiaAltri1: calc(m.energiaAltri1),
energiaAltri2: calc(m.energiaAltri2),
);
return it.copyWith(metrics: distributedMetrics);
}).toList();
emit(state.copyWith(individualTargets: updated));
}
/// Distribuisce equamente le metriche del target di negozio tra tutti gli addetti
void distributeMetricsEqually() {
final weights = {
for (final it in state.individualTargets) it.staffId: 1.0,
};
distributeMetrics(staffWeights: weights);
}
void setActiveTab(int tab) {
emit(state.copyWith(activeTab: tab));
}
Future<bool> save() async {
if (state.target.storeId == null || state.target.storeId!.isEmpty) {
emit(
state.copyWith(
errorMessage: 'Seleziona un negozio per questo target',
),
);
return false;
}
emit(state.copyWith(status: TargetFormStatus.saving));
try {
// 1. Salva il target di negozio
final savedStoreTarget = await _targetsRepository.saveStoreTarget(
state.target,
);
// 2. Prepara e salva gli individualTargets collegati a savedStoreTarget.id
if (savedStoreTarget.id != null && state.individualTargets.isNotEmpty) {
final toSave =
state.individualTargets.map((it) {
return it.copyWith(
targetId: savedStoreTarget.id!,
companyId: savedStoreTarget.companyId,
);
}).toList();
await _targetsRepository.saveIndividualTargets(toSave);
}
emit(
state.copyWith(
target: savedStoreTarget,
status: TargetFormStatus.success,
),
);
return true;
} catch (e) {
debugPrint('Errore salvataggio target: $e');
emit(
state.copyWith(
status: TargetFormStatus.failure,
errorMessage: 'Errore durante il salvataggio: $e',
),
);
return false;
}
}
}
@@ -0,0 +1,64 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/targets/models/individual_target_model.dart';
import 'package:flux/features/targets/models/target_model.dart';
enum TargetFormStatus {
initial,
loading,
ready,
saving,
success,
failure,
}
class TargetFormState extends Equatable {
final TargetModel target;
final List<IndividualTargetModel> individualTargets;
final List<StaffMemberModel> storeStaff;
final TargetFormStatus status;
final String? errorMessage;
final bool isEditing;
final int activeTab; // 0: Obiettivi Negozio, 1: Quote Addetti
const TargetFormState({
required this.target,
this.individualTargets = const [],
this.storeStaff = const [],
this.status = TargetFormStatus.initial,
this.errorMessage,
this.isEditing = false,
this.activeTab = 0,
});
TargetFormState copyWith({
TargetModel? target,
List<IndividualTargetModel>? individualTargets,
List<StaffMemberModel>? storeStaff,
TargetFormStatus? status,
String? errorMessage,
bool? isEditing,
int? activeTab,
}) {
return TargetFormState(
target: target ?? this.target,
individualTargets: individualTargets ?? this.individualTargets,
storeStaff: storeStaff ?? this.storeStaff,
status: status ?? this.status,
errorMessage: errorMessage,
isEditing: isEditing ?? this.isEditing,
activeTab: activeTab ?? this.activeTab,
);
}
@override
List<Object?> get props => [
target,
individualTargets,
storeStaff,
status,
errorMessage,
isEditing,
activeTab,
];
}
@@ -0,0 +1,129 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/targets/data/target_progress_service.dart';
import 'package:flux/features/targets/data/targets_repository.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
import 'package:flux/service_locator.dart';
part 'target_list_state.dart';
class TargetListCubit extends Cubit<TargetListState> {
final TargetsRepository _repository = sl<TargetsRepository>();
final OperationsRepository _operationsRepository = sl<OperationsRepository>();
final TargetProgressService _progressService = sl<TargetProgressService>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
StreamSubscription<void>? _targetsSub;
StreamSubscription<void>? _operationsSub;
TargetListCubit() : super(const TargetListState()) {
_targetsSub = _repository.onTargetsChanged.listen((_) {
loadTargets();
});
_operationsSub = _operationsRepository.onOperationsChanged.listen((_) {
loadTargets();
});
}
@override
Future<void> close() {
_targetsSub?.cancel();
_operationsSub?.cancel();
return super.close();
}
Future<void> loadTargets({String? storeId, DateTime? month}) async {
final companyId = _sessionCubit.state.company?.id;
if (companyId == null) {
emit(
state.copyWith(
status: TargetListStatus.failure,
errorMessage: 'Nessuna azienda associata alla sessione',
),
);
return;
}
emit(state.copyWith(status: TargetListStatus.loading));
final effectiveStoreId = storeId ?? state.selectedStoreId;
final effectiveMonth = month ?? state.selectedMonth;
DateTime? fromDate;
DateTime? toDate;
if (effectiveMonth != null) {
fromDate = DateTime(effectiveMonth.year, effectiveMonth.month, 1);
toDate = DateTime(
effectiveMonth.year,
effectiveMonth.month + 1,
0,
23,
59,
59,
);
}
try {
final targets = await _repository.getStoreTargets(
companyId: companyId,
storeId: effectiveStoreId,
fromDate: fromDate,
toDate: toDate,
);
// Calcolo progressi e ritmi per ciascun target trovato
final progressMap = <String, TargetProgressModel>{};
for (final target in targets) {
if (target.id != null) {
final progress = await _progressService.calculateTargetProgress(
target: target,
);
progressMap[target.id!] = progress;
}
}
emit(
state.copyWith(
status: TargetListStatus.success,
targets: targets,
progressMap: progressMap,
selectedStoreId: () => effectiveStoreId,
selectedMonth: () => effectiveMonth,
),
);
} catch (e) {
emit(
state.copyWith(
status: TargetListStatus.failure,
errorMessage: e.toString(),
),
);
}
}
void filterByStore(String? storeId) {
loadTargets(storeId: storeId);
}
void filterByMonth(DateTime? month) {
loadTargets(month: month);
}
Future<bool> deleteTarget(String id) async {
try {
await _repository.deleteStoreTarget(id);
return true;
} catch (e) {
emit(
state.copyWith(
status: TargetListStatus.failure,
errorMessage: "Errore durante l'eliminazione del target: $e",
),
);
return false;
}
}
}
@@ -0,0 +1,51 @@
part of 'target_list_cubit.dart';
enum TargetListStatus { initial, loading, success, failure }
class TargetListState extends Equatable {
final TargetListStatus status;
final List<TargetModel> targets;
final Map<String, TargetProgressModel> progressMap;
final String? selectedStoreId;
final DateTime? selectedMonth;
final String? errorMessage;
const TargetListState({
this.status = TargetListStatus.initial,
this.targets = const [],
this.progressMap = const {},
this.selectedStoreId,
this.selectedMonth,
this.errorMessage,
});
TargetListState copyWith({
TargetListStatus? status,
List<TargetModel>? targets,
Map<String, TargetProgressModel>? progressMap,
String? Function()? selectedStoreId,
DateTime? Function()? selectedMonth,
String? errorMessage,
}) {
return TargetListState(
status: status ?? this.status,
targets: targets ?? this.targets,
progressMap: progressMap ?? this.progressMap,
selectedStoreId:
selectedStoreId != null ? selectedStoreId() : this.selectedStoreId,
selectedMonth:
selectedMonth != null ? selectedMonth() : this.selectedMonth,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [
status,
targets,
progressMap,
selectedStoreId,
selectedMonth,
errorMessage,
];
}
@@ -0,0 +1,331 @@
import 'package:flutter/foundation.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/utils/working_days_helper.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/targets/models/target_metrics.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class TargetProgressService {
final SupabaseClient _supabase;
TargetProgressService({SupabaseClient? supabase})
: _supabase = supabase ?? sl<SupabaseClient>();
static const List<({String key, String label})> metricDefinitions = [
(key: 'mnp', label: 'MNP'),
(key: 'unica', label: 'TIM Unica'),
(key: 'nip', label: 'NIP'),
(key: 'business', label: 'Business'),
(key: 'contenuti', label: 'Contenuti'),
(key: 'calcio', label: 'Calcio'),
(key: 'fin', label: 'Finanziamenti'),
(key: 'upselling', label: 'Upselling'),
(key: 'cb', label: 'Customer Base'),
(key: 'al', label: 'Attivazioni Linea'),
(key: 'telepass', label: 'Telepass'),
(key: 'energiaTim', label: 'Energia TIM'),
(key: 'energiaAltri', label: 'Energia Non TIM'),
];
/// Calcola l'avanzamento completo per un target (di negozio e per ciascun addetto)
Future<TargetProgressModel> calculateTargetProgress({
required TargetModel target,
DateTime? now,
}) async {
final effectiveNow = now ?? DateTime.now();
// 1. Calcolo giorni lavorativi con esclusione di domeniche e festivi
final days = WorkingDaysHelper.calculateWorkingDaysPeriod(
start: target.startDay,
end: target.endDay,
now: effectiveNow,
);
// 2. Query su operations nel periodo target per lo store
final storeCounts = <String, int>{};
final staffCounts = <String, Map<String, int>>{};
// Inizializza contatori
for (final def in metricDefinitions) {
storeCounts[def.key] = 0;
}
try {
final storeId = target.storeId;
if (storeId != null && storeId.isNotEmpty) {
final response = await _supabase
.from(Tables.operations)
.select('''
id,
store_id,
staff_id,
created_at,
status,
is_business,
${Tables.operationDetails}(
type,
sub_type,
provider_id,
${Tables.providers}(name)
)
''')
.eq('company_id', target.companyId)
.eq('store_id', storeId)
.neq('status', 'failure')
.gte('created_at', target.startDay.toIso8601String())
.lte('created_at', target.endDay.toIso8601String());
final operations = response as List<dynamic>;
for (final op in operations) {
final staffId = op['staff_id'] as String?;
final isBusinessOp = op['is_business'] as bool? ?? false;
final details = op[Tables.operationDetails] as List<dynamic>? ?? [];
if (staffId != null && !staffCounts.containsKey(staffId)) {
staffCounts[staffId] = {
for (final def in metricDefinitions) def.key: 0,
};
}
for (final d in details) {
final typeStr = d['type'] as String?;
final opType = OperationType.fromValue(typeStr);
final subType = (d['sub_type'] as String?)?.trim().toLowerCase();
final providerMap = d[Tables.providers] as Map<String, dynamic>?;
final providerName = (providerMap?['name'] as String?)?.toLowerCase() ?? '';
final categoryKey = _mapDetailToCategory(
opType: opType,
subType: subType,
providerName: providerName,
isBusinessOp: isBusinessOp,
);
if (categoryKey != null && storeCounts.containsKey(categoryKey)) {
storeCounts[categoryKey] = (storeCounts[categoryKey] ?? 0) + 1;
if (staffId != null && staffCounts.containsKey(staffId)) {
staffCounts[staffId]![categoryKey] =
(staffCounts[staffId]![categoryKey] ?? 0) + 1;
}
}
}
}
}
} catch (e) {
debugPrint('Errore nel caricamento delle operazioni per il target: $e');
}
// 3. Costruzione CategoryProgress per il negozio
final storeCategories = <String, CategoryProgress>{};
for (final def in metricDefinitions) {
final actual = storeCounts[def.key] ?? 0;
final targets = _extractTargetS1S2(target.metrics, def.key);
storeCategories[def.key] = CategoryProgress.calculate(
key: def.key,
label: def.label,
actual: actual,
s1: targets.s1,
s2: targets.s2,
elapsedDays: days.elapsed,
remainingDays: days.remaining,
totalDays: days.total,
);
}
// 4. Costruzione avanzamento per singoli addetti
final staffProgressMap = <String, TargetProgressModel>{};
final individualTargetsList = target.individualTargets;
final bool hasExplicitIndividualTargets = individualTargetsList.any(
(it) => it.metrics.totalLevel1 > 0 || it.metrics.totalLevel2 > 0,
);
final int staffCount = individualTargetsList.isNotEmpty
? individualTargetsList.length
: (staffCounts.isNotEmpty ? staffCounts.length : 1);
for (final it in individualTargetsList) {
final sId = it.staffId;
final sCounts = staffCounts[sId] ?? {};
final sCategories = <String, CategoryProgress>{};
for (final def in metricDefinitions) {
final actual = sCounts[def.key] ?? 0;
({int s1, int s2}) targets;
if (hasExplicitIndividualTargets) {
targets = _extractTargetS1S2(it.metrics, def.key);
} else {
// Se non sono stati assegnati target individuali, dividi equamente il target del negozio
final storeTargets = _extractTargetS1S2(target.metrics, def.key);
targets = (
s1: staffCount > 0
? (storeTargets.s1 / staffCount).round()
: storeTargets.s1,
s2: staffCount > 0
? (storeTargets.s2 / staffCount).round()
: storeTargets.s2,
);
}
sCategories[def.key] = CategoryProgress.calculate(
key: def.key,
label: def.label,
actual: actual,
s1: targets.s1,
s2: targets.s2,
elapsedDays: days.elapsed,
remainingDays: days.remaining,
totalDays: days.total,
);
}
staffProgressMap[sId] = TargetProgressModel(
targetId: target.id ?? '',
storeId: target.storeId,
staffId: sId,
staffName: it.staff?.name,
totalWorkingDays: days.total,
elapsedWorkingDays: days.elapsed,
remainingWorkingDays: days.remaining,
categories: sCategories,
);
}
// Se ci sono addetti con operazioni che non compaiono in individualTargets, creiamo la loro scheda
for (final sId in staffCounts.keys) {
if (!staffProgressMap.containsKey(sId)) {
final sCounts = staffCounts[sId] ?? {};
final sCategories = <String, CategoryProgress>{};
for (final def in metricDefinitions) {
final actual = sCounts[def.key] ?? 0;
final storeTargets = _extractTargetS1S2(target.metrics, def.key);
final targets = (
s1: staffCount > 0
? (storeTargets.s1 / staffCount).round()
: storeTargets.s1,
s2: staffCount > 0
? (storeTargets.s2 / staffCount).round()
: storeTargets.s2,
);
sCategories[def.key] = CategoryProgress.calculate(
key: def.key,
label: def.label,
actual: actual,
s1: targets.s1,
s2: targets.s2,
elapsedDays: days.elapsed,
remainingDays: days.remaining,
totalDays: days.total,
);
}
staffProgressMap[sId] = TargetProgressModel(
targetId: target.id ?? '',
storeId: target.storeId,
staffId: sId,
totalWorkingDays: days.total,
elapsedWorkingDays: days.elapsed,
remainingWorkingDays: days.remaining,
categories: sCategories,
);
}
}
return TargetProgressModel(
targetId: target.id ?? '',
storeId: target.storeId,
totalWorkingDays: days.total,
elapsedWorkingDays: days.elapsed,
remainingWorkingDays: days.remaining,
categories: storeCategories,
staffProgress: staffProgressMap,
);
}
/// Mappa un dettaglio operazione alla chiave di metrica target corrispondente
String? _mapDetailToCategory({
required OperationType? opType,
required String? subType,
required String providerName,
required bool isBusinessOp,
}) {
if (opType == null) return null;
if (opType == OperationType.business || isBusinessOp) {
return 'business';
}
switch (opType) {
case OperationType.mnp:
return 'mnp';
case OperationType.unica:
return 'unica';
case OperationType.nip:
return 'nip';
case OperationType.entertainment:
if (subType == 'calcio') {
return 'calcio';
}
return 'contenuti';
case OperationType.fin:
return 'fin';
case OperationType.upselling:
return 'upselling';
case OperationType.cb:
return 'cb';
case OperationType.al:
return 'al';
case OperationType.telepass:
return 'telepass';
case OperationType.energy:
if (providerName.contains('tim')) {
return 'energiaTim';
}
return 'energiaAltri';
default:
return null;
}
}
/// Estrae i valori di Soglia 1 e Soglia 2 per la specifica categoria da TargetMetrics
({int s1, int s2}) _extractTargetS1S2(TargetMetrics m, String key) {
switch (key) {
case 'mnp':
return (s1: m.mnp1, s2: m.mnp2);
case 'unica':
return (s1: m.unica1, s2: m.unica2);
case 'nip':
return (s1: m.nip1, s2: m.nip2);
case 'business':
return (s1: m.business1, s2: m.business2);
case 'contenuti':
return (s1: m.contenuti1, s2: m.contenuti2);
case 'calcio':
return (s1: m.calcio1, s2: m.calcio2);
case 'fin':
return (s1: m.fin1, s2: m.fin2);
case 'upselling':
return (s1: m.upselling1, s2: m.upselling2);
case 'cb':
return (s1: m.cb1, s2: m.cb2);
case 'al':
return (s1: m.al1, s2: m.al2);
case 'telepass':
return (s1: m.telepass1, s2: m.telepass2);
case 'energiaTim':
return (s1: m.energiaTim1, s2: m.energiaTim2);
case 'energiaAltri':
return (s1: m.energiaAltri1, s2: m.energiaAltri2);
default:
return (s1: 0, s2: 0);
}
}
}
@@ -0,0 +1,296 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/targets/models/individual_target_model.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class TargetsRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
final StreamController<void> _targetsChangedController =
StreamController<void>.broadcast();
Stream<void> get onTargetsChanged => _targetsChangedController.stream;
void notifyTargetsChanged() {
if (!_targetsChangedController.isClosed) {
_targetsChangedController.add(null);
}
}
// ==========================================
// STORE TARGETS (Tabella 'targets')
// ==========================================
Future<TargetModel?> getStoreTargetById(String id) async {
try {
final response = await _supabase
.from(Tables.targets)
.select('''
*,
${Tables.stores}(*),
${Tables.individualTargets}(
*,
${Tables.staffMembers}(*)
)
''')
.eq('id', id)
.single();
return TargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore getStoreTargetById: $e');
return null;
}
}
Future<List<TargetModel>> getStoreTargets({
required String companyId,
String? storeId,
DateTime? fromDate,
DateTime? toDate,
}) async {
try {
var query = _supabase
.from(Tables.targets)
.select('''
*,
${Tables.stores}(*),
${Tables.individualTargets}(
*,
${Tables.staffMembers}(*)
)
''')
.eq('company_id', companyId);
if (storeId != null && storeId.isNotEmpty) {
query = query.eq('store_id', storeId);
}
if (fromDate != null) {
query = query.gte('end_day', fromDate.toIso8601String());
}
if (toDate != null) {
query = query.lte('start_day', toDate.toIso8601String());
}
final response = await query.order('start_day', ascending: false);
return (response as List<dynamic>)
.map((e) => TargetModel.fromMap(e as Map<String, dynamic>))
.toList();
} on Exception catch (e) {
debugPrint('Errore getStoreTargets: $e');
throw Exception('Errore nel recupero degli obiettivi di negozio: $e');
}
}
Future<TargetModel?> getStoreTargetForMonth({
required String companyId,
required String storeId,
required DateTime month,
}) async {
try {
final firstDay = DateTime(month.year, month.month, 1);
final lastDay = DateTime(month.year, month.month + 1, 0, 23, 59, 59);
final response = await _supabase
.from(Tables.targets)
.select('''
*,
${Tables.stores}(*),
${Tables.individualTargets}(
*,
${Tables.staffMembers}(*)
)
''')
.eq('company_id', companyId)
.eq('store_id', storeId)
.gte('end_day', firstDay.toIso8601String())
.lte('start_day', lastDay.toIso8601String())
.order('start_day', ascending: false)
.limit(1)
.maybeSingle();
if (response == null) return null;
return TargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore getStoreTargetForMonth: $e');
return null;
}
}
Future<TargetModel> saveStoreTarget(TargetModel target) async {
try {
final Map<String, dynamic> data = target.toMap();
final response = await _supabase
.from(Tables.targets)
.upsert(data)
.select('''
*,
${Tables.stores}(*),
${Tables.individualTargets}(
*,
${Tables.staffMembers}(*)
)
''')
.single();
notifyTargetsChanged();
return TargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore saveStoreTarget: $e');
throw Exception('Errore nel salvataggio dell\'obiettivo di negozio: $e');
}
}
Future<void> deleteStoreTarget(String id) async {
try {
await _supabase.from(Tables.targets).delete().eq('id', id);
notifyTargetsChanged();
} on Exception catch (e) {
debugPrint('Errore deleteStoreTarget: $e');
throw Exception('Errore nell\'eliminazione dell\'obiettivo di negozio: $e');
}
}
// ==========================================
// INDIVIDUAL TARGETS (Tabella 'individual_targets')
// ==========================================
Future<IndividualTargetModel?> getIndividualTargetById(String id) async {
try {
final response = await _supabase
.from(Tables.individualTargets)
.select('''
*,
${Tables.staffMembers}(*)
''')
.eq('id', id)
.single();
return IndividualTargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore getIndividualTargetById: $e');
return null;
}
}
Future<List<IndividualTargetModel>> getIndividualTargets({
required String companyId,
String? targetId,
String? staffId,
}) async {
try {
var query = _supabase
.from(Tables.individualTargets)
.select('''
*,
${Tables.staffMembers}(*)
''')
.eq('company_id', companyId);
if (targetId != null && targetId.isNotEmpty) {
query = query.eq('target_id', targetId);
}
if (staffId != null && staffId.isNotEmpty) {
query = query.eq('staff_id', staffId);
}
final response = await query.order('created_at', ascending: false);
return (response as List<dynamic>)
.map((e) => IndividualTargetModel.fromMap(e as Map<String, dynamic>))
.toList();
} on Exception catch (e) {
debugPrint('Errore getIndividualTargets: $e');
throw Exception('Errore nel recupero degli obiettivi individuali: $e');
}
}
Future<IndividualTargetModel?> getIndividualTargetForStaffAndTarget({
required String companyId,
required String targetId,
required String staffId,
}) async {
try {
final response = await _supabase
.from(Tables.individualTargets)
.select('''
*,
${Tables.staffMembers}(*)
''')
.eq('company_id', companyId)
.eq('target_id', targetId)
.eq('staff_id', staffId)
.maybeSingle();
if (response == null) return null;
return IndividualTargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore getIndividualTargetForStaffAndTarget: $e');
return null;
}
}
Future<IndividualTargetModel> saveIndividualTarget(
IndividualTargetModel target,
) async {
try {
final Map<String, dynamic> data = target.toMap();
final response = await _supabase
.from(Tables.individualTargets)
.upsert(data)
.select('''
*,
${Tables.staffMembers}(*)
''')
.single();
notifyTargetsChanged();
return IndividualTargetModel.fromMap(response);
} on Exception catch (e) {
debugPrint('Errore saveIndividualTarget: $e');
throw Exception('Errore nel salvataggio dell\'obiettivo individuale: $e');
}
}
Future<List<IndividualTargetModel>> saveIndividualTargets(
List<IndividualTargetModel> targets,
) async {
if (targets.isEmpty) return [];
try {
final List<Map<String, dynamic>> data =
targets.map((t) => t.toMap()).toList();
final response = await _supabase
.from(Tables.individualTargets)
.upsert(data)
.select('''
*,
${Tables.staffMembers}(*)
''');
notifyTargetsChanged();
return (response as List<dynamic>)
.map((e) => IndividualTargetModel.fromMap(e as Map<String, dynamic>))
.toList();
} on Exception catch (e) {
debugPrint('Errore saveIndividualTargets: $e');
throw Exception('Errore nel salvataggio degli obiettivi individuali: $e');
}
}
Future<void> deleteIndividualTarget(String id) async {
try {
await _supabase.from(Tables.individualTargets).delete().eq('id', id);
notifyTargetsChanged();
} on Exception catch (e) {
debugPrint('Errore deleteIndividualTarget: $e');
throw Exception('Errore nell\'eliminazione dell\'obiettivo individuale: $e');
}
}
void dispose() {
_targetsChangedController.close();
}
}
@@ -0,0 +1,108 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'target_metrics.dart';
class IndividualTargetModel extends Equatable {
final String? id;
final DateTime? createdAt;
final String targetId;
final String companyId;
final String staffId;
final StaffMemberModel? staff;
final String? description;
final TargetMetrics metrics;
const IndividualTargetModel({
this.id,
this.createdAt,
required this.targetId,
required this.companyId,
required this.staffId,
this.staff,
this.description,
this.metrics = const TargetMetrics(),
});
@override
List<Object?> get props => [
id,
createdAt,
targetId,
companyId,
staffId,
staff,
description,
metrics,
];
IndividualTargetModel copyWith({
String? id,
DateTime? createdAt,
String? targetId,
String? companyId,
String? staffId,
StaffMemberModel? staff,
String? description,
TargetMetrics? metrics,
}) {
return IndividualTargetModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
targetId: targetId ?? this.targetId,
companyId: companyId ?? this.companyId,
staffId: staffId ?? this.staffId,
staff: staff ?? this.staff,
description: description ?? this.description,
metrics: metrics ?? this.metrics,
);
}
factory IndividualTargetModel.empty({
String targetId = '',
String companyId = '',
String staffId = '',
}) {
return IndividualTargetModel(
targetId: targetId,
companyId: companyId,
staffId: staffId,
metrics: TargetMetrics.empty(),
);
}
factory IndividualTargetModel.fromMap(Map<String, dynamic> map) {
return IndividualTargetModel(
id: map['id'] as String?,
createdAt:
map['created_at'] != null
? DateTime.parse(map['created_at'] as String)
: null,
targetId: map['target_id'] as String? ?? '',
companyId: map['company_id'] as String? ?? '',
staffId: map['staff_id'] as String? ?? '',
staff:
map[Tables.staffMembers] != null
? StaffMemberModel.fromMap(
map[Tables.staffMembers] as Map<String, dynamic>,
)
: null,
description: map['description'] as String?,
metrics:
map['metrics'] != null && map['metrics'] is Map<String, dynamic>
? TargetMetrics.fromMap(map['metrics'] as Map<String, dynamic>)
: TargetMetrics.fromMap(map),
);
}
Map<String, dynamic> toMap() {
return {
if (id != null && id!.isNotEmpty) 'id': id,
'target_id': targetId,
'company_id': companyId,
'staff_id': staffId,
'description': description,
'metrics': metrics.toMap(),
};
}
}
@@ -0,0 +1,285 @@
import 'package:equatable/equatable.dart';
class TargetMetrics extends Equatable {
final int mnp1;
final int mnp2;
final int unica1;
final int unica2;
final int nip1;
final int nip2;
final int business1;
final int business2;
final int contenuti1;
final int contenuti2;
final int calcio1;
final int calcio2;
final int fin1;
final int fin2;
final int upselling1;
final int upselling2;
final int cb1;
final int cb2;
final int al1;
final int al2;
final int telepass1;
final int telepass2;
final int energiaTim1;
final int energiaTim2;
final int energiaAltri1;
final int energiaAltri2;
// Getter di compatibilità con codice pregresso
int get energiaTim => energiaTim1;
int get energiaAltri => energiaAltri1;
const TargetMetrics({
this.mnp1 = 0,
this.mnp2 = 0,
this.unica1 = 0,
this.unica2 = 0,
this.nip1 = 0,
this.nip2 = 0,
this.business1 = 0,
this.business2 = 0,
this.contenuti1 = 0,
this.contenuti2 = 0,
this.calcio1 = 0,
this.calcio2 = 0,
this.fin1 = 0,
this.fin2 = 0,
this.upselling1 = 0,
this.upselling2 = 0,
this.cb1 = 0,
this.cb2 = 0,
this.al1 = 0,
this.al2 = 0,
this.telepass1 = 0,
this.telepass2 = 0,
int? energiaTim1,
int? energiaTim,
this.energiaTim2 = 0,
int? energiaAltri1,
int? energiaAltri,
this.energiaAltri2 = 0,
}) : energiaTim1 = energiaTim1 ?? energiaTim ?? 0,
energiaAltri1 = energiaAltri1 ?? energiaAltri ?? 0;
@override
List<Object?> get props => [
mnp1,
mnp2,
unica1,
unica2,
nip1,
nip2,
business1,
business2,
contenuti1,
contenuti2,
calcio1,
calcio2,
fin1,
fin2,
upselling1,
upselling2,
cb1,
cb2,
al1,
al2,
telepass1,
telepass2,
energiaTim1,
energiaTim2,
energiaAltri1,
energiaAltri2,
];
TargetMetrics copyWith({
int? mnp1,
int? mnp2,
int? unica1,
int? unica2,
int? nip1,
int? nip2,
int? business1,
int? business2,
int? contenuti1,
int? contenuti2,
int? calcio1,
int? calcio2,
int? fin1,
int? fin2,
int? upselling1,
int? upselling2,
int? cb1,
int? cb2,
int? al1,
int? al2,
int? telepass1,
int? telepass2,
int? energiaTim1,
int? energiaTim,
int? energiaTim2,
int? energiaAltri1,
int? energiaAltri,
int? energiaAltri2,
}) {
return TargetMetrics(
mnp1: mnp1 ?? this.mnp1,
mnp2: mnp2 ?? this.mnp2,
unica1: unica1 ?? this.unica1,
unica2: unica2 ?? this.unica2,
nip1: nip1 ?? this.nip1,
nip2: nip2 ?? this.nip2,
business1: business1 ?? this.business1,
business2: business2 ?? this.business2,
contenuti1: contenuti1 ?? this.contenuti1,
contenuti2: contenuti2 ?? this.contenuti2,
calcio1: calcio1 ?? this.calcio1,
calcio2: calcio2 ?? this.calcio2,
fin1: fin1 ?? this.fin1,
fin2: fin2 ?? this.fin2,
upselling1: upselling1 ?? this.upselling1,
upselling2: upselling2 ?? this.upselling2,
cb1: cb1 ?? this.cb1,
cb2: cb2 ?? this.cb2,
al1: al1 ?? this.al1,
al2: al2 ?? this.al2,
telepass1: telepass1 ?? this.telepass1,
telepass2: telepass2 ?? this.telepass2,
energiaTim1: energiaTim1 ?? energiaTim ?? this.energiaTim1,
energiaTim2: energiaTim2 ?? this.energiaTim2,
energiaAltri1: energiaAltri1 ?? energiaAltri ?? this.energiaAltri1,
energiaAltri2: energiaAltri2 ?? this.energiaAltri2,
);
}
factory TargetMetrics.empty() {
return const TargetMetrics();
}
factory TargetMetrics.fromMap(Map<String, dynamic> map) {
return TargetMetrics(
mnp1: (map['mnp_1'] as num?)?.toInt() ?? 0,
mnp2: (map['mnp_2'] as num?)?.toInt() ?? 0,
unica1: (map['unica_1'] as num?)?.toInt() ?? 0,
unica2: (map['unica_2'] as num?)?.toInt() ?? 0,
nip1: (map['nip_1'] as num?)?.toInt() ?? 0,
nip2: (map['nip_2'] as num?)?.toInt() ?? 0,
business1: (map['business_1'] as num?)?.toInt() ?? 0,
business2: (map['business_2'] as num?)?.toInt() ?? 0,
contenuti1: (map['contenuti_1'] as num?)?.toInt() ?? 0,
contenuti2: (map['contenuti_2'] as num?)?.toInt() ?? 0,
calcio1: (map['calcio_1'] as num?)?.toInt() ?? 0,
calcio2: (map['calcio_2'] as num?)?.toInt() ?? 0,
fin1: (map['fin_1'] as num?)?.toInt() ?? 0,
fin2: (map['fin_2'] as num?)?.toInt() ?? 0,
upselling1: (map['upselling_1'] as num?)?.toInt() ?? 0,
upselling2: (map['upselling_2'] as num?)?.toInt() ?? 0,
cb1: (map['cb_1'] as num?)?.toInt() ?? 0,
cb2: (map['cb_2'] as num?)?.toInt() ?? 0,
al1: (map['al_1'] as num?)?.toInt() ?? 0,
al2: (map['al_2'] as num?)?.toInt() ?? 0,
telepass1: (map['telepass_1'] as num?)?.toInt() ?? 0,
telepass2: (map['telepass_2'] as num?)?.toInt() ?? 0,
energiaTim1: (map['energia_tim_1'] as num?)?.toInt() ??
(map['energia_tim'] as num?)?.toInt() ??
(map['Energia_tim'] as num?)?.toInt() ??
0,
energiaTim2: (map['energia_tim_2'] as num?)?.toInt() ??
(map['Energia_tim_2'] as num?)?.toInt() ??
0,
energiaAltri1: (map['energia_altri_1'] as num?)?.toInt() ??
(map['energia_altri'] as num?)?.toInt() ??
(map['Energia_altri'] as num?)?.toInt() ??
0,
energiaAltri2: (map['energia_altri_2'] as num?)?.toInt() ??
(map['Energia_altri_2'] as num?)?.toInt() ??
0,
);
}
Map<String, dynamic> toMap() {
return {
'mnp_1': mnp1,
'mnp_2': mnp2,
'unica_1': unica1,
'unica_2': unica2,
'nip_1': nip1,
'nip_2': nip2,
'business_1': business1,
'business_2': business2,
'contenuti_1': contenuti1,
'contenuti_2': contenuti2,
if (calcio1 > 0) 'calcio_1': calcio1,
if (calcio2 > 0) 'calcio_2': calcio2,
'fin_1': fin1,
'fin_2': fin2,
'upselling_1': upselling1,
'upselling_2': upselling2,
'cb_1': cb1,
'cb_2': cb2,
'al_1': al1,
'al_2': al2,
'telepass_1': telepass1,
'telepass_2': telepass2,
'energia_tim_1': energiaTim1,
'energia_tim_2': energiaTim2,
'energia_tim': energiaTim1,
'energia_altri_1': energiaAltri1,
'energia_altri_2': energiaAltri2,
'energia_altri': energiaAltri1,
};
}
/// Somma totale di tutti i target del Livello 1 (inclusa energia)
int get totalLevel1 =>
mnp1 +
unica1 +
nip1 +
business1 +
contenuti1 +
calcio1 +
fin1 +
upselling1 +
cb1 +
al1 +
telepass1 +
energiaTim1 +
energiaAltri1;
/// Somma totale di tutti i target del Livello 2 (inclusa energia)
int get totalLevel2 =>
mnp2 +
unica2 +
nip2 +
business2 +
contenuti2 +
calcio2 +
fin2 +
upselling2 +
cb2 +
al2 +
telepass2 +
energiaTim2 +
energiaAltri2;
/// Numero di categorie con almeno una soglia impostata (> 0)
int get activeMetricsCount {
int count = 0;
if (mnp1 > 0 || mnp2 > 0) count++;
if (unica1 > 0 || unica2 > 0) count++;
if (nip1 > 0 || nip2 > 0) count++;
if (business1 > 0 || business2 > 0) count++;
if (contenuti1 > 0 || contenuti2 > 0) count++;
if (calcio1 > 0 || calcio2 > 0) count++;
if (fin1 > 0 || fin2 > 0) count++;
if (upselling1 > 0 || upselling2 > 0) count++;
if (cb1 > 0 || cb2 > 0) count++;
if (al1 > 0 || al2 > 0) count++;
if (telepass1 > 0 || telepass2 > 0) count++;
if (energiaTim1 > 0 || energiaTim2 > 0) count++;
if (energiaAltri1 > 0 || energiaAltri2 > 0) count++;
return count;
}
}
@@ -0,0 +1,136 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'individual_target_model.dart';
import 'target_metrics.dart';
class TargetModel extends Equatable {
final String? id;
final DateTime? createdAt;
final DateTime startDay;
final DateTime endDay;
final String? description;
final String companyId;
final String? storeId;
final StoreModel? store;
final TargetMetrics metrics;
final List<IndividualTargetModel> individualTargets;
const TargetModel({
this.id,
this.createdAt,
required this.startDay,
required this.endDay,
this.description,
required this.companyId,
this.storeId,
this.store,
this.metrics = const TargetMetrics(),
this.individualTargets = const [],
});
@override
List<Object?> get props => [
id,
createdAt,
startDay,
endDay,
description,
companyId,
storeId,
store,
metrics,
individualTargets,
];
TargetModel copyWith({
String? id,
DateTime? createdAt,
DateTime? startDay,
DateTime? endDay,
String? description,
String? companyId,
String? storeId,
StoreModel? store,
TargetMetrics? metrics,
List<IndividualTargetModel>? individualTargets,
}) {
return TargetModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
startDay: startDay ?? this.startDay,
endDay: endDay ?? this.endDay,
description: description ?? this.description,
companyId: companyId ?? this.companyId,
storeId: storeId ?? this.storeId,
store: store ?? this.store,
metrics: metrics ?? this.metrics,
individualTargets: individualTargets ?? this.individualTargets,
);
}
factory TargetModel.empty({
String companyId = '',
String? storeId,
DateTime? startDay,
DateTime? endDay,
}) {
final now = DateTime.now();
final firstDayOfMonth = DateTime(now.year, now.month, 1);
final lastDayOfMonth = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
return TargetModel(
startDay: startDay ?? firstDayOfMonth,
endDay: endDay ?? lastDayOfMonth,
companyId: companyId,
storeId: storeId,
metrics: TargetMetrics.empty(),
individualTargets: const [],
);
}
factory TargetModel.fromMap(Map<String, dynamic> map) {
return TargetModel(
id: map['id'] as String?,
createdAt:
map['created_at'] != null
? DateTime.parse(map['created_at'] as String)
: null,
startDay: DateTime.parse(map['start_day'] as String),
endDay: DateTime.parse(map['end_day'] as String),
description: map['description'] as String?,
companyId: map['company_id'] as String? ?? '',
storeId: map['store_id'] as String?,
store:
map[Tables.stores] != null
? StoreModel.fromMap(map[Tables.stores] as Map<String, dynamic>)
: null,
metrics:
map['metrics'] != null && map['metrics'] is Map<String, dynamic>
? TargetMetrics.fromMap(map['metrics'] as Map<String, dynamic>)
: TargetMetrics.fromMap(map),
individualTargets:
map[Tables.individualTargets] != null &&
map[Tables.individualTargets] is List<dynamic>
? (map[Tables.individualTargets] as List<dynamic>)
.map(
(e) =>
IndividualTargetModel.fromMap(e as Map<String, dynamic>),
)
.toList()
: const [],
);
}
Map<String, dynamic> toMap() {
return {
if (id != null && id!.isNotEmpty) 'id': id,
'start_day': startDay.toIso8601String(),
'end_day': endDay.toIso8601String(),
'description': description,
'company_id': companyId,
if (storeId != null && storeId!.isNotEmpty) 'store_id': storeId,
'metrics': metrics.toMap(),
};
}
}
@@ -0,0 +1,346 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
/// Stato di avanzamento sul ritmo di ciascuna metrica
enum TargetPacingStatus {
/// In linea con lo sfidante o già superato (VERDE PIENO)
inLineS2(label: 'In linea Sfidante', emoji: '🚀'),
/// In linea con il minimo o già raggiunto (VERDINO)
inLineS1(label: 'In linea Minimo', emoji: '✅'),
/// Sotto ritmo ma vicino/recuperabile (ROSA)
recoverable(label: 'Da spingere', emoji: '⚡'),
/// Sotto ritmo grave o fermo (ROSSO)
critical(label: 'Critico', emoji: '🔴'),
/// Nessun obiettivo impostato per questa categoria
notSet(label: 'Non impostato', emoji: '—');
final String label;
final String emoji;
const TargetPacingStatus({required this.label, required this.emoji});
}
/// Avanzamento e ritmo su una singola metrica/categoria di obiettivo
class CategoryProgress extends Equatable {
final String key;
final String label;
final int actualPieces;
final int targetS1;
final int targetS2;
final TargetPacingStatus status;
final double actualDailyRate;
final double requiredDailyRateS1;
final double requiredDailyRateS2;
final double projectedPieces;
const CategoryProgress({
required this.key,
required this.label,
required this.actualPieces,
required this.targetS1,
required this.targetS2,
required this.status,
required this.actualDailyRate,
required this.requiredDailyRateS1,
required this.requiredDailyRateS2,
required this.projectedPieces,
});
/// Calcola il progresso di una singola metrica dati i giorni lavorativi
factory CategoryProgress.calculate({
required String key,
required String label,
required int actual,
required int s1,
required int s2,
required int elapsedDays,
required int remainingDays,
required int totalDays,
}) {
if (s1 == 0 && s2 == 0) {
return CategoryProgress(
key: key,
label: label,
actualPieces: actual,
targetS1: 0,
targetS2: 0,
status: TargetPacingStatus.notSet,
actualDailyRate: elapsedDays > 0 ? (actual / elapsedDays) : 0.0,
requiredDailyRateS1: 0.0,
requiredDailyRateS2: 0.0,
projectedPieces: elapsedDays > 0 ? (actual / elapsedDays) * totalDays : 0.0,
);
}
final actualDaily = elapsedDays > 0 ? (actual / elapsedDays) : 0.0;
final projected = actualDaily * totalDays;
final remainingPiecesS1 = s1 > actual ? (s1 - actual) : 0;
final remainingPiecesS2 = s2 > actual ? (s2 - actual) : 0;
final reqDailyS1 = remainingDays > 0 ? (remainingPiecesS1 / remainingDays) : 0.0;
final reqDailyS2 = remainingDays > 0 ? (remainingPiecesS2 / remainingDays) : 0.0;
// Determinazione dello stato di pacing cromatico a 4 livelli
TargetPacingStatus status;
if (elapsedDays == 0) {
status = TargetPacingStatus.inLineS1;
} else if (s2 > 0 && (actual >= s2 || projected >= s2)) {
status = TargetPacingStatus.inLineS2; // Verde pieno
} else if (actual >= s1 || projected >= s1) {
status = TargetPacingStatus.inLineS1; // Verdino
} else if (s1 > 0 && projected >= (s1 * 0.55)) {
status = TargetPacingStatus.recoverable; // Rosa (da spingere)
} else {
status = TargetPacingStatus.critical; // Rosso (critico)
}
return CategoryProgress(
key: key,
label: label,
actualPieces: actual,
targetS1: s1,
targetS2: s2,
status: status,
actualDailyRate: actualDaily,
requiredDailyRateS1: reqDailyS1,
requiredDailyRateS2: reqDailyS2,
projectedPieces: projected,
);
}
/// Ha un target attivo (> 0) impostato
bool get hasTarget => targetS1 > 0 || targetS2 > 0;
/// Obiettivo Soglia 2 già raggiunto/preso nei pezzi
bool get isAchievedS2 => targetS2 > 0 && actualPieces >= targetS2;
/// Obiettivo Soglia 1 già raggiunto/preso nei pezzi
bool get isAchievedS1 => targetS1 > 0 && actualPieces >= targetS1;
/// Obiettivo già raggiunto/preso (almeno Soglia 1)
bool get isAchieved => isAchievedS1 || isAchievedS2;
/// In linea con il ritmo di marcia ma non ancora formalmente raggiunto
bool get isInLineOnly =>
!isAchieved &&
(status == TargetPacingStatus.inLineS1 ||
status == TargetPacingStatus.inLineS2);
/// Sotto ritmo ma recuperabile (ROSA)
bool get isRecoverable => status == TargetPacingStatus.recoverable;
/// In forte ritardo critico o fermo (ROSSO)
bool get isCritical => status == TargetPacingStatus.critical;
/// Sotto ritmo complessivo (Rosa o Rosso)
bool get isBehind => isRecoverable || isCritical;
@override
List<Object?> get props => [
key,
label,
actualPieces,
targetS1,
targetS2,
status,
actualDailyRate,
requiredDailyRateS1,
requiredDailyRateS2,
projectedPieces,
];
}
/// Modello aggregato di avanzamento target per il negozio o per singolo addetto
class TargetProgressModel extends Equatable {
final String targetId;
final String? storeId;
final String? staffId;
final String? staffName;
final int totalWorkingDays;
final int elapsedWorkingDays;
final int remainingWorkingDays;
final Map<String, CategoryProgress> categories;
final Map<String, TargetProgressModel> staffProgress;
const TargetProgressModel({
required this.targetId,
this.storeId,
this.staffId,
this.staffName,
required this.totalWorkingDays,
required this.elapsedWorkingDays,
required this.remainingWorkingDays,
required this.categories,
this.staffProgress = const {},
});
factory TargetProgressModel.empty() => const TargetProgressModel(
targetId: '',
totalWorkingDays: 0,
elapsedWorkingDays: 0,
remainingWorkingDays: 0,
categories: {},
staffProgress: {},
);
/// Somma di tutti i pezzi realizzati finora
int get totalActualPieces =>
categories.values.fold(0, (sum, c) => sum + c.actualPieces);
/// Totale pezzi obiettivo Soglia 1
int get totalTargetS1 =>
categories.values.fold(0, (sum, c) => sum + c.targetS1);
/// Totale pezzi obiettivo Soglia 2
int get totalTargetS2 =>
categories.values.fold(0, (sum, c) => sum + c.targetS2);
/// Numero di obiettivi già raggiunti/presi (almeno Soglia 1)
int get countAchieved =>
categories.values.where((c) => c.isAchieved).length;
/// Numero di obiettivi già raggiunti in Soglia 2 (Sfidante)
int get countAchievedS2 =>
categories.values.where((c) => c.isAchievedS2).length;
/// Numero di obiettivi già raggiunti in Soglia 1 ma non ancora in Soglia 2
int get countAchievedS1 =>
categories.values.where((c) => c.isAchievedS1 && !c.isAchievedS2).length;
/// Numero di obiettivi non ancora raggiunti ma attualmente in linea con il ritmo
int get countInLineOnly =>
categories.values.where((c) => c.isInLineOnly).length;
/// Numero di obiettivi in linea o già raggiunti in Soglia 2
int get countInLineS2 => categories.values
.where((c) => c.status == TargetPacingStatus.inLineS2)
.length;
/// Numero di obiettivi in linea o già raggiunti in Soglia 1
int get countInLineS1 => categories.values
.where((c) => c.status == TargetPacingStatus.inLineS1)
.length;
/// Numero di obiettivi sotto ritmo ma vicini/recuperabili (ROSA)
int get countRecoverable => categories.values
.where((c) => c.status == TargetPacingStatus.recoverable)
.length;
/// Numero di obiettivi in forte ritardo o fermi (ROSSO)
int get countCritical => categories.values
.where((c) => c.status == TargetPacingStatus.critical)
.length;
/// Numero totale di obiettivi sotto ritmo (Rosa + Rosso)
int get countBehind => countRecoverable + countCritical;
/// Numero di categorie con obiettivo attivo (> 0)
int get countTotalActive => categories.values
.where((c) => c.hasTarget)
.length;
/// Media giornaliera complessiva tenuta finora
double get overallActualDailyRate =>
elapsedWorkingDays > 0 ? (totalActualPieces / elapsedWorkingDays) : 0.0;
/// Media giornaliera complessiva necessaria per raggiungere Soglia 1
double get overallRequiredDailyRateS1 {
final remainingPieces =
totalTargetS1 > totalActualPieces ? (totalTargetS1 - totalActualPieces) : 0;
return remainingWorkingDays > 0 ? (remainingPieces / remainingWorkingDays) : 0.0;
}
/// Media giornaliera complessiva necessaria per raggiungere Soglia 2
double get overallRequiredDailyRateS2 {
final remainingPieces =
totalTargetS2 > totalActualPieces ? (totalTargetS2 - totalActualPieces) : 0;
return remainingWorkingDays > 0 ? (remainingPieces / remainingWorkingDays) : 0.0;
}
@override
List<Object?> get props => [
targetId,
storeId,
staffId,
staffName,
totalWorkingDays,
elapsedWorkingDays,
remainingWorkingDays,
categories,
staffProgress,
];
}
/// Palette cromatica a 4 livelli (Verde, Verdino, Rosa, Rosso) per massima chiarezza visiva
class PacingTheme {
final Color primary;
final Color background;
final Color border;
final Color text;
final String label;
final IconData icon;
const PacingTheme({
required this.primary,
required this.background,
required this.border,
required this.text,
required this.label,
required this.icon,
});
static PacingTheme of(TargetPacingStatus status) {
switch (status) {
case TargetPacingStatus.inLineS2:
return const PacingTheme(
primary: Color(0xFF15803D), // Verde pieno (Sfidante centrato o in linea)
background: Color(0xFFDCFCE7),
border: Color(0xFF86EFAC),
text: Color(0xFF14532D),
label: 'In linea Sfidante',
icon: Icons.rocket_launch_rounded,
);
case TargetPacingStatus.inLineS1:
return const PacingTheme(
primary: Color(0xFF0D9488), // Verdino / Mint (Minimo centrato o in linea)
background: Color(0xFFCCFBF1),
border: Color(0xFF5EEAD4),
text: Color(0xFF115E59),
label: 'In linea Minimo',
icon: Icons.check_circle_outline_rounded,
);
case TargetPacingStatus.recoverable:
return const PacingTheme(
primary: Color(0xFFDB2777), // Rosa (Sotto ritmo ma recuperabile)
background: Color(0xFFFCE7F3),
border: Color(0xFFF9A8D4),
text: Color(0xFF831843),
label: 'Da spingere',
icon: Icons.bolt_rounded,
);
case TargetPacingStatus.critical:
return const PacingTheme(
primary: Color(0xFFDC2626), // Rosso (Forte ritardo)
background: Color(0xFFFEE2E2),
border: Color(0xFFFCA5A5),
text: Color(0xFF7F1D1D),
label: 'In ritardo',
icon: Icons.warning_amber_rounded,
);
case TargetPacingStatus.notSet:
return const PacingTheme(
primary: Colors.grey,
background: Color(0xFFF3F4F6),
border: Color(0xFFE5E7EB),
text: Color(0xFF374151),
label: 'Non impostato',
icon: Icons.remove,
);
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,836 @@
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/features/master_data/store/bloc/store_cubit.dart';
import 'package:flux/features/targets/blocs/target_list_cubit.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/models/target_progress_model.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
class TargetListScreen extends StatefulWidget {
const TargetListScreen({super.key});
@override
State<TargetListScreen> createState() => _TargetListScreenState();
}
class _TargetListScreenState extends State<TargetListScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
final currentStoreId =
context.read<SessionCubit>().state.currentStore?.id;
context.read<TargetListCubit>().loadTargets(storeId: currentStoreId);
});
}
String _formatMonthYear(DateTime date) {
try {
final formatter = DateFormat('MMMM yyyy', 'it_IT');
final formatted = formatter.format(date);
return formatted[0].toUpperCase() + formatted.substring(1);
} catch (_) {
final formatter = DateFormat('MM/yyyy');
return formatter.format(date);
}
}
String _formatDateRange(DateTime start, DateTime end) {
final formatter = DateFormat('dd/MM/yyyy');
return '${formatter.format(start)} - ${formatter.format(end)}';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
return Scaffold(
backgroundColor: theme.colorScheme.surface,
body: SafeArea(
child: Column(
children: [
// ==========================================
// HEADER
// ==========================================
Container(
padding: EdgeInsets.symmetric(
horizontal: isDesktop ? 24.0 : 16.0,
vertical: isDesktop ? 20.0 : 12.0,
),
color: theme.colorScheme.surface,
child: _buildHeader(context, theme, isDesktop),
),
const Divider(height: 1),
// ==========================================
// LISTA DEI TARGET
// ==========================================
Expanded(
child: BlocBuilder<TargetListCubit, TargetListState>(
builder: (context, state) {
if (state.status == TargetListStatus.loading &&
state.targets.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == TargetListStatus.failure &&
state.targets.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 12),
Text(
state.errorMessage ??
'Errore nel caricamento dei target',
style: const TextStyle(fontSize: 16),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: () {
context.read<TargetListCubit>().loadTargets();
},
icon: const Icon(Icons.refresh),
label: const Text('Riprova'),
),
],
),
);
}
if (state.targets.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(
alpha: 0.1,
),
shape: BoxShape.circle,
),
child: Icon(
Icons.track_changes_outlined,
size: 64,
color: theme.colorScheme.primary,
),
),
const SizedBox(height: 20),
Text(
'Nessun target configurato',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
'Definisci gli obiettivi mensili del negozio e assegnali agli addetti.',
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: 14,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
ElevatedButton.icon(
icon: const Icon(Icons.add),
label: const Text('Crea Primo Target'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
onPressed: () => _goToNewTarget(context),
),
],
),
),
);
}
return RefreshIndicator(
onRefresh: () async {
await context.read<TargetListCubit>().loadTargets();
},
child: ListView.separated(
padding: const EdgeInsets.all(24.0),
itemCount: state.targets.length,
separatorBuilder: (_, _) => const SizedBox(height: 16),
itemBuilder: (context, index) {
final target = state.targets[index];
final progress = state.progressMap[target.id];
return _buildTargetCard(
context,
target,
theme,
progress: progress,
);
},
),
);
},
),
),
],
),
),
);
}
Widget _buildHeader(BuildContext context, ThemeData theme, bool isDesktop) {
return BlocBuilder<TargetListCubit, TargetListState>(
builder: (context, state) {
final stores = context.watch<StoreCubit>().state.stores;
final titleWidget = Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Icon(
Icons.track_changes_outlined,
color: theme.colorScheme.primary,
size: isDesktop ? 28 : 24,
),
const SizedBox(width: 10),
Expanded(
child: Text(
'Obiettivi & Target',
style: (isDesktop
? theme.textTheme.headlineMedium
: theme.textTheme.titleLarge)
?.copyWith(
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 4),
Text(
'Gestione e avanzamento delle quote mensili di vendita',
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: isDesktop ? 13 : 12,
),
),
],
);
final storeFilterWidget = stores.length > 1
? Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: theme.dividerColor.withValues(alpha: 0.4),
),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<String?>(
value: state.selectedStoreId,
isDense: true,
isExpanded: !isDesktop,
hint: const Text('Tutti i negozi'),
items: [
const DropdownMenuItem<String?>(
value: null,
child: Text('Tutti i negozi'),
),
...stores.map((s) {
return DropdownMenuItem<String?>(
value: s.id,
child: Text(
s.name,
overflow: TextOverflow.ellipsis,
),
);
}),
],
onChanged: (val) {
context.read<TargetListCubit>().filterByStore(val);
},
),
),
)
: null;
final newTargetButton = ElevatedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: const Text('Nuovo Target'),
style: ElevatedButton.styleFrom(
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
padding: EdgeInsets.symmetric(
horizontal: isDesktop ? 18 : 14,
vertical: isDesktop ? 12 : 10,
),
),
onPressed: () => _goToNewTarget(context),
);
if (isDesktop) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: titleWidget),
const SizedBox(width: 16),
if (storeFilterWidget != null) ...[
storeFilterWidget,
const SizedBox(width: 12),
],
newTargetButton,
],
);
}
// Su schermi mobili / stretti disponiamo su due livelli
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
titleWidget,
const SizedBox(height: 12),
Row(
children: [
if (storeFilterWidget != null) ...[
Expanded(child: storeFilterWidget),
const SizedBox(width: 10),
] else ...[
const Spacer(),
],
newTargetButton,
],
),
],
);
},
);
}
Widget _buildTargetCard(
BuildContext context,
TargetModel target,
ThemeData theme, {
TargetProgressModel? progress,
}) {
final title = _formatMonthYear(target.startDay);
final range = _formatDateRange(target.startDay, target.endDay);
final storeName = target.store?.name ?? 'Negozio';
final activeMetricsCount = target.metrics.activeMetricsCount;
final staffCount = target.individualTargets.length;
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.6)),
),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _goToTargetDetail(context, target),
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Riga 1: Titolo Mese + Badge Negozio + Azioni (Modifica / Elimina)
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.calendar_month_outlined,
color: theme.colorScheme.primary,
size: 26,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
Chip(
label: Text(
storeName,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
backgroundColor: theme.colorScheme.primary
.withValues(alpha: 0.1),
side: BorderSide.none,
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
),
],
),
const SizedBox(height: 4),
Text(
range,
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
// Menu Azioni (Modifica / Elimina)
IconButton(
icon: const Icon(Icons.edit_outlined),
tooltip: 'Modifica quote target',
onPressed: () => _goToEditTarget(context, target),
),
IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
tooltip: 'Elimina target',
onPressed: () => _confirmDelete(context, target),
),
],
),
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 16),
// Riga 2: Stato Avanzamento Obiettivi (Presi, In Linea, Sotto)
if (progress != null) ...[
() {
final greenTheme = PacingTheme.of(TargetPacingStatus.inLineS2);
final verdinoTheme = PacingTheme.of(TargetPacingStatus.inLineS1);
final pinkTheme = PacingTheme.of(TargetPacingStatus.recoverable);
final redTheme = PacingTheme.of(TargetPacingStatus.critical);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Sottotitolo informativo: Giorni Lavorativi ed Addetti
Row(
children: [
Icon(
Icons.schedule_outlined,
size: 15,
color: theme.colorScheme.primary,
),
const SizedBox(width: 6),
Expanded(
child: Text(
'${progress.elapsedWorkingDays} gg trascorsi • ${progress.remainingWorkingDays} gg rimasti (escl. dom. e festivi) • $staffCount addetti',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 12),
// I 3 INDICATORI CHIAVE: GIÀ PRESI, IN LINEA, SOTTO RITMO
Wrap(
spacing: 12,
runSpacing: 10,
children: [
// 1. GIÀ PRESI (Verde)
_buildPacingMetricCard(
title: 'GIÀ PRESI',
value: '${progress.countAchieved}',
suffix: '/ ${progress.countTotalActive}',
note: progress.countAchievedS2 > 0
? '${progress.countAchievedS2} centrati in S2'
: (progress.countAchieved > 0
? 'Obiettivi raggiunti'
: 'Nessuno ancora'),
color: greenTheme.text,
backgroundColor: greenTheme.background,
borderColor: greenTheme.border,
icon: Icons.emoji_events_rounded,
),
// 2. IN LINEA (Verdino)
_buildPacingMetricCard(
title: 'IN LINEA',
value: '${progress.countInLineOnly}',
suffix: 'obiettivi',
note: 'A ritmo per chiudere',
color: verdinoTheme.text,
backgroundColor: verdinoTheme.background,
borderColor: verdinoTheme.border,
icon: Icons.trending_up_rounded,
),
// 3. SOTTO RITMO (Rosa o Rosso)
_buildPacingMetricCard(
title: 'SOTTO RITMO',
value: '${progress.countBehind}',
suffix: 'da spingere',
note: progress.countBehind == 0
? 'Tutto a ritmo!'
: '${progress.countRecoverable} recuperabili • ${progress.countCritical} critici',
color: progress.countBehind == 0
? greenTheme.text
: (progress.countCritical > 0
? redTheme.text
: pinkTheme.text),
backgroundColor: progress.countBehind == 0
? greenTheme.background
: (progress.countCritical > 0
? redTheme.background
: pinkTheme.background),
borderColor: progress.countBehind == 0
? greenTheme.border
: (progress.countCritical > 0
? redTheme.border
: pinkTheme.border),
icon: progress.countBehind == 0
? Icons.check_circle_rounded
: (progress.countCritical > 0
? Icons.warning_amber_rounded
: Icons.bolt_rounded),
),
],
),
const SizedBox(height: 14),
// Panoramica Categorie Attive con il loro rispettivo stato
Wrap(
spacing: 8,
runSpacing: 8,
children: [
...progress.categories.values
.where((c) => c.hasTarget)
.map((c) {
if (c.isAchieved) {
return _buildSmartChip(
icon: Icons.emoji_events_rounded,
label: '${c.label}: Preso! 🎉',
color: greenTheme.text,
backgroundColor: greenTheme.background,
borderColor: greenTheme.border,
);
} else if (c.isInLineOnly) {
return _buildSmartChip(
icon: Icons.check_circle_outline_rounded,
label: '${c.label}: In linea ✅',
color: verdinoTheme.text,
backgroundColor: verdinoTheme.background,
borderColor: verdinoTheme.border,
);
} else if (c.isRecoverable) {
return _buildSmartChip(
icon: Icons.bolt_rounded,
label: '${c.label}: Da spingere ⚡',
color: pinkTheme.text,
backgroundColor: pinkTheme.background,
borderColor: pinkTheme.border,
);
} else {
return _buildSmartChip(
icon: Icons.warning_amber_rounded,
label: '${c.label}: In ritardo 🔴',
color: redTheme.text,
backgroundColor: redTheme.background,
borderColor: redTheme.border,
);
}
}),
],
),
],
);
}(),
] else ...[
// Fallback indicatori di base se il progresso è ancora in caricamento
Wrap(
spacing: 12,
runSpacing: 8,
children: [
_buildMetricBadge(
label: 'Obiettivi Attivi',
value: '$activeMetricsCount categorie',
color: Colors.blue,
icon: Icons.flag_outlined,
),
_buildMetricBadge(
label: 'Addetti Coinvolti',
value: '$staffCount assegnati',
color: Colors.teal,
icon: Icons.people_outline,
),
],
),
],
const SizedBox(height: 14),
// Pulsante Visualizza Avanzamento
Align(
alignment: Alignment.centerRight,
child: TextButton.icon(
onPressed: () => _goToTargetDetail(context, target),
icon: const Icon(Icons.analytics_outlined, size: 18),
label: const Text('Vedi Avanzamento & Statistiche'),
),
),
],
),
),
),
);
}
Widget _buildSmartChip({
required IconData icon,
required String label,
required Color color,
required Color backgroundColor,
Color? borderColor,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: borderColor ?? color.withValues(alpha: 0.3),
width: 1.2,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: color),
const SizedBox(width: 6),
Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
);
}
Widget _buildPacingMetricCard({
required String title,
required String value,
required String suffix,
required String note,
required Color color,
required Color backgroundColor,
required Color borderColor,
IconData? icon,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: borderColor, width: 1.2),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon, size: 14, color: color.withValues(alpha: 0.9)),
const SizedBox(width: 5),
],
Text(
title,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: color.withValues(alpha: 0.9),
letterSpacing: 0.5,
),
),
],
),
const SizedBox(height: 4),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
value,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w900,
color: color,
),
),
const SizedBox(width: 5),
Text(
suffix,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: color.withValues(alpha: 0.85),
),
),
],
),
const SizedBox(height: 2),
Text(
note,
style: TextStyle(
fontSize: 10,
color: color.withValues(alpha: 0.8),
fontWeight: FontWeight.w500,
),
),
],
),
);
}
Widget _buildMetricBadge({
required String label,
required String value,
required Color color,
required IconData icon,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withValues(alpha: 0.25)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 10,
color: Colors.grey.shade700,
fontWeight: FontWeight.w500,
),
),
Text(
value,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
],
),
);
}
void _goToNewTarget(BuildContext context) {
context.pushNamed(Routes.targetForm);
}
void _goToEditTarget(BuildContext context, TargetModel target) {
context.pushNamed(Routes.targetForm, extra: target);
}
void _goToTargetDetail(BuildContext context, TargetModel target) {
context.pushNamed(Routes.targetDetail, extra: target);
}
Future<void> _confirmDelete(BuildContext context, TargetModel target) async {
final title = _formatMonthYear(target.startDay);
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: Colors.red),
SizedBox(width: 8),
Text('Elimina Target'),
],
),
content: Text(
'Sei sicuro di voler eliminare il target di "$title"?\nVerranno eliminati anche tutti i target individuali assegnati agli addetti per questo mese.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Annulla'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Elimina'),
),
],
);
},
);
if (confirmed == true && context.mounted) {
final success = await context.read<TargetListCubit>().deleteTarget(
target.id!,
);
if (success && context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('Target eliminato.')));
}
}
}
}
+55 -6
View File
@@ -8,6 +8,7 @@ import 'package:flux/features/settings/data/settings_repository.dart';
import 'package:flux/features/tasks/data/task_repository.dart';
import 'package:flux/features/tasks/models/task_model.dart';
import 'package:flux/features/tasks/models/task_reminder_config.dart';
import 'package:flux/features/tasks/models/task_status.dart';
import 'package:get_it/get_it.dart';
part 'task_form_state.dart';
@@ -30,7 +31,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
}
String get _companyId => _sessionCubit.state.company!.id!;
String get _currentUserId => _sessionCubit.state.currentStaffMember!.id!;
StaffMemberModel get _currentUser => _sessionCubit.state.currentStaffMember!;
String? get _currentStoreId => _sessionCubit.state.currentStore?.id;
// --- ARMED INITIALIZATION (Nuovo, Esistente o Deep Link) ---
@@ -57,6 +58,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
dueDate: task.dueDate,
isGlobal: task.isGlobal, // Sfrutta il tuo getter storeId == null
selectedStaffIds: task.assignedToIds,
taskStatus: task.status,
),
);
await _loadExistingTaskReminders(task.id!);
@@ -129,7 +131,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
try {
final defaults = await _settingsRepository.getMyReminderDefaults(
companyId: _companyId,
staffId: _currentUserId,
staffId: _currentUser.id!,
);
final initialReminders = defaults
.map(
@@ -155,7 +157,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
try {
final existingConfigs = await _repository.fetchPersonalReminders(
taskId: taskId,
staffId: _currentUserId,
staffId: _currentUser.id!,
);
emit(state.copyWith(reminders: existingConfigs));
} catch (e) {
@@ -218,7 +220,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
final taskToSave = TaskModel(
id: state.id,
companyId: _companyId,
createdById: _currentUserId,
createdBy: _currentUser,
title: state.title.trim(),
description: state.description.trim(),
dueDate: state.dueDate,
@@ -233,14 +235,14 @@ class TaskFormCubit extends Cubit<TaskFormState> {
await _repository.createTask(
task: taskToSave,
assignedStaffIds: state.selectedStaffIds,
currentUserId: _currentUserId,
currentUserId: _currentUser.id!,
currentUserCustomReminders: state.reminders,
);
} else {
await _repository.updateTask(
task: taskToSave,
assignedStaffIds: state.selectedStaffIds,
currentUserId: _currentUserId,
currentUserId: _currentUser.id!,
currentUserCustomReminders: state.reminders,
);
}
@@ -254,4 +256,51 @@ class TaskFormCubit extends Cubit<TaskFormState> {
);
}
}
Future<void> deleteTask() async {
if (state.id == null) return;
emit(state.copyWith(status: TaskFormStatus.submitting));
try {
await _repository.deleteTask(state.id!);
emit(state.copyWith(status: TaskFormStatus.success));
} catch (e) {
emit(
state.copyWith(
status: TaskFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
Future<void> updateTaskLocalStatus(TaskStatus newStatus) async {
emit(state.copyWith(taskStatus: newStatus));
}
Future<void> updateTaskStatus(TaskStatus newStatus) async {
try {
// Chiamiamo il repo passando il task aggiornato
await _repository.updateTaskStatus(
taskId: state.id!,
newStatus: newStatus,
updatedById: _currentUser.id!,
);
if (!isClosed) {
// Se l'update va a buon fine, aggiorniamo lo stato locale del cubit
emit(
state.copyWith(status: TaskFormStatus.success, taskStatus: newStatus),
);
}
} catch (e) {
if (!isClosed) {
emit(
state.copyWith(
status: TaskFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
}
}
@@ -11,9 +11,9 @@ class TaskFormState extends Equatable {
final bool isGlobal;
final List<String> selectedStaffIds;
final List<TaskReminderConfig> reminders;
final Map<String, List<StaffMemberModel>>
groupedAvailableStaff; // <-- RIPRISTINATO
final Map<String, List<StaffMemberModel>> groupedAvailableStaff;
final String? errorMessage;
final TaskStatus taskStatus;
const TaskFormState({
this.id,
@@ -26,6 +26,7 @@ class TaskFormState extends Equatable {
this.reminders = const [],
this.groupedAvailableStaff = const {},
this.errorMessage,
this.taskStatus = TaskStatus.open,
});
bool get isFormValid => title.trim().isNotEmpty;
@@ -41,6 +42,7 @@ class TaskFormState extends Equatable {
List<TaskReminderConfig>? reminders,
Map<String, List<StaffMemberModel>>? groupedAvailableStaff,
String? errorMessage,
TaskStatus? taskStatus,
}) {
return TaskFormState(
id: id ?? this.id,
@@ -54,6 +56,7 @@ class TaskFormState extends Equatable {
groupedAvailableStaff:
groupedAvailableStaff ?? this.groupedAvailableStaff,
errorMessage: errorMessage,
taskStatus: taskStatus ?? this.taskStatus,
);
}
@@ -69,5 +72,6 @@ class TaskFormState extends Equatable {
reminders,
groupedAvailableStaff,
errorMessage,
taskStatus,
];
}
+85 -15
View File
@@ -21,7 +21,7 @@ class TasksRepository {
}) async {
try {
final response = await _supabase
.from('task_reminders')
.from(Tables.taskReminders)
.select()
.eq('task_id', taskId)
.eq('staff_id', staffId)
@@ -53,13 +53,17 @@ class TasksRepository {
int? limit,
}) async {
try {
// 1. FASE FILTRI: Usa il join esplicito stile "Notes"
// 1. FASE FILTRI: Disambiguazione completa su Tasks e Assignments
var filterBuilder = _supabase
.from(Tables.tasks)
.select('''
*,
creator:${Tables.staffMembers}!created_by_id(*),
updater:${Tables.staffMembers}!updated_by_id(*),
task_assignments:${Tables.taskAssignments} (
${Tables.staffMembers} (*)
*,
assignee:${Tables.staffMembers}!staff_id(*),
assigner:${Tables.staffMembers}!assigned_by_id(*)
)
''')
.eq('company_id', companyId);
@@ -71,7 +75,6 @@ class TasksRepository {
}
if (staffId != null) {
// Grazie al trigger, hai l'array pronto per il filtro senza impazzire!
filterBuilder = filterBuilder.contains('assigned_to_ids', [staffId]);
}
@@ -105,8 +108,12 @@ class TasksRepository {
.from(Tables.tasks)
.select('''
*,
creator:${Tables.staffMembers}!created_by_id(*),
updater:${Tables.staffMembers}!updated_by_id(*),
task_assignments:${Tables.taskAssignments} (
${Tables.staffMembers} (*)
*,
assignee:${Tables.staffMembers}!staff_id(*),
assigner:${Tables.staffMembers}!assigned_by_id(*)
)
''')
.eq('id', taskId)
@@ -122,14 +129,11 @@ class TasksRepository {
// =========================================================================
// REALTIME STREAM (La sentinella per la bacheca)
// =========================================================================
Stream<List<TaskModel>> watchCompanyTasks(String companyId) {
Stream<List<Map<String, dynamic>>> watchCompanyTasks(String companyId) {
return _supabase
.from('tasks')
.stream(primaryKey: ['id'])
.eq('company_id', companyId)
.map((listOfMaps) {
return listOfMaps.map((map) => TaskModel.fromMap(map)).toList();
});
.eq('company_id', companyId);
}
// =========================================================================
@@ -160,6 +164,7 @@ class TasksRepository {
'task_id': taskId,
'staff_id': staffId,
'company_id': task.companyId,
'assigned_by_id': currentUserId,
},
)
.toList();
@@ -276,7 +281,7 @@ class TasksRepository {
// 1. Aggiornamento dati Task Base
await _supabase
.from('tasks')
.from(Tables.tasks)
.update({
'title': task.title,
'description': task.description,
@@ -286,15 +291,51 @@ class TasksRepository {
})
.eq('id', taskId);
// 2. Aggiornamento Assegnazioni: eliminiamo le vecchie, inseriamo le nuove
await _supabase.from('task_assignments').delete().eq('task_id', taskId);
if (assignedStaffIds.isNotEmpty) {
final assignmentsToInsert = assignedStaffIds
// 🥷 2. GESTIONE CHIRURGICA DELLE ASSEGNAZIONI (Addio spam!)
// A) Recuperiamo chi è GIÀ assegnato a questo task
final existingAssignmentsResponse = await _supabase
.from('task_assignments')
.select('staff_id')
.eq('task_id', taskId);
final List<String> existingStaffIds =
(existingAssignmentsResponse as List)
.map((row) => row['staff_id'] as String)
.toList();
// B) Calcoliamo i Delta con i Set di Dart (Pura magia matematica)
final newStaffIdsSet = assignedStaffIds.toSet();
final existingStaffIdsSet = existingStaffIds.toSet();
// Quelli da inserire (presenti nei nuovi, ma non nei vecchi)
final toInsertIds = newStaffIdsSet
.difference(existingStaffIdsSet)
.toList();
// Quelli da eliminare (presenti nei vecchi, ma non nei nuovi)
final toDeleteIds = existingStaffIdsSet
.difference(newStaffIdsSet)
.toList();
// C) Eseguiamo solo lo stretto necessario
if (toDeleteIds.isNotEmpty) {
await _supabase
.from('task_assignments')
.delete()
.eq('task_id', taskId)
.inFilter('staff_id', toDeleteIds);
}
if (toInsertIds.isNotEmpty) {
final assignmentsToInsert = toInsertIds
.map(
(staffId) => {
'task_id': taskId,
'staff_id': staffId,
'company_id': task.companyId,
'assigned_by_id':
currentUserId, // Il nostro salvavita anti-fantasma
},
)
.toList();
@@ -352,6 +393,35 @@ class TasksRepository {
}
}
Future<void> updateTaskStatus({
required String taskId,
required TaskStatus newStatus,
required String? updatedById,
}) async {
try {
await _supabase
.from(Tables.tasks)
.update({
'status': newStatus.toValue,
'updated_by_id': updatedById,
'updated_at': DateTime.now().toIso8601String(),
})
.eq('id', taskId);
} catch (e) {
throw Exception(
'Errore durante l\'aggiornamento dello stato del task: $e',
);
}
}
Future<void> deleteTask(String taskId) async {
try {
await _supabase.from(Tables.tasks).delete().eq('id', taskId);
} catch (e) {
throw Exception('Errore durante la cancellazione del task: $e');
}
}
// --- HELPER PRIVATO PER LA MAPPA DEL REMINDER ---
Map<String, dynamic> _buildReminderRow(
TaskModel task,
+21 -9
View File
@@ -9,11 +9,12 @@ class TaskModel extends Equatable {
final String? description;
final List<String> assignedToIds;
final List<StaffMemberModel> assignedToStaff; // I dati completi dal JOIN
final String? createdById;
final StaffMemberModel? createdBy;
final DateTime? dueDate;
final TaskStatus status;
final DateTime? createdAt;
final String? storeId;
final StaffMemberModel? updatedBy;
const TaskModel({
this.id,
@@ -22,24 +23,25 @@ class TaskModel extends Equatable {
this.description,
this.assignedToIds = const [],
this.assignedToStaff = const [],
this.createdById,
this.createdBy,
this.dueDate,
this.status = TaskStatus.open,
this.createdAt,
this.storeId,
this.updatedBy,
});
bool get isGlobal => storeId == null;
// --- FACTORY: MODELLO VUOTO (Per le creazioni) ---
factory TaskModel.empty({String? companyId, String? createdById}) {
factory TaskModel.empty({String? companyId, StaffMemberModel? createdBy}) {
return TaskModel(
companyId: companyId,
title: '',
description: '',
assignedToIds: const [],
assignedToStaff: const [],
createdById: createdById,
createdBy: createdBy,
status: TaskStatus.open,
createdAt: DateTime.now(),
);
@@ -54,11 +56,12 @@ class TaskModel extends Equatable {
description,
assignedToIds,
assignedToStaff,
createdById,
createdBy,
dueDate,
status,
createdAt,
storeId,
updatedBy,
];
// --- COPY WITH ---
@@ -69,13 +72,15 @@ class TaskModel extends Equatable {
String? description,
List<String>? assignedToIds,
List<StaffMemberModel>? assignedToStaff,
String? createdById,
StaffMemberModel? createdBy,
DateTime? dueDate,
bool clearDueDate = false, // Flag ninja per resettare la scadenza
TaskStatus? status,
DateTime? createdAt,
String? storeId,
bool clearStoreId = false,
StaffMemberModel? updatedBy,
String? updatedByDisplayName,
}) {
return TaskModel(
id: id ?? this.id,
@@ -84,11 +89,12 @@ class TaskModel extends Equatable {
description: description ?? this.description,
assignedToIds: assignedToIds ?? this.assignedToIds,
assignedToStaff: assignedToStaff ?? this.assignedToStaff,
createdById: createdById ?? this.createdById,
createdBy: createdBy ?? this.createdBy,
dueDate: clearDueDate ? null : (dueDate ?? this.dueDate),
status: status ?? this.status,
createdAt: createdAt ?? this.createdAt,
storeId: clearStoreId ? null : (storeId ?? this.storeId),
updatedBy: updatedBy ?? this.updatedBy,
);
}
@@ -124,7 +130,9 @@ class TaskModel extends Equatable {
description: map['description'] as String?,
assignedToIds: parsedAssignedToIds,
assignedToStaff: staffList,
createdById: map['created_by_id'] as String?,
createdBy: map['created_by_id'] != null
? StaffMemberModel.fromMap(map['creator'])
: null,
dueDate: map['due_date'] != null
? DateTime.parse(map['due_date'] as String).toLocal()
: null,
@@ -133,6 +141,9 @@ class TaskModel extends Equatable {
? DateTime.parse(map['created_at'] as String).toLocal()
: null,
storeId: map['store_id'] as String?,
updatedBy: map['updated_by_id'] != null
? StaffMemberModel.fromMap(map['updater'])
: null,
);
}
@@ -145,10 +156,11 @@ class TaskModel extends Equatable {
if (description != null) 'description': description,
// Passiamo l'array vuoto se non ci sono assegnazioni
'assigned_to_ids': assignedToIds.isEmpty ? null : assignedToIds,
if (createdById != null) 'created_by_id': createdById,
if (createdBy != null) 'created_by_id': createdBy!.id,
'due_date': dueDate?.toUtc().toIso8601String(),
'status': status.toValue,
'store_id': storeId,
if (updatedBy != null) 'updated_by_id': updatedBy!.id,
};
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
enum TaskStatus { open, inProgress, completed }
extension TaskStatusExtension on TaskStatus {
String get name {
String get displayName {
switch (this) {
case TaskStatus.open:
return 'Da Iniziare';
+76 -7
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tasks/blocs/task_form_cubit.dart';
import 'package:flux/features/tasks/models/task_status.dart';
import 'package:go_router/go_router.dart';
class TaskFormScreen extends StatefulWidget {
@@ -123,6 +124,30 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
appBar: AppBar(
title: Text(isEditing ? 'Modifica Task' : 'Nuovo Task'),
actions: [
// 🥷 1. BOTTONE COMPLETAMENTO RAPIDO (Solo se in edit e non già completato)
if (isEditing && state.taskStatus != TaskStatus.completed)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
vertical: 8.0,
),
child: ElevatedButton.icon(
onPressed: () {
context.read<TaskFormCubit>().updateTaskStatus(
TaskStatus.completed,
);
},
icon: const Icon(Icons.check_circle_outline),
label: const Text('Completa'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green.shade600,
foregroundColor: Colors.white,
elevation: 0,
),
),
),
// 🥷 2. LOADER O BOTTONE SALVA
if (state.status == TaskFormStatus.submitting)
const Padding(
padding: EdgeInsets.all(16.0),
@@ -133,13 +158,18 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
),
)
else
TextButton.icon(
onPressed: state.isFormValid ? () => cubit.saveTask() : null,
icon: const Icon(Icons.save),
label: const Text('Salva'),
style: TextButton.styleFrom(
foregroundColor: Colors.orange,
disabledForegroundColor: Colors.grey,
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: TextButton.icon(
onPressed: state.isFormValid
? () => cubit.saveTask()
: null,
icon: const Icon(Icons.save),
label: const Text('Salva'),
style: TextButton.styleFrom(
foregroundColor: Colors.orange,
disabledForegroundColor: Colors.grey,
),
),
),
],
@@ -264,6 +294,45 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
),
onChanged: cubit.updateDescription,
),
if (state.id != null) ...[
const SizedBox(height: 16),
DropdownButtonFormField<TaskStatus>(
// Leggiamo lo stato attuale dal Cubit (o usiamo un default per i nuovi task)
initialValue: state.taskStatus,
decoration: InputDecoration(
labelText: 'Stato Attuale',
prefixIcon: const Icon(Icons.flag_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
filled: true,
fillColor: Theme.of(context).colorScheme.surface,
),
// Mappiamo tutti i valori dell'enum in elementi della tendina
items: TaskStatus.values.map((TaskStatus status) {
return DropdownMenuItem<TaskStatus>(
value: status,
child: Text(
status
.displayName, // Usa la property displayName del tuo enum!
style: TextStyle(
fontWeight: status == state.taskStatus
? FontWeight.bold
: FontWeight.normal,
),
),
);
}).toList(),
onChanged: (TaskStatus? newStatus) {
if (newStatus != null && newStatus != state.taskStatus) {
context.read<TaskFormCubit>().updateTaskStatus(newStatus);
}
},
),
],
const SizedBox(height: 24),
// --- SCADENZA ---
@@ -17,11 +17,15 @@ class TicketListCubit extends Cubit<TicketListState> {
loadTickets(refresh: true);
}
int _fetchId = 0;
/// Recupera i ticket. Se reset = true, svuota la lista e riparte da offset 0.
Future<void> loadTickets({bool refresh = false}) async {
if (state.isLoading) return;
if (state.isLoading && !refresh) return;
if (!refresh && state.hasReachedMax) return;
final currentFetchId = ++_fetchId;
emit(
state.copyWith(
isLoading: true,
@@ -43,6 +47,8 @@ class TicketListCubit extends Cubit<TicketListState> {
staffIdFilter: state.staffIdFilter,
);
if (currentFetchId != _fetchId) return;
emit(
state.copyWith(
tickets: refresh ? newTickets : [...state.tickets, ...newTickets],
@@ -51,6 +57,7 @@ class TicketListCubit extends Cubit<TicketListState> {
),
);
} catch (e) {
if (currentFetchId != _fetchId) return;
emit(state.copyWith(isLoading: false, errorMessage: e.toString()));
}
}
@@ -55,6 +55,44 @@ class TicketShippingCubit extends Cubit<TicketShippingState> {
}
}
Future<void> createQuickProvider({
required String name,
required String address,
String city = '',
String zipCode = '',
String province = '',
}) async {
emit(state.copyWith(status: TicketShippingStatus.loading));
try {
final newProvider = await _repository.createQuickRepairCenter(
name: name,
address: address,
city: city,
zipCode: zipCode,
province: province,
);
final updatedProviders = List<ProviderModel>.from(state.availableProviders)
..add(newProvider);
emit(
state.copyWith(
status: TicketShippingStatus.initial,
availableProviders: updatedProviders,
),
);
selectProvider(newProvider.id!);
} catch (e) {
emit(
state.copyWith(
status: TicketShippingStatus.failure,
errorMessage: e.toString(),
),
);
}
}
void selectProvider(String providerId) {
final ProviderModel provider = state.availableProviders.firstWhere(
(p) => p.id == providerId,
@@ -59,9 +59,21 @@ class TicketRepository {
query = query.eq('staff_id', staffIdFilter);
}
if (searchTerm != null && searchTerm.isNotEmpty) {
// Filtra sui campi della tabella principale O su quelli della tabella joinata
query = query.or('customer.name.ilike.%$searchTerm%');
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
final matchingCustomerIds = await _findMatchingCustomerIds(cleanTerm);
final List<String> orConditions = [
'request.ilike.%$cleanTerm%',
'reference_id.ilike.%$cleanTerm%',
'public_notes.ilike.%$cleanTerm%',
'internal_notes.ilike.%$cleanTerm%',
'target_sn.ilike.%$cleanTerm%',
'source_sn.ilike.%$cleanTerm%',
];
if (matchingCustomerIds.isNotEmpty) {
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
}
query = query.or(orConditions.join(','));
}
final response = await query
@@ -74,6 +86,23 @@ class TicketRepository {
}
}
Future<List<String>> _findMatchingCustomerIds(String searchTerm) async {
try {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
final companyId = GetIt.I.get<SessionCubit>().state.company?.id;
var customerQuery = _supabase.from(Tables.customers).select('id');
if (companyId != null && companyId.isNotEmpty) {
customerQuery = customerQuery.eq('company_id', companyId);
}
final response = await customerQuery
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%')
.limit(100);
return (response as List).map((c) => c['id'].toString()).toList();
} catch (_) {
return [];
}
}
// --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI TUTTA L'AZIENDA ---
Future<List<TicketModel>> fetchTickets({
required String? companyId,
@@ -123,9 +152,21 @@ class TicketRepository {
query = query.eq('staff_id', staffIdFilter);
}
if (searchTerm != null && searchTerm.isNotEmpty) {
// Filtra sui campi della tabella principale O su quelli della tabella joinata
query = query.or('customer.name.ilike.%$searchTerm%');
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
final matchingCustomerIds = await _findMatchingCustomerIds(cleanTerm);
final List<String> orConditions = [
'request.ilike.%$cleanTerm%',
'reference_id.ilike.%$cleanTerm%',
'public_notes.ilike.%$cleanTerm%',
'internal_notes.ilike.%$cleanTerm%',
'target_sn.ilike.%$cleanTerm%',
'source_sn.ilike.%$cleanTerm%',
];
if (matchingCustomerIds.isNotEmpty) {
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
}
query = query.or(orConditions.join(','));
}
final response = await query
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more