Compare commits

..
57 Commits
Author SHA1 Message Date
brontomark 6d2c563ce2 feat: add customer orders feature with management, forms, and PDF export
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m37s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m38s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m24s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 10m50s
2026-12-02 18:26:45 +01:00
brontomark 5fcc16fb9c refactor: improve responsive layout across dashboard cards and add unit tests
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m20s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m35s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m41s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 10m33s
2026-11-29 13:56:44 +01:00
brontomark 1084b03610 feat: implement auto-save functionality for operations form 2026-11-29 13:17:56 +01:00
brontomark 63edd51420 v
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m0s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m23s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m57s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 14m52s
2026-11-21 15:10:50 +01:00
brontomark 7572f4c061 compilazione linux su docker x retrocompatibilità 2026-11-21 15:10:24 +01:00
brontomark 57a4dc6f68 filtri avanzati operazioni
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m31s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m50s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m26s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m43s
2026-11-21 10:23:04 +01:00
brontomark 4b111766dc aggiunta quantità a intrattenimento e unica
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m6s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m23s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m37s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 26m18s
2026-11-12 11:09:34 +01:00
brontomark 2bf668a088 pdf compression
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m43s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m21s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m32s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m39s
2026-11-03 15:38:03 +01:00
brontomark 0adb1a8f1c pdf compression 2026-11-03 15:37:44 +01:00
brontomark 606a1fc3a9 fix lista ticket
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m7s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m28s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m33s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 15m1s
2026-10-23 09:49:14 +02:00
brontomark 4e3732597b fix upload allegati
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m10s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m15s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 10m8s
2026-10-15 17:05:19 +02:00
brontomark 53496a2a9d aggiunto supporto al salvataggio rotazione immagini
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m55s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m43s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m15s
2026-10-15 13:11:51 +02:00
brontomark 0cc7c76df9 wow, cropped images e thumbnails
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m35s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m13s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 3m13s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m18s
2026-10-15 11:45:08 +02:00
brontomark ca67d86a71 sdf 2026-10-14 17:34:54 +02:00
brontomark 33e309909e fix CI
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m21s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m45s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 8m9s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 12m42s
2026-10-14 16:24:18 +02:00
brontomark ab64bf0621 fixed CI with new selfhosted endpoint
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m3s
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 2m9s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-linux (push) Canceled after 8s
2026-10-14 16:21:23 +02:00
brontomark dcb19cf839 changed to supabase self hosted
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m14s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m27s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 11m8s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 19m11s
2026-10-14 16:00:34 +02:00
brontomark bc9e0769cd aggiunto download degli allegati e visualizzazione anteprime nella attachmentsection
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m39s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 3m10s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 10m45s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m25s
2026-10-13 11:31:13 +02:00
brontomark 7dd8a3ac71 aggiunto qr dati finanziamento
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m21s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m52s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m55s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m59s
2026-10-10 11:38:07 +02:00
brontomark 70db03066b aggiunto qr dati finanziamento 2026-10-10 11:37:34 +02:00
brontomark addb06a61a fix discriminante system_role / job_title
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 26s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 31s
Build and Release FLUX (Multi-Platform) / build-linux (push) Canceled after 30s
2026-10-09 15:59:47 +02:00
brontomark 5e505d96b3 v
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m4s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m35s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 7m13s
2026-10-09 15:36:25 +02:00
brontomark 66c7094ada possibilità di disattivare staff e altre migliorie 2026-10-09 15:36:06 +02:00
brontomark bd496ad37f c
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m49s
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 2m23s
2026-10-09 15:18:23 +02:00
brontomark 771f1f921b a
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 30s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 36s
Build and Release FLUX (Multi-Platform) / build-linux (push) Canceled after 42s
2026-10-09 12:03:31 +02:00
brontomark 2c02dfcf8b sistemati bug 2026-10-09 12:02:48 +02:00
brontomark 89e5d4014d migliorato upload da mobile 2026-10-09 11:22:11 +02:00
brontomark 8e396a7885 passaggio a pdfrx al posto di pdfx finalmente. Ora i pdf in flux sono compatibili con tutte le piattaforme 2026-10-08 19:13:38 +02:00
brontomark 9b7b4beaa8 v
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m17s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m32s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m43s
2026-10-06 13:16:26 +02:00
brontomark 531b3ba3f2 o
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m31s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 10s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m17s
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
2026-10-06 13:05:53 +02:00
brontomark d0036b729d cambiato tanto
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 48s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m28s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m16s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 11s
2026-10-06 12:10:50 +02:00
brontomark 4d791d2213 risolti diversi crash e aggiunta presa bollette
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 3s
Build and Release FLUX (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-macos (push) Canceled after 0s
Build and Release FLUX (Multi-Platform) / build-web (push) Canceled after 1m1s
2026-10-06 11:59:17 +02:00
brontomark 19fc90b830 a 2026-10-05 13:42:11 +02:00
brontomark 4f0fe7bab5 a 2026-10-04 10:43:03 +02:00
brontomark 7323f68e62 version
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m59s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m24s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m47s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 11m15s
2026-09-24 10:41:53 +02:00
brontomark a33b08a0c3 fix(ci): set User-Agent on Invoke-RestMethod for Windows Supabase update and bump to 2.0.11
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 6m3s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 6m51s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 4m2s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 15m20s
2026-09-21 09:48:09 +02:00
brontomark c8fdd29cf4 v
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m55s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m26s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 9m48s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 11m3s
2026-09-21 09:30:44 +02:00
brontomark 00615b92a0 fix(windows): use {autopf} with PrivilegesRequired=lowest and bump to v2.0.9
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m50s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m21s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 12m2s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m59s
2026-09-19 19:24:11 +02:00
brontomark 832be3d797 feat: supporto latest_version, riga AppImage e gestione aggiornamento facoltativo/obbligatorio
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m53s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m20s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 6m18s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 14m10s
2026-09-19 18:42:34 +02:00
brontomark 72f9d88f96 auto update
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m58s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m22s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 7m41s
Build and Release FLUX (Multi-Platform) / build-macos (push) Has been cancelled
2026-09-19 18:25:30 +02:00
brontomark d4a6b142c5 v
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 3m5s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m50s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m24s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 6m48s
Build and Release FLUX (Multi-Platform) / build-macos (push) Has been cancelled
2026-09-19 17:13:41 +02:00
brontomark 8da4dc9d75 prova
Build and Release FLUX (Multi-Platform) / build-android (push) Failing after 15s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m46s
Build and Release FLUX (Multi-Platform) / build-linux (push) Failing after 1m15s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m44s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 10m4s
2026-09-19 16:51:35 +02:00
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
173 changed files with 23911 additions and 1790 deletions

No files matched your search

+123 -73
View File
@@ -18,6 +18,11 @@ jobs:
run: |
Set-Content -Path ".env" -Value "${{ secrets.ENV_FILE_CONTENT }}"
- name: Pulizia Cache Dart e Download Dipendenze
run: |
if (Test-Path ".dart_tool") { Remove-Item -Recurse -Force ".dart_tool" }
flutter pub get
- name: Build Flutter Windows
run: flutter build windows --release
@@ -49,50 +54,36 @@ jobs:
files: "build/windows/installer/FluxInstaller.exe"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Aggiorna Link Windows su Supabase
run: |
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
$apiKey = "${{ secrets.SUPABASE_SERVICE_KEY }}"
if ([string]::IsNullOrWhiteSpace($apiKey)) {
$apiKey = "sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
}
$body = @{
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
latest_version = $TagVersion
} | ConvertTo-Json -Compress
[System.IO.File]::WriteAllText("$PWD\payload.json", $body, (New-Object System.Text.UTF8Encoding($false)))
curl.exe -i -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.windows" `
-H "apikey: $apiKey" `
-H "Authorization: Bearer $apiKey" `
-H "Content-Type: application/json" `
--data-binary "@payload.json"
Remove-Item -Force "$PWD\payload.json"
- name: Pulisci Workspace Windows
if: always()
run: Remove-Item -Recurse -Force ./*
# -----------------------------------------------------------------
# JOB 2: ANDROID APK (Gira sul tuo MacBook)
# -----------------------------------------------------------------
build-android:
runs-on: macos-runner # <--- Etichetta del tuo Mac
steps:
- name: Checkout del codice
uses: actions/checkout@v3
# Logica Bash per Mac: usiamo le virgolette singole forti per evitare escape strani
- name: Crea file .env
run: |
cat << 'EOF' > .env
${{ secrets.ENV_FILE_CONTENT }}
EOF
- name: Build Flutter APK
run: flutter build apk --release
# Carichiamo l'APK universale o quelli splittati nelle release di Gitea
- name: Upload Android Asset
uses: https://gitea.com/actions/release-action@main
with:
files: "build/app/outputs/flutter-apk/app-release.apk"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Aggiorna Link Android su Supabase
run: |
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.49f18b19-2129-46c0-b690-a97db725b5a8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/app-release.apk\"}"
- name: Aggiorna Link Windows su Supabase
run: |
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.1f888b30-5cbf-4a16-820c-5036a3af0cf8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe\"}"
# -----------------------------------------------------------------
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul tuo MacBook)
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul runner Fedora o Mac)
# -----------------------------------------------------------------
build-web:
runs-on: macos-runner # <--- Etichetta del tuo Mac
runs-on: cross-runner
steps:
- name: Checkout del codice
uses: actions/checkout@v3
@@ -103,6 +94,11 @@ jobs:
${{ secrets.ENV_FILE_CONTENT }}
EOF
- name: Pulizia Cache e Fetch Dipendenze
run: |
rm -rf .dart_tool
flutter pub get
- name: Build Flutter Web
run: flutter build web --release
@@ -114,11 +110,24 @@ jobs:
run: |
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
- name: Aggiorna Versione Web su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.web" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"latest_version\": \"$TagVersion\"}"
# -----------------------------------------------------------------
# JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner)
# JOB 4: LINUX APPIMAGE (Build isolata su Ubuntu 22.04 via Docker)
# -----------------------------------------------------------------
build-linux:
runs-on: cross-runner # <--- Etichetta del tuo runner Linux / Fedora
runs-on: linux-runner # <--- Etichetta del tuo runner Linux in ufficio
steps:
- name: Checkout del codice
uses: actions/checkout@v3
@@ -129,46 +138,87 @@ jobs:
${{ secrets.ENV_FILE_CONTENT }}
EOF
- name: Build Flutter Linux
run: flutter build linux --release
- name: Prepara AppDir per AppImage
- name: Prepara immagine Docker (Ubuntu 22.04 / x86-64-baseline)
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
docker build -t flux-linux-builder -f docker/linux-appimage.Dockerfile docker
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
- name: Build Flutter Linux e Genera AppImage nel container
run: |
if [ ! -f ./appimagetool-x86_64.AppImage ]; then
curl -L -o appimagetool-x86_64.AppImage https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 ./appimagetool-x86_64.AppImage build/Flux.AppDir Flux-x86_64.AppImage
docker run --rm \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
-v "$PWD:/workspace" \
flux-linux-builder
- name: Upload Linux AppImage Asset
uses: https://gitea.com/actions/release-action@main
with:
files: "Flux-x86_64.AppImage"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Aggiorna Link Linux su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.AppImage" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\", \"latest_version\": \"$TagVersion\"}"
# -----------------------------------------------------------------
# JOB 5: MACOS (Gira sul tuo Mac / macos-runner)
# -----------------------------------------------------------------
build-macos:
runs-on: macos-runner
steps:
- name: Checkout del codice
uses: actions/checkout@v3
- name: Crea file .env
run: |
cat << 'EOF' > .env
${{ secrets.ENV_FILE_CONTENT }}
EOF
- name: Pulizia Cache e Fetch Dipendenze
run: |
rm -rf .dart_tool
flutter pub get
- name: Build Flutter macOS
run: flutter build macos --release
- name: Genera DMG e ZIP macOS
run: |
# Crea DMG dell'applicazione
hdiutil create -volname "Flux" -srcfolder "build/macos/Build/Products/Release/flux.app" -ov -format UDZO "Flux-macOS.dmg"
# Crea anche archivio ZIP di backup
cd build/macos/Build/Products/Release
zip -r -y ../../../../Flux-macOS.zip "flux.app"
cd -
- name: Upload macOS Assets
uses: https://gitea.com/actions/release-action@main
with:
files: |
Flux-macOS.dmg
Flux-macOS.zip
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Aggiorna Link macOS su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.macos" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}"
+4
View File
@@ -11,6 +11,10 @@ analyzer:
- "ios/**"
- "macos/**"
- ".dart_tool/**"
- android/**
- web/**
- windows/**
- linux/**
linter:
rules:
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -euo pipefail
SRC_DIR="/tmp/flux-src"
APPDIR="/tmp/Flux.AppDir"
OUT_APPIMAGE="/workspace/Flux-x86_64.AppImage"
rm -rf "${SRC_DIR}" "${APPDIR}"
mkdir -p "${SRC_DIR}"
tar -C /workspace \
--exclude='./.git' \
--exclude='./build' \
--exclude='./.dart_tool' \
--exclude='./*.AppImage' \
--exclude='./*.AppDir' \
--exclude='./appimagetool*' \
-cf - . | tar -C "${SRC_DIR}" -xf -
cd "${SRC_DIR}"
flutter pub get
flutter build linux --release
mkdir -p "${APPDIR}"
cp -r build/linux/x64/release/bundle/* "${APPDIR}/"
cp assets/icon/icon.png "${APPDIR}/flux.png"
cat << 'EOF' > "${APPDIR}/AppRun"
#!/bin/sh
cd "$(dirname "$0")"
exec ./flux "$@"
EOF
chmod +x "${APPDIR}/AppRun"
cat << 'EOF' > "${APPDIR}/Flux.desktop"
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Flux
Exec=flux %u
Icon=flux
Categories=Utility;
EOF
ARCH=x86_64 appimagetool "${APPDIR}" "${OUT_APPIMAGE}"
if [ -n "${HOST_UID:-}" ] && [ -n "${HOST_GID:-}" ]; then
chown "${HOST_UID}:${HOST_GID}" "${OUT_APPIMAGE}"
fi
+45
View File
@@ -0,0 +1,45 @@
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
ca-certificates \
clang \
cmake \
curl \
file \
git \
libgtk-3-dev \
liblzma-dev \
libstdc++-12-dev \
ninja-build \
pkg-config \
unzip \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
ARG FLUTTER_CHANNEL=stable
RUN git config --global --add safe.directory '*' \
&& git clone https://github.com/flutter/flutter.git -b "${FLUTTER_CHANNEL}" --depth 1 /opt/flutter
ENV PATH="/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:${PATH}"
RUN flutter config --no-analytics --enable-linux-desktop \
&& flutter precache --linux
RUN curl -fsSL -o /tmp/appimagetool.AppImage \
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage \
&& chmod +x /tmp/appimagetool.AppImage \
&& cd /opt \
&& /tmp/appimagetool.AppImage --appimage-extract \
&& mv /opt/squashfs-root /opt/appimagetool \
&& ln -s /opt/appimagetool/AppRun /usr/local/bin/appimagetool \
&& rm -f /tmp/appimagetool.AppImage
COPY build-linux-appimage.sh /usr/local/bin/build-linux-appimage.sh
RUN chmod +x /usr/local/bin/build-linux-appimage.sh
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/build-linux-appimage.sh"]
+13 -8
View File
@@ -28,14 +28,19 @@ class SessionCubit extends Cubit<SessionState> {
: super(const SessionState(status: SessionStatus.initial)) {
initializeSession();
// Possiamo metterci in ascolto dei cambiamenti di Auth (Login/Logout)
_supabase.auth.onAuthStateChange.listen((data) {
final AuthChangeEvent event = data.event;
if (event == AuthChangeEvent.signedIn) {
initializeSession();
} else if (event == AuthChangeEvent.signedOut) {
emit(const SessionState(status: SessionStatus.unauthenticated));
}
});
_supabase.auth.onAuthStateChange.listen(
(data) {
final AuthChangeEvent event = data.event;
if (event == AuthChangeEvent.signedIn) {
initializeSession();
} else if (event == AuthChangeEvent.signedOut) {
emit(const SessionState(status: SessionStatus.unauthenticated));
}
},
onError: (error, stackTrace) {
debugPrint('Auth state change error: $error');
},
);
}
Future<void> initializeSession() async {
+3
View File
@@ -5,6 +5,7 @@ class Tables {
static const String campaigns = 'campaigns';
static const String companies = 'companies';
static const String customers = 'customers';
static const String customerOrders = 'customer_orders';
static const String documentSequences = 'document_sequences';
static const String models = 'models';
static const String notes = 'notes';
@@ -18,6 +19,8 @@ class Tables {
static const String staffInStores = 'staff_in_stores';
static const String staffMembers = 'staff_members';
static const String stores = 'stores';
static const String targets = 'targets';
static const String individualTargets = 'individual_targets';
static const String tasks = 'tasks';
static const String taskAssignments = 'task_assignments';
static const String taskReminders = 'task_reminders';
@@ -0,0 +1,106 @@
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
/// Modalità di avviso preferita del cliente (condivisa tra Ordini Clienti e Ticket Assistenza)
enum ContactPreference {
whatsappPrimary(
value: 'whatsapp_primary',
label: 'WhatsApp (Principale)',
shortLabel: 'WA Principale',
materialIcon: Icons.chat_bubble_outline_rounded,
color: Colors.green,
usesAlternativePhone: false,
isWhatsapp: true,
isCall: false,
isEmail: false,
),
whatsappAlternative(
value: 'whatsapp_alternative',
label: 'WhatsApp (Recapito Alternativo)',
shortLabel: 'WA Alternativo',
materialIcon: Icons.chat_bubble_outline_rounded,
color: Colors.teal,
usesAlternativePhone: true,
isWhatsapp: true,
isCall: false,
isEmail: false,
),
callPrimary(
value: 'call_primary',
label: 'Telefonata (Principale)',
shortLabel: 'Tel. Principale',
materialIcon: Icons.phone_outlined,
color: Colors.blue,
usesAlternativePhone: false,
isWhatsapp: false,
isCall: true,
isEmail: false,
),
callAlternative(
value: 'call_alternative',
label: 'Telefonata (Recapito Alternativo)',
shortLabel: 'Tel. Alternativo',
materialIcon: Icons.phone_forwarded_outlined,
color: Colors.indigo,
usesAlternativePhone: true,
isWhatsapp: false,
isCall: true,
isEmail: false,
),
email(
value: 'email',
label: 'Email',
shortLabel: 'Email',
materialIcon: Icons.alternate_email_rounded,
color: Colors.deepOrange,
usesAlternativePhone: false,
isWhatsapp: false,
isCall: false,
isEmail: true,
);
final String value;
final String label;
final String shortLabel;
final IconData materialIcon;
final Color color;
final bool usesAlternativePhone;
final bool isWhatsapp;
final bool isCall;
final bool isEmail;
const ContactPreference({
required this.value,
required this.label,
required this.shortLabel,
required this.materialIcon,
required this.color,
required this.usesAlternativePhone,
required this.isWhatsapp,
required this.isCall,
required this.isEmail,
});
Widget buildIcon({double size = 16, Color? overrideColor}) {
final c = overrideColor ?? color;
if (isWhatsapp) {
return FaIcon(FontAwesomeIcons.whatsapp, size: size, color: c);
}
return Icon(materialIcon, size: size, color: c);
}
static ContactPreference fromString(
String? val, {
ContactPreference fallback = ContactPreference.whatsappPrimary,
}) {
if (val == null || val.trim().isEmpty) return fallback;
final clean = val.trim().toLowerCase();
for (final item in ContactPreference.values) {
if (item.value.toLowerCase() == clean ||
item.name.toLowerCase() == clean) {
return item;
}
}
return fallback;
}
}
+43 -6
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/core/widgets/app_version_label.dart';
import 'package:go_router/go_router.dart';
// ==========================================
@@ -142,11 +143,24 @@ class _AppMenuState extends State<AppMenu> {
Routes.tickets,
'/tickets',
),
_SubMenuItem(
'Ordini Clienti',
Routes.customerOrders,
'/orders',
),
_SubMenuItem('Tasks', Routes.tasks, '/tasks'),
_SubMenuItem('Sticky Notes', Routes.notes, '/notes'),
],
),
const SizedBox(height: 8),
_buildRouteItem(
title: 'Obiettivi',
icon: Icons.track_changes_outlined,
routeName: Routes.targets,
pathToCheck: '/targets',
isCollapsed: effectivelyCollapsed,
),
const SizedBox(height: 8),
// --- IL MENU GERARCHICO (ANAGRAFICHE) ---
@@ -189,6 +203,12 @@ class _AppMenuState extends State<AppMenu> {
),
),
// --- VERSIONE APP CON HYPERLINK ---
Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: AppVersionLabel(isCollapsed: effectivelyCollapsed),
),
// --- PULSANTE TOGGLE (Solo Desktop) ---
if (!widget.isDrawer)
Padding(
@@ -249,7 +269,9 @@ class _AppMenuState extends State<AppMenu> {
),
child: Icon(
icon,
color: isSelected ? theme.colorScheme.primary : null,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant,
),
),
),
@@ -262,11 +284,19 @@ class _AppMenuState extends State<AppMenu> {
alpha: 0.4,
),
selected: isSelected,
leading: Icon(icon, color: isSelected ? theme.colorScheme.primary : null),
leading: Icon(
icon,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant,
),
title: Text(
title,
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurface,
),
maxLines: 1,
overflow: TextOverflow.clip,
@@ -313,7 +343,7 @@ class _AppMenuState extends State<AppMenu> {
: FontWeight.normal,
color: widget.currentPath == item.pathToCheck
? theme.colorScheme.primary
: null,
: theme.colorScheme.onSurface,
),
),
),
@@ -330,7 +360,9 @@ class _AppMenuState extends State<AppMenu> {
),
child: Icon(
icon,
color: isSelected ? theme.colorScheme.primary : null,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant,
),
),
);
@@ -344,12 +376,17 @@ class _AppMenuState extends State<AppMenu> {
tilePadding: const EdgeInsets.symmetric(horizontal: 16),
leading: Icon(
icon,
color: isSelected ? theme.colorScheme.primary : null,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant,
),
title: Text(
title,
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurface,
),
maxLines: 1,
overflow: TextOverflow.clip,
@@ -375,7 +412,7 @@ class _AppMenuState extends State<AppMenu> {
: FontWeight.normal,
color: isSubSelected
? theme.colorScheme.primary
: theme.textTheme.bodyMedium?.color,
: theme.colorScheme.onSurface,
),
maxLines: 1,
overflow: TextOverflow.clip,
+163 -3
View File
@@ -12,15 +12,23 @@ import 'package:flux/features/auth/ui/auth_screen.dart';
import 'package:flux/features/auth/ui/set_password_screen.dart';
import 'package:flux/features/company/bloc/company_settings_cubit.dart';
import 'package:flux/features/company/ui/company_settings_screen.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_form_cubit.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/ui/customer_order_form_screen.dart';
import 'package:flux/features/customer_orders/ui/customer_order_list_screen.dart';
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/customers/ui/customer_detail_screen.dart';
import 'package:flux/features/customers/ui/customer_form_screen.dart';
import 'package:flux/features/customers/ui/customers_list_screen.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
import 'package:flux/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart';
import 'package:flux/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart';
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
import 'package:flux/features/home/dashboard_task_list/blocs/dashboard_task_list_cubit.dart';
import 'package:flux/features/home/ui/home_screen.dart';
import 'package:flux/features/master_data/master_data_hub_content.dart';
@@ -45,6 +53,8 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/ui/financing_form_screen.dart';
import 'package:flux/features/operations/ui/operation_form_screen.dart';
import 'package:flux/features/operations/ui/operation_list_screen.dart';
import 'package:flux/features/settings/blocs/reminder_defaults_cubit.dart';
@@ -61,8 +71,18 @@ import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/tickets/ui/ticket_form_screen.dart';
import 'package:flux/features/tickets/ui/ticket_list_screen.dart';
import 'package:flux/features/tickets/ui/ticket_workspace/ticket_workspace_screen.dart';
import 'package:flux/features/targets/blocs/target_form_cubit.dart';
import 'package:flux/features/targets/blocs/target_list_cubit.dart';
import 'package:flux/features/targets/data/targets_repository.dart';
import 'package:flux/features/targets/models/target_model.dart';
import 'package:flux/features/targets/blocs/target_detail_cubit.dart';
import 'package:flux/features/targets/ui/target_detail_screen.dart';
import 'package:flux/features/targets/ui/target_form_screen.dart';
import 'package:flux/features/targets/ui/target_list_screen.dart';
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
import 'package:flux/features/tracking/models/tracking_model.dart';
import 'package:flux/service_locator.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
@@ -84,8 +104,13 @@ class AppRouter {
final isGoingToSetPassword = state.matchedLocation == '/set-password';
// 1. LA PASSATOIA VIP (DEVE ESSERE IN CIMA)
// Usiamo state.uri.path perché state.matchedLocation a volte fa i capricci coi deep link iniziali
final isPublicRoute = state.uri.path.startsWith('/upload');
// Usiamo sia state.uri.path che state.matchedLocation per sicurezza con i deep link
final path = state.uri.path;
final matched = state.matchedLocation;
final isPublicRoute = path.startsWith('/upload') ||
path.startsWith('/financing') ||
matched.startsWith('/upload') ||
matched.startsWith('/financing');
if (isPublicRoute) {
// Ritorna null esplicitamente per dire al router "Rimani qui e non fare altri controlli"
@@ -100,6 +125,9 @@ class AppRouter {
if (sessionState.status == SessionStatus.unauthenticated) {
// Se sta già andando alle uniche altre pagine pubbliche, lascialo andare
if (isGoingToLogin || isGoingToSetPassword) return null;
if (path != '/' && path.isNotEmpty) {
pendingRoute = state.uri.toString();
}
// Altrimenti bloccalo e mandalo al login
return '/login';
}
@@ -141,6 +169,14 @@ class AppRouter {
child: const OnboardingScreen(),
),
),
GoRoute(
path: '/financing/:sessionId',
name: Routes.financing,
builder: (context, state) {
final sessionId = state.pathParameters['sessionId'] ?? '';
return FinancingFormScreen(sessionId: sessionId);
},
),
// --- CORE APP (DENTRO LA SHELL CON NAVIGATION BAR/RAIL) ---
ShellRoute(
@@ -179,6 +215,25 @@ class AppRouter {
staffId: sessionCubit.state.currentStaffMember?.id,
),
),
BlocProvider<DashboardTargetProgressCubit>(
create: (context) => DashboardTargetProgressCubit(
companyId: sessionCubit.state.company?.id,
storeId: sessionCubit.state.currentStore?.id,
staffId: sessionCubit.state.currentStaffMember?.id,
),
),
BlocProvider<DashboardExpiringContractsCubit>(
create: (context) => DashboardExpiringContractsCubit(
companyId: sessionCubit.state.company?.id,
storeId: sessionCubit.state.currentStore?.id,
),
),
BlocProvider<DashboardDailyRicontattiCubit>(
create: (context) => DashboardDailyRicontattiCubit(
companyId: sessionCubit.state.company?.id,
storeId: sessionCubit.state.currentStore?.id,
),
),
],
child: const HomeScreen(),
);
@@ -271,13 +326,30 @@ class AppRouter {
GoRoute(
path: '/operations',
name: Routes.operations,
builder: (context, state) => const OperationListScreen(),
builder: (context, state) {
final params = state.extra is OperationFilterParams
? state.extra as OperationFilterParams
: OperationFilterParams.fromQueryParams(
state.uri.queryParameters,
);
return OperationListScreen(
initialFilters: params.isNotEmpty ? params : null,
);
},
),
GoRoute(
path: '/tickets',
name: Routes.tickets,
builder: (context, state) => const TicketListScreen(),
),
GoRoute(
path: '/orders',
name: Routes.customerOrders,
builder: (context, state) => BlocProvider(
create: (_) => sl<CustomerOrderListCubit>(),
child: const CustomerOrderListScreen(),
),
),
GoRoute(
path: '/notes',
name: Routes.notes,
@@ -311,10 +383,52 @@ class AppRouter {
);
},
),
GoRoute(
path: '/targets',
name: Routes.targets,
builder: (context, state) => BlocProvider(
create: (_) => sl<TargetListCubit>(),
child: const TargetListScreen(),
),
),
],
),
// --- DETTAGLI E OPERATIVITÀ (FUORI DALLA SHELL - TUTTO SCHERMO) ---
GoRoute(
path: '/targets/form',
name: Routes.targetForm,
builder: (context, state) {
final existingTarget = state.extra as TargetModel?;
final session = context.read<SessionCubit>().state;
final companyId = session.company?.id ?? '';
final defaultStoreId = session.currentStore?.id ?? '';
return BlocProvider<TargetFormCubit>(
create: (context) => TargetFormCubit(
targetsRepository: sl<TargetsRepository>(),
staffRepository: sl<StaffRepository>(),
staffCubit: context.read<StaffCubit>(),
)..init(
initialTarget: existingTarget,
companyId: companyId,
defaultStoreId: defaultStoreId,
),
child: const TargetFormScreen(),
);
},
),
GoRoute(
path: '/targets/detail',
name: Routes.targetDetail,
builder: (context, state) {
final target = state.extra as TargetModel;
return BlocProvider<TargetDetailCubit>(
create: (context) => TargetDetailCubit(target: target)..init(),
child: TargetDetailScreen(target: target),
);
},
),
GoRoute(
path: '/providers/form',
name: Routes.providerForm,
@@ -520,6 +634,52 @@ class AppRouter {
},
),
GoRoute(
path: '/orders/form/:id',
name: Routes.customerOrderForm,
builder: (context, state) {
final String pathId = state.pathParameters['id'] ?? 'new';
final record =
state.extra
as ({
StaffMemberModel? createdBy,
CustomerOrderModel? order,
})?;
final String? realOrderId;
if (pathId == 'new') {
realOrderId = null;
} else if (record?.order?.id != null) {
realOrderId = record!.order!.id;
} else {
realOrderId = pathId;
}
context.read<CustomersListCubit>().loadCustomers();
return MultiBlocProvider(
providers: [
BlocProvider(
create: (_) => AttachmentsBloc(
parentId: realOrderId,
parentType: AttachmentParentType.customerOrder,
),
),
BlocProvider(
create: (_) => CustomerOrderFormCubit(
createdBy: record?.createdBy,
existingOrder: record?.order,
),
),
],
child: CustomerOrderFormScreen(
orderId: realOrderId,
order: record?.order,
),
);
},
),
GoRoute(
path: '/upload/:type/:id',
name: Routes.upload,
+6
View File
@@ -27,4 +27,10 @@ class Routes {
static const String tasks = 'tasks';
static const String taskForm = 'task-form';
static const String reminderSettings = 'reminder-settings';
static const String targets = 'targets';
static const String targetForm = 'target-form';
static const String targetDetail = 'target-detail';
static const String financing = 'financing';
static const String customerOrders = 'customer-orders';
static const String customerOrderForm = 'customer-order-form';
}
+36 -12
View File
@@ -104,11 +104,25 @@ ThemeData fluxDarkTheme = ThemeData(
),
),
drawerTheme: const DrawerThemeData(
backgroundColor: FluxColors.darkSurface,
surfaceTintColor: Colors.transparent,
),
expansionTileTheme: const ExpansionTileThemeData(
iconColor: FluxColors.accentTurquoise,
collapsedIconColor: FluxColors.darkTextSecondary,
textColor: FluxColors.darkTextPrimary,
collapsedTextColor: FluxColors.darkTextPrimary,
),
listTileTheme: ListTileThemeData(
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
// Colore dell'icona (Turchese Flux)
iconColor: FluxColors.accentTurquoise,
selectedColor: FluxColors.primaryBlue,
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.15),
// Colore del testo
titleTextStyle: GoogleFonts.poppins(
color: FluxColors.darkTextPrimary,
@@ -121,9 +135,6 @@ ThemeData fluxDarkTheme = ThemeData(
),
// Per far apparire la "manina" su Web/Desktop
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
// NOTA: Se overlayColor non esiste, Flutter userà i colori
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
),
elevatedButtonTheme: ElevatedButtonThemeData(
@@ -189,26 +200,37 @@ ThemeData fluxLightTheme = ThemeData(
),
),
drawerTheme: const DrawerThemeData(
backgroundColor: FluxColors.lightSurface,
surfaceTintColor: Colors.transparent,
),
expansionTileTheme: const ExpansionTileThemeData(
iconColor: FluxColors.accentTurquoise,
collapsedIconColor: FluxColors.lightTextSecondary,
textColor: FluxColors.lightTextPrimary,
collapsedTextColor: FluxColors.lightTextPrimary,
),
listTileTheme: ListTileThemeData(
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
// Colore dell'icona (Turchese Flux)
iconColor: FluxColors.accentTurquoise,
// Colore del testo
selectedColor: FluxColors.primaryBlue,
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.1),
// Colore del testo per il tema chiaro
titleTextStyle: GoogleFonts.poppins(
color: FluxColors.darkTextPrimary,
color: FluxColors.lightTextPrimary,
fontSize: 16,
fontWeight: FontWeight.w500,
),
subtitleTextStyle: GoogleFonts.poppins(
color: FluxColors.darkTextSecondary,
color: FluxColors.lightTextSecondary,
fontSize: 13,
),
// Per far apparire la "manina" su Web/Desktop
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
// NOTA: Se overlayColor non esiste, Flutter userà i colori
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
),
// Il pulsante principale rimane Blu Elettrico, molto visibile
@@ -260,12 +282,14 @@ extension FluxThemeContext on BuildContext {
// --- Testi (La parte mancante) ---
// Mappiamo primaryText sul colore del titolo e secondaryText su quello del corpo
Color get primaryText =>
Theme.of(this).textTheme.titleLarge?.color ?? Colors.white;
Theme.of(this).textTheme.titleLarge?.color ??
Theme.of(this).colorScheme.onSurface;
Color get secondaryText =>
Theme.of(this).textTheme.bodyMedium?.color ?? Colors.grey;
Theme.of(this).textTheme.bodyMedium?.color ??
Theme.of(this).colorScheme.onSurfaceVariant;
// Opzionale: un colore ancora più tenue per suggerimenti o icone disabilitate
Color get hintText =>
Theme.of(this).textTheme.bodySmall?.color ??
Colors.grey.withValues(alpha: 0.5);
Theme.of(this).colorScheme.onSurface.withValues(alpha: 0.5);
}
+164
View File
@@ -0,0 +1,164 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
class AutoUpdateService {
/// Verifica se la piattaforma corrente supporta l'aggiornamento automatico trasparente
static bool get isAutoUpdateSupported {
if (kIsWeb) return false;
if (Platform.isWindows) return true;
if (Platform.isLinux && Platform.environment['APPIMAGE'] != null) {
return true;
}
return false;
}
/// Scarica l'aggiornamento e lo applica in modo silenzioso
static Future<void> downloadAndApplyUpdate({
required String downloadUrl,
required void Function(double progress, String status) onProgress,
}) async {
if (kIsWeb) {
throw UnsupportedError("L'auto-update non è supportato su Web.");
}
if (Platform.isWindows) {
await _updateWindows(downloadUrl, onProgress);
} else if (Platform.isLinux) {
await _updateLinux(downloadUrl, onProgress);
} else {
throw UnsupportedError("Piattaforma non supportata per l'auto-update.");
}
}
/// Gestione aggiornamento Windows
static Future<void> _updateWindows(
String downloadUrl,
void Function(double progress, String status) onProgress,
) async {
final tempDir = Directory.systemTemp;
final installerFile = File('${tempDir.path}\\FluxInstaller_Update.exe');
if (installerFile.existsSync()) {
try {
installerFile.deleteSync();
} catch (_) {}
}
onProgress(0.0, "Download aggiornamento in corso...");
await _downloadFile(downloadUrl, installerFile, onProgress);
onProgress(1.0, "Installazione e riavvio in corso...");
await Future.delayed(const Duration(milliseconds: 500));
// Lancia l'installer in modalità silenziosa per utente singolo
// /VERYSILENT: nessuna interfaccia
// /SUPPRESSMSGBOXES: nessun popup
// /NORESTART: non riavvia il PC
await Process.start(
installerFile.path,
['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'],
mode: ProcessStartMode.detached,
);
// Chiude l'applicazione per consentire la sostituzione dei file
exit(0);
}
/// Gestione aggiornamento Linux (AppImage in-place)
static Future<void> _updateLinux(
String downloadUrl,
void Function(double progress, String status) onProgress,
) async {
final currentAppImagePath = Platform.environment['APPIMAGE'];
if (currentAppImagePath == null) {
throw StateError(
"L'applicazione non è in esecuzione come AppImage.",
);
}
final newAppImageFile = File('$currentAppImagePath.new');
if (newAppImageFile.existsSync()) {
try {
newAppImageFile.deleteSync();
} catch (_) {}
}
onProgress(0.0, "Download nuova versione in corso...");
await _downloadFile(downloadUrl, newAppImageFile, onProgress);
onProgress(1.0, "Finalizzazione e riavvio...");
await Future.delayed(const Duration(milliseconds: 300));
// Assegna il permesso di esecuzione
await Process.run('chmod', ['+x', newAppImageFile.path]);
// Sostituzione atomica del vecchio file AppImage con il nuovo
newAppImageFile.renameSync(currentAppImagePath);
// Rilancia la nuova versione
await Process.start(
currentAppImagePath,
[],
mode: ProcessStartMode.detached,
);
// Termina il processo attuale
exit(0);
}
/// Download in streaming con tracciamento del progresso
static Future<void> _downloadFile(
String url,
File destinationFile,
void Function(double progress, String status) onProgress,
) async {
final client = HttpClient();
client.autoUncompress = true;
try {
final uri = Uri.parse(url);
final request = await client.getUrl(uri);
final response = await request.close();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw HttpException(
'Download fallito con codice di stato ${response.statusCode}',
uri: uri,
);
}
final contentLength = response.contentLength;
int downloadedBytes = 0;
final sink = destinationFile.openWrite();
await for (final chunk in response) {
sink.add(chunk);
downloadedBytes += chunk.length;
if (contentLength > 0) {
final progress = (downloadedBytes / contentLength).clamp(0.0, 1.0);
final percent = (progress * 100).toStringAsFixed(0);
final downloadedMb =
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
final totalMb = (contentLength / (1024 * 1024)).toStringAsFixed(1);
onProgress(
progress,
'Scaricamento: $percent% ($downloadedMb MB di $totalMb MB)',
);
} else {
final downloadedMb =
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
onProgress(0.5, 'Scaricamento in corso ($downloadedMb MB)...');
}
}
await sink.flush();
await sink.close();
} finally {
client.close();
}
}
}
+149
View File
@@ -0,0 +1,149 @@
import 'dart:typed_data';
import 'package:image/image.dart' as img;
/// Utilità per la gestione delle immagini e normalizzazione dell'orientamento EXIF.
class ImageUtils {
/// Verifica se l'estensione corrisponde a un'immagine supportata.
static bool isImageExtension(String? extension) {
if (extension == null) return false;
final ext = extension.toLowerCase().replaceAll('.', '');
return ['jpg', 'jpeg', 'png', 'webp', 'bmp'].contains(ext);
}
/// Verifica se un nome file o percorso è un'immagine supportata.
static bool isImagePath(String path) {
final dotIndex = path.lastIndexOf('.');
if (dotIndex == -1 || dotIndex == path.length - 1) return false;
return isImageExtension(path.substring(dotIndex + 1));
}
/// Ruota fisicamente i pixel dell'immagine se contiene metadati EXIF di orientamento
/// (tipico delle fotocamere degli smartphone), resettando l'orientamento a 1 (normale).
/// Se l'immagine è già dritta o non possiede metadati EXIF, restituisce i byte originali.
static Uint8List normalizeOrientation(Uint8List bytes, {String? extension}) {
try {
final image = img.decodeImage(bytes);
if (image == null) return bytes;
// Se non ha tag di orientamento o è già orientata dritta (1)
if (!image.exif.imageIfd.hasOrientation || image.exif.imageIfd.orientation == 1) {
return bytes;
}
// Applica la rotazione fisica dei pixel e resetta il tag EXIF
final baked = img.bakeOrientation(image);
final ext = extension?.toLowerCase().replaceAll('.', '');
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
if (isPng) {
return Uint8List.fromList(img.encodePng(baked));
} else {
return Uint8List.fromList(img.encodeJpg(baked, quality: 92));
}
} catch (_) {
// In caso di errore di parsing/decodifica, restituisce i byte inalterati
return bytes;
}
}
/// Ruota fisicamente i byte di un'immagine di un numero di quarti di giro (90° * quarterTurns).
static Uint8List rotateBytes(
Uint8List bytes, {
required int quarterTurns,
String? extension,
}) {
final turns = quarterTurns % 4;
if (turns == 0) return bytes;
try {
final image = img.decodeImage(bytes);
if (image == null) return bytes;
final angle = turns * 90;
final rotated = img.copyRotate(image, angle: angle);
final ext = extension?.toLowerCase().replaceAll('.', '');
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
if (isPng) {
return Uint8List.fromList(img.encodePng(rotated));
} else {
return Uint8List.fromList(img.encodeJpg(rotated, quality: 92));
}
} catch (_) {
return bytes;
}
}
/// Ottimizza e comprime un'immagine per l'esportazione in PDF (es. portali TIM).
/// Normalizza l'orientamento EXIF, ridimensiona proporzionalmente se supera [maxDimension]
/// e codifica in JPEG con qualità [quality] per ridurre drasticamente il peso del PDF.
static Uint8List compressForPdf(
Uint8List bytes, {
int maxDimension = 1800,
int quality = 78,
}) {
try {
final decoded = img.decodeImage(bytes);
if (decoded == null) return bytes;
var processed = decoded;
if (processed.exif.imageIfd.hasOrientation &&
processed.exif.imageIfd.orientation != 1) {
processed = img.bakeOrientation(processed);
}
if (processed.width > maxDimension || processed.height > maxDimension) {
processed = _resizeToMaxDimension(processed, maxDimension);
}
return Uint8List.fromList(img.encodeJpg(processed, quality: quality));
} catch (_) {
return bytes;
}
}
/// Converte i pixel grezzi BGRA8888 (es. renderizzati da pdfrx) in un JPEG compresso
/// pronto per l'inserimento nel PDF, evitando il passaggio per PNG lossless.
static Uint8List encodeBgraPixelsToJpg(
Uint8List bgraPixels, {
required int width,
required int height,
int maxDimension = 1800,
int quality = 78,
}) {
var image = img.Image.fromBytes(
width: width,
height: height,
bytes: bgraPixels.buffer,
numChannels: 4,
order: img.ChannelOrder.bgra,
);
if (image.width > maxDimension || image.height > maxDimension) {
image = _resizeToMaxDimension(image, maxDimension);
}
return Uint8List.fromList(img.encodeJpg(image, quality: quality));
}
static img.Image _resizeToMaxDimension(img.Image source, int maxDimension) {
final aspectRatio = source.width / source.height;
final int targetWidth;
final int targetHeight;
if (source.width >= source.height) {
targetWidth = maxDimension;
targetHeight = (maxDimension / aspectRatio).round();
} else {
targetHeight = maxDimension;
targetWidth = (maxDimension * aspectRatio).round();
}
return img.copyResize(
source,
width: targetWidth,
height: targetHeight,
interpolation: img.Interpolation.linear,
);
}
}
+282
View File
@@ -0,0 +1,282 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flux/core/utils/auto_update_service.dart';
import 'package:flux/core/utils/version_check_service.dart';
import 'package:universal_html/html.dart' as html;
import 'package:url_launcher/url_launcher.dart';
class UpdatePromptHelper {
/// Avvia una verifica manuale degli aggiornamenti con feedback visivo immediato
static Future<void> showManualUpdateCheck(BuildContext context) async {
// Feedback immediato tramite SnackBar
final messenger = ScaffoldMessenger.of(context);
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
const SnackBar(
content: Row(
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
),
SizedBox(width: 12),
Text("Verifica aggiornamenti in corso..."),
],
),
duration: Duration(seconds: 2),
),
);
try {
final currentVersion = await VersionCheckService.getShortVersionString();
final updateInfo = await VersionCheckService().checkUpdate();
if (!context.mounted) return;
messenger.hideCurrentSnackBar();
if (updateInfo != null && updateInfo.hasUpdate) {
// Nuova versione disponibile: mostra il dialog informativo e di azione
showDialog(
context: context,
barrierDismissible: !updateInfo.isMandatory,
builder: (dialogContext) => _ManualUpdateDialog(
updateInfo: updateInfo,
currentVersion: currentVersion,
),
);
} else {
// Nessun aggiornamento: l'app è già all'ultima versione
messenger.showSnackBar(
SnackBar(
backgroundColor: Colors.green.shade700,
content: Row(
children: [
const Icon(Icons.check_circle_outline, color: Colors.white),
const SizedBox(width: 12),
Expanded(
child: Text(
"Flux è aggiornato all'ultima versione disponibile ($currentVersion).",
style: const TextStyle(color: Colors.white),
),
),
],
),
duration: const Duration(seconds: 4),
),
);
}
} catch (e) {
if (!context.mounted) return;
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
SnackBar(
backgroundColor: Colors.red.shade700,
content: Row(
children: [
const Icon(Icons.error_outline, color: Colors.white),
const SizedBox(width: 12),
Expanded(
child: Text(
"Impossibile verificare gli aggiornamenti: $e",
style: const TextStyle(color: Colors.white),
),
),
],
),
duration: const Duration(seconds: 4),
),
);
}
}
}
class _ManualUpdateDialog extends StatefulWidget {
final UpdateInfo updateInfo;
final String currentVersion;
const _ManualUpdateDialog({
required this.updateInfo,
required this.currentVersion,
});
@override
State<_ManualUpdateDialog> createState() => _ManualUpdateDialogState();
}
class _ManualUpdateDialogState extends State<_ManualUpdateDialog> {
bool _isUpdating = false;
double _downloadProgress = 0.0;
String _statusMessage = "";
String? _errorMessage;
Future<void> _startUpdate() async {
setState(() {
_isUpdating = true;
_errorMessage = null;
_downloadProgress = 0.0;
_statusMessage = "Avvio aggiornamento...";
});
try {
await AutoUpdateService.downloadAndApplyUpdate(
downloadUrl: widget.updateInfo.downloadUrl,
onProgress: (progress, status) {
if (mounted) {
setState(() {
_downloadProgress = progress;
_statusMessage = status;
});
}
},
);
} catch (e) {
if (mounted) {
setState(() {
_isUpdating = false;
_errorMessage = "Errore durante l'aggiornamento: $e";
});
}
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final updateInfo = widget.updateInfo;
return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: Row(
children: [
Icon(
updateInfo.isMandatory
? Icons.warning_amber_rounded
: (kIsWeb ? Icons.cached : Icons.system_update),
color: updateInfo.isMandatory ? Colors.amber[700] : Colors.blue,
size: 28,
),
const SizedBox(width: 12),
Expanded(
child: Text(
updateInfo.isMandatory
? "Aggiornamento Obbligatorio"
: "Nuova Versione Disponibile",
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
],
),
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text.rich(
TextSpan(
style: const TextStyle(fontSize: 14),
children: [
const TextSpan(text: "Versione installata: "),
TextSpan(
text: widget.currentVersion,
style: const TextStyle(fontWeight: FontWeight.bold),
),
const TextSpan(text: "\nNuova versione disponibile: "),
TextSpan(
text: "v${updateInfo.latestVersion}",
style: TextStyle(
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
],
),
),
const SizedBox(height: 12),
Text(
kIsWeb
? "È stata rilasciata una nuova versione. Ricarica la pagina per applicarla."
: (updateInfo.isMandatory
? "La versione attuale non è più supportata. Aggiorna all'ultima versione per continuare a lavorare."
: "Vuoi scaricare e installare l'aggiornamento adesso?"),
style: TextStyle(
fontSize: 14,
color: theme.colorScheme.onSurface.withValues(alpha: 0.8),
),
),
if (_errorMessage != null) ...[
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
),
child: Text(
_errorMessage!,
style: const TextStyle(color: Colors.red, fontSize: 13),
),
),
],
if (_isUpdating) ...[
const SizedBox(height: 16),
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: LinearProgressIndicator(
value: _downloadProgress > 0 ? _downloadProgress : null,
minHeight: 8,
),
),
const SizedBox(height: 8),
Text(
_statusMessage,
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurface.withValues(alpha: 0.7),
),
),
],
],
),
),
actions: _isUpdating
? []
: [
if (!updateInfo.isMandatory)
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text("PIÙ TARDI"),
),
if (kIsWeb)
FilledButton.icon(
icon: const Icon(Icons.refresh),
label: const Text("RICARICA ORA"),
onPressed: () {
html.window.location.reload();
},
)
else if (AutoUpdateService.isAutoUpdateSupported)
FilledButton.icon(
icon: const Icon(Icons.system_update_alt),
label: const Text("AGGIORNA ORA"),
onPressed: _startUpdate,
)
else
FilledButton.icon(
icon: const Icon(Icons.open_in_browser),
label: const Text("SCARICA"),
onPressed: () async {
final url = Uri.parse(updateInfo.downloadUrl);
await launchUrl(url, mode: LaunchMode.externalApplication);
if (context.mounted) Navigator.of(context).pop();
},
),
],
);
}
}
+122 -55
View File
@@ -3,46 +3,86 @@ import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
enum UpdateType {
none,
optional,
mandatory,
}
class UpdateInfo {
final UpdateType type;
final String latestVersion;
final String minVersion;
final String downloadUrl;
const UpdateInfo({
required this.type,
required this.latestVersion,
required this.minVersion,
required this.downloadUrl,
});
bool get isMandatory => type == UpdateType.mandatory;
bool get isOptional => type == UpdateType.optional;
bool get hasUpdate => type != UpdateType.none;
}
class VersionCheckService {
Future<String?> checkForceUpdate() async {
Future<UpdateInfo?> checkUpdate() async {
try {
// 1. Capiamo su che piattaforma sta girando l'app in questo istante
String currentPlatform = _getCurrentPlatform();
final platformAliases = _getPlatformAliases();
// 2. Recuperiamo SOLO la riga corrispondente alla nostra piattaforma
final dbResponse = await Supabase.instance.client
.from('app_config')
.select('min_version, download_url')
.eq('platform', currentPlatform)
.maybeSingle(); // Usiamo maybeSingle così se non c'è la riga non crasha
.select('platform, min_version, latest_version, download_url');
if (dbResponse == null) {
return null; // Nessuna regola per questa piattaforma
if (dbResponse.isEmpty) {
return null;
}
String minVersionFromDb = dbResponse['min_version'] as String;
String downloadUrl = dbResponse['download_url'] as String;
final rows = List<Map<String, dynamic>>.from(dbResponse);
final config = rows.firstWhere(
(r) {
final p = (r['platform'] as String?)?.toLowerCase().trim() ?? '';
return platformAliases.any((alias) => alias.toLowerCase() == p);
},
orElse: () => {},
);
// 3. Recuperiamo la versione locale di Flutter
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String localVersionRaw = packageInfo.version;
if (config.isEmpty) {
return null;
}
// 🥷 TRUCCO 1: Pulizia totale dai build number (+37) o tag "v"
String cleanLocal = localVersionRaw
.split('+')
.first
.replaceAll('v', '')
.trim();
String cleanDb = minVersionFromDb
.split('+')
.first
.replaceAll('v', '')
.trim();
final minVersionRaw = (config['min_version'] as String?) ?? '0.0.0';
final latestVersionRaw =
(config['latest_version'] as String?) ?? minVersionRaw;
final downloadUrl = (config['download_url'] as String?) ?? '';
// 🥷 TRUCCO 2: Confronto Semantico Reale
if (_isVersionLower(current: cleanLocal, minimum: cleanDb)) {
// Ritorna il link VERO per questa specifica piattaforma preso dal CSV!
return downloadUrl;
final packageInfo = await PackageInfo.fromPlatform();
final localVersionRaw = packageInfo.version;
final cleanLocal = _cleanVersion(localVersionRaw);
final cleanMin = _cleanVersion(minVersionRaw);
final cleanLatest = _cleanVersion(latestVersionRaw);
// Se la versione locale è inferiore alla minima ammessa -> obbligatorio
if (_isVersionLower(current: cleanLocal, target: cleanMin)) {
return UpdateInfo(
type: UpdateType.mandatory,
latestVersion: latestVersionRaw,
minVersion: minVersionRaw,
downloadUrl: downloadUrl,
);
}
// Se è >= della minima ma inferiore all'ultima disponibile -> facoltativo
if (_isVersionLower(current: cleanLocal, target: cleanLatest)) {
return UpdateInfo(
type: UpdateType.optional,
latestVersion: latestVersionRaw,
minVersion: minVersionRaw,
downloadUrl: downloadUrl,
);
}
return null;
@@ -52,43 +92,70 @@ class VersionCheckService {
}
}
// Helper ninja per mappare le piattaforme in base alle stringhe del tuo DB
String _getCurrentPlatform() {
if (kIsWeb) return 'web';
if (Platform.isAndroid) return 'android';
if (Platform.isIOS) return 'ios';
if (Platform.isWindows) return 'windows';
if (Platform.isMacOS) return 'macos';
if (Platform.isLinux) return 'linux';
return 'unknown';
Future<String?> checkForceUpdate() async {
final info = await checkUpdate();
return info?.isMandatory == true ? info?.downloadUrl : null;
}
// Il motore matematico (resta invariato)
bool _isVersionLower({required String current, required String minimum}) {
if (current == minimum) return false;
static Future<String> getAppVersionString() async {
try {
final info = await PackageInfo.fromPlatform();
return info.buildNumber.isNotEmpty
? 'v${info.version}+${info.buildNumber}'
: 'v${info.version}';
} catch (_) {
return '';
}
}
List<int> currentParts = current
static Future<String> getFullVersionString() => getAppVersionString();
static Future<String> getShortVersionString() async {
try {
final info = await PackageInfo.fromPlatform();
return 'v${info.version}';
} catch (_) {
return '';
}
}
String _cleanVersion(String raw) {
return raw.split('+').first.replaceAll('v', '').trim();
}
List<String> _getPlatformAliases() {
if (kIsWeb) return const ['web'];
if (Platform.isAndroid) return const ['android'];
if (Platform.isIOS) return const ['ios'];
if (Platform.isWindows) return const ['windows'];
if (Platform.isMacOS) return const ['macos'];
if (Platform.isLinux) return const ['AppImage', 'linux'];
return const ['unknown'];
}
bool _isVersionLower({required String current, required String target}) {
if (current == target) return false;
final currentParts = current
.split('.')
.map((e) => int.tryParse(e) ?? 0)
.toList();
List<int> minParts = minimum
final targetParts = target
.split('.')
.map((e) => int.tryParse(e) ?? 0)
.toList();
while (currentParts.length < 3) {
currentParts.add(0);
}
while (minParts.length < 3) {
minParts.add(0);
}
final maxLength = currentParts.length > targetParts.length
? currentParts.length
: targetParts.length;
if (currentParts[0] != minParts[0]) {
return currentParts[0] < minParts[0];
for (int i = 0; i < maxLength; i++) {
final c = i < currentParts.length ? currentParts[i] : 0;
final t = i < targetParts.length ? targetParts[i] : 0;
if (c != t) {
return c < t;
}
}
if (currentParts[1] != minParts[1]) {
return currentParts[1] < minParts[1];
}
return currentParts[2] < minParts[2];
return false;
}
}
+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,
);
}
}
+99
View File
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flux/core/utils/update_prompt_helper.dart';
import 'package:flux/core/utils/version_check_service.dart';
class AppVersionLabel extends StatefulWidget {
final bool isCollapsed;
final bool showIcon;
const AppVersionLabel({
super.key,
this.isCollapsed = false,
this.showIcon = true,
});
@override
State<AppVersionLabel> createState() => _AppVersionLabelState();
}
class _AppVersionLabelState extends State<AppVersionLabel> {
String _version = "";
@override
void initState() {
super.initState();
_loadVersion();
}
Future<void> _loadVersion() async {
final v = await VersionCheckService.getShortVersionString();
if (mounted) {
setState(() {
_version = v;
});
}
}
@override
Widget build(BuildContext context) {
if (_version.isEmpty) return const SizedBox.shrink();
final theme = Theme.of(context);
final textMuted = theme.colorScheme.onSurface.withValues(alpha: 0.5);
if (widget.isCollapsed) {
return Tooltip(
message: "Flux $_version\nClicca per verificare aggiornamenti",
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
child: Container(
height: 36,
width: 36,
alignment: Alignment.center,
child: Icon(
Icons.info_outline,
size: 16,
color: textMuted,
),
),
),
);
}
return Tooltip(
message: "Clicca per verificare se ci sono aggiornamenti",
child: InkWell(
borderRadius: BorderRadius.circular(6),
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.showIcon) ...[
Icon(
Icons.info_outline,
size: 13,
color: textMuted,
),
const SizedBox(width: 6),
],
Text(
"Flux $_version",
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: textMuted,
decoration: TextDecoration.underline,
decorationColor: textMuted.withValues(alpha: 0.4),
decorationStyle: TextDecorationStyle.dotted,
),
),
],
),
),
),
);
}
}
@@ -1,6 +1,7 @@
import 'package:equatable/equatable.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/utils/image_utils.dart';
import 'package:image_picker/image_picker.dart';
part 'image_upload_state.dart';
@@ -18,9 +19,29 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
);
}
void clearFiles() {
emit(state.copyWith(status: ImageUploadStatus.initial, stagedFiles: []));
}
void addFiles(List<PlatformFile> files) {
final List<PlatformFile> processedFiles = files.map((file) {
if (file.bytes != null && ImageUtils.isImagePath(file.name)) {
final normalizedBytes = ImageUtils.normalizeOrientation(
file.bytes!,
extension: file.extension,
);
return PlatformFile(
name: file.name,
size: normalizedBytes.length,
bytes: normalizedBytes,
path: file.path,
);
}
return file;
}).toList();
List<PlatformFile> newFiles = List.from(state.stagedFiles);
newFiles.addAll(files);
newFiles.addAll(processedFiles);
emit(
state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
);
@@ -43,12 +64,19 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
stagedFiles: files,
),
);
final rawBytes = await photo.readAsBytes();
final normalizedBytes = ImageUtils.normalizeOrientation(
rawBytes,
extension: 'jpg',
);
final List<PlatformFile> newFiles = List.from(files);
newFiles.removeLast();
final PlatformFile loadedFile = PlatformFile(
name: photo.name,
size: await photo.length(),
bytes: await photo.readAsBytes(),
size: normalizedBytes.length,
bytes: normalizedBytes,
path: photo.path,
);
newFiles.add(loadedFile);
@@ -49,45 +49,77 @@ class ImageUploadScreen extends StatelessWidget {
},
child: Scaffold(
appBar: AppBar(
title: Text('Upload: $title'),
automaticallyImplyLeading:
state.status != ImageUploadStatus.uploading,
title: Text(title),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Stack(
children: [
Column(
children: [
// --- SEZIONE PULSANTI (Fotocamera / Galleria) ---
// --- BARRA SUPERIORE: ANNULLA / INVIA ---
Padding(
padding: const EdgeInsets.all(16.0),
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 10.0,
),
child: Row(
children: [
// ANNULLA
Expanded(
child: ElevatedButton.icon(
onPressed:
state.status == ImageUploadStatus.uploading
? null
: () => _handleCamera(context),
icon: const Icon(Icons.camera_alt),
label: const Text('SCATTA'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 16,
flex: 2,
child: SizedBox(
height: 48,
child: OutlinedButton.icon(
onPressed:
state.status == ImageUploadStatus.uploading
? null
: () => _handleCancel(context),
icon: const Icon(Icons.close, size: 20),
label: const Text(
'Annulla',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.red.shade700,
side: BorderSide(color: Colors.red.shade300),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
),
const SizedBox(width: 12),
// INVIA
Expanded(
child: OutlinedButton.icon(
onPressed:
state.status == ImageUploadStatus.uploading
? null
: () => _handleFilePicker(context),
icon: const Icon(Icons.folder),
label: const Text("GALLERIA"),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 16,
flex: 3,
child: SizedBox(
height: 48,
child: FilledButton.icon(
onPressed:
state.stagedFiles.isEmpty ||
state.status ==
ImageUploadStatus.uploading
? null
: () => _submitAllFiles(context),
icon: const Icon(Icons.cloud_upload, size: 20),
label: Text(
state.stagedFiles.isEmpty
? 'Invia'
: 'Invia (${state.stagedFiles.length})',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
@@ -96,27 +128,52 @@ class ImageUploadScreen extends StatelessWidget {
),
),
const Divider(),
const Divider(height: 1),
// --- SEZIONE ANTEPRIME (La GridView Magica) ---
// --- SEZIONE ANTEPRIME ---
Expanded(
child: state.stagedFiles.isEmpty
? const Center(
child: Text(
"Nessun file selezionato.\nScatta una foto o scegli dalla galleria.",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.add_photo_alternate_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(
"Nessun file selezionato",
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
SizedBox(height: 8),
Text(
"Tocca 'Scatta' o 'Galleria' in basso per aggiungere foto o documenti.",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
],
),
),
)
: GridView.builder(
padding: const EdgeInsets.all(16),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount:
3, // 3 colonne stile galleria
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
crossAxisCount: 3,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
itemCount: state.stagedFiles.length,
itemBuilder: (context, index) {
final file = state.stagedFiles[index];
@@ -145,7 +202,6 @@ class ImageUploadScreen extends StatelessWidget {
return Stack(
clipBehavior: Clip.none,
children: [
// L'ANTEPRIMA
Container(
width: double.infinity,
height: double.infinity,
@@ -159,19 +215,10 @@ class ImageUploadScreen extends StatelessWidget {
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: isImg
? (file.bytes != null
// Se abbiamo i bytes (es. scatto da fotocamera) usiamo quelli (a prova di Web!)
? Image.memory(
file.bytes!,
fit: BoxFit.cover,
)
// Altrimenti andiamo di file fisico
: const Center(
child:
CircularProgressIndicator(
color: Colors.blue,
),
))
? Image.memory(
file.bytes!,
fit: BoxFit.cover,
)
: const Column(
mainAxisAlignment:
MainAxisAlignment.center,
@@ -194,11 +241,9 @@ class ImageUploadScreen extends StatelessWidget {
),
),
),
// IL PULSANTE CESTINO (In alto a destra)
Positioned(
top: -8,
right: -8,
top: -6,
right: -6,
child: GestureDetector(
onTap: () => context
.read<ImageUploadCubit>()
@@ -222,42 +267,113 @@ class ImageUploadScreen extends StatelessWidget {
},
),
),
// --- SEZIONE INVIA E CHIUDI ---
// --- SEZIONE INFERIORE (A portata di pollice: Scatta e Galleria) ---
SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton.icon(
// Il pulsante si accende SOLO se ci sono file nel carrello
onPressed:
state.stagedFiles.isEmpty ||
state.status == ImageUploadStatus.uploading
? null
: () => _submitAllFiles(context),
icon: const Icon(Icons.cloud_upload),
label: Text(
"INVIA ${state.stagedFiles.length} FILE E CHIUDI",
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 12.0,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.06),
blurRadius: 8,
offset: const Offset(0, -2),
),
],
),
child: Row(
children: [
// SCATTA
Expanded(
child: SizedBox(
height: 56,
child: FilledButton.icon(
onPressed:
state.status ==
ImageUploadStatus.uploading
? null
: () => _handleCamera(context),
icon: const Icon(Icons.camera_alt, size: 24),
label: const Text(
'Scatta',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
),
),
),
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(
context,
).colorScheme.primary,
foregroundColor: Theme.of(
context,
).colorScheme.onPrimary,
const SizedBox(width: 12),
// GALLERIA
Expanded(
child: SizedBox(
height: 56,
child: OutlinedButton.icon(
onPressed:
state.status ==
ImageUploadStatus.uploading
? null
: () => _handleFilePicker(context),
icon: const Icon(
Icons.photo_library,
size: 24,
),
label: const Text(
'Galleria',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
),
),
),
),
],
),
),
),
],
),
if (state.status == ImageUploadStatus.uploading)
Container(
color: Colors.black45,
child: const Center(
child: Card(
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text(
'Caricamento in corso...',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
),
),
),
),
],
),
),
@@ -266,6 +382,40 @@ class ImageUploadScreen extends StatelessWidget {
);
}
void _handleCancel(BuildContext context) {
final cubit = context.read<ImageUploadCubit>();
if (cubit.state.stagedFiles.isNotEmpty) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Annullare caricamento?'),
content: const Text('I file selezionati verranno rimossi.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('No, continua'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
Navigator.pop(ctx);
cubit.clearFiles();
if (Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
},
child: const Text('Sì, annulla'),
),
],
),
);
} else {
if (Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
}
}
// --- LOGICA FOTOCAMERA E LIBRERIA ---
Future<void> _handleCamera(BuildContext context) async {
final ImageUploadCubit imageUploadCubit = context.read<ImageUploadCubit>();
@@ -43,6 +43,21 @@ class UploadSuccessScreen extends StatelessWidget {
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16, color: Colors.black54),
),
const SizedBox(height: 24),
if (Navigator.of(context).canPop())
OutlinedButton.icon(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.add_photo_alternate),
label: const Text('Carica altri file per questa pratica'),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.green.shade800,
side: BorderSide(color: Colors.green.shade600),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 12,
),
),
),
],
),
),
+12 -14
View File
@@ -2,7 +2,7 @@ import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/core/utils/functions.dart';
import 'package:pdfx/pdfx.dart';
import 'package:pdfrx/pdfrx.dart';
import 'package:internet_file/internet_file.dart';
class PdfViewerWidget extends StatefulWidget {
@@ -20,7 +20,7 @@ class PdfViewerWidget extends StatefulWidget {
}
class _PdfViewerWidgetState extends State<PdfViewerWidget> {
late PdfControllerPinch _pdfController;
Uint8List? _pdfData;
bool _isLoading = true;
String? _errorMessage;
@@ -45,11 +45,12 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
throw Exception("Nessun documento trovato");
}
_pdfController = PdfControllerPinch(
document: PdfDocument.openData(pdfData),
);
if (mounted) setState(() => _isLoading = false);
if (mounted) {
setState(() {
_pdfData = pdfData;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
@@ -60,12 +61,6 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
}
}
@override
void dispose() {
_pdfController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
@@ -87,7 +82,10 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
onPressed: () => Navigator.pop(context),
),
),
body: PdfViewPinch(controller: _pdfController),
body: PdfViewer.data(
_pdfData!,
sourceName: widget.storagePath ?? 'document.pdf',
),
);
}
}
+126 -72
View File
@@ -4,7 +4,7 @@ import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:qr_flutter/qr_flutter.dart';
class QrUploadDialog extends StatelessWidget {
class QrUploadDialog extends StatefulWidget {
final String deepLinkUrl;
final String title;
@@ -14,89 +14,143 @@ class QrUploadDialog extends StatelessWidget {
required this.title,
});
@override
State<QrUploadDialog> createState() => _QrUploadDialogState();
}
class _QrUploadDialogState extends State<QrUploadDialog> {
int _initialFileCount = 0;
@override
void initState() {
super.initState();
// Memorizziamo quanti file c'erano al momento dell'apertura per contare solo i nuovi ricevuti
_initialFileCount = context.read<AttachmentsBloc>().state.allFiles.length;
}
@override
Widget build(BuildContext context) {
// Usiamo i colori del tema per renderlo coerente col tuo design
final theme = Theme.of(context);
return BlocListener<AttachmentsBloc, AttachmentsState>(
listener: (context, state) {
Navigator.of(context).pop();
},
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
listenWhen: (previous, current) =>
previous.allFiles.length < current.allFiles.length,
child: AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
backgroundColor: theme.colorScheme.surface,
title: Column(
children: [
Icon(
Icons.qr_code_scanner,
size: 48,
color: theme.colorScheme.primary,
current.allFiles.length > previous.allFiles.length,
listener: (context, state) {
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Nuovo file ricevuto via QR Code! 📄 ($sessionReceived in questa sessione)',
),
const SizedBox(height: 16),
Text(
title,
textAlign: TextAlign.center,
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
),
content: SizedBox(
height: 400,
width: 350,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min, // Fondamentale per i dialog
children: [
const Text(
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 14, color: Colors.grey),
),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors
.white, // Lo sfondo bianco salva la vita sui temi scuri
borderRadius: BorderRadius.circular(16),
duration: const Duration(seconds: 2),
backgroundColor: Colors.green.shade700,
),
);
},
builder: (context, state) {
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
backgroundColor: theme.colorScheme.surface,
title: Column(
children: [
Icon(
Icons.qr_code_scanner,
size: 48,
color: theme.colorScheme.primary,
),
const SizedBox(height: 16),
Text(
widget.title,
textAlign: TextAlign.center,
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
),
content: SizedBox(
height: 400,
width: 350,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 14, color: Colors.grey),
),
child: QrImageView(
data: deepLinkUrl,
version: QrVersions.auto,
size: 200.0,
//Opzionale: puoi metterci il logo di FLUX in mezzo!
embeddedImage: const AssetImage('assets/images/logo.png'),
embeddedImageStyle: const QrEmbeddedImageStyle(
size: Size(40, 40),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
),
child: QrImageView(
data: widget.deepLinkUrl,
version: QrVersions.auto,
size: 200.0,
embeddedImage: const AssetImage(
'assets/images/logo.png',
),
embeddedImageStyle: const QrEmbeddedImageStyle(
size: Size(40, 40),
),
),
),
),
const SizedBox(height: 16),
Text(
"In attesa di file...",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
sessionReceived > 0
? Icons.check_circle_outline
: Icons.hourglass_empty,
size: 18,
color: sessionReceived > 0
? Colors.green
: theme.colorScheme.primary,
),
const SizedBox(width: 8),
Text(
sessionReceived > 0
? "$sessionReceived file ricevuti! (In ascolto...)"
: "In attesa di file...",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: sessionReceived > 0
? Colors.green
: theme.colorScheme.primary,
),
),
],
),
),
const SizedBox(height: 8),
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
],
if (_initialFileCount > 0 && sessionReceived == 0) ...[
const SizedBox(height: 4),
Text(
"($_initialFileCount file già presenti nella pratica)",
style: const TextStyle(fontSize: 11, color: Colors.grey),
),
],
const SizedBox(height: 8),
const LinearProgressIndicator(),
],
),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(context.l10n.commonClose),
),
],
actionsAlignment: MainAxisAlignment.center,
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(context.l10n.commonClose),
),
],
actionsAlignment: MainAxisAlignment.center,
);
},
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,141 @@
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customers/models/customer_model.dart';
class ContactPreferenceSection extends StatelessWidget {
final ContactPreference selectedPreference;
final ValueChanged<ContactPreference> onPreferenceChanged;
final CustomerModel? customer;
final TextEditingController? alternativePhoneController;
final bool alwaysShowAlternativePhone;
const ContactPreferenceSection({
super.key,
required this.selectedPreference,
required this.onPreferenceChanged,
this.customer,
this.alternativePhoneController,
this.alwaysShowAlternativePhone = false,
});
String _resolveTargetDestination() {
final altText =
alternativePhoneController?.text.trim().isNotEmpty == true
? alternativePhoneController!.text.trim()
: (customer?.alternativePhoneNumber.trim() ?? '');
if (selectedPreference.isEmail) {
return customer?.email.trim() ?? '';
}
if (selectedPreference.usesAlternativePhone) {
return altText;
}
return customer?.phoneNumber.trim() ?? '';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final showAltField =
alwaysShowAlternativePhone || selectedPreference.usesAlternativePhone;
final destination = _resolveTargetDestination();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Modalità di Avviso Cliente',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: ContactPreference.values.map((pref) {
final isSelected = pref == selectedPreference;
return ChoiceChip(
selected: isSelected,
showCheckmark: false,
avatar: pref.buildIcon(
size: 15,
overrideColor: isSelected ? pref.color : Colors.grey.shade600,
),
label: Text(
pref.shortLabel,
style: TextStyle(
fontSize: 12.5,
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
color: isSelected ? pref.color : null,
),
),
selectedColor: pref.color.withValues(alpha: 0.15),
side: BorderSide(
color: isSelected
? pref.color.withValues(alpha: 0.6)
: theme.dividerColor.withValues(alpha: 0.35),
),
onSelected: (_) => onPreferenceChanged(pref),
);
}).toList(),
),
if (customer != null) ...[
const SizedBox(height: 8),
Row(
children: [
Icon(
destination.isNotEmpty
? Icons.check_circle_outline_rounded
: Icons.warning_amber_rounded,
size: 15,
color: destination.isNotEmpty ? Colors.green : Colors.orange,
),
const SizedBox(width: 6),
Expanded(
child: Text(
destination.isNotEmpty
? 'Verrà avvisato su: $destination (${selectedPreference.label})'
: 'Attenzione: nessun recapito impostato per "${selectedPreference.label}"',
style: TextStyle(
fontSize: 12,
color: destination.isNotEmpty
? theme.colorScheme.onSurfaceVariant
: Colors.orange.shade800,
fontWeight: destination.isNotEmpty
? FontWeight.normal
: FontWeight.w600,
),
),
),
],
),
],
if (showAltField && alternativePhoneController != null) ...[
const SizedBox(height: 12),
TextFormField(
controller: alternativePhoneController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: selectedPreference.usesAlternativePhone
? 'Recapito Alternativo *'
: 'Recapito Alternativo (opzionale)',
hintText: 'Es. telefono coniuge / ufficio...',
prefixIcon: const Icon(Icons.phone_forwarded_outlined),
helperText: customer != null
? 'Se compilato, verrà salvato anche sull\'anagrafica del cliente'
: null,
),
validator: (val) {
if (selectedPreference.usesAlternativePhone &&
(val == null || val.trim().isEmpty)) {
return 'Inserisci il recapito alternativo per avvisare il cliente';
}
return null;
},
),
],
],
);
}
}
@@ -85,6 +85,7 @@ class SharedCustomerSection extends StatelessWidget {
),
if (hasCustomer &&
(customer!.phoneNumber.isNotEmpty ||
customer!.alternativePhoneNumber.isNotEmpty ||
customer!.email.isNotEmpty)) ...[
const SizedBox(height: 12), // Un po' più di respiro dal box sopra
// Mettiamo i contatti in un Container con un po' di stile per farli sembrare una "Contact Card" integrata
@@ -148,8 +149,79 @@ class SharedCustomerSection extends StatelessWidget {
],
),
// Sezione divisoria se ci sono entrambi
// --- RIGA RECAPITO ALTERNATIVO ---
if (customer!.phoneNumber.isNotEmpty &&
customer!.alternativePhoneNumber.isNotEmpty)
const Divider(height: 8, thickness: 0.5),
if (customer!.alternativePhoneNumber.isNotEmpty)
Row(
children: [
IconButton(
visualDensity: VisualDensity.compact,
onPressed: () => launchUrl(
Uri.parse(
'https://wa.me/39${customer!.alternativePhoneNumber}',
),
),
icon: const FaIcon(
FontAwesomeIcons.whatsapp,
color: Colors.teal,
size: 20,
),
tooltip: 'WhatsApp su recapito alternativo',
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
SelectableText(
customer!.alternativePhoneNumber,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
Text(
'Recapito alternativo',
style: TextStyle(
fontSize: 10.5,
color: Colors.grey.shade600,
),
),
],
),
),
IconButton(
visualDensity: VisualDensity.compact,
onPressed: () {
Clipboard.setData(
ClipboardData(
text: customer!.alternativePhoneNumber,
),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Recapito alternativo copiato!'),
duration: Duration(seconds: 2),
),
);
},
icon: const Icon(
Icons.copy,
size: 18,
color: Colors.grey,
),
tooltip: 'Copia',
),
],
),
// Sezione divisoria se c'è email dopo un telefono
if ((customer!.phoneNumber.isNotEmpty ||
customer!.alternativePhoneNumber.isNotEmpty) &&
customer!.email.isNotEmpty)
const Divider(height: 8, thickness: 0.5),
@@ -27,13 +27,26 @@ class SharedModelSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final hasModel = modelId != null && modelId!.isNotEmpty;
final currentModelId = modelId;
final currentModelName = modelName;
final hasModelId = currentModelId != null && currentModelId.isNotEmpty;
final hasModelName = currentModelName != null && currentModelName.isNotEmpty;
final hasModel = hasModelId || hasModelName;
final String subtitleText;
if (hasModelName) {
subtitleText = currentModelName;
} else if (hasModelId) {
subtitleText = 'Modello selezionato';
} else {
subtitleText = 'Nessun modello selezionato';
}
return ListTile(
tileColor: backgroundColor,
title: Text(label),
subtitle: Text(
hasModel ? modelName! : 'Nessun modello selezionato',
subtitleText,
style: TextStyle(
color: hasModel ? null : Colors.grey,
fontWeight: hasModel ? FontWeight.bold : FontWeight.normal,
@@ -124,8 +137,12 @@ class SharedModelSection extends StatelessWidget {
);
if (newModel != null) {
// CHIAMIAMO LA CALLBACK!
onModelSelected(newModel.id, newModel.nameWithBrand);
final selectedId = newModel.id ?? '';
final selectedName =
newModel.nameWithBrand.isNotEmpty
? newModel.nameWithBrand
: newModel.name;
onModelSelected(selectedId, selectedName);
if (context.mounted) Navigator.pop(modalContext);
}
},
@@ -149,11 +166,12 @@ class SharedModelSection extends StatelessWidget {
),
),
onTap: () {
// CHIAMIAMO LA CALLBACK!
onModelSelected(
deviceModel.id!,
deviceModel.nameWithBrand,
);
final selectedId = deviceModel.id ?? '';
final selectedName =
deviceModel.nameWithBrand.isNotEmpty
? deviceModel.nameWithBrand
: deviceModel.name;
onModelSelected(selectedId, selectedName);
Navigator.pop(modalContext);
},
);
@@ -76,11 +76,16 @@ class SharedFilesSection extends StatelessWidget {
'https://flux.catelli.it/upload/${state.parentType.name}/$targetId?companyId=$companyId';
if (context.mounted) {
final attachmentBloc =
context.read<AttachmentsBloc>();
showDialog(
context: context,
builder: (_) => QrUploadDialog(
deepLinkUrl: deepLink,
title: 'Carica File: $titleNameForUpload',
builder: (_) => BlocProvider.value(
value: attachmentBloc,
child: QrUploadDialog(
deepLinkUrl: deepLink,
title: 'Carica File: $titleNameForUpload',
),
),
);
}
@@ -53,7 +53,9 @@ class StaffSection extends StatelessWidget {
);
}
final staffMembers = state.storeStaff;
final staffMembers = state.storeStaff
.where((staff) => staff.isActive || staff.id == selectedStaffId)
.toList();
// FIX: Feedback visivo se la lista è vuota
if (staffMembers.isEmpty) {
+15 -1
View File
@@ -61,7 +61,21 @@ class StaffSelectorModal extends StatelessWidget {
if (state.status == StaffStatus.loading) {
return const CircularProgressIndicator();
}
final staffList = state.storeStaff;
final rawList = state.storeStaff.isNotEmpty
? state.storeStaff
: state.allStaff;
final staffList = rawList.where((s) => s.isActive).toList();
if (staffList.isEmpty) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Text(
'Nessun collaboratore attivo trovato.',
style: TextStyle(color: Colors.grey.shade600),
),
);
}
return _buildStaffGrid(context, staffList);
},
),
@@ -1,7 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
@@ -16,6 +16,7 @@ part 'attachments_state.dart';
class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
final _repository = GetIt.I.get<AttachmentsRepository>();
StreamSubscription<List<AttachmentModel>>? _realtimeSubscription;
AttachmentsBloc({String? parentId, required AttachmentParentType parentType})
: super(
@@ -36,6 +37,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
on<DeleteSpecificAttachmentEvent>(_onDeleteSpecificAttachment);
on<SelectAllAttachmentsEvent>(_onSelectAllAttachments);
on<ClearAttachmentSelectionEvent>(_onClearAttachmentSelection);
on<RemoteAttachmentsUpdatedEvent>(_onRemoteAttachmentsUpdated);
on<UpdateAttachmentViewModeEvent>(_onUpdateAttachmentViewMode);
on<AttachmentUpdatedEvent>(_onAttachmentUpdated);
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
if (parentId != null && currentCompanyId != null) {
@@ -43,6 +47,12 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
}
}
@override
Future<void> close() {
_realtimeSubscription?.cancel();
return super.close();
}
FutureOr<void> _onParentEntitySaved(
ParentEntitySavedEvent event,
Emitter<AttachmentsState> emit,
@@ -65,7 +75,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
bytes: file.localBytes,
);
// Chiamiamo il metodo generico passando il parentId e il TYPE
return _repository.uploadAndRegisterFile(
parentId: event.newParentId,
parentType: state.parentType,
@@ -96,26 +105,75 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
Emitter<AttachmentsState> emit,
) async {
final currentId = event.parentId ?? state.parentId;
if (currentId == null || currentId.isEmpty) return;
if (currentId != null) {
emit(state.copyWith(status: AttachmentsStatus.loading));
emit(
state.copyWith(
parentId: currentId,
status:
state.remoteFiles.isEmpty
? AttachmentsStatus.loading
: state.status,
),
);
await emit.forEach(
_repository.getFilesStream(
currentId,
state.parentType,
), // Passiamo il tipo!
onData: (List<AttachmentModel> data) =>
state.copyWith(status: AttachmentsStatus.ready, remoteFiles: data),
onError: (error, stackTrace) => state.copyWith(
status: AttachmentsStatus.failure,
error: error.toString(),
// 1. Caricamento immediato via REST (Robusto e istantaneo)
try {
final remoteList = await _repository.getFiles(
currentId,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: remoteList,
error: null,
),
);
} catch (e) {
debugPrint("Avviso REST getFiles: $e");
if (state.remoteFiles.isEmpty) {
emit(
state.copyWith(
status: AttachmentsStatus.failure,
error: "Impossibile recuperare gli allegati: $e",
),
);
}
}
// 2. Iscrizione Realtime in background (senza bloccare la coda eventi)
await _realtimeSubscription?.cancel();
try {
_realtimeSubscription = _repository
.getFilesStream(currentId, state.parentType)
.listen(
(data) {
add(RemoteAttachmentsUpdatedEvent(data));
},
onError: (error) {
debugPrint("Avviso stream Realtime AttachmentsBloc: $error");
},
);
} catch (e) {
debugPrint("Avviso inizializzazione Realtime: $e");
}
}
void _onAddAttachments(
void _onRemoteAttachmentsUpdated(
RemoteAttachmentsUpdatedEvent event,
Emitter<AttachmentsState> emit,
) {
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: event.files,
error: null,
),
);
}
FutureOr<void> _onAddAttachments(
AddAttachmentsEvent event,
Emitter<AttachmentsState> emit,
) async {
@@ -132,32 +190,52 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return;
}
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
if (currentId == null) {
final newLocalFiles = event.files.map((file) {
// FISCHIO SALVAVITA PER DESKTOP: se i bytes sono nulli, li leggiamo dal path fisico!
Uint8List? rawBytes = file.bytes;
if (rawBytes == null && file.path != null) {
rawBytes = File(file.path!).readAsBytesSync();
}
// Normalizziamo i file garantendo la presenza dei byte (fondamentale su desktop)
final processedFiles =
event.files.map((file) {
Uint8List? rawBytes = file.bytes;
if (rawBytes == null && file.path != null && !kIsWeb) {
try {
final f = File(file.path!);
if (f.existsSync()) {
rawBytes = f.readAsBytesSync();
}
} catch (_) {}
}
return AttachmentModel(
id: null,
companyId: currentCompanyId,
operationId: state.parentType == AttachmentParentType.operation
? ''
: null,
ticketId: state.parentType == AttachmentParentType.ticket ? '' : null,
customerId: state.parentType == AttachmentParentType.customer
? ''
: null,
name: file.name.fileNameWithoutExtension(),
extension: file.name.fileExtension(),
storagePath: '',
fileSize: file.size,
localBytes: rawBytes, // Ora i byte ci sono al 100% anche su Mac!
);
}).toList();
return PlatformFile(
name: file.name,
size: file.size > 0 ? file.size : (rawBytes?.length ?? 0),
bytes: rawBytes,
path: file.path,
readStream: file.readStream,
);
}).toList();
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
if (currentId == null || currentId.isEmpty) {
final newLocalFiles =
processedFiles.map((file) {
return AttachmentModel(
id: null,
companyId: currentCompanyId,
operationId:
state.parentType == AttachmentParentType.operation ? '' : null,
ticketId:
state.parentType == AttachmentParentType.ticket ? '' : null,
customerId:
state.parentType == AttachmentParentType.customer ? '' : null,
customerOrderId:
state.parentType == AttachmentParentType.customerOrder
? ''
: null,
name: file.name.fileNameWithoutExtension(),
extension: file.name.fileExtension(),
storagePath: '',
fileSize: file.size,
localBytes: file.bytes,
);
}).toList();
emit(
state.copyWith(
@@ -171,18 +249,31 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
// BIVIO 2: PRATICA ESISTENTE (Upload immediato)
emit(state.copyWith(status: AttachmentsStatus.uploading));
try {
final List<Future<void>> uploadTasks = event.files.map((file) {
return _repository.uploadAndRegisterFile(
parentId: currentId,
parentType: state.parentType,
pickedFile: file,
companyId: currentCompanyId,
bucket: _getBucketForParentType,
);
}).toList();
final List<Future<void>> uploadTasks =
processedFiles.map((file) {
return _repository.uploadAndRegisterFile(
parentId: currentId,
parentType: state.parentType,
pickedFile: file,
companyId: currentCompanyId,
bucket: _getBucketForParentType,
);
}).toList();
await Future.wait(uploadTasks);
emit(state.copyWith(status: AttachmentsStatus.ready));
// Aggiornamento immediato via REST (garantisce visualizzazione immediata anche senza WebSocket)
final updatedFiles = await _repository.getFiles(
currentId,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: updatedFiles,
error: null,
),
);
} catch (e) {
emit(
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
@@ -223,11 +314,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
// 2. Gestione Foto Fotocamera (XFile)
if (event.photos != null) {
for (var photo in event.photos!) {
// Leggiamo i byte asincronamente
final bytes = await photo.readAsBytes();
final fileSize = await photo.length();
// Lo travestiamo da PlatformFile per passarlo al Repository!
final fakePlatformFile = PlatformFile(
name: photo.name,
size: fileSize,
@@ -247,9 +336,18 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
}
}
// Esecuzione parallela di tutti i documenti e foto
await Future.wait(uploadTasks);
emit(state.copyWith(status: AttachmentsStatus.success));
final updatedFiles = await _repository.getFiles(
state.parentId!,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.success,
remoteFiles: updatedFiles,
),
);
} catch (e) {
emit(
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
@@ -268,7 +366,22 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
currentContextType: state.parentType,
bucket: _getBucketForParentType,
);
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
if (state.parentId != null) {
final updatedFiles = await _repository.getFiles(
state.parentId!,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: updatedFiles,
selectedFiles: [],
),
);
} else {
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
}
} catch (e) {
emit(
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
@@ -293,7 +406,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
SelectAllAttachmentsEvent event,
Emitter<AttachmentsState> emit,
) {
// Prendiamo TUTTI i file (locali e remoti) e li buttiamo nei selezionati
emit(state.copyWith(selectedFiles: state.allFiles));
}
@@ -301,7 +413,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
ClearAttachmentSelectionEvent event,
Emitter<AttachmentsState> emit,
) {
// Svuotiamo brutalmente la lista
emit(state.copyWith(selectedFiles: []));
}
@@ -311,38 +422,38 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
) async {
if (state.selectedFiles.isEmpty) return;
// BIVIO 1: PRATICA/TICKET NON ANCORA SALVATA (Modalità Locale)
if (state.parentId == null) {
final updatedLocalFiles = state.localFiles.map((file) {
if (state.selectedFiles.contains(file)) {
// Assegniamo dinamicamente l'ID in base all'entità scelta
switch (event.targetType) {
case AttachmentParentType.customer:
return file.copyWith(customerId: event.targetId);
case AttachmentParentType.ticket:
return file.copyWith(ticketId: event.targetId);
case AttachmentParentType.operation:
return file.copyWith(operationId: event.targetId);
case AttachmentParentType.shippingDocument:
return file.copyWith(shippingDocumentId: event.targetId);
case AttachmentParentType.note:
return file.copyWith(noteId: event.targetId);
}
}
return file;
}).toList();
final updatedLocalFiles =
state.localFiles.map((file) {
if (state.selectedFiles.contains(file)) {
switch (event.targetType) {
case AttachmentParentType.customer:
return file.copyWith(customerId: event.targetId);
case AttachmentParentType.ticket:
return file.copyWith(ticketId: event.targetId);
case AttachmentParentType.operation:
return file.copyWith(operationId: event.targetId);
case AttachmentParentType.shippingDocument:
return file.copyWith(shippingDocumentId: event.targetId);
case AttachmentParentType.note:
return file.copyWith(noteId: event.targetId);
case AttachmentParentType.customerOrder:
return file.copyWith(customerOrderId: event.targetId);
}
}
return file;
}).toList();
emit(
state.copyWith(
localFiles: updatedLocalFiles,
selectedFiles: [], // Svuotiamo la selezione
selectedFiles: [],
status: AttachmentsStatus.ready,
),
);
return;
}
// BIVIO 2: PRATICA/TICKET ESISTENTE (Modalità Remota su DB)
emit(state.copyWith(status: AttachmentsStatus.loading));
try {
final List<Future<void>> linkTasks = [];
@@ -361,8 +472,17 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
await Future.wait(linkTasks);
// Lo stream aggiornerà automaticamente la UI
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
final updatedFiles = await _repository.getFiles(
state.parentId!,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: updatedFiles,
selectedFiles: [],
),
);
} catch (e) {
emit(
state.copyWith(
@@ -377,23 +497,35 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
RenameAttachmentEvent event,
Emitter<AttachmentsState> emit,
) async {
// BIVIO 1: File Locale (Bozza)
if (event.file.localBytes != null) {
final updatedLocalFiles = state.localFiles.map((f) {
if (f == event.file) {
return f.copyWith(name: event.newName);
}
return f;
}).toList();
final updatedLocalFiles =
state.localFiles.map((f) {
if (f == event.file) {
return f.copyWith(name: event.newName);
}
return f;
}).toList();
emit(state.copyWith(localFiles: updatedLocalFiles));
return;
}
// BIVIO 2: File Remoto (Salvato su DB)
emit(state.copyWith(status: AttachmentsStatus.loading));
try {
await _repository.renameAttachment(event.file.id!, event.newName);
emit(state.copyWith(status: AttachmentsStatus.ready));
if (state.parentId != null) {
final updatedFiles = await _repository.getFiles(
state.parentId!,
state.parentType,
);
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: updatedFiles,
),
);
} else {
emit(state.copyWith(status: AttachmentsStatus.ready));
}
} catch (e) {
emit(
state.copyWith(
@@ -409,13 +541,68 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
Emitter<AttachmentsState> emit,
) {
if (event.file.localBytes != null) {
final updatedLocalFiles = state.localFiles
.where((f) => f != event.file)
.toList();
final updatedLocalFiles =
state.localFiles.where((f) => f != event.file).toList();
emit(state.copyWith(localFiles: updatedLocalFiles));
}
}
FutureOr<void> _onUpdateAttachmentViewMode(
UpdateAttachmentViewModeEvent event,
Emitter<AttachmentsState> emit,
) async {
if (event.file.localBytes != null) {
final updatedLocalFiles = state.localFiles.map((f) {
if (f == event.file) {
return f.copyWith(viewMode: event.viewMode);
}
return f;
}).toList();
emit(state.copyWith(localFiles: updatedLocalFiles));
return;
}
if (event.file.id == null) return;
try {
final updatedRemoteFiles = state.remoteFiles.map((f) {
if (f.id == event.file.id) {
return f.copyWith(viewMode: event.viewMode);
}
return f;
}).toList();
emit(state.copyWith(remoteFiles: updatedRemoteFiles));
await _repository.updateAttachmentViewMode(event.file.id!, event.viewMode);
} catch (e) {
debugPrint("Errore aggiornamento viewMode in DB: $e");
}
}
FutureOr<void> _onAttachmentUpdated(
AttachmentUpdatedEvent event,
Emitter<AttachmentsState> emit,
) {
final updatedRemote = state.remoteFiles.map((f) {
if (f.id == event.file.id) {
return event.file;
}
return f;
}).toList();
final updatedLocal = state.localFiles.map((f) {
if (f.id == event.file.id || (f.id == null && f.name == event.file.name)) {
return event.file;
}
return f;
}).toList();
emit(state.copyWith(
remoteFiles: updatedRemote,
localFiles: updatedLocal,
));
}
Bucket get _getBucketForParentType {
switch (state.parentType) {
case AttachmentParentType.customer:
@@ -428,6 +615,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return Bucket.companyDocuments;
case AttachmentParentType.note:
return Bucket.documents;
case AttachmentParentType.customerOrder:
return Bucket.documents;
}
}
}
@@ -71,3 +71,28 @@ class DeleteSpecificAttachmentEvent extends AttachmentsEvent {
final AttachmentModel file;
const DeleteSpecificAttachmentEvent(this.file);
}
class RemoteAttachmentsUpdatedEvent extends AttachmentsEvent {
final List<AttachmentModel> files;
const RemoteAttachmentsUpdatedEvent(this.files);
@override
List<Object?> get props => [files];
}
class UpdateAttachmentViewModeEvent extends AttachmentsEvent {
final AttachmentModel file;
final AttachmentViewMode viewMode;
const UpdateAttachmentViewModeEvent(this.file, this.viewMode);
@override
List<Object?> get props => [file, viewMode];
}
class AttachmentUpdatedEvent extends AttachmentsEvent {
final AttachmentModel file;
const AttachmentUpdatedEvent(this.file);
@override
List<Object?> get props => [file];
}
@@ -7,7 +7,8 @@ enum AttachmentParentType {
ticket('ticket_id'),
customer('customer_id'),
shippingDocument('shipping_document_id'),
note('note_id');
note('note_id'),
customerOrder('customer_order_id');
final String dbColumn;
const AttachmentParentType(this.dbColumn);
@@ -1,7 +1,9 @@
import 'dart:typed_data';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:flux/core/utils/image_utils.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
@@ -44,6 +46,30 @@ class AttachmentsRepository {
return 'shipping_document_id';
case AttachmentParentType.note:
return 'note_id';
case AttachmentParentType.customerOrder:
return 'customer_order_id';
}
}
/// RECUPERA I FILE IN MODALITÀ REST (Immediato e affidabile)
Future<List<AttachmentModel>> getFiles(
String parentId,
AttachmentParentType parentType,
) async {
try {
final columnName = _getColumnNameForParent(parentType);
final response = await _supabase
.from(Tables.attachments)
.select()
.eq(columnName, parentId)
.order('created_at', ascending: true);
return (response as List)
.map((map) => AttachmentModel.fromMap(map as Map<String, dynamic>))
.toList();
} catch (e) {
throw Exception("Impossibile recuperare gli allegati dal DB: $e");
}
}
@@ -75,7 +101,6 @@ class AttachmentsRepository {
String? rawFileName, // Alternativa: nome del file
}) async {
// 🛡️ L'ASSERT NINJA: O c'è il pickedFile, o ci sono i byte e il nome.
// L'assert funziona solo in debug, ma è perfetto per beccare subito errori di chiamata!
assert(
pickedFile != null || (rawBytes != null && rawFileName != null),
'Devi passare o un PlatformFile, oppure rawBytes e rawFileName!',
@@ -88,25 +113,35 @@ class AttachmentsRepository {
final int finalFileSize;
if (pickedFile != null) {
if (pickedFile.bytes == null) {
Uint8List? fileBytes = pickedFile.bytes;
// Se su Desktop i bytes sono nulli ma abbiamo il path, leggiamo direttamente da disco
if (fileBytes == null && pickedFile.path != null && !kIsWeb) {
try {
final f = File(pickedFile.path!);
if (f.existsSync()) {
fileBytes = f.readAsBytesSync();
}
} catch (_) {}
}
if (fileBytes == null) {
throw Exception(
"I bytes del file sono vuoti! Ricarica la pagina senza cache.",
);
}
finalBytes = pickedFile.bytes!;
finalBytes = fileBytes;
finalFileName = pickedFile.name;
finalFileSize = pickedFile.size;
finalFileSize = pickedFile.size > 0 ? pickedFile.size : finalBytes.length;
} else {
// Se pickedFile è null, grazie all'assert sappiamo che questi non lo sono
finalBytes = rawBytes!;
finalFileName = rawFileName!;
finalFileSize = finalBytes.length; // Calcoliamo la size dai byte reali
finalFileSize = finalBytes.length;
}
// 2. Estraiamo l'estensione e puliamo il nome
final extension = finalFileName.contains('.')
? finalFileName.split('.').last
: ''; // Fallback se il file non ha estensione
: '';
final cleanName = finalFileName
.replaceAll(RegExp(r'[^\w\s\.-]'), '')
@@ -123,7 +158,10 @@ class AttachmentsRepository {
.uploadBinary(
storagePath,
finalBytes,
fileOptions: FileOptions(contentType: _guessContentType(extension)),
fileOptions: FileOptions(
contentType: _guessContentType(extension),
upsert: true,
),
);
// 5. Creiamo la mappa per il DB dinamicamente
@@ -164,6 +202,8 @@ class AttachmentsRepository {
AttachmentParentType.ticket: file.ticketId,
AttachmentParentType.customer: file.customerId,
AttachmentParentType.shippingDocument: file.shippingDocumentId,
AttachmentParentType.note: file.noteId,
AttachmentParentType.customerOrder: file.customerOrderId,
};
// 2. Simuliamo la rimozione del collegamento per il contesto attuale
@@ -185,10 +225,17 @@ class AttachmentsRepository {
// B. Nessuno usa più questo file! ELIMINAZIONE FISICA TOTALE.
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
if (file.storagePath != null) {
await _supabase.storage.from(bucket.value).remove([
final pathsToRemove = <String>[
if (file.storagePath != null && file.storagePath!.isNotEmpty)
file.storagePath!,
]);
if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty)
file.thumbnailPath!,
if (file.croppedStoragePath != null &&
file.croppedStoragePath!.isNotEmpty)
file.croppedStoragePath!,
];
if (pathsToRemove.isNotEmpty) {
await _supabase.storage.from(bucket.value).remove(pathsToRemove);
}
}
}
@@ -216,7 +263,6 @@ class AttachmentsRepository {
required String targetId,
}) async {
try {
// Facciamo un semplice UPDATE aggiungendo l'ID nella colonna giusta
await _supabase
.from(Tables.attachments)
.update({targetType.dbColumn: targetId})
@@ -226,9 +272,107 @@ class AttachmentsRepository {
}
}
/// AGGIORNA LA MODALITÀ DI VISUALIZZAZIONE PREFERITA (cropped / original)
Future<void> updateAttachmentViewMode(
String fileId,
AttachmentViewMode viewMode,
) async {
try {
await _supabase
.from(Tables.attachments)
.update({'view_mode': viewMode.value})
.eq('id', fileId);
} catch (e) {
throw Exception(
"Errore nell'aggiornamento della modalità di visualizzazione: $e",
);
}
}
/// Salva la rotazione permanente del file originale aggiornando storage_path con un nuovo timestamp.
/// Questo farà scattare il trigger Postgres per il worker Python (autocrop e thumbnail).
Future<AttachmentModel> rotateAttachment({
required AttachmentModel attachment,
required int quarterTurns,
required Bucket bucket,
}) async {
final turns = quarterTurns % 4;
if (turns == 0) return attachment;
if (attachment.storagePath == null || attachment.storagePath!.isEmpty) {
throw Exception("Impossibile ruotare: storagePath mancante.");
}
try {
// 1. Recuperiamo i byte originali
Uint8List originalBytes;
if (attachment.localBytes != null) {
originalBytes = attachment.localBytes!;
} else {
originalBytes = await downloadAttachmentBytes(
storagePath: attachment.storagePath!,
bucket: bucket,
);
}
// 2. Ruotiamo fisicamente i pixel
final rotatedBytes = ImageUtils.rotateBytes(
originalBytes,
quarterTurns: turns,
extension: attachment.extension,
);
// 3. Generiamo il nuovo storagePath con un nuovo timestamp per evitare cache e triggerare l'update
final oldPath = attachment.storagePath!;
final lastSlash = oldPath.lastIndexOf('/');
final dir = lastSlash != -1 ? oldPath.substring(0, lastSlash) : '';
final filename =
lastSlash != -1 ? oldPath.substring(lastSlash + 1) : oldPath;
final nameWithoutTimestamp =
filename.replaceFirst(RegExp(r'^\d+_'), '');
final newTimestamp = DateTime.now().millisecondsSinceEpoch;
final newStoragePath = dir.isNotEmpty
? '$dir/${newTimestamp}_$nameWithoutTimestamp'
: '${newTimestamp}_$nameWithoutTimestamp';
// 4. Carichiamo il nuovo file ruotato nello storage
await _supabase.storage
.from(bucket.value)
.uploadBinary(
newStoragePath,
rotatedBytes,
fileOptions: FileOptions(
contentType: _guessContentType(attachment.extension),
upsert: true,
),
);
// 5. Aggiorniamo il record su Postgres (triggera il worker Python)
final updateData = {
'storage_path': newStoragePath,
'file_size': rotatedBytes.length,
};
if (attachment.id != null) {
await _supabase
.from(Tables.attachments)
.update(updateData)
.eq('id', attachment.id!);
}
// 6. Restituiamo il modello aggiornato
return attachment.copyWith(
storagePath: newStoragePath,
fileSize: rotatedBytes.length,
localBytes: rotatedBytes,
);
} catch (e) {
throw Exception("Errore durante il salvataggio della rotazione: $e");
}
}
// Helper per indovinare il content-type base
String _guessContentType(String extension) {
switch (extension.toLowerCase()) {
switch (extension.toLowerCase().replaceAll('.', '')) {
case 'pdf':
return 'application/pdf';
case 'png':
@@ -236,6 +380,28 @@ class AttachmentsRepository {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'webp':
return 'image/webp';
case 'heic':
return 'image/heic';
case 'heif':
return 'image/heif';
case 'gif':
return 'image/gif';
case 'svg':
return 'image/svg+xml';
case 'txt':
return 'text/plain';
case 'csv':
return 'text/csv';
case 'doc':
return 'application/msword';
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
case 'xls':
return 'application/vnd.ms-excel';
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
default:
return 'application/octet-stream';
}
@@ -2,6 +2,22 @@ import 'dart:typed_data';
import 'package:equatable/equatable.dart';
enum AttachmentViewMode {
cropped('cropped'),
original('original');
final String value;
const AttachmentViewMode(this.value);
static AttachmentViewMode? fromString(String? val) {
if (val == null) return null;
final clean = val.trim().toLowerCase();
if (clean == 'cropped') return AttachmentViewMode.cropped;
if (clean == 'original') return AttachmentViewMode.original;
return null;
}
}
class AttachmentModel extends Equatable {
final String? id;
final DateTime? createdAt;
@@ -10,9 +26,13 @@ class AttachmentModel extends Equatable {
final String? ticketId;
final String? shippingDocumentId;
final String? noteId;
final String? customerOrderId;
final String name;
final String extension;
final String? storagePath;
final String? thumbnailPath;
final String? croppedStoragePath;
final AttachmentViewMode? viewMode;
final int fileSize;
final Uint8List? localBytes;
final String companyId;
@@ -25,14 +45,25 @@ class AttachmentModel extends Equatable {
this.ticketId,
this.shippingDocumentId,
this.noteId,
this.customerOrderId,
required this.name,
required this.extension,
this.storagePath,
this.thumbnailPath,
this.croppedStoragePath,
this.viewMode,
required this.fileSize,
this.localBytes,
required this.companyId,
});
factory AttachmentModel.empty() => const AttachmentModel(
name: '',
extension: '',
fileSize: 0,
companyId: '',
);
@override
List<Object?> get props => [
id,
@@ -42,9 +73,13 @@ class AttachmentModel extends Equatable {
ticketId,
shippingDocumentId,
noteId,
customerOrderId,
name,
extension,
storagePath,
thumbnailPath,
croppedStoragePath,
viewMode,
fileSize,
localBytes,
companyId,
@@ -54,6 +89,25 @@ class AttachmentModel extends Equatable {
bool get isPdf => extension.toLowerCase().replaceAll('.', '') == 'pdf';
String? get effectiveStoragePath {
if (viewMode == AttachmentViewMode.cropped) {
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
return croppedStoragePath;
}
return storagePath;
} else if (viewMode == AttachmentViewMode.original) {
if (storagePath != null && storagePath!.isNotEmpty) {
return storagePath;
}
return croppedStoragePath;
}
// Default fallback quando viewMode non è specificato
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
return croppedStoragePath;
}
return storagePath;
}
String get sizeFormatted {
if (fileSize <= 0) return "0 B";
const suffixes = ["B", "KB", "MB", "GB", "TB"];
@@ -71,9 +125,13 @@ class AttachmentModel extends Equatable {
String? ticketId,
String? shippingDocumentId,
String? noteId,
String? customerOrderId,
String? name,
String? extension,
String? storagePath,
String? thumbnailPath,
String? croppedStoragePath,
AttachmentViewMode? viewMode,
int? fileSize,
Uint8List? localBytes,
String? companyId,
@@ -85,9 +143,13 @@ class AttachmentModel extends Equatable {
ticketId: ticketId ?? this.ticketId,
shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId,
noteId: noteId ?? this.noteId,
customerOrderId: customerOrderId ?? this.customerOrderId,
name: name ?? this.name,
extension: extension ?? this.extension,
storagePath: storagePath ?? this.storagePath,
thumbnailPath: thumbnailPath ?? this.thumbnailPath,
croppedStoragePath: croppedStoragePath ?? this.croppedStoragePath,
viewMode: viewMode ?? this.viewMode,
fileSize: fileSize ?? this.fileSize,
localBytes: localBytes ?? this.localBytes,
companyId: companyId ?? this.companyId,
@@ -104,9 +166,13 @@ class AttachmentModel extends Equatable {
ticketId: map['ticket_id'] as String?,
shippingDocumentId: map['shipping_document_id'] as String?,
noteId: map['note_id'] as String?,
customerOrderId: map['customer_order_id'] as String?,
name: map['name'] as String,
extension: map['extension'] as String,
storagePath: map['storage_path'] as String?,
thumbnailPath: map['thumbnail_path'] as String?,
croppedStoragePath: map['cropped_storage_path'] as String?,
viewMode: AttachmentViewMode.fromString(map['view_mode'] as String?),
fileSize: map['file_size'] is int
? map['file_size']
: int.tryParse(map['file_size']?.toString() ?? '0') ?? 0,
@@ -125,8 +191,12 @@ class AttachmentModel extends Equatable {
'ticket_id': ticketId,
'shipping_document_id': shippingDocumentId,
'note_id': noteId,
'customer_order_id': customerOrderId,
'file_size': fileSize,
'company_id': companyId,
'thumbnail_path': thumbnailPath,
'cropped_storage_path': croppedStoragePath,
'view_mode': (viewMode ?? AttachmentViewMode.original).value,
};
}
}
@@ -1,110 +1,360 @@
import 'dart:typed_data';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'package:get_it/get_it.dart';
import 'package:universal_html/html.dart' as html;
import 'package:flux/core/utils/functions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:pdfx/pdfx.dart';
import 'package:flux/features/attachments/data/attachments_repository.dart';
import 'package:flux/core/utils/image_utils.dart';
import 'package:pdfrx/pdfrx.dart';
import 'package:internet_file/internet_file.dart';
class AttachmentViewerScreen extends StatefulWidget {
final AttachmentModel attachment;
final AttachmentModel? attachment;
final List<AttachmentModel>? attachments;
final int initialIndex;
final Function(String newName)? onRename;
final Function(AttachmentModel attachment, String newName)? onRenameAttachment;
final VoidCallback? onDelete;
final Function(AttachmentModel attachment)? onDeleteAttachment;
final Function(AttachmentModel attachment, AttachmentViewMode viewMode)? onViewModeChanged;
final Function(AttachmentModel attachment)? onAttachmentUpdated;
const AttachmentViewerScreen({
super.key,
required this.attachment,
this.attachment,
this.attachments,
this.initialIndex = 0,
this.onRename,
this.onRenameAttachment,
this.onDelete,
});
this.onDeleteAttachment,
this.onViewModeChanged,
this.onAttachmentUpdated,
}) : assert(
attachment != null || (attachments != null && attachments.length > 0),
'Devi fornire un allegato o una lista di allegati non vuota.',
);
@override
State<AttachmentViewerScreen> createState() => _AttachmentViewerScreenState();
}
class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
PdfControllerPinch? _pdfController;
late List<AttachmentModel> _items;
late int _currentIndex;
final FocusNode _focusNode = FocusNode();
bool _isLoading = true;
bool _isSavingRotation = false;
String? _errorMessage;
Uint8List? _fileBytes;
late String _fileName;
int _loadToken = 0;
int _rotationTurns = 0;
bool _showCropped = true;
final Map<String, Uint8List> _bytesCache = {};
bool get isPdf => widget.attachment.extension.toLowerCase() == 'pdf';
AttachmentModel get _currentAttachment => _items[_currentIndex];
bool get isPdf =>
_currentAttachment.extension.toLowerCase().replaceAll('.', '') == 'pdf';
bool get hasMultipleFiles => _items.length > 1;
bool get canGoPrevious => _currentIndex > 0;
bool get canGoNext => _currentIndex < _items.length - 1;
bool get _hasCropped =>
_currentAttachment.croppedStoragePath != null &&
_currentAttachment.croppedStoragePath!.isNotEmpty;
bool get _hasOriginal =>
_currentAttachment.storagePath != null &&
_currentAttachment.storagePath!.isNotEmpty;
bool get canToggleCrop => !isPdf && _hasCropped && _hasOriginal;
String? get _activeStoragePath {
final item = _currentAttachment;
if (_showCropped && _hasCropped) {
return item.croppedStoragePath;
}
return item.storagePath;
}
bool _computeInitialShowCropped(AttachmentModel attachment) {
if (attachment.viewMode == AttachmentViewMode.original) {
return false;
}
if (attachment.viewMode == AttachmentViewMode.cropped) {
return true;
}
return attachment.croppedStoragePath != null &&
attachment.croppedStoragePath!.isNotEmpty;
}
@override
void initState() {
super.initState();
_fileName = widget.attachment.name;
_loadFile();
}
Future<void> _loadFile() async {
try {
// 1. Capiamo da dove prendere i dati
if (widget.attachment.localBytes != null) {
_fileBytes = widget.attachment.localBytes;
} else if (widget.attachment.storagePath != null &&
widget.attachment.storagePath!.isNotEmpty) {
final signedUrl = await getSignedUrl(widget.attachment.storagePath!);
_fileBytes = await InternetFile.get(signedUrl);
} else {
throw Exception("Nessun documento trovato o byte mancanti.");
}
// 2. Se è PDF, inizializziamo il controller
if (isPdf && _fileBytes != null) {
_pdfController = PdfControllerPinch(
document: PdfDocument.openData(_fileBytes!),
);
}
if (mounted) setState(() => _isLoading = false);
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
_errorMessage = e.toString();
});
}
if (widget.attachments != null && widget.attachments!.isNotEmpty) {
_items = List<AttachmentModel>.from(widget.attachments!);
_currentIndex = widget.initialIndex.clamp(0, _items.length - 1);
} else if (widget.attachment != null) {
_items = [widget.attachment!];
_currentIndex = 0;
} else {
_items = [];
_currentIndex = 0;
}
if (_items.isNotEmpty) {
_showCropped = _computeInitialShowCropped(_currentAttachment);
}
_loadFile();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_focusNode.requestFocus();
}
});
}
@override
void dispose() {
_pdfController?.dispose();
_focusNode.dispose();
super.dispose();
}
void _goToPrevious() {
if (!canGoPrevious) return;
_changeFile(_currentIndex - 1);
}
void _goToNext() {
if (!canGoNext) return;
_changeFile(_currentIndex + 1);
}
void _changeFile(int newIndex) {
if (newIndex < 0 || newIndex >= _items.length) return;
final newAttachment = _items[newIndex];
setState(() {
_currentIndex = newIndex;
_showCropped = _computeInitialShowCropped(newAttachment);
_isLoading = true;
_errorMessage = null;
_fileBytes = null;
_rotationTurns = 0;
});
_loadFile();
}
void _toggleCropView() {
if (!canToggleCrop) return;
final nextShowCropped = !_showCropped;
final nextMode = nextShowCropped
? AttachmentViewMode.cropped
: AttachmentViewMode.original;
final nextPath = nextShowCropped
? _currentAttachment.croppedStoragePath
: _currentAttachment.storagePath;
final updatedAttachment = _currentAttachment.copyWith(viewMode: nextMode);
setState(() {
_showCropped = nextShowCropped;
_items[_currentIndex] = updatedAttachment;
_rotationTurns = 0;
});
if (widget.onViewModeChanged != null) {
widget.onViewModeChanged!(updatedAttachment, nextMode);
} else if (updatedAttachment.id != null) {
try {
final repository = GetIt.I.get<AttachmentsRepository>();
repository.updateAttachmentViewMode(updatedAttachment.id!, nextMode);
} catch (_) {}
}
if (nextPath != null && _bytesCache.containsKey(nextPath)) {
setState(() {
_fileBytes = _bytesCache[nextPath];
_isLoading = false;
_errorMessage = null;
});
} else {
setState(() {
_isLoading = true;
_errorMessage = null;
});
_loadFile();
}
}
Future<void> _saveRotation() async {
final turns = _rotationTurns % 4;
if (turns == 0 || _isSavingRotation) return;
setState(() {
_isSavingRotation = true;
});
try {
final repository = GetIt.I.get<AttachmentsRepository>();
final updated = await repository.rotateAttachment(
attachment: _currentAttachment,
quarterTurns: turns,
bucket: Bucket.documents,
);
if (!mounted) return;
setState(() {
_items[_currentIndex] = updated;
_rotationTurns = 0;
_showCropped = false; // Mostra l'originale ruotato appena salvato
_isSavingRotation = false;
if (updated.storagePath != null && updated.localBytes != null) {
_bytesCache[updated.storagePath!] = updated.localBytes!;
}
if (updated.localBytes != null) {
_fileBytes = updated.localBytes;
}
});
widget.onAttachmentUpdated?.call(updated);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Rotazione salvata! Il server aggiornerà ritaglio e anteprima.',
),
backgroundColor: Colors.green,
duration: Duration(seconds: 4),
),
);
} catch (e) {
if (!mounted) return;
setState(() {
_isSavingRotation = false;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Errore durante il salvataggio della rotazione: $e'),
backgroundColor: Colors.red,
),
);
}
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent) {
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
if (canGoPrevious) {
_goToPrevious();
return KeyEventResult.handled;
}
} else if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
if (canGoNext) {
_goToNext();
return KeyEventResult.handled;
}
}
}
return KeyEventResult.ignored;
}
Future<void> _loadFile() async {
final token = ++_loadToken;
final item = _currentAttachment;
try {
Uint8List? bytes;
if (item.localBytes != null) {
bytes = item.localBytes;
} else {
final path = _activeStoragePath;
if (path != null && path.isNotEmpty) {
if (_bytesCache.containsKey(path)) {
bytes = _bytesCache[path];
} else {
try {
final signedUrl = await getSignedUrl(path);
bytes = await InternetFile.get(signedUrl);
} catch (e) {
// Se fallisce il ritaglio e abbiamo l'originale, proviamo l'originale come fallback
if (_showCropped && _hasOriginal && item.storagePath != path) {
final signedUrl = await getSignedUrl(item.storagePath!);
bytes = await InternetFile.get(signedUrl);
_showCropped = false;
} else {
rethrow;
}
}
if (!isPdf) {
bytes = ImageUtils.normalizeOrientation(
bytes,
extension: item.extension,
);
}
_bytesCache[path] = bytes;
}
} else {
throw Exception("Nessun documento trovato o byte mancanti.");
}
}
if (token != _loadToken || !mounted) return;
if (bytes != null && !isPdf && item.localBytes != null) {
bytes = ImageUtils.normalizeOrientation(
bytes,
extension: item.extension,
);
}
setState(() {
_fileBytes = bytes;
_isLoading = false;
});
} catch (e) {
if (token != _loadToken || !mounted) return;
setState(() {
_isLoading = false;
_errorMessage = e.toString();
});
}
}
void _showRenameDialog() {
final ctrl = TextEditingController(text: _fileName);
final current = _currentAttachment;
final ctrl = TextEditingController(text: current.name);
ctrl.selection = TextSelection(
baseOffset: 0,
extentOffset: ctrl.text.length,
);
final focusNode = FocusNode();
final dialogFocusNode = FocusNode();
showDialog(
context: context,
builder: (context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => focusNode.requestFocus(),
(_) => dialogFocusNode.requestFocus(),
);
return AlertDialog(
title: const Text('Rinomina File'),
content: TextField(
controller: ctrl,
focusNode: focusNode,
focusNode: dialogFocusNode,
decoration: InputDecoration(
labelText: 'Nuovo nome',
suffixText: '.${widget.attachment.extension}',
suffixText: '.${current.extension}',
),
onSubmitted: (val) {
Navigator.pop(context);
if (val.trim().isNotEmpty && widget.onRename != null) {
setState(() {
_fileName = val.trim();
});
widget.onRename!(val.trim());
}
_applyRename(val);
},
),
actions: [
@@ -115,73 +365,288 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
ElevatedButton(
onPressed: () {
Navigator.pop(context);
if (ctrl.text.trim().isNotEmpty && widget.onRename != null) {
setState(() {
_fileName = ctrl.text.trim();
});
widget.onRename!(ctrl.text.trim());
}
_applyRename(ctrl.text);
},
child: const Text('Salva'),
),
],
);
},
).then((_) {
if (mounted) {
_focusNode.requestFocus();
}
});
}
void _applyRename(String val) {
final trimmed = val.trim();
if (trimmed.isEmpty) return;
final current = _currentAttachment;
final updated = current.copyWith(name: trimmed);
setState(() {
_items[_currentIndex] = updated;
});
widget.onRenameAttachment?.call(current, trimmed);
widget.onRename?.call(trimmed);
}
void _confirmDelete() {
final current = _currentAttachment;
showDialog(
context: context,
builder: (c) => AlertDialog(
title: const Text('Eliminare file?'),
content: const Text(
'Sei sicuro di voler eliminare questo allegato?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(c),
child: const Text('Annulla'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
Navigator.pop(c); // Chiude dialog
widget.onDeleteAttachment?.call(current);
widget.onDelete?.call();
Navigator.pop(context); // Chiude il viewer
},
child: const Text('Elimina'),
),
],
),
);
}
Future<void> _downloadCurrentFile() async {
final bytes = _fileBytes;
if (bytes == null || bytes.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('File non ancora caricato o non disponibile.'),
),
);
return;
}
String fullName = _currentAttachment.name;
final ext = _currentAttachment.extension.toLowerCase().replaceAll('.', '');
if (_showCropped && canToggleCrop) {
fullName = '${fullName}_cropped';
}
if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) {
fullName = '$fullName.$ext';
}
if (kIsWeb) {
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
html.AnchorElement(href: url)
..setAttribute('download', fullName)
..click();
html.Url.revokeObjectUrl(url);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Download avviato: $fullName')),
);
}
} else {
final savePath = await FilePicker.saveFile(
dialogTitle: 'Salva file',
fileName: fullName,
bytes: bytes,
);
if (savePath != null) {
final targetFile = File(savePath);
await targetFile.writeAsBytes(bytes);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('File salvato in: $savePath')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black87, // Sfondo scuro per i viewer è il top
appBar: AppBar(
backgroundColor: Colors.black,
foregroundColor: Colors.white,
title: Text(_fileName, style: const TextStyle(fontSize: 16)),
actions: [
if (widget.onRename != null)
IconButton(
icon: const Icon(Icons.edit),
tooltip: 'Rinomina',
onPressed: _showRenameDialog,
),
if (widget.onDelete != null)
IconButton(
icon: const Icon(Icons.delete, color: Colors.redAccent),
tooltip: 'Elimina',
onPressed: () {
// Chiediamo conferma
showDialog(
context: context,
builder: (c) => AlertDialog(
title: const Text('Eliminare file?'),
content: const Text(
'Sei sicuro di voler eliminare questo allegato?',
return Focus(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: _handleKeyEvent,
child: Scaffold(
backgroundColor: Colors.black87,
appBar: AppBar(
backgroundColor: Colors.black,
foregroundColor: Colors.white,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
_currentAttachment.name,
style: const TextStyle(fontSize: 16),
overflow: TextOverflow.ellipsis,
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (hasMultipleFiles) ...[
Text(
'${_currentIndex + 1} di ${_items.length}',
style: const TextStyle(fontSize: 12, color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(c),
child: const Text('Annulla'),
if (canToggleCrop)
const Text(
' • ',
style: TextStyle(fontSize: 12, color: Colors.white70),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
],
if (canToggleCrop)
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: _showCropped
? Colors.amber.withValues(alpha: 0.2)
: Colors.white10,
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: _showCropped
? Colors.amberAccent
: Colors.white30,
width: 0.8,
),
onPressed: () {
Navigator.pop(c); // Chiude dialog
widget.onDelete!(); // Lancia eliminazione
Navigator.pop(context); // Chiude il viewer
},
child: const Text('Elimina'),
),
],
),
);
},
child: Text(
_showCropped ? 'Ritaglio automatico' : 'Originale',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: _showCropped
? Colors.amberAccent
: Colors.white70,
),
),
),
],
),
],
),
actions: [
if (canToggleCrop)
IconButton(
icon: Icon(
_showCropped
? Icons.photo_size_select_actual_outlined
: Icons.crop,
color: _showCropped ? Colors.amberAccent : Colors.white,
),
tooltip: _showCropped
? 'Passa alla foto originale'
: 'Passa al ritaglio automatico',
onPressed: _toggleCropView,
),
if (!isPdf)
IconButton(
icon: const Icon(Icons.rotate_right),
tooltip: 'Ruota',
onPressed: () {
setState(() {
_rotationTurns = (_rotationTurns + 1) % 4;
});
},
),
if (!isPdf && _rotationTurns % 4 != 0)
_isSavingRotation
? const Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Center(
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
),
),
)
: Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: FilledButton.icon(
style: FilledButton.styleFrom(
backgroundColor: Colors.green.shade700,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 10),
visualDensity: VisualDensity.compact,
),
icon: const Icon(Icons.check, size: 16),
label: const Text(
'Salva',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: _saveRotation,
),
),
IconButton(
icon: const Icon(Icons.download),
tooltip: 'Scarica',
onPressed: _downloadCurrentFile,
),
],
if (widget.onRename != null || widget.onRenameAttachment != null)
IconButton(
icon: const Icon(Icons.edit),
tooltip: 'Rinomina',
onPressed: _showRenameDialog,
),
if (widget.onDelete != null || widget.onDeleteAttachment != null)
IconButton(
icon: const Icon(Icons.delete, color: Colors.redAccent),
tooltip: 'Elimina',
onPressed: _confirmDelete,
),
],
),
body: Stack(
children: [
Positioned.fill(
child: _buildBody(),
),
// Freccia Precedente
if (hasMultipleFiles && canGoPrevious)
Positioned(
left: 16,
top: 0,
bottom: 0,
child: Center(
child: _NavigationArrowButton(
icon: Icons.arrow_back_ios_new_rounded,
tooltip: 'File precedente (←)',
onPressed: _goToPrevious,
),
),
),
// Freccia Successivo
if (hasMultipleFiles && canGoNext)
Positioned(
right: 16,
top: 0,
bottom: 0,
child: Center(
child: _NavigationArrowButton(
icon: Icons.arrow_forward_ios_rounded,
tooltip: 'File successivo (→)',
onPressed: _goToNext,
),
),
),
],
),
),
body: _buildBody(),
);
}
@@ -208,13 +673,63 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
);
}
if (isPdf && _pdfController != null) {
return PdfViewPinch(controller: _pdfController!);
if (isPdf && _fileBytes != null) {
return PdfViewer.data(
_fileBytes!,
sourceName: '${_currentAttachment.id}_${_currentAttachment.name}.pdf',
params: const PdfViewerParams(
backgroundColor: Colors.transparent,
enableKeyboardNavigation: false,
),
);
} else {
return InteractiveViewer(
maxScale: 5.0,
child: Center(child: Image.memory(_fileBytes!)),
child: Center(
child: RotatedBox(
quarterTurns: _rotationTurns,
child: Image.memory(_fileBytes!),
),
),
);
}
}
}
class _NavigationArrowButton extends StatelessWidget {
final IconData icon;
final String tooltip;
final VoidCallback onPressed;
const _NavigationArrowButton({
required this.icon,
required this.tooltip,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return Tooltip(
message: tooltip,
child: Material(
color: Colors.black.withValues(alpha: 0.55),
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 6,
child: InkWell(
onTap: onPressed,
hoverColor: Colors.white.withValues(alpha: 0.2),
splashColor: Colors.white.withValues(alpha: 0.3),
child: Padding(
padding: const EdgeInsets.all(12),
child: Icon(
icon,
color: Colors.white,
size: 28,
),
),
),
),
);
}
}
@@ -0,0 +1,320 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customers/data/customer_repository.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/service_locator.dart';
part 'customer_order_form_state.dart';
class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final CustomerRepository _customerRepository = sl<CustomerRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
CustomerOrderFormCubit({
StaffMemberModel? createdBy,
CustomerOrderModel? existingOrder,
}) : super(
CustomerOrderFormState(
order:
existingOrder ??
CustomerOrderModel.empty().copyWith(
createdById: createdBy?.id,
createdByName: createdBy?.name,
),
),
);
Future<void> initForm({
String? orderId,
CustomerOrderModel? existingOrder,
}) async {
final companyId = _sessionCubit.state.company?.id ?? '';
if (existingOrder != null && existingOrder.id != null) {
emit(
state.copyWith(
order: existingOrder,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
// Aggiorniamo anche in background con i dettagli freschi (es. da scansione o relazioni)
final fresh = await _repository.getOrderById(existingOrder.id!);
if (fresh != null && !isClosed) {
emit(state.copyWith(order: fresh));
}
return;
}
if (orderId != null && orderId.isNotEmpty) {
emit(state.copyWith(status: CustomerOrderFormStatus.loading));
final fetched = await _repository.getOrderById(orderId);
if (fetched == null) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Ordine non trovato.',
),
);
return;
}
emit(
state.copyWith(
order: fetched,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
return;
}
// Nuovo ordine
final currentStore = _sessionCubit.state.currentStore;
final currentStaff = _sessionCubit.state.currentStaffMember;
final newOrder = state.order.copyWith(
companyId: companyId,
storeId: currentStore?.id,
storeDisplayName: currentStore?.name,
createdById: state.order.createdById ?? currentStaff?.id,
createdByName: state.order.createdByName ?? currentStaff?.name,
orderDate: DateTime.now(),
status: CustomerOrderStatus.toOrder,
);
emit(
state.copyWith(
order: newOrder,
status: CustomerOrderFormStatus.ready,
),
);
_loadAvailableTags(companyId);
}
Future<void> _loadAvailableTags(String companyId) async {
if (companyId.isEmpty) return;
final tags = await _repository.fetchDistinctTags(companyId);
if (!isClosed) {
emit(state.copyWith(availableTags: tags));
}
}
void updateCustomer(CustomerModel customer) {
final currentAlt = state.order.alternativePhoneNumber?.trim() ?? '';
final resolvedAlt = currentAlt.isNotEmpty
? currentAlt
: (customer.alternativePhoneNumber.trim().isNotEmpty
? customer.alternativePhoneNumber.trim()
: null);
emit(
state.copyWith(
order: state.order.copyWith(
customerId: customer.id,
customer: customer,
alternativePhoneNumber: resolvedAlt,
),
),
);
}
void updateFields({
DateTime? orderDate,
String? storeId,
String? storeDisplayName,
String? productDescription,
int? quantity,
String? notes,
double? price,
double? deposit,
String? externalCode,
CustomerOrderStatus? status,
ContactPreference? contactPreference,
String? alternativePhoneNumber,
bool? customerNotified,
}) {
DateTime? notifiedAt = state.order.customerNotifiedAt;
bool clearNotifiedAt = false;
if (customerNotified != null) {
if (customerNotified && !state.order.customerNotified) {
notifiedAt = DateTime.now();
} else if (!customerNotified) {
clearNotifiedAt = true;
}
}
emit(
state.copyWith(
order: state.order.copyWith(
orderDate: orderDate ?? state.order.orderDate,
storeId: storeId ?? state.order.storeId,
storeDisplayName: storeDisplayName ?? state.order.storeDisplayName,
productDescription:
productDescription ?? state.order.productDescription,
quantity: quantity ?? state.order.quantity,
notes: notes ?? state.order.notes,
price: price ?? state.order.price,
deposit: deposit ?? state.order.deposit,
externalCode: externalCode ?? state.order.externalCode,
status: status ?? state.order.status,
contactPreference: contactPreference ?? state.order.contactPreference,
alternativePhoneNumber:
alternativePhoneNumber ?? state.order.alternativePhoneNumber,
customerNotified: customerNotified ?? state.order.customerNotified,
customerNotifiedAt: notifiedAt,
clearCustomerNotifiedAt: clearNotifiedAt,
),
),
);
}
void addTag(String rawTag) {
final clean = rawTag.trim();
if (clean.isEmpty) return;
final exists = state.order.tags.any(
(t) => t.toLowerCase() == clean.toLowerCase(),
);
if (exists) return;
final updatedTags = [...state.order.tags, clean];
final updatedAvailable = state.availableTags.any(
(t) => t.toLowerCase() == clean.toLowerCase(),
)
? state.availableTags
: ([...state.availableTags, clean]
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase())));
emit(
state.copyWith(
order: state.order.copyWith(tags: updatedTags),
availableTags: updatedAvailable,
),
);
}
void removeTag(String tag) {
final updatedTags = state.order.tags.where((t) => t != tag).toList();
emit(state.copyWith(order: state.order.copyWith(tags: updatedTags)));
}
/// Salva l'ordine (o crea bozza per allegati / QR)
Future<CustomerOrderModel?> saveOrder({
CustomerOrderStatus? overrideStatus,
bool silentForAttachment = false,
}) async {
final previousStatus = state.order.status;
final orderToSave = overrideStatus != null
? state.order.copyWith(status: overrideStatus)
: state.order;
if (orderToSave.customerId == null || orderToSave.customerId!.isEmpty) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Seleziona un cliente prima di salvare.',
),
);
return null;
}
if (orderToSave.productDescription.trim().isEmpty) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: 'Inserisci il prodotto richiesto dal cliente.',
),
);
return null;
}
if (!silentForAttachment) {
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
}
try {
final CustomerOrderModel saved;
if (orderToSave.id == null || orderToSave.id!.isEmpty) {
saved = await _repository.insertOrder(orderToSave);
} else {
saved = await _repository.updateOrder(orderToSave);
}
await _syncCustomerAlternativePhone(orderToSave);
final transitionedToArrived =
saved.status == CustomerOrderStatus.arrived &&
previousStatus != CustomerOrderStatus.arrived;
emit(
state.copyWith(
status: silentForAttachment
? CustomerOrderFormStatus.ready
: CustomerOrderFormStatus.saved,
order: saved,
justMarkedArrived: transitionedToArrived,
errorMessage: null,
),
);
return saved;
} catch (e) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: e.toString(),
),
);
return null;
}
}
Future<void> markCustomerNotified(bool notified) async {
final now = DateTime.now();
final updated = state.order.copyWith(
customerNotified: notified,
customerNotifiedAt: notified ? now : null,
clearCustomerNotifiedAt: !notified,
);
emit(state.copyWith(order: updated));
if (updated.id != null && updated.id!.isNotEmpty) {
try {
final saved = await _repository.updateOrder(updated);
if (!isClosed) {
emit(state.copyWith(order: saved));
}
} catch (_) {}
}
}
Future<void> deleteOrder() async {
final id = state.order.id;
if (id == null || id.isEmpty) return;
emit(state.copyWith(status: CustomerOrderFormStatus.saving));
try {
await _repository.deleteOrder(id);
emit(state.copyWith(status: CustomerOrderFormStatus.deleted));
} catch (e) {
emit(
state.copyWith(
status: CustomerOrderFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
Future<void> _syncCustomerAlternativePhone(CustomerOrderModel order) async {
final customer = order.customer;
final newAlt = order.alternativePhoneNumber?.trim() ?? '';
if (customer == null || customer.id == null || newAlt.isEmpty) return;
if (customer.alternativePhoneNumber.trim() == newAlt) return;
try {
await _customerRepository.updateCustomer(
customer.copyWith(alternativePhoneNumber: newAlt),
);
} catch (_) {}
}
}
@@ -0,0 +1,52 @@
part of 'customer_order_form_cubit.dart';
enum CustomerOrderFormStatus {
initial,
loading,
ready,
saving,
saved,
deleted,
failure,
}
class CustomerOrderFormState extends Equatable {
final CustomerOrderFormStatus status;
final CustomerOrderModel order;
final List<String> availableTags;
final String? errorMessage;
final bool justMarkedArrived;
const CustomerOrderFormState({
this.status = CustomerOrderFormStatus.initial,
required this.order,
this.availableTags = const [],
this.errorMessage,
this.justMarkedArrived = false,
});
CustomerOrderFormState copyWith({
CustomerOrderFormStatus? status,
CustomerOrderModel? order,
List<String>? availableTags,
String? errorMessage,
bool? justMarkedArrived,
}) {
return CustomerOrderFormState(
status: status ?? this.status,
order: order ?? this.order,
availableTags: availableTags ?? this.availableTags,
errorMessage: errorMessage,
justMarkedArrived: justMarkedArrived ?? false,
);
}
@override
List<Object?> get props => [
status,
order,
availableTags,
errorMessage,
justMarkedArrived,
];
}
@@ -0,0 +1,159 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customer_orders/data/customer_orders_repository.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/service_locator.dart';
part 'customer_order_list_state.dart';
class CustomerOrderListCubit extends Cubit<CustomerOrderListState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
StreamSubscription<void>? _ordersSubscription;
Timer? _searchDebounce;
CustomerOrderListCubit() : super(const CustomerOrderListState()) {
_ordersSubscription = _repository.onOrdersChanged.listen((_) {
loadOrders(silent: true);
loadTags();
});
}
Future<void> init() async {
await Future.wait([loadOrders(), loadTags()]);
}
Future<void> loadTags() async {
final companyId = _sessionCubit.state.company?.id;
if (companyId == null || companyId.isEmpty) return;
final tags = await _repository.fetchDistinctTags(companyId);
if (!isClosed) {
emit(state.copyWith(availableTags: tags));
}
}
Future<void> loadOrders({bool silent = false}) async {
final companyId = _sessionCubit.state.company?.id;
if (companyId == null || companyId.isEmpty) return;
if (!silent) {
emit(state.copyWith(status: CustomerOrderListStatus.loading));
}
try {
final orders = await _repository.fetchOrders(
companyId: companyId,
quickFilter: state.quickFilter,
storeId: state.storeIdFilter,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
selectedTags: state.selectedTags,
);
if (!isClosed) {
emit(
state.copyWith(
status: CustomerOrderListStatus.success,
orders: orders,
errorMessage: null,
),
);
}
} catch (e) {
if (!isClosed) {
emit(
state.copyWith(
status: CustomerOrderListStatus.failure,
errorMessage: e.toString(),
),
);
}
}
}
void setQuickFilter(CustomerOrderQuickFilter filter) {
if (state.quickFilter == filter) return;
emit(state.copyWith(quickFilter: filter));
loadOrders();
}
void setSearchTerm(String query) {
_searchDebounce?.cancel();
emit(
state.copyWith(
searchTerm: query,
clearSearchTerm: query.trim().isEmpty,
),
);
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
loadOrders();
});
}
void setStoreFilter(String? storeId) {
emit(
state.copyWith(
storeIdFilter: storeId,
clearStoreFilter: storeId == null || storeId.isEmpty,
),
);
loadOrders();
}
void setDateRange(DateTimeRange? range) {
emit(
state.copyWith(
dateRange: range,
clearDateRange: range == null,
),
);
loadOrders();
}
void toggleTagFilter(String tag) {
final updated = List<String>.from(state.selectedTags);
if (updated.contains(tag)) {
updated.remove(tag);
} else {
updated.add(tag);
}
emit(state.copyWith(selectedTags: updated));
loadOrders();
}
void resetFilters() {
emit(
state.copyWith(
quickFilter: CustomerOrderQuickFilter.active,
clearStoreFilter: true,
clearSearchTerm: true,
clearDateRange: true,
selectedTags: const [],
),
);
loadOrders();
}
Future<void> quickUpdateStatus(
CustomerOrderModel order,
CustomerOrderStatus newStatus,
) async {
try {
await _repository.updateOrder(order.copyWith(status: newStatus));
} catch (e) {
if (!isClosed) {
emit(state.copyWith(errorMessage: e.toString()));
}
}
}
@override
Future<void> close() {
_ordersSubscription?.cancel();
_searchDebounce?.cancel();
return super.close();
}
}
@@ -0,0 +1,75 @@
part of 'customer_order_list_cubit.dart';
enum CustomerOrderListStatus { initial, loading, success, failure }
class CustomerOrderListState extends Equatable {
final CustomerOrderListStatus status;
final List<CustomerOrderModel> orders;
final List<String> availableTags;
final CustomerOrderQuickFilter quickFilter;
final String? storeIdFilter;
final String? searchTerm;
final DateTimeRange? dateRange;
final List<String> selectedTags;
final String? errorMessage;
const CustomerOrderListState({
this.status = CustomerOrderListStatus.initial,
this.orders = const [],
this.availableTags = const [],
this.quickFilter = CustomerOrderQuickFilter.active,
this.storeIdFilter,
this.searchTerm,
this.dateRange,
this.selectedTags = const [],
this.errorMessage,
});
bool get hasAdvancedFilters =>
(storeIdFilter != null && storeIdFilter!.isNotEmpty) ||
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
dateRange != null ||
selectedTags.isNotEmpty;
CustomerOrderListState copyWith({
CustomerOrderListStatus? status,
List<CustomerOrderModel>? orders,
List<String>? availableTags,
CustomerOrderQuickFilter? quickFilter,
String? storeIdFilter,
bool clearStoreFilter = false,
String? searchTerm,
bool clearSearchTerm = false,
DateTimeRange? dateRange,
bool clearDateRange = false,
List<String>? selectedTags,
String? errorMessage,
}) {
return CustomerOrderListState(
status: status ?? this.status,
orders: orders ?? this.orders,
availableTags: availableTags ?? this.availableTags,
quickFilter: quickFilter ?? this.quickFilter,
storeIdFilter: clearStoreFilter
? null
: (storeIdFilter ?? this.storeIdFilter),
searchTerm: clearSearchTerm ? null : (searchTerm ?? this.searchTerm),
dateRange: clearDateRange ? null : (dateRange ?? this.dateRange),
selectedTags: selectedTags ?? this.selectedTags,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [
status,
orders,
availableTags,
quickFilter,
storeIdFilter,
searchTerm,
dateRange,
selectedTags,
errorMessage,
];
}
@@ -0,0 +1,198 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class CustomerOrdersRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
final StreamController<void> _ordersChangedController =
StreamController<void>.broadcast();
Stream<void> get onOrdersChanged => _ordersChangedController.stream;
void notifyOrdersChanged() {
if (!_ordersChangedController.isClosed) {
_ordersChangedController.add(null);
}
}
static const String _selectRelations = '''
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*)
''';
Future<CustomerOrderModel?> getOrderById(String id) async {
try {
final response = await _supabase
.from(Tables.customerOrders)
.select(_selectRelations)
.eq('id', id)
.single();
return CustomerOrderModel.fromMap(response);
} catch (e) {
debugPrint('Errore getOrderById ($id): $e');
return null;
}
}
Future<List<CustomerOrderModel>> fetchOrders({
required String companyId,
CustomerOrderQuickFilter quickFilter = CustomerOrderQuickFilter.active,
String? storeId,
String? searchTerm,
DateTimeRange? dateRange,
List<String> selectedTags = const [],
}) async {
try {
var query = _supabase
.from(Tables.customerOrders)
.select(_selectRelations)
.eq('company_id', companyId);
final statuses = quickFilter.dbStatuses;
if (statuses != null && statuses.isNotEmpty) {
query = query.inFilter('status', statuses);
}
if (storeId != null && storeId.isNotEmpty) {
query = query.eq('store_id', storeId);
}
if (dateRange != null) {
final start = DateTime(
dateRange.start.year,
dateRange.start.month,
dateRange.start.day,
);
final end = DateTime(
dateRange.end.year,
dateRange.end.month,
dateRange.end.day,
23,
59,
59,
999,
);
query = query
.gte('order_date', start.toUtc().toIso8601String())
.lte('order_date', end.toUtc().toIso8601String());
}
if (selectedTags.isNotEmpty) {
query = query.overlaps('tags', selectedTags);
}
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
try {
final custRes = await _supabase
.from(Tables.customers)
.select('id')
.eq('company_id', companyId)
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%,alternative_phone_number.ilike.%$cleanTerm%');
matchingCustomerIds = (custRes as List)
.map((row) => row['id'].toString())
.toList();
} catch (_) {}
if (matchingCustomerIds.isNotEmpty) {
final idsJoined = matchingCustomerIds.join(',');
query = query.or(
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%,customer_id.in.($idsJoined)',
);
} else {
query = query.or(
'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%',
);
}
}
final response = await query.order('order_date', ascending: false);
return (response as List)
.map((map) => CustomerOrderModel.fromMap(map as Map<String, dynamic>))
.toList();
} catch (e) {
debugPrint('Errore fetchOrders: $e');
throw Exception('Impossibile caricare gli ordini: $e');
}
}
/// Recupera l'elenco ordinato di tutte le etichette (tags) già usate nell'azienda per l'autocomplete
Future<List<String>> fetchDistinctTags(String companyId) async {
try {
final response = await _supabase
.from(Tables.customerOrders)
.select('tags')
.eq('company_id', companyId)
.not('tags', 'is', null);
final Set<String> distinct = {};
for (final row in (response as List)) {
final rawList = row['tags'] as List?;
if (rawList != null) {
for (final tag in rawList) {
final clean = tag.toString().trim();
if (clean.isNotEmpty) distinct.add(clean);
}
}
}
final sorted = distinct.toList()
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
return sorted;
} catch (e) {
debugPrint('Errore fetchDistinctTags: $e');
return const [];
}
}
Future<CustomerOrderModel> insertOrder(CustomerOrderModel order) async {
try {
final res = await _supabase
.from(Tables.customerOrders)
.insert(order.toMap())
.select(_selectRelations)
.single();
notifyOrdersChanged();
return CustomerOrderModel.fromMap(res);
} catch (e) {
debugPrint('Errore insertOrder: $e');
throw Exception('Errore nella creazione dell\'ordine: $e');
}
}
Future<CustomerOrderModel> updateOrder(CustomerOrderModel order) async {
try {
final res = await _supabase
.from(Tables.customerOrders)
.update(order.toMap())
.eq('id', order.id!)
.select(_selectRelations)
.single();
notifyOrdersChanged();
return CustomerOrderModel.fromMap(res);
} catch (e) {
debugPrint('Errore updateOrder: $e');
throw Exception('Errore nell\'aggiornamento dell\'ordine: $e');
}
}
Future<void> deleteOrder(String id) async {
try {
await _supabase.from(Tables.customerOrders).delete().eq('id', id);
notifyOrdersChanged();
} catch (e) {
debugPrint('Errore deleteOrder: $e');
throw Exception('Errore nell\'eliminazione dell\'ordine: $e');
}
}
}
@@ -0,0 +1,254 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customers/models/customer_model.dart';
class CustomerOrderModel extends Equatable {
final String? id;
final DateTime? createdAt;
final DateTime? updatedAt;
final DateTime orderDate;
final String companyId;
final String? storeId;
final String? storeDisplayName;
final String? createdById;
final String? createdByName;
final String? customerId;
final CustomerModel? customer;
final String productDescription;
final int quantity;
final String notes;
final double price;
final double deposit;
final String externalCode;
final CustomerOrderStatus status;
final List<String> tags;
final ContactPreference contactPreference;
final String? alternativePhoneNumber;
final bool customerNotified;
final DateTime? customerNotifiedAt;
final List<AttachmentModel> attachments;
const CustomerOrderModel({
this.id,
this.createdAt,
this.updatedAt,
required this.orderDate,
required this.companyId,
this.storeId,
this.storeDisplayName,
this.createdById,
this.createdByName,
this.customerId,
this.customer,
this.productDescription = '',
this.quantity = 1,
this.notes = '',
this.price = 0.0,
this.deposit = 0.0,
this.externalCode = '',
this.status = CustomerOrderStatus.toOrder,
this.tags = const [],
this.contactPreference = ContactPreference.whatsappPrimary,
this.alternativePhoneNumber,
this.customerNotified = false,
this.customerNotifiedAt,
this.attachments = const [],
});
/// Importo residuo da incassare in cassa al netto dell'eventuale acconto
double get remainingAmount =>
(price - deposit) > 0 ? (price - deposit) : 0.0;
/// URL deep link codificato nel QR dell'etichetta prodotto
String get deepLinkUrl =>
id != null && id!.isNotEmpty ? 'https://flux.catelli.it/orders/form/$id' : '';
/// Recapito effettivo da usare in base alla preferenza scelta
String get effectiveContactDestination {
if (contactPreference.isEmail) {
return customer?.email.trim() ?? '';
}
if (contactPreference.usesAlternativePhone) {
final orderAlt = alternativePhoneNumber?.trim() ?? '';
if (orderAlt.isNotEmpty) return orderAlt;
return customer?.alternativePhoneNumber.trim() ?? '';
}
return customer?.phoneNumber.trim() ?? '';
}
factory CustomerOrderModel.empty() => CustomerOrderModel(
orderDate: DateTime.now(),
companyId: '',
);
CustomerOrderModel copyWith({
String? id,
DateTime? createdAt,
DateTime? updatedAt,
DateTime? orderDate,
String? companyId,
String? storeId,
String? storeDisplayName,
String? createdById,
String? createdByName,
String? customerId,
CustomerModel? customer,
String? productDescription,
int? quantity,
String? notes,
double? price,
double? deposit,
String? externalCode,
CustomerOrderStatus? status,
List<String>? tags,
ContactPreference? contactPreference,
String? alternativePhoneNumber,
bool? customerNotified,
DateTime? customerNotifiedAt,
bool clearCustomerNotifiedAt = false,
List<AttachmentModel>? attachments,
}) {
return CustomerOrderModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
orderDate: orderDate ?? this.orderDate,
companyId: companyId ?? this.companyId,
storeId: storeId ?? this.storeId,
storeDisplayName: storeDisplayName ?? this.storeDisplayName,
createdById: createdById ?? this.createdById,
createdByName: createdByName ?? this.createdByName,
customerId: customerId ?? this.customerId,
customer: customer ?? this.customer,
productDescription: productDescription ?? this.productDescription,
quantity: quantity != null ? (quantity < 1 ? 1 : quantity) : this.quantity,
notes: notes ?? this.notes,
price: price ?? this.price,
deposit: deposit ?? this.deposit,
externalCode: externalCode ?? this.externalCode,
status: status ?? this.status,
tags: tags ?? this.tags,
contactPreference: contactPreference ?? this.contactPreference,
alternativePhoneNumber:
alternativePhoneNumber ?? this.alternativePhoneNumber,
customerNotified: customerNotified ?? this.customerNotified,
customerNotifiedAt: clearCustomerNotifiedAt
? null
: (customerNotifiedAt ?? this.customerNotifiedAt),
attachments: attachments ?? this.attachments,
);
}
factory CustomerOrderModel.fromMap(Map<String, dynamic> map) {
final rawQty = (map['quantity'] as num?)?.toInt() ?? 1;
final rawTags = (map['tags'] as List?)
?.map((e) => e.toString().trim())
.where((e) => e.isNotEmpty)
.toList() ??
const <String>[];
final createdAtLocal = map['created_at'] != null
? DateTime.parse(map['created_at'] as String).toLocal()
: null;
return CustomerOrderModel(
id: map['id'] as String?,
createdAt: createdAtLocal,
updatedAt: map['updated_at'] != null
? DateTime.parse(map['updated_at'] as String).toLocal()
: null,
orderDate: map['order_date'] != null
? DateTime.parse(map['order_date'] as String).toLocal()
: (createdAtLocal ?? DateTime.now()),
companyId: map['company_id'] as String? ?? '',
storeId: map['store_id'] as String?,
storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(),
createdById: map['created_by_id'] as String?,
createdByName: (map[Tables.staffMembers]?['name'] as String?)?.myFormat(),
customerId: map['customer_id'] as String?,
customer: map[Tables.customers] != null
? CustomerModel.fromMap(
map[Tables.customers] as Map<String, dynamic>,
)
: null,
productDescription: map['product_description'] as String? ?? '',
quantity: rawQty < 1 ? 1 : rawQty,
notes: map['notes'] as String? ?? '',
price: (map['price'] as num?)?.toDouble() ?? 0.0,
deposit: (map['deposit'] as num?)?.toDouble() ?? 0.0,
externalCode: map['external_code'] as String? ?? '',
status: CustomerOrderStatus.fromString(map['status'] as String?),
tags: rawTags,
contactPreference: ContactPreference.fromString(
map['contact_preference'] as String?,
),
alternativePhoneNumber: map['alternative_phone_number'] as String?,
customerNotified: map['customer_notified'] as bool? ?? false,
customerNotifiedAt: map['customer_notified_at'] != null
? DateTime.parse(map['customer_notified_at'] as String).toLocal()
: null,
attachments: (map[Tables.attachments] as List?)
?.map(
(x) => AttachmentModel.fromMap(x as Map<String, dynamic>),
)
.toList() ??
const [],
);
}
Map<String, dynamic> toMap() {
return {
if (id != null && id!.isNotEmpty) 'id': id,
'order_date': orderDate.toUtc().toIso8601String(),
'company_id': companyId,
'store_id': storeId,
if (createdById != null && createdById!.isNotEmpty)
'created_by_id': createdById,
'customer_id': customerId,
'product_description': productDescription.trim(),
'quantity': quantity < 1 ? 1 : quantity,
'notes': notes.trim(),
'price': price,
'deposit': deposit,
'external_code': externalCode.trim(),
'status': status.value,
'tags': tags.map((t) => t.trim()).where((t) => t.isNotEmpty).toList(),
'contact_preference': contactPreference.value,
'alternative_phone_number': alternativePhoneNumber?.trim(),
'customer_notified': customerNotified,
'customer_notified_at': customerNotifiedAt?.toUtc().toIso8601String(),
};
}
@override
List<Object?> get props => [
id,
createdAt,
updatedAt,
orderDate,
companyId,
storeId,
storeDisplayName,
createdById,
createdByName,
customerId,
customer,
productDescription,
quantity,
notes,
price,
deposit,
externalCode,
status,
tags,
contactPreference,
alternativePhoneNumber,
customerNotified,
customerNotifiedAt,
attachments,
];
}
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
/// Stato del ciclo di vita di un Ordine Cliente
enum CustomerOrderStatus {
toOrder(
value: 'to_order',
label: 'Da ordinare',
icon: Icons.shopping_cart_checkout_rounded,
color: Colors.deepOrange,
isActive: true,
),
ordered(
value: 'ordered',
label: 'Ordinato',
icon: Icons.local_shipping_outlined,
color: Colors.blue,
isActive: true,
),
arrived(
value: 'arrived',
label: 'Arrivato',
icon: Icons.inventory_2_rounded,
color: Colors.teal,
isActive: true,
),
delivered(
value: 'delivered',
label: 'Consegnato',
icon: Icons.check_circle_rounded,
color: Colors.green,
isActive: false,
),
cancelled(
value: 'cancelled',
label: 'Annullato',
icon: Icons.cancel_outlined,
color: Colors.grey,
isActive: false,
);
final String value;
final String label;
final IconData icon;
final Color color;
final bool isActive;
const CustomerOrderStatus({
required this.value,
required this.label,
required this.icon,
required this.color,
required this.isActive,
});
static CustomerOrderStatus fromString(String? val) {
if (val == null || val.trim().isEmpty) return CustomerOrderStatus.toOrder;
final clean = val.trim().toLowerCase();
for (final s in CustomerOrderStatus.values) {
if (s.value == clean || s.name.toLowerCase() == clean) {
return s;
}
}
return CustomerOrderStatus.toOrder;
}
}
/// Filtro rapido di stato nella lista Ordini Clienti
enum CustomerOrderQuickFilter {
active('Da ultimare'),
toOrder('Da ordinare'),
ordered('Ordinati'),
arrived('Arrivati'),
delivered('Consegnati'),
all('Tutti');
final String label;
const CustomerOrderQuickFilter(this.label);
List<String>? get dbStatuses {
switch (this) {
case CustomerOrderQuickFilter.active:
return [
CustomerOrderStatus.toOrder.value,
CustomerOrderStatus.ordered.value,
CustomerOrderStatus.arrived.value,
];
case CustomerOrderQuickFilter.toOrder:
return [CustomerOrderStatus.toOrder.value];
case CustomerOrderQuickFilter.ordered:
return [CustomerOrderStatus.ordered.value];
case CustomerOrderQuickFilter.arrived:
return [CustomerOrderStatus.arrived.value];
case CustomerOrderQuickFilter.delivered:
return [CustomerOrderStatus.delivered.value];
case CustomerOrderQuickFilter.all:
return null;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,770 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/models/customer_order_status.dart';
import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart';
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:printing/printing.dart';
class CustomerOrderListScreen extends StatefulWidget {
const CustomerOrderListScreen({super.key});
@override
State<CustomerOrderListScreen> createState() =>
_CustomerOrderListScreenState();
}
class _CustomerOrderListScreenState extends State<CustomerOrderListScreen> {
final TextEditingController _searchCtrl = TextEditingController();
@override
void initState() {
super.initState();
context.read<CustomerOrderListCubit>().init();
context.read<StoreCubit>().loadStores();
}
@override
void dispose() {
_searchCtrl.dispose();
super.dispose();
}
Future<void> _createNewOrder(BuildContext context) async {
final createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, order: null),
);
}
Future<void> _pickDateRange(
BuildContext context,
DateTimeRange? current,
) async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2023),
lastDate: DateTime.now().add(const Duration(days: 365)),
initialDateRange: current,
);
if (picked != null && context.mounted) {
context.read<CustomerOrderListCubit>().setDateRange(picked);
}
}
Future<void> _printLabel(BuildContext context, CustomerOrderModel order) async {
final service = CustomerOrderLabelPdfService();
await Printing.layoutPdf(
name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}',
onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final dateFmt = DateFormat('dd/MM/yyyy');
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
return BlocBuilder<CustomerOrderListCubit, CustomerOrderListState>(
builder: (context, state) {
return Scaffold(
backgroundColor: theme.colorScheme.surface,
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _createNewOrder(context),
icon: const Icon(Icons.add_shopping_cart_rounded),
label: const Text('Nuovo Ordine'),
),
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final isMobile = constraints.maxWidth < 650;
final hPad = isMobile ? 16.0 : 24.0;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// --- HEADER & FILTRI ---
Padding(
padding: EdgeInsets.fromLTRB(hPad, 16, hPad, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ordini Clienti',
style: (isMobile
? theme.textTheme.titleLarge
: theme.textTheme.headlineSmall)
?.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'Richieste prodotti, etichette acquisti e ritiri in cassa',
style: theme.textTheme.bodySmall
?.copyWith(
color: theme
.colorScheme
.onSurfaceVariant,
),
),
],
),
),
IconButton(
tooltip: 'Aggiorna lista',
onPressed: () => context
.read<CustomerOrderListCubit>()
.init(),
icon: const Icon(Icons.refresh_rounded),
),
],
),
const SizedBox(height: 12),
// Barra ricerca + Data + Negozio
Wrap(
spacing: 10,
runSpacing: 10,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
SizedBox(
width: isMobile ? double.infinity : 320,
child: TextField(
controller: _searchCtrl,
onChanged: (val) => context
.read<CustomerOrderListCubit>()
.setSearchTerm(val),
decoration: InputDecoration(
hintText:
'Cerca cliente, prodotto, codice cassa...',
prefixIcon: const Icon(
Icons.search,
size: 20,
),
isDense: true,
suffixIcon:
_searchCtrl.text.trim().isNotEmpty
? IconButton(
icon: const Icon(
Icons.clear,
size: 18,
),
onPressed: () {
_searchCtrl.clear();
context
.read<
CustomerOrderListCubit
>()
.setSearchTerm('');
},
)
: null,
),
),
),
// Filtro Date
OutlinedButton.icon(
icon: Icon(
Icons.date_range_outlined,
size: 18,
color: state.dateRange != null
? theme.colorScheme.primary
: null,
),
label: Text(
state.dateRange != null
? '${dateFmt.format(state.dateRange!.start)} - ${dateFmt.format(state.dateRange!.end)}'
: 'Filtra Date',
),
onPressed: () =>
_pickDateRange(context, state.dateRange),
),
if (state.dateRange != null)
IconButton(
tooltip: 'Rimuovi filtro date',
visualDensity: VisualDensity.compact,
onPressed: () => context
.read<CustomerOrderListCubit>()
.setDateRange(null),
icon: const Icon(Icons.close, size: 18),
),
// Filtro Negozio
BlocBuilder<StoreCubit, StoreState>(
builder: (context, storeState) {
if (storeState.stores.length <= 1) {
return const SizedBox.shrink();
}
return DropdownButtonHideUnderline(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
decoration: BoxDecoration(
border: Border.all(
color: theme.dividerColor.withValues(
alpha: 0.5,
),
),
borderRadius: BorderRadius.circular(8),
),
child: DropdownButton<String?>(
value: state.storeIdFilter,
hint: const Text('Tutti i negozi'),
isDense: true,
items: [
const DropdownMenuItem<String?>(
value: null,
child: Text('Tutti i negozi'),
),
...storeState.stores.map(
(s) => DropdownMenuItem<String?>(
value: s.id,
child: Text(s.name),
),
),
],
onChanged: (val) => context
.read<CustomerOrderListCubit>()
.setStoreFilter(val),
),
),
);
},
),
if (state.hasAdvancedFilters)
TextButton.icon(
onPressed: () {
_searchCtrl.clear();
context
.read<CustomerOrderListCubit>()
.resetFilters();
},
icon: const Icon(
Icons.filter_alt_off_outlined,
size: 18,
),
label: const Text('Azzera filtri'),
),
],
),
const SizedBox(height: 10),
// Quick Status Filters (Default: "Da ultimare")
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: CustomerOrderQuickFilter.values.map((
f,
) {
final selected = state.quickFilter == f;
return Padding(
padding: const EdgeInsets.only(right: 8),
child: ChoiceChip(
label: Text(f.label),
selected: selected,
onSelected: (_) => context
.read<CustomerOrderListCubit>()
.setQuickFilter(f),
),
);
}).toList(),
),
),
// Filtro Etichette (se presenti)
if (state.availableTags.isNotEmpty) ...[
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Icon(
Icons.label_outline_rounded,
size: 16,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(width: 6),
...state.availableTags.map((tag) {
final isSelected = state.selectedTags
.contains(tag);
return Padding(
padding: const EdgeInsets.only(right: 6),
child: FilterChip(
visualDensity: VisualDensity.compact,
label: Text(
tag,
style: const TextStyle(fontSize: 12),
),
selected: isSelected,
onSelected: (_) => context
.read<CustomerOrderListCubit>()
.toggleTagFilter(tag),
),
);
}),
],
),
),
],
],
),
),
const Divider(height: 1),
// --- CORPO LISTA ---
Expanded(
child: _buildListBody(
context,
theme,
state,
hPad: hPad,
dateFmt: dateFmt,
currencyFmt: currencyFmt,
),
),
],
);
},
),
),
);
},
);
}
Widget _buildListBody(
BuildContext context,
ThemeData theme,
CustomerOrderListState state, {
required double hPad,
required DateFormat dateFmt,
required NumberFormat currencyFmt,
}) {
if (state.status == CustomerOrderListStatus.loading &&
state.orders.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == CustomerOrderListStatus.failure) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Text(
'Errore nel caricamento ordini:\n${state.errorMessage}',
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error),
),
),
);
}
if (state.orders.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.inventory_2_outlined,
size: 56,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
),
const SizedBox(height: 12),
Text(
'Nessun ordine trovato per i filtri selezionati.',
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: 15,
),
),
],
),
);
}
return ListView.separated(
padding: EdgeInsets.fromLTRB(hPad, 14, hPad, 96),
itemCount: state.orders.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final order = state.orders[index];
return _buildOrderCard(
context,
theme,
order,
dateFmt: dateFmt,
currencyFmt: currencyFmt,
);
},
);
}
Widget _buildOrderCard(
BuildContext context,
ThemeData theme,
CustomerOrderModel order, {
required DateFormat dateFmt,
required NumberFormat currencyFmt,
}) {
final status = order.status;
final pref = order.contactPreference;
final needsCustomerAlert =
status == CustomerOrderStatus.arrived && !order.customerNotified;
return Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(
color: status == CustomerOrderStatus.arrived
? Colors.teal.withValues(alpha: 0.5)
: theme.dividerColor.withValues(alpha: 0.35),
width: status == CustomerOrderStatus.arrived ? 1.4 : 1,
),
),
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': order.id!},
extra: (createdBy: null, order: order),
),
child: Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Riga 1: Data + Negozio + Stato cliccabile + Stampa QR rapida
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.calendar_today_outlined,
size: 13,
color: context.secondaryText,
),
const SizedBox(width: 4),
Text(
dateFmt.format(order.orderDate),
style: TextStyle(
fontSize: 12,
color: context.secondaryText,
fontWeight: FontWeight.w600,
),
),
if (order.storeDisplayName != null &&
order.storeDisplayName!.isNotEmpty) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(
alpha: 0.08,
),
borderRadius: BorderRadius.circular(6),
),
child: Text(
order.storeDisplayName!,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary,
),
),
),
],
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (needsCustomerAlert)
Container(
margin: const EdgeInsets.only(right: 6),
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Colors.amber.shade600),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.notifications_active_outlined,
size: 13,
color: Colors.amber.shade900,
),
const SizedBox(width: 4),
Text(
'Da avvisare',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.amber.shade900,
),
),
],
),
)
else if (order.customerNotified)
Container(
margin: const EdgeInsets.only(right: 6),
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: const Text(
'Avvisato ✓',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
),
// Menu rapido cambio stato
PopupMenuButton<CustomerOrderStatus>(
tooltip: 'Cambia stato rapidamente',
onSelected: (newStatus) {
context
.read<CustomerOrderListCubit>()
.quickUpdateStatus(order, newStatus);
},
itemBuilder: (_) => CustomerOrderStatus.values
.map(
(s) => PopupMenuItem(
value: s,
child: Row(
children: [
Icon(s.icon, size: 18, color: s.color),
const SizedBox(width: 8),
Text(s.label),
],
),
),
)
.toList(),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 9,
vertical: 4,
),
decoration: BoxDecoration(
color: status.color.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: status.color.withValues(alpha: 0.45),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(status.icon, size: 14, color: status.color),
const SizedBox(width: 5),
Text(
status.label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: status.color,
),
),
const SizedBox(width: 2),
Icon(
Icons.arrow_drop_down,
size: 16,
color: status.color,
),
],
),
),
),
if (order.id != null) ...[
const SizedBox(width: 4),
IconButton(
tooltip: 'Stampa etichetta QR',
visualDensity: VisualDensity.compact,
onPressed: () => _printLabel(context, order),
icon: const Icon(Icons.qr_code_2_rounded, size: 20),
),
],
],
),
],
),
const SizedBox(height: 8),
// Riga 2: Prodotto + Quantità
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
order.quantity > 1
? '${order.productDescription} ×${order.quantity}'
: order.productDescription,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
),
),
),
if (order.price > 0) ...[
const SizedBox(width: 8),
Text(
currencyFmt.format(order.price),
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
color: theme.colorScheme.primary,
),
),
],
],
),
const SizedBox(height: 6),
// Riga 3: Cliente + Canale di avviso + Codice Cassa / Acconto
Wrap(
spacing: 12,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.person_outline, size: 15),
const SizedBox(width: 4),
Text(
order.customer?.name ?? 'Cliente sconosciuto',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
pref.buildIcon(size: 14),
const SizedBox(width: 4),
Text(
pref.shortLabel,
style: TextStyle(
fontSize: 12,
color: pref.color,
fontWeight: FontWeight.w600,
),
),
],
),
if (order.externalCode.isNotEmpty)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(5),
),
child: Text(
'Cod. Cassa: ${order.externalCode}',
style: const TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
),
),
),
if (order.deposit > 0)
Text(
'Acconto: ${currencyFmt.format(order.deposit)}',
style: TextStyle(
fontSize: 12,
color: Colors.teal.shade700,
fontWeight: FontWeight.w600,
),
),
],
),
// Riga 4: Etichette (se presenti)
if (order.tags.isNotEmpty) ...[
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 4,
children: order.tags
.map(
(tag) => Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.deepPurple.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.deepPurple.withValues(alpha: 0.3),
),
),
child: Text(
'#$tag',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: Colors.deepPurple,
),
),
),
)
.toList(),
),
],
],
),
),
),
);
}
}
@@ -0,0 +1,116 @@
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
class CustomerOrderLabelPdfService {
/// Genera il PDF dell'etichetta prodotto con QR code, leggendo le misure
/// configurate nelle Impostazioni Azienda (fallback 40 x 30 mm).
Future<pw.Document> generateOrderLabelPdf(CustomerOrderModel order) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
final company = GetIt.I.get<SessionCubit>().state.company;
final widthMm = company?.labelWidth ?? 40.0;
final heightMm = company?.labelHeight ?? 30.0;
final isVertical = company?.isLabelVertical ?? false;
final pageFormat = isVertical
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
: PdfPageFormat(widthMm * PdfPageFormat.mm, heightMm * PdfPageFormat.mm);
final effectiveW = pageFormat.width;
final effectiveH = pageFormat.height;
final minSide = effectiveW < effectiveH ? effectiveW : effectiveH;
final qrSize = (minSide - 6 * PdfPageFormat.mm).clamp(
14 * PdfPageFormat.mm,
26 * PdfPageFormat.mm,
);
final customerName = order.customer?.name ?? 'Cliente';
final qtySuffix = order.quantity > 1 ? ' (x${order.quantity})' : '';
final productLine = '${order.productDescription}$qtySuffix';
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final priceStr = order.price > 0 ? currencyFmt.format(order.price) : '';
final codeStr = order.externalCode.trim();
final qrData = order.deepLinkUrl.isNotEmpty
? order.deepLinkUrl
: (order.id ?? '');
pdf.addPage(
pw.Page(
pageFormat: pageFormat,
margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm),
build: (context) {
final infoBlock = pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
mainAxisAlignment: pw.MainAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text(
customerName,
style: pw.TextStyle(font: boldFont, fontSize: 8.5),
maxLines: 1,
overflow: pw.TextOverflow.clip,
),
pw.SizedBox(height: 1.5),
pw.Text(
productLine,
style: pw.TextStyle(font: font, fontSize: 7.2),
maxLines: 2,
overflow: pw.TextOverflow.clip,
),
if (codeStr.isNotEmpty || priceStr.isNotEmpty) ...[
pw.SizedBox(height: 2),
pw.Text(
[
if (codeStr.isNotEmpty) 'Cod: $codeStr',
if (priceStr.isNotEmpty) priceStr,
].join(' • '),
style: pw.TextStyle(font: boldFont, fontSize: 7.5),
maxLines: 1,
overflow: pw.TextOverflow.clip,
),
],
],
);
final qrWidget = pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(),
data: qrData,
width: qrSize,
height: qrSize,
);
if (effectiveH > effectiveW) {
return pw.Column(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
infoBlock,
pw.SizedBox(height: 2),
qrWidget,
],
);
}
return pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
pw.Expanded(child: infoBlock),
pw.SizedBox(width: 2 * PdfPageFormat.mm),
qrWidget,
],
);
},
),
);
return pdf;
}
}
@@ -65,6 +65,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
void updateFields({
String? name,
String? phoneNumber,
String? alternativePhoneNumber,
String? email,
String? note,
bool? doNotDisturb,
@@ -76,6 +77,8 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
customer: state.customer.copyWith(
name: name ?? state.customer.name,
phoneNumber: phoneNumber ?? state.customer.phoneNumber,
alternativePhoneNumber:
alternativePhoneNumber ?? state.customer.alternativePhoneNumber,
email: email ?? state.customer.email,
note: note ?? state.customer.note,
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
@@ -112,16 +115,19 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
Future<CustomerModel?> quickCreateCustomer({
required String name,
String? phone,
String? alternativePhone,
String? email,
String? note,
required bool isBusiness,
String? fiscalCode,
}) async {
final newCustomer = CustomerModel(
name: name,
phoneNumber: phone ?? '',
alternativePhoneNumber: alternativePhone ?? '',
email: email ?? '',
companyId: _sessionCubit.state.company!.id!,
note: '',
note: note ?? '',
isBusiness: isBusiness,
fiscalCode: fiscalCode?.trim().toUpperCase(),
);
@@ -7,6 +7,7 @@ class CustomerModel extends Equatable {
final DateTime? createdAt;
final String name;
final String phoneNumber;
final String alternativePhoneNumber;
final String email;
final String note;
final DateTime? lastContactDate;
@@ -22,6 +23,7 @@ class CustomerModel extends Equatable {
this.createdAt,
required this.name,
required this.phoneNumber,
this.alternativePhoneNumber = '',
required this.email,
required this.note,
this.lastContactDate,
@@ -39,6 +41,7 @@ class CustomerModel extends Equatable {
createdAt,
name,
phoneNumber,
alternativePhoneNumber,
email,
note,
lastContactDate,
@@ -50,13 +53,13 @@ class CustomerModel extends Equatable {
fiscalCode,
];
factory CustomerModel.empty() => CustomerModel(
factory CustomerModel.empty() => const CustomerModel(
name: '',
phoneNumber: '',
alternativePhoneNumber: '',
email: '',
note: '',
companyId:
'', // Dovrebbe essere sempre fornito, ma lasciamo vuoto per sicurezza
companyId: '',
);
CustomerModel copyWith({
@@ -64,6 +67,7 @@ class CustomerModel extends Equatable {
DateTime? createdAt,
String? name,
String? phoneNumber,
String? alternativePhoneNumber,
String? email,
String? note,
DateTime? lastContactDate,
@@ -79,6 +83,8 @@ class CustomerModel extends Equatable {
createdAt: createdAt ?? this.createdAt,
name: name ?? this.name,
phoneNumber: phoneNumber ?? this.phoneNumber,
alternativePhoneNumber:
alternativePhoneNumber ?? this.alternativePhoneNumber,
email: email ?? this.email,
note: note ?? this.note,
lastContactDate: lastContactDate ?? this.lastContactDate,
@@ -98,8 +104,9 @@ class CustomerModel extends Equatable {
? DateTime.parse(map['created_at'])
: null,
name: (map['name'] as String).myFormat(),
phoneNumber: map['phone_number'],
email: map['email'],
phoneNumber: map['phone_number'] as String? ?? '',
alternativePhoneNumber: map['alternative_phone_number'] as String? ?? '',
email: map['email'] as String? ?? '',
note: map['note'] ?? '',
lastContactDate: map['last_contact_date'] != null
? DateTime.parse(map['last_contact_date'])
@@ -117,11 +124,14 @@ class CustomerModel extends Equatable {
);
}
Map<String, dynamic> toMap() => toJson();
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
'name': name.toLowerCase().trim(),
'phone_number': phoneNumber,
'phone_number': phoneNumber.trim(),
'alternative_phone_number': alternativePhoneNumber.trim(),
'email': email.toLowerCase().trim(),
'note': note,
if (lastContactDate != null)
@@ -352,7 +352,9 @@ class _FileCard extends StatelessWidget {
height: MediaQuery.of(context).size.height * 0.8,
child: file.isPdf
? PdfViewerWidget(storagePath: file.storagePath)
: ImageViewerWidget(storagePath: file.storagePath),
: ImageViewerWidget(
storagePath: file.effectiveStoragePath,
),
),
),
),
@@ -23,6 +23,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
// Controller inizializzati con i dati del cliente (se presenti)
final TextEditingController _nomeController = TextEditingController();
final TextEditingController _telefonoController = TextEditingController();
final TextEditingController _telefonoAltController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _noteController = TextEditingController();
final TextEditingController _fiscalCodeController = TextEditingController();
@@ -49,6 +50,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
void dispose() {
_nomeController.dispose();
_telefonoController.dispose();
_telefonoAltController.dispose();
_emailController.dispose();
_noteController.dispose();
_fiscalCodeController.dispose();
@@ -62,6 +64,9 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
if (_telefonoController.text.isEmpty) {
_telefonoController.text = customer.phoneNumber;
}
if (_telefonoAltController.text.isEmpty) {
_telefonoAltController.text = customer.alternativePhoneNumber;
}
if (_emailController.text.isEmpty) {
_emailController.text = customer.email;
}
@@ -78,6 +83,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
context.read<CustomerFormCubit>().updateFields(
name: _nomeController.text.trim(),
phoneNumber: _telefonoController.text.trim(),
alternativePhoneNumber: _telefonoAltController.text.trim(),
email: _emailController.text.trim(),
note: _noteController.text.trim(),
fiscalCode: _fiscalCodeController.text.trim(),
@@ -166,12 +172,19 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
),
const SizedBox(height: 16),
FluxTextField(
label: 'Telefono',
label: 'Telefono Principale',
icon: Icons.phone_android_outlined,
controller: _telefonoController,
keyboardType: TextInputType.phone,
),
const SizedBox(height: 16),
FluxTextField(
label: 'Recapito Alternativo',
icon: Icons.phone_forwarded_outlined,
controller: _telefonoAltController,
keyboardType: TextInputType.phone,
),
const SizedBox(height: 16),
FluxTextField(
label: 'Email',
icon: Icons.alternate_email_outlined,
@@ -15,6 +15,7 @@ class QuickCustomerDialog extends StatefulWidget {
class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
late final TextEditingController _nameCtrl;
final _phoneCtrl = TextEditingController();
final _altPhoneCtrl = TextEditingController();
final _emailCtrl = TextEditingController();
final _noteCtrl = TextEditingController();
bool _isBusiness = false;
@@ -33,6 +34,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
void dispose() {
_nameCtrl.dispose();
_phoneCtrl.dispose();
_altPhoneCtrl.dispose();
_emailCtrl.dispose();
_noteCtrl.dispose();
_fiscalCodeCtrl.dispose();
@@ -52,7 +54,9 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
isBusiness: _isBusiness,
name: _nameCtrl.text.trim(),
phone: _phoneCtrl.text.trim(),
alternativePhone: _altPhoneCtrl.text.trim(),
email: _emailCtrl.text.trim(),
note: _noteCtrl.text.trim(),
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
);
@@ -117,7 +121,18 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
const SizedBox(height: 8),
TextField(
controller: _phoneCtrl,
decoration: const InputDecoration(labelText: "Telefono"),
decoration: const InputDecoration(
labelText: "Telefono Principale",
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 8),
TextField(
controller: _altPhoneCtrl,
decoration: const InputDecoration(
labelText: "Recapito Alternativo (opzionale)",
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
),
@@ -0,0 +1,248 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:get_it/get_it.dart';
import 'dashboard_daily_ricontatti_state.dart';
class DashboardDailyRicontattiCubit extends Cubit<DashboardDailyRicontattiState> {
final OperationsRepository _operationsRepository;
final StaffRepository _staffRepository;
String? companyId;
String? storeId;
StreamSubscription<void>? _operationsSubscription;
Timer? _pollingTimer;
DashboardDailyRicontattiCubit({
this.companyId,
this.storeId,
OperationsRepository? operationsRepository,
StaffRepository? staffRepository,
}) : _operationsRepository =
operationsRepository ?? GetIt.I.get<OperationsRepository>(),
_staffRepository = staffRepository ?? GetIt.I.get<StaffRepository>(),
super(
DashboardDailyRicontattiState(
date: DateTime.now(),
),
);
void updateContext({
String? newCompanyId,
String? newStoreId,
}) {
bool changed = false;
if (newCompanyId != null && newCompanyId != companyId) {
companyId = newCompanyId;
changed = true;
}
if (newStoreId != null && newStoreId != storeId) {
storeId = newStoreId;
changed = true;
}
if (changed) {
refresh();
}
}
void startListening() {
emit(state.copyWith(status: DashboardDailyRicontattiStatus.loading));
stopListening();
_loadDailyRicontattiSilently();
// 1. Ascolto notifiche di creazione/modifica operazioni in real-time
_operationsSubscription =
_operationsRepository.onOperationsChanged.listen((_) {
_loadDailyRicontattiSilently();
});
// 2. Polling periodico ogni 30 secondi
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
_loadDailyRicontattiSilently();
});
}
void stopListening() {
_operationsSubscription?.cancel();
_operationsSubscription = null;
_pollingTimer?.cancel();
_pollingTimer = null;
}
void refresh() {
_loadDailyRicontattiSilently();
}
Future<void> _loadDailyRicontattiSilently() async {
if (companyId == null || storeId == null) {
if (!isClosed) {
emit(
state.copyWith(
status: DashboardDailyRicontattiStatus.initial,
summaries: [],
totalRicontattiToday: 0,
totalRicontattiMonth: 0,
),
);
}
return;
}
try {
final now = DateTime.now();
final todayStart = DateTime(now.year, now.month, now.day, 0, 0, 0);
final todayEnd = DateTime(now.year, now.month, now.day, 23, 59, 59, 999);
// 1. Recupero staff del negozio
final allStaff = await _staffRepository.getStaffMembers(
companyId!,
storeId: storeId,
);
// 1. Escludiamo i collaboratori con qualifica Manager o Tester, o disattivati
final Set<String> excludedStaffIds = {};
for (final s in allStaff) {
if (s.isExcludedFromRicontattiFocus && s.id != null) {
excludedStaffIds.add(s.id!);
}
}
final activeEligibleStaff = allStaff
.where((s) => !s.isExcludedFromRicontattiFocus)
.toList();
// 2. Recupero conteggi mensili per addetto del negozio
final monthlyCountsByStaff =
await _operationsRepository.getMonthlyRicontattiCountsByStaff(
companyId: companyId!,
storeId: storeId!,
month: now,
);
// 3. Recupero operazioni create oggi nel negozio
final paginatedOps = await _operationsRepository.fetchPaginatedOperations(
companyId: companyId!,
storeId: storeId,
dateRange: DateTimeRange(start: todayStart, end: todayEnd),
page: 1,
itemsPerPage: 150,
onlyShowInDashboard: false,
);
// 4. Filtro per tipo Ricontatto
final ricontattiOps = paginatedOps.operations.where((op) {
return op.details.any((d) => d.type == OperationType.ricontatto);
}).toList();
// 5. Raggruppamento per addetto ammissibile
final List<StaffDailyRicontattiSummary> summaries = [];
final Set<String> processedStaffIds = Set<String>.from(excludedStaffIds);
for (final staff in activeEligibleStaff) {
final staffId = staff.id ?? '';
processedStaffIds.add(staffId);
final staffOps = ricontattiOps.where((op) => op.staffId == staffId).toList();
int staffCount = 0;
for (final op in staffOps) {
final countInOp = op.details.where((d) => d.type == OperationType.ricontatto).length;
staffCount += countInOp > 0 ? countInOp : 1;
}
final staffMonthCount = monthlyCountsByStaff[staffId] ?? 0;
summaries.add(
StaffDailyRicontattiSummary(
staffId: staffId,
staffName: staff.name,
jobTitle: staff.jobTitle,
systemRole: staff.systemRole,
count: staffCount,
monthCount: staffMonthCount,
operations: staffOps,
),
);
}
// 6. Verifica se ci sono operazioni attribuite a staff non presente nella lista
for (final op in ricontattiOps) {
final opStaffId = op.staffId ?? '';
if (opStaffId.isNotEmpty && !processedStaffIds.contains(opStaffId)) {
processedStaffIds.add(opStaffId);
final staffOps = ricontattiOps.where((o) => o.staffId == opStaffId).toList();
int staffCount = 0;
for (final o in staffOps) {
final countInOp = o.details.where((d) => d.type == OperationType.ricontatto).length;
staffCount += countInOp > 0 ? countInOp : 1;
}
final staffMonthCount = monthlyCountsByStaff[opStaffId] ?? 0;
summaries.add(
StaffDailyRicontattiSummary(
staffId: opStaffId,
staffName: op.staffDisplayName ?? 'Operatore',
count: staffCount,
monthCount: staffMonthCount,
operations: staffOps,
),
);
}
}
// 7. Calcolo totali coerenti con gli addetti visibili
int grandTotal = 0;
int grandMonthTotal = 0;
for (final s in summaries) {
grandTotal += s.count;
grandMonthTotal += s.monthCount;
}
// 8. Ordinamento: per numero di ricontatti oggi decrescente, poi per mese decrescente, poi per nome
summaries.sort((a, b) {
final countCmp = b.count.compareTo(a.count);
if (countCmp != 0) return countCmp;
final monthCmp = b.monthCount.compareTo(a.monthCount);
if (monthCmp != 0) return monthCmp;
return a.staffName.toLowerCase().compareTo(b.staffName.toLowerCase());
});
if (isClosed) return;
emit(
state.copyWith(
status: DashboardDailyRicontattiStatus.success,
summaries: summaries,
totalRicontattiToday: grandTotal,
totalRicontattiMonth: grandMonthTotal,
date: now,
errorMessage: null,
),
);
} catch (e, stack) {
debugPrint('Errore in DashboardDailyRicontattiCubit: $e\n$stack');
if (isClosed) return;
emit(
state.copyWith(
status: DashboardDailyRicontattiStatus.failure,
errorMessage: e.toString(),
),
);
}
}
@override
Future<void> close() {
stopListening();
return super.close();
}
}
@@ -0,0 +1,64 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
enum DashboardDailyRicontattiStatus { initial, loading, success, failure }
class DashboardDailyRicontattiState extends Equatable {
final DashboardDailyRicontattiStatus status;
final List<StaffDailyRicontattiSummary> summaries;
final int totalRicontattiToday;
final int totalRicontattiMonth;
final DateTime date;
final String? errorMessage;
const DashboardDailyRicontattiState({
this.status = DashboardDailyRicontattiStatus.initial,
this.summaries = const [],
this.totalRicontattiToday = 0,
this.totalRicontattiMonth = 0,
required this.date,
this.errorMessage,
});
/// Numero di addetti che hanno raggiunto l'obiettivo (>= 2)
int get staffWithGoal => summaries.where((s) => s.hasReachedGoal).length;
/// Numero di addetti che hanno registrato almeno 1 ricontatto (= 1)
int get staffWithOne => summaries.where((s) => s.hasStarted).length;
/// Numero di addetti a 0
int get staffAtZero => summaries.where((s) => s.isZero).length;
/// Totale addetti monitorati
int get activeStaffCount => summaries.length;
DashboardDailyRicontattiState copyWith({
DashboardDailyRicontattiStatus? status,
List<StaffDailyRicontattiSummary>? summaries,
int? totalRicontattiToday,
int? totalRicontattiMonth,
DateTime? date,
String? errorMessage,
}) {
return DashboardDailyRicontattiState(
status: status ?? this.status,
summaries: summaries ?? this.summaries,
totalRicontattiToday:
totalRicontattiToday ?? this.totalRicontattiToday,
totalRicontattiMonth:
totalRicontattiMonth ?? this.totalRicontattiMonth,
date: date ?? this.date,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [
status,
summaries,
totalRicontattiToday,
totalRicontattiMonth,
date,
errorMessage,
];
}
@@ -0,0 +1,73 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
/// Modello di riepilogo giornaliero dei ricontatti per singolo addetto.
class StaffDailyRicontattiSummary extends Equatable {
final String staffId;
final String staffName;
final String? jobTitle;
final SystemRole systemRole;
final int count;
final int monthCount;
final List<OperationModel> operations;
const StaffDailyRicontattiSummary({
required this.staffId,
required this.staffName,
this.jobTitle,
this.systemRole = SystemRole.user,
required this.count,
this.monthCount = 0,
this.operations = const [],
});
/// Ha raggiunto l'obiettivo consigliato (almeno 2 ricontatti al giorno)
bool get hasReachedGoal => count >= 2;
/// Ha iniziato la raccolta (1 ricontatto preso)
bool get hasStarted => count == 1;
/// Non ha ancora registrato alcun ricontatto oggi
bool get isZero => count == 0;
StaffDailyRicontattiSummary copyWith({
String? staffId,
String? staffName,
String? jobTitle,
SystemRole? systemRole,
int? count,
int? monthCount,
List<OperationModel>? operations,
}) {
return StaffDailyRicontattiSummary(
staffId: staffId ?? this.staffId,
staffName: staffName ?? this.staffName,
jobTitle: jobTitle ?? this.jobTitle,
systemRole: systemRole ?? this.systemRole,
count: count ?? this.count,
monthCount: monthCount ?? this.monthCount,
operations: operations ?? this.operations,
);
}
factory StaffDailyRicontattiSummary.empty() {
return const StaffDailyRicontattiSummary(
staffId: '',
staffName: '',
count: 0,
monthCount: 0,
);
}
@override
List<Object?> get props => [
staffId,
staffName,
jobTitle,
systemRole,
count,
monthCount,
operations,
];
}
@@ -0,0 +1,979 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
class DashboardDailyRicontattiCard extends StatelessWidget {
const DashboardDailyRicontattiCard({super.key});
@override
Widget build(BuildContext context) {
// Visibile a chi ha qualifica Manager o Titolare (o Admin di sistema)
final staff = context.watch<SessionCubit>().state.currentStaffMember;
final canView = staff?.canViewRicontattiFocus ?? false;
if (!canView) {
return const SizedBox.shrink();
}
return BlocBuilder<DashboardDailyRicontattiCubit,
DashboardDailyRicontattiState>(
builder: (context, state) {
final theme = Theme.of(context);
return LayoutBuilder(
builder: (context, outerConstraints) {
final isMobile = outerConstraints.maxWidth < 600;
final hPad = isMobile ? 16.0 : 24.0;
final vGap = isMobile ? 16.0 : 24.0;
return Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.35),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: Colors.amber.shade700.withValues(alpha: 0.06),
blurRadius: 18,
offset: const Offset(0, 6),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(context, theme, state, isCompact: isMobile),
Divider(
height: 1,
color: theme.dividerColor.withValues(alpha: 0.15),
),
if (state.status == DashboardDailyRicontattiStatus.loading &&
state.summaries.isEmpty)
_buildLoading(theme)
else if (state.status ==
DashboardDailyRicontattiStatus.failure)
_buildError(context, theme, state)
else if (state.summaries.isEmpty)
_buildEmpty(theme)
else ...[
_buildOverviewStats(
context,
theme,
state,
isCompact: isMobile,
),
Padding(
padding: EdgeInsets.fromLTRB(
isMobile ? 14 : 18,
0,
isMobile ? 14 : 18,
isMobile ? 14 : 18,
),
child: _buildStaffGrid(context, theme, state.summaries),
),
],
],
),
),
);
},
);
},
);
}
Widget _buildTotalPillBadge(DashboardDailyRicontattiState state) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: Colors.amber.shade500.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.amber.shade600.withValues(alpha: 0.4),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${state.totalRicontattiToday}',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Colors.amber.shade900,
),
),
const SizedBox(width: 5),
Text(
'oggi',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.amber.shade800,
),
),
const SizedBox(width: 6),
Text(
'(mese: ${state.totalRicontattiMonth})',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900.withValues(alpha: 0.85),
),
),
],
),
);
}
Widget _buildHeader(
BuildContext context,
ThemeData theme,
DashboardDailyRicontattiState state, {
bool isCompact = false,
}) {
if (isCompact) {
return Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(9),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.amber.shade600,
Colors.orange.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.event_repeat_rounded,
color: Colors.white,
size: 20,
),
),
const SizedBox(width: 10),
Expanded(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 6,
runSpacing: 4,
children: [
Text(
'FOCUS RICONTATTI DI OGGI',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: 0.3,
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
),
child: Text(
'MANAGER',
style: TextStyle(
fontSize: 9.5,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900,
letterSpacing: 0.4,
),
),
),
],
),
),
IconButton(
tooltip: 'Aggiorna ora',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh_rounded, size: 20),
onPressed: () =>
context.read<DashboardDailyRicontattiCubit>().refresh(),
),
],
),
const SizedBox(height: 6),
Text(
'Raccolta situazioni da ricontattare & bollette',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
_buildTotalPillBadge(state),
],
),
);
}
return Padding(
padding: const EdgeInsets.all(18.0),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.amber.shade600,
Colors.orange.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(14),
boxShadow: [
BoxShadow(
color: Colors.amber.shade700.withValues(alpha: 0.3),
blurRadius: 8,
offset: const Offset(0, 3),
),
],
),
child: const Icon(
Icons.event_repeat_rounded,
color: Colors.white,
size: 24,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Flexible(
child: Text(
'FOCUS RICONTATTI DI OGGI',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: 0.5,
),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
),
child: Text(
'MANAGER',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w800,
color: Colors.amber.shade900,
letterSpacing: 0.4,
),
),
),
],
),
const SizedBox(height: 3),
Text(
'Raccolta situazioni da ricontattare & bollette (chi sta facendo e chi no)',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
],
),
),
const SizedBox(width: 12),
_buildTotalPillBadge(state),
const SizedBox(width: 6),
IconButton(
tooltip: 'Aggiorna ora',
icon: const Icon(Icons.refresh_rounded, size: 20),
onPressed: () =>
context.read<DashboardDailyRicontattiCubit>().refresh(),
),
],
),
);
}
Widget _buildOverviewStats(
BuildContext context,
ThemeData theme,
DashboardDailyRicontattiState state, {
bool isCompact = false,
}) {
final hasZeros = state.staffAtZero > 0;
final pad = isCompact ? 14.0 : 18.0;
return Padding(
padding: EdgeInsets.fromLTRB(pad, 12, pad, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: isCompact ? 8 : 12,
runSpacing: 8,
children: [
_buildStatChip(
icon: Icons.check_circle_rounded,
color: Colors.green.shade600,
bgColor: Colors.green.shade50,
label: '>= 2 Ricontatti',
count: state.staffWithGoal,
),
_buildStatChip(
icon: Icons.hourglass_top_rounded,
color: Colors.blue.shade600,
bgColor: Colors.blue.shade50,
label: '1 Ricontatto',
count: state.staffWithOne,
),
_buildStatChip(
icon: Icons.warning_amber_rounded,
color: Colors.deepOrange.shade600,
bgColor: Colors.deepOrange.shade50,
label: '0 Ricontatti',
count: state.staffAtZero,
),
],
),
if (hasZeros) ...[
const SizedBox(height: 10),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.deepOrange.shade50.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Colors.deepOrange.shade200,
),
),
child: Row(
children: [
Icon(
Icons.info_outline_rounded,
size: 16,
color: Colors.deepOrange.shade800,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'${state.staffAtZero} ${state.staffAtZero == 1 ? "addetto non ha" : "addetti non hanno"} ancora raccolto alcun ricontatto oggi.',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Colors.deepOrange.shade900,
),
),
),
],
),
),
],
],
),
);
}
Widget _buildStatChip({
required IconData icon,
required Color color,
required Color bgColor,
required String label,
required int count,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: color.withValues(alpha: 0.3)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 6),
Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),
),
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$count',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w800,
color: Colors.white,
),
),
),
],
),
);
}
Widget _buildStaffGrid(
BuildContext context,
ThemeData theme,
List<StaffDailyRicontattiSummary> summaries,
) {
return LayoutBuilder(
builder: (context, constraints) {
// Calcola quante colonne in base alla larghezza disponibile
final double width = constraints.maxWidth;
final int crossAxisCount = width > 1100
? 4
: width > 750
? 3
: width > 480
? 2
: 1;
return GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: summaries.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
mainAxisExtent: crossAxisCount == 1 ? 86 : 104,
),
itemBuilder: (context, index) {
final summary = summaries[index];
return _StaffItemCard(summary: summary);
},
);
},
);
}
Widget _buildLoading(ThemeData theme) {
return const Padding(
padding: EdgeInsets.all(32.0),
child: Center(
child: SizedBox(
width: 28,
height: 28,
child: CircularProgressIndicator(strokeWidth: 2.5),
),
),
);
}
Widget _buildError(
BuildContext context,
ThemeData theme,
DashboardDailyRicontattiState state,
) {
return Padding(
padding: const EdgeInsets.all(24.0),
child: Center(
child: Column(
children: [
Icon(Icons.error_outline, color: theme.colorScheme.error, size: 32),
const SizedBox(height: 8),
Text(
'Impossibile caricare i dati dei ricontatti',
style: TextStyle(color: theme.colorScheme.error),
),
const SizedBox(height: 8),
TextButton.icon(
onPressed: () =>
context.read<DashboardDailyRicontattiCubit>().refresh(),
icon: const Icon(Icons.refresh),
label: const Text('Riprova'),
),
],
),
),
);
}
Widget _buildEmpty(ThemeData theme) {
return const Padding(
padding: EdgeInsets.all(24.0),
child: Center(
child: Text(
'Nessun addetto attivo registrato per questo negozio.',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
);
}
}
class _StaffItemCard extends StatelessWidget {
final StaffDailyRicontattiSummary summary;
const _StaffItemCard({required this.summary});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
// Stile in base al conteggio
final bool hasGoal = summary.hasReachedGoal;
final bool hasOne = summary.hasStarted;
final bool isZero = summary.isZero;
final Color primaryColor = hasGoal
? Colors.green.shade600
: hasOne
? Colors.blue.shade600
: Colors.grey.shade500;
final Color cardBg = hasGoal
? Colors.green.shade50.withValues(alpha: 0.3)
: hasOne
? Colors.blue.shade50.withValues(alpha: 0.3)
: theme.colorScheme.surface;
final Color borderColor = hasGoal
? Colors.green.shade400
: hasOne
? Colors.blue.shade300
: theme.dividerColor.withValues(alpha: 0.25);
final String initials = _getInitials(summary.staffName);
return InkWell(
onTap: () => _handleTap(context),
borderRadius: BorderRadius.circular(14),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: cardBg,
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: borderColor,
width: isZero ? 1.0 : 1.5,
),
),
child: Row(
children: [
// Avatar con iniziali
CircleAvatar(
radius: 20,
backgroundColor: primaryColor.withValues(alpha: 0.15),
child: Text(
initials,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w800,
color: primaryColor,
),
),
),
const SizedBox(width: 10),
// Nome e stato
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
summary.staffName,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: isZero
? context.primaryText.withValues(alpha: 0.75)
: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 3),
_buildStatusChip(hasGoal, hasOne, isZero),
],
),
),
const SizedBox(width: 8),
// Grande numero conteggio e riepilogo mese tra parentesi
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'${summary.count}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w900,
height: 1.0,
color: hasGoal
? Colors.green.shade700
: hasOne
? Colors.blue.shade700
: Colors.grey.shade400,
),
),
const SizedBox(width: 4),
Text(
'oggi',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: hasGoal
? Colors.green.shade700
: hasOne
? Colors.blue.shade700
: Colors.grey.shade500,
),
),
],
),
const SizedBox(height: 3),
Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular(6),
),
child: Text(
'(mese: ${summary.monthCount})',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.85),
),
),
),
],
),
],
),
),
);
}
Widget _buildStatusChip(bool hasGoal, bool hasOne, bool isZero) {
if (hasGoal) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star_rounded, size: 13, color: Colors.green.shade700),
const SizedBox(width: 3),
Text(
'Obiettivo preso',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: Colors.green.shade700,
),
),
],
);
}
if (hasOne) {
return Text(
'1 raccolto',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Colors.blue.shade700,
),
);
}
return Text(
'0 ricontatti',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Colors.deepOrange.shade600,
),
);
}
String _getInitials(String name) {
final parts = name.trim().split(RegExp(r'\s+'));
if (parts.isEmpty || parts[0].isEmpty) return '?';
if (parts.length == 1) return parts[0][0].toUpperCase();
return '${parts[0][0]}${parts[1][0]}'.toUpperCase();
}
void _handleTap(BuildContext context) {
if (summary.operations.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${summary.staffName} non ha ancora registrato ricontatti oggi (${summary.monthCount} nel mese).',
),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
),
);
return;
}
// Mostra bottom sheet di dettaglio con le operazioni prese oggi dall'addetto
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (sheetContext) => _StaffOperationsSheet(summary: summary),
);
}
}
class _StaffOperationsSheet extends StatelessWidget {
final StaffDailyRicontattiSummary summary;
const _StaffOperationsSheet({required this.summary});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final timeFormat = DateFormat('HH:mm');
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
),
padding: EdgeInsets.only(
top: 16,
left: 20,
right: 20,
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
),
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.75,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: 40,
height: 4,
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: theme.dividerColor.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(2),
),
),
),
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.person_rounded,
color: Colors.amber.shade900,
size: 22,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
summary.staffName,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'${summary.count} ${summary.count == 1 ? "ricontatto oggi" : "ricontatti oggi"} • (${summary.monthCount} nel mese)',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close),
),
],
),
const SizedBox(height: 16),
Divider(height: 1, color: theme.dividerColor.withValues(alpha: 0.2)),
const SizedBox(height: 12),
Flexible(
child: ListView.separated(
shrinkWrap: true,
itemCount: summary.operations.length,
separatorBuilder: (context, _) => Divider(
height: 16,
color: theme.dividerColor.withValues(alpha: 0.1),
),
itemBuilder: (context, index) {
final op = summary.operations[index];
final ricontattoDetails = op.details
.where((d) => d.type == OperationType.ricontatto)
.toList();
final timeStr = op.createdAt != null
? timeFormat.format(op.createdAt!)
: '--:--';
return InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () {
Navigator.of(context).pop();
context.pushNamed(
Routes.operationForm,
extra: (createdBy: null, operation: op),
pathParameters: {'id': op.id!},
);
},
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 4.0,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Text(
timeStr,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
op.customer?.name ?? 'Cliente non specificato',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
const SizedBox(height: 4),
Wrap(
spacing: 6,
runSpacing: 4,
children: ricontattoDetails.map((detail) {
final label = detail.subType != null &&
detail.subType!.isNotEmpty
? detail.subType!
: 'Ricontatto';
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(6),
),
child: Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Colors.amber.shade900,
),
),
);
}).toList(),
),
if (op.note.trim().isNotEmpty) ...[
const SizedBox(height: 4),
Text(
op.note,
style: TextStyle(
fontSize: 12,
fontStyle: FontStyle.italic,
color: theme.colorScheme.onSurfaceVariant,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
const SizedBox(width: 8),
const Icon(
Icons.chevron_right_rounded,
size: 20,
color: Colors.grey,
),
],
),
),
);
},
),
),
],
),
);
}
}
@@ -0,0 +1,80 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_state.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:get_it/get_it.dart';
class DashboardExpiringContractsCubit
extends Cubit<DashboardExpiringContractsState> {
final OperationsRepository _repository =
GetIt.I.get<OperationsRepository>();
final String? companyId;
final String? storeId;
StreamSubscription<void>? _operationsSubscription;
Timer? _pollingTimer;
DashboardExpiringContractsCubit({
required this.companyId,
required this.storeId,
}) : super(const DashboardExpiringContractsState());
void startListening() {
emit(state.copyWith(status: DashboardExpiringContractsStatus.loading));
stopListening();
_loadExpiringSilently();
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
_loadExpiringSilently();
});
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
_loadExpiringSilently();
});
}
void stopListening() {
_operationsSubscription?.cancel();
_operationsSubscription = null;
_pollingTimer?.cancel();
_pollingTimer = null;
}
void refresh() {
_loadExpiringSilently();
}
void _loadExpiringSilently() async {
try {
if (companyId == null || companyId!.isEmpty) return;
final expiringOps = await _repository.fetchExpiringOperations(
companyId: companyId!,
storeId: storeId,
limit: 20,
);
if (isClosed) return;
emit(
state.copyWith(
status: DashboardExpiringContractsStatus.success,
operations: expiringOps,
error: null,
),
);
} catch (e) {
if (isClosed) return;
emit(
state.copyWith(
status: DashboardExpiringContractsStatus.failure,
error: e.toString(),
),
);
}
}
@override
Future<void> close() {
stopListening();
return super.close();
}
}
@@ -0,0 +1,31 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/operations/models/operation_model.dart';
enum DashboardExpiringContractsStatus { initial, loading, success, failure }
class DashboardExpiringContractsState extends Equatable {
final DashboardExpiringContractsStatus status;
final List<OperationModel> operations;
final String? error;
const DashboardExpiringContractsState({
this.status = DashboardExpiringContractsStatus.initial,
this.operations = const [],
this.error,
});
DashboardExpiringContractsState copyWith({
DashboardExpiringContractsStatus? status,
List<OperationModel>? operations,
String? error,
}) {
return DashboardExpiringContractsState(
status: status ?? this.status,
operations: operations ?? this.operations,
error: error,
);
}
@override
List<Object?> get props => [status, operations, error];
}
@@ -0,0 +1,289 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_state.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:go_router/go_router.dart';
class DashboardExpiringContractsCard extends StatelessWidget {
const DashboardExpiringContractsCard({super.key});
@override
Widget build(BuildContext context) {
return _ExpiringContractsCardContent();
}
}
class _ExpiringContractsCardContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
const color = Colors.orange;
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.3)),
),
child: InkWell(
onTap: () => context.pushNamed(Routes.operations),
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// --- HEADER DELLA CARD ---
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.event_repeat_outlined,
color: color,
size: 20,
),
),
const SizedBox(width: 12),
Expanded(
child: Text(
context.l10n.homeExpiringContracts,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 12),
// --- LISTA OPERAZIONI IN SCADENZA ---
Expanded(
child: BlocBuilder<DashboardExpiringContractsCubit,
DashboardExpiringContractsState>(
builder: (context, state) {
if (state.status ==
DashboardExpiringContractsStatus.loading ||
state.status ==
DashboardExpiringContractsStatus.initial) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (state.status ==
DashboardExpiringContractsStatus.failure) {
return Center(
child: Text(
"Errore di caricamento",
style: TextStyle(color: theme.colorScheme.error),
),
);
}
if (state.operations.isEmpty) {
return Center(
child: Text(
"Nessun contratto in scadenza.",
style: TextStyle(
color: context.secondaryText,
fontStyle: FontStyle.italic,
),
),
);
}
return ListView.separated(
itemCount: state.operations.length,
separatorBuilder: (context, index) => Divider(
height: 1,
color: theme.dividerColor.withValues(alpha: 0.3),
),
itemBuilder: (context, index) {
final operation = state.operations[index];
final earliestExp =
OperationsRepository.getEarliestExpiration(operation);
final phone = operation.customer?.phoneNumber;
return InkWell(
onTap: () => context.pushNamed(
Routes.operationForm,
extra: (createdBy: null, operation: operation),
pathParameters: {'id': operation.id!},
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
child: Row(
children: [
Flexible(
child: Text(
operation.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (operation
.attachments
.isNotEmpty) ...[
const SizedBox(width: 4),
Icon(
Icons.attach_file,
size: 14,
color: context.secondaryText,
),
],
],
),
),
const SizedBox(width: 8),
_buildExpiryBadge(context, earliestExp),
],
),
const SizedBox(height: 4),
Row(
children: [
if (phone != null && phone.isNotEmpty) ...[
Text(
phone,
style: TextStyle(
color: context.secondaryText,
fontSize: 11,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(width: 8),
],
Expanded(child: _buildBadges(operation)),
],
),
],
),
),
);
},
);
},
),
),
],
),
),
),
);
}
Widget _buildBadges(OperationModel op) {
final labels = op.details
.map((d) {
final tLabel = d.type?.shortLabel ?? d.type?.value ?? '';
final sub = d.subType?.trim() ?? '';
final base = sub.isNotEmpty ? '$tLabel: $sub' : tLabel;
if (base.isEmpty) return '';
return d.quantity > 1 ? '$base ×${d.quantity}' : base;
})
.where((l) => l.isNotEmpty)
.toList();
if (labels.isEmpty) {
return const SizedBox.shrink();
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: labels
.map(
(label) => Container(
margin: const EdgeInsets.only(right: 4),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.amber.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: Colors.amber.withValues(alpha: 0.3),
width: 1,
),
),
child: Text(
label,
style: TextStyle(
color: Colors.amber.shade800,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
)
.toList(),
),
);
}
Widget _buildExpiryBadge(BuildContext context, DateTime? expiry) {
if (expiry == null) return const SizedBox.shrink();
final now = DateTime.now();
final differenceDays = expiry.difference(now).inDays;
final isExpired = expiry.isBefore(now);
Color badgeColor = Colors.orange;
String text = "${expiry.day}/${expiry.month}/${expiry.year}";
if (isExpired) {
badgeColor = Colors.red;
text = "Scaduto ($text)";
} else if (differenceDays <= 30) {
badgeColor = Colors.redAccent;
text = "Tra $differenceDays gg";
} else if (differenceDays <= 60) {
badgeColor = Colors.orange;
text = "Tra ~${(differenceDays / 30).round()} mesi";
} else {
badgeColor = Colors.blue;
text = "${expiry.day}/${expiry.month}/${expiry.year}";
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: badgeColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: badgeColor.withValues(alpha: 0.4)),
),
child: Text(
text,
style: TextStyle(
color: badgeColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
);
}
}
@@ -35,10 +35,15 @@ class DashboardNoteListCubit extends Cubit<DashboardNoteListState> {
try {
_subscription = _repository
.notesStream(companyId: companyId!, currentStaffId: staffId!)
.listen((_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadNotesSilently();
});
.listen(
(_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadNotesSilently();
},
onError: (error, stackTrace) {
debugPrint('Dashboard notes stream error: $error');
},
);
} on Exception catch (e) {
debugPrint(e.toString());
}
@@ -1,14 +1,36 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
import 'package:flux/features/notes/data/notes_repository.dart';
import 'package:flux/features/notes/models/note_model.dart';
import 'package:go_router/go_router.dart'; // Supponendo tu usi GoRouter per la navigazione
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
class DashboardNoteListCard extends StatelessWidget {
const DashboardNoteListCard({super.key});
Future<void> _createNewNote(BuildContext context) async {
final sessionState = context.read<SessionCubit>().state;
final companyId = sessionState.company?.id;
final currentStaffId = sessionState.currentStaffMember?.id;
if (companyId == null || currentStaffId == null) return;
final emptyNote = NoteModel.empty(
createdBy: currentStaffId,
companyId: companyId,
);
final noteId = await GetIt.I.get<NotesRepository>().saveNote(emptyNote);
if (!context.mounted) return;
context.pushNamed(
Routes.noteForm,
pathParameters: {'id': noteId},
extra: emptyNote.copyWith(id: noteId),
);
}
@override
Widget build(BuildContext context) {
return Card(
@@ -44,55 +66,59 @@ class DashboardNoteListCard extends StatelessWidget {
),
),
const SizedBox(width: 12),
Text(
'Le mie Note',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
Expanded(
child: Text(
'Le mie Note',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
const SizedBox(height: 12),
// Il corpo del widget collegato al Bloc
BlocBuilder<DashboardNoteListCubit, DashboardNoteListState>(
builder: (context, state) {
if (state.status == DashboardNoteListStatus.loading &&
state.notes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
Expanded(
child: BlocBuilder<
DashboardNoteListCubit,
DashboardNoteListState
>(
builder: (context, state) {
if (state.status == DashboardNoteListStatus.loading &&
state.notes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == DashboardNoteListStatus.failure) {
return const Center(
child: Text(
'Errore nel caricamento delle note.',
style: TextStyle(color: Colors.red),
),
);
}
if (state.status == DashboardNoteListStatus.failure) {
return const Center(
child: Text(
'Errore nel caricamento delle note.',
style: TextStyle(color: Colors.red),
),
);
}
if (state.notes.isEmpty) {
return _buildEmptyState(context);
}
if (state.notes.isEmpty) {
return _buildEmptyState(context);
}
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
final displayNotes = state.notes.take(4).toList();
// Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard
final displayNotes = state.notes.take(4).toList();
return SizedBox(
height: 140, // Altezza fissa per lo scroll orizzontale
child: ListView.builder(
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: displayNotes.length,
itemBuilder: (context, index) {
return _buildMiniPostIt(context, displayNotes[index]);
},
),
);
},
);
},
),
),
],
),
@@ -168,7 +194,7 @@ class DashboardNoteListCard extends StatelessWidget {
Widget _buildEmptyState(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.grey.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
@@ -178,16 +204,18 @@ class DashboardNoteListCard extends StatelessWidget {
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.sticky_note_2_outlined,
size: 32,
size: 28,
color: Colors.grey,
),
const SizedBox(height: 8),
const SizedBox(height: 6),
const Text('Nessuna nota presente.'),
TextButton(
onPressed: () => context.push('/notes/create'),
style: TextButton.styleFrom(visualDensity: VisualDensity.compact),
onPressed: () => _createNewNote(context),
child: const Text('Creane una ora'),
),
],
@@ -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,31 +32,37 @@ 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 {
if (companyId == null || storeId == null) return;
final paginatedData = await _repository.fetchPaginatedOperations(
companyId: companyId!,
storeId: storeId!,
page: 1,
itemsPerPage: 20,
onlyShowInDashboard: true,
);
if (isClosed) return;
emit(
@@ -113,6 +113,17 @@ class _LatestOperationsCardContent extends StatelessWidget {
),
itemBuilder: (context, index) {
final operation = state.operations[index];
final types = operation.details
.map(
(d) =>
d.type?.shortLabel ?? d.type?.value ?? '',
)
.where((t) => t.trim().isNotEmpty)
.toList();
final dateStr = operation.createdAt != null
? "${operation.createdAt!.day.toString().padLeft(2, '0')}/${operation.createdAt!.month.toString().padLeft(2, '0')}"
: '';
return InkWell(
onTap: () => context.pushNamed(
Routes.operationForm,
@@ -123,45 +134,40 @@ class _LatestOperationsCardContent extends StatelessWidget {
padding: const EdgeInsets.symmetric(
vertical: 8.0,
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
flex: 5,
child: Text(
operation.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
Row(
children: [
Expanded(
child: Text(
operation.customer?.name ??
(operation.reference
.trim()
.isNotEmpty
? operation.reference
: 'Cliente sconosciuto'),
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
Expanded(
flex: 5,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
const SizedBox(width: 8),
Text(
dateStr,
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
),
),
child: _buildBadgeList(
operation.details
.map((d) => d.type)
.whereType<String>()
.where(
(t) => t.trim().isNotEmpty,
)
.toList(),
),
),
),
Text(
"${operation.createdAt?.day}/${operation.createdAt?.month}",
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
),
],
),
const SizedBox(height: 4),
_buildBadgeList(types),
],
),
),
@@ -14,7 +14,9 @@ class DashboardStoreTicketListCubit
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
final String? companyId;
final String? storeId;
StreamSubscription<void>? _subscription;
StreamSubscription<void>? _realtimeSubscription;
StreamSubscription<void>? _localSubscription;
Timer? _pollingTimer;
DashboardStoreTicketListCubit({
required this.companyId,
@@ -26,8 +28,16 @@ class DashboardStoreTicketListCubit
);
void stopListening() {
_subscription?.cancel();
_subscription = null;
_realtimeSubscription?.cancel();
_realtimeSubscription = null;
_localSubscription?.cancel();
_localSubscription = null;
_pollingTimer?.cancel();
_pollingTimer = null;
}
void refresh() {
_loadTicketsSilently();
}
void startListening() {
@@ -38,21 +48,49 @@ class DashboardStoreTicketListCubit
// Primo caricamento
_loadTicketsSilently();
// Inizio ascolto campanello
// 1. Ascolto notifiche locali di mutazione in memoria (reattività istantanea)
_localSubscription = _repository.onTicketsChanged.listen((_) {
_loadTicketsSilently();
});
// 2. Ascolto campanello Supabase Realtime (se attivo in DB)
try {
_subscription = _repository
.getLatestStoreTicketsStream(storeId: storeId!, limit: 10)
.listen((_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadTicketsSilently();
});
if (storeId != null && storeId!.isNotEmpty) {
_realtimeSubscription = _repository
.getLatestStoreTicketsStream(storeId: storeId!, limit: 10)
.listen(
(_) {
_loadTicketsSilently();
},
onError: (error, stackTrace) {
debugPrint('Realtime store tickets stream error: $error');
},
);
}
} on Exception catch (e) {
debugPrint(e.toString());
}
// 3. Polling di sicurezza ogni 30 secondi
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
_loadTicketsSilently();
});
}
Future<void> _loadTicketsSilently() async {
try {
if (companyId == null || companyId!.isEmpty) {
if (!isClosed) {
emit(
state.copyWith(
status: DashboardStoreTicketListStatus.initial,
tickets: [],
errorMessage: null,
),
);
}
return;
}
final tickets = await _repository.fetchTickets(
companyId: companyId!,
storeId: storeId,
@@ -114,6 +114,10 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget {
itemBuilder: (context, index) {
final ticket = state.tickets[index];
final statusColor = ticket.ticketStatus.color;
final dateStr = ticket.createdAt != null
? "${ticket.createdAt!.day.toString().padLeft(2, '0')}/${ticket.createdAt!.month.toString().padLeft(2, '0')}"
: '';
return InkWell(
onTap: () => context.pushNamed(
Routes.ticketForm,
@@ -125,47 +129,50 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget {
vertical: 8.0,
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
width: 8,
height:
30, // Un'altezza fissa per farlo comparire!
width: 6,
height: 34,
decoration: BoxDecoration(
color: statusColor,
borderRadius: BorderRadius.circular(
4,
), // Angoli smussati per stile
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(width: 4),
const SizedBox(width: 10),
Expanded(
flex: 5,
child: Text(
ticket.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
),
),
Expanded(
flex: 5,
child: Text(
ticket.targetModelName ??
'Modello sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w600,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
ticket.customer?.name ??
'Cliente sconosciuto',
style: TextStyle(
fontWeight: FontWeight.w700,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 2),
Text(
ticket.targetModelName ??
'Modello sconosciuto',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: context.secondaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
const SizedBox(width: 8),
Text(
"${ticket.createdAt?.day}/${ticket.createdAt?.month}",
dateStr,
style: TextStyle(
color: context.secondaryText,
fontSize: 12,
@@ -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,
];
}
File diff suppressed because it is too large. Load diff
@@ -29,12 +29,15 @@ class DashboardTaskListCubit extends Cubit<DashboardTaskListState> {
// Inizio ascolto campanello
try {
_tasksSubscription = _repository.watchCompanyTasks(companyId!).listen((
_,
) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadTasksSilently();
});
_tasksSubscription = _repository.watchCompanyTasks(companyId!).listen(
(_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadTasksSilently();
},
onError: (error, stackTrace) {
debugPrint('Dashboard tasks stream error: $error');
},
);
} on Exception catch (e) {
debugPrint(e.toString());
}
+207 -157
View File
@@ -6,6 +6,10 @@ import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
import 'package:flux/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
import 'package:flux/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.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';
@@ -19,6 +23,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 +79,29 @@ class _HomeScreenState extends State<HomeScreen> {
context.read<DashboardTaskListCubit>().stopListening();
context.read<DashboardStoreTicketListCubit>().stopListening();
context.read<DashboardNoteListCubit>().stopListening();
context.read<DashboardTargetProgressCubit>().stopListening();
context.read<DashboardExpiringContractsCubit>().stopListening();
context.read<DashboardDailyRicontattiCubit>().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<DashboardDailyRicontattiCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
);
context.read<DashboardStoreOperationListCubit>().startListening();
context.read<DashboardTaskListCubit>().startListening();
context.read<DashboardStoreTicketListCubit>().startListening();
context.read<DashboardNoteListCubit>().startListening();
context.read<DashboardTargetProgressCubit>().startListening();
context.read<DashboardExpiringContractsCubit>().startListening();
context.read<DashboardDailyRicontattiCubit>().startListening();
}
@override
@@ -96,78 +118,145 @@ class _HomeScreenState extends State<HomeScreen> {
return Scaffold(
backgroundColor: theme.colorScheme.surface,
body: SafeArea(
child: Column(
children: [
// ==========================================
// 1. HEADER FISSO (Non scrolla mai)
// ==========================================
Container(
padding: const EdgeInsets.all(24.0),
// Un leggero colore di sfondo aiuta a staccare l'header quando il contenuto ci passa sotto
color: theme.colorScheme.surface,
child: _buildHeader(context, theme),
),
child: LayoutBuilder(
builder: (context, constraints) {
final isMobile = constraints.maxWidth < 600;
final isSingleColGrid = constraints.maxWidth < 650;
final hPad = isMobile ? 16.0 : 24.0;
final vGap = isMobile ? 16.0 : 24.0;
// ==========================================
// 2. CORPO DELLA DASHBOARD (Scrollabile)
// ==========================================
Expanded(
child: CustomScrollView(
slivers: [
// --- QUICK ACTIONS: AZIONI RAPIDE ---
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: _buildQuickActions(context),
),
return Column(
children: [
// ==========================================
// 1. HEADER FISSO SU DESKTOP / TABLET LARGO
// ==========================================
if (!isMobile)
Container(
padding: const EdgeInsets.all(24.0),
color: theme.colorScheme.surface,
child: _buildHeader(context, theme, isMobile: false),
),
const SliverToBoxAdapter(child: SizedBox(height: 32)),
// ==========================================
// 2. CORPO DELLA DASHBOARD (Scrollabile)
// ==========================================
Expanded(
child: BlocListener<SessionCubit, SessionState>(
listenWhen: (prev, curr) =>
prev.currentStore?.id != curr.currentStore?.id ||
prev.currentStaffMember?.id !=
curr.currentStaffMember?.id ||
prev.company?.id != curr.company?.id,
listener: (context, sessionState) {
context.read<DashboardTargetProgressCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
newStaffId: sessionState.currentStaffMember?.id,
);
context.read<DashboardDailyRicontattiCubit>().updateContext(
newCompanyId: sessionState.company?.id,
newStoreId: sessionState.currentStore?.id,
);
},
child: CustomScrollView(
slivers: [
// Su mobile l'header scrolla col contenuto così non ruba mezzo schermo
if (isMobile)
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(
hPad,
8.0,
hPad,
14.0,
),
child: _buildHeader(
context,
theme,
isMobile: true,
),
),
),
// --- 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,
// --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) ---
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: _buildQuickActions(
context,
isMobile: isMobile,
),
),
delegate: SliverChildListDelegate([
DashboardStoreOperationListCard(),
DashboardStoreTicketListCard(),
_buildDashboardWidget(
title: context.l10n.homeExpiringContracts,
icon: Icons.assignment_late_outlined,
color: Colors.orange,
context: context,
),
DashboardNoteListCard(),
DashboardTaskListCard(),
]),
// --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) ---
const SliverToBoxAdapter(
child: DashboardDailyRicontattiCard(),
),
// --- 3. HERO TARGET DEL GIORNO ---
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap),
child: const DashboardTargetHeroCard(),
),
),
SliverToBoxAdapter(
child: SizedBox(height: isMobile ? 4 : 8),
),
// --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) ---
SliverPadding(
padding: EdgeInsets.symmetric(horizontal: hPad),
sliver: SliverGrid(
gridDelegate: isSingleColGrid
? const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
mainAxisSpacing: 14,
mainAxisExtent: 268,
)
: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 500,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
mainAxisExtent: 290,
),
delegate: SliverChildListDelegate([
const DashboardStoreOperationListCard(),
const DashboardStoreTicketListCard(),
const DashboardExpiringContractsCard(),
const DashboardNoteListCard(),
const DashboardTaskListCard(),
]),
),
),
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
),
),
// Spazio finale per non far attaccare l'ultima card al fondo
const SliverToBoxAdapter(child: SizedBox(height: 40)),
],
),
),
],
),
],
);
},
),
),
);
}
// ==========================================
Widget _buildHeader(BuildContext context, ThemeData theme) {
Widget _buildHeader(
BuildContext context,
ThemeData theme, {
required bool isMobile,
}) {
final user = context.watch<SessionCubit>().state.currentStaffMember;
final currentStore = context.watch<SessionCubit>().state.currentStore;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
@@ -175,31 +264,33 @@ class _HomeScreenState extends State<HomeScreen> {
children: [
Text(
context.l10n.homeWelcomeBack(user?.name ?? "Utente"),
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: -0.5,
color: context.primaryText, // Uso dell'estensione!
),
style:
(isMobile
? theme.textTheme.titleLarge
: theme.textTheme.headlineMedium)
?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: -0.5,
color: context.primaryText,
),
maxLines: isMobile ? 1 : 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
SizedBox(height: isMobile ? 6 : 8),
InkWell(
onTap: () => _showStoreSelector(context, theme),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
padding: EdgeInsets.symmetric(
horizontal: isMobile ? 10 : 12,
vertical: isMobile ? 5 : 6,
),
decoration: BoxDecoration(
color: context.primary.withValues(
alpha: 0.08,
), // Sfondo delicato
color: context.primary.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: context.primary.withValues(
alpha: 0.2,
), // Bordino netto
color: context.primary.withValues(alpha: 0.2),
),
),
child: Row(
@@ -207,15 +298,24 @@ class _HomeScreenState extends State<HomeScreen> {
children: [
Icon(Icons.storefront, size: 16, color: context.primary),
const SizedBox(width: 8),
Text(
currentStore?.name ?? context.l10n.homeNoStoreFound,
style: TextStyle(
fontWeight: FontWeight.w600,
color: context.primary,
Flexible(
child: Text(
currentStore?.name ?? context.l10n.homeNoStoreFound,
style: TextStyle(
fontSize: isMobile ? 13 : 14,
fontWeight: FontWeight.w600,
color: context.primary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
Icon(Icons.arrow_drop_down, color: context.primary),
Icon(
Icons.arrow_drop_down,
size: 20,
color: context.primary,
),
],
),
),
@@ -223,17 +323,22 @@ class _HomeScreenState extends State<HomeScreen> {
],
),
),
const SizedBox(width: 12),
CircleAvatar(
radius: 24,
// Usiamo il Turchese (accent) in trasparenza per l'avatar
radius: isMobile ? 20 : 24,
backgroundColor: context.accent.withValues(alpha: 0.15),
child: Icon(Icons.person, color: context.accent, size: 26),
child: Icon(
Icons.person,
color: context.accent,
size: isMobile ? 22 : 26,
),
),
],
);
}
Widget _buildQuickActions(BuildContext context) {
Widget _buildQuickActions(BuildContext context, {bool isMobile = false}) {
final gap = isMobile ? 8.0 : 12.0;
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
@@ -242,6 +347,7 @@ class _HomeScreenState extends State<HomeScreen> {
icon: Icons.add,
label: context.l10n.commonOperation,
color: Colors.blue,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
@@ -252,11 +358,12 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.handyman,
label: context.l10n.homeNewOperationTicket,
color: Colors.redAccent,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
@@ -267,11 +374,28 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.add_shopping_cart_rounded,
label: 'Ordine Cliente',
color: Colors.teal,
compact: isMobile,
onTap: () async {
StaffMemberModel? createdBy = await getStaffMember(context);
if (createdBy == null || !context.mounted) return;
context.pushNamed(
Routes.customerOrderForm,
pathParameters: {'id': 'new'},
extra: (createdBy: createdBy, order: null),
);
},
),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.note_add,
label: context.l10n.commonNote,
color: Colors.amber,
compact: isMobile,
onTap: () async {
final companyId = context.read<SessionCubit>().state.company!.id!;
final currentStaffId = context
@@ -294,11 +418,12 @@ class _HomeScreenState extends State<HomeScreen> {
);
},
),
const SizedBox(width: 12),
SizedBox(width: gap),
QuickActionButton(
icon: Icons.task_alt,
label: context.l10n.commonTask,
color: Colors.orange,
compact: isMobile,
onTap: () {
context.pushNamed(Routes.taskForm, pathParameters: {'id': 'new'});
},
@@ -308,82 +433,7 @@ class _HomeScreenState extends State<HomeScreen> {
);
}
Widget _buildDashboardWidget({
required BuildContext context,
required String title,
required IconData icon,
required Color color,
VoidCallback? onTap,
}) {
final theme = Theme.of(context);
return Card(
elevation: 0,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
),
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: color, size: 20),
),
const SizedBox(width: 12),
Expanded(
child: Text(
title,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: context.primaryText,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
IconButton(
icon: Icon(
Icons.more_vert,
size: 20,
color: context.secondaryText,
),
onPressed: () {},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
const Spacer(),
Center(
child: Text(
context.l10n.commonComingSoon,
style: TextStyle(
color: context.secondaryText.withValues(alpha: 0.7),
fontStyle: FontStyle.italic,
fontSize: 13,
),
),
),
const Spacer(),
],
),
),
),
);
}
void _showStoreSelector(BuildContext context, ThemeData theme) {
showModalBottomSheet(
+13 -4
View File
@@ -7,6 +7,7 @@ class QuickActionButton extends StatelessWidget {
final String label;
final Color color;
final VoidCallback onTap;
final bool compact;
const QuickActionButton({
super.key,
@@ -14,6 +15,7 @@ class QuickActionButton extends StatelessWidget {
required this.label,
required this.color,
required this.onTap,
this.compact = false,
});
@override
@@ -22,7 +24,10 @@ class QuickActionButton extends StatelessWidget {
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
padding: EdgeInsets.symmetric(
horizontal: compact ? 12 : 16,
vertical: compact ? 10 : 12,
),
decoration: BoxDecoration(
border: Border.all(color: color.withValues(alpha: 0.3)),
color: color.withValues(alpha: 0.05),
@@ -31,11 +36,15 @@ class QuickActionButton extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 20),
const SizedBox(width: 8),
Icon(icon, color: color, size: compact ? 18 : 20),
SizedBox(width: compact ? 6 : 8),
Text(
label,
style: TextStyle(fontWeight: FontWeight.bold, color: color),
style: TextStyle(
fontSize: compact ? 13 : 14,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
@@ -126,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) {
@@ -138,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,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);
}
}
@@ -383,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})',
),
@@ -24,21 +24,23 @@ class StaffRepository {
${Tables.stores}(*)
)
''')
.eq('company_id', companyId);
.eq('company_id', companyId)
.order('name', ascending: true);
if (storeId != null) {
filterBuilder = filterBuilder.or(
'store_id.eq.$storeId,store_id.is.null',
);
}
final response = await filterBuilder;
var transformBuilder = filterBuilder.order('name', ascending: true);
final response = await transformBuilder;
return (response as List)
final list = (response as List)
.map((s) => StaffMemberModel.fromMap(s))
.toList();
if (storeId != null) {
return list
.where((s) =>
s.assignedStoreIds.isEmpty || s.assignedStoreIds.contains(storeId))
.toList();
}
return list;
} on Exception catch (e) {
debugPrint('Errore nel recupero della lista di staff: $e');
throw Exception('Errore nel recupero della lista di staff: $e');
@@ -77,6 +77,35 @@ class StaffMemberModel extends Equatable {
);
}
/// Indica se il collaboratore ha la qualifica di Manager o Titolare (tramite jobTitle)
bool get isManagerOrTitolare {
final title = (jobTitle ?? '').trim().toLowerCase();
return title.contains('manager') || title.contains('titolare');
}
/// Discriminante per vedere o meno il Focus Ricontatti: Manager e Titolare (o Admin di sistema)
bool get canViewRicontattiFocus {
if (isManagerOrTitolare) return true;
if (systemRole == SystemRole.admin) return true;
return false;
}
/// Discriminante per non comparire tra gli utenti "controllati" (addetti):
/// Manager, Titolari, Tester o collaboratori disattivati
bool get isExcludedFromControlledStaff {
if (!isActive) return true;
final title = (jobTitle ?? '').trim().toLowerCase();
if (title.contains('manager') ||
title.contains('titolare') ||
title.contains('tester')) {
return true;
}
return false;
}
/// Alias retrocompatibile
bool get isExcludedFromRicontattiFocus => isExcludedFromControlledStaff;
factory StaffMemberModel.empty() {
return const StaffMemberModel(
companyId: '',
@@ -142,24 +142,64 @@ class _StaffScreenState extends State<StaffScreen> {
myRole == SystemRole.admin || myRole == SystemRole.manager;
final hasEmail = member.email != null && member.email!.trim().isNotEmpty;
final bool isActive = member.isActive;
return Card(
elevation: 0,
color: isActive ? null : context.surface.withValues(alpha: 0.6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: context.accent.withValues(alpha: 0.1)),
side: BorderSide(
color: isActive
? context.accent.withValues(alpha: 0.1)
: Colors.red.withValues(alpha: 0.2),
),
),
child: ListTile(
contentPadding: const EdgeInsets.all(12),
leading: CircleAvatar(
backgroundColor: context.accent.withValues(alpha: 0.1),
backgroundColor: isActive
? context.accent.withValues(alpha: 0.1)
: Colors.grey.withValues(alpha: 0.2),
child: Text(
member.name[0].toUpperCase(),
style: TextStyle(color: context.accent),
style: TextStyle(
color: isActive ? context.accent : Colors.grey,
),
),
),
title: Text(
member.name,
style: const TextStyle(fontWeight: FontWeight.bold),
title: Row(
children: [
Flexible(
child: Text(
member.name,
style: TextStyle(
fontWeight: FontWeight.bold,
color: isActive ? null : context.secondaryText,
),
overflow: TextOverflow.ellipsis,
),
),
if (!isActive) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.red.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(4),
border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
),
child: const Text(
'DISATTIVATO',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
],
],
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -177,19 +217,18 @@ class _StaffScreenState extends State<StaffScreen> {
Text(
'Qualifica: ${member.jobTitle!}',
style: TextStyle(
color: context.accent,
color: isActive ? context.accent : Colors.grey,
fontWeight: FontWeight.w500,
),
),
],
],
),
// MODIFICA UX: Menu a tendina per le azioni (Salva spazio e previene overflow)
trailing: canManageStaff && hasEmail
trailing: canManageStaff
? PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) {
if (value == 'invite_reset') {
onSelected: (value) async {
if (value == 'invite_reset' && hasEmail) {
if (!member.hasJoined) {
context.read<StaffCubit>().inviteStaffMember(
member: member,
@@ -207,22 +246,97 @@ class _StaffScreenState extends State<StaffScreen> {
} else {
context.read<StaffCubit>().resetPassword(member.email!);
}
} else if (value == 'toggle_active') {
final newActiveState = !member.isActive;
final confirm = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
newActiveState
? "Riattivare ${member.name}?"
: "Disattivare ${member.name}?",
),
content: Text(
newActiveState
? "L'addetto tornerà attivo e selezionabile per nuove operazioni, ticket e gare."
: "L'addetto non comparirà più nella selezione per nuove operazioni o ticket e non comparirà nelle gare e nelle loro ripartizioni. I dati storici rimarranno intatti.",
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text("Annulla"),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor:
newActiveState ? Colors.green : Colors.red,
),
onPressed: () => Navigator.pop(ctx, true),
child: Text(
newActiveState ? "Riattiva" : "Disattiva",
),
),
],
),
);
if (confirm != true || !mounted) return;
context.read<StaffCubit>().saveStaffMember(
member.copyWith(isActive: newActiveState),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
newActiveState
? "${member.name} riattivato con successo!"
: "${member.name} disattivato con successo.",
),
backgroundColor:
newActiveState ? Colors.green : Colors.orange.shade800,
),
);
}
},
itemBuilder: (context) => [
if (hasEmail)
PopupMenuItem(
value: 'invite_reset',
child: Row(
children: [
Icon(
!member.hasJoined ? Icons.send : Icons.lock_reset,
size: 20,
),
const SizedBox(width: 12),
Text(
!member.hasJoined
? "Re-invia Invito"
: "Reset Password",
),
],
),
),
PopupMenuItem(
value: 'invite_reset',
value: 'toggle_active',
child: Row(
children: [
Icon(
!member.hasJoined ? Icons.send : Icons.lock_reset,
member.isActive
? Icons.person_off_outlined
: Icons.person_add_alt_outlined,
size: 20,
color: member.isActive ? Colors.redAccent : Colors.green,
),
const SizedBox(width: 12),
Text(
!member.hasJoined
? "Re-invia Invito"
: "Reset Password",
member.isActive
? "Disattiva Addetto"
: "Riattiva Addetto",
style: TextStyle(
color:
member.isActive ? Colors.redAccent : Colors.green,
),
),
],
),
@@ -241,6 +355,7 @@ class _StaffScreenState extends State<StaffScreen> {
final emailController = TextEditingController(text: member?.email);
final phoneController = TextEditingController(text: member?.phoneNumber);
final jobTitleController = TextEditingController(text: member?.jobTitle);
bool isActive = member?.isActive ?? true;
SystemRole selectedRole = member?.systemRole ?? SystemRole.user;
List<String> tempSelectedStores =
@@ -345,7 +460,31 @@ class _StaffScreenState extends State<StaffScreen> {
),
],
),
const SizedBox(height: 24),
const SizedBox(height: 16),
// SWITCH ATTIVO / DISATTIVATO
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: isActive,
title: const Text(
"Collaboratore Attivo",
style: TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
isActive
? "Visibile per nuove operazioni, ticket e gare"
: "Disattivato (invisibile per nuove operazioni, ticket e gare)",
style: TextStyle(
fontSize: 12,
color: context.secondaryText,
),
),
activeThumbColor: context.accent,
onChanged: (val) {
setModalState(() => isActive = val);
},
),
const SizedBox(height: 16),
const Text(
"Assegna ai Negozi",
@@ -412,6 +551,7 @@ class _StaffScreenState extends State<StaffScreen> {
phoneNumber: phoneController.text.trim(),
jobTitle: jobTitleController.text.trim(),
systemRole: selectedRole,
isActive: isActive,
companyId: GetIt.I
.get<SessionCubit>()
.state
+9 -4
View File
@@ -37,10 +37,15 @@ class NotesCubit extends Cubit<NotesState> {
try {
_subscription = _repository
.notesStream(companyId: companyId!, currentStaffId: staffId!)
.listen((_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadNotesSilently();
});
.listen(
(_) {
// Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
_loadNotesSilently();
},
onError: (error, stackTrace) {
debugPrint('Notes stream error: $error');
},
);
} on Exception catch (e) {
debugPrint(e.toString());
}
+91 -34
View File
@@ -21,10 +21,13 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
late TextEditingController _titleController;
late TextEditingController _contentController;
late final NotesCubit _notesCubit;
late final String _companyId;
late String _selectedColor;
late bool _isPinned;
late bool _isSharedAll;
late List<String> _selectedStaffIds;
bool _hasPendingChanges = false;
bool _isDeleted = false;
// Inizializziamo il Debouncer a 500 millisecondi
final _debouncer = Debouncer(milliseconds: 500);
@@ -44,6 +47,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
_titleController = TextEditingController(text: widget.note.title ?? '');
_contentController = TextEditingController(text: widget.note.content ?? '');
_notesCubit = context.read<NotesCubit>();
_companyId = widget.note.companyId.isNotEmpty
? widget.note.companyId
: context.read<SessionCubit>().state.company!.id!;
_selectedColor = widget.note.color;
_isPinned = widget.note.isPinned;
_isSharedAll = widget.note.isSharedAll;
@@ -58,29 +64,49 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
void dispose() {
_titleController.removeListener(_onFieldsChanged);
_contentController.removeListener(_onFieldsChanged);
_titleController.dispose();
_contentController.dispose();
_debouncer.dispose();
// --- IL BOTTO FINALE: PULIZIA SILENZIOSA ---
_checkAndCleanupIfEmpty(_note.id!);
// Se ci sono modifiche pendenti non ancora salvate dal debouncer, salviamole subito
if (!_isDeleted) {
_flushIfPending();
// --- IL BOTTO FINALE: PULIZIA SILENZIOSA ---
_checkAndCleanupIfEmpty(_note.id!);
}
_titleController.dispose();
_contentController.dispose();
super.dispose();
}
/// Chiamata ogni volta che l'utente digita una lettera
void _onFieldsChanged() {
_hasPendingChanges = true;
_debouncer.run(() => _triggerAutoSave());
}
void _flushIfPending() {
final isNoteEmpty =
_titleController.text.trim().isEmpty &&
_contentController.text.trim().isEmpty;
if (_hasPendingChanges && !isNoteEmpty) {
_triggerAutoSave();
}
}
void _closeNote() {
FocusScope.of(context).unfocus();
_flushIfPending();
Navigator.of(context).maybePop();
}
/// Salva in background notificando il BLoC (così la bacheca si aggiorna in tempo reale)
void _triggerAutoSave() {
final companyId = context.read<SessionCubit>().state.company!.id!;
_hasPendingChanges = false;
final updatedNote = NoteModel(
id: widget.note.id,
createdBy: widget.note.createdBy,
companyId: companyId,
companyId: _companyId,
title: _titleController.text.trim(),
content: _contentController.text.trim(),
color: _selectedColor,
@@ -98,9 +124,6 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
final titleEmpty = _titleController.text.trim().isEmpty;
final contentEmpty = _contentController.text.trim().isEmpty;
//Se hai un modo per verificare se ci sono allegati associati (es. tramite una query locale o un contatore),
// assicurati che non ce ne siano prima di eliminare.
// Assumiamo che se non ha scritto testo ed è appena stata creata, sia vuota.
if (titleEmpty && contentEmpty) {
// Notifichiamo anche il Bloc dell'avvenuta cancellazione così pulisce lo stato locale
_notesCubit.deleteNote(noteId);
@@ -108,6 +131,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
}
void _deleteNote() {
_isDeleted = true;
_hasPendingChanges = false;
_debouncer.dispose();
_notesCubit.deleteNote(widget.note.id!);
Navigator.pop(context);
}
@@ -223,28 +249,60 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: 'Chiudi nota',
onPressed: _closeNote,
),
flexibleSpace: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeNote,
),
// Freccia indietro chiara per fare contrasto sullo sfondo grigio scuro
iconTheme: const IconThemeData(color: Colors.white70),
),
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 64, left: 16, right: 16),
child: Container(
// 2. IL NOSTRO POST-IT FISICO
decoration: BoxDecoration(
color: noteColor,
borderRadius: BorderRadius.circular(16), // Bordi arrotondati
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.4), // Ombra morbida
blurRadius: 24,
offset: const Offset(0, 12),
),
],
),
padding: const EdgeInsets.all(24.0),
body: Stack(
children: [
// Area esterna cliccabile: toccando fuori dal Post-it la nota si chiude
Positioned.fill(
child: GestureDetector(
key: const ValueKey('note_outside_backdrop'),
behavior: HitTestBehavior.opaque,
onTap: _closeNote,
),
),
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: SingleChildScrollView(
padding: const EdgeInsets.only(
top: 8,
bottom: 48,
left: 16,
right: 16,
),
child: GestureDetector(
key: const ValueKey('note_postit_card'),
behavior: HitTestBehavior.opaque,
onTap: () {},
child: Container(
// 2. IL NOSTRO POST-IT FISICO
decoration: BoxDecoration(
color: noteColor,
borderRadius: BorderRadius.circular(
16,
), // Bordi arrotondati
boxShadow: [
BoxShadow(
color: Colors.black.withValues(
alpha: 0.4,
), // Ombra morbida
blurRadius: 24,
offset: const Offset(0, 12),
),
],
),
padding: const EdgeInsets.all(24.0),
child: Column(
// 3. MainAxisSize.min fa sì che il Post-it sia alto solo quanto serve!
mainAxisSize: MainAxisSize.min,
@@ -393,7 +451,7 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
height: 1.5,
),
maxLines: null,
minLines: 12,
minLines: MediaQuery.sizeOf(context).height < 750 ? 6 : 10,
decoration: const InputDecoration(
hintText: 'Scrivi qui la tua nota...',
hintStyle: TextStyle(color: Colors.black38),
@@ -478,10 +536,6 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
),
],
const SizedBox(height: 24),
const Divider(color: Colors.black12),
const SizedBox(height: 24),
// --- ALLEGATI ---
// SharedAttachmentsSection(
// parentType: AttachmentParentType.note,
@@ -493,6 +547,9 @@ class _NoteFormScreenState extends State<NoteFormScreen> {
),
),
),
);
),
],
),
);
}
}
@@ -4,6 +4,7 @@ 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';
@@ -22,7 +23,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
if (initialDetail == null &&
allProviders != null &&
allProviders.isNotEmpty) {
const defaultType = 'AL';
const defaultType = OperationType.al;
setTypeWithSmartDefaults(
newType: defaultType,
allProviders: allProviders,
@@ -32,15 +33,18 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
}
void updateFields({
String? type,
OperationType? type,
String? subType,
ProviderModel? provider,
ModelModel? model,
String? modelId,
String? description,
DateTime? expirationDate,
int? quantity,
}) {
final current = state.operationDetail;
final sanitizedQuantity =
quantity != null ? (quantity < 1 ? 1 : quantity) : current.quantity;
final updated = current.copyWith(
type: type ?? current.type,
subType: subType ?? current.subType,
@@ -55,6 +59,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
modelId: modelId ?? current.modelId,
description: description ?? current.description,
expirationDate: expirationDate ?? current.expirationDate,
quantity: sanitizedQuantity,
);
emit(
@@ -79,7 +84,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
}
void setTypeWithSmartDefaults({
required String newType,
required OperationType newType,
required List<ProviderModel> allProviders,
String? defaultProviderId,
}) {
@@ -88,7 +93,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
final foundDefault = allProviders.firstWhere(
(p) =>
p.id == defaultProviderId &&
p.supportsOperation(newType) &&
p.supportsOperationType(newType) &&
p.isActive,
orElse: () => const ProviderModel(companyId: '', name: ''),
);
@@ -98,7 +103,7 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
}
if (selectedProvider == null) {
final foundCompatible = allProviders.firstWhere(
(p) => p.supportsOperation(newType) && p.isActive,
(p) => p.supportsOperationType(newType) && p.isActive,
orElse: () => const ProviderModel(companyId: '', name: ''),
);
if (foundCompatible.id != null) {
@@ -109,7 +114,8 @@ class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
final current = state.operationDetail;
final updated = current.copyWith(
type: newType,
subType: newType == 'Energy' ? 'Luce' : null,
subType: newType == OperationType.energy ? EnergySubtypes.luce : null,
quantity: newType.supportsQuantity ? current.quantity : 1,
provider: selectedProvider != null ? () => selectedProvider : null,
providerId: selectedProvider?.id,
);
@@ -1,6 +1,7 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:uuid/uuid.dart';
part 'operation_details_list_state.dart';
@@ -10,8 +11,12 @@ class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
void addOperationDetail(OperationDetailModel operationDetail) {
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final detailToAdd =
(operationDetail.id != null && operationDetail.id!.isNotEmpty)
? operationDetail
: operationDetail.copyWith(id: const Uuid().v4());
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails.add(operationDetail);
updatedDetails.add(detailToAdd);
emit(
OperationDetailsListState(
details: updatedDetails,
@@ -94,4 +99,22 @@ class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
),
);
}
/// Aggiorna la quantità/valore di un dettaglio esistente (minimo 1)
void updateOperationDetailQuantity(int index, int newQuantity) {
if (index < 0 || index >= state.details.length) return;
final clamped = newQuantity < 1 ? 1 : newQuantity;
if (state.details[index].quantity == clamped) return;
emit(state.copyWith(status: OperationDetailsListStatus.ready));
final updatedDetails = List<OperationDetailModel>.from(state.details);
updatedDetails[index] = updatedDetails[index].copyWith(quantity: clamped);
emit(
OperationDetailsListState(
details: updatedDetails,
selectedIds: state.selectedIds,
status: OperationDetailsListStatus.updated,
),
);
}
}
@@ -1,4 +1,6 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
@@ -14,6 +16,12 @@ class OperationFormCubit extends Cubit<OperationFormState> {
final OperationsRepository _repository = sl<OperationsRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
Timer? _debounceTimer;
Timer? _periodicTimer;
static const Duration _debounceDuration = Duration(milliseconds: 1500);
static const Duration _periodicDuration = Duration(seconds: 60);
OperationFormCubit({
StaffMemberModel? createdBy,
OperationModel? existingOperation,
@@ -44,6 +52,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
} else if (operationId != null) {
emit(state.copyWith(status: OperationFormStatus.loading));
try {
@@ -56,6 +65,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
} on Exception catch (e) {
emit(
state.copyWith(
@@ -80,9 +90,10 @@ class OperationFormCubit extends Cubit<OperationFormState> {
),
status: OperationFormStatus.ready,
isNew: true,
hasUnsavedChanges: true,
hasUnsavedChanges: false,
),
);
_startPeriodicTimer();
}
} catch (e) {
emit(
@@ -94,16 +105,100 @@ class OperationFormCubit extends Cubit<OperationFormState> {
}
}
// --- SALVATAGGIO ---
// --- TIMER E AUTOSAVE ---
void _scheduleAutoSave() {
_debounceTimer?.cancel();
_debounceTimer = Timer(_debounceDuration, () {
autoSave();
});
}
void _startPeriodicTimer() {
_periodicTimer?.cancel();
_periodicTimer = Timer.periodic(_periodicDuration, (_) {
if (state.hasUnsavedChanges && !state.isAutoSaving) {
autoSave();
}
});
}
Future<void> autoSave() async {
_debounceTimer?.cancel();
if (state.operation.id == null ||
state.status != OperationFormStatus.ready ||
!state.hasUnsavedChanges ||
state.isAutoSaving) {
return;
}
emit(state.copyWith(isAutoSaving: true, autoSaveError: null));
try {
final snapshotBeforeSave = state.operation;
OperationModel operationToSave = snapshotBeforeSave;
if (operationToSave.reference.isEmpty) {
if (operationToSave.customer != null &&
operationToSave.customer!.phoneNumber.isNotEmpty) {
operationToSave = operationToSave.copyWith(
reference: '${operationToSave.customer?.phoneNumber} - auto',
);
}
}
final savedOperation = await _repository.updateOperation(operationToSave);
final savedTimestamp = savedOperation.updatedAt ?? DateTime.now();
final bool hasNewChanges = state.operation != snapshotBeforeSave;
emit(
state.copyWith(
isAutoSaving: false,
hasUnsavedChanges: hasNewChanges,
lastSavedAt: savedTimestamp,
autoSaveError: null,
operation: state.operation.copyWith(
createdAt: savedOperation.createdAt,
updatedAt: savedTimestamp,
details: savedOperation.details,
),
),
);
} catch (e) {
debugPrint('Errore durante autosave operazione: $e');
emit(
state.copyWith(
isAutoSaving: false,
autoSaveError: e.toString(),
),
);
}
}
Future<void> flushAutoSave() async {
_debounceTimer?.cancel();
if (state.hasUnsavedChanges && !state.isAutoSaving) {
await autoSave();
}
}
// --- SALVATAGGIO MANUALE DEFINITIVO ---
Future<void> saveOperation({required OperationStatus targetStatus}) async {
_debounceTimer?.cancel();
emit(
state.copyWith(status: OperationFormStatus.saving, errorMessage: null),
state.copyWith(
status: OperationFormStatus.saving,
isAutoSaving: false,
errorMessage: null,
),
);
try {
OperationModel operationToSave = state.operation.copyWith(
status: targetStatus,
showInDashboard: true,
);
if (operationToSave.reference.isEmpty) {
if (operationToSave.customer != null &&
@@ -117,13 +212,14 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
}
}
await _repository.updateOperation(operationToSave);
final savedOperation = await _repository.updateOperation(operationToSave);
emit(
state.copyWith(
status: OperationFormStatus.success,
operation: operationToSave,
operation: savedOperation,
isNew: false,
hasUnsavedChanges: false,
lastSavedAt: savedOperation.updatedAt ?? DateTime.now(),
),
);
} catch (e) {
@@ -138,7 +234,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
// --- ANNULLA E ELIMINA SE NUOVA ---
Future<void> discardAndExit() async {
emit(state.copyWith(status: OperationFormStatus.saving));
_debounceTimer?.cancel();
_periodicTimer?.cancel();
emit(state.copyWith(status: OperationFormStatus.saving, isAutoSaving: false));
try {
if (state.isNew && state.operation.id != null) {
await _repository.deleteOperation(state.operation.id!);
@@ -164,7 +262,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
final id = state.operation.id;
if (id == null || id.isEmpty) return;
emit(state.copyWith(status: OperationFormStatus.saving));
_debounceTimer?.cancel();
_periodicTimer?.cancel();
emit(state.copyWith(status: OperationFormStatus.saving, isAutoSaving: false));
try {
await _repository.deleteOperation(id);
emit(
@@ -203,6 +303,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
);
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
_scheduleAutoSave();
}
void updateCustomer(CustomerModel customer) {
@@ -213,11 +314,20 @@ class OperationFormCubit extends Cubit<OperationFormState> {
isBusiness: isBusiness,
);
emit(state.copyWith(operation: updatedOperation, hasUnsavedChanges: true));
_scheduleAutoSave();
}
void updateOperationDetailsList(List<OperationDetailModel> details) {
final current = state.operation;
final updated = current.copyWith(details: details);
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
_scheduleAutoSave();
}
@override
Future<void> close() {
_debounceTimer?.cancel();
_periodicTimer?.cancel();
return super.close();
}
}
@@ -16,6 +16,9 @@ class OperationFormState extends Equatable {
final String? errorMessage;
final bool isNew;
final bool hasUnsavedChanges;
final bool isAutoSaving;
final DateTime? lastSavedAt;
final String? autoSaveError;
const OperationFormState({
this.status = OperationFormStatus.initial,
@@ -23,6 +26,9 @@ class OperationFormState extends Equatable {
this.errorMessage,
this.isNew = false,
this.hasUnsavedChanges = false,
this.isAutoSaving = false,
this.lastSavedAt,
this.autoSaveError,
});
OperationFormState copyWith({
@@ -31,6 +37,9 @@ class OperationFormState extends Equatable {
String? errorMessage,
bool? isNew,
bool? hasUnsavedChanges,
bool? isAutoSaving,
DateTime? lastSavedAt,
String? autoSaveError,
}) {
return OperationFormState(
status: status ?? this.status,
@@ -38,6 +47,9 @@ class OperationFormState extends Equatable {
errorMessage: errorMessage,
isNew: isNew ?? this.isNew,
hasUnsavedChanges: hasUnsavedChanges ?? this.hasUnsavedChanges,
isAutoSaving: isAutoSaving ?? this.isAutoSaving,
lastSavedAt: lastSavedAt ?? this.lastSavedAt,
autoSaveError: autoSaveError,
);
}
@@ -48,5 +60,8 @@ class OperationFormState extends Equatable {
errorMessage,
isNew,
hasUnsavedChanges,
isAutoSaving,
lastSavedAt,
autoSaveError,
];
}
@@ -1,9 +1,13 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:get_it/get_it.dart';
part 'operation_list_state.dart';
@@ -12,10 +16,19 @@ class OperationListCubit extends Cubit<OperationListState> {
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
OperationListCubit() : super(const OperationListState());
StreamSubscription<void>? _operationsSubscription;
int _fetchId = 0;
OperationListCubit() : super(const OperationListState()) {
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
refreshCurrentPage();
});
}
void refreshCurrentPage() {
loadSpecificPageDesktop(state.currentPage);
}
// 🥷 MOTORE 1: DESKTOP (Sostituisce la lista)
Future<void> loadSpecificPageDesktop(int page) async {
final currentFetchId = ++_fetchId;
@@ -29,6 +42,11 @@ class OperationListCubit extends Cubit<OperationListState> {
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
detailType: state.detailType,
subType: state.subType,
categoryKey: state.categoryKey,
staffId: state.staffId,
storeId: state.storeId,
);
if (currentFetchId != _fetchId) return;
@@ -74,6 +92,11 @@ class OperationListCubit extends Cubit<OperationListState> {
itemsPerPage: state.itemsPerPage,
searchTerm: state.searchTerm,
dateRange: state.dateRange,
detailType: state.detailType,
subType: state.subType,
categoryKey: state.categoryKey,
staffId: state.staffId,
storeId: state.storeId,
);
if (currentFetchId != _fetchId) return;
@@ -101,13 +124,74 @@ class OperationListCubit extends Cubit<OperationListState> {
}
}
void updateFilters({String? text, DateTimeRange? range}) {
/// Applica un set completo di parametri di filtro (es. proveniente da una card Obiettivo)
void applyFilterParams(OperationFilterParams params) {
emit(
state.copyWith(
// 🥷 FORZIAMO IL TIPO: Diciamo a Dart che il risultato del ternario è proprio una funzione
searchTerm: text != null ? () => text : null,
dateRange: range != null ? () => range : null,
searchTerm: () => params.searchTerm,
dateRange: () => params.dateRange,
detailType: () => params.detailType,
subType: () => params.subType,
categoryKey: () => params.categoryKey,
categoryLabel: () => params.categoryLabel,
staffId: () => params.staffId,
staffDisplayName: () => params.staffDisplayName,
storeId: () => params.storeId,
currentPage: 1,
hasReachedMax: false,
),
);
loadSpecificPageDesktop(1);
}
void updateFilters({
String? text,
DateTimeRange? range,
OperationType? detailType,
String? subType,
String? categoryKey,
String? categoryLabel,
String? staffId,
String? staffDisplayName,
String? storeId,
bool clearText = false,
bool clearRange = false,
bool clearDetailType = false,
bool clearSubType = false,
bool clearCategory = false,
bool clearStaff = false,
bool clearStore = false,
}) {
emit(
state.copyWith(
searchTerm: clearText
? () => null
: (text != null ? () => text : null),
dateRange: clearRange
? () => null
: (range != null ? () => range : null),
detailType: clearDetailType
? () => null
: (detailType != null ? () => detailType : null),
subType: clearSubType
? () => null
: (subType != null ? () => subType : null),
categoryKey: clearCategory
? () => null
: (categoryKey != null ? () => categoryKey : null),
categoryLabel: clearCategory
? () => null
: (categoryLabel != null ? () => categoryLabel : null),
staffId: clearStaff
? () => null
: (staffId != null ? () => staffId : null),
staffDisplayName: clearStaff
? () => null
: (staffDisplayName != null ? () => staffDisplayName : null),
storeId: clearStore
? () => null
: (storeId != null ? () => storeId : null),
currentPage: 1, // Reset obbligatorio alla prima pagina
hasReachedMax: false,
),
@@ -118,10 +202,13 @@ class OperationListCubit extends Cubit<OperationListState> {
}
void clearFilters() {
// Invece di un const vuoto che potrebbe bruciarti l'impostazione itemsPerPage,
// creiamo uno stato pulito ma manteniamo la preferenza di paginazione.
emit(OperationListState(itemsPerPage: state.itemsPerPage));
loadSpecificPageDesktop(1);
}
@override
Future<void> close() {
_operationsSubscription?.cancel();
return super.close();
}
}
@@ -13,9 +13,16 @@ class OperationListState extends Equatable {
final int totalItems;
final bool hasReachedMax;
// 🥷 I FILTRI MANCANTI (Riparati!)
// Filtri Avanzati
final String? searchTerm;
final DateTimeRange? dateRange;
final OperationType? detailType;
final String? subType;
final String? categoryKey;
final String? categoryLabel;
final String? staffId;
final String? staffDisplayName;
final String? storeId;
const OperationListState({
this.status = OperationListStatus.initial,
@@ -27,11 +34,54 @@ class OperationListState extends Equatable {
this.hasReachedMax = false,
this.searchTerm,
this.dateRange,
this.detailType,
this.subType,
this.categoryKey,
this.categoryLabel,
this.staffId,
this.staffDisplayName,
this.storeId,
});
int get totalPages => (totalItems / itemsPerPage).ceil();
// 🥷 COPYWITH AVANZATO: Gestisce lo sbiancamento dei filtri alla perfezione
bool get hasActiveFilters =>
(searchTerm != null && searchTerm!.trim().isNotEmpty) ||
dateRange != null ||
detailType != null ||
(subType != null && subType!.trim().isNotEmpty) ||
categoryKey != null ||
staffId != null ||
storeId != null;
int get activeFiltersCount {
int count = 0;
if (searchTerm != null && searchTerm!.trim().isNotEmpty) count++;
if (dateRange != null) count++;
if (detailType != null) count++;
if (subType != null && subType!.trim().isNotEmpty && categoryKey == null) {
count++;
}
if (categoryKey != null) count++;
if (staffId != null) count++;
if (storeId != null) count++;
return count;
}
OperationFilterParams toFilterParams() {
return OperationFilterParams(
searchTerm: searchTerm,
dateRange: dateRange,
detailType: detailType,
subType: subType,
categoryKey: categoryKey,
categoryLabel: categoryLabel,
staffId: staffId,
staffDisplayName: staffDisplayName,
storeId: storeId,
);
}
OperationListState copyWith({
OperationListStatus? status,
List<OperationModel>? operations,
@@ -40,9 +90,15 @@ class OperationListState extends Equatable {
int? itemsPerPage,
int? totalItems,
bool? hasReachedMax,
String? Function()? searchTerm, // Callback per gestire il null esplicito
DateTimeRange? Function()?
dateRange, // Callback per gestire il null esplicito
String? Function()? searchTerm,
DateTimeRange? Function()? dateRange,
OperationType? Function()? detailType,
String? Function()? subType,
String? Function()? categoryKey,
String? Function()? categoryLabel,
String? Function()? staffId,
String? Function()? staffDisplayName,
String? Function()? storeId,
}) {
return OperationListState(
status: status ?? this.status,
@@ -52,10 +108,17 @@ class OperationListState extends Equatable {
itemsPerPage: itemsPerPage ?? this.itemsPerPage,
totalItems: totalItems ?? this.totalItems,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
// Se passi la funzione la eseguiamo, altrimenti teniamo il valore corrente
searchTerm: searchTerm != null ? searchTerm() : this.searchTerm,
dateRange: dateRange != null ? dateRange() : this.dateRange,
detailType: detailType != null ? detailType() : this.detailType,
subType: subType != null ? subType() : this.subType,
categoryKey: categoryKey != null ? categoryKey() : this.categoryKey,
categoryLabel:
categoryLabel != null ? categoryLabel() : this.categoryLabel,
staffId: staffId != null ? staffId() : this.staffId,
staffDisplayName:
staffDisplayName != null ? staffDisplayName() : this.staffDisplayName,
storeId: storeId != null ? storeId() : this.storeId,
);
}
@@ -70,5 +133,12 @@ class OperationListState extends Equatable {
hasReachedMax,
searchTerm,
dateRange,
detailType,
subType,
categoryKey,
categoryLabel,
staffId,
staffDisplayName,
storeId,
];
}
@@ -1,15 +1,29 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/consts.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/operation_type.dart';
import 'package:flux/features/operations/models/paginated_operations.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:uuid/uuid.dart';
class OperationsRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
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
@@ -41,10 +55,15 @@ class OperationsRepository {
String? storeId,
String? staffId,
String? providerId,
OperationType? detailType,
String? subType,
String? categoryKey,
bool? isBusiness,
required int page,
int itemsPerPage = 20,
String? searchTerm,
DateTimeRange? dateRange,
bool onlyShowInDashboard = false,
}) async {
try {
// Calcoliamo il range di partenza e fine per Supabase
@@ -53,6 +72,12 @@ class OperationsRepository {
final from = (page - 1) * itemsPerPage;
final to = from + itemsPerPage - 1;
final hasDetailFilter = detailType != null ||
(subType != null && subType.trim().isNotEmpty) ||
(categoryKey != null && categoryKey != 'business');
final detailJoin = hasDetailFilter ? '!inner' : '';
var query = _supabase
.from(Tables.operations)
.select('''
@@ -61,7 +86,7 @@ class OperationsRepository {
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
${Tables.operationDetails}$detailJoin(
*,
${Tables.providers}(*),
${Tables.models}(*)
@@ -69,25 +94,67 @@ class OperationsRepository {
''')
.eq('company_id', companyId);
if (onlyShowInDashboard) {
query = query.eq('show_in_dashboard', true);
}
// Se veniamo da una categoria target, escludiamo le operazioni annullate/scartate
if (categoryKey != null) {
query = query.neq('status', 'failure');
}
// Filtro Range Date
if (dateRange != null) {
final start = dateRange.start;
final end = (dateRange.end.hour == 0 && dateRange.end.minute == 0)
? DateTime(
dateRange.end.year,
dateRange.end.month,
dateRange.end.day,
23,
59,
59,
999,
)
: dateRange.end;
query = query
.gte('created_at', dateRange.start.toIso8601String())
.lte('created_at', dateRange.end.toIso8601String());
.gte('created_at', start.toIso8601String())
.lte('created_at', end.toIso8601String());
}
if (storeId != null) {
query = query.or('store_id.eq.$storeId,store_id.is.null');
if (storeId != null && storeId.isNotEmpty) {
if (categoryKey != null) {
query = query.eq('store_id', storeId);
} else {
query = query.or('store_id.eq.$storeId,store_id.is.null');
}
}
if (staffId != null) {
query = query.or('staff_id.eq.$staffId,staff_id.is.null');
if (staffId != null && staffId.isNotEmpty) {
query = query.eq('staff_id', staffId);
}
if (providerId != null) {
if (providerId != null && providerId.isNotEmpty) {
query = query.or('provider_id.eq.$providerId,provider_id.is.null');
}
// Filtro per Dettaglio Operazione / Categoria
if (categoryKey == 'business' || isBusiness == true) {
query = query.or(
'is_business.eq.true,${Tables.operationDetails}.type.eq.Business',
);
} else {
if (detailType != null) {
query = query.eq('${Tables.operationDetails}.type', detailType.value);
}
if (subType != null && subType.trim().isNotEmpty) {
query = query.ilike(
'${Tables.operationDetails}.sub_type',
'%${subType.trim()}%',
);
}
}
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
@@ -161,6 +228,7 @@ class OperationsRepository {
staffId: createdById,
companyId: currentStore.companyId,
status: OperationStatus.success,
showInDashboard: false,
)
.toMap(),
)
@@ -169,6 +237,7 @@ class OperationsRepository {
${Tables.staffMembers}(*)
''')
.single();
notifyOperationsChanged();
return OperationModel.fromMap(res);
} on Exception catch (e) {
debugPrint('ERRORE CREAZIONE OPERAZIONE: $e');
@@ -179,26 +248,53 @@ class OperationsRepository {
Future<void> deleteOperation(String id) async {
try {
await _supabase.from(Tables.operations).delete().eq('id', id);
notifyOperationsChanged();
} catch (e) {
debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e');
throw Exception('Errore nella cancellazione dell\'operazione: $e');
}
}
Future<void> updateOperation(OperationModel operation) async {
Future<OperationModel> updateOperation(OperationModel operation) async {
try {
await _supabase
final updatedRow = await _supabase
.from(Tables.operations)
.update(operation.toMap())
.eq('id', operation.id!);
.eq('id', operation.id!)
.select()
.maybeSingle();
final currentDetailIds =
operation.details
.map((d) => d.id)
.where((id) => id != null && id.isNotEmpty)
.cast<String>()
.toList();
final DateTime resolvedUpdatedAt = updatedRow?['updated_at'] != null
? DateTime.parse(updatedRow!['updated_at'] as String).toLocal()
: DateTime.now();
final DateTime? resolvedCreatedAt =
operation.createdAt ??
(updatedRow?['created_at'] != null
? DateTime.parse(updatedRow!['created_at'] as String).toLocal()
: null);
final updatedDetails = <OperationDetailModel>[];
for (OperationDetailModel detail in operation.details) {
final detailId = (detail.id != null && detail.id!.isNotEmpty)
? detail.id!
: const Uuid().v4();
final detailToSave = detail.copyWith(
id: detailId,
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
updatedDetails.add(detailToSave);
}
final currentDetailIds = updatedDetails.map((d) => d.id!).toList();
if (currentDetailIds.isNotEmpty) {
await _supabase
.from(Tables.operationDetails)
@@ -212,22 +308,132 @@ class OperationsRepository {
.eq('operation_id', operation.id!);
}
for (OperationDetailModel detail in operation.details) {
final detailToSave = detail.copyWith(
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
}
notifyOperationsChanged();
return operation.copyWith(
createdAt: resolvedCreatedAt,
updatedAt: resolvedUpdatedAt,
details: updatedDetails,
);
} catch (e) {
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
throw Exception('Errore nel salvataggio dell\'operazione: $e');
}
}
Future<List<OperationModel>> fetchExpiringOperations({
required String companyId,
String? storeId,
int limit = 20,
}) async {
try {
var query = _supabase
.from(Tables.operations)
.select('''
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}!inner(
*,
${Tables.providers}(*),
${Tables.models}(*)
)
''')
.eq('company_id', companyId)
.not('${Tables.operationDetails}.expiration_date', 'is', null);
if (storeId != null && storeId.isNotEmpty) {
query = query.or('store_id.eq.$storeId,store_id.is.null');
}
final response = await query
.order('created_at', ascending: false)
.limit(limit);
final List<OperationModel> operations = (response as List)
.map((map) => OperationModel.fromMap(map as Map<String, dynamic>))
.toList();
operations.sort((a, b) {
final aExp = getEarliestExpiration(a);
final bExp = getEarliestExpiration(b);
if (aExp == null && bExp == null) return 0;
if (aExp == null) return 1;
if (bExp == null) return -1;
return aExp.compareTo(bExp);
});
return operations;
} catch (e) {
debugPrint('Errore nel recupero contratti/operazioni in scadenza: $e');
return [];
}
}
static DateTime? getEarliestExpiration(OperationModel op) {
DateTime? earliest;
for (final d in op.details) {
if (d.expirationDate != null) {
if (earliest == null || d.expirationDate!.isBefore(earliest)) {
earliest = d.expirationDate;
}
}
}
return earliest;
}
/// Recupera il conteggio dei ricontatti registrati nel mese per ciascun addetto del negozio
Future<Map<String, int>> getMonthlyRicontattiCountsByStaff({
required String companyId,
required String storeId,
required DateTime month,
}) async {
try {
final monthStart = DateTime(month.year, month.month, 1, 0, 0, 0);
final monthEnd = DateTime(month.year, month.month + 1, 0, 23, 59, 59, 999);
final response = await _supabase
.from(Tables.operations)
.select('''
id,
staff_id,
${Tables.operationDetails}(
type
)
''')
.eq('company_id', companyId)
.eq('store_id', storeId)
.neq('status', 'failure')
.gte('created_at', monthStart.toIso8601String())
.lte('created_at', monthEnd.toIso8601String());
final operations = response as List<dynamic>;
final Map<String, int> staffCounts = {};
for (final op in operations) {
final staffId = op['staff_id'] as String?;
if (staffId == null || staffId.isEmpty) continue;
final details = op[Tables.operationDetails] as List<dynamic>? ?? [];
int ricontattiInOp = 0;
for (final detail in details) {
final typeVal = detail['type']?.toString();
if (typeVal != null &&
OperationType.fromValue(typeVal) == OperationType.ricontatto) {
ricontattiInOp++;
}
}
if (ricontattiInOp > 0) {
staffCounts[staffId] = (staffCounts[staffId] ?? 0) + ricontattiInOp;
}
}
return staffCounts;
} catch (e) {
debugPrint('Errore nel recupero conteggi ricontatti del mese: $e');
return {};
}
}
}
@@ -0,0 +1,236 @@
class FinancingTranslations {
static const List<FinancingLanguage> supportedLanguages = [
FinancingLanguage(code: 'it', name: 'Italiano', flag: '🇮🇹', isRtl: false),
FinancingLanguage(code: 'en', name: 'English', flag: '🇬🇧', isRtl: false),
FinancingLanguage(code: 'fr', name: 'Français', flag: '🇫🇷', isRtl: false),
FinancingLanguage(code: 'es', name: 'Español', flag: '🇪🇸', isRtl: false),
FinancingLanguage(code: 'ar', name: 'العربية', flag: '🇸🇦', isRtl: true),
FinancingLanguage(code: 'uk', name: 'Українська', flag: '🇺🇦', isRtl: false),
FinancingLanguage(code: 'ru', name: 'Русский', flag: '🇷🇺', isRtl: false),
FinancingLanguage(code: 'mk', name: 'Македонски', flag: '🇲🇰', isRtl: false),
FinancingLanguage(code: 'sq', name: 'Shqip', flag: '🇦🇱', isRtl: false),
];
static const List<String> canonicalMaritalStatuses = [
'Celibe / Nubile',
'Coniugato/a',
'Separato/a',
'Divorziato/a',
'Vedovo/a',
];
static const List<String> canonicalIncomeRanges = [
'Fino a 2.000 €',
'Da 2.000 € a 5.000 €',
'Oltre 5.000 €',
];
static FinancingStrings getStrings(String langCode) {
switch (langCode) {
case 'en':
return const FinancingStrings(
title: 'Financing Details',
subtitle: 'Please fill in the information below required for your financing application.',
maritalStatusLabel: 'Marital Status',
maritalOptions: ['Single', 'Married', 'Separated', 'Divorced', 'Widowed'],
occupationLabel: 'Occupation',
occupationHint: 'e.g. Employee, Factory Worker, Self-employed...',
incomeLabel: 'Net Monthly Income',
incomeOptions: ['Up to €2,000', 'From €2,000 to €5,000', 'Over €5,000'],
submitButton: 'Submit Information',
errorRequired: 'Please complete all fields before submitting.',
successTitle: 'Information Submitted!',
successSubtitle: 'Thank you! Your information has been safely received by our store. You can close this page.',
);
case 'fr':
return const FinancingStrings(
title: 'Informations de Financement',
subtitle: 'Veuillez renseigner les informations requises pour votre demande de financement.',
maritalStatusLabel: 'État Civil',
maritalOptions: ['Célibataire', 'Marié(e)', 'Séparé(e)', 'Divorcé(e)', 'Veuf / Veuve'],
occupationLabel: 'Profession',
occupationHint: 'Ex. Employé, Ouvrier, Artisan, Indépendant...',
incomeLabel: 'Revenu Mensuel Net',
incomeOptions: ['Jusqu\'à 2 000 €', 'De 2 000 € à 5 000 €', 'Plus de 5 000 €'],
submitButton: 'Envoyer les données',
errorRequired: 'Veuillez remplir tous les champs avant de soumettre.',
successTitle: 'Données transmises avec succès !',
successSubtitle: 'Merci ! Les informations ont été reçues par notre conseiller. Vous pouvez fermer cette page.',
);
case 'es':
return const FinancingStrings(
title: 'Datos para Financiación',
subtitle: 'Completa los siguientes datos necesarios para la solicitud de financiación.',
maritalStatusLabel: 'Estado Civil',
maritalOptions: ['Soltero/a', 'Casado/a', 'Separado/a', 'Divorciado/a', 'Viudo/a'],
occupationLabel: 'Profesión',
occupationHint: 'Ej. Empleado, Obrero, Autónomo, Comerciante...',
incomeLabel: 'Ingreso Mensual Neto',
incomeOptions: ['Hasta 2.000 €', 'De 2.000 € a 5.000 €', 'Más de 5.000 €'],
submitButton: 'Enviar Datos',
errorRequired: 'Por favor, completa todos los campos antes de enviar.',
successTitle: '¡Datos enviados con éxito!',
successSubtitle: '¡Gracias! Nuestro asesor ha recibido tus datos. Ya puedes cerrar esta pantalla.',
);
case 'ar':
return const FinancingStrings(
title: 'بيانات التمويل',
subtitle: 'يرجى تعبئة البيانات التالية المطلوبة لإتمام معاملة التمويل.',
maritalStatusLabel: 'الحالة الاجتماعية',
maritalOptions: ['أعزب / عزباء', 'متزوج / متزوجة', 'منفصل / منفصلة', 'مطلق / مطلقة', 'أرمل / أرملة'],
occupationLabel: 'المهنة',
occupationHint: 'مثال: موظف، عامل، تاجر، عمل حر...',
incomeLabel: 'الدخل الشهري الصافي',
incomeOptions: ['حتى 2,000 يورو', 'من 2,000 إلى 5,000 يورو', 'أكثر من 5,000 يورو'],
submitButton: 'إرسال البيانات',
errorRequired: 'يرجى ملء جميع الحقول قبل الإرسال.',
successTitle: 'تم إرسال البيانات بنجاح!',
successSubtitle: 'شكراً لك! لقد استلم موظفنا البيانات بنجاح. يمكنك إغلاق هذه الصفحة الآن.',
);
case 'uk':
return const FinancingStrings(
title: 'Дані для фінансування',
subtitle: 'Будь ласка, заповніть наступні дані, необхідні для оформлення фінансування.',
maritalStatusLabel: 'Сімейний стан',
maritalOptions: ['Неодружений / Незаміжня', 'Одружений / Заміжня', 'Розлучений / Розлучена', 'Проживає окремо', 'Вдівець / Вдова'],
occupationLabel: 'Професія / Посада',
occupationHint: 'Наприклад: Службовець, Робітник, ФОП...',
incomeLabel: 'Чистий щомісячний дохід',
incomeOptions: ['До 2 000 €', 'Від 2 000 € до 5 000 €', 'Понад 5 000 €'],
submitButton: 'Надіслати дані',
errorRequired: 'Будь ласка, заповніть усі поля перед відправленням.',
successTitle: 'Дані успішно надіслано!',
successSubtitle: 'Дякуємо! Наш фахівець отримав ваші дані. Ви можете закрити цю сторінку.',
);
case 'ru':
return const FinancingStrings(
title: 'Данные для финансирования',
subtitle: 'Пожалуйста, заполните следующие данные, необходимые для оформления финансирования.',
maritalStatusLabel: 'Семейное положение',
maritalOptions: ['Холост / Не замужем', 'Женат / Замужем', 'Проживает раздельно', 'Разведен / Разведена', 'Вдовец / Вдова'],
occupationLabel: 'Профессия / Должность',
occupationHint: 'Например: Служащий, Рабочий, Предприниматель...',
incomeLabel: 'Чистый ежемесячный доход',
incomeOptions: ['До 2 000 €', 'От 2 000 € до 5 000 €', 'Более 5 000 €'],
submitButton: 'Отправить данные',
errorRequired: 'Пожалуйста, заполните все поля перед отправкой.',
successTitle: 'Данные успешно отправлены!',
successSubtitle: 'Спасибо! Наш сотрудник получил ваши данные. Вы можете закрыть эту страницу.',
);
case 'mk':
return const FinancingStrings(
title: 'Податоци за финансирање',
subtitle: 'Ве молиме пополнете ги следните податоци потребни за апликацијата за финансирање.',
maritalStatusLabel: 'Брачна состојба',
maritalOptions: ['Неженет / Немажена', 'Оженет / Мажена', 'Разделен / Разделена', 'Разведен / Разведена', 'Вдовец / Вдовица'],
occupationLabel: 'Професија',
occupationHint: 'Пр. Вработен, Работник, Трговец...',
incomeLabel: 'Нето месечен приход',
incomeOptions: ['До 2.000 €', 'Од 2.000 € до 5.000 €', 'Над 5.000 €'],
submitButton: 'Испрати податоци',
errorRequired: 'Ве молиме пополнете ги сите полиња пред испраќање.',
successTitle: 'Податоците се успешно испратени!',
successSubtitle: 'Ви благодариме! Нашиот оператор ги прими вашите податоци. Можете да го затворите овој прозорец.',
);
case 'sq':
return const FinancingStrings(
title: 'Të dhënat për Financim',
subtitle: 'Ju lutemi plotësoni të dhënat e mëposhtme të nevojshme për kërkesën për financim.',
maritalStatusLabel: 'Gjendja Civile',
maritalOptions: ['Beqar / Beqare', 'I/E martuar', 'I/E ndarë', 'I/E divorcuar', 'I/E ve'],
occupationLabel: 'Profesioni',
occupationHint: 'P.sh. Punonjës, Punëtor, Tregtar, Vetëpunësuar...',
incomeLabel: 'Të Ardhurat Mujore Neto',
incomeOptions: ['Deri në 2.000 €', 'Nga 2.000 € në 5.000 €', 'Mbi 5.000 €'],
submitButton: 'Dërgo të Dhënat',
errorRequired: 'Ju lutemi plotësoni të gjitha fushat para dërgimit.',
successTitle: 'Të dhënat u dërguan me sukses!',
successSubtitle: 'Faleminderit! Operatori ynë i pranoi të dhënat tuaja. Mund ta mbyllni këtë faqe.',
);
case 'it':
default:
return const FinancingStrings(
title: 'Dati per Finanziamento',
subtitle: 'Compila i seguenti dati necessari per la pratica di finanziamento.',
maritalStatusLabel: 'Stato Civile',
maritalOptions: ['Celibe / Nubile', 'Coniugato/a', 'Separato/a', 'Divorziato/a', 'Vedovo/a'],
occupationLabel: 'Professione',
occupationHint: 'Es. Impiegato, Operaio, Commerciante, Autonomo...',
incomeLabel: 'Reddito Mensile Netto',
incomeOptions: ['Fino a 2.000 €', 'Da 2.000 € a 5.000 €', 'Oltre 5.000 €'],
submitButton: 'Invia Dati',
errorRequired: 'Per favore compila tutti i campi prima di inviare.',
successTitle: 'Dati inviati con successo!',
successSubtitle: 'Grazie! Le informazioni sono state ricevute dal nostro operatore. Puoi chiudere questa schermata.',
);
}
}
static String formatNoteText({
required int maritalStatusIndex,
required String occupation,
required int incomeRangeIndex,
required String languageName,
}) {
final marital = (maritalStatusIndex >= 0 && maritalStatusIndex < canonicalMaritalStatuses.length)
? canonicalMaritalStatuses[maritalStatusIndex]
: 'Non specificato';
final income = (incomeRangeIndex >= 0 && incomeRangeIndex < canonicalIncomeRanges.length)
? canonicalIncomeRanges[incomeRangeIndex]
: 'Non specificato';
final cleanOccupation = occupation.trim().isNotEmpty ? occupation.trim() : 'Non specificata';
return '''
[DATI FINANZIAMENTO]
• Stato civile: $marital
• Professione: $cleanOccupation
• Reddito mensile: $income
(Compilato dal cliente via QR - Lingua: $languageName)''';
}
}
class FinancingLanguage {
final String code;
final String name;
final String flag;
final bool isRtl;
const FinancingLanguage({
required this.code,
required this.name,
required this.flag,
required this.isRtl,
});
}
class FinancingStrings {
final String title;
final String subtitle;
final String maritalStatusLabel;
final List<String> maritalOptions;
final String occupationLabel;
final String occupationHint;
final String incomeLabel;
final List<String> incomeOptions;
final String submitButton;
final String errorRequired;
final String successTitle;
final String successSubtitle;
const FinancingStrings({
required this.title,
required this.subtitle,
required this.maritalStatusLabel,
required this.maritalOptions,
required this.occupationLabel,
required this.occupationHint,
required this.incomeLabel,
required this.incomeOptions,
required this.submitButton,
required this.errorRequired,
required this.successTitle,
required this.successSubtitle,
});
}
@@ -2,12 +2,13 @@ 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 String? type;
final OperationType? type;
final String? providerId;
final String? modelId;
final String? description;
@@ -15,6 +16,7 @@ class OperationDetailModel extends Equatable {
final String companyId;
final String? lastCampaignId;
final String? subType;
final int quantity;
// Aggiunte comode per relazioni
final ProviderModel? provider;
@@ -32,6 +34,7 @@ class OperationDetailModel extends Equatable {
this.companyId = '',
this.lastCampaignId,
this.subType,
this.quantity = 1,
this.provider,
this.model,
});
@@ -49,6 +52,7 @@ class OperationDetailModel extends Equatable {
companyId,
lastCampaignId,
subType,
quantity,
provider,
model,
];
@@ -57,7 +61,7 @@ class OperationDetailModel extends Equatable {
String? id,
DateTime? createdAt,
String? operationId,
String? type,
OperationType? type,
String? providerId,
String? modelId,
String? description,
@@ -65,6 +69,7 @@ class OperationDetailModel extends Equatable {
String? companyId,
String? lastCampaignId,
String? subType,
int? quantity,
ProviderModel? Function()? provider,
ModelModel? Function()? model,
}) => OperationDetailModel(
@@ -79,22 +84,24 @@ class OperationDetailModel extends Equatable {
companyId: companyId ?? this.companyId,
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
subType: subType ?? this.subType,
quantity: quantity ?? this.quantity,
provider: provider != null ? provider() : this.provider,
model: model != null ? model() : this.model,
);
factory OperationDetailModel.empty() {
return OperationDetailModel();
return const OperationDetailModel();
}
factory OperationDetailModel.fromMap(Map<String, dynamic> map) {
final rawQuantity = (map['quantity'] as num?)?.toInt() ?? 1;
return OperationDetailModel(
id: map['id'] as String?,
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'])
: null,
operationId: map['operation_id'] as String? ?? '',
type: map['type'] 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?,
@@ -104,6 +111,7 @@ class OperationDetailModel extends Equatable {
companyId: map['company_id'] as String? ?? '',
lastCampaignId: map['last_campaign_id'] as String?,
subType: map['sub_type'] as String?,
quantity: rawQuantity < 1 ? 1 : rawQuantity,
provider: (map[Tables.providers] != null)
? ProviderModel.fromMap(map[Tables.providers] as Map<String, dynamic>)
: null,
@@ -129,7 +137,7 @@ class OperationDetailModel extends Equatable {
return {
if (id?.isNotEmpty == true) 'id': id,
if (operationId.isNotEmpty) 'operation_id': operationId,
if (type?.isNotEmpty == true) 'type': type,
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,
@@ -139,6 +147,7 @@ class OperationDetailModel extends Equatable {
if (lastCampaignId?.isNotEmpty == true)
'last_campaign_id': lastCampaignId,
if (subType?.isNotEmpty == true) 'sub_type': subType,
'quantity': quantity < 1 ? 1 : quantity,
};
}
}
@@ -0,0 +1,221 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/targets/models/target_model.dart';
/// Parametri per il filtraggio avanzato delle operazioni
class OperationFilterParams extends Equatable {
final String? searchTerm;
final DateTimeRange? dateRange;
final OperationType? detailType;
final String? subType;
final String? categoryKey;
final String? categoryLabel;
final String? staffId;
final String? staffDisplayName;
final String? storeId;
const OperationFilterParams({
this.searchTerm,
this.dateRange,
this.detailType,
this.subType,
this.categoryKey,
this.categoryLabel,
this.staffId,
this.staffDisplayName,
this.storeId,
});
factory OperationFilterParams.empty() => const OperationFilterParams();
bool get isEmpty =>
(searchTerm == null || searchTerm!.trim().isEmpty) &&
dateRange == null &&
detailType == null &&
(subType == null || subType!.trim().isEmpty) &&
categoryKey == null &&
staffId == null &&
storeId == null;
bool get isNotEmpty => !isEmpty;
/// Costruisce i filtri a partire da una categoria di target (es. clic da card obiettivo MNP, Calcio, ecc.)
factory OperationFilterParams.fromTargetCategory({
required String categoryKey,
required String categoryLabel,
required TargetModel target,
String? staffId,
String? staffDisplayName,
}) {
OperationType? detailType;
String? subType;
switch (categoryKey) {
case 'mnp':
detailType = OperationType.mnp;
break;
case 'unica':
detailType = OperationType.unica;
break;
case 'nip':
detailType = OperationType.nip;
break;
case 'al':
detailType = OperationType.al;
break;
case 'telepass':
detailType = OperationType.telepass;
break;
case 'fin':
detailType = OperationType.fin;
break;
case 'upselling':
detailType = OperationType.upselling;
break;
case 'cb':
detailType = OperationType.cb;
break;
case 'ricontatti':
detailType = OperationType.ricontatto;
break;
case 'calcio':
detailType = OperationType.entertainment;
subType = 'calcio';
break;
case 'contenuti':
detailType = OperationType.entertainment;
break;
case 'business':
detailType = OperationType.business;
break;
case 'energiaTim':
case 'energiaAltri':
detailType = OperationType.energy;
break;
}
return OperationFilterParams(
categoryKey: categoryKey,
categoryLabel: categoryLabel,
detailType: detailType,
subType: subType,
dateRange: DateTimeRange(
start: target.startDay,
end: target.endDay,
),
storeId: target.storeId,
staffId: staffId,
staffDisplayName: staffDisplayName,
);
}
/// Estrae i parametri dai queryParameters di GoRouter
factory OperationFilterParams.fromQueryParams(Map<String, String> query) {
if (query.isEmpty) return const OperationFilterParams();
DateTimeRange? range;
final startStr = query['startDate'];
final endStr = query['endDate'];
if (startStr != null && endStr != null) {
try {
final start = DateTime.parse(startStr);
final end = DateTime.parse(endStr);
range = DateTimeRange(start: start, end: end);
} catch (_) {}
}
final typeStr = query['type'] ?? query['detailType'];
final opType = OperationType.fromValue(typeStr);
return OperationFilterParams(
searchTerm: query['search'] ?? query['searchTerm'],
dateRange: range,
detailType: opType,
subType: query['subType'],
categoryKey: query['categoryKey'],
categoryLabel: query['categoryLabel'],
staffId: query['staffId'],
staffDisplayName: query['staffDisplayName'],
storeId: query['storeId'],
);
}
Map<String, String> toQueryParams() {
final map = <String, String>{};
if (searchTerm != null && searchTerm!.isNotEmpty) {
map['search'] = searchTerm!;
}
if (dateRange != null) {
map['startDate'] = dateRange!.start.toIso8601String();
map['endDate'] = dateRange!.end.toIso8601String();
}
if (detailType != null) {
map['type'] = detailType!.value;
}
if (subType != null && subType!.isNotEmpty) {
map['subType'] = subType!;
}
if (categoryKey != null) {
map['categoryKey'] = categoryKey!;
}
if (categoryLabel != null) {
map['categoryLabel'] = categoryLabel!;
}
if (staffId != null) {
map['staffId'] = staffId!;
}
if (staffDisplayName != null) {
map['staffDisplayName'] = staffDisplayName!;
}
if (storeId != null) {
map['storeId'] = storeId!;
}
return map;
}
OperationFilterParams copyWith({
String? searchTerm,
DateTimeRange? dateRange,
OperationType? detailType,
String? subType,
String? categoryKey,
String? categoryLabel,
String? staffId,
String? staffDisplayName,
String? storeId,
bool clearSearch = false,
bool clearRange = false,
bool clearDetailType = false,
bool clearSubType = false,
bool clearCategory = false,
bool clearStaff = false,
bool clearStore = false,
}) {
return OperationFilterParams(
searchTerm: clearSearch ? null : (searchTerm ?? this.searchTerm),
dateRange: clearRange ? null : (dateRange ?? this.dateRange),
detailType: clearDetailType ? null : (detailType ?? this.detailType),
subType: clearSubType ? null : (subType ?? this.subType),
categoryKey: clearCategory ? null : (categoryKey ?? this.categoryKey),
categoryLabel: clearCategory ? null : (categoryLabel ?? this.categoryLabel),
staffId: clearStaff ? null : (staffId ?? this.staffId),
staffDisplayName:
clearStaff ? null : (staffDisplayName ?? this.staffDisplayName),
storeId: clearStore ? null : (storeId ?? this.storeId),
);
}
@override
List<Object?> get props => [
searchTerm,
dateRange,
detailType,
subType,
categoryKey,
categoryLabel,
staffId,
staffDisplayName,
storeId,
];
}
@@ -28,6 +28,7 @@ enum OperationStatus {
class OperationModel extends Equatable {
final String? id;
final DateTime? createdAt;
final DateTime? updatedAt;
final String note;
final bool showInDashboard;
final String companyId;
@@ -50,6 +51,7 @@ class OperationModel extends Equatable {
const OperationModel({
this.id,
this.createdAt,
this.updatedAt,
this.note = '',
this.showInDashboard = true,
required this.companyId,
@@ -69,6 +71,7 @@ class OperationModel extends Equatable {
OperationModel copyWith({
String? id,
DateTime? createdAt,
DateTime? updatedAt,
String? note,
bool? showInDashboard,
String? companyId,
@@ -86,6 +89,7 @@ class OperationModel extends Equatable {
}) => OperationModel(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
note: note ?? this.note,
showInDashboard: showInDashboard ?? this.showInDashboard,
companyId: companyId ?? this.companyId,
@@ -106,6 +110,7 @@ class OperationModel extends Equatable {
List<Object?> get props => [
id,
createdAt,
updatedAt,
note,
showInDashboard,
companyId,
@@ -126,6 +131,8 @@ class OperationModel extends Equatable {
return OperationModel(
id: null,
createdAt: null,
updatedAt: null,
showInDashboard: false,
companyId: '',
details: const [],
);
@@ -135,7 +142,10 @@ class OperationModel extends Equatable {
return OperationModel(
id: map['id'] as String?,
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'])
? DateTime.parse(map['created_at'] as String).toLocal()
: null,
updatedAt: map['updated_at'] != null
? DateTime.parse(map['updated_at'] as String).toLocal()
: null,
note: map['note'] as String? ?? '',
showInDashboard: map['show_in_dashboard'] as bool? ?? true,
@@ -0,0 +1,163 @@
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,
),
ricontatto(
value: 'Ricontatto',
label: 'Ricontatto / Scadenza',
shortLabel: 'Ricontatto',
icon: Icons.event_repeat_outlined,
color: Colors.amber,
),
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,
});
/// Indica se il dettaglio supporta una quantità/valore personalizzabile (es. pacchetti multi-canale o Unica)
bool get supportsQuantity =>
this == OperationType.entertainment || this == OperationType.unica;
/// Ricostruisce l'enum dal valore stringa salvato su DB in modo case-insensitive
static OperationType? fromValue(String? val) {
if (val == null || val.trim().isEmpty) return null;
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];
}
/// Sottotipi standard per Ricontatti / Bollette in scadenza
class RicontattoSubtypes {
static const String luce = 'Luce';
static const String gas = 'Gas';
static const String dual = 'Luce e Gas';
static const String telefonia = 'Telefonia';
static const String altro = 'Altro';
static const List<String> all = [luce, gas, dual, telefonia, altro];
}
@@ -0,0 +1,592 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/features/operations/models/financing_translations.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class FinancingFormScreen extends StatefulWidget {
final String sessionId;
const FinancingFormScreen({
super.key,
required this.sessionId,
});
@override
State<FinancingFormScreen> createState() => _FinancingFormScreenState();
}
class _FinancingFormScreenState extends State<FinancingFormScreen> {
FinancingLanguage _currentLang = FinancingTranslations.supportedLanguages.first; // Default Italiano
final _occupationController = TextEditingController();
final _formKey = GlobalKey<FormState>();
int? _selectedMaritalIndex;
int? _selectedIncomeIndex;
bool _isSubmitting = false;
bool _isSuccess = false;
String? _errorMessage;
RealtimeChannel? _channel;
StreamSubscription? _ackSubscription;
@override
void initState() {
super.initState();
_initRealtimeChannel();
}
void _initRealtimeChannel() {
if (widget.sessionId.isEmpty) return;
try {
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
_channel?.onBroadcast(
event: 'ack',
callback: (payload) {
if (mounted && _isSubmitting) {
setState(() {
_isSubmitting = false;
_isSuccess = true;
});
}
},
).subscribe();
} catch (e) {
debugPrint('Errore init channel financing: $e');
}
}
@override
void dispose() {
_ackSubscription?.cancel();
if (_channel != null) {
Supabase.instance.client.removeChannel(_channel!);
}
_occupationController.dispose();
super.dispose();
}
Future<void> _submit() async {
final strings = FinancingTranslations.getStrings(_currentLang.code);
if (_selectedMaritalIndex == null ||
_selectedIncomeIndex == null ||
_occupationController.text.trim().isEmpty) {
setState(() {
_errorMessage = strings.errorRequired;
});
return;
}
setState(() {
_errorMessage = null;
_isSubmitting = true;
});
final formattedText = FinancingTranslations.formatNoteText(
maritalStatusIndex: _selectedMaritalIndex!,
occupation: _occupationController.text.trim(),
incomeRangeIndex: _selectedIncomeIndex!,
languageName: _currentLang.name,
);
try {
if (_channel == null) {
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
_channel?.subscribe();
}
await _channel?.sendBroadcastMessage(
event: 'submit',
payload: {
'maritalStatusIndex': _selectedMaritalIndex,
'occupation': _occupationController.text.trim(),
'incomeRangeIndex': _selectedIncomeIndex,
'languageCode': _currentLang.code,
'languageName': _currentLang.name,
'formattedText': formattedText,
},
);
// Timeout di sicurezza: se entro 3 secondi non riceviamo ack specifico,
// consideriamo comunque la trasmissione completata con successo
Future.delayed(const Duration(seconds: 2), () {
if (mounted && _isSubmitting) {
setState(() {
_isSubmitting = false;
_isSuccess = true;
});
}
});
} catch (e) {
if (mounted) {
setState(() {
_isSubmitting = false;
_errorMessage = 'Errore di connessione: $e';
});
}
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final strings = FinancingTranslations.getStrings(_currentLang.code);
return Directionality(
textDirection: _currentLang.isRtl ? TextDirection.rtl : TextDirection.ltr,
child: Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
centerTitle: true,
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
Icons.account_balance_wallet_outlined,
color: theme.colorScheme.primary,
size: 22,
),
),
const SizedBox(width: 10),
Flexible(
child: Text(
strings.title,
style: const TextStyle(
color: Color(0xFF1E293B),
fontWeight: FontWeight.bold,
fontSize: 18,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
body: SafeArea(
child: _isSuccess
? _buildSuccessView(strings, theme)
: _buildFormView(strings, theme),
),
),
);
}
Widget _buildSuccessView(FinancingStrings strings, ThemeData theme) {
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 90,
height: 90,
decoration: BoxDecoration(
color: Colors.green.shade50,
shape: BoxShape.circle,
border: Border.all(color: Colors.green.shade200, width: 2),
),
child: Icon(
Icons.check_circle_rounded,
color: Colors.green.shade600,
size: 56,
),
),
const SizedBox(height: 24),
Text(
strings.successTitle,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Color(0xFF0F172A),
),
),
const SizedBox(height: 12),
Text(
strings.successSubtitle,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
color: Colors.grey.shade700,
height: 1.4,
),
),
const SizedBox(height: 36),
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.blue.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.blue.shade100),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.info_outline, color: Colors.blue.shade700, size: 20),
const SizedBox(width: 8),
Flexible(
child: Text(
'Sessione completata',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: Colors.blue.shade900,
),
),
),
],
),
),
],
),
),
);
}
Widget _buildFormView(FinancingStrings strings, ThemeData theme) {
return SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 540),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// SELETTORE LINGUA
_buildLanguageSelector(),
const SizedBox(height: 16),
// DESCRIZIONE
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFE2E8F0)),
),
child: Row(
children: [
Icon(
Icons.privacy_tip_outlined,
color: theme.colorScheme.primary,
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
strings.subtitle,
style: const TextStyle(
fontSize: 13,
color: Color(0xFF475569),
height: 1.35,
),
),
),
],
),
),
const SizedBox(height: 20),
// 1. STATO CIVILE
_buildSectionHeader(
icon: Icons.favorite_border,
title: strings.maritalStatusLabel,
theme: theme,
),
const SizedBox(height: 10),
_buildChoiceList(
options: strings.maritalOptions,
selectedIndex: _selectedMaritalIndex,
onSelected: (idx) {
setState(() => _selectedMaritalIndex = idx);
},
),
const SizedBox(height: 24),
// 2. PROFESSIONE
_buildSectionHeader(
icon: Icons.work_outline,
title: strings.occupationLabel,
theme: theme,
),
const SizedBox(height: 10),
TextFormField(
controller: _occupationController,
textInputAction: TextInputAction.done,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
decoration: InputDecoration(
hintText: strings.occupationHint,
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide(
color: theme.colorScheme.primary,
width: 2,
),
),
),
onChanged: (_) {
if (_errorMessage != null) {
setState(() => _errorMessage = null);
}
},
),
const SizedBox(height: 24),
// 3. REDDITO MENSILE
_buildSectionHeader(
icon: Icons.euro_symbol_outlined,
title: strings.incomeLabel,
theme: theme,
),
const SizedBox(height: 10),
_buildChoiceList(
options: strings.incomeOptions,
selectedIndex: _selectedIncomeIndex,
onSelected: (idx) {
setState(() => _selectedIncomeIndex = idx);
},
),
const SizedBox(height: 24),
// MESSAGGIO DI ERRORE
if (_errorMessage != null) ...[
Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: Colors.red.shade50,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.red.shade200),
),
child: Row(
children: [
Icon(Icons.error_outline, color: Colors.red.shade700, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
_errorMessage!,
style: TextStyle(
color: Colors.red.shade800,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
const SizedBox(height: 16),
],
// PULSANTE INVIO
SizedBox(
height: 54,
child: FilledButton.icon(
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
elevation: 1,
),
onPressed: _isSubmitting ? null : _submit,
icon: _isSubmitting
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Icon(Icons.send_rounded, size: 20),
label: Text(
_isSubmitting ? '...' : strings.submitButton,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 32),
],
),
),
),
),
);
}
Widget _buildLanguageSelector() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(left: 4.0, bottom: 8.0),
child: Text(
'Seleziona lingua / Choose language:',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF64748B),
),
),
),
SizedBox(
height: 42,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: FinancingTranslations.supportedLanguages.length,
separatorBuilder: (_, _) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final lang = FinancingTranslations.supportedLanguages[index];
final isSelected = lang.code == _currentLang.code;
return ChoiceChip(
showCheckmark: false,
labelPadding: const EdgeInsets.symmetric(horizontal: 4),
avatar: Text(lang.flag, style: const TextStyle(fontSize: 16)),
label: Text(
lang.name,
style: TextStyle(
fontSize: 13,
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
color: isSelected ? Colors.white : const Color(0xFF1E293B),
),
),
selected: isSelected,
selectedColor: Theme.of(context).colorScheme.primary,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isSelected
? Theme.of(context).colorScheme.primary
: const Color(0xFFCBD5E1),
),
),
onSelected: (selected) {
if (selected) {
setState(() {
_currentLang = lang;
_errorMessage = null;
});
}
},
);
},
),
),
],
);
}
Widget _buildSectionHeader({
required IconData icon,
required String title,
required ThemeData theme,
}) {
return Row(
children: [
Icon(icon, size: 20, color: theme.colorScheme.primary),
const SizedBox(width: 8),
Text(
title,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFF1E293B),
),
),
],
);
}
Widget _buildChoiceList({
required List<String> options,
required int? selectedIndex,
required ValueChanged<int> onSelected,
}) {
return Column(
children: List.generate(options.length, (index) {
final label = options[index];
final isSelected = selectedIndex == index;
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => onSelected(index),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.primary.withValues(alpha: 0.08)
: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isSelected
? Theme.of(context).colorScheme.primary
: const Color(0xFFCBD5E1),
width: isSelected ? 2 : 1,
),
),
child: Row(
children: [
Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_off,
color: isSelected
? Theme.of(context).colorScheme.primary
: const Color(0xFF94A3B8),
size: 20,
),
const SizedBox(width: 12),
Expanded(
child: Text(
label,
style: TextStyle(
fontSize: 15,
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
color: isSelected
? Theme.of(context).colorScheme.primary
: const Color(0xFF1E293B),
),
),
),
],
),
),
),
);
}),
);
}
}
@@ -6,7 +6,9 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/ui/widgets/financing_qr_dialog.dart';
import 'package:flux/features/operations/ui/widgets/operation_details_section.dart';
import 'package:intl/intl.dart';
class OperationFormScreen extends StatefulWidget {
final String? operationId;
@@ -20,7 +22,8 @@ class OperationFormScreen extends StatefulWidget {
enum _UnsavedChangesAction { cancel, saveAndClose, discard }
class _OperationFormScreenState extends State<OperationFormScreen> {
class _OperationFormScreenState extends State<OperationFormScreen>
with WidgetsBindingObserver {
final _formKey = GlobalKey<FormState>();
bool _isInitialized = false;
@@ -32,6 +35,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_referenceController.addListener(_onFieldChanged);
_notesController.addListener(_onFieldChanged);
@@ -50,6 +54,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_referenceController.removeListener(_onFieldChanged);
_notesController.removeListener(_onFieldChanged);
_referenceController.dispose();
@@ -57,6 +62,19 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused ||
state == AppLifecycleState.hidden ||
state == AppLifecycleState.detached) {
if (_isInitialized && mounted) {
_flushControllersToCubit();
context.read<OperationFormCubit>().flushAutoSave();
}
}
}
void _onFieldChanged() {
if (!_isInitialized) return;
_flushControllersToCubit();
@@ -83,9 +101,17 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
void _saveOperation({
required OperationStatus targetStatus,
required bool isClosingIntent,
}) {
}) async {
if (!_formKey.currentState!.validate()) return;
if (isClosingIntent) {
final details = context.read<OperationFormCubit>().state.operation.details;
if (details.isEmpty) {
final shouldProceed = await _showEmptyDetailsWarningDialog(context);
if (shouldProceed != true || !mounted) return;
}
}
_isClosingIntent = isClosingIntent;
_flushControllersToCubit();
@@ -95,6 +121,36 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
);
}
Future<bool?> _showEmptyDetailsWarningDialog(BuildContext context) {
return showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: Colors.orange),
SizedBox(width: 8),
Text('Dettagli operazione vuoti'),
],
),
content: const Text(
'Non hai inserito alcun dettaglio per questa operazione.\n\nVuoi procedere comunque a salvare e uscire, oppure annullare per aggiungerli?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Annulla'),
),
ElevatedButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Salva e chiudi comunque'),
),
],
);
},
);
}
Future<_UnsavedChangesAction?> _showUnsavedChangesDialog(
BuildContext context,
) {
@@ -152,6 +208,116 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
}
}
Widget _buildAutoSaveIndicator(OperationFormState formState) {
if (formState.isAutoSaving) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Salvataggio automatico in corso...',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(width: 6),
Text(
'Salvataggio...',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
fontStyle: FontStyle.italic,
),
),
],
),
),
);
}
if (formState.autoSaveError != null) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Errore salvataggio: ${formState.autoSaveError}',
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.cloud_off, size: 16, color: Colors.red),
SizedBox(width: 4),
Text(
'Errore salvataggio',
style: TextStyle(fontSize: 12, color: Colors.red),
),
],
),
),
);
}
if (formState.hasUnsavedChanges) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message: 'Modifiche non salvate (salvataggio a breve...)',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Text(
'In modifica...',
style: TextStyle(
fontSize: 12,
color: Colors.orange.shade800,
),
),
],
),
),
);
}
if (formState.lastSavedAt != null) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Tooltip(
message:
'Ultimo salvataggio alle ${DateFormat('HH:mm:ss').format(formState.lastSavedAt!)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.cloud_done_rounded, size: 16, color: Colors.green),
const SizedBox(width: 4),
Text(
'Salvato ${DateFormat('HH:mm').format(formState.lastSavedAt!)}',
style: TextStyle(
fontSize: 12,
color: Colors.green.shade700,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
}
return const SizedBox.shrink();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -171,6 +337,15 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
!_isInitialized) {
_syncTextControllers(formState.operation);
}
if (formState.operation.id != null &&
formState.operation.id!.isNotEmpty) {
final attachmentsBloc = formContext.read<AttachmentsBloc>();
if (attachmentsBloc.state.parentId != formState.operation.id) {
attachmentsBloc.add(
ParentEntitySavedEvent(formState.operation.id!),
);
}
}
if ((formState.status == OperationFormStatus.success &&
_isClosingIntent) ||
formState.status == OperationFormStatus.discarded) {
@@ -226,21 +401,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
overflow: TextOverflow.ellipsis,
),
actions: [
if (formState.hasUnsavedChanges)
Padding(
padding: const EdgeInsets.only(right: 4.0),
child: Tooltip(
message: 'Modifiche non salvate',
child: Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
),
),
_buildAutoSaveIndicator(formState),
IconButton(
icon: const Icon(Icons.save),
tooltip: formState.hasUnsavedChanges
@@ -248,18 +409,20 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
: 'Nessuna modifica da salvare',
onPressed:
formState.hasUnsavedChanges &&
formState.status != OperationFormStatus.saving
? () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: false,
)
: null,
formState.status != OperationFormStatus.saving &&
!formState.isAutoSaving
? () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: false,
)
: null,
),
IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
tooltip: 'Elimina pratica',
onPressed:
formState.status != OperationFormStatus.saving
formState.status != OperationFormStatus.saving &&
!formState.isAutoSaving
? () => _showDeleteConfirmationDialog(formContext)
: null,
),
@@ -494,13 +657,71 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
);
}
Widget _buildTimestampsBar(OperationFormState state) {
final createdAt = state.operation.createdAt;
final updatedAt =
state.lastSavedAt ?? state.operation.updatedAt ?? createdAt;
if (createdAt == null && updatedAt == null) {
return const SizedBox.shrink();
}
final dateTimeFormat = DateFormat('dd/MM/yyyy HH:mm');
final fullFormat = DateFormat('dd/MM/yyyy HH:mm:ss');
final mutedColor = Theme.of(
context,
).colorScheme.onSurfaceVariant.withValues(alpha: 0.8);
return Padding(
padding: const EdgeInsets.only(left: 4, right: 4, bottom: 12),
child: Wrap(
spacing: 20,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (createdAt != null)
Tooltip(
message: 'Creata il ${fullFormat.format(createdAt)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.schedule_rounded, size: 14, color: mutedColor),
const SizedBox(width: 5),
Text(
'Creata: ${dateTimeFormat.format(createdAt)}',
style: TextStyle(fontSize: 12, color: mutedColor),
),
],
),
),
if (updatedAt != null)
Tooltip(
message: 'Ultima modifica il ${fullFormat.format(updatedAt)}',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.history_rounded, size: 15, color: mutedColor),
const SizedBox(width: 5),
Text(
'Ultima modifica: ${dateTimeFormat.format(updatedAt)}',
style: TextStyle(fontSize: 12, color: mutedColor),
),
],
),
),
],
),
);
}
Widget _buildResponsiveLayout(
bool isUltraWide,
bool isDesktop,
OperationFormState state,
) {
final Widget cardsLayout;
if (isUltraWide) {
return Column(
cardsLayout = Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -516,7 +737,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
} else if (isDesktop) {
return Row(
cardsLayout = Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
@@ -531,7 +752,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
} else {
return Column(
cardsLayout = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_cardAnagrafica(state),
@@ -541,6 +762,14 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildTimestampsBar(state),
cardsLayout,
],
);
}
// --- LE CARD MODULARIZZATE E COLORATE ---
@@ -582,6 +811,19 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
title: 'Note Interne',
icon: Icons.notes,
themeColor: Colors.teal,
headerTrailing: OutlinedButton.icon(
icon: const Icon(Icons.qr_code_2, size: 18),
label: const Text('Dati Finanziamento'),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.teal,
side: const BorderSide(color: Colors.teal),
visualDensity: VisualDensity.compact,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
onPressed: _showFinancingQrDialog,
),
children: [
TextFormField(
controller: _notesController,
@@ -602,6 +844,32 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
);
}
void _showFinancingQrDialog() {
showDialog(
context: context,
builder: (dialogCtx) => FinancingQrDialog(
onDataReceived: (formattedData) {
setState(() {
final existing = _notesController.text.trim();
if (existing.isEmpty) {
_notesController.text = formattedData;
} else {
_notesController.text = '$existing\n\n$formattedData';
}
});
_flushControllersToCubit();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Dati finanziamento inseriti nelle note!'),
backgroundColor: Colors.teal,
duration: Duration(seconds: 3),
),
);
},
),
);
}
Widget _cardAllegati(OperationFormState state) {
return _buildCard(
title: 'Allegati e Documenti',
@@ -612,6 +880,15 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
parentType: AttachmentParentType.operation,
parentId: state.operation.id,
titleForUpload: state.operation.customer?.name ?? 'Nuova Pratica',
onEnsureEntitySaved: () async {
if (!_formKey.currentState!.validate()) return null;
_flushControllersToCubit();
final cubit = context.read<OperationFormCubit>();
await cubit.saveOperation(
targetStatus: state.operation.status,
);
return cubit.state.operation.id;
},
),
],
);
@@ -623,6 +900,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
required IconData icon,
required Color themeColor,
required List<Widget> children,
Widget? headerTrailing,
}) {
return Card(
margin: const EdgeInsets.only(bottom: 24),
@@ -647,13 +925,16 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
child: Icon(icon, color: themeColor),
),
const SizedBox(width: 12),
Text(
title,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
color: themeColor,
Expanded(
child: Text(
title,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
color: themeColor,
),
),
),
?headerTrailing,
],
),
const Divider(height: 32),
@@ -6,11 +6,16 @@ import 'package:flux/core/widgets/staff_selector_modal.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/operation_type.dart';
import 'package:flux/features/operations/ui/widgets/operation_filter_sheet.dart';
import 'package:go_router/go_router.dart';
class OperationListScreen extends StatefulWidget {
const OperationListScreen({super.key});
final OperationFilterParams? initialFilters;
const OperationListScreen({super.key, this.initialFilters});
@override
State<OperationListScreen> createState() => _OperationListScreenState();
@@ -33,18 +38,43 @@ class _OperationListScreenState extends State<OperationListScreen> {
super.initState();
_scrollController.addListener(_onScroll);
// Primo caricamento: partiamo da pagina 1
// (Il Cubit deciderà se fare il boot iniziale o se c'era già roba in cache)
// Primo caricamento: partiamo da pagina 1 o applichiamo filtri iniziali
WidgetsBinding.instance.addPostFrameCallback((_) {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
if (isDesktop) {
context.read<OperationListCubit>().loadSpecificPageDesktop(1);
final cubit = context.read<OperationListCubit>();
if (widget.initialFilters != null && widget.initialFilters!.isNotEmpty) {
if (widget.initialFilters!.searchTerm != null &&
widget.initialFilters!.searchTerm!.isNotEmpty) {
_searchController.text = widget.initialFilters!.searchTerm!;
_showSearchBar = true;
}
cubit.applyFilterParams(widget.initialFilters!);
} else {
context.read<OperationListCubit>().loadNextPageMobile(refresh: true);
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
if (isDesktop) {
cubit.loadSpecificPageDesktop(1);
} else {
cubit.loadNextPageMobile(refresh: true);
}
}
});
}
@override
void didUpdateWidget(covariant OperationListScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialFilters != oldWidget.initialFilters &&
widget.initialFilters != null) {
if (widget.initialFilters!.searchTerm != null &&
widget.initialFilters!.searchTerm!.isNotEmpty) {
_searchController.text = widget.initialFilters!.searchTerm!;
_showSearchBar = true;
}
context
.read<OperationListCubit>()
.applyFilterParams(widget.initialFilters!);
}
}
void _onScroll() {
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
// 🥷 COMPORTAMENTO IBRIDO: Lo scroll infinito si attiva SOLO su mobile
@@ -137,120 +167,72 @@ class _OperationListScreenState extends State<OperationListScreen> {
actions: [
IconButton(
icon: Icon(_showSearchBar ? Icons.close : Icons.search),
tooltip: _showSearchBar ? 'Chiudi ricerca' : 'Cerca',
onPressed: () {
setState(() {
_showSearchBar = !_showSearchBar;
if (!_showSearchBar) {
_debounce?.cancel();
_searchController.clear();
context.read<OperationListCubit>().clearFilters();
context.read<OperationListCubit>().updateFilters(
clearText: true,
);
}
});
},
),
if (!isDesktop) // Il pull-to-refresh c'è già su mobile, su desktop mettiamo un tasto manuale
IconButton(
icon: const Icon(Icons.filter_list),
onPressed: () {
// TODO: Bottone Filtri Avanzati (es. DateRange Picker)
},
),
BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
return IconButton(
icon: state.hasActiveFilters
? Badge(
label: Text('${state.activeFiltersCount}'),
child: const Icon(Icons.filter_list),
)
: const Icon(Icons.filter_list),
tooltip: 'Filtri avanzati',
onPressed: () => _openFilterModal(context, state),
);
},
),
BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
if (!state.hasActiveFilters) {
return const SizedBox.shrink();
}
return IconButton(
icon: const Icon(Icons.filter_alt_off),
tooltip: 'Azzera filtri',
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
);
},
),
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Ricarica',
onPressed: () {
context.read<OperationListCubit>().refreshCurrentPage();
},
),
],
),
// --- CORPO RESPONSIVO ---
body: BlocBuilder<OperationListCubit, OperationListState>(
builder: (context, state) {
if (state.status == OperationListStatus.loading &&
state.operations.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
return Column(
children: [
// Barra orizzontale filtri attivi (se presenti)
_buildActiveFiltersBar(context, state),
if (state.operations.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Nessuna pratica trovata."),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () => isDesktop
? context
.read<OperationListCubit>()
.loadSpecificPageDesktop(1)
: context.read<OperationListCubit>().loadNextPageMobile(
refresh: true,
),
child: const Text("Ricarica"),
),
],
Expanded(
child: _buildBodyContent(context, state, isDesktop),
),
);
}
// 🥷 SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
if (isDesktop) {
return Column(
children: [
Expanded(
child: GridView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
420, // Larghezza bilanciata per le card su desktop
mainAxisExtent:
185, // Altezza controllata per evitare buchi bianchi
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: state.operations.length,
itemBuilder: (context, index) {
final operation = state.operations[index];
return _buildResponsiveCard(operation);
},
),
),
_buildDesktopPaginationFooter(
state,
), // La barra in fondo stile Gmail
],
);
}
// 🥷 SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
return RefreshIndicator(
onRefresh: () => context
.read<OperationListCubit>()
.loadNextPageMobile(refresh: true),
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.only(
bottom: 80,
left: 8,
right: 8,
top: 8,
),
itemCount: state.hasReachedMax
? state.operations.length
: state.operations.length + 1,
itemBuilder: (context, index) {
if (index >= state.operations.length) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
final operation = state.operations[index];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: _buildResponsiveCard(operation),
);
},
),
],
);
},
),
@@ -272,6 +254,289 @@ class _OperationListScreenState extends State<OperationListScreen> {
);
}
void _openFilterModal(BuildContext context, OperationListState state) {
OperationFilterSheet.show(
context,
currentFilters: state.toFilterParams(),
onApply: (newParams) {
context.read<OperationListCubit>().applyFilterParams(newParams);
},
onReset: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
);
}
Widget _buildActiveFiltersBar(
BuildContext context,
OperationListState state,
) {
if (!state.hasActiveFilters) return const SizedBox.shrink();
final theme = Theme.of(context);
final cubit = context.read<OperationListCubit>();
return Container(
width: double.infinity,
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.25),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: ActionChip(
visualDensity: VisualDensity.compact,
avatar: const Icon(
Icons.filter_alt_off,
size: 14,
color: Colors.redAccent,
),
label: const Text(
'Azzera tutto',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Colors.redAccent,
),
),
backgroundColor: Colors.redAccent.withValues(alpha: 0.08),
side: BorderSide(
color: Colors.redAccent.withValues(alpha: 0.3),
),
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
cubit.clearFilters();
},
),
),
if (state.categoryLabel != null || state.detailType != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: Icon(
state.detailType?.icon ?? Icons.category,
size: 14,
color: state.detailType?.color ?? theme.colorScheme.primary,
),
label: Text(
state.categoryLabel != null
? 'Obiettivo: ${state.categoryLabel}'
: (state.subType != null && state.subType!.isNotEmpty
? '${state.detailType!.shortLabel} (${state.subType})'
: state.detailType!.shortLabel),
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(
clearDetailType: true,
clearSubType: true,
clearCategory: true,
),
),
),
],
if (state.staffDisplayName != null || state.staffId != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.person, size: 14),
label: Text(
'Addetto: ${state.staffDisplayName ?? 'Selezionato'}',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(clearStaff: true),
),
),
],
if (state.dateRange != null) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.date_range, size: 14),
label: Text(
'${_formatDate(state.dateRange!.start)} - ${_formatDate(state.dateRange!.end)}',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () => cubit.updateFilters(clearRange: true),
),
),
],
if (state.searchTerm != null &&
state.searchTerm!.trim().isNotEmpty) ...[
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Chip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.search, size: 14),
label: Text(
'"${state.searchTerm}"',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
deleteIcon: const Icon(Icons.close, size: 14),
onDeleted: () {
_searchController.clear();
cubit.updateFilters(clearText: true);
},
),
),
],
],
),
),
);
}
Widget _buildBodyContent(
BuildContext context,
OperationListState state,
bool isDesktop,
) {
if (state.status == OperationListStatus.loading &&
state.operations.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.operations.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
state.hasActiveFilters
? Icons.filter_list_off
: Icons.inbox_outlined,
size: 48,
color: Colors.grey.shade400,
),
const SizedBox(height: 12),
Text(
state.hasActiveFilters
? 'Nessuna operazione trovata con i filtri attuali.'
: 'Nessuna pratica trovata.',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
if (state.hasActiveFilters)
ElevatedButton.icon(
icon: const Icon(Icons.filter_alt_off, size: 18),
label: const Text('Azzera filtri'),
onPressed: () {
_searchController.clear();
setState(() => _showSearchBar = false);
context.read<OperationListCubit>().clearFilters();
},
)
else
ElevatedButton(
onPressed: () => isDesktop
? context
.read<OperationListCubit>()
.loadSpecificPageDesktop(1)
: context.read<OperationListCubit>().loadNextPageMobile(
refresh: true,
),
child: const Text('Ricarica'),
),
],
),
),
);
}
// SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
if (isDesktop) {
return Column(
children: [
Expanded(
child: GridView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 420,
mainAxisExtent: 185,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: state.operations.length,
itemBuilder: (context, index) {
final operation = state.operations[index];
return _buildResponsiveCard(operation);
},
),
),
_buildDesktopPaginationFooter(state),
],
);
}
// SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
return RefreshIndicator(
onRefresh: () => context
.read<OperationListCubit>()
.loadNextPageMobile(refresh: true),
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.only(
bottom: 80,
left: 8,
right: 8,
top: 8,
),
itemCount: state.hasReachedMax
? state.operations.length
: state.operations.length + 1,
itemBuilder: (context, index) {
if (index >= state.operations.length) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
final operation = state.operations[index];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: _buildResponsiveCard(operation),
);
},
),
);
}
String _formatDate(DateTime dt) {
return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
}
// --- COSTRUZIONE DELLA COMPONENTISTICA DETTAGLIATA ---
Widget _buildResponsiveCard(OperationModel operation) {
@@ -406,33 +671,19 @@ class _RichOperationCard extends StatelessWidget {
}
}
Color _getTypeColor(String? type) {
switch (type?.toUpperCase()) {
case 'FIN':
return Colors.deepPurple;
case 'TELEPASS':
return Colors.yellow.shade700;
case 'ENERGY':
return Colors.amber.shade700;
case 'ENTERTAINMENT':
return Colors.pinkAccent;
case 'AL':
case 'MNP':
return Colors.indigo;
case 'NIP':
case 'FWA':
return Colors.cyan;
default:
return Colors.blueGrey;
}
Color _getTypeColor(OperationType? type) {
return type?.color ?? Colors.blueGrey;
}
IconData? _getIconForType(String? type, String? subtype) {
if (type?.toLowerCase() == 'energy') {
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;
}
return null;
if (type == OperationType.entertainment) {
if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer;
}
return type?.icon;
}
Widget _buildDetailItem(BuildContext context, OperationDetailModel detail) {
@@ -440,9 +691,11 @@ class _RichOperationCard extends StatelessWidget {
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
final icon = _getIconForType(detail.type, detail.subType);
final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty)
? '${detail.type ?? ''} (${detail.subType})'
: (detail.type ?? 'Dettaglio');
final baseLabel = (detail.subType != null && detail.subType!.isNotEmpty)
? '${detail.type?.shortLabel ?? ''} (${detail.subType})'
: (detail.type?.shortLabel ?? 'Dettaglio');
final typeLabel =
detail.quantity > 1 ? '$baseLabel ×${detail.quantity}' : baseLabel;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
@@ -0,0 +1,345 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flux/features/operations/models/financing_translations.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:uuid/uuid.dart';
class FinancingQrDialog extends StatefulWidget {
final ValueChanged<String> onDataReceived;
const FinancingQrDialog({
super.key,
required this.onDataReceived,
});
@override
State<FinancingQrDialog> createState() => _FinancingQrDialogState();
}
class _FinancingQrDialogState extends State<FinancingQrDialog> {
late final String _sessionId;
late final String _deepLinkUrl;
RealtimeChannel? _channel;
bool _isReceived = false;
Map<String, dynamic>? _receivedPayload;
bool _copied = false;
@override
void initState() {
super.initState();
_sessionId = const Uuid().v4();
_deepLinkUrl = 'https://flux.catelli.it/financing/$_sessionId';
_setupRealtimeChannel();
}
void _setupRealtimeChannel() {
try {
_channel = Supabase.instance.client.channel('financing_$_sessionId');
_channel?.onBroadcast(
event: 'submit',
callback: (payload) {
if (!mounted) return;
// Invia risposta di conferma (ACK) allo smartphone del cliente
_channel?.sendBroadcastMessage(
event: 'ack',
payload: {'status': 'ok'},
);
final maritalIndex = payload['maritalStatusIndex'] as int? ?? 0;
final occupation = payload['occupation'] as String? ?? '';
final incomeIndex = payload['incomeRangeIndex'] as int? ?? 0;
final languageName = payload['languageName'] as String? ?? 'Italiano';
final formattedText = payload['formattedText'] as String? ??
FinancingTranslations.formatNoteText(
maritalStatusIndex: maritalIndex,
occupation: occupation,
incomeRangeIndex: incomeIndex,
languageName: languageName,
);
widget.onDataReceived(formattedText);
setState(() {
_isReceived = true;
_receivedPayload = {
'marital': (maritalIndex >= 0 &&
maritalIndex <
FinancingTranslations.canonicalMaritalStatuses.length)
? FinancingTranslations.canonicalMaritalStatuses[maritalIndex]
: 'N/D',
'occupation': occupation,
'income': (incomeIndex >= 0 &&
incomeIndex <
FinancingTranslations.canonicalIncomeRanges.length)
? FinancingTranslations.canonicalIncomeRanges[incomeIndex]
: 'N/D',
'language': languageName,
};
});
},
).subscribe();
} catch (e) {
debugPrint('Errore setup realtime channel: $e');
}
}
@override
void dispose() {
if (_channel != null) {
Supabase.instance.client.removeChannel(_channel!);
}
super.dispose();
}
void _copyToClipboard() {
Clipboard.setData(ClipboardData(text: _deepLinkUrl));
setState(() => _copied = true);
Future.delayed(const Duration(seconds: 2), () {
if (mounted) setState(() => _copied = false);
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
backgroundColor: theme.colorScheme.surface,
title: Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.teal.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10),
),
child: const Icon(Icons.qr_code_2, color: Colors.teal, size: 28),
),
const SizedBox(width: 12),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Dati Finanziamento',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
),
Text(
'Raccolta via smartphone cliente',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
),
],
),
content: SizedBox(
width: 380,
child: SingleChildScrollView(
child: _isReceived
? _buildReceivedContent(theme)
: _buildQrContent(theme),
),
),
actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
actions: [
if (!_isReceived) ...[
OutlinedButton.icon(
onPressed: _copyToClipboard,
icon: Icon(_copied ? Icons.check : Icons.copy, size: 16),
label: Text(_copied ? 'Link Copiato!' : 'Copia Link'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Annulla'),
),
] else ...[
FilledButton.icon(
style: FilledButton.styleFrom(backgroundColor: Colors.teal),
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.check, size: 18),
label: const Text('Chiudi (Dati inseriti nelle note)'),
),
],
],
);
}
Widget _buildQrContent(ThemeData theme) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Fai inquadrare questo codice al cliente con la fotocamera del suo telefono.',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: Colors.grey),
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: Colors.amber.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.amber.shade200),
),
child: Text(
'🌐 Il cliente potrà scegliere la lingua (IT, EN, FR, ES, AR, UK, RU, MK, SQ)',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Colors.amber.shade900,
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.grey.shade200),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.04),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: QrImageView(
data: _deepLinkUrl,
version: QrVersions.auto,
size: 210.0,
embeddedImage: const AssetImage('assets/images/logo.png'),
embeddedImageStyle: const QrEmbeddedImageStyle(
size: Size(40, 40),
),
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.teal),
),
const SizedBox(width: 10),
Text(
'In attesa che il cliente compili i dati...',
style: TextStyle(
fontSize: 13,
fontStyle: FontStyle.italic,
color: Colors.grey.shade700,
),
),
],
),
],
);
}
Widget _buildReceivedContent(ThemeData theme) {
final marital = _receivedPayload?['marital'] ?? '';
final occupation = _receivedPayload?['occupation'] ?? '';
final income = _receivedPayload?['income'] ?? '';
final lang = _receivedPayload?['language'] ?? '';
return Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: Colors.teal.shade50,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.teal.shade200),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.check_circle, color: Colors.teal, size: 28),
const SizedBox(width: 10),
Expanded(
child: Text(
'Dati ricevuti con successo! 🎉',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.teal.shade900,
),
),
),
],
),
const SizedBox(height: 14),
const Divider(height: 1),
const SizedBox(height: 12),
_buildInfoRow('Stato civile', marital),
const SizedBox(height: 8),
_buildInfoRow('Professione', occupation),
const SizedBox(height: 8),
_buildInfoRow('Reddito mensile', income),
const SizedBox(height: 8),
_buildInfoRow('Lingua cliente', lang),
const SizedBox(height: 14),
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(Icons.notes, size: 18, color: Colors.teal.shade700),
const SizedBox(width: 8),
const Expanded(
child: Text(
'I dati sono stati automaticamente inseriti nel campo note dell\'operazione.',
style: TextStyle(fontSize: 12, color: Colors.black87),
),
),
],
),
),
],
),
);
}
Widget _buildInfoRow(String label, String value) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 110,
child: Text(
label,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: Colors.black54,
),
),
),
Expanded(
child: Text(
value,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
),
],
);
}
}
@@ -7,23 +7,12 @@ import 'package:flux/features/master_data/providers/models/provider_model_extens
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';
import 'package:flux/features/master_data/products/models/model_model.dart';
class OperationDetailsSection extends StatelessWidget {
const OperationDetailsSection({super.key});
static const List<String> _availableTypes = [
'AL',
'MNP',
'NIP',
'UNICA',
'FWA',
'TELEPASS',
'Energy',
'Fin',
'Entertainment',
'Altro',
];
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -117,10 +106,11 @@ class OperationDetailsSection extends StatelessWidget {
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)
? '${detail.type ?? ''} (${detail.subType})'
: (detail.type ?? 'Dettaglio');
? '$typeLabel (${detail.subType})'
: typeLabel;
return Card(
elevation: 0,
@@ -150,7 +140,10 @@ class OperationDetailsSection extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
typeText,
@@ -160,9 +153,30 @@ class OperationDetailsSection extends StatelessWidget {
fontSize: 14,
),
),
if (detail.quantity > 1)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2,
),
decoration: BoxDecoration(
color: typeColor.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: typeColor.withValues(alpha: 0.35),
),
),
child: Text(
'×${detail.quantity}',
style: TextStyle(
color: typeColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
if (detail.provider?.name != null &&
detail.provider!.name.isNotEmpty) ...[
const SizedBox(width: 8),
detail.provider!.name.isNotEmpty)
Chip(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
@@ -181,7 +195,6 @@ class OperationDetailsSection extends StatelessWidget {
color: providerColor.withValues(alpha: 0.3),
),
),
],
],
),
if (detail.model?.name != null &&
@@ -226,6 +239,34 @@ class OperationDetailsSection extends StatelessWidget {
],
),
],
if (detail.type?.supportsQuantity == true) ...[
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
'Valore / Qtà:',
style: TextStyle(
fontSize: 12,
color: Colors.grey[700],
fontWeight: FontWeight.w500,
),
),
_QuantityStepper(
quantity: detail.quantity,
color: typeColor,
compact: true,
onChanged: (nextQty) {
context
.read<OperationDetailsListCubit>()
.updateOperationDetailQuantity(index, nextQty);
},
),
],
),
],
],
),
),
@@ -292,48 +333,19 @@ class OperationDetailsSection extends StatelessWidget {
);
}
Color _getTypeColor(String? type) {
switch (type?.toUpperCase()) {
case 'FIN':
return Colors.deepPurple;
case 'TELEPASS':
return Colors.yellow.shade800;
case 'ENERGY':
return Colors.amber.shade800;
case 'ENTERTAINMENT':
return Colors.pinkAccent;
case 'AL':
case 'MNP':
return Colors.indigo;
case 'NIP':
case 'FWA':
return Colors.cyan;
default:
return Colors.blueGrey;
}
Color _getTypeColor(OperationType? type) {
return type?.color ?? Colors.blueGrey;
}
IconData _getIconForType(String? type, String? subtype) {
if (type?.toLowerCase() == 'energy') {
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;
}
switch (type?.toUpperCase()) {
case 'FIN':
return Icons.devices;
case 'TELEPASS':
return Icons.directions_car;
case 'ENTERTAINMENT':
return Icons.tv;
case 'AL':
case 'MNP':
return Icons.phone_android;
case 'NIP':
case 'FWA':
return Icons.wifi;
default:
return Icons.build;
if (type == OperationType.entertainment) {
if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer;
}
return type?.icon ?? Icons.build;
}
}
@@ -372,7 +384,7 @@ class _OperationDetailFormSheetState
super.dispose();
}
void _showProviderModal(BuildContext context, String operationType) {
void _showProviderModal(BuildContext context, OperationType? operationType) {
final formCubit = context.read<OperationDetailsFormCubit>();
showModalBottomSheet(
context: context,
@@ -415,7 +427,7 @@ class _OperationDetailFormSheetState
final filteredProviders =
state.providers.where((p) {
return p.supportsOperation(operationType) &&
return p.supportsOperationType(operationType) &&
p.isActive;
}).toList();
@@ -528,7 +540,7 @@ class _OperationDetailFormSheetState
>(
builder: (context, formState) {
final detail = formState.operationDetail;
final currentType = detail.type ?? 'AL';
final currentType = detail.type ?? OperationType.al;
return Padding(
padding: EdgeInsets.only(
@@ -573,11 +585,10 @@ class _OperationDetailFormSheetState
spacing: 8.0,
runSpacing: 8.0,
children:
OperationDetailsSection._availableTypes.map((
type,
) {
OperationType.values.map((type) {
return ChoiceChip(
label: Text(type),
avatar: Icon(type.icon, size: 16),
label: Text(type.shortLabel),
selected: currentType == type,
onSelected: (selected) {
if (selected) {
@@ -638,18 +649,18 @@ class _OperationDetailFormSheetState
const SizedBox(height: 16),
// 3. Scenario Energy (Dropdown Fisso)
if (currentType == 'Energy') ...[
if (currentType == OperationType.energy) ...[
DropdownButtonFormField<String>(
initialValue:
(detail.subType != null &&
detail.subType!.isNotEmpty)
? detail.subType
: 'Luce',
: EnergySubtypes.luce,
decoration: const InputDecoration(
labelText: 'Dettaglio Fornitura',
),
items:
['Luce', 'Gas']
EnergySubtypes.all
.map(
(s) => DropdownMenuItem(
value: s,
@@ -681,7 +692,7 @@ class _OperationDetailFormSheetState
],
// 4. Scenario Fin (Ricerca Modello/Prodotto)
if (currentType == 'Fin') ...[
if (currentType == OperationType.fin) ...[
SharedModelSection(
label: 'Seleziona Dispositivo/Prodotto',
modelId: detail.modelId,
@@ -689,22 +700,116 @@ class _OperationDetailFormSheetState
onModelSelected: (id, name) {
context
.read<OperationDetailsFormCubit>()
.updateFields(modelId: id);
.updateFields(
modelId: id,
model: ModelModel(
id: id,
name: name,
nameWithBrand: name,
brandId: '',
),
);
},
),
const SizedBox(height: 16),
],
// 5. Scenario Entertainment o Custom (Testo libero)
if (currentType == 'Entertainment' ||
currentType == 'Altro') ...[
// 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: InputDecoration(
labelText:
currentType == 'Entertainment'
? 'Piattaforma (es. Netflix, DAZN, Spotify...)'
: 'Specifica il servizio (es. Monopattino)',
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 Ricontatto / Bolletta in scadenza
if (currentType == OperationType.ricontatto) ...[
const Text(
'Tipo di Fornitura / Servizio da Ricontattare',
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13),
),
const SizedBox(height: 8),
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: RicontattoSubtypes.all.map((sub) {
final isSelected = detail.subType?.toLowerCase() == sub.toLowerCase();
return ChoiceChip(
avatar: sub == RicontattoSubtypes.luce
? const Icon(Icons.bolt_outlined, size: 16)
: (sub == RicontattoSubtypes.gas
? const Icon(Icons.local_fire_department_outlined, size: 16)
: (sub == RicontattoSubtypes.telefonia
? const Icon(Icons.phone_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: _descriptionController,
decoration: const InputDecoration(
labelText: 'Gestore Attuale / Note Offerta',
hintText: 'Es. Enel Luce 0.15€/kWh, scadenza vincolo tra 10 mesi...',
),
onChanged: (val) {
context
.read<OperationDetailsFormCubit>()
.updateFields(description: 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
@@ -715,12 +820,68 @@ class _OperationDetailFormSheetState
const SizedBox(height: 16),
],
// Valore / Quantità (per Entertainment e Unica)
if (currentType.supportsQuantity) ...[
const Text(
'Valore / Quantità',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
const SizedBox(height: 4),
Text(
currentType == OperationType.entertainment
? 'Indica quanti canali/contenuti vale questo pacchetto (es. TIMVISION L = 3).'
: 'Indica quante unità vale questo servizio Unica.',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
),
),
const SizedBox(height: 10),
Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_QuantityStepper(
quantity: detail.quantity,
color: currentType.color,
onChanged: (val) {
context
.read<OperationDetailsFormCubit>()
.updateFields(quantity: val);
},
),
Wrap(
spacing: 6,
children: [1, 2, 3, 4, 5].map((preset) {
return ChoiceChip(
label: Text('×$preset'),
selected: detail.quantity == preset,
onSelected: (selected) {
if (selected) {
context
.read<OperationDetailsFormCubit>()
.updateFields(quantity: preset);
}
},
);
}).toList(),
),
],
),
const SizedBox(height: 16),
],
// 6. Scadenza (Reattiva per tipi complessi)
if ([
'Energy',
'Fin',
'Entertainment',
'Altro',
OperationType.energy,
OperationType.fin,
OperationType.entertainment,
OperationType.ricontatto,
OperationType.altro,
].contains(currentType)) ...[
_buildDurationQuickPicks(context),
const SizedBox(height: 16),
@@ -807,3 +968,77 @@ class _OperationDetailFormSheetState
);
}
}
class _QuantityStepper extends StatelessWidget {
final int quantity;
final Color color;
final ValueChanged<int> onChanged;
final bool compact;
const _QuantityStepper({
required this.quantity,
required this.color,
required this.onChanged,
this.compact = false,
});
@override
Widget build(BuildContext context) {
final canDecrement = quantity > 1;
final buttonSize = compact ? 28.0 : 34.0;
final iconSize = compact ? 16.0 : 18.0;
final fontSize = compact ? 13.0 : 15.0;
return Container(
decoration: BoxDecoration(
color: color.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withValues(alpha: 0.3)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
borderRadius: const BorderRadius.horizontal(left: Radius.circular(7)),
onTap: canDecrement ? () => onChanged(quantity - 1) : null,
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: Icon(
Icons.remove,
size: iconSize,
color: canDecrement ? color : Colors.grey.shade400,
),
),
),
Container(
constraints: BoxConstraints(minWidth: compact ? 28 : 34),
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Text(
'$quantity',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: fontSize,
color: color,
),
),
),
InkWell(
borderRadius: const BorderRadius.horizontal(right: Radius.circular(7)),
onTap: () => onChanged(quantity + 1),
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: Icon(
Icons.add,
size: iconSize,
color: color,
),
),
),
],
),
);
}
}
@@ -0,0 +1,649 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/operations/models/operation_filter_params.dart';
import 'package:flux/features/operations/models/operation_type.dart';
/// BottomSheet per impostare i filtri avanzati della lista operazioni
class OperationFilterSheet extends StatefulWidget {
final OperationFilterParams currentFilters;
final ValueChanged<OperationFilterParams> onApply;
final VoidCallback onReset;
const OperationFilterSheet({
super.key,
required this.currentFilters,
required this.onApply,
required this.onReset,
});
static Future<void> show(
BuildContext context, {
required OperationFilterParams currentFilters,
required ValueChanged<OperationFilterParams> onApply,
required VoidCallback onReset,
}) {
return showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => OperationFilterSheet(
currentFilters: currentFilters,
onApply: onApply,
onReset: onReset,
),
);
}
@override
State<OperationFilterSheet> createState() => _OperationFilterSheetState();
}
class _OperationFilterSheetState extends State<OperationFilterSheet> {
OperationType? _selectedType;
late TextEditingController _subTypeController;
StaffMemberModel? _selectedStaff;
DateTimeRange? _selectedDateRange;
@override
void initState() {
super.initState();
_selectedType = widget.currentFilters.detailType;
_subTypeController = TextEditingController(
text: widget.currentFilters.subType ?? '',
);
_selectedDateRange = widget.currentFilters.dateRange;
// Inizializza l'addetto se presente
if (widget.currentFilters.staffId != null) {
final staffState = context.read<StaffCubit>().state;
final staffList = staffState.storeStaff.isNotEmpty
? staffState.storeStaff
: staffState.allStaff;
for (final s in staffList) {
if (s.id == widget.currentFilters.staffId) {
_selectedStaff = s;
break;
}
}
}
}
@override
void dispose() {
_subTypeController.dispose();
super.dispose();
}
void _setDatePreset(String preset) {
final now = DateTime.now();
switch (preset) {
case 'today':
final start = DateTime(now.year, now.month, now.day, 0, 0, 0);
final end = DateTime(now.year, now.month, now.day, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'last7':
final start = DateTime(now.year, now.month, now.day - 6, 0, 0, 0);
final end = DateTime(now.year, now.month, now.day, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'thisMonth':
final start = DateTime(now.year, now.month, 1, 0, 0, 0);
final end = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'lastMonth':
final start = DateTime(now.year, now.month - 1, 1, 0, 0, 0);
final end = DateTime(now.year, now.month, 0, 23, 59, 59);
setState(() => _selectedDateRange = DateTimeRange(start: start, end: end));
break;
case 'all':
setState(() => _selectedDateRange = null);
break;
}
}
Future<void> _pickCustomDateRange() async {
final now = DateTime.now();
final picked = await showDateRangePicker(
context: context,
initialDateRange: _selectedDateRange ??
DateTimeRange(
start: DateTime(now.year, now.month, 1),
end: DateTime(now.year, now.month, now.day),
),
firstDate: DateTime(2020),
lastDate: DateTime(now.year + 5),
);
if (picked != null) {
setState(() {
_selectedDateRange = DateTimeRange(
start: DateTime(
picked.start.year,
picked.start.month,
picked.start.day,
0,
0,
0,
),
end: DateTime(
picked.end.year,
picked.end.month,
picked.end.day,
23,
59,
59,
),
);
});
}
}
void _apply() {
final subText = _subTypeController.text.trim();
final params = widget.currentFilters.copyWith(
detailType: _selectedType,
subType: subText.isNotEmpty ? subText : null,
staffId: _selectedStaff?.id,
staffDisplayName: _selectedStaff?.name,
dateRange: _selectedDateRange,
clearDetailType: _selectedType == null,
clearSubType: subText.isEmpty,
clearStaff: _selectedStaff == null,
clearRange: _selectedDateRange == null,
// Se l'utente ha modificato manualmente tipo o sottotipo, svuotiamo categoryKey specifica
clearCategory: _selectedType != widget.currentFilters.detailType,
);
widget.onApply(params);
Navigator.of(context).pop();
}
void _reset() {
widget.onReset();
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final mediaQuery = MediaQuery.of(context);
return DraggableScrollableSheet(
initialChildSize: 0.85,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (_, scrollController) {
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
),
child: Column(
children: [
// Maniglia top
Center(
child: Container(
width: 40,
height: 4,
margin: const EdgeInsets.only(top: 12, bottom: 8),
decoration: BoxDecoration(
color: theme.dividerColor,
borderRadius: BorderRadius.circular(2),
),
),
),
// Header
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
Icons.tune,
color: theme.colorScheme.primary,
size: 22,
),
const SizedBox(width: 8),
Text(
'Filtri Avanzati',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
TextButton.icon(
onPressed: _reset,
icon: const Icon(Icons.filter_alt_off, size: 18),
label: const Text('Azzera tutto'),
style: TextButton.styleFrom(
foregroundColor: Colors.redAccent,
),
),
],
),
),
const Divider(height: 1),
// Corpo con i filtri
Expanded(
child: ListView(
controller: scrollController,
padding: const EdgeInsets.all(20),
children: [
// 1. TIPO SERVIZIO / DETTAGLIO
_buildSectionTitle(
theme,
title: 'Tipo di Servizio / Dettaglio',
icon: Icons.category_outlined,
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti'),
selected: _selectedType == null,
onSelected: (selected) {
if (selected) {
setState(() {
_selectedType = null;
_subTypeController.clear();
});
}
},
),
...OperationType.values.map((type) {
final isSelected = _selectedType == type;
return ChoiceChip(
avatar: Icon(
type.icon,
size: 16,
color: isSelected ? Colors.white : type.color,
),
label: Text(type.shortLabel),
selected: isSelected,
selectedColor: type.color,
labelStyle: TextStyle(
color: isSelected ? Colors.white : null,
fontWeight:
isSelected ? FontWeight.bold : FontWeight.normal,
),
onSelected: (selected) {
setState(() {
_selectedType = selected ? type : null;
if (!selected) _subTypeController.clear();
});
},
);
}),
],
),
const SizedBox(height: 24),
// 2. SOTTOTIPO / SPECIFICA (se applicabile)
if (_selectedType != null) ...[
_buildSectionTitle(
theme,
title: 'Sottotipo / Offerta specifica',
icon: Icons.subdirectory_arrow_right,
),
const SizedBox(height: 10),
if (_selectedType == OperationType.entertainment) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti i contenuti'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...EntertainmentSubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
avatar: sub == EntertainmentSubtypes.calcio
? const Icon(Icons.sports_soccer, size: 15)
: (sub == EntertainmentSubtypes.cinemaTv
? const Icon(Icons.movie_outlined, size: 15)
: null),
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
] else if (_selectedType == OperationType.energy) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutte le forniture'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...EnergySubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
] else if (_selectedType == OperationType.ricontatto) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti i ricontatti'),
selected: _subTypeController.text.isEmpty,
onSelected: (sel) {
if (sel) {
setState(() => _subTypeController.clear());
}
},
),
...RicontattoSubtypes.all.map((sub) {
final isSel = _subTypeController.text
.trim()
.toLowerCase() ==
sub.toLowerCase();
return ChoiceChip(
label: Text(sub),
selected: isSel,
onSelected: (sel) {
setState(() {
_subTypeController.text = sel ? sub : '';
});
},
);
}),
],
),
const SizedBox(height: 10),
],
TextField(
controller: _subTypeController,
decoration: InputDecoration(
labelText: 'Filtro testuale sottotipo (opzionale)',
hintText: 'Es. DAZN, TIMVISION, Luce...',
prefixIcon: const Icon(Icons.search, size: 18),
suffixIcon: _subTypeController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear, size: 18),
onPressed: () => setState(
() => _subTypeController.clear(),
),
)
: null,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 24),
],
// 3. COLLABORATORE / ADDETTO
_buildSectionTitle(
theme,
title: 'Collaboratore / Addetto',
icon: Icons.person_outline,
),
const SizedBox(height: 10),
BlocBuilder<StaffCubit, StaffState>(
builder: (context, staffState) {
final rawList = staffState.storeStaff.isNotEmpty
? staffState.storeStaff
: staffState.allStaff;
final activeStaff =
rawList.where((s) => s.isActive).toList();
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('Tutti gli addetti'),
selected: _selectedStaff == null,
onSelected: (sel) {
if (sel) setState(() => _selectedStaff = null);
},
),
...activeStaff.map((staff) {
final isSel = _selectedStaff?.id == staff.id;
return ChoiceChip(
avatar: CircleAvatar(
radius: 10,
backgroundColor: isSel
? Colors.white
: theme.colorScheme.primary.withValues(
alpha: 0.2,
),
child: Text(
staff.name.isNotEmpty
? staff.name[0].toUpperCase()
: '?',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: isSel
? theme.colorScheme.primary
: theme.colorScheme.primary,
),
),
),
label: Text(staff.name),
selected: isSel,
onSelected: (sel) {
setState(() {
_selectedStaff = sel ? staff : null;
});
},
);
}),
],
);
},
),
const SizedBox(height: 24),
// 4. RANGE DATE / PERIODO
_buildSectionTitle(
theme,
title: 'Periodo / Data Creazione',
icon: Icons.calendar_month_outlined,
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ActionChip(
avatar: const Icon(Icons.all_inclusive, size: 16),
label: const Text('Sempre'),
backgroundColor: _selectedDateRange == null
? theme.colorScheme.primaryContainer
: null,
onPressed: () => _setDatePreset('all'),
),
ActionChip(
label: const Text('Oggi'),
onPressed: () => _setDatePreset('today'),
),
ActionChip(
label: const Text('Ultimi 7 gg'),
onPressed: () => _setDatePreset('last7'),
),
ActionChip(
label: const Text('Questo mese'),
onPressed: () => _setDatePreset('thisMonth'),
),
ActionChip(
label: const Text('Mese scorso'),
onPressed: () => _setDatePreset('lastMonth'),
),
ActionChip(
avatar: const Icon(Icons.date_range, size: 16),
label: const Text('Personalizzato...'),
onPressed: _pickCustomDateRange,
),
],
),
if (_selectedDateRange != null) ...[
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 10,
),
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer
.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: theme.colorScheme.primary.withValues(
alpha: 0.3,
),
),
),
child: Row(
children: [
Icon(
Icons.check_circle_outline,
size: 18,
color: theme.colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Dal ${_formatDate(_selectedDateRange!.start)} al ${_formatDate(_selectedDateRange!.end)}',
style: TextStyle(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
fontSize: 13,
),
),
),
IconButton(
icon: const Icon(Icons.close, size: 18),
onPressed: () =>
setState(() => _selectedDateRange = null),
tooltip: 'Rimuovi filtro data',
),
],
),
),
],
],
),
),
// Footer con bottoni di conferma
Container(
padding: EdgeInsets.fromLTRB(
20,
12,
20,
12 + mediaQuery.viewPadding.bottom,
),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
border: Border(
top: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
),
),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Annulla'),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: ElevatedButton.icon(
icon: const Icon(Icons.done),
label: const Text('Applica Filtri'),
onPressed: _apply,
),
),
],
),
),
],
),
);
},
);
}
Widget _buildSectionTitle(
ThemeData theme, {
required String title,
required IconData icon,
}) {
return Row(
children: [
Icon(icon, size: 18, color: theme.colorScheme.primary),
const SizedBox(width: 6),
Text(
title,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
),
],
);
}
String _formatDate(DateTime dt) {
return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
}
}
@@ -4,6 +4,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/utils/update_prompt_helper.dart';
import 'package:flux/core/utils/version_check_service.dart';
import 'package:flux/features/settings/blocs/settings_cubit.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
@@ -91,6 +93,22 @@ class SettingsScreen extends StatelessWidget {
context: context,
onTap: () => context.pushNamed(Routes.themeSettings),
),
const Divider(height: 30),
FutureBuilder<String>(
future: VersionCheckService.getFullVersionString(),
builder: (context, snapshot) {
final versionText = snapshot.data ?? '...';
return _settingsTile(
icon: Icons.info_outline,
title: 'Versione Flux',
subtitle: versionText.isNotEmpty
? '$versionText • Tocca per verificare aggiornamenti'
: 'Verifica disponibilità aggiornamenti',
context: context,
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
);
},
),
]),
const SizedBox(height: 24),
@@ -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,351 @@
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 attivo
final List<IndividualTargetModel> individuals = [];
for (final staff in storeStaff) {
if (staff.id == null || !staff.isActive) 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
if (staff.isNotEmpty) {
return staff.where((s) => s.isActive).toList();
}
// 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 || !staff.isActive) 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),
ricontatti1: calc(m.ricontatti1),
ricontatti2: calc(m.ricontatti2),
);
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;
}
}
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more