Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0036b729d | ||
|
|
4d791d2213 | ||
|
|
19fc90b830 | ||
|
|
4f0fe7bab5 | ||
|
|
7323f68e62 | ||
|
|
a33b08a0c3 | ||
|
|
c8fdd29cf4 | ||
|
|
00615b92a0 | ||
|
|
832be3d797 | ||
|
|
72f9d88f96 | ||
|
|
d4a6b142c5 | ||
|
|
8da4dc9d75 | ||
|
|
6ad0aa3e23 | ||
|
|
11c5352555 | ||
|
|
a0bdb9a535 | ||
|
|
37d69e3ddc | ||
|
|
524da71a45 | ||
|
|
3949d6d13c | ||
|
|
d5591b2c91 | ||
|
|
97d19f1d17 | ||
|
|
282a959f88 | ||
|
|
aaa6cdf704 | ||
|
|
bc1614c71b | ||
|
|
b71656d0a6 | ||
|
|
9374f4ab46 | ||
|
|
3b3e65bd1c | ||
|
|
ce035e2204 | ||
|
|
70c0c25521 | ||
|
|
8cd55f53f7 | ||
|
|
6e01729bf5 | ||
|
|
4b4d0c5cb6 | ||
|
|
ff27727f10 | ||
|
|
8f0ad23c0b | ||
|
|
729c893463 | ||
|
|
eb31ad7173 | ||
|
|
a652232b25 | ||
|
|
b8f752d246 | ||
|
|
b837a5fa1e | ||
|
|
9154a16fe1 | ||
|
|
48f6f92f9c | ||
|
|
c6e3594850 | ||
|
|
c6a1b203ce | ||
|
|
1c96ff9516 | ||
|
|
409c064902 | ||
|
|
66667fb440 | ||
|
|
c41fcd37b3 | ||
|
|
9cd0b98a16 | ||
|
|
8951bff083 | ||
|
|
a514bba8b2 | ||
|
|
f8504d466a | ||
|
|
22bb86f052 | ||
|
|
fc850795c9 | ||
|
|
b60ce96dd7 | ||
|
|
6582da60d4 | ||
|
|
d42cc5af1d | ||
|
|
7ea0e2ac10 | ||
|
|
5ce0110197 | ||
|
|
4efc3ce182 | ||
|
|
01515910b6 | ||
|
|
f27ede7625 | ||
|
|
99ab7abf6e | ||
|
|
a7fd37a894 | ||
|
|
8ad2b7cf7e | ||
|
|
3210b4fcfa | ||
|
|
a51ac8fe7f | ||
|
|
7fad6ee02b | ||
|
|
6a6e792cd9 | ||
|
|
3c33c8765a | ||
|
|
27a5bc16bc | ||
|
|
808de7b354 | ||
|
|
618cbc0396 | ||
|
|
67a56f2954 | ||
|
|
88b1a618bd | ||
|
|
d989b14967 | ||
|
|
d4ff2b9a7e | ||
|
|
06ee11521d | ||
|
|
55d6429dc5 | ||
|
|
44c85766fc | ||
|
|
b69308e1ef | ||
|
|
6394e5a2cd | ||
|
|
f31ff19a74 | ||
|
|
064179a753 | ||
|
|
727eaac3d9 | ||
|
|
bd81173559 | ||
|
|
9bace01b93 | ||
|
|
5ad3e12b1f | ||
|
|
6211cc6729 | ||
|
|
f15a2aa6e6 | ||
|
|
aed841dc0b | ||
|
|
221260aca3 |
No files matched your search
+155
-37
@@ -21,11 +21,27 @@ jobs:
|
||||
- name: Build Flutter Windows
|
||||
run: flutter build windows --release
|
||||
|
||||
# 1. FIRMA DELL'ESEGUIBILE RAW
|
||||
- name: Firma Eseguibile Flutter
|
||||
run: |
|
||||
# Cerca dinamicamente signtool.exe nell'SDK di Windows per non sbagliare percorso
|
||||
$Signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1).FullName
|
||||
|
||||
# Sostituisci il percorso con dove hai salvato fisicamente il file .pfx sul PC del runner!
|
||||
& $Signtool sign /f "C:\flux_privato.pfx" /p "${{ secrets.PFX_PASSWORD }}" /fd SHA256 "build\windows\x64\runner\Release\flux.exe"
|
||||
|
||||
- name: Build Windows Installer
|
||||
run: |
|
||||
$TagVersion = "${{ github.ref_name }}".Substring(1)
|
||||
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" "/DMyAppVersion=$TagVersion" "win_installer.iss"
|
||||
|
||||
# 2. FIRMA DELL'INSTALLER GENERATO DA INNO SETUP
|
||||
- name: Firma Installer
|
||||
run: |
|
||||
$Signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1).FullName
|
||||
|
||||
& $Signtool sign /f "C:\flux_privato.pfx" /p "${{ secrets.PFX_PASSWORD }}" /fd SHA256 "build\windows\installer\FluxInstaller.exe"
|
||||
|
||||
# Nel dubbio usiamo l'action per caricare l'asset
|
||||
- name: Upload Windows Asset
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
@@ -33,50 +49,30 @@ 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')
|
||||
$headers = @{
|
||||
"apikey" = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Authorization" = "Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Content-Type" = "application/json"
|
||||
}
|
||||
$body = (@{
|
||||
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
|
||||
latest_version = $TagVersion
|
||||
} | ConvertTo-Json)
|
||||
Invoke-RestMethod -Uri "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.windows" -Method Patch -Headers $headers -Body $body -UserAgent "flux-runner"
|
||||
|
||||
- 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
|
||||
@@ -96,4 +92,126 @@ jobs:
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
|
||||
- name: Aggiorna Versione Web su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.web" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"latest_version\": \"$TagVersion\"}"
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner)
|
||||
# -----------------------------------------------------------------
|
||||
build-linux:
|
||||
runs-on: linux-runner # <--- Etichetta del tuo runner Linux / Fedora in ufficio
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Crea file .env
|
||||
run: |
|
||||
cat << 'EOF' > .env
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Build Flutter Linux
|
||||
run: flutter build linux --release
|
||||
|
||||
- name: Prepara AppDir per AppImage
|
||||
run: |
|
||||
mkdir -p build/Flux.AppDir
|
||||
cp -r build/linux/x64/release/bundle/* build/Flux.AppDir/
|
||||
cp assets/icon/icon.png build/Flux.AppDir/flux.png
|
||||
|
||||
cat << 'EOF' > build/Flux.AppDir/AppRun
|
||||
#!/bin/sh
|
||||
cd "$(dirname "$0")"
|
||||
exec ./flux "$@"
|
||||
EOF
|
||||
chmod +x build/Flux.AppDir/AppRun
|
||||
|
||||
cat << 'EOF' > build/Flux.AppDir/Flux.desktop
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Type=Application
|
||||
Terminal=false
|
||||
Name=Flux
|
||||
Exec=flux %u
|
||||
Icon=flux
|
||||
Categories=Utility;
|
||||
EOF
|
||||
|
||||
- name: Scarica appimagetool se non presente
|
||||
run: |
|
||||
if [ ! -f ./appimagetool-x86_64.AppImage ]; then
|
||||
curl -L -o appimagetool-x86_64.AppImage https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
|
||||
chmod +x appimagetool-x86_64.AppImage
|
||||
fi
|
||||
|
||||
- name: Genera AppImage
|
||||
run: |
|
||||
ARCH=x86_64 ./appimagetool-x86_64.AppImage build/Flux.AppDir Flux-x86_64.AppImage
|
||||
|
||||
- name: Upload Linux AppImage Asset
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: "Flux-x86_64.AppImage"
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link Linux su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.AppImage" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-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: 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}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}"
|
||||
@@ -46,3 +46,7 @@ app.*.map.json
|
||||
/android/app/release
|
||||
|
||||
.env
|
||||
|
||||
appimagetool*
|
||||
*.AppDir
|
||||
*.AppImage
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"deno.enable": true
|
||||
}
|
||||
@@ -7,6 +7,14 @@ analyzer:
|
||||
- "lib/l10n/*.dart"
|
||||
- "**/*.g.dart" # Già che ci siamo escludiamo tutti i file generati (tipo quelli di JsonSerializable)
|
||||
- "**/*.freezed.dart"
|
||||
- "build/**"
|
||||
- "ios/**"
|
||||
- "macos/**"
|
||||
- ".dart_tool/**"
|
||||
- android/**
|
||||
- web/**
|
||||
- windows/**
|
||||
- linux/**
|
||||
|
||||
linter:
|
||||
rules:
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services")
|
||||
// END: FlutterFire Configuration
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
// 2. CARICHIAMO IL KEYSTORE QUI FUORI IN MODO PULITO
|
||||
val keystoreProperties = Properties()
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.catellisrl.flux"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
@@ -20,7 +33,6 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.catellisrl.flux"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
@@ -30,11 +42,22 @@ android {
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties["keyAlias"] as String?
|
||||
keyPassword = keystoreProperties["keyPassword"] as String?
|
||||
storeFile = keystoreProperties["storeFile"]?.let { file(it as String) }
|
||||
storePassword = keystoreProperties["storePassword"] as String?
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
signingConfig = if (keystorePropertiesFile.exists()) {
|
||||
signingConfigs.getByName("release")
|
||||
} else {
|
||||
signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "249756116297",
|
||||
"project_id": "flux-87e49",
|
||||
"storage_bucket": "flux-87e49.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:249756116297:android:a2c3d37323752069cf2698",
|
||||
"android_client_info": {
|
||||
"package_name": "com.catellisrl.flux"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyA6-uX6504B3yofeo7YQwfQaS0cCDoZnvY"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -20,6 +20,9 @@ pluginManagement {
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "8.11.1" apply false
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services") version("4.3.15") apply false
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.android") version "2.2.20" apply false
|
||||
}
|
||||
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"flutter":{"platforms":{"android":{"default":{"projectId":"flux-87e49","appId":"1:249756116297:android:a2c3d37323752069cf2698","fileOutput":"android/app/google-services.json"}},"ios":{"default":{"projectId":"flux-87e49","appId":"1:249756116297:ios:fe9dadca7150da16cf2698","uploadDebugSymbols":false,"fileOutput":"ios/Runner/GoogleService-Info.plist"}},"macos":{"default":{"projectId":"flux-87e49","appId":"1:249756116297:ios:fe9dadca7150da16cf2698","uploadDebugSymbols":false,"fileOutput":"macos/Runner/GoogleService-Info.plist"}},"dart":{"lib/firebase_options.dart":{"projectId":"flux-87e49","configurations":{"android":"1:249756116297:android:a2c3d37323752069cf2698","ios":"1:249756116297:ios:fe9dadca7150da16cf2698","macos":"1:249756116297:ios:fe9dadca7150da16cf2698","web":"1:249756116297:web:7c652e51004414b7cf2698","windows":"1:249756116297:web:b094277c2fedb425cf2698"}}}}}}
|
||||
@@ -0,0 +1 @@
|
||||
␍ .env␍asset.envassets/icon/icon.png␍assetassets/icon/icon.png assets/images/flux_logo_dark.png␍asset assets/images/flux_logo_dark.png!assets/images/flux_logo_light.png␍asset!assets/images/flux_logo_light.pngassets/svg/flux_logo_dark.svg␍assetassets/svg/flux_logo_dark.svgassets/svg/flux_logo_light.svg␍assetassets/svg/flux_logo_light.svgMpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otf␍assetMpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otfKpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otf␍assetKpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otfIpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf␍assetIpackages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf
|
||||
@@ -0,0 +1 @@
|
||||
[{"family":"MaterialIcons","fonts":[{"asset":"fonts/MaterialIcons-Regular.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeBrands","fonts":[{"weight":400,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Brands-Regular-400.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeRegular","fonts":[{"weight":400,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Regular-400.otf"}]},{"family":"packages/font_awesome_flutter/FontAwesomeSolid","fonts":[{"weight":900,"asset":"packages/font_awesome_flutter/lib/fonts/Font-Awesome-7-Free-Solid-900.otf"}]}]
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"format-version":[1,0,0],"native-assets":{}}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 45 KiB |
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="220mm"
|
||||
height="70mm"
|
||||
viewBox="0 0 220 70"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="linearGradient4">
|
||||
<stop
|
||||
style="stop-color:#0467a8;stop-opacity:1;"
|
||||
offset="0.17659575"
|
||||
id="stop6" />
|
||||
<stop
|
||||
style="stop-color:#09a8bd;stop-opacity:1;"
|
||||
offset="1"
|
||||
id="stop7" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
xlink:href="#linearGradient4"
|
||||
id="linearGradient5"
|
||||
x1="2.1388452"
|
||||
y1="38.851192"
|
||||
x2="70.730141"
|
||||
y2="38.851192"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="translate(0,-1.0583333)" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata1">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<path
|
||||
d="m 79.119202,16.272909 v 38.473103 h 5.331457 V 36.220011 H 101.87182 V 31.672485 H 84.450659 v -10.85205 h 20.275251 v -4.547526 z m 31.691608,0 v 38.473103 h 25.36434 V 50.198486 H 116.14226 V 16.272909 Z m 30.10359,0 v 23.02185 c 0,2.911107 0.31379,5.365736 0.94206,7.363892 0.64622,1.998156 1.69671,3.703477 3.15071,5.115967 1.27449,1.240234 2.84499,2.179539 4.71186,2.816882 1.86686,0.637342 4.05705,0.956014 6.57014,0.956014 2.45924,0 4.61323,-0.301962 6.46214,-0.904854 1.84891,-0.602892 3.46453,-1.558906 4.84673,-2.868042 1.454,-1.378039 2.49505,-3.100586 3.12332,-5.167644 0.64622,-2.084283 0.96894,-4.521687 0.96894,-7.312215 v -23.02185 h -5.33095 v 23.409423 c 0,1.877578 -0.15269,3.453709 -0.45785,4.728394 -0.28721,1.25746 -0.78097,2.377115 -1.48105,3.358968 -0.80777,1.136881 -1.88451,1.989542 -3.23081,2.557983 -1.3463,0.551216 -2.97976,0.826823 -4.90047,0.826823 -1.90277,0 -3.53675,-0.28422 -4.90099,-0.852661 -1.3463,-0.56844 -2.41411,-1.412489 -3.20394,-2.532145 -0.70008,-0.981853 -1.20276,-2.07567 -1.50792,-3.281453 -0.28721,-1.205784 -0.43098,-2.850817 -0.43098,-4.9351 V 16.272909 Z m 37.72327,0 13.65137,19.249471 -13.97486,19.223632 h 5.81618 l 11.20139,-15.838826 10.93163,15.838826 h 6.16603 L 198.6163,35.289836 212.45628,16.272909 h -5.84305 l -11.03964,15.63212 -10.79727,-15.63212 z"
|
||||
style="font-size:54.019px;font-family:Roboto;-inkscape-font-specification:'Roboto, @wght=600';font-variation-settings:'wght' 600;stroke-width:0.270095"
|
||||
id="path10" />
|
||||
<path
|
||||
d="m 18.746659,32.35048 v 35.012333 l 7.483265,0.01602 -0.0078,-15.15153 -0.444417,0.0088 -0.283187,-5.574853 0.724503,-0.09353 -0.0052,-10.30273 c -2.477109,-1.576343 -4.681183,-2.913234 -7.467245,-3.91449 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path4" />
|
||||
<path
|
||||
d="m 34.188094,44.204537 -2.362646,1.228349 -3.40186,0.850077 -2.92902,0.378272 0.283187,5.574853 4.819344,-0.09405 3.024105,-1.03973 2.362129,-1.417484 1.512053,-0.756027 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path3" />
|
||||
<path
|
||||
d="m 30.789852,3.3827393 c -2.718649,-0.031966 -5.436525,0.014505 -8.153508,0.092501 -1.657421,0.047579 -3.410165,1.1618896 -3.915523,2.4758178 -0.117943,1.3009842 -0.120443,2.6260493 -0.194303,3.9361939 -0.03417,4.6029962 0.05579,9.2082292 0.06976,13.8120772 l 8.031551,2.645316 V 15.482776 c -0.06845,-1.616367 -0.186384,-3.220801 5.17e-4,-4.823995 1.450909,-0.02681 2.901798,-0.0533 4.352706,-0.0801 0.05294,-7.58e-4 0.101815,-0.0019 0.146761,-0.0026 -0.133325,0.0041 -0.29154,0.0097 -0.465088,0.01705 5.402012,0.128802 10.810722,0.09637 16.214514,0.01395 1.312459,0.137599 2.534326,-0.34712 3.780648,-0.6609411 0.688414,-0.375834 1.230544,-1.0271554 1.861385,-1.5115356 0.530757,-0.2588779 0.43123,-0.8718681 0.550871,-1.361674 0.317571,-1.2121917 0.137814,-2.4561815 0.111104,-3.690214 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path2" />
|
||||
<path
|
||||
d="m 56.166081,18.073315 c -1.612095,0.517615 -3.326896,0.856005 -4.876705,1.482597 -1.672317,1.636751 -3.569999,3.080027 -4.731494,5.154724 -1.760645,2.382939 -3.026169,5.086524 -4.280876,7.757666 -0.891629,2.073315 -1.768619,4.152921 -2.589506,6.255433 l 4.441073,4.251936 c 1.398551,-3.4772 2.668634,-7.012956 4.53719,-10.275341 0.629987,-1.555517 1.666989,-2.831823 2.828251,-4.022494 1.022671,-1.037894 1.767254,-2.482454 3.326929,-2.735233 0.889424,-0.171791 1.852674,-1.15661 2.651001,-0.326079 1.091115,0.724393 2.380755,1.270451 3.353284,2.101164 0.773793,1.805199 1.727371,3.571064 2.391068,5.400187 -0.10305,3.050467 0.318141,6.150981 -0.478523,9.13536 -0.227898,1.392226 -0.44891,2.787081 -1.327568,3.939294 -0.639724,0.878207 -0.930155,2.134421 -1.788004,2.776575 -1.441269,0.609895 -2.847747,1.462494 -4.310848,1.920296 -1.617481,-0.300784 -3.315903,-0.407844 -4.88394,-0.826823 -2.069996,-1.549653 -4.248341,-2.976127 -5.912301,-4.986259 -2.758844,-2.90603 -5.507188,-5.823363 -8.591207,-8.391735 -3.338252,-2.881492 -6.432985,-6.060987 -10.113077,-8.519377 -1.00535,-0.833342 -2.074808,-1.535604 -3.393075,-1.725476 -2.128037,-0.523545 -4.194319,-1.47308 -6.429582,-1.257805 -2.170664,0.06994 -4.409538,-0.393106 -6.482808,0.438733 -0.9003416,0.331796 -2.1359215,0.232269 -2.4158733,1.361674 -1.9123575,3.173056 -3.6177926,6.486404 -4.6400268,10.062435 -0.4008915,1.586154 -0.4139892,3.222181 -0.038241,4.817794 l 0.1400432,0.924491 c 0.8820904,-2.491562 1.2764827,-5.195371 2.8018961,-7.407299 0.6237014,-1.09468 1.1172001,-2.309336 2.3424927,-2.850472 1.0032429,-0.704794 1.9546502,-1.540401 3.2581987,-1.487765 3.00294,-0.587415 6.099427,-0.06595 9.095052,0.498161 1.4899,0.270585 2.725854,0.959381 4.081922,1.606103 2.823588,1.93021 5.578022,3.981722 8.006229,6.392375 3.658406,4.382924 6.878979,9.116624 10.426754,13.577466 1.153639,1.018099 2.201592,2.226861 3.41943,3.129008 1.866433,0.375292 3.683112,1.179818 5.582605,1.267623 2.379016,-0.109475 4.813761,-0.01813 7.158736,-0.251148 2.193684,-1.301699 4.557492,-2.436561 6.645589,-3.841626 1.382677,-2.657284 2.904182,-5.268723 4.200261,-7.954553 0.355987,-2.855588 0.956499,-5.711351 1.159619,-8.566919 -0.441278,-2.56316 -0.629473,-5.204579 -1.227832,-7.718909 -1.026057,-1.96421 -1.887153,-4.070949 -3.014287,-5.947957 -1.857041,-1.18145 -3.561937,-2.667789 -5.518009,-3.65094 -1.601938,-0.471008 -3.198698,-1.192578 -4.803841,-1.506885 z"
|
||||
style="fill:url(#linearGradient5);stroke-width:0.264583"
|
||||
id="path1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.7 KiB |
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="220mm"
|
||||
height="70mm"
|
||||
viewBox="0 0 220 70"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="linearGradient4">
|
||||
<stop
|
||||
style="stop-color:#0467a8;stop-opacity:1;"
|
||||
offset="0.17659575"
|
||||
id="stop6" />
|
||||
<stop
|
||||
style="stop-color:#09a8bd;stop-opacity:1;"
|
||||
offset="1"
|
||||
id="stop7" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
xlink:href="#linearGradient4"
|
||||
id="linearGradient5"
|
||||
x1="2.1388452"
|
||||
y1="38.851192"
|
||||
x2="70.730141"
|
||||
y2="38.851192"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="translate(0,-1.0583333)" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata1">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<path
|
||||
d="m 79.119202,16.272909 v 38.473103 h 5.331457 V 36.220011 H 101.87182 V 31.672485 H 84.450659 v -10.85205 h 20.275251 v -4.547526 z m 31.691608,0 v 38.473103 h 25.36434 V 50.198486 H 116.14226 V 16.272909 Z m 30.10359,0 v 23.02185 c 0,2.911107 0.31379,5.365736 0.94206,7.363892 0.64622,1.998156 1.69671,3.703477 3.15071,5.115967 1.27449,1.240234 2.84499,2.179539 4.71186,2.816882 1.86686,0.637342 4.05705,0.956014 6.57014,0.956014 2.45924,0 4.61323,-0.301962 6.46214,-0.904854 1.84891,-0.602892 3.46453,-1.558906 4.84673,-2.868042 1.454,-1.378039 2.49505,-3.100586 3.12332,-5.167644 0.64622,-2.084283 0.96894,-4.521687 0.96894,-7.312215 v -23.02185 h -5.33095 v 23.409423 c 0,1.877578 -0.15269,3.453709 -0.45785,4.728394 -0.28721,1.25746 -0.78097,2.377115 -1.48105,3.358968 -0.80777,1.136881 -1.88451,1.989542 -3.23081,2.557983 -1.3463,0.551216 -2.97976,0.826823 -4.90047,0.826823 -1.90277,0 -3.53675,-0.28422 -4.90099,-0.852661 -1.3463,-0.56844 -2.41411,-1.412489 -3.20394,-2.532145 -0.70008,-0.981853 -1.20276,-2.07567 -1.50792,-3.281453 -0.28721,-1.205784 -0.43098,-2.850817 -0.43098,-4.9351 V 16.272909 Z m 37.72327,0 13.65137,19.249471 -13.97486,19.223632 h 5.81618 l 11.20139,-15.838826 10.93163,15.838826 h 6.16603 L 198.6163,35.289836 212.45628,16.272909 h -5.84305 l -11.03964,15.63212 -10.79727,-15.63212 z"
|
||||
style="font-size:54.019px;font-family:Roboto;-inkscape-font-specification:'Roboto, @wght=600';font-variation-settings:'wght' 600;stroke-width:0.270095;fill:#ffffff;fill-opacity:1"
|
||||
id="path10" />
|
||||
<path
|
||||
d="m 18.746659,32.35048 v 35.012333 l 7.483265,0.01602 -0.0078,-15.15153 -0.444417,0.0088 -0.283187,-5.574853 0.724503,-0.09353 -0.0052,-10.30273 c -2.477109,-1.576343 -4.681183,-2.913234 -7.467245,-3.91449 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path4" />
|
||||
<path
|
||||
d="m 34.188094,44.204537 -2.362646,1.228349 -3.40186,0.850077 -2.92902,0.378272 0.283187,5.574853 4.819344,-0.09405 3.024105,-1.03973 2.362129,-1.417484 1.512053,-0.756027 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path3" />
|
||||
<path
|
||||
d="m 30.789852,3.3827393 c -2.718649,-0.031966 -5.436525,0.014505 -8.153508,0.092501 -1.657421,0.047579 -3.410165,1.1618896 -3.915523,2.4758178 -0.117943,1.3009842 -0.120443,2.6260493 -0.194303,3.9361939 -0.03417,4.6029962 0.05579,9.2082292 0.06976,13.8120772 l 8.031551,2.645316 V 15.482776 c -0.06845,-1.616367 -0.186384,-3.220801 5.17e-4,-4.823995 1.450909,-0.02681 2.901798,-0.0533 4.352706,-0.0801 0.05294,-7.58e-4 0.101815,-0.0019 0.146761,-0.0026 -0.133325,0.0041 -0.29154,0.0097 -0.465088,0.01705 5.402012,0.128802 10.810722,0.09637 16.214514,0.01395 1.312459,0.137599 2.534326,-0.34712 3.780648,-0.6609411 0.688414,-0.375834 1.230544,-1.0271554 1.861385,-1.5115356 0.530757,-0.2588779 0.43123,-0.8718681 0.550871,-1.361674 0.317571,-1.2121917 0.137814,-2.4561815 0.111104,-3.690214 z"
|
||||
style="font-variation-settings:'wght' 600;fill:#0467a8;stroke-width:0.264583"
|
||||
id="path2" />
|
||||
<path
|
||||
d="m 56.166081,18.073315 c -1.612095,0.517615 -3.326896,0.856005 -4.876705,1.482597 -1.672317,1.636751 -3.569999,3.080027 -4.731494,5.154724 -1.760645,2.382939 -3.026169,5.086524 -4.280876,7.757666 -0.891629,2.073315 -1.768619,4.152921 -2.589506,6.255433 l 4.441073,4.251936 c 1.398551,-3.4772 2.668634,-7.012956 4.53719,-10.275341 0.629987,-1.555517 1.666989,-2.831823 2.828251,-4.022494 1.022671,-1.037894 1.767254,-2.482454 3.326929,-2.735233 0.889424,-0.171791 1.852674,-1.15661 2.651001,-0.326079 1.091115,0.724393 2.380755,1.270451 3.353284,2.101164 0.773793,1.805199 1.727371,3.571064 2.391068,5.400187 -0.10305,3.050467 0.318141,6.150981 -0.478523,9.13536 -0.227898,1.392226 -0.44891,2.787081 -1.327568,3.939294 -0.639724,0.878207 -0.930155,2.134421 -1.788004,2.776575 -1.441269,0.609895 -2.847747,1.462494 -4.310848,1.920296 -1.617481,-0.300784 -3.315903,-0.407844 -4.88394,-0.826823 -2.069996,-1.549653 -4.248341,-2.976127 -5.912301,-4.986259 -2.758844,-2.90603 -5.507188,-5.823363 -8.591207,-8.391735 -3.338252,-2.881492 -6.432985,-6.060987 -10.113077,-8.519377 -1.00535,-0.833342 -2.074808,-1.535604 -3.393075,-1.725476 -2.128037,-0.523545 -4.194319,-1.47308 -6.429582,-1.257805 -2.170664,0.06994 -4.409538,-0.393106 -6.482808,0.438733 -0.9003416,0.331796 -2.1359215,0.232269 -2.4158733,1.361674 -1.9123575,3.173056 -3.6177926,6.486404 -4.6400268,10.062435 -0.4008915,1.586154 -0.4139892,3.222181 -0.038241,4.817794 l 0.1400432,0.924491 c 0.8820904,-2.491562 1.2764827,-5.195371 2.8018961,-7.407299 0.6237014,-1.09468 1.1172001,-2.309336 2.3424927,-2.850472 1.0032429,-0.704794 1.9546502,-1.540401 3.2581987,-1.487765 3.00294,-0.587415 6.099427,-0.06595 9.095052,0.498161 1.4899,0.270585 2.725854,0.959381 4.081922,1.606103 2.823588,1.93021 5.578022,3.981722 8.006229,6.392375 3.658406,4.382924 6.878979,9.116624 10.426754,13.577466 1.153639,1.018099 2.201592,2.226861 3.41943,3.129008 1.866433,0.375292 3.683112,1.179818 5.582605,1.267623 2.379016,-0.109475 4.813761,-0.01813 7.158736,-0.251148 2.193684,-1.301699 4.557492,-2.436561 6.645589,-3.841626 1.382677,-2.657284 2.904182,-5.268723 4.200261,-7.954553 0.355987,-2.855588 0.956499,-5.711351 1.159619,-8.566919 -0.441278,-2.56316 -0.629473,-5.204579 -1.227832,-7.718909 -1.026057,-1.96421 -1.887153,-4.070949 -3.014287,-5.947957 -1.857041,-1.18145 -3.561937,-2.667789 -5.518009,-3.65094 -1.601938,-0.471008 -3.198698,-1.192578 -4.803841,-1.506885 z"
|
||||
style="fill:url(#linearGradient5);stroke-width:0.264583"
|
||||
id="path1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"app_name":"flux","version":"1.3.1","build_number":"47","package_name":"flux"}
|
||||
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -7,6 +7,7 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
101B9A4BF8F30D998DDC11D4 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = D4B70082D3146D8C2B7AFA02 /* GoogleService-Info.plist */; };
|
||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
|
||||
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
|
||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
||||
@@ -67,6 +68,7 @@
|
||||
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
AB44F93458B7D70EE383A3A9 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
|
||||
BDDDA09E437D9C0E7B65B3B1 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
|
||||
D4B70082D3146D8C2B7AFA02 /* GoogleService-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = "GoogleService-Info.plist"; path = "Runner/GoogleService-Info.plist"; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -126,6 +128,7 @@
|
||||
331C8082294A63A400263BE5 /* RunnerTests */,
|
||||
F5D002C3092D87755D552D32 /* Pods */,
|
||||
6A991A28CCED9666CA172E00 /* Frameworks */,
|
||||
D4B70082D3146D8C2B7AFA02 /* GoogleService-Info.plist */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -267,6 +270,7 @@
|
||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
|
||||
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
|
||||
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
|
||||
101B9A4BF8F30D998DDC11D4 /* GoogleService-Info.plist in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>API_KEY</key>
|
||||
<string>AIzaSyAllwaoNyqHsZtqfMMo9DxVS6-q7yBwWow</string>
|
||||
<key>GCM_SENDER_ID</key>
|
||||
<string>249756116297</string>
|
||||
<key>PLIST_VERSION</key>
|
||||
<string>1</string>
|
||||
<key>BUNDLE_ID</key>
|
||||
<string>com.catellisrl.flux</string>
|
||||
<key>PROJECT_ID</key>
|
||||
<string>flux-87e49</string>
|
||||
<key>STORAGE_BUCKET</key>
|
||||
<string>flux-87e49.firebasestorage.app</string>
|
||||
<key>IS_ADS_ENABLED</key>
|
||||
<false></false>
|
||||
<key>IS_ANALYTICS_ENABLED</key>
|
||||
<false></false>
|
||||
<key>IS_APPINVITE_ENABLED</key>
|
||||
<true></true>
|
||||
<key>IS_GCM_ENABLED</key>
|
||||
<true></true>
|
||||
<key>IS_SIGNIN_ENABLED</key>
|
||||
<true></true>
|
||||
<key>GOOGLE_APP_ID</key>
|
||||
<string>1:249756116297:ios:fe9dadca7150da16cf2698</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,9 +1,15 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/data/core_repository.dart';
|
||||
import 'package:flux/features/company/models/company_model.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:collection/collection.dart'; // Per firstWhereOrNull
|
||||
@@ -22,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 {
|
||||
@@ -39,112 +50,183 @@ class SessionCubit extends Cubit<SessionState> {
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. CHI È QUESTO UTENTE? (Vediamo se ha un profilo staff, che sia Invitato o Admin)
|
||||
StaffMemberModel? staff = await _repository.getStaffMemberByUserId(
|
||||
user.id,
|
||||
);
|
||||
CompanyModel? company;
|
||||
if (staff != null) {
|
||||
// --- LA MAGIA DEL SENSORE ---
|
||||
if (staff.hasJoined == false) {
|
||||
// È la primissima volta che entra! Aggiorniamo il DB.
|
||||
await _repository.updateStaffMember(staff.id!, {'has_joined': true});
|
||||
// Aggiorniamo anche il nostro modello in memoria per questa sessione
|
||||
staff = staff.copyWith(hasJoined: true);
|
||||
// Riportiamo lo stato su initial per far girare lo spinner se stiamo riprovando
|
||||
emit(state.copyWith(status: SessionStatus.initial, errorMessage: null));
|
||||
|
||||
// WRAP DELLA LOGICA IN UN BLOCCO PROTETTO DA TIMEOUT (10 Secondi)
|
||||
await Future(() async {
|
||||
StaffMemberModel? staff = await _repository.getStaffMemberByUserId(
|
||||
user.id,
|
||||
);
|
||||
CompanyModel? company;
|
||||
|
||||
if (staff != null) {
|
||||
if (staff.hasJoined == false) {
|
||||
await _repository.updateStaffMember(staff.id!, {
|
||||
'has_joined': true,
|
||||
});
|
||||
staff = staff.copyWith(hasJoined: true);
|
||||
}
|
||||
company = await _repository.getCompanyById(staff.companyId);
|
||||
} else {
|
||||
company = await _repository.getCompanyByOwnerId(user.id);
|
||||
}
|
||||
|
||||
company = await _repository.getCompanyById(staff.companyId);
|
||||
} else {
|
||||
// È l'Admin in onboarding
|
||||
company = await _repository.getCompanyByOwnerId(user.id);
|
||||
}
|
||||
// 1. Controllo Azienda
|
||||
if (company == null) {
|
||||
return emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
user: user,
|
||||
onboardingStep: OnboardingStep.company,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(company: company));
|
||||
}
|
||||
|
||||
if (staff != null) {
|
||||
// L'utente esiste già nel sistema! Carichiamo l'azienda per cui lavora
|
||||
company = await _repository.getCompanyById(staff.companyId);
|
||||
} else {
|
||||
// L'utente non ha profilo. Probabilmente è l'Admin che ha appena
|
||||
// fatto Sign Up e sta iniziando l'Onboarding
|
||||
company = await _repository.getCompanyByOwnerId(user.id);
|
||||
}
|
||||
if (company == null) {
|
||||
return emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
user: user,
|
||||
onboardingStep: OnboardingStep.company,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(company: company));
|
||||
}
|
||||
final stores = await _repository.getStoresByCompanyId(company.id!);
|
||||
if (stores.isEmpty) {
|
||||
return emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
user: user,
|
||||
company: company,
|
||||
onboardingStep: OnboardingStep.store,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(currentStore: stores.first));
|
||||
}
|
||||
|
||||
// 2. Controllo Negozi
|
||||
final stores = await _repository.getStoresByCompanyId(company.id!);
|
||||
if (stores.isEmpty) {
|
||||
return emit(
|
||||
if (staff == null) {
|
||||
return emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
user: user,
|
||||
company: company,
|
||||
onboardingStep: OnboardingStep.staff,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final lastStoreId = _prefs.getString(_lastStoreKey);
|
||||
final activeStore =
|
||||
stores.firstWhereOrNull((s) => s.id == lastStoreId) ?? stores.first;
|
||||
|
||||
if (lastStoreId != activeStore.id && activeStore.id != null) {
|
||||
await _prefs.setString(_lastStoreKey, activeStore.id!);
|
||||
}
|
||||
|
||||
setIsSingleUserMode(_prefs.getBool('isSingleUserMode') ?? false);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
status: SessionStatus.authenticated,
|
||||
user: user,
|
||||
company: company,
|
||||
onboardingStep: OnboardingStep.store,
|
||||
currentStore: activeStore,
|
||||
currentStaffMember: staff,
|
||||
onboardingStep: OnboardingStep.none,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(currentStore: stores.first));
|
||||
}
|
||||
|
||||
// 3. Controllo Staff (Paziente Zero)
|
||||
if (staff == null) {
|
||||
return emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.onboardingRequired,
|
||||
user: user,
|
||||
company: company,
|
||||
onboardingStep: OnboardingStep.staff,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- TUTTO COMPLETATO: LOGICA DEL NEGOZIO DI DEFAULT ---
|
||||
|
||||
// Leggiamo l'ultimo negozio dalle SharedPreferences
|
||||
final lastStoreId = _prefs.getString(_lastStoreKey);
|
||||
|
||||
// Cerchiamo quel negozio nella lista. Se non c'è (magari è stato eliminato), prendiamo il primo.
|
||||
final activeStore =
|
||||
stores.firstWhereOrNull((s) => s.id == lastStoreId) ?? stores.first;
|
||||
|
||||
// Se non avevamo il lastStoreId salvato, salviamolo ora
|
||||
if (lastStoreId != activeStore.id && activeStore.id != null) {
|
||||
await _prefs.setString(_lastStoreKey, activeStore.id!);
|
||||
}
|
||||
|
||||
setIsSingleUserMode(_prefs.getBool('isSingleUserMode') ?? false);
|
||||
|
||||
// 4. BENVENUTO A BORDO
|
||||
// FCM è fuori dall'await principale, quindi va bene così
|
||||
_registerFcmToken(companyId: company.id!, staffId: staff.id!);
|
||||
}).timeout(
|
||||
const Duration(seconds: 10), // Tempo massimo concesso al server
|
||||
onTimeout: () {
|
||||
throw TimeoutException(
|
||||
'Il server di FLUX non risponde. Controlla la connessione.',
|
||||
);
|
||||
},
|
||||
);
|
||||
} on TimeoutException catch (e) {
|
||||
// 🎯 BINGO! IL TIMEOUT È SCATTATO
|
||||
debugPrint("Timeout Inizializzazione: ${e.message}");
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus.authenticated,
|
||||
user: user,
|
||||
company: company,
|
||||
currentStore: activeStore,
|
||||
currentStaffMember: staff,
|
||||
onboardingStep: OnboardingStep.none, // Svuotiamo l'onboarding
|
||||
),
|
||||
state.copyWith(status: SessionStatus.error, errorMessage: e.message),
|
||||
);
|
||||
} catch (e) {
|
||||
// Se esplode il database, non lasciamo l'app freezata in 'initial'
|
||||
// Altri errori generici del DB o di rete
|
||||
debugPrint("Errore Inizializzazione: $e");
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: SessionStatus
|
||||
.unauthenticated, // O un nuovo stato SessionStatus.error
|
||||
status: SessionStatus.error,
|
||||
errorMessage: "Si è verificato un errore di connessione imprevisto.",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _registerFcmToken({
|
||||
required String companyId,
|
||||
required String staffId,
|
||||
}) async {
|
||||
// Scudo anti-crash per lo sviluppo su Linux / Windows
|
||||
if (!kIsWeb &&
|
||||
!Platform.isAndroid &&
|
||||
!Platform.isIOS &&
|
||||
!Platform.isMacOS) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final messaging = FirebaseMessaging.instance;
|
||||
|
||||
// 1. Richiesta permessi di notifica
|
||||
final settings = await messaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
|
||||
String? fcmToken;
|
||||
if (kIsWeb) {
|
||||
fcmToken = await messaging.getToken(
|
||||
vapidKey:
|
||||
'BLMUr7crlRghEW6iWtRZ7Y0a74OPAMG9Oh37ewhVP3_5YD9e5RHUeO79sDys6P-7KjOz6I6HiaPqNndmatQlu3g',
|
||||
);
|
||||
} else {
|
||||
fcmToken = await messaging.getToken();
|
||||
}
|
||||
|
||||
if (fcmToken != null) {
|
||||
final supabase = GetIt.I.get<SupabaseClient>();
|
||||
|
||||
// Determiniamo la piattaforma in modo sicuro per Linux
|
||||
String osPlatform = 'web';
|
||||
if (!kIsWeb) {
|
||||
if (Platform.isAndroid) osPlatform = 'android';
|
||||
if (Platform.isIOS) osPlatform = 'ios';
|
||||
if (Platform.isMacOS) osPlatform = 'macos';
|
||||
}
|
||||
|
||||
// 3. UPSERT su Supabase condizionato dal vincolo 'fcm_token'
|
||||
await supabase.from('staff_devices').upsert(
|
||||
{
|
||||
'company_id': companyId,
|
||||
'staff_id': staffId,
|
||||
'fcm_token': fcmToken,
|
||||
'os_platform': osPlatform,
|
||||
'updated_at': DateTime.now().toIso8601String(),
|
||||
},
|
||||
onConflict:
|
||||
'fcm_token', // Se il token esiste già, aggiorna questa riga!
|
||||
);
|
||||
|
||||
debugPrint(
|
||||
'Dispositivo registrato con successo su FLUX Cloud. Platform: $osPlatform',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
debugPrint('Permesso push negato dall\'utente.');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Errore durante la registrazione del dispositivo: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void updateCurrentCompany(CompanyModel newCompany) {
|
||||
emit(state.copyWith(company: newCompany));
|
||||
}
|
||||
@@ -170,4 +252,13 @@ class SessionCubit extends Cubit<SessionState> {
|
||||
void setIsSingleUserMode(bool isSingleUser) {
|
||||
emit(state.copyWith(isSingleUserMode: isSingleUser));
|
||||
}
|
||||
|
||||
void updateCurrentStoreLocally(StoreModel updatedStore) {
|
||||
// Verifichiamo che l'utente stia effettivamente lavorando nel negozio appena modificato
|
||||
if (state.currentStore != null &&
|
||||
state.currentStore!.id == updatedStore.id) {
|
||||
// Emettiamo il nuovo stato sovrascrivendo solo il negozio corrente
|
||||
emit(state.copyWith(currentStore: updatedStore));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ enum SessionStatus {
|
||||
unauthenticated,
|
||||
onboardingRequired,
|
||||
authenticated,
|
||||
error,
|
||||
}
|
||||
|
||||
/// Definisce lo step esatto dell'onboarding (Paranoia Mode)
|
||||
@@ -26,6 +27,7 @@ class SessionState extends Equatable {
|
||||
final OnboardingStep onboardingStep;
|
||||
final bool isMobileDevice;
|
||||
final bool isSingleUserMode;
|
||||
final String? errorMessage;
|
||||
|
||||
const SessionState({
|
||||
this.status = SessionStatus.initial,
|
||||
@@ -36,6 +38,7 @@ class SessionState extends Equatable {
|
||||
this.onboardingStep = OnboardingStep.none,
|
||||
this.isMobileDevice = false,
|
||||
this.isSingleUserMode = false,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
/// Metodo per creare una copia dello stato modificando solo i campi necessari
|
||||
@@ -48,6 +51,7 @@ class SessionState extends Equatable {
|
||||
OnboardingStep? onboardingStep,
|
||||
bool? isMobileDevice,
|
||||
bool? isSingleUserMode,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return SessionState(
|
||||
status: status ?? this.status,
|
||||
@@ -58,6 +62,7 @@ class SessionState extends Equatable {
|
||||
onboardingStep: onboardingStep ?? this.onboardingStep,
|
||||
isMobileDevice: isMobileDevice ?? this.isMobileDevice,
|
||||
isSingleUserMode: isSingleUserMode ?? this.isSingleUserMode,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -71,6 +76,7 @@ class SessionState extends Equatable {
|
||||
onboardingStep,
|
||||
isMobileDevice,
|
||||
isSingleUserMode,
|
||||
errorMessage,
|
||||
];
|
||||
|
||||
// Helper rapidi per la UI
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class Tables {
|
||||
static const String appConfig = 'app_config';
|
||||
static const String attachments = 'attachments';
|
||||
static const String brands = 'brands';
|
||||
static const String campaigns = 'campaigns';
|
||||
@@ -9,6 +10,7 @@ class Tables {
|
||||
static const String notes = 'notes';
|
||||
static const String noteCollaborators = 'note_collaborators';
|
||||
static const String operations = 'operations';
|
||||
static const String operationDetails = 'operation_details';
|
||||
static const String providerLocations = 'provider_locations';
|
||||
static const String providers = 'providers';
|
||||
static const String providersInStores = 'providers_in_stores';
|
||||
@@ -16,8 +18,11 @@ class Tables {
|
||||
static const String staffInStores = 'staff_in_stores';
|
||||
static const String staffMembers = 'staff_members';
|
||||
static const String stores = 'stores';
|
||||
static const String targets = 'targets';
|
||||
static const String individualTargets = 'individual_targets';
|
||||
static const String tasks = 'tasks';
|
||||
static const String taskAssignments = 'task_assignments';
|
||||
static const String taskReminders = 'task_reminders';
|
||||
static const String tickets = 'tickets';
|
||||
static const String trackings = 'trackings';
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
|
||||
// ==========================================
|
||||
@@ -89,10 +90,16 @@ class _AppMenuState extends State<AppMenu> {
|
||||
Icon(Icons.bolt, color: theme.colorScheme.primary, size: 32),
|
||||
if (!effectivelyCollapsed) ...[
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
"FLUX",
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (widget.isDrawer) Navigator.pop(context);
|
||||
context.goNamed(Routes.home);
|
||||
},
|
||||
child: Text(
|
||||
"FLUX",
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -111,14 +118,45 @@ class _AppMenuState extends State<AppMenu> {
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
children: [
|
||||
_buildRouteItem(
|
||||
title: context.l10n.commonDashboard,
|
||||
title: 'Dashboard',
|
||||
icon: Icons.dashboard_outlined,
|
||||
routeName: Routes.home, // <--- Usiamo la tua costante!
|
||||
routeName: Routes.home,
|
||||
pathToCheck:
|
||||
'/', // Il path da controllare per colorarlo
|
||||
isCollapsed: effectivelyCollapsed,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// --- SEZIONE OPERATIVA ---
|
||||
_buildHierarchicalItem(
|
||||
title: 'Operatività',
|
||||
icon: Icons.work_outline,
|
||||
basePathToCheck: '/',
|
||||
isCollapsed: effectivelyCollapsed,
|
||||
subItems: [
|
||||
_SubMenuItem(
|
||||
'Operazioni',
|
||||
Routes.operations,
|
||||
'/operations',
|
||||
),
|
||||
_SubMenuItem(
|
||||
'Assistenza',
|
||||
Routes.tickets,
|
||||
'/tickets',
|
||||
),
|
||||
_SubMenuItem('Tasks', Routes.tasks, '/tasks'),
|
||||
_SubMenuItem('Sticky Notes', Routes.notes, '/notes'),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
_buildRouteItem(
|
||||
title: 'Obiettivi',
|
||||
icon: Icons.track_changes_outlined,
|
||||
routeName: Routes.targets,
|
||||
pathToCheck: '/targets',
|
||||
isCollapsed: effectivelyCollapsed,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// --- IL MENU GERARCHICO (ANAGRAFICHE) ---
|
||||
_buildHierarchicalItem(
|
||||
@@ -160,6 +198,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(
|
||||
@@ -220,7 +264,9 @@ class _AppMenuState extends State<AppMenu> {
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -233,11 +279,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,
|
||||
@@ -256,7 +310,9 @@ class _AppMenuState extends State<AppMenu> {
|
||||
required bool isCollapsed,
|
||||
required List<_SubMenuItem> subItems,
|
||||
}) {
|
||||
final isSelected = widget.currentPath.startsWith(basePathToCheck);
|
||||
final isSelected = subItems.any(
|
||||
(item) => widget.currentPath.startsWith(item.pathToCheck),
|
||||
);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
if (isCollapsed) {
|
||||
@@ -282,7 +338,7 @@ class _AppMenuState extends State<AppMenu> {
|
||||
: FontWeight.normal,
|
||||
color: widget.currentPath == item.pathToCheck
|
||||
? theme.colorScheme.primary
|
||||
: null,
|
||||
: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -299,7 +355,9 @@ class _AppMenuState extends State<AppMenu> {
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
color: isSelected
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -313,12 +371,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,
|
||||
@@ -344,7 +407,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,
|
||||
|
||||
@@ -7,9 +7,9 @@ import 'package:flux/core/layout/app_shell.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/widgets/image_upload/blocs/image_upload_cubit.dart';
|
||||
import 'package:flux/core/widgets/image_upload/ui/image_upload_screen.dart';
|
||||
import 'package:flux/core/widgets/set_password_screen.dart';
|
||||
import 'package:flux/core/widgets/image_upload/ui/upload_success_screen.dart';
|
||||
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/customers/blocs/customer_form_cubit.dart';
|
||||
@@ -18,6 +18,11 @@ 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_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';
|
||||
@@ -39,12 +44,15 @@ import 'package:flux/features/notes/ui/notes_list_screen.dart';
|
||||
import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart';
|
||||
import 'package:flux/features/onboarding/ui/onboarding_screen.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/ui/operation_form_screen.dart';
|
||||
import 'package:flux/features/operations/ui/operation_list_screen.dart';
|
||||
import 'package:flux/features/settings/settings_screen.dart';
|
||||
import 'package:flux/features/settings/theme_settings_view.dart';
|
||||
import 'package:flux/features/settings/blocs/reminder_defaults_cubit.dart';
|
||||
import 'package:flux/features/settings/ui/reminder_settings_screen.dart';
|
||||
import 'package:flux/features/settings/ui/settings_screen.dart';
|
||||
import 'package:flux/features/settings/ui/theme_settings_view.dart';
|
||||
import 'package:flux/features/tasks/blocs/task_form_cubit.dart';
|
||||
import 'package:flux/features/tasks/blocs/task_list_cubit.dart';
|
||||
import 'package:flux/features/tasks/models/task_model.dart';
|
||||
@@ -55,16 +63,32 @@ 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';
|
||||
|
||||
class AppRouter {
|
||||
// 1. CREIAMO LA CHIAVE GLOBALE DEL NAVIGATORE
|
||||
static final GlobalKey<NavigatorState> rootNavigatorKey =
|
||||
GlobalKey<NavigatorState>();
|
||||
static String? pendingRoute;
|
||||
static GoRouter createRouter(SessionCubit sessionCubit) {
|
||||
return GoRouter(
|
||||
navigatorKey: rootNavigatorKey,
|
||||
initialLocation: '/',
|
||||
refreshListenable: GoRouterRefreshStream(sessionCubit.stream),
|
||||
|
||||
redirect: (context, state) {
|
||||
final sessionState = sessionCubit.state;
|
||||
final isGoingToLogin = state.matchedLocation == '/login';
|
||||
@@ -143,11 +167,45 @@ class AppRouter {
|
||||
builder: (context, state) {
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<DashboardStoreOperationListCubit>(
|
||||
create: (context) => DashboardStoreOperationListCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardTaskListCubit>(
|
||||
create: (context) => DashboardTaskListCubit(),
|
||||
create: (context) => DashboardTaskListCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
staffId: sessionCubit.state.currentStaffMember?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardStoreTicketListCubit>(
|
||||
create: (context) => DashboardStoreTicketListCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardNoteListCubit>(
|
||||
create: (context) => DashboardNoteListCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: HomeScreen(),
|
||||
child: const HomeScreen(),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -218,6 +276,16 @@ class AppRouter {
|
||||
name: Routes.themeSettings,
|
||||
builder: (context, state) => const ThemeSettingsView(),
|
||||
),
|
||||
GoRoute(
|
||||
path: 'reminderSettings',
|
||||
name: Routes.reminderSettings,
|
||||
builder: (context, state) =>
|
||||
BlocProvider<ReminderDefaultsCubit>(
|
||||
create: (context) => ReminderDefaultsCubit(),
|
||||
|
||||
child: const ReminderSettingsScreen(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -268,10 +336,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,
|
||||
@@ -463,10 +573,15 @@ class AppRouter {
|
||||
existingOperation: record?.operation,
|
||||
),
|
||||
),
|
||||
BlocProvider(
|
||||
create: (context) => OperationDetailsListCubit(
|
||||
details: record?.operation?.details ?? [],
|
||||
),
|
||||
),
|
||||
],
|
||||
child: OperationFormScreen(
|
||||
operationId: realOperationId,
|
||||
existingOperation: record?.operation,
|
||||
operation: record?.operation,
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -541,16 +656,21 @@ class AppRouter {
|
||||
realTaskId = pathId;
|
||||
}
|
||||
|
||||
final allStaffList = context.read<StaffCubit>().state.allStaff;
|
||||
List<StaffMemberModel>? preloadedStaff;
|
||||
try {
|
||||
preloadedStaff = context.read<StaffCubit>().state.allStaff;
|
||||
} catch (_) {
|
||||
preloadedStaff = null; // Fallback se la rotta è isolata
|
||||
}
|
||||
|
||||
// Creiamo il BLoC "al volo" solo per questa schermata
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<TaskFormCubit>(
|
||||
create: (context) => TaskFormCubit(
|
||||
globalStaff: allStaffList,
|
||||
initialTask: task,
|
||||
existingTask: task,
|
||||
initialTaskId: realTaskId,
|
||||
allStaff: preloadedStaff,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -26,4 +26,8 @@ class Routes {
|
||||
static const String notes = 'notes';
|
||||
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';
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/routes/app_router.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
// Chiamala dopo l'autenticazione o nel main()
|
||||
Future<void> setupInteractedMessage() async {
|
||||
// CASO A: L'app era completamente CHIUSA e viene aperta tappando la notifica
|
||||
RemoteMessage? initialMessage = await FirebaseMessaging.instance
|
||||
.getInitialMessage();
|
||||
if (initialMessage != null) {
|
||||
_handleNotificationTap(initialMessage);
|
||||
}
|
||||
|
||||
// CASO B: L'app era in BACKGROUND (minimizzata) e l'utente tappa la notifica
|
||||
FirebaseMessaging.onMessageOpenedApp.listen(_handleNotificationTap);
|
||||
}
|
||||
|
||||
void _handleNotificationTap(RemoteMessage message) {
|
||||
final eventType = message.data['eventType'];
|
||||
final referenceId = message.data['referenceId'];
|
||||
|
||||
if (eventType == 'task_assigned' && referenceId != null) {
|
||||
final routePath = '/tasks/form/$referenceId';
|
||||
final context = AppRouter.rootNavigatorKey.currentContext;
|
||||
|
||||
if (context != null) {
|
||||
// Scenario A: App già aperta, naviga all'istante
|
||||
context.push(routePath);
|
||||
} else {
|
||||
// Scenario B: App chiusa. Il contesto non c'è ancora, congeliamo la rotta!
|
||||
debugPrint("App in fase di avvio. Congelo la rotta: $routePath");
|
||||
AppRouter.pendingRoute = routePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
-12
@@ -104,11 +104,25 @@ ThemeData fluxDarkTheme = ThemeData(
|
||||
),
|
||||
),
|
||||
|
||||
drawerTheme: const DrawerThemeData(
|
||||
backgroundColor: FluxColors.darkSurface,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
),
|
||||
|
||||
expansionTileTheme: const ExpansionTileThemeData(
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
collapsedIconColor: FluxColors.darkTextSecondary,
|
||||
textColor: FluxColors.darkTextPrimary,
|
||||
collapsedTextColor: FluxColors.darkTextPrimary,
|
||||
),
|
||||
|
||||
listTileTheme: ListTileThemeData(
|
||||
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
// Colore dell'icona (Turchese Flux)
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
selectedColor: FluxColors.primaryBlue,
|
||||
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.15),
|
||||
// Colore del testo
|
||||
titleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextPrimary,
|
||||
@@ -121,9 +135,6 @@ ThemeData fluxDarkTheme = ThemeData(
|
||||
),
|
||||
// Per far apparire la "manina" su Web/Desktop
|
||||
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
|
||||
|
||||
// NOTA: Se overlayColor non esiste, Flutter userà i colori
|
||||
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
|
||||
),
|
||||
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
@@ -189,26 +200,37 @@ ThemeData fluxLightTheme = ThemeData(
|
||||
),
|
||||
),
|
||||
|
||||
drawerTheme: const DrawerThemeData(
|
||||
backgroundColor: FluxColors.lightSurface,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
),
|
||||
|
||||
expansionTileTheme: const ExpansionTileThemeData(
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
collapsedIconColor: FluxColors.lightTextSecondary,
|
||||
textColor: FluxColors.lightTextPrimary,
|
||||
collapsedTextColor: FluxColors.lightTextPrimary,
|
||||
),
|
||||
|
||||
listTileTheme: ListTileThemeData(
|
||||
// Definiamo la forma arrotondata (fondamentale per l'effetto moderno)
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
// Colore dell'icona (Turchese Flux)
|
||||
iconColor: FluxColors.accentTurquoise,
|
||||
// Colore del testo
|
||||
selectedColor: FluxColors.primaryBlue,
|
||||
selectedTileColor: FluxColors.primaryBlue.withValues(alpha: 0.1),
|
||||
// Colore del testo per il tema chiaro
|
||||
titleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextPrimary,
|
||||
color: FluxColors.lightTextPrimary,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
subtitleTextStyle: GoogleFonts.poppins(
|
||||
color: FluxColors.darkTextSecondary,
|
||||
color: FluxColors.lightTextSecondary,
|
||||
fontSize: 13,
|
||||
),
|
||||
// Per far apparire la "manina" su Web/Desktop
|
||||
mouseCursor: WidgetStateProperty.all(SystemMouseCursors.click),
|
||||
|
||||
// NOTA: Se overlayColor non esiste, Flutter userà i colori
|
||||
// di default del tema (splashColor e hoverColor) definiti nel ThemeData generale.
|
||||
),
|
||||
|
||||
// Il pulsante principale rimane Blu Elettrico, molto visibile
|
||||
@@ -260,12 +282,14 @@ extension FluxThemeContext on BuildContext {
|
||||
// --- Testi (La parte mancante) ---
|
||||
// Mappiamo primaryText sul colore del titolo e secondaryText su quello del corpo
|
||||
Color get primaryText =>
|
||||
Theme.of(this).textTheme.titleLarge?.color ?? Colors.white;
|
||||
Theme.of(this).textTheme.titleLarge?.color ??
|
||||
Theme.of(this).colorScheme.onSurface;
|
||||
Color get secondaryText =>
|
||||
Theme.of(this).textTheme.bodyMedium?.color ?? Colors.grey;
|
||||
Theme.of(this).textTheme.bodyMedium?.color ??
|
||||
Theme.of(this).colorScheme.onSurfaceVariant;
|
||||
|
||||
// Opzionale: un colore ancora più tenue per suggerimenti o icone disabilitate
|
||||
Color get hintText =>
|
||||
Theme.of(this).textTheme.bodySmall?.color ??
|
||||
Colors.grey.withValues(alpha: 0.5);
|
||||
Theme.of(this).colorScheme.onSurface.withValues(alpha: 0.5);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
class AutoUpdateService {
|
||||
/// Verifica se la piattaforma corrente supporta l'aggiornamento automatico trasparente
|
||||
static bool get isAutoUpdateSupported {
|
||||
if (kIsWeb) return false;
|
||||
if (Platform.isWindows) return true;
|
||||
if (Platform.isLinux && Platform.environment['APPIMAGE'] != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Scarica l'aggiornamento e lo applica in modo silenzioso
|
||||
static Future<void> downloadAndApplyUpdate({
|
||||
required String downloadUrl,
|
||||
required void Function(double progress, String status) onProgress,
|
||||
}) async {
|
||||
if (kIsWeb) {
|
||||
throw UnsupportedError("L'auto-update non è supportato su Web.");
|
||||
}
|
||||
|
||||
if (Platform.isWindows) {
|
||||
await _updateWindows(downloadUrl, onProgress);
|
||||
} else if (Platform.isLinux) {
|
||||
await _updateLinux(downloadUrl, onProgress);
|
||||
} else {
|
||||
throw UnsupportedError("Piattaforma non supportata per l'auto-update.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gestione aggiornamento Windows
|
||||
static Future<void> _updateWindows(
|
||||
String downloadUrl,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final tempDir = Directory.systemTemp;
|
||||
final installerFile = File('${tempDir.path}\\FluxInstaller_Update.exe');
|
||||
|
||||
if (installerFile.existsSync()) {
|
||||
try {
|
||||
installerFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
onProgress(0.0, "Download aggiornamento in corso...");
|
||||
await _downloadFile(downloadUrl, installerFile, onProgress);
|
||||
|
||||
onProgress(1.0, "Installazione e riavvio in corso...");
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
// Lancia l'installer in modalità silenziosa per utente singolo
|
||||
// /VERYSILENT: nessuna interfaccia
|
||||
// /SUPPRESSMSGBOXES: nessun popup
|
||||
// /NORESTART: non riavvia il PC
|
||||
await Process.start(
|
||||
installerFile.path,
|
||||
['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
|
||||
// Chiude l'applicazione per consentire la sostituzione dei file
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/// Gestione aggiornamento Linux (AppImage in-place)
|
||||
static Future<void> _updateLinux(
|
||||
String downloadUrl,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final currentAppImagePath = Platform.environment['APPIMAGE'];
|
||||
if (currentAppImagePath == null) {
|
||||
throw StateError(
|
||||
"L'applicazione non è in esecuzione come AppImage.",
|
||||
);
|
||||
}
|
||||
|
||||
final newAppImageFile = File('$currentAppImagePath.new');
|
||||
if (newAppImageFile.existsSync()) {
|
||||
try {
|
||||
newAppImageFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
onProgress(0.0, "Download nuova versione in corso...");
|
||||
await _downloadFile(downloadUrl, newAppImageFile, onProgress);
|
||||
|
||||
onProgress(1.0, "Finalizzazione e riavvio...");
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
|
||||
// Assegna il permesso di esecuzione
|
||||
await Process.run('chmod', ['+x', newAppImageFile.path]);
|
||||
|
||||
// Sostituzione atomica del vecchio file AppImage con il nuovo
|
||||
newAppImageFile.renameSync(currentAppImagePath);
|
||||
|
||||
// Rilancia la nuova versione
|
||||
await Process.start(
|
||||
currentAppImagePath,
|
||||
[],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
|
||||
// Termina il processo attuale
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/// Download in streaming con tracciamento del progresso
|
||||
static Future<void> _downloadFile(
|
||||
String url,
|
||||
File destinationFile,
|
||||
void Function(double progress, String status) onProgress,
|
||||
) async {
|
||||
final client = HttpClient();
|
||||
client.autoUncompress = true;
|
||||
|
||||
try {
|
||||
final uri = Uri.parse(url);
|
||||
final request = await client.getUrl(uri);
|
||||
final response = await request.close();
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw HttpException(
|
||||
'Download fallito con codice di stato ${response.statusCode}',
|
||||
uri: uri,
|
||||
);
|
||||
}
|
||||
|
||||
final contentLength = response.contentLength;
|
||||
int downloadedBytes = 0;
|
||||
|
||||
final sink = destinationFile.openWrite();
|
||||
|
||||
await for (final chunk in response) {
|
||||
sink.add(chunk);
|
||||
downloadedBytes += chunk.length;
|
||||
|
||||
if (contentLength > 0) {
|
||||
final progress = (downloadedBytes / contentLength).clamp(0.0, 1.0);
|
||||
final percent = (progress * 100).toStringAsFixed(0);
|
||||
final downloadedMb =
|
||||
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
|
||||
final totalMb = (contentLength / (1024 * 1024)).toStringAsFixed(1);
|
||||
|
||||
onProgress(
|
||||
progress,
|
||||
'Scaricamento: $percent% ($downloadedMb MB di $totalMb MB)',
|
||||
);
|
||||
} else {
|
||||
final downloadedMb =
|
||||
(downloadedBytes / (1024 * 1024)).toStringAsFixed(1);
|
||||
onProgress(0.5, 'Scaricamento in corso ($downloadedMb MB)...');
|
||||
}
|
||||
}
|
||||
|
||||
await sink.flush();
|
||||
await sink.close();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +1,160 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class VersionCheckService {
|
||||
final _supabase = Supabase.instance.client;
|
||||
enum UpdateType {
|
||||
none,
|
||||
optional,
|
||||
mandatory,
|
||||
}
|
||||
|
||||
/// Controlla se l'app corrente deve essere bloccata o aggiornata.
|
||||
/// Ritorna il link di download se l'aggiornamento è obbligatorio, altrimenti null.
|
||||
Future<String?> checkForceUpdate() async {
|
||||
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<UpdateInfo?> checkUpdate() async {
|
||||
try {
|
||||
// 1. Determiniamo la piattaforma corrente
|
||||
String platformKey = 'web';
|
||||
if (!kIsWeb) {
|
||||
if (Platform.isAndroid) platformKey = 'android';
|
||||
if (Platform.isWindows) platformKey = 'windows';
|
||||
final platformAliases = _getPlatformAliases();
|
||||
|
||||
final dbResponse = await Supabase.instance.client
|
||||
.from('app_config')
|
||||
.select('platform, min_version, latest_version, download_url');
|
||||
|
||||
if (dbResponse.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. Recuperiamo la configurazione minima da Supabase
|
||||
final data = await _supabase
|
||||
.from('app_config')
|
||||
.select()
|
||||
.eq('platform', platformKey)
|
||||
.maybeSingle();
|
||||
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: () => {},
|
||||
);
|
||||
|
||||
if (data == null) return null;
|
||||
if (config.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final String minVersion = data['min_version'];
|
||||
final String downloadUrl = data['download_url'];
|
||||
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?) ?? '';
|
||||
|
||||
// 3. Recuperiamo la versione attuale dell'app dal pubspec.yaml
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
final String currentVersion = packageInfo.version;
|
||||
final localVersionRaw = packageInfo.version;
|
||||
|
||||
// 4. Confronto matematico semantico (es. 1.2.3 vs 1.1.9)
|
||||
if (_isVersionLower(currentVersion, minVersion)) {
|
||||
return downloadUrl; // Aggiornamento obbligatorio richiesto!
|
||||
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;
|
||||
} catch (e) {
|
||||
debugPrint('Errore controllo versione: $e');
|
||||
return null; // In caso di errore non blocchiamo l'utente
|
||||
debugPrint("Errore durante il check versione: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isVersionLower(String current, String min) {
|
||||
List<int> currentParts = current
|
||||
Future<String?> checkForceUpdate() async {
|
||||
final info = await checkUpdate();
|
||||
return info?.isMandatory == true ? info?.downloadUrl : null;
|
||||
}
|
||||
|
||||
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 '';
|
||||
}
|
||||
}
|
||||
|
||||
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 = min
|
||||
final targetParts = target
|
||||
.split('.')
|
||||
.map((e) => int.tryParse(e) ?? 0)
|
||||
.toList();
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int currentPart = currentParts.length > i ? currentParts[i] : 0;
|
||||
int minPart = minParts.length > i ? minParts[i] : 0;
|
||||
final maxLength = currentParts.length > targetParts.length
|
||||
? currentParts.length
|
||||
: targetParts.length;
|
||||
|
||||
if (currentPart < minPart) return true;
|
||||
if (currentPart > minPart) return false;
|
||||
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;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/// Enum con le festività nazionali italiane
|
||||
enum ItalianHoliday {
|
||||
capodanno(day: 1, month: 1, label: 'Capodanno'),
|
||||
epifania(day: 6, month: 1, label: 'Epifania'),
|
||||
liberazione(day: 25, month: 4, label: 'Festa della Liberazione'),
|
||||
lavoro(day: 1, month: 5, label: 'Festa dei Lavoratori'),
|
||||
repubblica(day: 2, month: 6, label: 'Festa della Repubblica'),
|
||||
ferragosto(day: 15, month: 8, label: 'Ferragosto'),
|
||||
ognissanti(day: 1, month: 11, label: 'Tutti i Santi'),
|
||||
immacolata(day: 8, month: 12, label: 'Immacolata Concezione'),
|
||||
natale(day: 25, month: 12, label: 'Natale'),
|
||||
santoStefano(day: 26, month: 12, label: 'Santo Stefano');
|
||||
|
||||
final int day;
|
||||
final int month;
|
||||
final String label;
|
||||
|
||||
const ItalianHoliday({
|
||||
required this.day,
|
||||
required this.month,
|
||||
required this.label,
|
||||
});
|
||||
|
||||
/// Verifica se una determinata data corrisponde alla festività fissa
|
||||
bool matches(DateTime date) => date.day == day && date.month == month;
|
||||
}
|
||||
|
||||
/// Helper per determinare se un giorno è lavorativo ed effettuare il conteggio dei giorni
|
||||
class WorkingDaysHelper {
|
||||
WorkingDaysHelper._();
|
||||
|
||||
/// Verifica se la data è domenica o festività nazionale italiana (fissa o Pasquetta)
|
||||
static bool isWorkingDay(DateTime date) {
|
||||
// 1. Domenica esclusa
|
||||
if (date.weekday == DateTime.sunday) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. Festività fisse
|
||||
for (final holiday in ItalianHoliday.values) {
|
||||
if (holiday.matches(date)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pasquetta (Lunedì dell'Angelo)
|
||||
final easterMonday = calculateEasterMonday(date.year);
|
||||
if (date.year == easterMonday.year &&
|
||||
date.month == easterMonday.month &&
|
||||
date.day == easterMonday.day) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Calcola la data del Lunedì dell'Angelo (Pasquetta) tramite l'algoritmo di Meeus/Jones/Butcher
|
||||
static DateTime calculateEasterMonday(int year) {
|
||||
final a = year % 19;
|
||||
final b = year ~/ 100;
|
||||
final c = year % 100;
|
||||
final d = b ~/ 4;
|
||||
final e = b % 4;
|
||||
final f = (b + 8) ~/ 25;
|
||||
final g = (b - f + 1) ~/ 3;
|
||||
final h = (19 * a + b - d - g + 15) % 30;
|
||||
final i = c ~/ 4;
|
||||
final k = c % 4;
|
||||
final l = (32 + 2 * e + 2 * i - h - k) % 7;
|
||||
final m = (a + 11 * h + 22 * l) ~/ 451;
|
||||
final month = (h + l - 7 * m + 114) ~/ 31;
|
||||
final day = ((h + l - 7 * m + 114) % 31) + 1;
|
||||
|
||||
final easterSunday = DateTime(year, month, day);
|
||||
// Pasquetta è il giorno successivo a Pasqua
|
||||
return easterSunday.add(const Duration(days: 1));
|
||||
}
|
||||
|
||||
/// Conta i giorni lavorativi compresi tra [start] e [end] (inclusi)
|
||||
static int countWorkingDays(DateTime start, DateTime end) {
|
||||
if (start.isAfter(end)) return 0;
|
||||
|
||||
int count = 0;
|
||||
DateTime current = DateTime(start.year, start.month, start.day);
|
||||
final targetEnd = DateTime(end.year, end.month, end.day);
|
||||
|
||||
while (!current.isAfter(targetEnd)) {
|
||||
if (isWorkingDay(current)) {
|
||||
count++;
|
||||
}
|
||||
current = current.add(const Duration(days: 1));
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// Calcola la ripartizione dei giorni lavorativi per un periodo target:
|
||||
/// - [total]: giorni lavorativi totali del periodo
|
||||
/// - [elapsed]: giorni lavorativi trascorsi fino ad oggi (minimo 1 se il periodo è iniziato)
|
||||
/// - [remaining]: giorni lavorativi rimanenti da oggi (incluso oggi se è giorno lavorativo) a fine periodo
|
||||
static ({int total, int elapsed, int remaining}) calculateWorkingDaysPeriod({
|
||||
required DateTime start,
|
||||
required DateTime end,
|
||||
DateTime? now,
|
||||
}) {
|
||||
final today = now ?? DateTime.now();
|
||||
final cleanToday = DateTime(today.year, today.month, today.day);
|
||||
final cleanStart = DateTime(start.year, start.month, start.day);
|
||||
final cleanEnd = DateTime(end.year, end.month, end.day);
|
||||
|
||||
final total = countWorkingDays(cleanStart, cleanEnd);
|
||||
|
||||
// Se siamo prima dell'inizio del periodo
|
||||
if (cleanToday.isBefore(cleanStart)) {
|
||||
return (total: total, elapsed: 0, remaining: total);
|
||||
}
|
||||
|
||||
// Se siamo oltre la fine del periodo
|
||||
if (cleanToday.isAfter(cleanEnd)) {
|
||||
return (total: total, elapsed: total, remaining: 0);
|
||||
}
|
||||
|
||||
// Siamo all'interno del periodo
|
||||
// Giorni trascorsi: dall'inizio fino a oggi
|
||||
final elapsedDays = countWorkingDays(cleanStart, cleanToday);
|
||||
final remainingDays = countWorkingDays(cleanToday, cleanEnd);
|
||||
|
||||
return (
|
||||
total: total > 0 ? total : 1,
|
||||
elapsed: elapsedDays > 0 ? elapsedDays : 1,
|
||||
remaining: remainingDays > 0 ? remainingDays : 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/utils/update_prompt_helper.dart';
|
||||
import 'package:flux/core/utils/version_check_service.dart';
|
||||
|
||||
class AppVersionLabel extends StatefulWidget {
|
||||
final bool isCollapsed;
|
||||
final bool showIcon;
|
||||
|
||||
const AppVersionLabel({
|
||||
super.key,
|
||||
this.isCollapsed = false,
|
||||
this.showIcon = true,
|
||||
});
|
||||
|
||||
@override
|
||||
State<AppVersionLabel> createState() => _AppVersionLabelState();
|
||||
}
|
||||
|
||||
class _AppVersionLabelState extends State<AppVersionLabel> {
|
||||
String _version = "";
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadVersion();
|
||||
}
|
||||
|
||||
Future<void> _loadVersion() async {
|
||||
final v = await VersionCheckService.getShortVersionString();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_version = v;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_version.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final textMuted = theme.colorScheme.onSurface.withValues(alpha: 0.5);
|
||||
|
||||
if (widget.isCollapsed) {
|
||||
return Tooltip(
|
||||
message: "Flux $_version\nClicca per verificare aggiornamenti",
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
|
||||
child: Container(
|
||||
height: 36,
|
||||
width: 36,
|
||||
alignment: Alignment.center,
|
||||
child: Icon(
|
||||
Icons.info_outline,
|
||||
size: 16,
|
||||
color: textMuted,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Tooltip(
|
||||
message: "Clicca per verificare se ci sono aggiornamenti",
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
onTap: () => UpdatePromptHelper.showManualUpdateCheck(context),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (widget.showIcon) ...[
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 13,
|
||||
color: textMuted,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
],
|
||||
Text(
|
||||
"Flux $_version",
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: textMuted,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: textMuted.withValues(alpha: 0.4),
|
||||
decorationStyle: TextDecorationStyle.dotted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -19,84 +19,119 @@ class QrUploadDialog extends StatelessWidget {
|
||||
// Usiamo i colori del tema per renderlo coerente col tuo design
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocListener<AttachmentsBloc, AttachmentsState>(
|
||||
listener: (context, state) {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
|
||||
listenWhen: (previous, current) =>
|
||||
previous.allFiles.length < current.allFiles.length,
|
||||
child: AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.qr_code_scanner,
|
||||
size: 48,
|
||||
color: theme.colorScheme.primary,
|
||||
listener: (context, state) {
|
||||
final newCount = state.allFiles.length;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'File caricato con successo via QR Code! 📄 ($newCount allegati in totale)',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
height: 400,
|
||||
width: 350,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min, // Fondamentale per i dialog
|
||||
children: [
|
||||
const Text(
|
||||
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors
|
||||
.white, // Lo sfondo bianco salva la vita sui temi scuri
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
duration: const Duration(seconds: 2),
|
||||
backgroundColor: Colors.green.shade700,
|
||||
),
|
||||
);
|
||||
},
|
||||
builder: (context, state) {
|
||||
final fileCount = state.allFiles.length;
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.qr_code_scanner,
|
||||
size: 48,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
height: 400,
|
||||
width: 350,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min, // Fondamentale per i dialog
|
||||
children: [
|
||||
const Text(
|
||||
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
child: QrImageView(
|
||||
data: deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 200.0,
|
||||
//Opzionale: puoi metterci il logo di FLUX in mezzo!
|
||||
embeddedImage: const AssetImage('assets/images/logo.png'),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors
|
||||
.white, // Lo sfondo bianco salva la vita sui temi scuri
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: QrImageView(
|
||||
data: deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 200.0,
|
||||
embeddedImage: const AssetImage(
|
||||
'assets/images/logo.png',
|
||||
),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
"In attesa di file...",
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
fileCount > 0
|
||||
? Icons.check_circle_outline
|
||||
: Icons.hourglass_empty,
|
||||
size: 18,
|
||||
color: fileCount > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
fileCount > 0
|
||||
? "$fileCount file ricevuti! (In ascolto...)"
|
||||
: "In attesa di file...",
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: fileCount > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.commonClose),
|
||||
),
|
||||
],
|
||||
actionsAlignment: MainAxisAlignment.center,
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.commonClose),
|
||||
),
|
||||
],
|
||||
actionsAlignment: MainAxisAlignment.center,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
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/utils/extensions.dart';
|
||||
import 'package:flux/core/widgets/flux_text_field.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class SetPasswordScreen extends StatefulWidget {
|
||||
const SetPasswordScreen({super.key});
|
||||
|
||||
@override
|
||||
State<SetPasswordScreen> createState() => _SetPasswordScreenState();
|
||||
}
|
||||
|
||||
class _SetPasswordScreenState extends State<SetPasswordScreen> {
|
||||
final _passwordCtrl = TextEditingController();
|
||||
bool _isLoading = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_passwordCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _savePassword() async {
|
||||
final newPassword = _passwordCtrl.text.trim();
|
||||
if (newPassword.length < 6) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.setPasswordScreenAtLeast6Chars)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _isLoading = true);
|
||||
|
||||
try {
|
||||
// 1. Aggiorniamo la password dell'utente (che Supabase ha già loggato grazie al link della mail)
|
||||
await GetIt.I.get<SupabaseClient>().auth.updateUser(
|
||||
UserAttributes(password: newPassword),
|
||||
);
|
||||
|
||||
// 2. Finito! Lo mandiamo alla home o facciamo ricaricare la sessione al SessionCubit
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.setPasswordScreenPasswordSetWelcome),
|
||||
),
|
||||
);
|
||||
context.go('/'); // Rimandiamo al router principale
|
||||
}
|
||||
} on AuthException catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.authError(e.message))),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.commonError(e.toString()))),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(context.l10n.setPasswordScreenWelcomeInFlux),
|
||||
automaticallyImplyLeading:
|
||||
false, // Non può tornare indietro, deve mettere la password!
|
||||
actions: [
|
||||
IconButton.filled(
|
||||
onPressed: () => context.read<SessionCubit>().signOut(),
|
||||
icon: Icon(Icons.logout),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Icon(Icons.lock_reset, size: 80, color: Colors.blueAccent),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
context.l10n.setPasswordScreenSetPassword,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
context.l10n.setPasswordInviteAcceptedChoosePassword,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
FluxTextField(
|
||||
controller: _passwordCtrl,
|
||||
label: context.l10n.commonNewPassword,
|
||||
icon: Icons.lock,
|
||||
isPassword: true,
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
ElevatedButton(
|
||||
onPressed: _isLoading ? null : _savePassword,
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
),
|
||||
child: _isLoading
|
||||
? const CircularProgressIndicator(color: Colors.white)
|
||||
: Text(
|
||||
context.l10n.setPasswordScreenSaveAndStart,
|
||||
style: TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,14 +34,14 @@ class SharedAttachmentsSection extends StatefulWidget {
|
||||
final String? parentId;
|
||||
final String titleForUpload;
|
||||
final AttachmentParentType parentType;
|
||||
final Future<String?> Function()? onGenerateIdForQr;
|
||||
final Future<String?> Function()? onEnsureEntitySaved;
|
||||
|
||||
const SharedAttachmentsSection({
|
||||
super.key,
|
||||
this.parentId,
|
||||
this.titleForUpload = 'Cliente_sconosciuto',
|
||||
required this.parentType,
|
||||
this.onGenerateIdForQr,
|
||||
this.onEnsureEntitySaved,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -56,6 +56,24 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadExportDirectory();
|
||||
_syncParentIdIfNeeded();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant SharedAttachmentsSection oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.parentId != oldWidget.parentId) {
|
||||
_syncParentIdIfNeeded();
|
||||
}
|
||||
}
|
||||
|
||||
void _syncParentIdIfNeeded() {
|
||||
if (widget.parentId != null && widget.parentId!.isNotEmpty) {
|
||||
final attachmentsBloc = context.read<AttachmentsBloc>();
|
||||
if (attachmentsBloc.state.parentId != widget.parentId) {
|
||||
attachmentsBloc.add(ParentEntitySavedEvent(widget.parentId!));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- GESTIONE CARTELLA CITRIX (SOLO DESKTOP) ---
|
||||
@@ -90,6 +108,29 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
|
||||
// --- SELEZIONE FILE DAL PC/TELEFONO ---
|
||||
Future<void> _pickFiles() async {
|
||||
final attachmentsBloc = context.read<AttachmentsBloc>();
|
||||
String? targetId = attachmentsBloc.state.parentId ?? widget.parentId;
|
||||
|
||||
// 🥷 SE L'ID NON C'È (Nuova Operazione), PROVIAMO IL SALVATAGGIO PREVENTIVO
|
||||
if (targetId == null || targetId.isEmpty) {
|
||||
if (widget.onEnsureEntitySaved != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Salvataggio rapido scheda per allegati... ⏳'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
|
||||
targetId = await widget.onEnsureEntitySaved!();
|
||||
}
|
||||
}
|
||||
|
||||
if (targetId != null &&
|
||||
targetId.isNotEmpty &&
|
||||
attachmentsBloc.state.parentId != targetId) {
|
||||
attachmentsBloc.add(ParentEntitySavedEvent(targetId));
|
||||
}
|
||||
|
||||
final result = await FilePicker.pickFiles(
|
||||
allowMultiple: true,
|
||||
type: FileType.custom,
|
||||
@@ -97,29 +138,180 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
withData: true,
|
||||
);
|
||||
|
||||
if (result != null && mounted) {
|
||||
// MAGIA: Passiamo direttamente la lista di PlatformFile al tuo BLoC!
|
||||
context.read<AttachmentsBloc>().add(AddAttachmentsEvent(result.files));
|
||||
if (result == null || result.files.isEmpty || !mounted) return;
|
||||
|
||||
final List<PlatformFile> processedFiles = [];
|
||||
|
||||
for (int i = 0; i < result.files.length; i++) {
|
||||
final file = result.files[i];
|
||||
|
||||
Widget previewWidget;
|
||||
final ext = file.extension?.toLowerCase() ?? '';
|
||||
|
||||
if ((ext == 'jpg' || ext == 'jpeg' || ext == 'png') &&
|
||||
file.bytes != null) {
|
||||
previewWidget = Image.memory(file.bytes!, fit: BoxFit.contain);
|
||||
} else if (ext == 'pdf') {
|
||||
previewWidget = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
} else {
|
||||
previewWidget = const Center(
|
||||
child: Icon(Icons.insert_drive_file, size: 80, color: Colors.blue),
|
||||
);
|
||||
}
|
||||
|
||||
final rawOriginalName =
|
||||
file.name.contains('.')
|
||||
? file.name.substring(0, file.name.lastIndexOf('.'))
|
||||
: file.name;
|
||||
|
||||
final defaultSuggested =
|
||||
result.files.length == 1
|
||||
? widget.titleForUpload
|
||||
: '${widget.titleForUpload}_${i + 1}';
|
||||
|
||||
final finalName = await showDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder:
|
||||
(_) => QuickRenameDialog(
|
||||
title:
|
||||
result.files.length == 1
|
||||
? 'Nome Allegato'
|
||||
: 'Nome Allegato (${i + 1}/${result.files.length})',
|
||||
suggestedName:
|
||||
defaultSuggested.isNotEmpty
|
||||
? defaultSuggested
|
||||
: rawOriginalName,
|
||||
suffixText: ext.isNotEmpty ? '.$ext' : null,
|
||||
confirmButtonText: 'Importa (Invio)',
|
||||
previewWidget: previewWidget,
|
||||
),
|
||||
);
|
||||
|
||||
if (finalName != null && finalName.trim().isNotEmpty) {
|
||||
final cleanName = finalName.trim();
|
||||
final extString = ext.isNotEmpty ? '.$ext' : '';
|
||||
final fullNewName =
|
||||
cleanName.endsWith(extString) ? cleanName : '$cleanName$extString';
|
||||
|
||||
final updatedFile = PlatformFile(
|
||||
name: fullNewName,
|
||||
size: file.size,
|
||||
path: file.path,
|
||||
bytes: file.bytes,
|
||||
readStream: file.readStream,
|
||||
);
|
||||
processedFiles.add(updatedFile);
|
||||
} else {
|
||||
processedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (processedFiles.isEmpty || !mounted) return;
|
||||
|
||||
// 1. Aggiungiamo i file rinominati al BLoC
|
||||
attachmentsBloc.add(AddAttachmentsEvent(processedFiles));
|
||||
|
||||
// 2. Chiediamo se cancellare i file fisici dal computer
|
||||
if (!kIsWeb) {
|
||||
final filesOnDisk =
|
||||
processedFiles
|
||||
.where((f) => f.path != null && File(f.path!).existsSync())
|
||||
.toList();
|
||||
|
||||
if (filesOnDisk.isNotEmpty && mounted) {
|
||||
final shouldDelete = await showDialog<bool>(
|
||||
context: context,
|
||||
builder:
|
||||
(dialogContext) => AlertDialog(
|
||||
title: const Row(
|
||||
children: [
|
||||
Icon(Icons.delete_forever, color: Colors.red),
|
||||
SizedBox(width: 8),
|
||||
Text('Eliminare file dal computer?'),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
'I file (${filesOnDisk.length}) sono stati importati in Flux.\n\nVuoi cancellare i file originali dal tuo computer per liberare spazio?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('No, mantieni sul PC'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: const Text('Sì, elimina dal PC'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (shouldDelete == true) {
|
||||
int deletedCount = 0;
|
||||
for (var f in filesOnDisk) {
|
||||
try {
|
||||
final fileObj = File(f.path!);
|
||||
if (fileObj.existsSync()) {
|
||||
await fileObj.delete();
|
||||
deletedCount++;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Errore durante l\'eliminazione del file locale: $e');
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted && deletedCount > 0) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'$deletedCount file fisici eliminati dal computer.',
|
||||
),
|
||||
backgroundColor: Colors.orange.shade800,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- APERTURA VIEWER ---
|
||||
void _openFile(AttachmentModel file) {
|
||||
void _openFile(
|
||||
AttachmentModel file, {
|
||||
List<AttachmentModel>? files,
|
||||
int? initialIndex,
|
||||
}) {
|
||||
// 1. Catturiamo il BLoC dalla pagina corrente prima di navigare
|
||||
final operationFilesBloc = context.read<AttachmentsBloc>();
|
||||
final allFilesList = files ?? operationFilesBloc.state.allFiles;
|
||||
final index = initialIndex ??
|
||||
(allFilesList.isNotEmpty ? allFilesList.indexOf(file) : 0);
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (viewerContext) => BlocProvider.value(
|
||||
value: operationFilesBloc,
|
||||
child: AttachmentViewerScreen(
|
||||
attachment: file,
|
||||
onRename: (newName) {
|
||||
attachments: allFilesList.isNotEmpty ? allFilesList : [file],
|
||||
initialIndex: index >= 0 ? index : 0,
|
||||
onRenameAttachment: (targetFile, newName) {
|
||||
// Spara l'evento al BLoC e lui farà il resto!
|
||||
operationFilesBloc.add(RenameAttachmentEvent(file, newName));
|
||||
operationFilesBloc.add(
|
||||
RenameAttachmentEvent(targetFile, newName),
|
||||
);
|
||||
},
|
||||
onDelete: () {
|
||||
operationFilesBloc.add(DeleteSpecificAttachmentEvent(file));
|
||||
onDeleteAttachment: (targetFile) {
|
||||
operationFilesBloc.add(
|
||||
DeleteSpecificAttachmentEvent(targetFile),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -477,11 +669,11 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
icon: const Icon(Icons.qr_code_scanner),
|
||||
color: theme.colorScheme.primary, // Sempre colorato!
|
||||
onPressed: () async {
|
||||
String? targetId = state.parentId;
|
||||
String? targetId = state.parentId ?? widget.parentId;
|
||||
|
||||
// SE L'ID NON C'È, CHIAMIAMO IL SALVATAGGIO IN BACKGROUND!
|
||||
if (targetId == null) {
|
||||
if (widget.onGenerateIdForQr != null) {
|
||||
if (targetId == null || targetId.isEmpty) {
|
||||
if (widget.onEnsureEntitySaved != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
@@ -491,12 +683,29 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
),
|
||||
);
|
||||
|
||||
// Aspettiamo che il TicketFormCubit faccia il suo lavoro
|
||||
targetId = await widget.onGenerateIdForQr!();
|
||||
targetId = await widget.onEnsureEntitySaved!();
|
||||
}
|
||||
}
|
||||
|
||||
// Se fallisce (es. validazione form non passata), ci fermiamo
|
||||
if (targetId == null) return;
|
||||
if (targetId == null || targetId.isEmpty) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Salva la scheda prima di generare il QR Code per gli allegati.',
|
||||
),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.mounted) return;
|
||||
|
||||
final attachmentBloc = context.read<AttachmentsBloc>();
|
||||
if (attachmentBloc.state.parentId != targetId) {
|
||||
attachmentBloc.add(ParentEntitySavedEvent(targetId));
|
||||
}
|
||||
|
||||
// GENERAZIONE DEL DEEP LINK AGNOSTICO
|
||||
@@ -509,8 +718,6 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
'https://flux.catelli.it/upload/${state.parentType.name}/$targetId?companyId=$companyId';
|
||||
|
||||
if (context.mounted) {
|
||||
final attachmentBloc = context.read<AttachmentsBloc>();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (_) => BlocProvider.value(
|
||||
@@ -696,7 +903,11 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
children: [
|
||||
// CARD DEL FILE
|
||||
InkWell(
|
||||
onTap: () => _openFile(file),
|
||||
onTap: () => _openFile(
|
||||
file,
|
||||
files: allFiles,
|
||||
initialIndex: index,
|
||||
),
|
||||
onLongPress: () {
|
||||
// Selezione rapida con long press!
|
||||
context.read<AttachmentsBloc>().add(
|
||||
|
||||
@@ -202,6 +202,57 @@ class SharedCustomerSection extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
// --- RIGA CODICE FISCALE ---
|
||||
if (customer!.fiscalCode != null &&
|
||||
customer!.fiscalCode!.isNotEmpty) ...[
|
||||
const Divider(height: 8, thickness: 0.5),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed:
|
||||
null, // Rimosso il // dopo mailto:, è più sicuro
|
||||
icon: const Icon(
|
||||
Icons.person_outline,
|
||||
color: Colors.green,
|
||||
size: 20,
|
||||
),
|
||||
tooltip: 'Codice Fiscale',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
// L'Expanded è vitale per le email che possono essere lunghissime
|
||||
child: SelectableText(
|
||||
customer!.fiscalCode!,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () {
|
||||
Clipboard.setData(
|
||||
ClipboardData(text: customer!.fiscalCode!),
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Codice Fiscale copiato!'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.copy,
|
||||
size: 18,
|
||||
color: Colors.grey,
|
||||
),
|
||||
tooltip: 'Copia',
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
@@ -14,7 +16,6 @@ part 'attachments_state.dart';
|
||||
|
||||
class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
final _repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final String? companyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
|
||||
AttachmentsBloc({String? parentId, required AttachmentParentType parentType})
|
||||
: super(
|
||||
@@ -36,8 +37,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
on<SelectAllAttachmentsEvent>(_onSelectAllAttachments);
|
||||
on<ClearAttachmentSelectionEvent>(_onClearAttachmentSelection);
|
||||
|
||||
// Se il BLoC nasce già con un ID, carichiamo i file
|
||||
if (parentId != null && companyId != null) {
|
||||
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
if (parentId != null && currentCompanyId != null) {
|
||||
add(LoadAttachmentsEvent(parentId: parentId));
|
||||
}
|
||||
}
|
||||
@@ -46,6 +47,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
ParentEntitySavedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
final companyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
parentId: event.newParentId,
|
||||
@@ -117,14 +120,30 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
final currentId = state.parentId;
|
||||
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale)
|
||||
if (currentCompanyId == null) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.failure,
|
||||
error: "Company ID non trovato nella sessione",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
|
||||
if (currentId == null) {
|
||||
final newLocalFiles = event.files.map((file) {
|
||||
// Assegniamo i campi dinamicamente in base al parentType!
|
||||
// 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();
|
||||
}
|
||||
|
||||
return AttachmentModel(
|
||||
id: null,
|
||||
companyId: companyId!,
|
||||
companyId: currentCompanyId,
|
||||
operationId: state.parentType == AttachmentParentType.operation
|
||||
? ''
|
||||
: null,
|
||||
@@ -136,7 +155,7 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: file.bytes,
|
||||
localBytes: rawBytes, // Ora i byte ci sono al 100% anche su Mac!
|
||||
);
|
||||
}).toList();
|
||||
|
||||
@@ -157,7 +176,7 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
parentId: currentId,
|
||||
parentType: state.parentType,
|
||||
pickedFile: file,
|
||||
companyId: companyId!,
|
||||
companyId: currentCompanyId,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
@@ -1,110 +1,191 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flux/core/utils/functions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:pdfx/pdfx.dart';
|
||||
import 'package:internet_file/internet_file.dart';
|
||||
|
||||
class AttachmentViewerScreen extends StatefulWidget {
|
||||
final AttachmentModel attachment;
|
||||
final AttachmentModel? attachment;
|
||||
final List<AttachmentModel>? attachments;
|
||||
final int initialIndex;
|
||||
final Function(String newName)? onRename;
|
||||
final Function(AttachmentModel attachment, String newName)? onRenameAttachment;
|
||||
final VoidCallback? onDelete;
|
||||
final Function(AttachmentModel attachment)? onDeleteAttachment;
|
||||
|
||||
const AttachmentViewerScreen({
|
||||
super.key,
|
||||
required this.attachment,
|
||||
this.attachment,
|
||||
this.attachments,
|
||||
this.initialIndex = 0,
|
||||
this.onRename,
|
||||
this.onRenameAttachment,
|
||||
this.onDelete,
|
||||
});
|
||||
this.onDeleteAttachment,
|
||||
}) : assert(
|
||||
attachment != null || (attachments != null && attachments.length > 0),
|
||||
'Devi fornire un allegato o una lista di allegati non vuota.',
|
||||
);
|
||||
|
||||
@override
|
||||
State<AttachmentViewerScreen> createState() => _AttachmentViewerScreenState();
|
||||
}
|
||||
|
||||
class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
late List<AttachmentModel> _items;
|
||||
late int _currentIndex;
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
PdfControllerPinch? _pdfController;
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
Uint8List? _fileBytes;
|
||||
late String _fileName;
|
||||
int _loadToken = 0;
|
||||
|
||||
bool get isPdf => widget.attachment.extension.toLowerCase() == 'pdf';
|
||||
AttachmentModel get _currentAttachment => _items[_currentIndex];
|
||||
bool get isPdf =>
|
||||
_currentAttachment.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
bool get hasMultipleFiles => _items.length > 1;
|
||||
bool get canGoPrevious => _currentIndex > 0;
|
||||
bool get canGoNext => _currentIndex < _items.length - 1;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_fileName = widget.attachment.name;
|
||||
_loadFile();
|
||||
}
|
||||
|
||||
Future<void> _loadFile() async {
|
||||
try {
|
||||
// 1. Capiamo da dove prendere i dati
|
||||
if (widget.attachment.localBytes != null) {
|
||||
_fileBytes = widget.attachment.localBytes;
|
||||
} else if (widget.attachment.storagePath != null &&
|
||||
widget.attachment.storagePath!.isNotEmpty) {
|
||||
final signedUrl = await getSignedUrl(widget.attachment.storagePath!);
|
||||
_fileBytes = await InternetFile.get(signedUrl);
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
}
|
||||
|
||||
// 2. Se è PDF, inizializziamo il controller
|
||||
if (isPdf && _fileBytes != null) {
|
||||
_pdfController = PdfControllerPinch(
|
||||
document: PdfDocument.openData(_fileBytes!),
|
||||
);
|
||||
}
|
||||
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
}
|
||||
if (widget.attachments != null && widget.attachments!.isNotEmpty) {
|
||||
_items = List<AttachmentModel>.from(widget.attachments!);
|
||||
_currentIndex = widget.initialIndex.clamp(0, _items.length - 1);
|
||||
} else if (widget.attachment != null) {
|
||||
_items = [widget.attachment!];
|
||||
_currentIndex = 0;
|
||||
} else {
|
||||
_items = [];
|
||||
_currentIndex = 0;
|
||||
}
|
||||
|
||||
_loadFile();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
_focusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focusNode.dispose();
|
||||
_pdfController?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _goToPrevious() {
|
||||
if (!canGoPrevious) return;
|
||||
_changeFile(_currentIndex - 1);
|
||||
}
|
||||
|
||||
void _goToNext() {
|
||||
if (!canGoNext) return;
|
||||
_changeFile(_currentIndex + 1);
|
||||
}
|
||||
|
||||
void _changeFile(int newIndex) {
|
||||
if (newIndex < 0 || newIndex >= _items.length) return;
|
||||
_pdfController?.dispose();
|
||||
_pdfController = null;
|
||||
setState(() {
|
||||
_currentIndex = newIndex;
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
_fileBytes = null;
|
||||
});
|
||||
_loadFile();
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyDownEvent) {
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
|
||||
if (canGoPrevious) {
|
||||
_goToPrevious();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
} else if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
|
||||
if (canGoNext) {
|
||||
_goToNext();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Future<void> _loadFile() async {
|
||||
final token = ++_loadToken;
|
||||
final item = _currentAttachment;
|
||||
|
||||
try {
|
||||
Uint8List? bytes;
|
||||
if (item.localBytes != null) {
|
||||
bytes = item.localBytes;
|
||||
} else if (item.storagePath != null &&
|
||||
item.storagePath!.isNotEmpty) {
|
||||
final signedUrl = await getSignedUrl(item.storagePath!);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
}
|
||||
|
||||
if (token != _loadToken || !mounted) return;
|
||||
|
||||
PdfControllerPinch? controller;
|
||||
if (isPdf && bytes != null) {
|
||||
controller = PdfControllerPinch(
|
||||
document: PdfDocument.openData(bytes),
|
||||
);
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_fileBytes = bytes;
|
||||
_pdfController = controller;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (token != _loadToken || !mounted) return;
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _showRenameDialog() {
|
||||
final ctrl = TextEditingController(text: _fileName);
|
||||
final current = _currentAttachment;
|
||||
final ctrl = TextEditingController(text: current.name);
|
||||
ctrl.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: ctrl.text.length,
|
||||
);
|
||||
final focusNode = FocusNode();
|
||||
final dialogFocusNode = FocusNode();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => focusNode.requestFocus(),
|
||||
(_) => dialogFocusNode.requestFocus(),
|
||||
);
|
||||
return AlertDialog(
|
||||
title: const Text('Rinomina File'),
|
||||
content: TextField(
|
||||
controller: ctrl,
|
||||
focusNode: focusNode,
|
||||
focusNode: dialogFocusNode,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nuovo nome',
|
||||
suffixText: '.${widget.attachment.extension}',
|
||||
suffixText: '.${current.extension}',
|
||||
),
|
||||
onSubmitted: (val) {
|
||||
Navigator.pop(context);
|
||||
if (val.trim().isNotEmpty && widget.onRename != null) {
|
||||
setState(() {
|
||||
_fileName = val.trim();
|
||||
});
|
||||
widget.onRename!(val.trim());
|
||||
}
|
||||
_applyRename(val);
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
@@ -115,73 +196,141 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
if (ctrl.text.trim().isNotEmpty && widget.onRename != null) {
|
||||
setState(() {
|
||||
_fileName = ctrl.text.trim();
|
||||
});
|
||||
widget.onRename!(ctrl.text.trim());
|
||||
}
|
||||
_applyRename(ctrl.text);
|
||||
},
|
||||
child: const Text('Salva'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
).then((_) {
|
||||
if (mounted) {
|
||||
_focusNode.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _applyRename(String val) {
|
||||
final trimmed = val.trim();
|
||||
if (trimmed.isEmpty) return;
|
||||
final current = _currentAttachment;
|
||||
final updated = current.copyWith(name: trimmed);
|
||||
setState(() {
|
||||
_items[_currentIndex] = updated;
|
||||
});
|
||||
widget.onRenameAttachment?.call(current, trimmed);
|
||||
widget.onRename?.call(trimmed);
|
||||
}
|
||||
|
||||
void _confirmDelete() {
|
||||
final current = _currentAttachment;
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Eliminare file?'),
|
||||
content: const Text(
|
||||
'Sei sicuro di voler eliminare questo allegato?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(c); // Chiude dialog
|
||||
widget.onDeleteAttachment?.call(current);
|
||||
widget.onDelete?.call();
|
||||
Navigator.pop(context); // Chiude il viewer
|
||||
},
|
||||
child: const Text('Elimina'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black87, // Sfondo scuro per i viewer è il top
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
title: Text(_fileName, style: const TextStyle(fontSize: 16)),
|
||||
actions: [
|
||||
if (widget.onRename != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
tooltip: 'Rinomina',
|
||||
onPressed: _showRenameDialog,
|
||||
return Focus(
|
||||
focusNode: _focusNode,
|
||||
autofocus: true,
|
||||
onKeyEvent: _handleKeyEvent,
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.black87,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_currentAttachment.name,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (hasMultipleFiles)
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
if (widget.onRename != null || widget.onRenameAttachment != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
tooltip: 'Rinomina',
|
||||
onPressed: _showRenameDialog,
|
||||
),
|
||||
if (widget.onDelete != null || widget.onDeleteAttachment != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.redAccent),
|
||||
tooltip: 'Elimina',
|
||||
onPressed: _confirmDelete,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: _buildBody(),
|
||||
),
|
||||
if (widget.onDelete != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.redAccent),
|
||||
tooltip: 'Elimina',
|
||||
onPressed: () {
|
||||
// Chiediamo conferma
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Eliminare file?'),
|
||||
content: const Text(
|
||||
'Sei sicuro di voler eliminare questo allegato?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(c); // Chiude dialog
|
||||
widget.onDelete!(); // Lancia eliminazione
|
||||
Navigator.pop(context); // Chiude il viewer
|
||||
},
|
||||
child: const Text('Elimina'),
|
||||
),
|
||||
],
|
||||
// Freccia Precedente
|
||||
if (hasMultipleFiles && canGoPrevious)
|
||||
Positioned(
|
||||
left: 16,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: _NavigationArrowButton(
|
||||
icon: Icons.arrow_back_ios_new_rounded,
|
||||
tooltip: 'File precedente (←)',
|
||||
onPressed: _goToPrevious,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Freccia Successivo
|
||||
if (hasMultipleFiles && canGoNext)
|
||||
Positioned(
|
||||
right: 16,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: _NavigationArrowButton(
|
||||
icon: Icons.arrow_forward_ios_rounded,
|
||||
tooltip: 'File successivo (→)',
|
||||
onPressed: _goToNext,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: _buildBody(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -218,3 +367,41 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _NavigationArrowButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String tooltip;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
const _NavigationArrowButton({
|
||||
required this.icon,
|
||||
required this.tooltip,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Tooltip(
|
||||
message: tooltip,
|
||||
child: Material(
|
||||
color: Colors.black.withValues(alpha: 0.55),
|
||||
shape: const CircleBorder(),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
elevation: 6,
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
hoverColor: Colors.white.withValues(alpha: 0.2),
|
||||
splashColor: Colors.white.withValues(alpha: 0.3),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: Colors.white,
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,17 @@ import 'package:flutter/material.dart';
|
||||
class QuickRenameDialog extends StatefulWidget {
|
||||
final String suggestedName;
|
||||
final Widget previewWidget; // Può essere Image.memory o un'icona PDF
|
||||
final String title;
|
||||
final String? suffixText;
|
||||
final String confirmButtonText;
|
||||
|
||||
const QuickRenameDialog({
|
||||
super.key,
|
||||
required this.suggestedName,
|
||||
required this.previewWidget,
|
||||
this.title = 'Rinomina File',
|
||||
this.suffixText = '.pdf',
|
||||
this.confirmButtonText = 'Conferma (Invio)',
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -45,7 +51,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Rinomina per Export'),
|
||||
title: Text(widget.title),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -60,10 +66,10 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
TextField(
|
||||
controller: _nameCtrl,
|
||||
focusNode: _focusNode,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nome del file',
|
||||
suffixText: '.pdf', // Facciamo capire che sarà un PDF
|
||||
border: OutlineInputBorder(),
|
||||
suffixText: widget.suffixText,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
// MAGIA UX 2: Se preme invio sulla tastiera, salva e chiude!
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
@@ -77,7 +83,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.of(context).pop(_nameCtrl.text),
|
||||
child: const Text('Esporta (Invio)'),
|
||||
child: Text(widget.confirmButtonText),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/core/utils/app_message.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
part 'auth_state.dart';
|
||||
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final _supabase = GetIt.instance<SupabaseClient>();
|
||||
final _staffRepository = GetIt.instance<StaffRepository>();
|
||||
|
||||
AuthCubit() : super(const AuthState());
|
||||
|
||||
@@ -95,10 +96,7 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _supabase.auth.resetPasswordForEmail(
|
||||
email,
|
||||
redirectTo: resetPasswordUrl,
|
||||
);
|
||||
await _staffRepository.resetPassword(email);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AuthStatus.pwResetSent,
|
||||
|
||||
@@ -128,6 +128,30 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
_submit(), // Se lo supporti nel tuo widget custom
|
||||
),
|
||||
|
||||
// Link "Dimenticato password?" solo in Login mode
|
||||
if (state.isLoginMode) ...[
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: isLoading
|
||||
? null
|
||||
: () => context
|
||||
.read<AuthCubit>()
|
||||
.requestPasswordReset(
|
||||
_emailController.text.trim(),
|
||||
),
|
||||
child: Text(
|
||||
context.l10n.authScreenForgotPassword,
|
||||
style: TextStyle(
|
||||
color: context.accent,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// --- BOTTONE PRINCIPALE ---
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/main.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class SetPasswordScreen extends StatefulWidget {
|
||||
const SetPasswordScreen({super.key});
|
||||
|
||||
@override
|
||||
State<SetPasswordScreen> createState() => _SetPasswordScreenState();
|
||||
}
|
||||
|
||||
class _SetPasswordScreenState extends State<SetPasswordScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _passwordController = TextEditingController();
|
||||
final _confirmPasswordController = TextEditingController();
|
||||
bool _isLoading = false;
|
||||
bool _obscurePassword = true;
|
||||
String? _errorMessage;
|
||||
|
||||
// Variabile per abilitare l'inserimento
|
||||
bool _isSessionReady = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_forceSessionRecovery();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_passwordController.dispose();
|
||||
_confirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// 🎯 LA VERA MAGIA: RICOSTRUIAMO LA SESSIONE A MANO
|
||||
Future<void> _forceSessionRecovery() async {
|
||||
try {
|
||||
// 1. Prendiamo il frammento dalla cassaforte
|
||||
final fragment = initialRecoveryFragment ?? Uri.base.fragment;
|
||||
|
||||
if (fragment.contains('access_token=')) {
|
||||
// 2. Dividiamo la stringa in una mappa chiave:valore
|
||||
final params = Uri.splitQueryString(fragment);
|
||||
final refreshToken = params['refresh_token'];
|
||||
|
||||
if (refreshToken != null) {
|
||||
// 3. Forziamo Supabase a loggare l'utente col refresh token!
|
||||
await Supabase.instance.client.auth.setSession(refreshToken);
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSessionReady = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: se Supabase ce l'aveva già fatta miracolosamente
|
||||
if (Supabase.instance.client.auth.currentSession != null) {
|
||||
setState(() => _isSessionReady = true);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("Errore ripristino manuale sessione: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _submitNewPassword() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
if (!_isSessionReady) {
|
||||
setState(() {
|
||||
_errorMessage =
|
||||
"Sincronizzazione di sicurezza fallita. Il link potrebbe essere scaduto.";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
// Ora questo updateUser troverà la sessione viva e vegeta!
|
||||
await Supabase.instance.client.auth.updateUser(
|
||||
UserAttributes(password: _passwordController.text.trim()),
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Password impostata con successo! Benvenuto in FLUX.',
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
context.go('/');
|
||||
}
|
||||
} on AuthException catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = e.message;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = "Si è verificato un errore imprevisto. Riprova.";
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Rendiamo la schermata responsive ed elegante per il Web (Cloudflare)
|
||||
final size = MediaQuery.of(context).size;
|
||||
final isWebContainer = size.width > 600;
|
||||
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Container(
|
||||
width: isWebContainer ? 450 : size.width,
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Logo o Brand FLUX
|
||||
Text(
|
||||
'FLUX',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: -1,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Configura la tua chiave di accesso per iniziare a collaborare.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.grey[600], fontSize: 14),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
if (_errorMessage != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: const TextStyle(color: Colors.red, fontSize: 13),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Campo Password
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nuova Password',
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePassword
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
),
|
||||
onPressed: () => setState(
|
||||
() => _obscurePassword = !_obscurePassword,
|
||||
),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Inserisci una password';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'La password deve avere almeno 6 caratteri';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Campo Conferma Password
|
||||
TextFormField(
|
||||
controller: _confirmPasswordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Conferma Password',
|
||||
prefixIcon: Icon(Icons.lock_reset_rounded),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value != _passwordController.text) {
|
||||
return 'Le password non coincidono';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Bottone di Invio
|
||||
ElevatedButton(
|
||||
onPressed: _isLoading ? null : _submitNewPassword,
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: _isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: const Text(
|
||||
'Conferma e Accedi',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
String? note,
|
||||
bool? doNotDisturb,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -79,6 +80,8 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
note: note ?? state.customer.note,
|
||||
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
|
||||
isBusiness: isBusiness ?? state.customer.isBusiness,
|
||||
fiscalCode:
|
||||
fiscalCode?.trim().toUpperCase() ?? state.customer.fiscalCode,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -111,6 +114,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
String? phone,
|
||||
String? email,
|
||||
required bool isBusiness,
|
||||
String? fiscalCode,
|
||||
}) async {
|
||||
final newCustomer = CustomerModel(
|
||||
name: name,
|
||||
@@ -119,6 +123,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
companyId: _sessionCubit.state.company!.id!,
|
||||
note: '',
|
||||
isBusiness: isBusiness,
|
||||
fiscalCode: fiscalCode?.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,7 @@ class CustomerModel extends Equatable {
|
||||
final bool isActive;
|
||||
final List<AttachmentModel> attachments;
|
||||
final bool isBusiness;
|
||||
final String? fiscalCode;
|
||||
|
||||
const CustomerModel({
|
||||
this.id,
|
||||
@@ -29,6 +30,7 @@ class CustomerModel extends Equatable {
|
||||
this.isActive = true,
|
||||
this.attachments = const [],
|
||||
this.isBusiness = false,
|
||||
this.fiscalCode,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -45,6 +47,7 @@ class CustomerModel extends Equatable {
|
||||
isActive,
|
||||
attachments,
|
||||
isBusiness,
|
||||
fiscalCode,
|
||||
];
|
||||
|
||||
factory CustomerModel.empty() => CustomerModel(
|
||||
@@ -69,6 +72,7 @@ class CustomerModel extends Equatable {
|
||||
bool? isActive,
|
||||
List<AttachmentModel>? attachments,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
return CustomerModel(
|
||||
id: id ?? this.id,
|
||||
@@ -83,6 +87,7 @@ class CustomerModel extends Equatable {
|
||||
isActive: isActive ?? this.isActive,
|
||||
attachments: attachments ?? this.attachments,
|
||||
isBusiness: isBusiness ?? this.isBusiness,
|
||||
fiscalCode: fiscalCode ?? this.fiscalCode,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -108,6 +113,7 @@ class CustomerModel extends Equatable {
|
||||
.toList() ??
|
||||
const [],
|
||||
isBusiness: map['is_business'] as bool? ?? false,
|
||||
fiscalCode: map['fiscal_code'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,6 +130,7 @@ class CustomerModel extends Equatable {
|
||||
'company_id': companyId,
|
||||
'is_active': isActive,
|
||||
'is_business': isBusiness,
|
||||
'fiscal_code': fiscalCode?.trim().toUpperCase(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/widgets/flux_text_field.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/attachments_section.dart';
|
||||
@@ -24,6 +25,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
final TextEditingController _telefonoController = TextEditingController();
|
||||
final TextEditingController _emailController = TextEditingController();
|
||||
final TextEditingController _noteController = TextEditingController();
|
||||
final TextEditingController _fiscalCodeController = TextEditingController();
|
||||
bool _isInitialized = false;
|
||||
|
||||
@override
|
||||
@@ -49,6 +51,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
_telefonoController.dispose();
|
||||
_emailController.dispose();
|
||||
_noteController.dispose();
|
||||
_fiscalCodeController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -65,6 +68,9 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
if (_noteController.text.isEmpty) {
|
||||
_noteController.text = customer.note;
|
||||
}
|
||||
if (_fiscalCodeController.text.isEmpty && customer.fiscalCode != null) {
|
||||
_fiscalCodeController.text = customer.fiscalCode!;
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
@@ -74,6 +80,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
phoneNumber: _telefonoController.text.trim(),
|
||||
email: _emailController.text.trim(),
|
||||
note: _noteController.text.trim(),
|
||||
fiscalCode: _fiscalCodeController.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -172,6 +179,20 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Partita IVA / Codice Fiscale',
|
||||
icon: Icons.person_outline,
|
||||
controller: _fiscalCodeController,
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(
|
||||
RegExp(r'[a-zA-Z0-9]'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Note',
|
||||
icon: Icons.notes_outlined,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
|
||||
|
||||
@@ -16,7 +17,8 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
final _phoneCtrl = TextEditingController();
|
||||
final _emailCtrl = TextEditingController();
|
||||
final _noteCtrl = TextEditingController();
|
||||
bool _isBusiness = false; // Aggiungiamo un campo per il tipo di cliente
|
||||
bool _isBusiness = false;
|
||||
final _fiscalCodeCtrl = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
@@ -33,6 +35,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
_phoneCtrl.dispose();
|
||||
_emailCtrl.dispose();
|
||||
_noteCtrl.dispose();
|
||||
_fiscalCodeCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -50,6 +53,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
name: _nameCtrl.text.trim(),
|
||||
phone: _phoneCtrl.text.trim(),
|
||||
email: _emailCtrl.text.trim(),
|
||||
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
setState(() => _isLoading = false);
|
||||
@@ -125,6 +129,20 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _fiscalCodeCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Codice Fiscale / Partita IVA",
|
||||
),
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
|
||||
],
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _noteCtrl,
|
||||
decoration: const InputDecoration(labelText: "Note rapide"),
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_state.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
class DashboardExpiringContractsCubit
|
||||
extends Cubit<DashboardExpiringContractsState> {
|
||||
final OperationsRepository _repository =
|
||||
GetIt.I.get<OperationsRepository>();
|
||||
final String? companyId;
|
||||
final String? storeId;
|
||||
StreamSubscription<void>? _operationsSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardExpiringContractsCubit({
|
||||
required this.companyId,
|
||||
required this.storeId,
|
||||
}) : super(const DashboardExpiringContractsState());
|
||||
|
||||
void startListening() {
|
||||
emit(state.copyWith(status: DashboardExpiringContractsStatus.loading));
|
||||
stopListening();
|
||||
|
||||
_loadExpiringSilently();
|
||||
|
||||
_operationsSubscription = _repository.onOperationsChanged.listen((_) {
|
||||
_loadExpiringSilently();
|
||||
});
|
||||
|
||||
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
_loadExpiringSilently();
|
||||
});
|
||||
}
|
||||
|
||||
void stopListening() {
|
||||
_operationsSubscription?.cancel();
|
||||
_operationsSubscription = null;
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
void refresh() {
|
||||
_loadExpiringSilently();
|
||||
}
|
||||
|
||||
void _loadExpiringSilently() async {
|
||||
try {
|
||||
if (companyId == null || companyId!.isEmpty) return;
|
||||
final expiringOps = await _repository.fetchExpiringOperations(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
limit: 20,
|
||||
);
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardExpiringContractsStatus.success,
|
||||
operations: expiringOps,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardExpiringContractsStatus.failure,
|
||||
error: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
enum DashboardExpiringContractsStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardExpiringContractsState extends Equatable {
|
||||
final DashboardExpiringContractsStatus status;
|
||||
final List<OperationModel> operations;
|
||||
final String? error;
|
||||
|
||||
const DashboardExpiringContractsState({
|
||||
this.status = DashboardExpiringContractsStatus.initial,
|
||||
this.operations = const [],
|
||||
this.error,
|
||||
});
|
||||
|
||||
DashboardExpiringContractsState copyWith({
|
||||
DashboardExpiringContractsStatus? status,
|
||||
List<OperationModel>? operations,
|
||||
String? error,
|
||||
}) {
|
||||
return DashboardExpiringContractsState(
|
||||
status: status ?? this.status,
|
||||
operations: operations ?? this.operations,
|
||||
error: error,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, operations, error];
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
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: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Nome Cliente & note
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
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,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
if (phone != null && phone.isNotEmpty)
|
||||
Text(
|
||||
phone,
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontSize: 11,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Badge Tipo / Subtipo
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: _buildBadges(operation),
|
||||
),
|
||||
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Data Scadenza Badge
|
||||
_buildExpiryBadge(context, earliestExp),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBadges(OperationModel op) {
|
||||
final labels = op.details
|
||||
.map((d) {
|
||||
final tLabel = d.type?.shortLabel ?? d.type?.value ?? '';
|
||||
final sub = d.subType?.trim() ?? '';
|
||||
if (sub.isNotEmpty) return '$tLabel: $sub';
|
||||
return tLabel;
|
||||
})
|
||||
.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: const TextStyle(
|
||||
color: Colors.amber,
|
||||
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,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/notes/models/note_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
part 'dashboard_note_list_state.dart';
|
||||
|
||||
class DashboardNoteListCubit extends Cubit<DashboardNoteListState> {
|
||||
final NotesRepository _repository = GetIt.I.get<NotesRepository>();
|
||||
final String? companyId;
|
||||
final String? staffId;
|
||||
StreamSubscription<void>? _subscription;
|
||||
|
||||
DashboardNoteListCubit({required this.companyId, required this.staffId})
|
||||
: super(DashboardNoteListState(status: DashboardNoteListStatus.initial));
|
||||
|
||||
void stopListening() {
|
||||
_subscription?.cancel();
|
||||
_subscription = null;
|
||||
}
|
||||
|
||||
void startListening() {
|
||||
stopListening();
|
||||
|
||||
emit(state.copyWith(status: DashboardNoteListStatus.loading));
|
||||
|
||||
// Primo caricamento
|
||||
_loadNotesSilently();
|
||||
|
||||
// Inizio ascolto campanello
|
||||
try {
|
||||
_subscription = _repository
|
||||
.notesStream(companyId: companyId!, currentStaffId: staffId!)
|
||||
.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());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadNotesSilently() async {
|
||||
try {
|
||||
final notes = await _repository.getNotes();
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardNoteListStatus.success,
|
||||
notes: notes,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardNoteListStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
part of 'dashboard_note_list_cubit.dart';
|
||||
|
||||
enum DashboardNoteListStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardNoteListState extends Equatable {
|
||||
final DashboardNoteListStatus status;
|
||||
final List<NoteModel> notes;
|
||||
final String? errorMessage;
|
||||
|
||||
const DashboardNoteListState({
|
||||
this.status = DashboardNoteListStatus.initial,
|
||||
this.notes = const [],
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
DashboardNoteListState copyWith({
|
||||
DashboardNoteListStatus? status,
|
||||
List<NoteModel>? notes,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DashboardNoteListState(
|
||||
status: status ?? this.status,
|
||||
notes: notes ?? this.notes,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, notes, errorMessage];
|
||||
}
|
||||
+6
-6
@@ -2,12 +2,12 @@ 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/features/notes/blocs/notes_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
|
||||
import 'package:flux/features/notes/models/note_model.dart';
|
||||
import 'package:go_router/go_router.dart'; // Supponendo tu usi GoRouter per la navigazione
|
||||
|
||||
class DashboardNotesWidget extends StatelessWidget {
|
||||
const DashboardNotesWidget({super.key});
|
||||
class DashboardNoteListCard extends StatelessWidget {
|
||||
const DashboardNoteListCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -59,14 +59,14 @@ class DashboardNotesWidget extends StatelessWidget {
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Il corpo del widget collegato al Bloc
|
||||
BlocBuilder<NotesBloc, NotesState>(
|
||||
BlocBuilder<DashboardNoteListCubit, DashboardNoteListState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == NotesStatus.loading &&
|
||||
if (state.status == DashboardNoteListStatus.loading &&
|
||||
state.notes.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (state.status == NotesStatus.failure) {
|
||||
if (state.status == DashboardNoteListStatus.failure) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Errore nel caricamento delle note.',
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.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';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
part 'dashboard_store_operation_list_state.dart';
|
||||
|
||||
class DashboardStoreOperationListCubit
|
||||
extends Cubit<DashboardStoreOperationListState> {
|
||||
final OperationsRepository _repository = GetIt.I.get<OperationsRepository>();
|
||||
final String? companyId;
|
||||
final String? storeId;
|
||||
StreamSubscription<void>? _operationsSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardStoreOperationListCubit({
|
||||
required this.companyId,
|
||||
required this.storeId,
|
||||
}) : super(
|
||||
const DashboardStoreOperationListState(
|
||||
status: DashboardStoreOperationListStatus.initial,
|
||||
),
|
||||
);
|
||||
|
||||
void startListening() {
|
||||
emit(state.copyWith(status: DashboardStoreOperationListStatus.loading));
|
||||
stopListening();
|
||||
|
||||
// Primo caricamento
|
||||
_loadOperationsSilently();
|
||||
|
||||
// 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(
|
||||
state.copyWith(
|
||||
status: DashboardStoreOperationListStatus.success,
|
||||
operations: paginatedData.operations,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardStoreOperationListStatus.failure,
|
||||
error: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
part of 'dashboard_store_operation_list_cubit.dart';
|
||||
|
||||
enum DashboardStoreOperationListStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardStoreOperationListState extends Equatable {
|
||||
final DashboardStoreOperationListStatus status;
|
||||
final String? error;
|
||||
final List<OperationModel> operations;
|
||||
|
||||
const DashboardStoreOperationListState({
|
||||
required this.status,
|
||||
this.error,
|
||||
this.operations = const [],
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, error, operations];
|
||||
|
||||
DashboardStoreOperationListState copyWith({
|
||||
DashboardStoreOperationListStatus? status,
|
||||
String? error,
|
||||
List<OperationModel>? operations,
|
||||
}) {
|
||||
return DashboardStoreOperationListState(
|
||||
status: status ?? this.status,
|
||||
error: error,
|
||||
operations: operations ?? this.operations,
|
||||
);
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
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_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class DashboardStoreOperationListCard extends StatelessWidget {
|
||||
const DashboardStoreOperationListCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _LatestOperationsCardContent();
|
||||
}
|
||||
}
|
||||
|
||||
class _LatestOperationsCardContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
const color = Colors.blue;
|
||||
|
||||
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),
|
||||
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.design_services_outlined,
|
||||
color: color,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.homeLatestOperations,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// --- CORPO DELLA CARD (LA LISTA REAL-TIME) ---
|
||||
Expanded(
|
||||
child:
|
||||
BlocBuilder<
|
||||
DashboardStoreOperationListCubit,
|
||||
DashboardStoreOperationListState
|
||||
>(
|
||||
builder: (context, state) {
|
||||
if (state.status ==
|
||||
DashboardStoreOperationListStatus.loading ||
|
||||
state.status ==
|
||||
DashboardStoreOperationListStatus.initial) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status ==
|
||||
DashboardStoreOperationListStatus.failure) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Errore di caricamento",
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.operations.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Nessun servizio recente.",
|
||||
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];
|
||||
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: Row(
|
||||
mainAxisAlignment:
|
||||
MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
operation.customer?.name ??
|
||||
'Cliente sconosciuto',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: context.primaryText,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
),
|
||||
child: _buildBadgeList(
|
||||
operation.details
|
||||
.map((d) => d.type)
|
||||
.whereType<String>()
|
||||
.where(
|
||||
(t) => t.trim().isNotEmpty,
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${operation.createdAt?.day}/${operation.createdAt?.month}",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBadgeList(List<String> types) {
|
||||
if (types.isEmpty) {
|
||||
return const Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: _OperationTypeBadge(label: 'N/A'),
|
||||
);
|
||||
}
|
||||
|
||||
return Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 4,
|
||||
children: types.map((t) => _OperationTypeBadge(label: t)).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OperationTypeBadge extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
const _OperationTypeBadge({required this.label});
|
||||
|
||||
Color _getBadgeColor(String type) {
|
||||
switch (type.toUpperCase()) {
|
||||
case 'FIN':
|
||||
case 'FINANZIAMENTO':
|
||||
return Colors.deepPurple;
|
||||
case 'TELEPASS':
|
||||
return Colors.amber.shade800;
|
||||
case 'ENERGY':
|
||||
case 'ENERGIA':
|
||||
return Colors.orange.shade800;
|
||||
case 'ENTERTAINMENT':
|
||||
return Colors.pinkAccent.shade700;
|
||||
case 'AL':
|
||||
case 'MNP':
|
||||
return Colors.indigo;
|
||||
case 'NIP':
|
||||
case 'FWA':
|
||||
return Colors.cyan.shade800;
|
||||
case 'FIBRA':
|
||||
case 'MOBILE':
|
||||
return Colors.blue.shade700;
|
||||
default:
|
||||
return Colors.blueGrey;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _getBadgeColor(label);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.2,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
part 'dashboard_store_ticket_list_state.dart';
|
||||
|
||||
class DashboardStoreTicketListCubit
|
||||
extends Cubit<DashboardStoreTicketListState> {
|
||||
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
|
||||
final String? companyId;
|
||||
final String? storeId;
|
||||
StreamSubscription<void>? _realtimeSubscription;
|
||||
StreamSubscription<void>? _localSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardStoreTicketListCubit({
|
||||
required this.companyId,
|
||||
required this.storeId,
|
||||
}) : super(
|
||||
const DashboardStoreTicketListState(
|
||||
status: DashboardStoreTicketListStatus.initial,
|
||||
),
|
||||
);
|
||||
|
||||
void stopListening() {
|
||||
_realtimeSubscription?.cancel();
|
||||
_realtimeSubscription = null;
|
||||
_localSubscription?.cancel();
|
||||
_localSubscription = null;
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
void refresh() {
|
||||
_loadTicketsSilently();
|
||||
}
|
||||
|
||||
void startListening() {
|
||||
stopListening();
|
||||
|
||||
emit(state.copyWith(status: DashboardStoreTicketListStatus.loading));
|
||||
|
||||
// Primo caricamento
|
||||
_loadTicketsSilently();
|
||||
|
||||
// 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 {
|
||||
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 {
|
||||
final tickets = await _repository.fetchTickets(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
);
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardStoreTicketListStatus.success,
|
||||
tickets: tickets,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardStoreTicketListStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
part of 'dashboard_store_ticket_list_cubit.dart';
|
||||
|
||||
enum DashboardStoreTicketListStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardStoreTicketListState extends Equatable {
|
||||
final DashboardStoreTicketListStatus status;
|
||||
final List<TicketModel> tickets;
|
||||
final String? errorMessage;
|
||||
|
||||
const DashboardStoreTicketListState({
|
||||
this.status = DashboardStoreTicketListStatus.initial,
|
||||
this.tickets = const [],
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
DashboardStoreTicketListState copyWith({
|
||||
DashboardStoreTicketListStatus? status,
|
||||
List<TicketModel>? tickets,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DashboardStoreTicketListState(
|
||||
status: status ?? this.status,
|
||||
tickets: tickets ?? this.tickets,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, tickets, errorMessage];
|
||||
}
|
||||
+40
-47
@@ -1,42 +1,21 @@
|
||||
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/core/utils/extensions.dart';
|
||||
import 'package:flux/features/home/latest_store_operations/bloc/latest_store_operations_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class LatestStoreOperationsCard extends StatelessWidget {
|
||||
const LatestStoreOperationsCard({super.key});
|
||||
class DashboardStoreTicketListCard extends StatelessWidget {
|
||||
const DashboardStoreTicketListCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final currentStoreId = context.read<SessionCubit>().state.currentStore?.id;
|
||||
|
||||
return BlocProvider(
|
||||
// 1. Creiamo il Bloc e facciamo partire subito la query
|
||||
create: (context) =>
|
||||
LatestStoreOperationsBloc()
|
||||
..add(InitLatestStoreOperationsEvent(currentStoreId ?? '')),
|
||||
child: BlocListener<SessionCubit, SessionState>(
|
||||
// 2. MAGIA: Se l'utente cambia negozio dalla barra in alto, riavviamo lo stream!
|
||||
listenWhen: (previous, current) =>
|
||||
previous.currentStore?.id != current.currentStore?.id,
|
||||
listener: (context, state) {
|
||||
if (state.currentStore?.id != null) {
|
||||
context.read<LatestStoreOperationsBloc>().add(
|
||||
InitLatestStoreOperationsEvent(state.currentStore!.id!),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: _LatestOperationsCardContent(),
|
||||
),
|
||||
);
|
||||
return _DashboardStoreTicketListCardContent();
|
||||
}
|
||||
}
|
||||
|
||||
class _LatestOperationsCardContent extends StatelessWidget {
|
||||
class _DashboardStoreTicketListCardContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
@@ -45,13 +24,13 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
return Card(
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.3)),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: () => context.pushNamed(Routes.operations),
|
||||
onTap: () => context.pushNamed(Routes.tickets),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -73,7 +52,7 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.homeLatestOperations,
|
||||
"Ticket recenti",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
@@ -91,21 +70,21 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
Expanded(
|
||||
child:
|
||||
BlocBuilder<
|
||||
LatestStoreOperationsBloc,
|
||||
LatestStoreOperationsState
|
||||
DashboardStoreTicketListCubit,
|
||||
DashboardStoreTicketListState
|
||||
>(
|
||||
builder: (context, state) {
|
||||
if (state.status ==
|
||||
LatestStoreOperationsStatus.loading ||
|
||||
DashboardStoreTicketListStatus.loading ||
|
||||
state.status ==
|
||||
LatestStoreOperationsStatus.initial) {
|
||||
DashboardStoreTicketListStatus.initial) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status ==
|
||||
LatestStoreOperationsStatus.failure) {
|
||||
DashboardStoreTicketListStatus.failure) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Errore di caricamento",
|
||||
@@ -114,10 +93,10 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
if (state.operations.isEmpty) {
|
||||
if (state.tickets.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Nessun servizio recente.",
|
||||
"Nessun ticket recente.",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontStyle: FontStyle.italic,
|
||||
@@ -127,18 +106,19 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
itemCount: state.operations.length,
|
||||
itemCount: state.tickets.length,
|
||||
separatorBuilder: (context, index) => Divider(
|
||||
height: 1,
|
||||
color: theme.dividerColor.withValues(alpha: 0.3),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final operation = state.operations[index];
|
||||
final ticket = state.tickets[index];
|
||||
final statusColor = ticket.ticketStatus.color;
|
||||
return InkWell(
|
||||
onTap: () => context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: operation),
|
||||
pathParameters: {'id': operation.id!},
|
||||
Routes.ticketForm,
|
||||
extra: (createdBy: null, ticket: ticket),
|
||||
pathParameters: {'id': ticket.id!},
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
@@ -148,10 +128,22 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
mainAxisAlignment:
|
||||
MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height:
|
||||
30, // Un'altezza fissa per farlo comparire!
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor,
|
||||
borderRadius: BorderRadius.circular(
|
||||
4,
|
||||
), // Angoli smussati per stile
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
operation.customer?.name ??
|
||||
ticket.customer?.name ??
|
||||
'Cliente sconosciuto',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
@@ -162,7 +154,8 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
operation.type,
|
||||
ticket.targetModelName ??
|
||||
'Modello sconosciuto',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: context.primaryText,
|
||||
@@ -172,7 +165,7 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${operation.createdAt?.day}/${operation.createdAt?.month}",
|
||||
"${ticket.createdAt?.day}/${ticket.createdAt?.month}",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontSize: 12,
|
||||
+155
@@ -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();
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/targets/models/target_model.dart';
|
||||
import 'package:flux/features/targets/models/target_progress_model.dart';
|
||||
|
||||
enum DashboardTargetProgressStatus {
|
||||
initial,
|
||||
loading,
|
||||
success,
|
||||
noTarget,
|
||||
failure,
|
||||
}
|
||||
|
||||
class DashboardTargetProgressState extends Equatable {
|
||||
final DashboardTargetProgressStatus status;
|
||||
final TargetModel? target;
|
||||
final TargetProgressModel? progress;
|
||||
final String? currentStaffId;
|
||||
final String? errorMessage;
|
||||
|
||||
const DashboardTargetProgressState({
|
||||
this.status = DashboardTargetProgressStatus.initial,
|
||||
this.target,
|
||||
this.progress,
|
||||
this.currentStaffId,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
DashboardTargetProgressState copyWith({
|
||||
DashboardTargetProgressStatus? status,
|
||||
TargetModel? target,
|
||||
TargetProgressModel? progress,
|
||||
String? currentStaffId,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DashboardTargetProgressState(
|
||||
status: status ?? this.status,
|
||||
target: target ?? this.target,
|
||||
progress: progress ?? this.progress,
|
||||
currentStaffId: currentStaffId ?? this.currentStaffId,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
/// Avanzamento specifico del membro dello staff indicato o correntemente connesso
|
||||
TargetProgressModel? getStaffProgress([String? staffId]) {
|
||||
final curProgress = progress;
|
||||
final id = staffId ?? currentStaffId;
|
||||
if (curProgress == null || id == null) return null;
|
||||
return curProgress.staffProgress[id];
|
||||
}
|
||||
|
||||
/// True se lo staff connesso o specificato ha almeno un target individuale attivo impostato
|
||||
bool hasStaffTargets([String? staffId]) {
|
||||
final sp = getStaffProgress(staffId);
|
||||
if (sp == null) return false;
|
||||
return sp.categories.values.any((c) => c.hasTarget);
|
||||
}
|
||||
|
||||
/// Lista delle categorie con target attivo per l'addetto indicato o connesso
|
||||
List<CategoryProgress> activeStaffCategories([String? staffId]) {
|
||||
final sp = getStaffProgress(staffId);
|
||||
if (sp == null) return const [];
|
||||
return sp.categories.values.where((c) => c.hasTarget).toList();
|
||||
}
|
||||
|
||||
/// Restituisce sempre l'avanzamento personalizzato per lo staff
|
||||
TargetProgressModel getEffectiveStaffProgress({
|
||||
required String? staffId,
|
||||
required String? staffName,
|
||||
}) {
|
||||
final sp = getStaffProgress(staffId);
|
||||
if (sp != null) {
|
||||
return sp;
|
||||
}
|
||||
|
||||
final curProgress = progress;
|
||||
if (curProgress == null) {
|
||||
return TargetProgressModel.empty();
|
||||
}
|
||||
|
||||
// Se l'addetto non è mappato nella lista (es. nuovo addetto senza operazioni),
|
||||
// creiamo una scheda personale con le categorie attive del negozio
|
||||
final staffCount = target?.individualTargets.length ?? 1;
|
||||
final divisor = staffCount > 0 ? staffCount : 1;
|
||||
|
||||
final userCategories = <String, CategoryProgress>{};
|
||||
for (final entry in curProgress.categories.entries) {
|
||||
final storeCat = entry.value;
|
||||
userCategories[entry.key] = CategoryProgress.calculate(
|
||||
key: storeCat.key,
|
||||
label: storeCat.label,
|
||||
actual: 0,
|
||||
s1: (storeCat.targetS1 / divisor).round(),
|
||||
s2: (storeCat.targetS2 / divisor).round(),
|
||||
elapsedDays: curProgress.elapsedWorkingDays,
|
||||
remainingDays: curProgress.remainingWorkingDays,
|
||||
totalDays: curProgress.totalWorkingDays,
|
||||
);
|
||||
}
|
||||
|
||||
return TargetProgressModel(
|
||||
targetId: curProgress.targetId,
|
||||
storeId: curProgress.storeId,
|
||||
staffId: staffId,
|
||||
staffName: staffName,
|
||||
totalWorkingDays: curProgress.totalWorkingDays,
|
||||
elapsedWorkingDays: curProgress.elapsedWorkingDays,
|
||||
remainingWorkingDays: curProgress.remainingWorkingDays,
|
||||
categories: userCategories,
|
||||
);
|
||||
}
|
||||
|
||||
/// Avanzamento specifico del membro dello staff correntemente connesso
|
||||
TargetProgressModel? get currentStaffProgress => getStaffProgress();
|
||||
|
||||
/// Lista delle categorie con target attivo per il negozio
|
||||
List<CategoryProgress> get activeStoreCategories {
|
||||
final curProgress = progress;
|
||||
if (curProgress == null) return const [];
|
||||
return curProgress.categories.values.where((c) => c.hasTarget).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
target,
|
||||
progress,
|
||||
currentStaffId,
|
||||
errorMessage,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,895 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/targets/models/target_progress_model.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class DashboardTargetHeroCard extends StatefulWidget {
|
||||
const DashboardTargetHeroCard({super.key});
|
||||
|
||||
@override
|
||||
State<DashboardTargetHeroCard> createState() =>
|
||||
_DashboardTargetHeroCardState();
|
||||
}
|
||||
|
||||
class _DashboardTargetHeroCardState extends State<DashboardTargetHeroCard> {
|
||||
bool _showAllCategories = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<DashboardTargetProgressCubit,
|
||||
DashboardTargetProgressState>(
|
||||
builder: (context, state) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
if (state.status == DashboardTargetProgressStatus.loading ||
|
||||
state.status == DashboardTargetProgressStatus.initial) {
|
||||
return _buildLoadingCard(theme);
|
||||
}
|
||||
|
||||
if (state.status == DashboardTargetProgressStatus.noTarget ||
|
||||
state.target == null ||
|
||||
state.progress == null) {
|
||||
return _buildNoTargetCard(context, theme);
|
||||
}
|
||||
|
||||
return _buildHeroContent(context, theme, state);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoadingCard(ThemeData theme) {
|
||||
return Container(
|
||||
height: 160,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.2)),
|
||||
),
|
||||
child: const Center(
|
||||
child: SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNoTargetCard(BuildContext context, ThemeData theme) {
|
||||
final currentStore = context.watch<SessionCubit>().state.currentStore;
|
||||
final now = DateTime.now();
|
||||
final months = [
|
||||
'Gennaio',
|
||||
'Febbraio',
|
||||
'Marzo',
|
||||
'Aprile',
|
||||
'Maggio',
|
||||
'Giugno',
|
||||
'Luglio',
|
||||
'Agosto',
|
||||
'Settembre',
|
||||
'Ottobre',
|
||||
'Novembre',
|
||||
'Dicembre'
|
||||
];
|
||||
final monthLabel = '${months[now.month - 1]} ${now.year}';
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.2),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.04),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.flag_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Nessun obiettivo per $monthLabel',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Imposta i target di ${currentStore?.name ?? "questo negozio"} per monitorare le medie giornaliere richieste e il ritmo di vendita.',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
FilledButton.icon(
|
||||
onPressed: () => context.pushNamed(Routes.targets),
|
||||
icon: const Icon(Icons.add, size: 18),
|
||||
label: const Text('Imposta Target'),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeroContent(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardTargetProgressState state,
|
||||
) {
|
||||
final progress = state.progress!;
|
||||
final target = state.target!;
|
||||
final staffMember =
|
||||
context.watch<SessionCubit>().state.currentStaffMember;
|
||||
final currentStore =
|
||||
context.watch<SessionCubit>().state.currentStore;
|
||||
final staffName = staffMember?.name ?? 'Ospite';
|
||||
final staffId = staffMember?.id;
|
||||
|
||||
final isManager = staffMember?.systemRole == SystemRole.manager ||
|
||||
staffMember?.systemRole == SystemRole.admin;
|
||||
|
||||
final activeProgress = isManager
|
||||
? progress
|
||||
: state.getEffectiveStaffProgress(
|
||||
staffId: staffId,
|
||||
staffName: staffName,
|
||||
);
|
||||
|
||||
final displayCategories = activeProgress.categories.values
|
||||
.where((c) => c.hasTarget)
|
||||
.toList();
|
||||
|
||||
final inLineCategories =
|
||||
displayCategories.where((c) => !c.isBehind).toList();
|
||||
final behindCategories =
|
||||
displayCategories.where((c) => c.isBehind).toList();
|
||||
|
||||
final categoriesToDisplay =
|
||||
_showAllCategories ? displayCategories : behindCategories;
|
||||
|
||||
final remainingDays = progress.remainingWorkingDays;
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isCompact = constraints.maxWidth < 600;
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.25),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.06),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// ==========================================
|
||||
// 1. HEADER DELLA CARD (TITOLO & GIORNI)
|
||||
// ==========================================
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
isCompact ? 14 : 20,
|
||||
isCompact ? 14 : 18,
|
||||
isCompact ? 14 : 20,
|
||||
isCompact ? 10 : 14,
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(isCompact ? 8 : 10),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
theme.colorScheme.primary,
|
||||
theme.colorScheme.primary.withValues(alpha: 0.8),
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: theme.colorScheme.primary
|
||||
.withValues(alpha: 0.25),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
Icons.trending_up_rounded,
|
||||
color: Colors.white,
|
||||
size: isCompact ? 20 : 22,
|
||||
),
|
||||
),
|
||||
SizedBox(width: isCompact ? 10 : 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
isManager ? 'RITMO NEGOZIO PER OGGI' : 'IL TUO RITMO PER OGGI',
|
||||
style: TextStyle(
|
||||
fontSize: isCompact ? 10.5 : 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
letterSpacing: 0.6,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 7,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer
|
||||
.withValues(alpha: 0.35),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
remainingDays > 1
|
||||
? 'Mancano $remainingDays gg'
|
||||
: (remainingDays == 1
|
||||
? 'Ultimo giorno!'
|
||||
: 'Mese concluso'),
|
||||
style: TextStyle(
|
||||
fontSize: isCompact ? 10 : 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
isManager
|
||||
? 'Obiettivi di ${currentStore?.name ?? "Negozio"} per oggi'
|
||||
: (staffMember != null
|
||||
? 'Cosa portare a casa oggi, $staffName'
|
||||
: 'Obiettivi personali per oggi'),
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
fontSize: isCompact ? 15 : 17,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
// Tasto rapido dettaglio
|
||||
if (isCompact)
|
||||
IconButton(
|
||||
onPressed: () => context.pushNamed(
|
||||
Routes.targetDetail,
|
||||
extra: target,
|
||||
),
|
||||
icon: const Icon(Icons.analytics_outlined),
|
||||
tooltip: 'Dettagli target',
|
||||
color: theme.colorScheme.primary,
|
||||
visualDensity: VisualDensity.compact,
|
||||
)
|
||||
else
|
||||
TextButton.icon(
|
||||
onPressed: () => context.pushNamed(
|
||||
Routes.targetDetail,
|
||||
extra: target,
|
||||
),
|
||||
icon: const Icon(Icons.analytics_outlined, size: 18),
|
||||
label: const Text('Dettagli'),
|
||||
style: TextButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
foregroundColor: theme.colorScheme.primary,
|
||||
textStyle: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// ==========================================
|
||||
// 2. FOCUS METRICHE: MEDIE RICHIESTE PER OGGI
|
||||
// ==========================================
|
||||
if (displayCategories.isEmpty)
|
||||
Padding(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
child: Text(
|
||||
'Nessun obiettivo attivo configurato per questo mese.',
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
// Banner sintetico per gli elementi in linea
|
||||
if (inLineCategories.isNotEmpty)
|
||||
_buildInLineSummaryBanner(
|
||||
theme,
|
||||
inLineCategories: inLineCategories,
|
||||
totalCategoriesCount: displayCategories.length,
|
||||
hasBehindCategories: behindCategories.isNotEmpty,
|
||||
isManager: isManager,
|
||||
),
|
||||
|
||||
if (categoriesToDisplay.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: categoriesToDisplay.length,
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent:
|
||||
constraints.maxWidth > 700 ? 260 : 200,
|
||||
mainAxisExtent: 168,
|
||||
crossAxisSpacing: 10,
|
||||
mainAxisSpacing: 10,
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final category = categoriesToDisplay[index];
|
||||
final storeCategory =
|
||||
progress.categories[category.key];
|
||||
return _buildCategoryDailyPacingCard(
|
||||
theme,
|
||||
category,
|
||||
storeCategory: storeCategory,
|
||||
isManager: isManager,
|
||||
);
|
||||
},
|
||||
),
|
||||
)
|
||||
else if (behindCategories.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 20,
|
||||
vertical: 8,
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Tutti gli obiettivi sono in linea col ritmo! 🎉',
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 14),
|
||||
|
||||
// ==========================================
|
||||
// 3. SEZIONE INFERIORE: RIEPILOGO NEGOZIO
|
||||
// ==========================================
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest
|
||||
.withValues(alpha: 0.35),
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
bottom: Radius.circular(19),
|
||||
),
|
||||
border: Border(
|
||||
top: BorderSide(
|
||||
color: theme.dividerColor.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
),
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: isCompact ? 14 : 20,
|
||||
vertical: 10,
|
||||
),
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 10,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
Wrap(
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.storefront_outlined,
|
||||
size: 17,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
Text(
|
||||
'Negozio:',
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: theme.colorScheme.primary,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
// Badge sintetici del negozio
|
||||
_buildMiniBadge(
|
||||
label:
|
||||
'${progress.countAchieved}/${progress.countTotalActive} Presi',
|
||||
color: const Color(0xFF15803D),
|
||||
bgColor: const Color(0xFFDCFCE7),
|
||||
),
|
||||
_buildMiniBadge(
|
||||
label: '${progress.countInLineOnly} In linea',
|
||||
color: const Color(0xFF0D9488),
|
||||
bgColor: const Color(0xFFCCFBF1),
|
||||
),
|
||||
if (progress.countBehind > 0)
|
||||
_buildMiniBadge(
|
||||
label: '${progress.countBehind} Sotto ritmo',
|
||||
color: const Color(0xFFDC2626),
|
||||
bgColor: const Color(0xFFFEE2E2),
|
||||
),
|
||||
],
|
||||
),
|
||||
InkWell(
|
||||
onTap: () => context.pushNamed(
|
||||
Routes.targetDetail,
|
||||
extra: target,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4,
|
||||
vertical: 2,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Apri analisi completa',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Icon(
|
||||
Icons.arrow_forward_rounded,
|
||||
size: 14,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryDailyPacingCard(
|
||||
ThemeData theme,
|
||||
CategoryProgress category, {
|
||||
CategoryProgress? storeCategory,
|
||||
bool isManager = false,
|
||||
}) {
|
||||
final pacingTheme = PacingTheme.of(category.status);
|
||||
final isAchieved = category.isAchieved;
|
||||
final hasS2 = category.targetS2 > 0;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(
|
||||
color: pacingTheme.border.withValues(alpha: 0.7),
|
||||
width: 1.2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: pacingTheme.primary.withValues(alpha: 0.04),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header tessera: Nome metrica + Pillola di stato
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
category.label.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
letterSpacing: 0.3,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: pacingTheme.background,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: pacingTheme.border, width: 0.8),
|
||||
),
|
||||
child: Text(
|
||||
isAchieved
|
||||
? 'Preso! 🎉'
|
||||
: (category.status == TargetPacingStatus.inLineS1 ||
|
||||
category.status == TargetPacingStatus.inLineS2
|
||||
? 'In linea ✅'
|
||||
: (category.status == TargetPacingStatus.recoverable
|
||||
? 'Da spingere ⚡'
|
||||
: 'In ritardo 🔴')),
|
||||
style: TextStyle(
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: pacingTheme.text,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
// Centro: Numero gigante MEDIA GIORNALIERA RICHIESTA PER OGGI
|
||||
if (isAchieved)
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
children: [
|
||||
Text(
|
||||
'RAGGIUNTO',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: pacingTheme.primary,
|
||||
letterSpacing: -0.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
const Text('🏆', style: TextStyle(fontSize: 16)),
|
||||
],
|
||||
),
|
||||
if (hasS2 && !category.isAchievedS2)
|
||||
Text(
|
||||
'Sfida (S2): ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.purple.shade700,
|
||||
),
|
||||
)
|
||||
else
|
||||
Text(
|
||||
isManager
|
||||
? 'Obiettivo negozio centrato!'
|
||||
: 'Obiettivo personale centrato!',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
else
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
children: [
|
||||
Text(
|
||||
category.requiredDailyRateS1.toStringAsFixed(1),
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: pacingTheme.text,
|
||||
letterSpacing: -0.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'/ giorno',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: pacingTheme.text.withValues(alpha: 0.8),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (hasS2)
|
||||
Text(
|
||||
'Sfida S2: ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
)
|
||||
else
|
||||
Text(
|
||||
'Target: ${category.targetS1} pz',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
// Footer: Avanzamento e ritmo
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
isManager
|
||||
? 'Negozio: ${category.actualPieces} / ${category.targetS1}'
|
||||
: 'I tuoi: ${category.actualPieces} / ${category.targetS1}',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'ritmo: ${category.actualDailyRate.toStringAsFixed(1)}/gg',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
child: LinearProgressIndicator(
|
||||
value: category.targetS1 > 0
|
||||
? (category.actualPieces / category.targetS1).clamp(0.0, 1.0)
|
||||
: 0.0,
|
||||
minHeight: 4,
|
||||
backgroundColor: pacingTheme.background,
|
||||
color: pacingTheme.primary,
|
||||
),
|
||||
),
|
||||
if (!isManager && storeCategory != null && storeCategory.targetS1 > 0) ...[
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Negozio: ${storeCategory.actualPieces}/${storeCategory.targetS1}',
|
||||
style: TextStyle(
|
||||
fontSize: 9.5,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'ritmo: ${storeCategory.actualDailyRate.toStringAsFixed(1)}/gg',
|
||||
style: TextStyle(
|
||||
fontSize: 9.5,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInLineSummaryBanner(
|
||||
ThemeData theme, {
|
||||
required List<CategoryProgress> inLineCategories,
|
||||
required int totalCategoriesCount,
|
||||
required bool hasBehindCategories,
|
||||
bool isManager = false,
|
||||
}) {
|
||||
final isDark = theme.brightness == Brightness.dark;
|
||||
final bannerBg = isDark
|
||||
? const Color(0xFF064E3B).withValues(alpha: 0.35)
|
||||
: const Color(0xFFF0FDF4);
|
||||
final bannerBorder = isDark
|
||||
? const Color(0xFF047857).withValues(alpha: 0.5)
|
||||
: const Color(0xFFBBF7D0);
|
||||
final bannerIconColor =
|
||||
isDark ? const Color(0xFF34D399) : const Color(0xFF16A34A);
|
||||
final bannerTextColor =
|
||||
isDark ? const Color(0xFF6EE7B7) : const Color(0xFF15803D);
|
||||
final bannerSubtextColor =
|
||||
isDark ? const Color(0xFFA7F3D0) : const Color(0xFF166534);
|
||||
|
||||
final subjectText = isManager ? 'Il negozio è in linea' : 'Sei in linea';
|
||||
|
||||
final titleText = !hasBehindCategories
|
||||
? '$subjectText con tutti i ${inLineCategories.length} obiettivi! 🎉'
|
||||
: '$subjectText con ${inLineCategories.length} ${inLineCategories.length == 1 ? 'obiettivo' : 'obiettivi'} su $totalCategoriesCount';
|
||||
|
||||
final categoryNames = inLineCategories.map((c) => c.label).join(' • ');
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.fromLTRB(16, 0, 16, 12),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: bannerBg,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: bannerBorder, width: 1),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.check_circle_rounded,
|
||||
color: bannerIconColor,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
titleText,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: bannerTextColor,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
categoryNames,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: bannerSubtextColor,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_showAllCategories = !_showAllCategories;
|
||||
});
|
||||
},
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_showAllCategories
|
||||
? 'Nascondi'
|
||||
: 'Mostra tutti (${inLineCategories.length})',
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: bannerTextColor,
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
_showAllCategories
|
||||
? Icons.keyboard_arrow_up
|
||||
: Icons.keyboard_arrow_down,
|
||||
size: 16,
|
||||
color: bannerTextColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMiniBadge({
|
||||
required String label,
|
||||
required Color color,
|
||||
required Color bgColor,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,62 @@
|
||||
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/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tasks/models/task_model.dart';
|
||||
import 'package:flux/features/tasks/models/task_status.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
part 'dashboard_task_list_state.dart';
|
||||
|
||||
class DashboardTaskListCubit extends Cubit<DashboardTaskListState> {
|
||||
final TaskRepository _repository = GetIt.I.get<TaskRepository>();
|
||||
final SupabaseClient _supabase = GetIt.I.get<SupabaseClient>();
|
||||
RealtimeChannel? _taskChannel;
|
||||
final TasksRepository _repository = GetIt.I.get<TasksRepository>();
|
||||
final String? staffId;
|
||||
final String? companyId;
|
||||
StreamSubscription<void>? _tasksSubscription;
|
||||
|
||||
DashboardTaskListCubit() : super(DashboardTaskListState());
|
||||
DashboardTaskListCubit({required this.staffId, required this.companyId})
|
||||
: super(const DashboardTaskListState());
|
||||
|
||||
void startListening() {
|
||||
stopListening();
|
||||
|
||||
void startListening({required String staffId}) async {
|
||||
emit(state.copyWith(status: DashboardTaskListStatus.loading));
|
||||
await _loadTasks(staffId: staffId);
|
||||
_taskChannel?.unsubscribe();
|
||||
_taskChannel = _supabase
|
||||
.channel('public:tasks_staff_$staffId')
|
||||
.onPostgresChanges(
|
||||
event: PostgresChangeEvent.all,
|
||||
schema: 'public',
|
||||
table: 'tasks',
|
||||
filter: PostgresChangeFilter(
|
||||
type: PostgresChangeFilterType.eq,
|
||||
column: 'staff_id',
|
||||
value: staffId,
|
||||
),
|
||||
callback: (payload) {
|
||||
_loadTasks(staffId: staffId);
|
||||
},
|
||||
);
|
||||
_taskChannel?.subscribe();
|
||||
|
||||
// Primo caricamento
|
||||
_loadTasksSilently();
|
||||
|
||||
// Inizio ascolto campanello
|
||||
try {
|
||||
_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());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadTasks({required String staffId}) async {
|
||||
void stopListening() {
|
||||
_tasksSubscription?.cancel();
|
||||
_tasksSubscription = null;
|
||||
}
|
||||
|
||||
Future<void> _loadTasksSilently() async {
|
||||
try {
|
||||
final tasks = await _repository.getTasks(
|
||||
companyId: GetIt.I.get<SessionCubit>().state.company!.id!,
|
||||
companyId: companyId!,
|
||||
staffId: staffId,
|
||||
statuses: [TaskStatus.open, TaskStatus.inProgress],
|
||||
limit: 10,
|
||||
);
|
||||
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardTaskListStatus.success,
|
||||
@@ -54,6 +65,7 @@ class DashboardTaskListCubit extends Cubit<DashboardTaskListState> {
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardTaskListStatus.failure,
|
||||
@@ -65,7 +77,7 @@ class DashboardTaskListCubit extends Cubit<DashboardTaskListState> {
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_taskChannel?.unsubscribe();
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+3
-20
@@ -1,34 +1,17 @@
|
||||
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_task_list/blocs/dashboard_task_list_cubit.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:flux/features/tasks/models/task_status.dart';
|
||||
|
||||
class DashboardTasksCard extends StatelessWidget {
|
||||
const DashboardTasksCard({super.key});
|
||||
class DashboardTaskListCard extends StatelessWidget {
|
||||
const DashboardTaskListCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Recuperiamo lo staff (o l'utente) loggato
|
||||
// Adatta il getter in base a come è strutturato il tuo SessionState
|
||||
final currentStaffId = context
|
||||
.read<SessionCubit>()
|
||||
.state
|
||||
.currentStaffMember
|
||||
?.id;
|
||||
|
||||
if (currentStaffId == null) {
|
||||
return const SizedBox.shrink(); // Sicurezza se lo stato non è pronto
|
||||
}
|
||||
|
||||
return BlocProvider(
|
||||
create: (context) =>
|
||||
DashboardTaskListCubit()..startListening(staffId: currentStaffId),
|
||||
child: const _DashboardTasksCardContent(),
|
||||
);
|
||||
return _DashboardTasksCardContent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
part '../../latest_store_operations/bloc/latest_store_operations_events.dart';
|
||||
part '../../latest_store_operations/bloc/latest_store_operations_state.dart';
|
||||
|
||||
class LatestStoreOperationsBloc
|
||||
extends Bloc<LatestStoreOperationsEvent, LatestStoreOperationsState> {
|
||||
final _repository = GetIt.I.get<OperationsRepository>();
|
||||
|
||||
LatestStoreOperationsBloc()
|
||||
: super(
|
||||
const LatestStoreOperationsState(
|
||||
status: LatestStoreOperationsStatus.initial,
|
||||
),
|
||||
) {
|
||||
on<InitLatestStoreOperationsEvent>((event, emit) async {
|
||||
emit(state.copyWith(status: LatestStoreOperationsStatus.loading));
|
||||
try {
|
||||
// 1. Creiamo uno stream "intermedio" che idrata i dati
|
||||
final hydratedStream = _repository
|
||||
.getLatestStoreOperationsStream(storeId: event.storeId, limit: 10)
|
||||
.asyncMap((List<OperationModel> rawOperations) async {
|
||||
// Questo gira ad ogni "scatto" dello stream di Supabase
|
||||
List<OperationModel> fullyHydratedOperations = [];
|
||||
|
||||
for (OperationModel operation in rawOperations) {
|
||||
// Peschiamo i dati completi (incluso il cliente)
|
||||
OperationModel fullOperation = await _repository
|
||||
.fetchOperationById(operation.id!);
|
||||
fullyHydratedOperations.add(fullOperation);
|
||||
}
|
||||
|
||||
// Passiamo la lista completa allo step successivo
|
||||
return fullyHydratedOperations;
|
||||
});
|
||||
|
||||
// 2. Ora passiamo lo stream idratato all'emit.forEach
|
||||
await emit.forEach(
|
||||
hydratedStream, // Usiamo lo stream modificato!
|
||||
onData: (List<OperationModel> fullyHydratedOperations) {
|
||||
// Qui ora è tutto sincrono e bellissimo
|
||||
return state.copyWith(
|
||||
operations: fullyHydratedOperations,
|
||||
status: LatestStoreOperationsStatus.success,
|
||||
);
|
||||
},
|
||||
onError: (error, stackTrace) => state.copyWith(
|
||||
status: LatestStoreOperationsStatus.failure,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: LatestStoreOperationsStatus.failure,
|
||||
error: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
part of 'latest_store_operations_bloc.dart';
|
||||
|
||||
sealed class LatestStoreOperationsEvent extends Equatable {
|
||||
const LatestStoreOperationsEvent();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
class InitLatestStoreOperationsEvent extends LatestStoreOperationsEvent {
|
||||
final String storeId;
|
||||
|
||||
const InitLatestStoreOperationsEvent(this.storeId);
|
||||
|
||||
@override
|
||||
List<Object> get props => [storeId];
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
part of 'latest_store_operations_bloc.dart';
|
||||
|
||||
enum LatestStoreOperationsStatus { initial, loading, success, failure }
|
||||
|
||||
class LatestStoreOperationsState extends Equatable {
|
||||
final LatestStoreOperationsStatus status;
|
||||
final String? error;
|
||||
final List<OperationModel> operations;
|
||||
|
||||
const LatestStoreOperationsState({
|
||||
required this.status,
|
||||
this.error,
|
||||
this.operations = const [],
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, error, operations];
|
||||
|
||||
LatestStoreOperationsState copyWith({
|
||||
LatestStoreOperationsStatus? status,
|
||||
String? error,
|
||||
List<OperationModel>? operations,
|
||||
}) {
|
||||
return LatestStoreOperationsState(
|
||||
status: status ?? this.status,
|
||||
error: error,
|
||||
operations: operations ?? this.operations,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
part 'latest_store_tickets_events.dart';
|
||||
part 'latest_store_tickets_state.dart';
|
||||
|
||||
class LatestStoreTicketsBloc
|
||||
extends Bloc<LatestStoreTicketsEvent, LatestStoreTicketsState> {
|
||||
final _repository = GetIt.I.get<TicketRepository>();
|
||||
LatestStoreTicketsBloc()
|
||||
: super(
|
||||
const LatestStoreTicketsState(status: LatestStoreTicketsStatus.initial),
|
||||
) {
|
||||
on<InitLatestStoreTicketsEvent>((event, emit) async {
|
||||
emit(state.copyWith(status: LatestStoreTicketsStatus.loading));
|
||||
try {
|
||||
final hydratedStream = _repository
|
||||
.getLatestStoreTicketsStream(storeId: event.storeId, limit: 10)
|
||||
.asyncMap((List<TicketModel> rawTickets) async {
|
||||
List<TicketModel> fullyHydratedTickets = [];
|
||||
|
||||
for (TicketModel ticket in rawTickets) {
|
||||
TicketModel fullTicket = await _repository.getTicketById(
|
||||
ticket.id!,
|
||||
);
|
||||
fullyHydratedTickets.add(fullTicket);
|
||||
}
|
||||
|
||||
return fullyHydratedTickets;
|
||||
});
|
||||
await emit.forEach(
|
||||
hydratedStream,
|
||||
onData: (List<TicketModel> fullyHydratedTickets) {
|
||||
return state.copyWith(
|
||||
tickets: fullyHydratedTickets,
|
||||
status: LatestStoreTicketsStatus.success,
|
||||
);
|
||||
},
|
||||
onError: (error, stackTrace) => state.copyWith(
|
||||
status: LatestStoreTicketsStatus.failure,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: LatestStoreTicketsStatus.failure,
|
||||
error: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
part of 'latest_store_tickets_bloc.dart';
|
||||
|
||||
abstract class LatestStoreTicketsEvent extends Equatable {
|
||||
const LatestStoreTicketsEvent();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
class InitLatestStoreTicketsEvent extends LatestStoreTicketsEvent {
|
||||
final String storeId;
|
||||
|
||||
const InitLatestStoreTicketsEvent(this.storeId);
|
||||
|
||||
@override
|
||||
List<Object> get props => [storeId];
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
part of 'latest_store_tickets_bloc.dart';
|
||||
|
||||
enum LatestStoreTicketsStatus { initial, loading, success, failure }
|
||||
|
||||
class LatestStoreTicketsState extends Equatable {
|
||||
final LatestStoreTicketsStatus status;
|
||||
final String? error;
|
||||
final List<TicketModel> tickets;
|
||||
const LatestStoreTicketsState({
|
||||
required this.status,
|
||||
this.error,
|
||||
this.tickets = const [],
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, error, tickets];
|
||||
|
||||
LatestStoreTicketsState copyWith({
|
||||
LatestStoreTicketsStatus? status,
|
||||
String? error,
|
||||
List<TicketModel>? tickets,
|
||||
}) {
|
||||
return LatestStoreTicketsState(
|
||||
status: status ?? this.status,
|
||||
error: error,
|
||||
tickets: tickets ?? this.tickets,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
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/latest_store_tickets/blocs/latest_store_tickets_bloc.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class LatestStoreTicketsCard extends StatelessWidget {
|
||||
const LatestStoreTicketsCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final currentStoreId = context.read<SessionCubit>().state.currentStore?.id;
|
||||
|
||||
return BlocProvider(
|
||||
// 1. Creiamo il Bloc e facciamo partire subito la query
|
||||
create: (context) =>
|
||||
LatestStoreTicketsBloc()
|
||||
..add(InitLatestStoreTicketsEvent(currentStoreId ?? '')),
|
||||
child: BlocListener<SessionCubit, SessionState>(
|
||||
// 2. MAGIA: Se l'utente cambia negozio dalla barra in alto, riavviamo lo stream!
|
||||
listenWhen: (previous, current) =>
|
||||
previous.currentStore?.id != current.currentStore?.id,
|
||||
listener: (context, state) {
|
||||
if (state.currentStore?.id != null) {
|
||||
context.read<LatestStoreTicketsBloc>().add(
|
||||
InitLatestStoreTicketsEvent(state.currentStore!.id!),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: _LatestStoreTicketsCardContent(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LatestStoreTicketsCardContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
const color = Colors.blue;
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: () => context.pushNamed(Routes.tickets),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.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.design_services_outlined,
|
||||
color: color,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
"Ticket recenti",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// --- CORPO DELLA CARD (LA LISTA REAL-TIME) ---
|
||||
Expanded(
|
||||
child: BlocBuilder<LatestStoreTicketsBloc, LatestStoreTicketsState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == LatestStoreTicketsStatus.loading ||
|
||||
state.status == LatestStoreTicketsStatus.initial) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (state.status == LatestStoreTicketsStatus.failure) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Errore di caricamento",
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.tickets.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"Nessun ticket recente.",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
itemCount: state.tickets.length,
|
||||
separatorBuilder: (context, index) => Divider(
|
||||
height: 1,
|
||||
color: theme.dividerColor.withValues(alpha: 0.3),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final ticket = state.tickets[index];
|
||||
final statusColor = ticket.ticketStatus.color;
|
||||
return InkWell(
|
||||
onTap: () => context.pushNamed(
|
||||
Routes.ticketForm,
|
||||
extra: (createdBy: null, ticket: ticket),
|
||||
pathParameters: {'id': ticket.id!},
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height:
|
||||
30, // Un'altezza fissa per farlo comparire!
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor,
|
||||
borderRadius: BorderRadius.circular(
|
||||
4,
|
||||
), // Angoli smussati per stile
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
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,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${ticket.createdAt?.day}/${ticket.createdAt?.month}",
|
||||
style: TextStyle(
|
||||
color: context.secondaryText,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,108 @@
|
||||
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/app_router.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/core/widgets/staff_selector_modal.dart';
|
||||
import 'package:flux/features/home/dashboard_task_list/ui/dashboard_tasks_card.dart';
|
||||
import 'package:flux/features/home/latest_store_operations/ui/latest_store_operations_card.dart';
|
||||
import 'package:flux/features/home/latest_store_tickets/ui/latest_store_tickets_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';
|
||||
import 'package:flux/features/home/dashboard_store_ticket_list/ui/dashboard_store_ticket_list_card.dart';
|
||||
import 'package:flux/features/home/dashboard_task_list/blocs/dashboard_task_list_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_task_list/ui/dashboard_task_list_card.dart';
|
||||
import 'package:flux/features/home/dashboard_store_operation_list/ui/latest_store_operations_card.dart';
|
||||
import 'package:flux/features/home/ui/quick_actions_widget.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/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/notes/models/note_model.dart';
|
||||
import 'package:flux/features/notes/ui/dashboard_notes_widget.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';
|
||||
|
||||
class HomeScreen extends StatelessWidget {
|
||||
class HomeScreen extends StatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
late final AppLifecycleListener _lifecycleListener;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (AppRouter.pendingRoute != null) {
|
||||
final destination = AppRouter.pendingRoute!;
|
||||
|
||||
// ⚠️ Svuota IMMEDIATAMENTE la variabile per evitare loop infiniti se si ruota lo schermo!
|
||||
AppRouter.pendingRoute = null;
|
||||
|
||||
// Spedisci l'utente al task!
|
||||
context.push(destination);
|
||||
}
|
||||
});
|
||||
|
||||
// Inizializziamo il sensore del ciclo di vita
|
||||
_lifecycleListener = AppLifecycleListener(
|
||||
onPause: () {
|
||||
// L'utente ha messo l'app in background (es. per rispondere a un messaggio su WhatsApp)
|
||||
// Chiudiamo i rubinetti per non sprecare risorse e prevenire crash
|
||||
_stopListeners();
|
||||
debugPrint('App in background: Stream sospesi.');
|
||||
},
|
||||
onResume: () {
|
||||
// L'utente è tornato sull'app!
|
||||
// Riappriamo i rubinetti, Supabase ricreerà una connessione fresca
|
||||
_startListeners();
|
||||
debugPrint('App in foreground: Stream riattivati.');
|
||||
},
|
||||
);
|
||||
|
||||
// Facciamo partire gli stream la primissima volta che la schermata si carica
|
||||
_startListeners();
|
||||
}
|
||||
|
||||
void _stopListeners() {
|
||||
context.read<DashboardStoreOperationListCubit>().stopListening();
|
||||
context.read<DashboardTaskListCubit>().stopListening();
|
||||
context.read<DashboardStoreTicketListCubit>().stopListening();
|
||||
context.read<DashboardNoteListCubit>().stopListening();
|
||||
context.read<DashboardTargetProgressCubit>().stopListening();
|
||||
context.read<DashboardExpiringContractsCubit>().stopListening();
|
||||
}
|
||||
|
||||
void _startListeners() {
|
||||
final sessionState = context.read<SessionCubit>().state;
|
||||
context.read<DashboardTargetProgressCubit>().updateContext(
|
||||
newCompanyId: sessionState.company?.id,
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
newStaffId: sessionState.currentStaffMember?.id,
|
||||
);
|
||||
context.read<DashboardStoreOperationListCubit>().startListening();
|
||||
context.read<DashboardTaskListCubit>().startListening();
|
||||
context.read<DashboardStoreTicketListCubit>().startListening();
|
||||
context.read<DashboardNoteListCubit>().startListening();
|
||||
context.read<DashboardTargetProgressCubit>().startListening();
|
||||
context.read<DashboardExpiringContractsCubit>().startListening();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Pulizia fondamentale
|
||||
_lifecycleListener.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
@@ -43,47 +126,63 @@ class HomeScreen extends StatelessWidget {
|
||||
// 2. CORPO DELLA DASHBOARD (Scrollabile)
|
||||
// ==========================================
|
||||
Expanded(
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
// --- QUICK ACTIONS: AZIONI RAPIDE ---
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
child: BlocListener<SessionCubit, SessionState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.currentStore?.id != curr.currentStore?.id ||
|
||||
prev.currentStaffMember?.id != curr.currentStaffMember?.id ||
|
||||
prev.company?.id != curr.company?.id,
|
||||
listener: (context, sessionState) {
|
||||
context.read<DashboardTargetProgressCubit>().updateContext(
|
||||
newCompanyId: sessionState.company?.id,
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
newStaffId: sessionState.currentStaffMember?.id,
|
||||
);
|
||||
},
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
// --- HERO TARGET DEL GIORNO (TUTTA LARGHEZZA IN CIMA) ---
|
||||
const SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
|
||||
child: DashboardTargetHeroCard(),
|
||||
),
|
||||
),
|
||||
|
||||
// --- QUICK ACTIONS: AZIONI RAPIDE ---
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
child: _buildQuickActions(context),
|
||||
),
|
||||
),
|
||||
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 32)),
|
||||
|
||||
// --- I WIDGET DELLA DASHBOARD (Responsive Grid) ---
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
child: _buildQuickActions(context),
|
||||
sliver: SliverGrid(
|
||||
gridDelegate:
|
||||
const SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: 500,
|
||||
mainAxisSpacing: 16,
|
||||
crossAxisSpacing: 16,
|
||||
childAspectRatio: 1.3,
|
||||
),
|
||||
delegate: SliverChildListDelegate([
|
||||
DashboardStoreOperationListCard(),
|
||||
DashboardStoreTicketListCard(),
|
||||
DashboardExpiringContractsCard(),
|
||||
DashboardNoteListCard(),
|
||||
DashboardTaskListCard(),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 32)),
|
||||
|
||||
// --- I WIDGET DELLA DASHBOARD (Responsive Grid) ---
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
sliver: SliverGrid(
|
||||
gridDelegate:
|
||||
const SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: 500,
|
||||
mainAxisSpacing: 16,
|
||||
crossAxisSpacing: 16,
|
||||
childAspectRatio: 1.3,
|
||||
),
|
||||
delegate: SliverChildListDelegate([
|
||||
LatestStoreOperationsCard(),
|
||||
LatestStoreTicketsCard(),
|
||||
_buildDashboardWidget(
|
||||
title: context.l10n.homeExpiringContracts,
|
||||
icon: Icons.assignment_late_outlined,
|
||||
color: Colors.orange,
|
||||
context: context,
|
||||
),
|
||||
DashboardNotesWidget(),
|
||||
DashboardTasksCard(),
|
||||
]),
|
||||
),
|
||||
),
|
||||
|
||||
// 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)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -93,9 +192,6 @@ class HomeScreen extends StatelessWidget {
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// WIDGET BUILDERS
|
||||
// ==========================================
|
||||
|
||||
Widget _buildHeader(BuildContext context, ThemeData theme) {
|
||||
final user = context.watch<SessionCubit>().state.currentStaffMember;
|
||||
final currentStore = context.watch<SessionCubit>().state.currentStore;
|
||||
@@ -232,7 +328,7 @@ class HomeScreen extends StatelessWidget {
|
||||
QuickActionButton(
|
||||
icon: Icons.task_alt,
|
||||
label: context.l10n.commonTask,
|
||||
color: Colors.teal,
|
||||
color: Colors.orange,
|
||||
onTap: () {
|
||||
context.pushNamed(Routes.taskForm, pathParameters: {'id': 'new'});
|
||||
},
|
||||
@@ -242,82 +338,7 @@ class HomeScreen extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart'; // Per estrarre gli store
|
||||
import '../models/provider_model.dart';
|
||||
@@ -32,7 +33,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
try {
|
||||
// 1. Scarichiamo tutti i negozi dell'azienda
|
||||
final storesResponse = await _client
|
||||
.from('store')
|
||||
.from(Tables.stores)
|
||||
.select('id, name')
|
||||
.eq('company_id', companyId);
|
||||
|
||||
@@ -41,7 +42,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
if (existingProvider != null && existingProvider.id != null) {
|
||||
// ... (Vecchio codice di recupero)
|
||||
final links = await _client
|
||||
.from('providers_in_stores')
|
||||
.from(Tables.providersInStores)
|
||||
.select('store_id')
|
||||
.eq('provider_id', existingProvider.id!);
|
||||
linkedStoreIds = (links as List)
|
||||
@@ -83,6 +84,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
String? fiscalCode,
|
||||
String? sdiCode,
|
||||
String? emailPec,
|
||||
String? Function()? colorHex,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -93,6 +95,7 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
fiscalCode: fiscalCode,
|
||||
sdiCode: sdiCode,
|
||||
emailPec: emailPec,
|
||||
colorHex: colorHex,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -123,11 +126,61 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
}
|
||||
|
||||
Future<void> addLocationLocal(ProviderLocationModel location) async {
|
||||
List<ProviderLocationModel> currentLocations = List<ProviderLocationModel>.from(
|
||||
state.localLocations,
|
||||
);
|
||||
|
||||
final bool shouldBeMain = location.isMain || currentLocations.isEmpty;
|
||||
|
||||
if (shouldBeMain) {
|
||||
currentLocations = currentLocations
|
||||
.map((loc) => loc.copyWith(isMain: false))
|
||||
.toList();
|
||||
}
|
||||
|
||||
currentLocations.add(location.copyWith(isMain: shouldBeMain));
|
||||
emit(state.copyWith(localLocations: currentLocations));
|
||||
}
|
||||
|
||||
void updateLocationLocal(int index, ProviderLocationModel location) {
|
||||
final currentLocations = List<ProviderLocationModel>.from(
|
||||
state.localLocations,
|
||||
);
|
||||
currentLocations.add(location);
|
||||
emit(state.copyWith(localLocations: currentLocations));
|
||||
if (index < 0 || index >= currentLocations.length) return;
|
||||
|
||||
bool shouldBeMain = location.isMain;
|
||||
if (!shouldBeMain && currentLocations.length == 1) {
|
||||
shouldBeMain = true;
|
||||
}
|
||||
|
||||
final List<ProviderLocationModel> updatedList = [];
|
||||
for (int i = 0; i < currentLocations.length; i++) {
|
||||
if (i == index) {
|
||||
updatedList.add(location.copyWith(isMain: shouldBeMain));
|
||||
} else {
|
||||
updatedList.add(
|
||||
shouldBeMain
|
||||
? currentLocations[i].copyWith(isMain: false)
|
||||
: currentLocations[i],
|
||||
);
|
||||
}
|
||||
}
|
||||
emit(state.copyWith(localLocations: updatedList));
|
||||
}
|
||||
|
||||
void setMainLocationLocal(int index) {
|
||||
final currentLocations = List<ProviderLocationModel>.from(
|
||||
state.localLocations,
|
||||
);
|
||||
if (index < 0 || index >= currentLocations.length) return;
|
||||
|
||||
final updatedList = currentLocations.asMap().entries.map((entry) {
|
||||
final idx = entry.key;
|
||||
final loc = entry.value;
|
||||
return loc.copyWith(isMain: idx == index);
|
||||
}).toList();
|
||||
|
||||
emit(state.copyWith(localLocations: updatedList));
|
||||
}
|
||||
|
||||
void removeLocationLocal(int index) {
|
||||
@@ -135,7 +188,13 @@ class ProviderFormCubit extends Cubit<ProviderFormState> {
|
||||
state.localLocations,
|
||||
);
|
||||
if (index >= 0 && index < currentLocations.length) {
|
||||
currentLocations.removeAt(index);
|
||||
final removedLoc = currentLocations.removeAt(index);
|
||||
if (removedLoc.id != null && removedLoc.id!.isNotEmpty) {
|
||||
_repository.deleteLocation(removedLoc.id!);
|
||||
}
|
||||
if (removedLoc.isMain && currentLocations.isNotEmpty) {
|
||||
currentLocations[0] = currentLocations[0].copyWith(isMain: true);
|
||||
}
|
||||
emit(state.copyWith(localLocations: currentLocations));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,12 @@ class ProviderRepository {
|
||||
|
||||
// 4. Gestione Sedi (Locations)
|
||||
Future<void> saveLocation(ProviderLocationModel location) async {
|
||||
if (location.isMain && location.providerId.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.providerLocations)
|
||||
.update({'is_main': false})
|
||||
.eq('provider_id', location.providerId);
|
||||
}
|
||||
await _supabase.from(Tables.providerLocations).upsert(location.toMap());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'provider_location_model.dart';
|
||||
import 'provider_role.dart';
|
||||
@@ -8,6 +9,7 @@ class ProviderModel extends Equatable {
|
||||
final String companyId;
|
||||
final String name; // Nome "commerciale" per riconoscerlo velocemente
|
||||
final bool isActive;
|
||||
final String? colorHex;
|
||||
|
||||
// Dati fiscali e legali
|
||||
final String? businessName; // Ragione Sociale
|
||||
@@ -29,6 +31,7 @@ class ProviderModel extends Equatable {
|
||||
required this.companyId,
|
||||
required this.name,
|
||||
this.isActive = true,
|
||||
this.colorHex,
|
||||
this.businessName,
|
||||
this.vatNumber,
|
||||
this.fiscalCode,
|
||||
@@ -42,6 +45,17 @@ class ProviderModel extends Equatable {
|
||||
this.locations,
|
||||
});
|
||||
|
||||
// 🥷 IL GETTER MAGICO: Converte l'esadecimale in un Color di Flutter
|
||||
Color get displayColor {
|
||||
if (colorHex == null || colorHex!.isEmpty) {
|
||||
return Colors.blueGrey; // Colore di default
|
||||
}
|
||||
|
||||
// Rimuove l'eventuale '#' e aggiunge 'FF' per l'opacità (Alpha)
|
||||
final hex = colorHex!.replaceAll('#', '');
|
||||
return Color(int.parse('FF$hex', radix: 16));
|
||||
}
|
||||
|
||||
factory ProviderModel.empty({required String companyId}) {
|
||||
return ProviderModel(
|
||||
companyId: companyId,
|
||||
@@ -56,6 +70,7 @@ class ProviderModel extends Equatable {
|
||||
String? companyId,
|
||||
String? name,
|
||||
bool? isActive,
|
||||
String? Function()? colorHex,
|
||||
String? businessName,
|
||||
String? vatNumber,
|
||||
String? fiscalCode,
|
||||
@@ -73,6 +88,7 @@ class ProviderModel extends Equatable {
|
||||
companyId: companyId ?? this.companyId,
|
||||
name: name ?? this.name,
|
||||
isActive: isActive ?? this.isActive,
|
||||
colorHex: colorHex != null ? colorHex() : this.colorHex,
|
||||
businessName: businessName ?? this.businessName,
|
||||
vatNumber: vatNumber ?? this.vatNumber,
|
||||
fiscalCode: fiscalCode ?? this.fiscalCode,
|
||||
@@ -114,6 +130,7 @@ class ProviderModel extends Equatable {
|
||||
companyId: map['company_id'] as String,
|
||||
name: map['name'] as String,
|
||||
isActive: map['is_active'] as bool? ?? true,
|
||||
colorHex: map['color_hex'] as String?,
|
||||
businessName: map['business_name'] as String?,
|
||||
vatNumber: map['vat_number'] as String?,
|
||||
fiscalCode: map['fiscal_code'] as String?,
|
||||
@@ -134,6 +151,7 @@ class ProviderModel extends Equatable {
|
||||
'company_id': companyId,
|
||||
'name': name,
|
||||
'is_active': isActive,
|
||||
'color_hex': colorHex,
|
||||
'business_name': businessName,
|
||||
'vat_number': vatNumber,
|
||||
'fiscal_code': fiscalCode,
|
||||
@@ -155,6 +173,7 @@ class ProviderModel extends Equatable {
|
||||
companyId,
|
||||
name,
|
||||
isActive,
|
||||
colorHex,
|
||||
businessName,
|
||||
vatNumber,
|
||||
fiscalCode,
|
||||
|
||||
@@ -0,0 +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 supportsOperationType(OperationType? operationType) {
|
||||
if (operationType == null || operationType == OperationType.altro) {
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (operationType) {
|
||||
case OperationType.al ||
|
||||
OperationType.mnp ||
|
||||
OperationType.cb ||
|
||||
OperationType.upselling:
|
||||
return roles.contains(ProviderRole.mobile);
|
||||
case OperationType.nip || OperationType.fwa:
|
||||
return roles.contains(ProviderRole.landline);
|
||||
case OperationType.unica:
|
||||
return roles.contains(ProviderRole.landline) ||
|
||||
roles.contains(ProviderRole.mobile);
|
||||
case OperationType.energy:
|
||||
return roles.contains(ProviderRole.energy);
|
||||
case OperationType.fin:
|
||||
return roles.contains(ProviderRole.financing);
|
||||
case OperationType.entertainment:
|
||||
return roles.contains(ProviderRole.entertainment);
|
||||
case OperationType.telepass:
|
||||
return roles.contains(ProviderRole.telepass);
|
||||
case OperationType.business:
|
||||
return roles.contains(ProviderRole.mobile) ||
|
||||
roles.contains(ProviderRole.landline);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool supportsOperation(String operationType) {
|
||||
final type = OperationType.fromValue(operationType);
|
||||
return supportsOperationType(type);
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,17 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
final List<String> _brandColors = [
|
||||
'#E60000', // Vodafone/Iliad (Rosso scuro)
|
||||
'#0047BB', // TIM (Blu)
|
||||
'#F4811F', // WINDTRE (Arancione)
|
||||
'#FFCC00', // Fastweb (Giallo)
|
||||
'#00A859', // Verde generico
|
||||
'#8E44AD', // Viola
|
||||
'#2C3E50', // Blu scuro/Nero
|
||||
'#607D8B', // BlueGrey (Default)
|
||||
];
|
||||
|
||||
void _flushControllers() {
|
||||
context.read<ProviderFormCubit>().updateFields(
|
||||
name: _nameCtrl.text.trim(),
|
||||
@@ -132,6 +143,8 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
|
||||
children: [
|
||||
_buildGeneralCard(context, state),
|
||||
const SizedBox(height: 24),
|
||||
_buildColorPicker(),
|
||||
const SizedBox(height: 24),
|
||||
_buildRolesCard(context, state),
|
||||
const SizedBox(height: 24),
|
||||
_buildFiscalCard(context),
|
||||
@@ -370,11 +383,47 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
|
||||
itemBuilder: (context, index) {
|
||||
final loc = state.localLocations[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
loc.isMain ? Icons.star : Icons.location_on,
|
||||
color: loc.isMain ? Colors.amber : null,
|
||||
onTap: () async {
|
||||
final providerFormCubit = context.read<ProviderFormCubit>();
|
||||
final res = await showDialog<ProviderLocationModel?>(
|
||||
context: context,
|
||||
builder: (context) => ProviderLocationDialog(initialLocation: loc),
|
||||
);
|
||||
if (res != null) {
|
||||
providerFormCubit.updateLocationLocal(index, res);
|
||||
}
|
||||
},
|
||||
leading: IconButton(
|
||||
tooltip: loc.isMain ? 'Sede predefinita' : 'Imposta come predefinita',
|
||||
icon: Icon(
|
||||
loc.isMain ? Icons.star : Icons.star_border,
|
||||
color: loc.isMain ? Colors.amber : Colors.grey,
|
||||
),
|
||||
onPressed: () => context
|
||||
.read<ProviderFormCubit>()
|
||||
.setMainLocationLocal(index),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(child: Text(loc.name)),
|
||||
if (loc.isMain)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.withValues(alpha: 0.2),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: const Text(
|
||||
'Predefinita',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.amber,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
title: Text(loc.name),
|
||||
subtitle: Text(
|
||||
'${loc.address}, ${loc.city} (${loc.province})',
|
||||
),
|
||||
@@ -392,4 +441,70 @@ class _ProviderFormScreenState extends State<ProviderFormScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildColorPicker() {
|
||||
return Column(
|
||||
children: [
|
||||
const Text(
|
||||
'Colore Riconoscitivo',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<ProviderFormCubit, ProviderFormState>(
|
||||
builder: (context, state) {
|
||||
// Se non ha un colore, usiamo il BlueGrey di default
|
||||
final currentColorHex = state.provider.colorHex ?? '#607D8B';
|
||||
|
||||
return Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: _brandColors.map((hexCode) {
|
||||
final isSelected =
|
||||
currentColorHex.toUpperCase() == hexCode.toUpperCase();
|
||||
|
||||
// Conversione rapida per disegnare il cerchio
|
||||
final colorValue = Color(
|
||||
int.parse('FF${hexCode.replaceAll('#', '')}', radix: 16),
|
||||
);
|
||||
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
onTap: () {
|
||||
// Aggiorniamo il Cubit con il nuovo colore
|
||||
context.read<ProviderFormCubit>().updateFields(
|
||||
colorHex: () => hexCode,
|
||||
);
|
||||
},
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
width: 42,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
color: colorValue,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: isSelected ? Colors.black : Colors.transparent,
|
||||
width: isSelected ? 3 : 0,
|
||||
),
|
||||
boxShadow: [
|
||||
if (isSelected)
|
||||
BoxShadow(
|
||||
color: colorValue.withValues(alpha: 0.4),
|
||||
blurRadius: 8,
|
||||
spreadRadius: 2,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: isSelected
|
||||
? const Icon(Icons.check, color: Colors.white, size: 24)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -117,9 +117,9 @@ class StaffCubit extends Cubit<StaffState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> resetPasswordOrResendInviteLink(String email) async {
|
||||
Future<void> resetPassword(String email) async {
|
||||
try {
|
||||
await _repository.resetPasswordOrResendInviteLink(email);
|
||||
await _repository.resetPassword(email);
|
||||
emit(state.copyWith(status: StaffStatus.emailSent, error: null));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||
@@ -10,19 +11,38 @@ class StaffRepository {
|
||||
// --- ANAGRAFICA PURA ---
|
||||
|
||||
// Prende tutto lo staff della Company (per l'Hub Anagrafiche)
|
||||
Future<List<StaffMemberModel>> getStaffMembers(String companyId) async {
|
||||
final response = await _supabase
|
||||
.from(Tables.staffMembers)
|
||||
.select('''
|
||||
*,
|
||||
store_assignments:${Tables.staffInStores} (
|
||||
${Tables.stores}(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId)
|
||||
.order('name', ascending: true);
|
||||
Future<List<StaffMemberModel>> getStaffMembers(
|
||||
String companyId, {
|
||||
String? storeId,
|
||||
}) async {
|
||||
try {
|
||||
var filterBuilder = _supabase
|
||||
.from(Tables.staffMembers)
|
||||
.select('''
|
||||
*,
|
||||
store_assignments:${Tables.staffInStores} (
|
||||
${Tables.stores}(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId);
|
||||
|
||||
return (response as List).map((s) => StaffMemberModel.fromMap(s)).toList();
|
||||
if (storeId != null) {
|
||||
filterBuilder = filterBuilder.or(
|
||||
'store_id.eq.$storeId,store_id.is.null',
|
||||
);
|
||||
}
|
||||
|
||||
var transformBuilder = filterBuilder.order('name', ascending: true);
|
||||
|
||||
final response = await transformBuilder;
|
||||
|
||||
return (response as List)
|
||||
.map((s) => StaffMemberModel.fromMap(s))
|
||||
.toList();
|
||||
} on Exception catch (e) {
|
||||
debugPrint('Errore nel recupero della lista di staff: $e');
|
||||
throw Exception('Errore nel recupero della lista di staff: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<StaffMemberModel?> getStaffMemberById(String staffId) async {
|
||||
@@ -84,12 +104,16 @@ class StaffRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> resetPasswordOrResendInviteLink(String email) async {
|
||||
Future<void> resetPassword(String email) async {
|
||||
try {
|
||||
await _supabase.auth.resetPasswordForEmail(
|
||||
email,
|
||||
redirectTo: resetPasswordUrl,
|
||||
final response = await Supabase.instance.client.functions.invoke(
|
||||
'reset_password',
|
||||
body: {'email': email.trim()},
|
||||
);
|
||||
|
||||
if (response.status != 200) {
|
||||
throw Exception(response.data['error'] ?? "Errore sconosciuto");
|
||||
}
|
||||
} catch (e) {
|
||||
throw Exception("Errore nell'invio del link: $e");
|
||||
}
|
||||
@@ -129,10 +153,10 @@ class StaffRepository {
|
||||
|
||||
// Assegna un membro a un negozio
|
||||
Future<void> assignStaffToStore(String staffId, String storeId) async {
|
||||
await _supabase.from(Tables.staffInStores).insert({
|
||||
await _supabase.from(Tables.staffInStores).upsert({
|
||||
'staff_member_id': staffId,
|
||||
'store_id': storeId,
|
||||
});
|
||||
}, onConflict: 'staff_member_id,store_id'); // Evita duplicati
|
||||
}
|
||||
|
||||
// Rimuove l'assegnazione
|
||||
|
||||
@@ -90,7 +90,7 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
return ListView.separated(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: list.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 12),
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 6),
|
||||
itemBuilder: (context, index) {
|
||||
return _buildStaffCard(list[index]);
|
||||
},
|
||||
@@ -190,16 +190,23 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
icon: const Icon(Icons.more_vert),
|
||||
onSelected: (value) {
|
||||
if (value == 'invite_reset') {
|
||||
context.read<StaffCubit>().resetPasswordOrResendInviteLink(
|
||||
member.email!,
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Operazione richiesta, controlla l\'email!',
|
||||
if (!member.hasJoined) {
|
||||
context.read<StaffCubit>().inviteStaffMember(
|
||||
member: member,
|
||||
selectedStoreIds: member.assignedStores
|
||||
.map((s) => s.id!)
|
||||
.toList(),
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Invito reinviato, controlla l\'email!',
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
} else {
|
||||
context.read<StaffCubit>().resetPassword(member.email!);
|
||||
}
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
|
||||
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user