Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -54,34 +54,34 @@ jobs:
|
||||
run: Remove-Item -Recurse -Force ./*
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 2: ANDROID APK (Gira sul tuo MacBook)
|
||||
# JOB 2: ANDROID APPBUNDLE (Gira sul runner Fedora o Mac)
|
||||
# -----------------------------------------------------------------
|
||||
build-android:
|
||||
runs-on: macos-runner # <--- Etichetta del tuo Mac
|
||||
runs-on: cross-runner
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Logica Bash per Mac: usiamo le virgolette singole forti per evitare escape strani
|
||||
# Logica Bash per Mac/Linux: usiamo le virgolette singole forti per evitare escape strani
|
||||
- name: Crea file .env
|
||||
run: |
|
||||
cat << 'EOF' > .env
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Build Flutter APK
|
||||
run: flutter build apk --release
|
||||
- name: Build Flutter AppBundle
|
||||
run: flutter build appbundle --release
|
||||
|
||||
# Carichiamo l'APK universale o quelli splittati nelle release di Gitea
|
||||
# Carichiamo l'AAB nelle release di Gitea per poi caricarlo su Google Play Console
|
||||
- name: Upload Android Asset
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: "build/app/outputs/flutter-apk/app-release.apk"
|
||||
files: "build/app/outputs/bundle/release/app-release.aab"
|
||||
api_key: ${{ secrets.MYRELEASE_TOKEN }}
|
||||
|
||||
- name: Aggiorna Link Android su Supabase
|
||||
run: |
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.49f18b19-2129-46c0-b690-a97db725b5a8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/app-release.apk\"}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.49f18b19-2129-46c0-b690-a97db725b5a8" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/app-release.aab\"}"
|
||||
|
||||
- name: Aggiorna Link Windows su Supabase
|
||||
run: |
|
||||
@@ -89,10 +89,10 @@ jobs:
|
||||
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul tuo MacBook)
|
||||
# JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul runner Fedora o Mac)
|
||||
# -----------------------------------------------------------------
|
||||
build-web:
|
||||
runs-on: macos-runner # <--- Etichetta del tuo Mac
|
||||
runs-on: cross-runner
|
||||
steps:
|
||||
- name: Checkout del codice
|
||||
uses: actions/checkout@v3
|
||||
@@ -112,4 +112,63 @@ jobs:
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
npx wrangler pages deploy build/web --project-name="flux" --branch="main"
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner)
|
||||
# -----------------------------------------------------------------
|
||||
build-linux:
|
||||
runs-on: cross-runner # <--- Etichetta del tuo runner Linux / Fedora
|
||||
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 }}
|
||||
@@ -46,3 +46,7 @@ app.*.map.json
|
||||
/android/app/release
|
||||
|
||||
.env
|
||||
|
||||
appimagetool*
|
||||
*.AppDir
|
||||
*.AppImage
|
||||
@@ -1,3 +1,6 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
@@ -8,6 +11,13 @@ plugins {
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
// 2. CARICHIAMO IL KEYSTORE QUI FUORI IN MODO PULITO
|
||||
val keystoreProperties = Properties()
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.catellisrl.flux"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
@@ -23,7 +33,6 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.catellisrl.flux"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
@@ -33,11 +42,22 @@ android {
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties["keyAlias"] as String?
|
||||
keyPassword = keystoreProperties["keyPassword"] as String?
|
||||
storeFile = keystoreProperties["storeFile"]?.let { file(it as String) }
|
||||
storePassword = keystoreProperties["storePassword"] as String?
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
signingConfig = if (keystorePropertiesFile.exists()) {
|
||||
signingConfigs.getByName("release")
|
||||
} else {
|
||||
signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
␍ .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.
@@ -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';
|
||||
@@ -18,6 +20,7 @@ class Tables {
|
||||
static const String stores = 'stores';
|
||||
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';
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ import 'package:flux/features/notes/ui/notes_list_screen.dart';
|
||||
import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart';
|
||||
import 'package:flux/features/onboarding/ui/onboarding_screen.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/ui/operation_form_screen.dart';
|
||||
@@ -505,10 +506,15 @@ class AppRouter {
|
||||
existingOperation: record?.operation,
|
||||
),
|
||||
),
|
||||
BlocProvider(
|
||||
create: (context) => OperationDetailsListCubit(
|
||||
details: record?.operation?.details ?? [],
|
||||
),
|
||||
),
|
||||
],
|
||||
child: OperationFormScreen(
|
||||
operationId: realOperationId,
|
||||
existingOperation: record?.operation,
|
||||
operation: record?.operation,
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,67 +1,94 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class VersionCheckService {
|
||||
final _supabase = Supabase.instance.client;
|
||||
|
||||
/// Controlla se l'app corrente deve essere bloccata o aggiornata.
|
||||
/// Ritorna il link di download se l'aggiornamento è obbligatorio, altrimenti null.
|
||||
Future<String?> checkForceUpdate() async {
|
||||
try {
|
||||
// 1. Determiniamo la piattaforma corrente
|
||||
String platformKey = 'web';
|
||||
if (!kIsWeb) {
|
||||
if (Platform.isAndroid) platformKey = 'android';
|
||||
if (Platform.isWindows) platformKey = 'windows';
|
||||
// 1. Capiamo su che piattaforma sta girando l'app in questo istante
|
||||
String currentPlatform = _getCurrentPlatform();
|
||||
|
||||
// 2. Recuperiamo SOLO la riga corrispondente alla nostra piattaforma
|
||||
final dbResponse = await Supabase.instance.client
|
||||
.from('app_config')
|
||||
.select('min_version, download_url')
|
||||
.eq('platform', currentPlatform)
|
||||
.maybeSingle(); // Usiamo maybeSingle così se non c'è la riga non crasha
|
||||
|
||||
if (dbResponse == null) {
|
||||
return null; // Nessuna regola per questa piattaforma
|
||||
}
|
||||
|
||||
// 2. Recuperiamo la configurazione minima da Supabase
|
||||
final data = await _supabase
|
||||
.from('app_config')
|
||||
.select()
|
||||
.eq('platform', platformKey)
|
||||
.maybeSingle();
|
||||
String minVersionFromDb = dbResponse['min_version'] as String;
|
||||
String downloadUrl = dbResponse['download_url'] as String;
|
||||
|
||||
if (data == null) return null;
|
||||
// 3. Recuperiamo la versione locale di Flutter
|
||||
PackageInfo packageInfo = await PackageInfo.fromPlatform();
|
||||
String localVersionRaw = packageInfo.version;
|
||||
|
||||
final String minVersion = data['min_version'];
|
||||
final String downloadUrl = data['download_url'];
|
||||
// 🥷 TRUCCO 1: Pulizia totale dai build number (+37) o tag "v"
|
||||
String cleanLocal = localVersionRaw
|
||||
.split('+')
|
||||
.first
|
||||
.replaceAll('v', '')
|
||||
.trim();
|
||||
String cleanDb = minVersionFromDb
|
||||
.split('+')
|
||||
.first
|
||||
.replaceAll('v', '')
|
||||
.trim();
|
||||
|
||||
// 3. Recuperiamo la versione attuale dell'app dal pubspec.yaml
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
final String currentVersion = packageInfo.version;
|
||||
|
||||
// 4. Confronto matematico semantico (es. 1.2.3 vs 1.1.9)
|
||||
if (_isVersionLower(currentVersion, minVersion)) {
|
||||
return downloadUrl; // Aggiornamento obbligatorio richiesto!
|
||||
// 🥷 TRUCCO 2: Confronto Semantico Reale
|
||||
if (_isVersionLower(current: cleanLocal, minimum: cleanDb)) {
|
||||
// Ritorna il link VERO per questa specifica piattaforma preso dal CSV!
|
||||
return downloadUrl;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
debugPrint('Errore controllo versione: $e');
|
||||
return null; // In caso di errore non blocchiamo l'utente
|
||||
debugPrint("Errore durante il check versione: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isVersionLower(String current, String min) {
|
||||
// Helper ninja per mappare le piattaforme in base alle stringhe del tuo DB
|
||||
String _getCurrentPlatform() {
|
||||
if (kIsWeb) return 'web';
|
||||
if (Platform.isAndroid) return 'android';
|
||||
if (Platform.isIOS) return 'ios';
|
||||
if (Platform.isWindows) return 'windows';
|
||||
if (Platform.isMacOS) return 'macos';
|
||||
if (Platform.isLinux) return 'linux';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// Il motore matematico (resta invariato)
|
||||
bool _isVersionLower({required String current, required String minimum}) {
|
||||
if (current == minimum) return false;
|
||||
|
||||
List<int> currentParts = current
|
||||
.split('.')
|
||||
.map((e) => int.tryParse(e) ?? 0)
|
||||
.toList();
|
||||
List<int> minParts = min
|
||||
List<int> minParts = minimum
|
||||
.split('.')
|
||||
.map((e) => int.tryParse(e) ?? 0)
|
||||
.toList();
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int currentPart = currentParts.length > i ? currentParts[i] : 0;
|
||||
int minPart = minParts.length > i ? minParts[i] : 0;
|
||||
|
||||
if (currentPart < minPart) return true;
|
||||
if (currentPart > minPart) return false;
|
||||
while (currentParts.length < 3) {
|
||||
currentParts.add(0);
|
||||
}
|
||||
return false;
|
||||
while (minParts.length < 3) {
|
||||
minParts.add(0);
|
||||
}
|
||||
|
||||
if (currentParts[0] != minParts[0]) {
|
||||
return currentParts[0] < minParts[0];
|
||||
}
|
||||
if (currentParts[1] != minParts[1]) {
|
||||
return currentParts[1] < minParts[1];
|
||||
}
|
||||
return currentParts[2] < minParts[2];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -90,6 +90,31 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
|
||||
// --- SELEZIONE FILE DAL PC/TELEFONO ---
|
||||
Future<void> _pickFiles() async {
|
||||
final attachmentsBloc = context.read<AttachmentsBloc>();
|
||||
String? targetId = attachmentsBloc.state.parentId;
|
||||
|
||||
// 🥷 SE L'ID NON C'È (Nuova Operazione), FORZIAMO 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),
|
||||
),
|
||||
);
|
||||
|
||||
// Chiamiamo la funzione passata dal TicketForm/OperationForm
|
||||
targetId = await widget.onEnsureEntitySaved!();
|
||||
}
|
||||
|
||||
// Se il salvataggio fallisce (es. form non valido), ci fermiamo per evitare file orfani
|
||||
if (targetId == null || targetId.isEmpty) return;
|
||||
|
||||
// Comunichiamo immediatamente al BLoC che l'entità padre è stata salvata e ha un nuovo ID.
|
||||
// Questo eviterà che i file finiscano nei `localFiles` temporanei.
|
||||
attachmentsBloc.add(ParentEntitySavedEvent(targetId));
|
||||
}
|
||||
|
||||
final result = await FilePicker.pickFiles(
|
||||
allowMultiple: true,
|
||||
type: FileType.custom,
|
||||
@@ -97,9 +122,147 @@ 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,7 +644,7 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
|
||||
// SE L'ID NON C'È, CHIAMIAMO IL SALVATAGGIO IN BACKGROUND!
|
||||
if (targetId == null) {
|
||||
if (widget.onGenerateIdForQr != null) {
|
||||
if (widget.onEnsureEntitySaved != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
@@ -492,7 +655,7 @@ 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
|
||||
|
||||
@@ -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',
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -3,11 +3,17 @@ import 'package:flutter/material.dart';
|
||||
class QuickRenameDialog extends StatefulWidget {
|
||||
final String suggestedName;
|
||||
final Widget previewWidget; // Può essere Image.memory o un'icona PDF
|
||||
final String title;
|
||||
final String? suffixText;
|
||||
final String confirmButtonText;
|
||||
|
||||
const QuickRenameDialog({
|
||||
super.key,
|
||||
required this.suggestedName,
|
||||
required this.previewWidget,
|
||||
this.title = 'Rinomina File',
|
||||
this.suffixText = '.pdf',
|
||||
this.confirmButtonText = 'Conferma (Invio)',
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -45,7 +51,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Rinomina per Export'),
|
||||
title: Text(widget.title),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -60,10 +66,10 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
TextField(
|
||||
controller: _nameCtrl,
|
||||
focusNode: _focusNode,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nome del file',
|
||||
suffixText: '.pdf', // Facciamo capire che sarà un PDF
|
||||
border: OutlineInputBorder(),
|
||||
suffixText: widget.suffixText,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
// MAGIA UX 2: Se preme invio sulla tastiera, salva e chiude!
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
@@ -77,7 +83,7 @@ class _QuickRenameDialogState extends State<QuickRenameDialog> {
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.of(context).pop(_nameCtrl.text),
|
||||
child: const Text('Esporta (Invio)'),
|
||||
child: Text(widget.confirmButtonText),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -69,6 +69,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
String? note,
|
||||
bool? doNotDisturb,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -79,6 +80,8 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
note: note ?? state.customer.note,
|
||||
doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
|
||||
isBusiness: isBusiness ?? state.customer.isBusiness,
|
||||
fiscalCode:
|
||||
fiscalCode?.trim().toUpperCase() ?? state.customer.fiscalCode,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -111,6 +114,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
String? phone,
|
||||
String? email,
|
||||
required bool isBusiness,
|
||||
String? fiscalCode,
|
||||
}) async {
|
||||
final newCustomer = CustomerModel(
|
||||
name: name,
|
||||
@@ -119,6 +123,7 @@ class CustomerFormCubit extends Cubit<CustomerFormState> {
|
||||
companyId: _sessionCubit.state.company!.id!,
|
||||
note: '',
|
||||
isBusiness: isBusiness,
|
||||
fiscalCode: fiscalCode?.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,7 @@ class CustomerModel extends Equatable {
|
||||
final bool isActive;
|
||||
final List<AttachmentModel> attachments;
|
||||
final bool isBusiness;
|
||||
final String? fiscalCode;
|
||||
|
||||
const CustomerModel({
|
||||
this.id,
|
||||
@@ -29,6 +30,7 @@ class CustomerModel extends Equatable {
|
||||
this.isActive = true,
|
||||
this.attachments = const [],
|
||||
this.isBusiness = false,
|
||||
this.fiscalCode,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -45,6 +47,7 @@ class CustomerModel extends Equatable {
|
||||
isActive,
|
||||
attachments,
|
||||
isBusiness,
|
||||
fiscalCode,
|
||||
];
|
||||
|
||||
factory CustomerModel.empty() => CustomerModel(
|
||||
@@ -69,6 +72,7 @@ class CustomerModel extends Equatable {
|
||||
bool? isActive,
|
||||
List<AttachmentModel>? attachments,
|
||||
bool? isBusiness,
|
||||
String? fiscalCode,
|
||||
}) {
|
||||
return CustomerModel(
|
||||
id: id ?? this.id,
|
||||
@@ -83,6 +87,7 @@ class CustomerModel extends Equatable {
|
||||
isActive: isActive ?? this.isActive,
|
||||
attachments: attachments ?? this.attachments,
|
||||
isBusiness: isBusiness ?? this.isBusiness,
|
||||
fiscalCode: fiscalCode ?? this.fiscalCode,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -108,6 +113,7 @@ class CustomerModel extends Equatable {
|
||||
.toList() ??
|
||||
const [],
|
||||
isBusiness: map['is_business'] as bool? ?? false,
|
||||
fiscalCode: map['fiscal_code'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,6 +130,7 @@ class CustomerModel extends Equatable {
|
||||
'company_id': companyId,
|
||||
'is_active': isActive,
|
||||
'is_business': isBusiness,
|
||||
'fiscal_code': fiscalCode?.trim().toUpperCase(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/widgets/flux_text_field.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/attachments_section.dart';
|
||||
@@ -24,6 +25,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
final TextEditingController _telefonoController = TextEditingController();
|
||||
final TextEditingController _emailController = TextEditingController();
|
||||
final TextEditingController _noteController = TextEditingController();
|
||||
final TextEditingController _fiscalCodeController = TextEditingController();
|
||||
bool _isInitialized = false;
|
||||
|
||||
@override
|
||||
@@ -49,6 +51,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
_telefonoController.dispose();
|
||||
_emailController.dispose();
|
||||
_noteController.dispose();
|
||||
_fiscalCodeController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -65,6 +68,9 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
if (_noteController.text.isEmpty) {
|
||||
_noteController.text = customer.note;
|
||||
}
|
||||
if (_fiscalCodeController.text.isEmpty && customer.fiscalCode != null) {
|
||||
_fiscalCodeController.text = customer.fiscalCode!;
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
@@ -74,6 +80,7 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
phoneNumber: _telefonoController.text.trim(),
|
||||
email: _emailController.text.trim(),
|
||||
note: _noteController.text.trim(),
|
||||
fiscalCode: _fiscalCodeController.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -172,6 +179,20 @@ class _CustomerFormScreenState extends State<CustomerFormScreen> {
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Partita IVA / Codice Fiscale',
|
||||
icon: Icons.person_outline,
|
||||
controller: _fiscalCodeController,
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(
|
||||
RegExp(r'[a-zA-Z0-9]'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FluxTextField(
|
||||
label: 'Note',
|
||||
icon: Icons.notes_outlined,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
|
||||
|
||||
@@ -16,7 +17,8 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
final _phoneCtrl = TextEditingController();
|
||||
final _emailCtrl = TextEditingController();
|
||||
final _noteCtrl = TextEditingController();
|
||||
bool _isBusiness = false; // Aggiungiamo un campo per il tipo di cliente
|
||||
bool _isBusiness = false;
|
||||
final _fiscalCodeCtrl = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
@@ -33,6 +35,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
_phoneCtrl.dispose();
|
||||
_emailCtrl.dispose();
|
||||
_noteCtrl.dispose();
|
||||
_fiscalCodeCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -50,6 +53,7 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
name: _nameCtrl.text.trim(),
|
||||
phone: _phoneCtrl.text.trim(),
|
||||
email: _emailCtrl.text.trim(),
|
||||
fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(),
|
||||
);
|
||||
|
||||
setState(() => _isLoading = false);
|
||||
@@ -125,6 +129,20 @@ class _QuickCustomerDialogState extends State<QuickCustomerDialog> {
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _fiscalCodeCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Codice Fiscale / Partita IVA",
|
||||
),
|
||||
keyboardType: TextInputType.text,
|
||||
autocorrect: false,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
|
||||
],
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _noteCtrl,
|
||||
decoration: const InputDecoration(labelText: "Note rapide"),
|
||||
|
||||
+4
-4
@@ -51,17 +51,17 @@ class DashboardStoreOperationListCubit
|
||||
|
||||
void _loadOperationsSilently() async {
|
||||
try {
|
||||
final operations = await _repository.fetchOperations(
|
||||
final paginatedData = await _repository.fetchPaginatedOperations(
|
||||
companyId: companyId!,
|
||||
storeId: storeId!,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
page: 1,
|
||||
itemsPerPage: 20,
|
||||
);
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardStoreOperationListStatus.success,
|
||||
operations: operations,
|
||||
operations: paginatedData.operations,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
|
||||
+82
-7
@@ -140,14 +140,19 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
operation.type,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: context.primaryText,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
),
|
||||
child: _buildBadgeList(
|
||||
operation.details
|
||||
.map((d) => d.type)
|
||||
.whereType<String>()
|
||||
.where(
|
||||
(t) => t.trim().isNotEmpty,
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
@@ -172,4 +177,74 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBadgeList(List<String> types) {
|
||||
if (types.isEmpty) {
|
||||
return const Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: _OperationTypeBadge(label: 'N/A'),
|
||||
);
|
||||
}
|
||||
|
||||
return Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 4,
|
||||
children: types.map((t) => _OperationTypeBadge(label: t)).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OperationTypeBadge extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
const _OperationTypeBadge({required this.label});
|
||||
|
||||
Color _getBadgeColor(String type) {
|
||||
switch (type.toUpperCase()) {
|
||||
case 'FIN':
|
||||
case 'FINANZIAMENTO':
|
||||
return Colors.deepPurple;
|
||||
case 'TELEPASS':
|
||||
return Colors.amber.shade800;
|
||||
case 'ENERGY':
|
||||
case 'ENERGIA':
|
||||
return Colors.orange.shade800;
|
||||
case 'ENTERTAINMENT':
|
||||
return Colors.pinkAccent.shade700;
|
||||
case 'AL':
|
||||
case 'MNP':
|
||||
return Colors.indigo;
|
||||
case 'NIP':
|
||||
case 'FWA':
|
||||
return Colors.cyan.shade800;
|
||||
case 'FIBRA':
|
||||
case 'MOBILE':
|
||||
return Colors.blue.shade700;
|
||||
default:
|
||||
return Colors.blueGrey;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _getBadgeColor(label);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.2,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/master_data/products/models/model_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
|
||||
part 'operation_details_form_state.dart';
|
||||
|
||||
class OperationDetailsFormCubit extends Cubit<OperationDetailsFormState> {
|
||||
OperationDetailsFormCubit({
|
||||
OperationDetailModel? initialDetail,
|
||||
int? editingIndex,
|
||||
List<ProviderModel>? allProviders,
|
||||
String? defaultProviderId,
|
||||
}) : super(
|
||||
OperationDetailsFormState(
|
||||
operationDetail: initialDetail ?? const OperationDetailModel(),
|
||||
editingIndex: editingIndex,
|
||||
),
|
||||
) {
|
||||
if (initialDetail == null &&
|
||||
allProviders != null &&
|
||||
allProviders.isNotEmpty) {
|
||||
const defaultType = 'AL';
|
||||
setTypeWithSmartDefaults(
|
||||
newType: defaultType,
|
||||
allProviders: allProviders,
|
||||
defaultProviderId: defaultProviderId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void updateFields({
|
||||
String? type,
|
||||
String? subType,
|
||||
ProviderModel? provider,
|
||||
ModelModel? model,
|
||||
String? modelId,
|
||||
String? description,
|
||||
DateTime? expirationDate,
|
||||
}) {
|
||||
final current = state.operationDetail;
|
||||
final updated = current.copyWith(
|
||||
type: type ?? current.type,
|
||||
subType: subType ?? current.subType,
|
||||
provider:
|
||||
provider != null
|
||||
? () => provider
|
||||
: (current.provider != null ? () => current.provider : null),
|
||||
model:
|
||||
model != null
|
||||
? () => model
|
||||
: (current.model != null ? () => current.model : null),
|
||||
modelId: modelId ?? current.modelId,
|
||||
description: description ?? current.description,
|
||||
expirationDate: expirationDate ?? current.expirationDate,
|
||||
);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
operationDetail: updated,
|
||||
status: OperationDetailsFormStatus.ready,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void setProvider(ProviderModel provider) {
|
||||
final updated = state.operationDetail.copyWith(
|
||||
provider: () => provider,
|
||||
providerId: provider.id,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operationDetail: updated,
|
||||
status: OperationDetailsFormStatus.ready,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void setTypeWithSmartDefaults({
|
||||
required String newType,
|
||||
required List<ProviderModel> allProviders,
|
||||
String? defaultProviderId,
|
||||
}) {
|
||||
ProviderModel? selectedProvider;
|
||||
if (defaultProviderId != null) {
|
||||
final foundDefault = allProviders.firstWhere(
|
||||
(p) =>
|
||||
p.id == defaultProviderId &&
|
||||
p.supportsOperation(newType) &&
|
||||
p.isActive,
|
||||
orElse: () => const ProviderModel(companyId: '', name: ''),
|
||||
);
|
||||
if (foundDefault.id != null) {
|
||||
selectedProvider = foundDefault;
|
||||
}
|
||||
}
|
||||
if (selectedProvider == null) {
|
||||
final foundCompatible = allProviders.firstWhere(
|
||||
(p) => p.supportsOperation(newType) && p.isActive,
|
||||
orElse: () => const ProviderModel(companyId: '', name: ''),
|
||||
);
|
||||
if (foundCompatible.id != null) {
|
||||
selectedProvider = foundCompatible;
|
||||
}
|
||||
}
|
||||
|
||||
final current = state.operationDetail;
|
||||
final updated = current.copyWith(
|
||||
type: newType,
|
||||
subType: newType == 'Energy' ? 'Luce' : null,
|
||||
provider: selectedProvider != null ? () => selectedProvider : null,
|
||||
providerId: selectedProvider?.id,
|
||||
);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
operationDetail: updated,
|
||||
status: OperationDetailsFormStatus.ready,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
part of 'operation_details_form_cubit.dart';
|
||||
|
||||
enum OperationDetailsFormStatus { ready, updated, failure }
|
||||
|
||||
class OperationDetailsFormState extends Equatable {
|
||||
final OperationDetailModel operationDetail;
|
||||
final String? errorMessage;
|
||||
final OperationDetailsFormStatus status;
|
||||
final int? editingIndex;
|
||||
|
||||
const OperationDetailsFormState({
|
||||
required this.operationDetail,
|
||||
this.errorMessage,
|
||||
this.status = OperationDetailsFormStatus.ready,
|
||||
this.editingIndex,
|
||||
});
|
||||
|
||||
bool get isEditing => editingIndex != null;
|
||||
|
||||
OperationDetailsFormState copyWith({
|
||||
OperationDetailModel? operationDetail,
|
||||
String? errorMessage,
|
||||
OperationDetailsFormStatus? status,
|
||||
int? Function()? editingIndex,
|
||||
}) {
|
||||
return OperationDetailsFormState(
|
||||
operationDetail: operationDetail ?? this.operationDetail,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
status: status ?? this.status,
|
||||
editingIndex: editingIndex != null ? editingIndex() : this.editingIndex,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
operationDetail,
|
||||
errorMessage,
|
||||
status,
|
||||
editingIndex,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
|
||||
part 'operation_details_list_state.dart';
|
||||
|
||||
class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
|
||||
OperationDetailsListCubit({required List<OperationDetailModel> details})
|
||||
: super(OperationDetailsListState(details: details));
|
||||
|
||||
void addOperationDetail(OperationDetailModel operationDetail) {
|
||||
emit(state.copyWith(status: OperationDetailsListStatus.ready));
|
||||
final updatedDetails = List<OperationDetailModel>.from(state.details);
|
||||
updatedDetails.add(operationDetail);
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: updatedDetails,
|
||||
status: OperationDetailsListStatus.updated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void deleteOperationDetail(int index) {
|
||||
emit(state.copyWith(status: OperationDetailsListStatus.ready));
|
||||
final updatedDetails = List<OperationDetailModel>.from(state.details);
|
||||
updatedDetails.removeAt(index);
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: updatedDetails,
|
||||
status: OperationDetailsListStatus.updated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void toggleOperationDetailsSelection(int index) {
|
||||
final updatedSelectedIds = List<int>.from(state.selectedIds);
|
||||
if (updatedSelectedIds.contains(index)) {
|
||||
updatedSelectedIds.remove(index);
|
||||
} else {
|
||||
updatedSelectedIds.add(index);
|
||||
}
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: state.details,
|
||||
selectedIds: updatedSelectedIds,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void selectAllOperationDetails() {
|
||||
final updatedSelectedIds = List<int>.from(state.selectedIds);
|
||||
for (int i = 0; i < state.details.length; i++) {
|
||||
if (!updatedSelectedIds.contains(i)) {
|
||||
updatedSelectedIds.add(i);
|
||||
}
|
||||
}
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: state.details,
|
||||
selectedIds: updatedSelectedIds,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void clearOperationDetailsSelection() {
|
||||
emit(OperationDetailsListState(details: state.details, selectedIds: []));
|
||||
}
|
||||
|
||||
void deleteSelectedOperationDetails() {
|
||||
emit(state.copyWith(status: OperationDetailsListStatus.ready));
|
||||
final updatedDetails = List<OperationDetailModel>.from(state.details);
|
||||
final updatedSelectedIds = List<int>.from(state.selectedIds);
|
||||
for (int i = updatedSelectedIds.length - 1; i >= 0; i--) {
|
||||
final index = updatedSelectedIds[i];
|
||||
updatedDetails.removeAt(index);
|
||||
}
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: updatedDetails,
|
||||
selectedIds: [],
|
||||
status: OperationDetailsListStatus.updated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void updateOperationDetail(int index, OperationDetailModel operationDetail) {
|
||||
emit(state.copyWith(status: OperationDetailsListStatus.ready));
|
||||
final updatedDetails = List<OperationDetailModel>.from(state.details);
|
||||
updatedDetails[index] = operationDetail;
|
||||
emit(
|
||||
OperationDetailsListState(
|
||||
details: updatedDetails,
|
||||
status: OperationDetailsListStatus.updated,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
part of 'operation_details_list_cubit.dart';
|
||||
|
||||
enum OperationDetailsListStatus { ready, updated, failure }
|
||||
|
||||
class OperationDetailsListState extends Equatable {
|
||||
final List<OperationDetailModel> details;
|
||||
final String? errorMessage;
|
||||
final List<int> selectedIds;
|
||||
final OperationDetailsListStatus status;
|
||||
|
||||
const OperationDetailsListState({
|
||||
this.details = const [],
|
||||
this.errorMessage,
|
||||
this.selectedIds = const [],
|
||||
this.status = OperationDetailsListStatus.ready,
|
||||
});
|
||||
|
||||
OperationDetailsListState copyWith({
|
||||
List<OperationDetailModel>? details,
|
||||
String? errorMessage,
|
||||
List<int>? selectedIds,
|
||||
OperationDetailsListStatus? status,
|
||||
}) {
|
||||
return OperationDetailsListState(
|
||||
details: details ?? this.details,
|
||||
errorMessage: errorMessage,
|
||||
selectedIds: selectedIds ?? this.selectedIds,
|
||||
status: status ?? this.status,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [details, errorMessage, selectedIds, status];
|
||||
}
|
||||
@@ -2,20 +2,17 @@ import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'operation_form_state.dart';
|
||||
|
||||
class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
|
||||
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
|
||||
final Uuid _uuid = const Uuid();
|
||||
final OperationsRepository _repository = sl<OperationsRepository>();
|
||||
final SessionCubit _sessionCubit = sl<SessionCubit>();
|
||||
|
||||
OperationFormCubit({
|
||||
StaffMemberModel? createdBy,
|
||||
@@ -43,16 +40,20 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
state.copyWith(
|
||||
operation: existingOperation,
|
||||
status: OperationFormStatus.ready,
|
||||
isNew: false,
|
||||
hasUnsavedChanges: false,
|
||||
),
|
||||
);
|
||||
} else if (operationId != null) {
|
||||
emit(state.copyWith(status: OperationFormStatus.loading));
|
||||
try {
|
||||
final operation = await _repository.fetchOperationById(operationId);
|
||||
final operation = await _repository.getOperationById(operationId);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: operation,
|
||||
status: OperationFormStatus.ready,
|
||||
isNew: false,
|
||||
hasUnsavedChanges: false,
|
||||
),
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
@@ -64,20 +65,22 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// NUOVA PRATICA: Creiamo un nuovo Batch UUID
|
||||
// NUOVA PRATICA
|
||||
final currentStore = _sessionCubit.state.currentStore;
|
||||
final companyId = _sessionCubit.state.company?.id ?? '';
|
||||
final newOperation = state.operation.copyWith(
|
||||
companyId: companyId,
|
||||
storeId: currentStore?.id,
|
||||
status: OperationStatus.success,
|
||||
reference: '',
|
||||
batchUuid: _uuid.v4(),
|
||||
final initialStaffDisplayName = state.operation.staffDisplayName;
|
||||
final newOperation = await _repository.createNewOperation(
|
||||
currentStore: currentStore!,
|
||||
createdById: state.operation.staffId!,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: newOperation,
|
||||
operation: newOperation.copyWith(
|
||||
staffDisplayName:
|
||||
newOperation.staffDisplayName ?? initialStaffDisplayName,
|
||||
),
|
||||
status: OperationFormStatus.ready,
|
||||
isNew: true,
|
||||
hasUnsavedChanges: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -91,41 +94,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
}
|
||||
}
|
||||
|
||||
// --- LOGICA BATCH ---
|
||||
|
||||
void _prepareNextOperationInBatch() {
|
||||
final current = state.operation;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.ready,
|
||||
operation: OperationModel(
|
||||
companyId: current.companyId,
|
||||
storeId: current.storeId,
|
||||
storeDisplayName: current.storeDisplayName,
|
||||
// 🥷 REINSERIAMO LO STAFF (Il "colpevole" era qui)
|
||||
staffId: current.staffId,
|
||||
staffDisplayName: current.staffDisplayName,
|
||||
|
||||
batchUuid: current.batchUuid,
|
||||
customerId: current.customerId,
|
||||
customer: current.customer,
|
||||
reference: current.reference,
|
||||
status: OperationStatus.draft,
|
||||
createdAt: DateTime.now(),
|
||||
// Mantieni isBusiness se vuoi che rimanga coerente col cliente
|
||||
isBusiness: current.isBusiness,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- SALVATAGGIO ---
|
||||
|
||||
Future<void> saveOperation({
|
||||
required OperationStatus targetStatus,
|
||||
required bool keepAdding,
|
||||
}) async {
|
||||
Future<void> saveOperation({required OperationStatus targetStatus}) async {
|
||||
emit(
|
||||
state.copyWith(status: OperationFormStatus.saving, errorMessage: null),
|
||||
);
|
||||
@@ -146,33 +117,15 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
);
|
||||
}
|
||||
}
|
||||
final savedOperation = await _repository.saveFullOperation(
|
||||
operation: operationToSave,
|
||||
await _repository.updateOperation(operationToSave);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.success,
|
||||
operation: operationToSave,
|
||||
isNew: false,
|
||||
hasUnsavedChanges: false,
|
||||
),
|
||||
);
|
||||
|
||||
if (keepAdding) {
|
||||
// Salviamo nella "memoria" del batch le pratiche create finora
|
||||
final updatedBatchList = List<OperationModel>.from(
|
||||
state.savedBatchOperations,
|
||||
)..add(savedOperation);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.successAndAddAnother,
|
||||
savedBatchOperations: updatedBatchList,
|
||||
),
|
||||
);
|
||||
|
||||
// Pulisce i campi per la prossima operazione
|
||||
_prepareNextOperationInBatch();
|
||||
} else {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.success,
|
||||
operation: savedOperation, // Aggiorniamo con l'ID restituito dal DB
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -183,95 +136,73 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> saveOperationDraft() async {
|
||||
// --- ANNULLA E ELIMINA SE NUOVA ---
|
||||
Future<void> discardAndExit() async {
|
||||
emit(state.copyWith(status: OperationFormStatus.saving));
|
||||
try {
|
||||
final operationToSave = state.operation;
|
||||
if (operationToSave.customerId == null ||
|
||||
operationToSave.customerId!.isEmpty) {
|
||||
throw Exception('Seleziona un cliente prima di poter usare il QR');
|
||||
if (state.isNew && state.operation.id != null) {
|
||||
await _repository.deleteOperation(state.operation.id!);
|
||||
}
|
||||
final savedOperation = await _repository.saveFullOperation(
|
||||
operation: operationToSave,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: savedOperation,
|
||||
status: OperationFormStatus.ready,
|
||||
status: OperationFormStatus.discarded,
|
||||
hasUnsavedChanges: false,
|
||||
),
|
||||
);
|
||||
return savedOperation.id;
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
errorMessage: "Errore durante l'eliminazione dell'operazione: $e",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- ELIMINAZIONE DEFINITIVA PRATICA ---
|
||||
Future<void> deleteCurrentOperation() async {
|
||||
final id = state.operation.id;
|
||||
if (id == null || id.isEmpty) return;
|
||||
|
||||
emit(state.copyWith(status: OperationFormStatus.saving));
|
||||
try {
|
||||
await _repository.deleteOperation(id);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.discarded,
|
||||
hasUnsavedChanges: false,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.failure,
|
||||
errorMessage: "Errore durante l'eliminazione dell'operazione: $e",
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- GESTIONE DEI CAMPI IN TEMPO REALE ---
|
||||
|
||||
void updateFields({
|
||||
String? reference,
|
||||
String? note,
|
||||
String? type,
|
||||
String? providerId,
|
||||
String? providerDisplayName,
|
||||
String? subType,
|
||||
String? description,
|
||||
DateTime? expirationDate,
|
||||
int? quantity,
|
||||
String? modelId,
|
||||
String? modelDisplayName,
|
||||
String? staffId,
|
||||
String? staffDisplayName,
|
||||
OperationStatus? status,
|
||||
bool? isBusiness,
|
||||
|
||||
bool clearProvider = false,
|
||||
bool clearType = false,
|
||||
bool clearSubType = false,
|
||||
bool clearDescription = false,
|
||||
bool clearExpiration = false,
|
||||
bool clearQuantity = false,
|
||||
bool clearModel = false,
|
||||
}) {
|
||||
final current = state.operation;
|
||||
|
||||
int? newQuantity;
|
||||
if (clearQuantity) newQuantity = 1;
|
||||
if (quantity != null && quantity <= 0) newQuantity = 0;
|
||||
if (quantity != null && quantity > 0) newQuantity = quantity;
|
||||
|
||||
final updated = current.copyWith(
|
||||
reference: reference ?? current.reference,
|
||||
note: note ?? current.note,
|
||||
providerId: clearProvider ? null : (providerId ?? current.providerId),
|
||||
providerDisplayName: clearProvider
|
||||
? null
|
||||
: (providerDisplayName ?? current.providerDisplayName),
|
||||
quantity: newQuantity ?? current.quantity,
|
||||
type: clearType ? null : (type ?? current.type),
|
||||
description: clearDescription
|
||||
? null
|
||||
: (description ?? current.description),
|
||||
subType: clearSubType ? null : (subType ?? current.subType),
|
||||
expirationDate: clearExpiration
|
||||
? null
|
||||
: (expirationDate ?? current.expirationDate),
|
||||
modelId: clearModel ? null : (modelId ?? current.modelId),
|
||||
modelDisplayName: clearModel
|
||||
? null
|
||||
: (modelDisplayName ?? current.modelDisplayName),
|
||||
staffId: staffId ?? current.staffId,
|
||||
staffDisplayName: staffDisplayName ?? current.staffDisplayName,
|
||||
status: status ?? current.status,
|
||||
isBusiness: isBusiness ?? current.isBusiness,
|
||||
);
|
||||
|
||||
emit(state.copyWith(operation: updated));
|
||||
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
|
||||
}
|
||||
|
||||
void updateCustomer(CustomerModel customer) {
|
||||
@@ -281,131 +212,12 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
customerId: customer.id,
|
||||
isBusiness: isBusiness,
|
||||
);
|
||||
emit(state.copyWith(operation: updatedOperation));
|
||||
emit(state.copyWith(operation: updatedOperation, hasUnsavedChanges: true));
|
||||
}
|
||||
|
||||
// --- UTILS ---
|
||||
|
||||
void updateOperationType(
|
||||
String newType, {
|
||||
required List<ProviderModel> allProviders,
|
||||
String? defaultProviderId,
|
||||
}) {
|
||||
// 1. Aggiorniamo il tipo nel modello in canna
|
||||
// (Presumo tu abbia un metodo copyWith o simile)
|
||||
final updatedOp = state.operation.copyWith(type: newType, subType: '');
|
||||
|
||||
// 2. Prepariamoci ad auto-selezionare il provider
|
||||
String? newProviderId = updatedOp.providerId;
|
||||
String? newProviderName = updatedOp.providerDisplayName;
|
||||
|
||||
// 3. LA LOGICA DI DEFAULT
|
||||
if (defaultProviderId != null) {
|
||||
// Troviamo il provider di default nella lista
|
||||
final defaultProvider = allProviders
|
||||
.where((p) => p.id == defaultProviderId)
|
||||
.firstOrNull;
|
||||
|
||||
if (defaultProvider != null) {
|
||||
// Usiamo l'extension appena creata!
|
||||
if (defaultProvider.supportsOperation(newType)) {
|
||||
newProviderId = defaultProvider.id;
|
||||
newProviderName = defaultProvider.name;
|
||||
} else {
|
||||
// Se cambi tipo (es. da Mobile a Luce) e il default non lo supporta, sbianchiamo
|
||||
newProviderId = null;
|
||||
newProviderName = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Emettiamo il nuovo stato
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: updatedOp.copyWith(
|
||||
providerId: newProviderId,
|
||||
providerDisplayName: newProviderName,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void setTypeWithSmartDefaults({
|
||||
required String newType,
|
||||
required List<ProviderModel> allProviders,
|
||||
String? defaultProviderId,
|
||||
}) {
|
||||
final currentOp = state.operation;
|
||||
|
||||
// -----------------------------------------
|
||||
// 1. SMART DATES: Calcolo Scadenze Default
|
||||
// -----------------------------------------
|
||||
DateTime? defaultDate;
|
||||
final now = DateTime.now();
|
||||
|
||||
if (newType == 'Energy') {
|
||||
defaultDate = DateTime(now.year, now.month + 24, now.day);
|
||||
}
|
||||
if (newType == 'Fin') {
|
||||
defaultDate = DateTime(now.year, now.month + 30, now.day);
|
||||
}
|
||||
if (newType == 'Entertainment') {
|
||||
defaultDate = DateTime(now.year, now.month + 12, now.day);
|
||||
}
|
||||
|
||||
// -----------------------------------------
|
||||
// 2. SMART PROVIDER: Filtro e Auto-Selezione
|
||||
// -----------------------------------------
|
||||
String? newProviderId = currentOp.providerId;
|
||||
String? newProviderName = currentOp.providerDisplayName;
|
||||
|
||||
// A) Il provider attuale è ancora compatibile col nuovo tipo scelto?
|
||||
if (newProviderId != null && newProviderId.isNotEmpty) {
|
||||
final currentProvider = allProviders
|
||||
.where((p) => p.id == newProviderId)
|
||||
.firstOrNull;
|
||||
|
||||
if (currentProvider == null ||
|
||||
!currentProvider.supportsOperation(newType)) {
|
||||
// Non è più compatibile (es. da TIM fisso passo a Energy). Lo sbianchiamo!
|
||||
newProviderId = null;
|
||||
newProviderName = null;
|
||||
}
|
||||
}
|
||||
|
||||
// B) Se non c'è un provider selezionato, proviamo ad auto-inserire quello di default del negozio
|
||||
if ((newProviderId == null || newProviderId.isEmpty) &&
|
||||
defaultProviderId != null) {
|
||||
final defaultProvider = allProviders
|
||||
.where((p) => p.id == defaultProviderId)
|
||||
.firstOrNull;
|
||||
|
||||
// Controlliamo che il default del negozio supporti questa specifica operazione
|
||||
if (defaultProvider != null &&
|
||||
defaultProvider.supportsOperation(newType)) {
|
||||
newProviderId = defaultProvider.id;
|
||||
newProviderName = defaultProvider.name;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------
|
||||
// 3. EMISSIONE DELLO STATO PULITO
|
||||
// -----------------------------------------
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: currentOp.copyWith(
|
||||
type: newType,
|
||||
subType:
|
||||
'', // Resettiamo il sottotipo per evitare incongruenze (es. passo da Luce a DAZN)
|
||||
expirationDate:
|
||||
defaultDate, // Impostiamo la scadenza di default se calcolata
|
||||
providerId: newProviderId,
|
||||
providerDisplayName: newProviderName,
|
||||
|
||||
modelId: null,
|
||||
modelDisplayName: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
void updateOperationDetailsList(List<OperationDetailModel> details) {
|
||||
final current = state.operation;
|
||||
final updated = current.copyWith(details: details);
|
||||
emit(state.copyWith(operation: updated, hasUnsavedChanges: true));
|
||||
}
|
||||
}
|
||||
@@ -6,35 +6,38 @@ enum OperationFormStatus {
|
||||
ready,
|
||||
saving,
|
||||
success,
|
||||
successAndAddAnother, // Nuovo stato in stile Ticket!
|
||||
failure,
|
||||
discarded,
|
||||
}
|
||||
|
||||
class OperationFormState extends Equatable {
|
||||
final OperationFormStatus status;
|
||||
final OperationModel operation;
|
||||
final String? errorMessage;
|
||||
// Teniamo traccia delle operazioni salvate in questa sessione (per UI riepilogo)
|
||||
final List<OperationModel> savedBatchOperations;
|
||||
final bool isNew;
|
||||
final bool hasUnsavedChanges;
|
||||
|
||||
const OperationFormState({
|
||||
this.status = OperationFormStatus.initial,
|
||||
required this.operation,
|
||||
this.errorMessage,
|
||||
this.savedBatchOperations = const [],
|
||||
this.isNew = false,
|
||||
this.hasUnsavedChanges = false,
|
||||
});
|
||||
|
||||
OperationFormState copyWith({
|
||||
OperationFormStatus? status,
|
||||
OperationModel? operation,
|
||||
String? errorMessage,
|
||||
List<OperationModel>? savedBatchOperations,
|
||||
bool? isNew,
|
||||
bool? hasUnsavedChanges,
|
||||
}) {
|
||||
return OperationFormState(
|
||||
status: status ?? this.status,
|
||||
operation: operation ?? this.operation,
|
||||
errorMessage: errorMessage,
|
||||
savedBatchOperations: savedBatchOperations ?? this.savedBatchOperations,
|
||||
isNew: isNew ?? this.isNew,
|
||||
hasUnsavedChanges: hasUnsavedChanges ?? this.hasUnsavedChanges,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ class OperationFormState extends Equatable {
|
||||
status,
|
||||
operation,
|
||||
errorMessage,
|
||||
savedBatchOperations,
|
||||
isNew,
|
||||
hasUnsavedChanges,
|
||||
];
|
||||
}
|
||||
@@ -12,72 +12,116 @@ class OperationListCubit extends Cubit<OperationListState> {
|
||||
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
|
||||
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
|
||||
|
||||
OperationListCubit() : super(const OperationListState()) {
|
||||
loadOperations(refresh: true);
|
||||
}
|
||||
OperationListCubit() : super(const OperationListState());
|
||||
|
||||
Future<void> loadOperations({bool refresh = false}) async {
|
||||
if (state.status == OperationListStatus.loading) return;
|
||||
if (!refresh && state.hasReachedMax) return;
|
||||
int _fetchId = 0;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationListStatus.loading,
|
||||
errorMessage: null,
|
||||
operations: refresh ? [] : state.operations,
|
||||
hasReachedMax: refresh ? false : state.hasReachedMax,
|
||||
),
|
||||
);
|
||||
// 🥷 MOTORE 1: DESKTOP (Sostituisce la lista)
|
||||
Future<void> loadSpecificPageDesktop(int page) async {
|
||||
final currentFetchId = ++_fetchId;
|
||||
emit(state.copyWith(status: OperationListStatus.loading));
|
||||
|
||||
try {
|
||||
final currentOffset = refresh ? 0 : state.operations.length;
|
||||
final companyId = _sessionCubit.state.company?.id;
|
||||
|
||||
if (companyId == null) {
|
||||
throw Exception("Company ID non trovato nella sessione");
|
||||
}
|
||||
|
||||
final newOperations = await _repository.fetchOperations(
|
||||
companyId: companyId,
|
||||
offset: currentOffset,
|
||||
limit: 50,
|
||||
searchTerm: state.query,
|
||||
final paginatedData = await _repository.fetchPaginatedOperations(
|
||||
companyId: companyId!,
|
||||
page: page,
|
||||
itemsPerPage: state.itemsPerPage,
|
||||
searchTerm: state.searchTerm,
|
||||
dateRange: state.dateRange,
|
||||
);
|
||||
|
||||
final bool reachedMax = newOperations.length < 50;
|
||||
if (currentFetchId != _fetchId) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationListStatus.success,
|
||||
operations: refresh
|
||||
? newOperations
|
||||
: [...state.operations, ...newOperations],
|
||||
hasReachedMax: reachedMax,
|
||||
operations: paginatedData.operations, // 🎯 SOSTITUISCE I DATI
|
||||
totalItems: paginatedData.totalCount,
|
||||
currentPage: page,
|
||||
hasReachedMax: paginatedData.operations.length < state.itemsPerPage,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (currentFetchId != _fetchId) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationListStatus.failure,
|
||||
errorMessage: "Errore nel caricamento operazioni: $e",
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void updateFilters({String? query, DateTimeRange? range}) {
|
||||
// 🥷 MOTORE 2: MOBILE (Accoda alla lista)
|
||||
Future<void> loadNextPageMobile({bool refresh = false}) async {
|
||||
if (state.hasReachedMax && !refresh) return;
|
||||
|
||||
final currentFetchId = ++_fetchId;
|
||||
|
||||
// Se stiamo pullando verso il basso (refresh), ripartiamo da pagina 1
|
||||
final targetPage = refresh ? 1 : state.currentPage + 1;
|
||||
|
||||
// Mostriamo il loading solo se è un refresh totale, altrimenti manteniamo lo stato success
|
||||
// per non far sparire la UI mentre carica in fondo
|
||||
if (refresh) emit(state.copyWith(status: OperationListStatus.loading));
|
||||
|
||||
try {
|
||||
final companyId = _sessionCubit.state.company?.id;
|
||||
final paginatedData = await _repository.fetchPaginatedOperations(
|
||||
companyId: companyId!,
|
||||
page: targetPage,
|
||||
itemsPerPage: state.itemsPerPage,
|
||||
searchTerm: state.searchTerm,
|
||||
dateRange: state.dateRange,
|
||||
);
|
||||
|
||||
if (currentFetchId != _fetchId) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationListStatus.success,
|
||||
// 🎯 ACCODA I DATI SE NON È REFRESH, ALTRIMENTI SOSTITUISCE
|
||||
operations:
|
||||
refresh ? paginatedData.operations : List.of(state.operations)
|
||||
..addAll(paginatedData.operations),
|
||||
totalItems: paginatedData.totalCount,
|
||||
currentPage: targetPage,
|
||||
hasReachedMax: paginatedData.operations.length < state.itemsPerPage,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (currentFetchId != _fetchId) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationListStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void updateFilters({String? text, DateTimeRange? range}) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
query: query ?? state.query,
|
||||
dateRange: range ?? state.dateRange,
|
||||
// 🥷 FORZIAMO IL TIPO: Diciamo a Dart che il risultato del ternario è proprio una funzione
|
||||
searchTerm: text != null ? () => text : null,
|
||||
dateRange: range != null ? () => range : null,
|
||||
|
||||
currentPage: 1, // Reset obbligatorio alla prima pagina
|
||||
hasReachedMax: false,
|
||||
),
|
||||
);
|
||||
loadOperations(refresh: true);
|
||||
|
||||
// Ricarichiamo la pagina 1 con i nuovi filtri applicati
|
||||
loadSpecificPageDesktop(1);
|
||||
}
|
||||
|
||||
void clearFilters() {
|
||||
emit(const OperationListState()); // Resetta tutto allo stato iniziale
|
||||
loadOperations(refresh: true);
|
||||
// Invece di un const vuoto che potrebbe bruciarti l'impostazione itemsPerPage,
|
||||
// creiamo uno stato pulito ma manteniamo la preferenza di paginazione.
|
||||
emit(OperationListState(itemsPerPage: state.itemsPerPage));
|
||||
|
||||
loadSpecificPageDesktop(1);
|
||||
}
|
||||
}
|
||||
@@ -5,35 +5,57 @@ enum OperationListStatus { initial, loading, success, failure }
|
||||
class OperationListState extends Equatable {
|
||||
final OperationListStatus status;
|
||||
final List<OperationModel> operations;
|
||||
final bool hasReachedMax;
|
||||
final String? errorMessage;
|
||||
final String query;
|
||||
|
||||
// Paginazione Ibrida
|
||||
final int currentPage;
|
||||
final int itemsPerPage;
|
||||
final int totalItems;
|
||||
final bool hasReachedMax;
|
||||
|
||||
// 🥷 I FILTRI MANCANTI (Riparati!)
|
||||
final String? searchTerm;
|
||||
final DateTimeRange? dateRange;
|
||||
|
||||
const OperationListState({
|
||||
this.status = OperationListStatus.initial,
|
||||
this.operations = const [],
|
||||
this.hasReachedMax = false,
|
||||
this.errorMessage,
|
||||
this.query = '',
|
||||
this.currentPage = 1,
|
||||
this.itemsPerPage = 25,
|
||||
this.totalItems = 0,
|
||||
this.hasReachedMax = false,
|
||||
this.searchTerm,
|
||||
this.dateRange,
|
||||
});
|
||||
|
||||
int get totalPages => (totalItems / itemsPerPage).ceil();
|
||||
|
||||
// 🥷 COPYWITH AVANZATO: Gestisce lo sbiancamento dei filtri alla perfezione
|
||||
OperationListState copyWith({
|
||||
OperationListStatus? status,
|
||||
List<OperationModel>? operations,
|
||||
bool? hasReachedMax,
|
||||
String? errorMessage,
|
||||
String? query,
|
||||
DateTimeRange? dateRange,
|
||||
int? currentPage,
|
||||
int? itemsPerPage,
|
||||
int? totalItems,
|
||||
bool? hasReachedMax,
|
||||
String? Function()? searchTerm, // Callback per gestire il null esplicito
|
||||
DateTimeRange? Function()?
|
||||
dateRange, // Callback per gestire il null esplicito
|
||||
}) {
|
||||
return OperationListState(
|
||||
status: status ?? this.status,
|
||||
operations: operations ?? this.operations,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
currentPage: currentPage ?? this.currentPage,
|
||||
itemsPerPage: itemsPerPage ?? this.itemsPerPage,
|
||||
totalItems: totalItems ?? this.totalItems,
|
||||
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
|
||||
errorMessage: errorMessage,
|
||||
query: query ?? this.query,
|
||||
dateRange: dateRange ?? this.dateRange,
|
||||
|
||||
// Se passi la funzione la eseguiamo, altrimenti teniamo il valore corrente
|
||||
searchTerm: searchTerm != null ? searchTerm() : this.searchTerm,
|
||||
dateRange: dateRange != null ? dateRange() : this.dateRange,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,9 +63,12 @@ class OperationListState extends Equatable {
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
operations,
|
||||
hasReachedMax,
|
||||
errorMessage,
|
||||
query,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
totalItems,
|
||||
hasReachedMax,
|
||||
searchTerm,
|
||||
dateRange,
|
||||
];
|
||||
}
|
||||
@@ -1,63 +1,72 @@
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/models/paginated_operations.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import '../models/operation_model.dart';
|
||||
|
||||
class OperationsRepository {
|
||||
final _supabase = Supabase.instance.client;
|
||||
final companyId = GetIt.I.get<SessionCubit>().state.company!.id;
|
||||
final SupabaseClient _supabase = sl<SupabaseClient>();
|
||||
|
||||
// --- RECUPERO SINGOLO SERVIZIO CON JOIN COMPLETO ---
|
||||
Future<OperationModel> fetchOperationById(String id) async {
|
||||
Future<OperationModel?> getOperationById(String id) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(Tables.operations)
|
||||
.select('''
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(name),
|
||||
${Tables.staffMembers}(name),
|
||||
${Tables.providers}(name),
|
||||
${Tables.models}(name_with_brand),
|
||||
${Tables.attachments}(*)
|
||||
''')
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*),
|
||||
${Tables.operationDetails}(
|
||||
*,
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(*)
|
||||
)
|
||||
''')
|
||||
.eq('id', id)
|
||||
.single();
|
||||
|
||||
debugPrint('response: $response');
|
||||
return OperationModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nel caricamento del servizio: $e');
|
||||
} on Exception catch (e) {
|
||||
debugPrint('response error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- RECUPERO PAGINATO CON FILTRI E JOIN ---
|
||||
Future<List<OperationModel>> fetchOperations({
|
||||
Future<PaginatedOperations> fetchPaginatedOperations({
|
||||
required String companyId,
|
||||
String? storeId,
|
||||
String? staffId,
|
||||
String? providerId,
|
||||
required int offset,
|
||||
int limit = 50,
|
||||
required int page,
|
||||
int itemsPerPage = 20,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
}) async {
|
||||
try {
|
||||
// Calcoliamo il range di partenza e fine per Supabase
|
||||
// Es. Pagina 1, 25 items -> range(0, 24)
|
||||
// Es. Pagina 2, 25 items -> range(25, 49)
|
||||
final from = (page - 1) * itemsPerPage;
|
||||
final to = from + itemsPerPage - 1;
|
||||
|
||||
var query = _supabase
|
||||
.from(Tables.operations)
|
||||
.select('''
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(name),
|
||||
${Tables.providers}(name),
|
||||
${Tables.models}(name_with_brand),
|
||||
${Tables.staffMembers}(name),
|
||||
${Tables.attachments}(*)
|
||||
''')
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*),
|
||||
${Tables.operationDetails}(
|
||||
*,
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId);
|
||||
|
||||
// Filtro Range Date
|
||||
@@ -79,26 +88,54 @@ class OperationsRepository {
|
||||
query = query.or('provider_id.eq.$providerId,provider_id.is.null');
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.isNotEmpty) {
|
||||
// Filtra sui campi della tabella principale O su quelli della tabella joinata
|
||||
query = query.or(
|
||||
'reference.ilike.%$searchTerm%,note.ilike.%$searchTerm%,customer.name.ilike.%$searchTerm%',
|
||||
);
|
||||
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
|
||||
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
|
||||
List<String> matchingCustomerIds = [];
|
||||
try {
|
||||
final customersRes = await _supabase
|
||||
.from(Tables.customers)
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%')
|
||||
.limit(100);
|
||||
matchingCustomerIds = (customersRes as List)
|
||||
.map((c) => c['id'].toString())
|
||||
.toList();
|
||||
} catch (_) {}
|
||||
|
||||
final List<String> orConditions = [
|
||||
'reference.ilike.%$cleanTerm%',
|
||||
'note.ilike.%$cleanTerm%',
|
||||
'description.ilike.%$cleanTerm%',
|
||||
];
|
||||
if (matchingCustomerIds.isNotEmpty) {
|
||||
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
|
||||
}
|
||||
query = query.or(orConditions.join(','));
|
||||
}
|
||||
|
||||
final response = await query
|
||||
.order('created_at', ascending: false)
|
||||
.range(offset, offset + limit - 1);
|
||||
|
||||
return (response as List)
|
||||
.range(from, to)
|
||||
.count(CountOption.exact);
|
||||
// 3. Estrazione dei dati
|
||||
final List<OperationModel> operations = (response.data as List)
|
||||
.map((map) => OperationModel.fromMap(map))
|
||||
.toList();
|
||||
|
||||
final int totalCount = response.count;
|
||||
|
||||
return PaginatedOperations(
|
||||
operations: operations,
|
||||
totalCount: totalCount,
|
||||
);
|
||||
} catch (e) {
|
||||
throw Exception('$e');
|
||||
debugPrint('Errore nel recupero della pagina $page: $e');
|
||||
throw Exception('Errore nel recupero della pagina $page: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Stream<List<OperationModel>> watchStoreOperations({
|
||||
Stream<List<Map<String, dynamic>>> watchStoreOperations({
|
||||
required String storeId,
|
||||
required int limit,
|
||||
}) {
|
||||
@@ -107,221 +144,90 @@ class OperationsRepository {
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('store_id', storeId)
|
||||
.order('created_at', ascending: false)
|
||||
.limit(limit)
|
||||
.map(
|
||||
(listOfMaps) =>
|
||||
listOfMaps.map((map) => OperationModel.fromMap(map)).toList(),
|
||||
);
|
||||
.limit(limit);
|
||||
}
|
||||
|
||||
// --- SALVATAGGIO COMPLETO (PRIMA PADRE, POI FIGLI) ---
|
||||
Future<OperationModel> saveFullOperation({
|
||||
required OperationModel operation,
|
||||
Future<OperationModel> createNewOperation({
|
||||
required StoreModel currentStore,
|
||||
required String createdById,
|
||||
}) async {
|
||||
try {
|
||||
// 1. Salvataggio classico dell'operazione corrente
|
||||
final response = await _supabase
|
||||
final res = await _supabase
|
||||
.from(Tables.operations)
|
||||
.upsert(operation.toMap())
|
||||
.select(
|
||||
'*, ${Tables.providers}(*), ${Tables.models}(*), ${Tables.stores}(*), ${Tables.staffMembers}(*), ${Tables.customers}(*), ${Tables.attachments}(*)',
|
||||
.insert(
|
||||
OperationModel.empty()
|
||||
.copyWith(
|
||||
storeId: currentStore.id,
|
||||
staffId: createdById,
|
||||
companyId: currentStore.companyId,
|
||||
status: OperationStatus.success,
|
||||
)
|
||||
.toMap(),
|
||||
)
|
||||
.select('''
|
||||
*,
|
||||
${Tables.staffMembers}(*)
|
||||
''')
|
||||
.single();
|
||||
|
||||
final savedOperation = OperationModel.fromMap(response);
|
||||
|
||||
// 2. ALLINEAMENTO BATCH SEMPRE ATTIVO!
|
||||
if (operation.batchUuid.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.operations)
|
||||
.update({'note': operation.note}) // Spalmiamo la nota attuale
|
||||
.eq(
|
||||
'batch_uuid',
|
||||
operation.batchUuid,
|
||||
); // Su tutte le pratiche di questo scontrino
|
||||
}
|
||||
|
||||
return savedOperation;
|
||||
} catch (e) {
|
||||
throw Exception("Errore nel salvataggio dell'operazione: $e");
|
||||
return OperationModel.fromMap(res);
|
||||
} on Exception catch (e) {
|
||||
debugPrint('ERRORE CREAZIONE OPERAZIONE: $e');
|
||||
throw Exception('Errore nella creazione dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- ELIMINAZIONE ---
|
||||
Future<void> deleteOperation(String id) async {
|
||||
try {
|
||||
await _supabase.from(Tables.operations).delete().eq('id', id);
|
||||
} catch (e) {
|
||||
throw Exception('$e');
|
||||
debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e');
|
||||
throw Exception('Errore nella cancellazione dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- RECUPERO TIPI CONTENUTI PIÙ FREQUENTI PER AUTOCOMPLETE ---
|
||||
Future<List<String>> fetchTopEntertainmentTypes(String companyId) async {
|
||||
try {
|
||||
// Cerchiamo i tipi più frequenti associati ai servizi di questa company
|
||||
// Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id
|
||||
final response = await _supabase
|
||||
.from(Tables.operations)
|
||||
.select('description')
|
||||
.eq('company_id', companyId)
|
||||
.eq('type', 'Entertainment')
|
||||
.limit(50); // Prendiamo un campione
|
||||
|
||||
// Logica rapida per contare le occorrenze e prendere i primi 5
|
||||
final Map<String, int> counts = {};
|
||||
for (var item in (response as List)) {
|
||||
final description = item['description'] as String;
|
||||
counts[description] = (counts[description] ?? 0) + 1;
|
||||
}
|
||||
|
||||
var sortedKeys = counts.keys.toList()
|
||||
..sort((a, b) => counts[b]!.compareTo(counts[a]!));
|
||||
|
||||
return sortedKeys.take(5).toList();
|
||||
} catch (e) {
|
||||
return [
|
||||
"Netflix",
|
||||
"DAZN",
|
||||
"Disney+",
|
||||
"Sky",
|
||||
]; // Fallback se non c'è ancora storia
|
||||
}
|
||||
}
|
||||
|
||||
/// Ascolta in tempo reale i file caricati per una pratica
|
||||
Stream<List<AttachmentModel>> getOperationFilesStream(String operationId) {
|
||||
return _supabase
|
||||
.from(Tables.attachments)
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('operation_id', operationId)
|
||||
.order('created_at', ascending: false)
|
||||
.map(
|
||||
(listOfMaps) =>
|
||||
listOfMaps.map((map) => AttachmentModel.fromMap(map)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AttachmentModel> uploadAndRegisterOperationFile({
|
||||
required String operationId,
|
||||
required PlatformFile pickedFile,
|
||||
}) async {
|
||||
final cleanFileName = pickedFile.name.replaceAll(
|
||||
RegExp(r'[^a-zA-Z0-9\.\-]'),
|
||||
'_',
|
||||
);
|
||||
final storagePath =
|
||||
'$companyId/operations/$operationId/${DateTime.now().millisecondsSinceEpoch}_$cleanFileName';
|
||||
final int fileSize = pickedFile.size;
|
||||
final fileToSave = AttachmentModel(
|
||||
companyId: GetIt.I.get<SessionCubit>().state.company!.id!,
|
||||
operationId: operationId,
|
||||
name: cleanFileName.fileNameWithoutExtension(),
|
||||
extension: cleanFileName.fileExtension(),
|
||||
storagePath: storagePath,
|
||||
fileSize: fileSize,
|
||||
);
|
||||
final String mimeType = fileToSave.extension.toLowerCase() == 'pdf'
|
||||
? 'application/pdf'
|
||||
: 'image/${fileToSave.extension}';
|
||||
try {
|
||||
// Usiamo bytes invece del path per massima compatibilità
|
||||
if (pickedFile.bytes == null && pickedFile.path == null) {
|
||||
throw 'Impossibile leggere il contenuto del file';
|
||||
}
|
||||
|
||||
// Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes
|
||||
if (pickedFile.bytes != null) {
|
||||
await _supabase.storage
|
||||
.from('documents')
|
||||
.uploadBinary(
|
||||
storagePath,
|
||||
pickedFile.bytes!,
|
||||
fileOptions: FileOptions(contentType: mimeType, upsert: true),
|
||||
);
|
||||
}
|
||||
|
||||
final response = await _supabase
|
||||
.from(Tables.attachments)
|
||||
.insert(fileToSave.toMap())
|
||||
.select()
|
||||
.single();
|
||||
|
||||
return AttachmentModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw 'Errore durante l\'upload: $e';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> copyFileToCustomer({
|
||||
required AttachmentModel file,
|
||||
required String customerId,
|
||||
}) async {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'customer_id': customerId})
|
||||
.eq('id', file.id!);
|
||||
}
|
||||
|
||||
Future<void> renameAttachment(String id, String newName) async {
|
||||
Future<void> updateOperation(OperationModel operation) async {
|
||||
try {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'name': newName})
|
||||
.eq('id', id);
|
||||
} catch (e) {
|
||||
throw '$e';
|
||||
}
|
||||
}
|
||||
.from(Tables.operations)
|
||||
.update(operation.toMap())
|
||||
.eq('id', operation.id!);
|
||||
|
||||
Future<void> deleteSpecificOperationFile(AttachmentModel file) async {
|
||||
try {
|
||||
if (file.customerId == null) {
|
||||
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
|
||||
await _supabase.storage.from('documents').remove([file.storagePath!]);
|
||||
} else {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'operation_id': null})
|
||||
.eq('id', file.id!);
|
||||
}
|
||||
} catch (e) {
|
||||
throw '$e';
|
||||
}
|
||||
}
|
||||
final currentDetailIds =
|
||||
operation.details
|
||||
.map((d) => d.id)
|
||||
.where((id) => id != null && id.isNotEmpty)
|
||||
.cast<String>()
|
||||
.toList();
|
||||
|
||||
Future<void> deleteOperationFiles(List<AttachmentModel> files) async {
|
||||
if (files.isEmpty) return;
|
||||
// 1. Prepariamo le liste di ID e di Percorsi
|
||||
final List<String> idsToDelete = [];
|
||||
final List<String> idsToEdit = [];
|
||||
final List<String> storagePathsToDelete = [];
|
||||
for (var file in files) {
|
||||
if (file.customerId == null) {
|
||||
idsToDelete.add(file.id!);
|
||||
storagePathsToDelete.add(file.storagePath!);
|
||||
} else {
|
||||
idsToEdit.add(file.id!);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (idsToDelete.isNotEmpty) {
|
||||
if (currentDetailIds.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.from(Tables.operationDetails)
|
||||
.delete()
|
||||
.inFilter('id', idsToDelete);
|
||||
await _supabase.storage.from('documents').remove(storagePathsToDelete);
|
||||
}
|
||||
if (idsToEdit.isNotEmpty) {
|
||||
.eq('operation_id', operation.id!)
|
||||
.not('id', 'in', currentDetailIds);
|
||||
} else {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'operation_id': null})
|
||||
.inFilter('id', idsToEdit);
|
||||
.from(Tables.operationDetails)
|
||||
.delete()
|
||||
.eq('operation_id', operation.id!);
|
||||
}
|
||||
|
||||
for (OperationDetailModel detail in operation.details) {
|
||||
final detailToSave = detail.copyWith(
|
||||
operationId:
|
||||
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
|
||||
companyId:
|
||||
detail.companyId.isNotEmpty
|
||||
? detail.companyId
|
||||
: operation.companyId,
|
||||
);
|
||||
await _supabase
|
||||
.from(Tables.operationDetails)
|
||||
.upsert(detailToSave.toMap());
|
||||
}
|
||||
} on PostgrestException catch (e) {
|
||||
throw 'Errore database: ${e.message}';
|
||||
} catch (e) {
|
||||
throw 'Errore durante l\'eliminazione dei file: $e';
|
||||
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
|
||||
throw Exception('Errore nel salvataggio dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/master_data/products/models/model_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||
|
||||
class OperationDetailModel extends Equatable {
|
||||
final String? id;
|
||||
final DateTime? createdAt;
|
||||
final String operationId;
|
||||
final String? type;
|
||||
final String? providerId;
|
||||
final String? modelId;
|
||||
final String? description;
|
||||
final DateTime? expirationDate;
|
||||
final String companyId;
|
||||
final String? lastCampaignId;
|
||||
final String? subType;
|
||||
|
||||
// Aggiunte comode per relazioni
|
||||
final ProviderModel? provider;
|
||||
final ModelModel? model;
|
||||
|
||||
const OperationDetailModel({
|
||||
this.id,
|
||||
this.createdAt,
|
||||
this.operationId = '',
|
||||
this.type,
|
||||
this.providerId,
|
||||
this.modelId,
|
||||
this.description,
|
||||
this.expirationDate,
|
||||
this.companyId = '',
|
||||
this.lastCampaignId,
|
||||
this.subType,
|
||||
this.provider,
|
||||
this.model,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
createdAt,
|
||||
operationId,
|
||||
type,
|
||||
providerId,
|
||||
modelId,
|
||||
description,
|
||||
expirationDate,
|
||||
companyId,
|
||||
lastCampaignId,
|
||||
subType,
|
||||
provider,
|
||||
model,
|
||||
];
|
||||
|
||||
OperationDetailModel copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
String? operationId,
|
||||
String? type,
|
||||
String? providerId,
|
||||
String? modelId,
|
||||
String? description,
|
||||
DateTime? expirationDate,
|
||||
String? companyId,
|
||||
String? lastCampaignId,
|
||||
String? subType,
|
||||
ProviderModel? Function()? provider,
|
||||
ModelModel? Function()? model,
|
||||
}) => OperationDetailModel(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
operationId: operationId ?? this.operationId,
|
||||
type: type ?? this.type,
|
||||
providerId: providerId ?? this.providerId,
|
||||
modelId: modelId ?? this.modelId,
|
||||
description: description ?? this.description,
|
||||
expirationDate: expirationDate ?? this.expirationDate,
|
||||
companyId: companyId ?? this.companyId,
|
||||
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
|
||||
subType: subType ?? this.subType,
|
||||
provider: provider != null ? provider() : this.provider,
|
||||
model: model != null ? model() : this.model,
|
||||
);
|
||||
|
||||
factory OperationDetailModel.empty() {
|
||||
return OperationDetailModel();
|
||||
}
|
||||
|
||||
factory OperationDetailModel.fromMap(Map<String, dynamic> map) {
|
||||
return OperationDetailModel(
|
||||
id: map['id'] as String?,
|
||||
createdAt: map['created_at'] != null
|
||||
? DateTime.parse(map['created_at'])
|
||||
: null,
|
||||
operationId: map['operation_id'] as String? ?? '',
|
||||
type: map['type'] as String?,
|
||||
providerId: map['provider_id'] as String?,
|
||||
modelId: map['model_id'] as String?,
|
||||
description: map['description'] as String?,
|
||||
expirationDate: map['expiration_date'] != null
|
||||
? DateTime.parse(map['expiration_date'])
|
||||
: null,
|
||||
companyId: map['company_id'] as String? ?? '',
|
||||
lastCampaignId: map['last_campaign_id'] as String?,
|
||||
subType: map['sub_type'] as String?,
|
||||
provider: (map[Tables.providers] != null)
|
||||
? ProviderModel.fromMap(map[Tables.providers] as Map<String, dynamic>)
|
||||
: null,
|
||||
model: (map[Tables.models] != null)
|
||||
? ModelModel.fromJson(map[Tables.models] as Map<String, dynamic>)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
final String? pId =
|
||||
(provider?.id != null && provider!.id!.isNotEmpty)
|
||||
? provider!.id
|
||||
: (providerId != null && providerId!.isNotEmpty
|
||||
? providerId
|
||||
: null);
|
||||
|
||||
final String? mId =
|
||||
(model?.id != null && model!.id!.isNotEmpty)
|
||||
? model!.id
|
||||
: (modelId != null && modelId!.isNotEmpty ? modelId : null);
|
||||
|
||||
return {
|
||||
if (id?.isNotEmpty == true) 'id': id,
|
||||
if (operationId.isNotEmpty) 'operation_id': operationId,
|
||||
if (type?.isNotEmpty == true) 'type': type,
|
||||
if (pId?.isNotEmpty == true) 'provider_id': pId,
|
||||
if (mId?.isNotEmpty == true) 'model_id': mId,
|
||||
if (description?.isNotEmpty == true) 'description': description,
|
||||
if (expirationDate != null)
|
||||
'expiration_date': expirationDate!.toIso8601String(),
|
||||
if (companyId.isNotEmpty) 'company_id': companyId,
|
||||
if (lastCampaignId?.isNotEmpty == true)
|
||||
'last_campaign_id': lastCampaignId,
|
||||
if (subType?.isNotEmpty == true) 'sub_type': subType,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
|
||||
enum OperationStatus {
|
||||
success('success', 'OK'),
|
||||
@@ -27,24 +28,13 @@ enum OperationStatus {
|
||||
class OperationModel extends Equatable {
|
||||
final String? id;
|
||||
final DateTime? createdAt;
|
||||
final String type;
|
||||
final String? subType;
|
||||
final String? providerId;
|
||||
final String? providerDisplayName;
|
||||
final String? modelId;
|
||||
final String? modelDisplayName;
|
||||
final String? description;
|
||||
final DateTime? expirationDate;
|
||||
final String note;
|
||||
final bool showInDashboard;
|
||||
final String batchUuid;
|
||||
final String companyId;
|
||||
final String storeId;
|
||||
final String? storeDisplayName;
|
||||
final int quantity;
|
||||
final String? staffId;
|
||||
final String? staffDisplayName;
|
||||
final String? lastCampaignId;
|
||||
final OperationStatus status;
|
||||
final String? customerId;
|
||||
final CustomerModel? customer;
|
||||
@@ -54,88 +44,61 @@ class OperationModel extends Equatable {
|
||||
// ALLEGATI (Aggiunto)
|
||||
final List<AttachmentModel> attachments;
|
||||
|
||||
// DETTAGLI OPERAZIONE (Aggiunto)
|
||||
final List<OperationDetailModel> details;
|
||||
|
||||
const OperationModel({
|
||||
this.id,
|
||||
this.createdAt,
|
||||
this.type = '',
|
||||
this.subType,
|
||||
this.providerId,
|
||||
this.providerDisplayName,
|
||||
this.modelId,
|
||||
this.modelDisplayName,
|
||||
this.description,
|
||||
this.expirationDate,
|
||||
this.note = '',
|
||||
this.showInDashboard = true,
|
||||
this.batchUuid = '',
|
||||
required this.companyId,
|
||||
this.storeId = '',
|
||||
this.storeDisplayName,
|
||||
this.quantity = 1,
|
||||
this.staffId,
|
||||
this.staffDisplayName,
|
||||
this.lastCampaignId,
|
||||
this.status = OperationStatus.draft,
|
||||
this.status = OperationStatus.success,
|
||||
this.customerId,
|
||||
this.customer,
|
||||
this.reference = '',
|
||||
this.attachments = const [],
|
||||
this.details = const [],
|
||||
this.isBusiness = false,
|
||||
});
|
||||
|
||||
OperationModel copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
String? type,
|
||||
String? subType,
|
||||
String? providerId,
|
||||
String? providerDisplayName,
|
||||
String? modelId,
|
||||
String? modelDisplayName,
|
||||
String? description,
|
||||
DateTime? expirationDate,
|
||||
String? note,
|
||||
bool? showInDashboard,
|
||||
String? batchUuid,
|
||||
String? companyId,
|
||||
String? storeId,
|
||||
String? storeDisplayName,
|
||||
int? quantity,
|
||||
String? staffId,
|
||||
String? staffDisplayName,
|
||||
String? lastCampaignId,
|
||||
OperationStatus? status,
|
||||
String? customerId,
|
||||
CustomerModel? customer,
|
||||
String? reference,
|
||||
List<AttachmentModel>? attachments,
|
||||
List<OperationDetailModel>? details,
|
||||
bool? isBusiness,
|
||||
}) => OperationModel(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
type: type ?? this.type,
|
||||
subType: subType ?? this.subType,
|
||||
providerId: providerId ?? this.providerId,
|
||||
providerDisplayName: providerDisplayName ?? this.providerDisplayName,
|
||||
modelId: modelId ?? this.modelId,
|
||||
modelDisplayName: modelDisplayName ?? this.modelDisplayName,
|
||||
description: description ?? this.description,
|
||||
expirationDate: expirationDate ?? this.expirationDate,
|
||||
note: note ?? this.note,
|
||||
showInDashboard: showInDashboard ?? this.showInDashboard,
|
||||
batchUuid: batchUuid ?? this.batchUuid,
|
||||
companyId: companyId ?? this.companyId,
|
||||
storeId: storeId ?? this.storeId,
|
||||
storeDisplayName: storeDisplayName ?? this.storeDisplayName,
|
||||
quantity: quantity ?? this.quantity,
|
||||
staffId: staffId ?? this.staffId,
|
||||
staffDisplayName: staffDisplayName ?? this.staffDisplayName,
|
||||
lastCampaignId: lastCampaignId ?? this.lastCampaignId,
|
||||
status: status ?? this.status,
|
||||
customerId: customerId ?? this.customerId,
|
||||
customer: customer ?? this.customer,
|
||||
reference: reference ?? this.reference,
|
||||
attachments: attachments ?? this.attachments,
|
||||
details: details ?? this.details,
|
||||
isBusiness: isBusiness ?? this.isBusiness,
|
||||
);
|
||||
|
||||
@@ -143,34 +106,29 @@ class OperationModel extends Equatable {
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
createdAt,
|
||||
type,
|
||||
subType,
|
||||
providerId,
|
||||
providerDisplayName,
|
||||
modelId,
|
||||
modelDisplayName,
|
||||
description,
|
||||
expirationDate,
|
||||
note,
|
||||
showInDashboard,
|
||||
batchUuid,
|
||||
companyId,
|
||||
storeId,
|
||||
storeDisplayName,
|
||||
quantity,
|
||||
staffId,
|
||||
staffDisplayName,
|
||||
lastCampaignId,
|
||||
status,
|
||||
customerId,
|
||||
customer,
|
||||
reference,
|
||||
attachments,
|
||||
details,
|
||||
isBusiness,
|
||||
];
|
||||
|
||||
factory OperationModel.empty() {
|
||||
return OperationModel(id: null, createdAt: null, companyId: '');
|
||||
return OperationModel(
|
||||
id: null,
|
||||
createdAt: null,
|
||||
companyId: '',
|
||||
details: const [],
|
||||
);
|
||||
}
|
||||
|
||||
factory OperationModel.fromMap(Map<String, dynamic> map) {
|
||||
@@ -179,42 +137,17 @@ class OperationModel extends Equatable {
|
||||
createdAt: map['created_at'] != null
|
||||
? DateTime.parse(map['created_at'])
|
||||
: null,
|
||||
type: map['type'] as String? ?? '',
|
||||
subType: map['sub_type'] as String?,
|
||||
|
||||
// I campi relazionali nullabili restano rigorosamente null!
|
||||
providerId: map['provider_id'] as String?,
|
||||
// MAGIA ANTI-CRASH: Usiamo ?['chiave'] per non far esplodere i join vuoti
|
||||
providerDisplayName: (map[Tables.providers]?['name'] as String?)
|
||||
?.myFormat(),
|
||||
|
||||
modelId: map['model_id'] as String?,
|
||||
modelDisplayName: (map[Tables.models]?['name_with_brand'] as String?)
|
||||
?.myFormat(),
|
||||
|
||||
description: map['description'] as String?,
|
||||
expirationDate: map['expiration_date'] != null
|
||||
? DateTime.parse(map['expiration_date'])
|
||||
: null,
|
||||
note: map['note'] as String? ?? '',
|
||||
showInDashboard: map['show_in_dashboard'] as bool? ?? true,
|
||||
batchUuid: map['batch_uuid'] as String? ?? '',
|
||||
companyId: map['company_id'] as String,
|
||||
|
||||
storeId:
|
||||
map['store_id'] as String? ??
|
||||
'', // Questo è non-nullable nella tua classe
|
||||
storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(),
|
||||
|
||||
quantity: map['quantity'] is int
|
||||
? map['quantity']
|
||||
: int.tryParse(map['quantity']?.toString() ?? '1') ?? 1,
|
||||
|
||||
staffId: map['staff_id'] as String?,
|
||||
staffDisplayName: (map[Tables.staffMembers]?['name'] as String?)
|
||||
?.myFormat(),
|
||||
|
||||
lastCampaignId: map['last_campaign_id'] as String?,
|
||||
status: OperationStatus.fromString(map['status'] ?? 'draft'),
|
||||
customerId: map['customer_id'] as String?,
|
||||
|
||||
@@ -228,6 +161,14 @@ class OperationModel extends Equatable {
|
||||
.toList() ??
|
||||
const [],
|
||||
|
||||
details:
|
||||
(map[Tables.operationDetails] as List?)
|
||||
?.map(
|
||||
(x) => OperationDetailModel.fromMap(x as Map<String, dynamic>),
|
||||
)
|
||||
.toList() ??
|
||||
const [],
|
||||
|
||||
reference: map['reference'] as String? ?? '',
|
||||
isBusiness: map['is_business'] as bool? ?? false,
|
||||
);
|
||||
@@ -236,21 +177,11 @@ class OperationModel extends Equatable {
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
if (id != null) 'id': id,
|
||||
'type': type,
|
||||
'sub_type': subType,
|
||||
'provider_id': providerId,
|
||||
'model_id': modelId,
|
||||
'description': description,
|
||||
if (expirationDate != null)
|
||||
'expiration_date': expirationDate!.toIso8601String(),
|
||||
'note': note,
|
||||
'show_in_dashboard': showInDashboard,
|
||||
'batch_uuid': batchUuid,
|
||||
'company_id': companyId,
|
||||
'store_id': storeId,
|
||||
'quantity': quantity,
|
||||
if (staffId != null) 'staff_id': staffId,
|
||||
if (lastCampaignId != null) 'last_campaign_id': lastCampaignId,
|
||||
'status': status.supabaseName,
|
||||
if (customerId != null) 'customer_id': customerId,
|
||||
'reference': reference,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
class PaginatedOperations extends Equatable {
|
||||
final List<OperationModel> operations;
|
||||
final int totalCount;
|
||||
|
||||
const PaginatedOperations({
|
||||
required this.operations,
|
||||
required this.totalCount,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [operations, totalCount];
|
||||
|
||||
PaginatedOperations copyWith({
|
||||
List<OperationModel>? operations,
|
||||
int? totalCount,
|
||||
}) {
|
||||
return PaginatedOperations(
|
||||
operations: operations ?? this.operations,
|
||||
totalCount: totalCount ?? this.totalCount,
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/widgets/staff_selector_modal.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -14,20 +18,40 @@ class OperationListScreen extends StatefulWidget {
|
||||
|
||||
class _OperationListScreenState extends State<OperationListScreen> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
Timer? _debounce;
|
||||
|
||||
// 🥷 1. LO STATO PER LE BULK ACTIONS
|
||||
// Set per gestire le Bulk Actions (Selezione multipla)
|
||||
final Set<String> _selectedOperationIds = {};
|
||||
bool get _isSelectionMode => _selectedOperationIds.isNotEmpty;
|
||||
|
||||
// Flag per mostrare/nascondere la barra di ricerca integrata nell'AppBar
|
||||
bool _showSearchBar = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scrollController.addListener(_onScroll);
|
||||
|
||||
// Primo caricamento: partiamo da pagina 1
|
||||
// (Il Cubit deciderà se fare il boot iniziale o se c'era già roba in cache)
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
|
||||
if (isDesktop) {
|
||||
context.read<OperationListCubit>().loadSpecificPageDesktop(1);
|
||||
} else {
|
||||
context.read<OperationListCubit>().loadNextPageMobile(refresh: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _onScroll() {
|
||||
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
|
||||
// 🥷 COMPORTAMENTO IBRIDO: Lo scroll infinito si attiva SOLO su mobile
|
||||
if (isDesktop) return;
|
||||
|
||||
if (_isBottom) {
|
||||
context.read<OperationListCubit>().loadOperations();
|
||||
context.read<OperationListCubit>().loadNextPageMobile();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +62,21 @@ class _OperationListScreenState extends State<OperationListScreen> {
|
||||
return currentScroll >= (maxScroll * 0.9);
|
||||
}
|
||||
|
||||
void _onSearchChanged(String text) {
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 400), () {
|
||||
if (!mounted) return;
|
||||
context.read<OperationListCubit>().updateFilters(
|
||||
text: text,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
_scrollController.dispose();
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -62,8 +98,10 @@ class _OperationListScreenState extends State<OperationListScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = MediaQuery.sizeOf(context).width >= 900;
|
||||
|
||||
return Scaffold(
|
||||
// 🥷 2. APPBAR DINAMICA (Standard o Modalità Selezione)
|
||||
// --- APP BAR DINAMICA E INTEGRATA ---
|
||||
appBar: _isSelectionMode
|
||||
? AppBar(
|
||||
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
|
||||
@@ -77,24 +115,50 @@ class _OperationListScreenState extends State<OperationListScreen> {
|
||||
icon: const Icon(Icons.edit_note),
|
||||
tooltip: 'Cambia Stato Massivo',
|
||||
onPressed: () {
|
||||
// TODO: Apri BottomSheet per cambiare stato a tutte le selezionate
|
||||
// TODO: Integrare bottom sheet per azioni massive
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
: AppBar(
|
||||
title: const Text("Gestione Servizi"),
|
||||
title: _showSearchBar
|
||||
? TextField(
|
||||
controller: _searchController,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Cerca per cliente, nota o riferimento...',
|
||||
border: InputBorder.none,
|
||||
),
|
||||
style: const TextStyle(fontSize: 16),
|
||||
onChanged: _onSearchChanged,
|
||||
)
|
||||
: const Text("Gestione Servizi"),
|
||||
elevation: 0,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.filter_list),
|
||||
icon: Icon(_showSearchBar ? Icons.close : Icons.search),
|
||||
onPressed: () {
|
||||
// TODO: Apri drawer laterale o modal per i filtri avanzati
|
||||
setState(() {
|
||||
_showSearchBar = !_showSearchBar;
|
||||
if (!_showSearchBar) {
|
||||
_debounce?.cancel();
|
||||
_searchController.clear();
|
||||
context.read<OperationListCubit>().clearFilters();
|
||||
}
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(icon: const Icon(Icons.search), onPressed: () {}),
|
||||
if (!isDesktop) // Il pull-to-refresh c'è già su mobile, su desktop mettiamo un tasto manuale
|
||||
IconButton(
|
||||
icon: const Icon(Icons.filter_list),
|
||||
onPressed: () {
|
||||
// TODO: Bottone Filtri Avanzati (es. DateRange Picker)
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// --- CORPO RESPONSIVO ---
|
||||
body: BlocBuilder<OperationListCubit, OperationListState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == OperationListStatus.loading &&
|
||||
@@ -103,83 +167,216 @@ class _OperationListScreenState extends State<OperationListScreen> {
|
||||
}
|
||||
|
||||
if (state.operations.isEmpty) {
|
||||
return const Center(child: Text("Nessuna pratica trovata."));
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("Nessuna pratica trovata."),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton(
|
||||
onPressed: () => isDesktop
|
||||
? context
|
||||
.read<OperationListCubit>()
|
||||
.loadSpecificPageDesktop(1)
|
||||
: context.read<OperationListCubit>().loadNextPageMobile(
|
||||
refresh: true,
|
||||
),
|
||||
child: const Text("Ricarica"),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 🥷 3. IL MOTORE RESPONSIVO
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => context.read<OperationListCubit>().loadOperations(
|
||||
refresh: true,
|
||||
),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Se lo schermo è largo (Desktop/Tablet), usiamo la griglia
|
||||
final isDesktop = constraints.maxWidth > 700;
|
||||
|
||||
return GridView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.all(12).copyWith(bottom: 80),
|
||||
// Magia della griglia: si adatta!
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent:
|
||||
450, // Larghezza massima della singola card
|
||||
mainAxisExtent:
|
||||
180, // Altezza fissa della card (da aggiustare in base ai tuoi font)
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
// 🥷 SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style
|
||||
if (isDesktop) {
|
||||
return Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: GridView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent:
|
||||
420, // Larghezza bilanciata per le card su desktop
|
||||
mainAxisExtent:
|
||||
185, // Altezza controllata per evitare buchi bianchi
|
||||
crossAxisSpacing: 16,
|
||||
mainAxisSpacing: 16,
|
||||
),
|
||||
itemCount: state.operations.length,
|
||||
itemBuilder: (context, index) {
|
||||
final operation = state.operations[index];
|
||||
return _buildResponsiveCard(operation);
|
||||
},
|
||||
),
|
||||
itemCount: state.hasReachedMax
|
||||
? state.operations.length
|
||||
: state.operations.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= state.operations.length) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
);
|
||||
}
|
||||
),
|
||||
_buildDesktopPaginationFooter(
|
||||
state,
|
||||
), // La barra in fondo stile Gmail
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final operation = state.operations[index];
|
||||
final isSelected = _selectedOperationIds.contains(
|
||||
operation.id,
|
||||
);
|
||||
// 🥷 SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => context
|
||||
.read<OperationListCubit>()
|
||||
.loadNextPageMobile(refresh: true),
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.only(
|
||||
bottom: 80,
|
||||
left: 8,
|
||||
right: 8,
|
||||
top: 8,
|
||||
),
|
||||
itemCount: state.hasReachedMax
|
||||
? state.operations.length
|
||||
: state.operations.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= state.operations.length) {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return _RichOperationCard(
|
||||
operation: operation,
|
||||
isSelected: isSelected,
|
||||
isSelectionMode: _isSelectionMode,
|
||||
onTap: () {
|
||||
if (_isSelectionMode) {
|
||||
_toggleSelection(operation.id!);
|
||||
} else {
|
||||
context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: operation),
|
||||
pathParameters: {'id': operation.id!},
|
||||
);
|
||||
}
|
||||
},
|
||||
onLongPress: () => _toggleSelection(operation.id!),
|
||||
);
|
||||
},
|
||||
final operation = state.operations[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4.0),
|
||||
child: _buildResponsiveCard(operation),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
floatingActionButton: _isSelectionMode
|
||||
? null // Nascondi il FAB se stai selezionando
|
||||
? null
|
||||
: FloatingActionButton(
|
||||
onPressed: () {
|
||||
/* Tuo codice per nuova operazione */
|
||||
onPressed: () async {
|
||||
StaffMemberModel? createdBy = await getStaffMember(context);
|
||||
if (createdBy == null || !context.mounted) return;
|
||||
context.pushNamed(
|
||||
Routes.operationForm,
|
||||
pathParameters: {'id': 'new'},
|
||||
extra: (createdBy: createdBy, operation: null),
|
||||
);
|
||||
},
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- COSTRUZIONE DELLA COMPONENTISTICA DETTAGLIATA ---
|
||||
|
||||
Widget _buildResponsiveCard(OperationModel operation) {
|
||||
final isSelected = _selectedOperationIds.contains(operation.id);
|
||||
return _RichOperationCard(
|
||||
operation: operation,
|
||||
isSelected: isSelected,
|
||||
isSelectionMode: _isSelectionMode,
|
||||
onTap: () {
|
||||
if (_isSelectionMode) {
|
||||
_toggleSelection(operation.id!);
|
||||
} else {
|
||||
context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: operation),
|
||||
pathParameters: {'id': operation.id!},
|
||||
);
|
||||
}
|
||||
},
|
||||
onLongPress: () => _toggleSelection(operation.id!),
|
||||
);
|
||||
}
|
||||
|
||||
// 🥷 LA BARRA DI PAGINAZIONE DESKTOP (Stile Gmail / Typesense)
|
||||
Widget _buildDesktopPaginationFooter(OperationListState state) {
|
||||
final theme = Theme.of(context);
|
||||
final cubit = context.read<OperationListCubit>();
|
||||
|
||||
// Calcolo intervallo visualizzato (es. 1-25 di 140)
|
||||
final fromItem = ((state.currentPage - 1) * state.itemsPerPage) + 1;
|
||||
final toItem =
|
||||
DateUtils.isSameDay(DateTime.now(), DateTime.now()) // segnaposto logico
|
||||
? (fromItem + state.operations.length - 1)
|
||||
: fromItem;
|
||||
|
||||
return Container(
|
||||
height: 56,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Info totali a sinistra
|
||||
Text(
|
||||
"$fromItem-$toItem di ${state.totalItems} pratiche totali",
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
|
||||
// Controlli di navigazione a destra
|
||||
Row(
|
||||
children: [
|
||||
// Prima Pagina
|
||||
IconButton(
|
||||
icon: const Icon(Icons.first_page),
|
||||
onPressed: state.currentPage > 1
|
||||
? () => cubit.loadSpecificPageDesktop(1)
|
||||
: null,
|
||||
),
|
||||
// Pagina Precedente
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_left),
|
||||
onPressed: state.currentPage > 1
|
||||
? () => cubit.loadSpecificPageDesktop(state.currentPage - 1)
|
||||
: null,
|
||||
),
|
||||
|
||||
// Indicatore numerico centrale impacchettato
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0),
|
||||
child: Text(
|
||||
"Pagina ${state.currentPage} di ${state.totalPages}",
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
|
||||
// Pagina Successiva
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_right),
|
||||
onPressed: state.currentPage < state.totalPages
|
||||
? () => cubit.loadSpecificPageDesktop(state.currentPage + 1)
|
||||
: null,
|
||||
),
|
||||
// Ultima Pagina
|
||||
IconButton(
|
||||
icon: const Icon(Icons.last_page),
|
||||
onPressed: state.currentPage < state.totalPages
|
||||
? () => cubit.loadSpecificPageDesktop(state.totalPages)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 🥷 4. LA SUPER CARD ESTRATTA
|
||||
// =========================================================================
|
||||
// 🥷 3. LA CARD RICCA, REATTIVA E DEFINITIVA (Quella revisionata insieme)
|
||||
// =========================================================================
|
||||
class _RichOperationCard extends StatelessWidget {
|
||||
final OperationModel operation;
|
||||
final bool isSelected;
|
||||
@@ -195,7 +392,6 @@ class _RichOperationCard extends StatelessWidget {
|
||||
required this.onLongPress,
|
||||
});
|
||||
|
||||
// 🥷 1. IL COLORE DELLO STATO: Centralizzato per usarlo ovunque
|
||||
Color _getStatusColor(OperationStatus status) {
|
||||
switch (status) {
|
||||
case OperationStatus.success:
|
||||
@@ -206,13 +402,12 @@ class _RichOperationCard extends StatelessWidget {
|
||||
case OperationStatus.waitingForSupport:
|
||||
return Colors.blue;
|
||||
case OperationStatus.failure:
|
||||
return Colors.grey.shade800; // O Colors.red se preferisci
|
||||
return Colors.grey.shade800;
|
||||
}
|
||||
}
|
||||
|
||||
// 🥷 2. IL COLORE DEL TIPO: Per farlo risaltare
|
||||
Color _getTypeColor(String type) {
|
||||
switch (type) {
|
||||
Color _getTypeColor(String? type) {
|
||||
switch (type?.toUpperCase()) {
|
||||
case 'FIN':
|
||||
return Colors.deepPurple;
|
||||
case 'TELEPASS':
|
||||
@@ -232,13 +427,87 @@ class _RichOperationCard extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
IconData? _getIconForType(String? type, String? subtype) {
|
||||
if (type?.toLowerCase() == 'energy') {
|
||||
if (subtype?.toLowerCase() == 'luce') return Icons.bolt;
|
||||
if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Widget _buildDetailItem(BuildContext context, OperationDetailModel detail) {
|
||||
final typeColor = _getTypeColor(detail.type);
|
||||
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
|
||||
final icon = _getIconForType(detail.type, detail.subType);
|
||||
|
||||
final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty)
|
||||
? '${detail.type ?? ''} (${detail.subType})'
|
||||
: (detail.type ?? 'Dettaglio');
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: typeColor.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(
|
||||
color: typeColor.withValues(alpha: 0.25),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(icon, size: 12, color: typeColor),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
Text(
|
||||
typeLabel,
|
||||
style: TextStyle(
|
||||
color: typeColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
if (detail.provider?.name != null && detail.provider!.name.isNotEmpty) ...[
|
||||
const SizedBox(width: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
|
||||
decoration: BoxDecoration(
|
||||
color: providerColor.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
detail.provider!.name,
|
||||
style: TextStyle(
|
||||
color: providerColor,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (detail.model?.name != null && detail.model!.name.isNotEmpty) ...[
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'• ${detail.model!.name}',
|
||||
style: TextStyle(
|
||||
color: Colors.grey[700],
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final statusColor = _getStatusColor(operation.status);
|
||||
final typeColor = _getTypeColor(operation.type);
|
||||
|
||||
return Card(
|
||||
margin: EdgeInsets.zero, // Gestito dai margini dei padri (griglia/lista)
|
||||
elevation: isSelected ? 4 : 1,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -256,32 +525,35 @@ class _RichOperationCard extends StatelessWidget {
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? theme.colorScheme.primaryContainer.withValues(alpha: 0.2)
|
||||
? theme.colorScheme.primaryContainer.withValues(alpha: 0.15)
|
||||
: null,
|
||||
// BANDA LATERALE LEGATA ALLO STATO (Stilosissima)
|
||||
// 🥷 COERENZA 100%: Banda laterale legata allo status per eliminare i malintesi cromatici
|
||||
border: Border(left: BorderSide(color: statusColor, width: 6)),
|
||||
),
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// --- HEADER ---
|
||||
// --- RIGA 1: RIFERIMENTO E DATA ---
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
if (isSelectionMode)
|
||||
SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: Checkbox(
|
||||
value: isSelected,
|
||||
onChanged: (_) => onTap(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: SizedBox(
|
||||
height: 18,
|
||||
width: 18,
|
||||
child: Checkbox(
|
||||
value: isSelected,
|
||||
onChanged: (_) => onTap(),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
operation.reference.isEmpty
|
||||
? 'Nessuna Riferimento'
|
||||
(operation.reference.isEmpty)
|
||||
? 'Senza Riferimento'
|
||||
: operation.reference,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: Colors.grey[600],
|
||||
@@ -291,7 +563,9 @@ class _RichOperationCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${operation.createdAt?.day.toString().padLeft(2, '0')}/${operation.createdAt?.month.toString().padLeft(2, '0')}/${operation.createdAt?.year}",
|
||||
operation.createdAt != null
|
||||
? "${operation.createdAt!.day.toString().padLeft(2, '0')}/${operation.createdAt!.month.toString().padLeft(2, '0')}/${operation.createdAt!.year}"
|
||||
: '',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
@@ -300,76 +574,22 @@ class _RichOperationCard extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// --- CLIENTE E TIPO OPERAZIONE ---
|
||||
// --- RIGA 2: NOME CLIENTE E CHIP PRIVATO / BUSINESS ---
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
operation.customer?.name ?? "Cliente sconosciuto",
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
fontSize: 15,
|
||||
),
|
||||
maxLines: 2,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// IL TIPO DI OPERAZIONE CHE SPICCA
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: typeColor.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: typeColor.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (_getIconForType(
|
||||
operation.type,
|
||||
operation.subType,
|
||||
) !=
|
||||
null) ...[
|
||||
Icon(
|
||||
_getIconForType(
|
||||
operation.type,
|
||||
operation.subType,
|
||||
),
|
||||
size: 14,
|
||||
color: typeColor,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
Text(
|
||||
operation.subType?.isNotEmpty == true
|
||||
? operation.subType!
|
||||
: operation.type,
|
||||
style: TextStyle(
|
||||
color: typeColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// --- I TAG COMPATTI (Business/Privato, Provider, Device) ---
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
// Espanso in "Business" e "Privato"
|
||||
_MiniChip(
|
||||
label: operation.isBusiness ? 'Business' : 'Privato',
|
||||
icon: operation.isBusiness
|
||||
@@ -377,27 +597,31 @@ class _RichOperationCard extends StatelessWidget {
|
||||
: Icons.person,
|
||||
color: operation.isBusiness ? Colors.indigo : Colors.teal,
|
||||
),
|
||||
|
||||
// Tag Provider con il suo colore personalizzato dal DB
|
||||
if (operation.providerId != null)
|
||||
_MiniChip(
|
||||
label: operation.providerDisplayName ?? 'Gestore',
|
||||
// Se hai popolato il campo colorHex, qui puoi usare: operation.provider?.displayColor ?? Colors.grey
|
||||
color: Colors.redAccent,
|
||||
),
|
||||
|
||||
if (operation.type == 'Fin' && operation.modelId != null)
|
||||
_MiniChip(
|
||||
label: operation.modelDisplayName ?? 'Modello',
|
||||
icon: Icons.devices,
|
||||
color: Colors.deepPurple,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// --- RIGA 3: LISTA DEI VARI DETTAGLI (TIPO E PROVIDER) ---
|
||||
if (operation.details.isEmpty)
|
||||
Text(
|
||||
'Nessun dettaglio',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: Colors.grey[500],
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
)
|
||||
else
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: operation.details
|
||||
.map((detail) => _buildDetailItem(context, detail))
|
||||
.toList(),
|
||||
),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
// --- FOOTER: Staff e Stato ---
|
||||
// --- RIGA 4: NOME ADDETTO E STATO ---
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
@@ -410,14 +634,31 @@ class _RichOperationCard extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
operation.staffDisplayName ?? 'Staff',
|
||||
operation.staffDisplayName ?? 'Assegnato',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
_buildOperationStatus(operation.status, statusColor),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
operation.status.displayName,
|
||||
style: const TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
@@ -427,34 +668,9 @@ class _RichOperationCard extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
IconData? _getIconForType(String type, String? subtype) {
|
||||
if (type == 'Energy') {
|
||||
if (subtype?.toLowerCase() == 'luce') return Icons.bolt;
|
||||
if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Widget _buildOperationStatus(OperationStatus status, Color statusColor) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
status.displayName,
|
||||
style: const TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Micro Widget di supporto per i tag interni
|
||||
class _MiniChip extends StatelessWidget {
|
||||
final String label;
|
||||
final IconData? icon;
|
||||
@@ -465,23 +681,23 @@ class _MiniChip extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.1),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3)),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
color: color.withValues(alpha: 0.08),
|
||||
border: Border.all(color: color.withValues(alpha: 0.25)),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(icon, size: 12, color: color),
|
||||
Icon(icon, size: 11, color: color),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontSize: 10,
|
||||
color: color,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/model_section.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
class OperationDetailsSection extends StatelessWidget {
|
||||
final OperationModel? currentOp;
|
||||
final String currentType;
|
||||
final TextEditingController freeTextSubtypeController;
|
||||
final TextEditingController freeTextDescriptionController;
|
||||
final Widget durationQuickPicks;
|
||||
|
||||
const OperationDetailsSection({
|
||||
super.key,
|
||||
required this.currentOp,
|
||||
required this.currentType,
|
||||
required this.freeTextSubtypeController,
|
||||
required this.freeTextDescriptionController,
|
||||
required this.durationQuickPicks,
|
||||
});
|
||||
|
||||
void _showProviderModal(BuildContext context, String operationType) {
|
||||
final OperationFormCubit cubit = context.read<OperationFormCubit>();
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (modalContext) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.5,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.8,
|
||||
expand: false,
|
||||
builder: (_, scrollController) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Seleziona Gestore',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(modalContext),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: BlocBuilder<ProviderListCubit, ProviderListState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == ProviderListStatus.loading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
// 🥷 IL TOCCO DEL NINJA: Filtriamo usando direttamente l'Extension sul Modello!
|
||||
final filteredProviders = state.providers.where((p) {
|
||||
return p.supportsOperation(operationType) && p.isActive;
|
||||
}).toList();
|
||||
|
||||
if (filteredProviders.isEmpty) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Nessun gestore compatibile con questo servizio.',
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return BlocProvider.value(
|
||||
value: cubit,
|
||||
child: ListView.builder(
|
||||
controller: scrollController,
|
||||
itemCount: filteredProviders.length,
|
||||
itemBuilder: (context, index) {
|
||||
final provider = filteredProviders[index];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.business),
|
||||
title: Text(
|
||||
provider.name,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
// Facoltativo: mostra i ruoli sotto al nome
|
||||
subtitle: Text(
|
||||
provider.roles
|
||||
.map((r) => r.displayValue)
|
||||
.join(', '),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
onTap: () {
|
||||
context.read<OperationFormCubit>().updateFields(
|
||||
providerId: provider.id,
|
||||
providerDisplayName: provider.name,
|
||||
);
|
||||
Navigator.pop(modalContext);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// PROVIDER (Mostrato quasi sempre)
|
||||
ListTile(
|
||||
title: const Text('Seleziona Gestore'),
|
||||
subtitle: Text(
|
||||
(currentOp?.providerDisplayName != null &&
|
||||
currentOp!.providerDisplayName!.isNotEmpty)
|
||||
? currentOp!.providerDisplayName!
|
||||
: 'Nessun gestore selezionato',
|
||||
style: TextStyle(
|
||||
color:
|
||||
(currentOp?.providerId == null ||
|
||||
currentOp!.providerId!.isEmpty)
|
||||
? Colors.grey
|
||||
: null,
|
||||
fontWeight:
|
||||
(currentOp?.providerId == null ||
|
||||
currentOp!.providerId!.isEmpty)
|
||||
? FontWeight.normal
|
||||
: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
trailing: const Icon(Icons.arrow_drop_down),
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(color: theme.dividerColor),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
onTap: () => _showProviderModal(context, currentType),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 1. SCENARIO ENERGY (Dropdown Fisso)
|
||||
if (currentType == 'Energy') ...[
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue:
|
||||
(currentOp?.subType != null && currentOp!.subType!.isNotEmpty)
|
||||
? currentOp!.subType
|
||||
: null,
|
||||
decoration: const InputDecoration(labelText: 'Dettaglio Fornitura'),
|
||||
items: [
|
||||
'Luce',
|
||||
'Gas',
|
||||
].map((s) => DropdownMenuItem(value: s, child: Text(s))).toList(),
|
||||
onChanged: (val) {
|
||||
if (val != null) {
|
||||
context.read<OperationFormCubit>().updateFields(subType: val);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: freeTextDescriptionController,
|
||||
decoration: InputDecoration(
|
||||
labelText: currentType == 'Energy'
|
||||
? 'Offerta scelta'
|
||||
: 'Nome del servizio/offerta',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// 2. SCENARIO FIN (Ricerca Modello/Prodotto)
|
||||
if (currentType == 'Fin') ...[
|
||||
SharedModelSection(
|
||||
label: 'Seleziona Dispositivo/Prodotto',
|
||||
modelId: currentOp?.modelId,
|
||||
modelName: currentOp?.modelDisplayName,
|
||||
onModelSelected: (id, name) {
|
||||
context.read<OperationFormCubit>().updateFields(
|
||||
modelId: id,
|
||||
modelDisplayName: name,
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// 3. SCENARIO ENTERTAINMENT O CUSTOM (Testo libero)
|
||||
if (currentType == 'Entertainment' || currentType == 'Altro') ...[
|
||||
TextFormField(
|
||||
controller: freeTextSubtypeController,
|
||||
decoration: InputDecoration(
|
||||
labelText: currentType == 'Entertainment'
|
||||
? 'Piattaforma (es. Netflix, DAZN, Spotify...)'
|
||||
: 'Specifica il servizio (es. Monopattino)',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// SCADENZA (Reattivo per tipi complessi)
|
||||
if ([
|
||||
'Energy',
|
||||
'Fin',
|
||||
'Entertainment',
|
||||
'Altro',
|
||||
].contains(currentType)) ...[
|
||||
const SizedBox(height: 8),
|
||||
durationQuickPicks, // Passiamo i chips dall'esterno
|
||||
const SizedBox(height: 16),
|
||||
ListTile(
|
||||
title: const Text('Data di Scadenza Effettiva'),
|
||||
subtitle: Text(
|
||||
currentOp?.expirationDate != null
|
||||
? "${currentOp!.expirationDate!.day}/${currentOp!.expirationDate!.month}/${currentOp!.expirationDate!.year}"
|
||||
: 'Nessuna scadenza impostata',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
|
||||
),
|
||||
trailing: const Icon(Icons.calendar_month, color: Colors.blue),
|
||||
tileColor: Colors.blue.withValues(alpha: 0.05),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: const BorderSide(color: Colors.blue, width: 0.5),
|
||||
),
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate:
|
||||
currentOp?.expirationDate ??
|
||||
DateTime.now().add(const Duration(days: 365)),
|
||||
firstDate: DateTime.now(),
|
||||
lastDate: DateTime.now().add(const Duration(days: 3650)),
|
||||
);
|
||||
if (date != null && context.mounted) {
|
||||
context.read<OperationFormCubit>().updateFields(
|
||||
expirationDate: date,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,809 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/widgets/shared_forms/model_section.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_details_form_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
|
||||
class OperationDetailsSection extends StatelessWidget {
|
||||
const OperationDetailsSection({super.key});
|
||||
|
||||
static const List<String> _availableTypes = [
|
||||
'AL',
|
||||
'MNP',
|
||||
'NIP',
|
||||
'UNICA',
|
||||
'FWA',
|
||||
'TELEPASS',
|
||||
'Energy',
|
||||
'Fin',
|
||||
'Entertainment',
|
||||
'Altro',
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocBuilder<OperationDetailsListCubit, OperationDetailsListState>(
|
||||
builder: (context, listState) {
|
||||
final details = listState.details;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Dettagli Servizi (${details.length})',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _openDetailFormModal(context),
|
||||
icon: const Icon(Icons.add, size: 18),
|
||||
label: const Text('Aggiungi Dettaglio'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (details.isEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(
|
||||
alpha: 0.3,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: theme.dividerColor.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.playlist_add,
|
||||
size: 40,
|
||||
color: Colors.grey.shade400,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Nessun dettaglio aggiunto',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.grey.shade700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Premi "+ Aggiungi Dettaglio" per inserire un servizio per questa pratica.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: details.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final detail = details[index];
|
||||
return _buildDetailTile(context, detail, index);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailTile(
|
||||
BuildContext context,
|
||||
OperationDetailModel detail,
|
||||
int index,
|
||||
) {
|
||||
final typeColor = _getTypeColor(detail.type);
|
||||
final providerColor = detail.provider?.displayColor ?? Colors.blueGrey;
|
||||
|
||||
final typeText =
|
||||
(detail.subType != null && detail.subType!.isNotEmpty)
|
||||
? '${detail.type ?? ''} (${detail.subType})'
|
||||
: (detail.type ?? 'Dettaglio');
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
side: BorderSide(color: typeColor.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: typeColor.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
_getIconForType(detail.type, detail.subType),
|
||||
color: typeColor,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
typeText,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: typeColor,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
if (detail.provider?.name != null &&
|
||||
detail.provider!.name.isNotEmpty) ...[
|
||||
const SizedBox(width: 8),
|
||||
Chip(
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
label: Text(
|
||||
detail.provider!.name,
|
||||
style: TextStyle(
|
||||
color: providerColor,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
backgroundColor: providerColor.withValues(
|
||||
alpha: 0.15,
|
||||
),
|
||||
side: BorderSide(
|
||||
color: providerColor.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
if (detail.model?.name != null &&
|
||||
detail.model!.name.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.devices, size: 14, color: Colors.grey),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
detail.model!.name,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
if (detail.description != null &&
|
||||
detail.description!.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
detail.description!,
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[700]),
|
||||
),
|
||||
],
|
||||
if (detail.expirationDate != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.calendar_month,
|
||||
size: 14,
|
||||
color: Colors.blue,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'Scadenza: ${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}',
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
color: Colors.blue,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit, size: 18),
|
||||
onPressed:
|
||||
() => _openDetailFormModal(
|
||||
context,
|
||||
existingDetail: detail,
|
||||
index: index,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.delete_outline,
|
||||
size: 18,
|
||||
color: Colors.red,
|
||||
),
|
||||
onPressed: () {
|
||||
context
|
||||
.read<OperationDetailsListCubit>()
|
||||
.deleteOperationDetail(index);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _openDetailFormModal(
|
||||
BuildContext context, {
|
||||
OperationDetailModel? existingDetail,
|
||||
int? index,
|
||||
}) {
|
||||
final listCubit = context.read<OperationDetailsListCubit>();
|
||||
final allProviders = context.read<ProviderListCubit>().state.providers;
|
||||
final defaultProviderId =
|
||||
context.read<SessionCubit>().state.currentStore?.defaultProviderId;
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (sheetContext) {
|
||||
return BlocProvider(
|
||||
create:
|
||||
(_) => OperationDetailsFormCubit(
|
||||
initialDetail: existingDetail,
|
||||
editingIndex: index,
|
||||
allProviders: allProviders,
|
||||
defaultProviderId: defaultProviderId,
|
||||
),
|
||||
child: _OperationDetailFormSheet(listCubit: listCubit),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Color _getTypeColor(String? type) {
|
||||
switch (type?.toUpperCase()) {
|
||||
case 'FIN':
|
||||
return Colors.deepPurple;
|
||||
case 'TELEPASS':
|
||||
return Colors.yellow.shade800;
|
||||
case 'ENERGY':
|
||||
return Colors.amber.shade800;
|
||||
case 'ENTERTAINMENT':
|
||||
return Colors.pinkAccent;
|
||||
case 'AL':
|
||||
case 'MNP':
|
||||
return Colors.indigo;
|
||||
case 'NIP':
|
||||
case 'FWA':
|
||||
return Colors.cyan;
|
||||
default:
|
||||
return Colors.blueGrey;
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getIconForType(String? type, String? subtype) {
|
||||
if (type?.toLowerCase() == 'energy') {
|
||||
if (subtype?.toLowerCase() == 'luce') return Icons.bolt;
|
||||
if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department;
|
||||
}
|
||||
switch (type?.toUpperCase()) {
|
||||
case 'FIN':
|
||||
return Icons.devices;
|
||||
case 'TELEPASS':
|
||||
return Icons.directions_car;
|
||||
case 'ENTERTAINMENT':
|
||||
return Icons.tv;
|
||||
case 'AL':
|
||||
case 'MNP':
|
||||
return Icons.phone_android;
|
||||
case 'NIP':
|
||||
case 'FWA':
|
||||
return Icons.wifi;
|
||||
default:
|
||||
return Icons.build;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _OperationDetailFormSheet extends StatefulWidget {
|
||||
final OperationDetailsListCubit listCubit;
|
||||
|
||||
const _OperationDetailFormSheet({required this.listCubit});
|
||||
|
||||
@override
|
||||
State<_OperationDetailFormSheet> createState() =>
|
||||
_OperationDetailFormSheetState();
|
||||
}
|
||||
|
||||
class _OperationDetailFormSheetState
|
||||
extends State<_OperationDetailFormSheet> {
|
||||
late TextEditingController _subtypeController;
|
||||
late TextEditingController _descriptionController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final initialDetail =
|
||||
context.read<OperationDetailsFormCubit>().state.operationDetail;
|
||||
_subtypeController = TextEditingController(
|
||||
text: initialDetail.subType ?? '',
|
||||
);
|
||||
_descriptionController = TextEditingController(
|
||||
text: initialDetail.description ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subtypeController.dispose();
|
||||
_descriptionController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _showProviderModal(BuildContext context, String operationType) {
|
||||
final formCubit = context.read<OperationDetailsFormCubit>();
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (modalContext) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.5,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.8,
|
||||
expand: false,
|
||||
builder: (_, scrollController) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Seleziona Gestore',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(modalContext),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: BlocBuilder<ProviderListCubit, ProviderListState>(
|
||||
builder: (context, state) {
|
||||
if (state.status == ProviderListStatus.loading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
final filteredProviders =
|
||||
state.providers.where((p) {
|
||||
return p.supportsOperation(operationType) &&
|
||||
p.isActive;
|
||||
}).toList();
|
||||
|
||||
if (filteredProviders.isEmpty) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Nessun gestore compatibile con questo servizio.',
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
controller: scrollController,
|
||||
itemCount: filteredProviders.length,
|
||||
itemBuilder: (context, index) {
|
||||
final provider = filteredProviders[index];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.business),
|
||||
title: Text(
|
||||
provider.name,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
provider.roles
|
||||
.map((r) => r.displayValue)
|
||||
.join(', '),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
onTap: () {
|
||||
formCubit.setProvider(provider);
|
||||
Navigator.pop(modalContext);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDurationQuickPicks(BuildContext context) {
|
||||
final durations = [3, 6, 12, 24, 30, 36, 48];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
"Imposta durata rapida (mesi):",
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children:
|
||||
durations.map((months) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: ActionChip(
|
||||
label: Text("$months m"),
|
||||
backgroundColor: Colors.blue.withValues(alpha: 0.05),
|
||||
onPressed: () {
|
||||
final now = DateTime.now();
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(
|
||||
expirationDate: DateTime(
|
||||
now.year,
|
||||
now.month + months,
|
||||
now.day,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.75,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
expand: false,
|
||||
builder: (_, scrollController) {
|
||||
return BlocBuilder<
|
||||
OperationDetailsFormCubit,
|
||||
OperationDetailsFormState
|
||||
>(
|
||||
builder: (context, formState) {
|
||||
final detail = formState.operationDetail;
|
||||
final currentType = detail.type ?? 'AL';
|
||||
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Header Bottom Sheet
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
formState.isEditing
|
||||
? 'Modifica Dettaglio Servizio'
|
||||
: 'Nuovo Dettaglio Servizio',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
children: [
|
||||
// 1. Tipo Servizio (Wrap di Chips)
|
||||
const Text(
|
||||
'Tipo Servizio',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8.0,
|
||||
runSpacing: 8.0,
|
||||
children:
|
||||
OperationDetailsSection._availableTypes.map((
|
||||
type,
|
||||
) {
|
||||
return ChoiceChip(
|
||||
label: Text(type),
|
||||
selected: currentType == type,
|
||||
onSelected: (selected) {
|
||||
if (selected) {
|
||||
final allProviders =
|
||||
context
|
||||
.read<ProviderListCubit>()
|
||||
.state
|
||||
.providers;
|
||||
final defaultProviderId =
|
||||
context
|
||||
.read<SessionCubit>()
|
||||
.state
|
||||
.currentStore
|
||||
?.defaultProviderId;
|
||||
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.setTypeWithSmartDefaults(
|
||||
newType: type,
|
||||
allProviders: allProviders,
|
||||
defaultProviderId:
|
||||
defaultProviderId,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 2. Seleziona Gestore
|
||||
ListTile(
|
||||
title: const Text('Seleziona Gestore'),
|
||||
subtitle: Text(
|
||||
(detail.provider != null)
|
||||
? detail.provider!.name
|
||||
: 'Nessun gestore selezionato',
|
||||
style: TextStyle(
|
||||
color:
|
||||
(detail.provider == null ||
|
||||
detail.provider!.name.isEmpty)
|
||||
? Colors.grey
|
||||
: null,
|
||||
fontWeight:
|
||||
(detail.provider == null ||
|
||||
detail.provider!.name.isEmpty)
|
||||
? FontWeight.normal
|
||||
: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
trailing: const Icon(Icons.arrow_drop_down),
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(color: theme.dividerColor),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
onTap: () => _showProviderModal(context, currentType),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 3. Scenario Energy (Dropdown Fisso)
|
||||
if (currentType == 'Energy') ...[
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue:
|
||||
(detail.subType != null &&
|
||||
detail.subType!.isNotEmpty)
|
||||
? detail.subType
|
||||
: 'Luce',
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Dettaglio Fornitura',
|
||||
),
|
||||
items:
|
||||
['Luce', 'Gas']
|
||||
.map(
|
||||
(s) => DropdownMenuItem(
|
||||
value: s,
|
||||
child: Text(s),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (val) {
|
||||
if (val != null) {
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(subType: val);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Offerta scelta',
|
||||
),
|
||||
onChanged: (val) {
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(description: val);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// 4. Scenario Fin (Ricerca Modello/Prodotto)
|
||||
if (currentType == 'Fin') ...[
|
||||
SharedModelSection(
|
||||
label: 'Seleziona Dispositivo/Prodotto',
|
||||
modelId: detail.modelId,
|
||||
modelName: detail.model?.nameWithBrand,
|
||||
onModelSelected: (id, name) {
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(modelId: id);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// 5. Scenario Entertainment o Custom (Testo libero)
|
||||
if (currentType == 'Entertainment' ||
|
||||
currentType == 'Altro') ...[
|
||||
TextFormField(
|
||||
controller: _subtypeController,
|
||||
decoration: InputDecoration(
|
||||
labelText:
|
||||
currentType == 'Entertainment'
|
||||
? 'Piattaforma (es. Netflix, DAZN, Spotify...)'
|
||||
: 'Specifica il servizio (es. Monopattino)',
|
||||
),
|
||||
onChanged: (val) {
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(subType: val);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// 6. Scadenza (Reattiva per tipi complessi)
|
||||
if ([
|
||||
'Energy',
|
||||
'Fin',
|
||||
'Entertainment',
|
||||
'Altro',
|
||||
].contains(currentType)) ...[
|
||||
_buildDurationQuickPicks(context),
|
||||
const SizedBox(height: 16),
|
||||
ListTile(
|
||||
title: const Text('Data di Scadenza Effettiva'),
|
||||
subtitle: Text(
|
||||
detail.expirationDate != null
|
||||
? "${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}"
|
||||
: 'Nessuna scadenza impostata',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
trailing: const Icon(
|
||||
Icons.calendar_month,
|
||||
color: Colors.blue,
|
||||
),
|
||||
tileColor: Colors.blue.withValues(alpha: 0.05),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: const BorderSide(
|
||||
color: Colors.blue,
|
||||
width: 0.5,
|
||||
),
|
||||
),
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate:
|
||||
detail.expirationDate ??
|
||||
DateTime.now().add(
|
||||
const Duration(days: 365),
|
||||
),
|
||||
firstDate: DateTime.now(),
|
||||
lastDate: DateTime.now().add(
|
||||
const Duration(days: 3650),
|
||||
),
|
||||
);
|
||||
if (date != null && context.mounted) {
|
||||
context
|
||||
.read<OperationDetailsFormCubit>()
|
||||
.updateFields(expirationDate: date);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Pulsante di conferma
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(48),
|
||||
),
|
||||
onPressed: () {
|
||||
final finalDetail = formState.operationDetail;
|
||||
|
||||
if (formState.isEditing) {
|
||||
widget.listCubit.updateOperationDetail(
|
||||
formState.editingIndex!,
|
||||
finalDetail,
|
||||
);
|
||||
} else {
|
||||
widget.listCubit.addOperationDetail(finalDetail);
|
||||
}
|
||||
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(
|
||||
formState.isEditing
|
||||
? 'Salva Modifiche'
|
||||
: 'Aggiungi Dettaglio',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import 'package:flux/features/settings/data/settings_repository.dart';
|
||||
import 'package:flux/features/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tasks/models/task_model.dart';
|
||||
import 'package:flux/features/tasks/models/task_reminder_config.dart';
|
||||
import 'package:flux/features/tasks/models/task_status.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
part 'task_form_state.dart';
|
||||
|
||||
@@ -30,7 +31,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
}
|
||||
|
||||
String get _companyId => _sessionCubit.state.company!.id!;
|
||||
String get _currentUserId => _sessionCubit.state.currentStaffMember!.id!;
|
||||
StaffMemberModel get _currentUser => _sessionCubit.state.currentStaffMember!;
|
||||
String? get _currentStoreId => _sessionCubit.state.currentStore?.id;
|
||||
|
||||
// --- ARMED INITIALIZATION (Nuovo, Esistente o Deep Link) ---
|
||||
@@ -57,6 +58,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
dueDate: task.dueDate,
|
||||
isGlobal: task.isGlobal, // Sfrutta il tuo getter storeId == null
|
||||
selectedStaffIds: task.assignedToIds,
|
||||
taskStatus: task.status,
|
||||
),
|
||||
);
|
||||
await _loadExistingTaskReminders(task.id!);
|
||||
@@ -129,7 +131,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
try {
|
||||
final defaults = await _settingsRepository.getMyReminderDefaults(
|
||||
companyId: _companyId,
|
||||
staffId: _currentUserId,
|
||||
staffId: _currentUser.id!,
|
||||
);
|
||||
final initialReminders = defaults
|
||||
.map(
|
||||
@@ -155,7 +157,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
try {
|
||||
final existingConfigs = await _repository.fetchPersonalReminders(
|
||||
taskId: taskId,
|
||||
staffId: _currentUserId,
|
||||
staffId: _currentUser.id!,
|
||||
);
|
||||
emit(state.copyWith(reminders: existingConfigs));
|
||||
} catch (e) {
|
||||
@@ -218,7 +220,7 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
final taskToSave = TaskModel(
|
||||
id: state.id,
|
||||
companyId: _companyId,
|
||||
createdById: _currentUserId,
|
||||
createdBy: _currentUser,
|
||||
title: state.title.trim(),
|
||||
description: state.description.trim(),
|
||||
dueDate: state.dueDate,
|
||||
@@ -233,14 +235,14 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
await _repository.createTask(
|
||||
task: taskToSave,
|
||||
assignedStaffIds: state.selectedStaffIds,
|
||||
currentUserId: _currentUserId,
|
||||
currentUserId: _currentUser.id!,
|
||||
currentUserCustomReminders: state.reminders,
|
||||
);
|
||||
} else {
|
||||
await _repository.updateTask(
|
||||
task: taskToSave,
|
||||
assignedStaffIds: state.selectedStaffIds,
|
||||
currentUserId: _currentUserId,
|
||||
currentUserId: _currentUser.id!,
|
||||
currentUserCustomReminders: state.reminders,
|
||||
);
|
||||
}
|
||||
@@ -254,4 +256,51 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteTask() async {
|
||||
if (state.id == null) return;
|
||||
emit(state.copyWith(status: TaskFormStatus.submitting));
|
||||
try {
|
||||
await _repository.deleteTask(state.id!);
|
||||
emit(state.copyWith(status: TaskFormStatus.success));
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TaskFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateTaskLocalStatus(TaskStatus newStatus) async {
|
||||
emit(state.copyWith(taskStatus: newStatus));
|
||||
}
|
||||
|
||||
Future<void> updateTaskStatus(TaskStatus newStatus) async {
|
||||
try {
|
||||
// Chiamiamo il repo passando il task aggiornato
|
||||
await _repository.updateTaskStatus(
|
||||
taskId: state.id!,
|
||||
newStatus: newStatus,
|
||||
updatedById: _currentUser.id!,
|
||||
);
|
||||
|
||||
if (!isClosed) {
|
||||
// Se l'update va a buon fine, aggiorniamo lo stato locale del cubit
|
||||
emit(
|
||||
state.copyWith(status: TaskFormStatus.success, taskStatus: newStatus),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TaskFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,9 @@ class TaskFormState extends Equatable {
|
||||
final bool isGlobal;
|
||||
final List<String> selectedStaffIds;
|
||||
final List<TaskReminderConfig> reminders;
|
||||
final Map<String, List<StaffMemberModel>>
|
||||
groupedAvailableStaff; // <-- RIPRISTINATO
|
||||
final Map<String, List<StaffMemberModel>> groupedAvailableStaff;
|
||||
final String? errorMessage;
|
||||
final TaskStatus taskStatus;
|
||||
|
||||
const TaskFormState({
|
||||
this.id,
|
||||
@@ -26,6 +26,7 @@ class TaskFormState extends Equatable {
|
||||
this.reminders = const [],
|
||||
this.groupedAvailableStaff = const {},
|
||||
this.errorMessage,
|
||||
this.taskStatus = TaskStatus.open,
|
||||
});
|
||||
|
||||
bool get isFormValid => title.trim().isNotEmpty;
|
||||
@@ -41,6 +42,7 @@ class TaskFormState extends Equatable {
|
||||
List<TaskReminderConfig>? reminders,
|
||||
Map<String, List<StaffMemberModel>>? groupedAvailableStaff,
|
||||
String? errorMessage,
|
||||
TaskStatus? taskStatus,
|
||||
}) {
|
||||
return TaskFormState(
|
||||
id: id ?? this.id,
|
||||
@@ -54,6 +56,7 @@ class TaskFormState extends Equatable {
|
||||
groupedAvailableStaff:
|
||||
groupedAvailableStaff ?? this.groupedAvailableStaff,
|
||||
errorMessage: errorMessage,
|
||||
taskStatus: taskStatus ?? this.taskStatus,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,5 +72,6 @@ class TaskFormState extends Equatable {
|
||||
reminders,
|
||||
groupedAvailableStaff,
|
||||
errorMessage,
|
||||
taskStatus,
|
||||
];
|
||||
}
|
||||
@@ -21,7 +21,7 @@ class TasksRepository {
|
||||
}) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from('task_reminders')
|
||||
.from(Tables.taskReminders)
|
||||
.select()
|
||||
.eq('task_id', taskId)
|
||||
.eq('staff_id', staffId)
|
||||
@@ -53,13 +53,17 @@ class TasksRepository {
|
||||
int? limit,
|
||||
}) async {
|
||||
try {
|
||||
// 1. FASE FILTRI: Usa il join esplicito stile "Notes"
|
||||
// 1. FASE FILTRI: Disambiguazione completa su Tasks e Assignments
|
||||
var filterBuilder = _supabase
|
||||
.from(Tables.tasks)
|
||||
.select('''
|
||||
*,
|
||||
creator:${Tables.staffMembers}!created_by_id(*),
|
||||
updater:${Tables.staffMembers}!updated_by_id(*),
|
||||
task_assignments:${Tables.taskAssignments} (
|
||||
${Tables.staffMembers} (*)
|
||||
*,
|
||||
assignee:${Tables.staffMembers}!staff_id(*),
|
||||
assigner:${Tables.staffMembers}!assigned_by_id(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId);
|
||||
@@ -71,7 +75,6 @@ class TasksRepository {
|
||||
}
|
||||
|
||||
if (staffId != null) {
|
||||
// Grazie al trigger, hai l'array pronto per il filtro senza impazzire!
|
||||
filterBuilder = filterBuilder.contains('assigned_to_ids', [staffId]);
|
||||
}
|
||||
|
||||
@@ -105,8 +108,12 @@ class TasksRepository {
|
||||
.from(Tables.tasks)
|
||||
.select('''
|
||||
*,
|
||||
creator:${Tables.staffMembers}!created_by_id(*),
|
||||
updater:${Tables.staffMembers}!updated_by_id(*),
|
||||
task_assignments:${Tables.taskAssignments} (
|
||||
${Tables.staffMembers} (*)
|
||||
*,
|
||||
assignee:${Tables.staffMembers}!staff_id(*),
|
||||
assigner:${Tables.staffMembers}!assigned_by_id(*)
|
||||
)
|
||||
''')
|
||||
.eq('id', taskId)
|
||||
@@ -122,14 +129,11 @@ class TasksRepository {
|
||||
// =========================================================================
|
||||
// REALTIME STREAM (La sentinella per la bacheca)
|
||||
// =========================================================================
|
||||
Stream<List<TaskModel>> watchCompanyTasks(String companyId) {
|
||||
Stream<List<Map<String, dynamic>>> watchCompanyTasks(String companyId) {
|
||||
return _supabase
|
||||
.from('tasks')
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('company_id', companyId)
|
||||
.map((listOfMaps) {
|
||||
return listOfMaps.map((map) => TaskModel.fromMap(map)).toList();
|
||||
});
|
||||
.eq('company_id', companyId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
@@ -160,6 +164,7 @@ class TasksRepository {
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'company_id': task.companyId,
|
||||
'assigned_by_id': currentUserId,
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
@@ -276,7 +281,7 @@ class TasksRepository {
|
||||
|
||||
// 1. Aggiornamento dati Task Base
|
||||
await _supabase
|
||||
.from('tasks')
|
||||
.from(Tables.tasks)
|
||||
.update({
|
||||
'title': task.title,
|
||||
'description': task.description,
|
||||
@@ -286,15 +291,51 @@ class TasksRepository {
|
||||
})
|
||||
.eq('id', taskId);
|
||||
|
||||
// 2. Aggiornamento Assegnazioni: eliminiamo le vecchie, inseriamo le nuove
|
||||
await _supabase.from('task_assignments').delete().eq('task_id', taskId);
|
||||
if (assignedStaffIds.isNotEmpty) {
|
||||
final assignmentsToInsert = assignedStaffIds
|
||||
// 🥷 2. GESTIONE CHIRURGICA DELLE ASSEGNAZIONI (Addio spam!)
|
||||
|
||||
// A) Recuperiamo chi è GIÀ assegnato a questo task
|
||||
final existingAssignmentsResponse = await _supabase
|
||||
.from('task_assignments')
|
||||
.select('staff_id')
|
||||
.eq('task_id', taskId);
|
||||
|
||||
final List<String> existingStaffIds =
|
||||
(existingAssignmentsResponse as List)
|
||||
.map((row) => row['staff_id'] as String)
|
||||
.toList();
|
||||
|
||||
// B) Calcoliamo i Delta con i Set di Dart (Pura magia matematica)
|
||||
final newStaffIdsSet = assignedStaffIds.toSet();
|
||||
final existingStaffIdsSet = existingStaffIds.toSet();
|
||||
|
||||
// Quelli da inserire (presenti nei nuovi, ma non nei vecchi)
|
||||
final toInsertIds = newStaffIdsSet
|
||||
.difference(existingStaffIdsSet)
|
||||
.toList();
|
||||
|
||||
// Quelli da eliminare (presenti nei vecchi, ma non nei nuovi)
|
||||
final toDeleteIds = existingStaffIdsSet
|
||||
.difference(newStaffIdsSet)
|
||||
.toList();
|
||||
|
||||
// C) Eseguiamo solo lo stretto necessario
|
||||
if (toDeleteIds.isNotEmpty) {
|
||||
await _supabase
|
||||
.from('task_assignments')
|
||||
.delete()
|
||||
.eq('task_id', taskId)
|
||||
.inFilter('staff_id', toDeleteIds);
|
||||
}
|
||||
|
||||
if (toInsertIds.isNotEmpty) {
|
||||
final assignmentsToInsert = toInsertIds
|
||||
.map(
|
||||
(staffId) => {
|
||||
'task_id': taskId,
|
||||
'staff_id': staffId,
|
||||
'company_id': task.companyId,
|
||||
'assigned_by_id':
|
||||
currentUserId, // Il nostro salvavita anti-fantasma
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
@@ -352,6 +393,35 @@ class TasksRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateTaskStatus({
|
||||
required String taskId,
|
||||
required TaskStatus newStatus,
|
||||
required String? updatedById,
|
||||
}) async {
|
||||
try {
|
||||
await _supabase
|
||||
.from(Tables.tasks)
|
||||
.update({
|
||||
'status': newStatus.toValue,
|
||||
'updated_by_id': updatedById,
|
||||
'updated_at': DateTime.now().toIso8601String(),
|
||||
})
|
||||
.eq('id', taskId);
|
||||
} catch (e) {
|
||||
throw Exception(
|
||||
'Errore durante l\'aggiornamento dello stato del task: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteTask(String taskId) async {
|
||||
try {
|
||||
await _supabase.from(Tables.tasks).delete().eq('id', taskId);
|
||||
} catch (e) {
|
||||
throw Exception('Errore durante la cancellazione del task: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- HELPER PRIVATO PER LA MAPPA DEL REMINDER ---
|
||||
Map<String, dynamic> _buildReminderRow(
|
||||
TaskModel task,
|
||||
|
||||
@@ -9,11 +9,12 @@ class TaskModel extends Equatable {
|
||||
final String? description;
|
||||
final List<String> assignedToIds;
|
||||
final List<StaffMemberModel> assignedToStaff; // I dati completi dal JOIN
|
||||
final String? createdById;
|
||||
final StaffMemberModel? createdBy;
|
||||
final DateTime? dueDate;
|
||||
final TaskStatus status;
|
||||
final DateTime? createdAt;
|
||||
final String? storeId;
|
||||
final StaffMemberModel? updatedBy;
|
||||
|
||||
const TaskModel({
|
||||
this.id,
|
||||
@@ -22,24 +23,25 @@ class TaskModel extends Equatable {
|
||||
this.description,
|
||||
this.assignedToIds = const [],
|
||||
this.assignedToStaff = const [],
|
||||
this.createdById,
|
||||
this.createdBy,
|
||||
this.dueDate,
|
||||
this.status = TaskStatus.open,
|
||||
this.createdAt,
|
||||
this.storeId,
|
||||
this.updatedBy,
|
||||
});
|
||||
|
||||
bool get isGlobal => storeId == null;
|
||||
|
||||
// --- FACTORY: MODELLO VUOTO (Per le creazioni) ---
|
||||
factory TaskModel.empty({String? companyId, String? createdById}) {
|
||||
factory TaskModel.empty({String? companyId, StaffMemberModel? createdBy}) {
|
||||
return TaskModel(
|
||||
companyId: companyId,
|
||||
title: '',
|
||||
description: '',
|
||||
assignedToIds: const [],
|
||||
assignedToStaff: const [],
|
||||
createdById: createdById,
|
||||
createdBy: createdBy,
|
||||
status: TaskStatus.open,
|
||||
createdAt: DateTime.now(),
|
||||
);
|
||||
@@ -54,11 +56,12 @@ class TaskModel extends Equatable {
|
||||
description,
|
||||
assignedToIds,
|
||||
assignedToStaff,
|
||||
createdById,
|
||||
createdBy,
|
||||
dueDate,
|
||||
status,
|
||||
createdAt,
|
||||
storeId,
|
||||
updatedBy,
|
||||
];
|
||||
|
||||
// --- COPY WITH ---
|
||||
@@ -69,13 +72,15 @@ class TaskModel extends Equatable {
|
||||
String? description,
|
||||
List<String>? assignedToIds,
|
||||
List<StaffMemberModel>? assignedToStaff,
|
||||
String? createdById,
|
||||
StaffMemberModel? createdBy,
|
||||
DateTime? dueDate,
|
||||
bool clearDueDate = false, // Flag ninja per resettare la scadenza
|
||||
TaskStatus? status,
|
||||
DateTime? createdAt,
|
||||
String? storeId,
|
||||
bool clearStoreId = false,
|
||||
StaffMemberModel? updatedBy,
|
||||
String? updatedByDisplayName,
|
||||
}) {
|
||||
return TaskModel(
|
||||
id: id ?? this.id,
|
||||
@@ -84,11 +89,12 @@ class TaskModel extends Equatable {
|
||||
description: description ?? this.description,
|
||||
assignedToIds: assignedToIds ?? this.assignedToIds,
|
||||
assignedToStaff: assignedToStaff ?? this.assignedToStaff,
|
||||
createdById: createdById ?? this.createdById,
|
||||
createdBy: createdBy ?? this.createdBy,
|
||||
dueDate: clearDueDate ? null : (dueDate ?? this.dueDate),
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
storeId: clearStoreId ? null : (storeId ?? this.storeId),
|
||||
updatedBy: updatedBy ?? this.updatedBy,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,7 +130,9 @@ class TaskModel extends Equatable {
|
||||
description: map['description'] as String?,
|
||||
assignedToIds: parsedAssignedToIds,
|
||||
assignedToStaff: staffList,
|
||||
createdById: map['created_by_id'] as String?,
|
||||
createdBy: map['created_by_id'] != null
|
||||
? StaffMemberModel.fromMap(map['creator'])
|
||||
: null,
|
||||
dueDate: map['due_date'] != null
|
||||
? DateTime.parse(map['due_date'] as String).toLocal()
|
||||
: null,
|
||||
@@ -133,6 +141,9 @@ class TaskModel extends Equatable {
|
||||
? DateTime.parse(map['created_at'] as String).toLocal()
|
||||
: null,
|
||||
storeId: map['store_id'] as String?,
|
||||
updatedBy: map['updated_by_id'] != null
|
||||
? StaffMemberModel.fromMap(map['updater'])
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -145,10 +156,11 @@ class TaskModel extends Equatable {
|
||||
if (description != null) 'description': description,
|
||||
// Passiamo l'array vuoto se non ci sono assegnazioni
|
||||
'assigned_to_ids': assignedToIds.isEmpty ? null : assignedToIds,
|
||||
if (createdById != null) 'created_by_id': createdById,
|
||||
if (createdBy != null) 'created_by_id': createdBy!.id,
|
||||
'due_date': dueDate?.toUtc().toIso8601String(),
|
||||
'status': status.toValue,
|
||||
'store_id': storeId,
|
||||
if (updatedBy != null) 'updated_by_id': updatedBy!.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
enum TaskStatus { open, inProgress, completed }
|
||||
|
||||
extension TaskStatusExtension on TaskStatus {
|
||||
String get name {
|
||||
String get displayName {
|
||||
switch (this) {
|
||||
case TaskStatus.open:
|
||||
return 'Da Iniziare';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/tasks/blocs/task_form_cubit.dart';
|
||||
import 'package:flux/features/tasks/models/task_status.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class TaskFormScreen extends StatefulWidget {
|
||||
@@ -123,6 +124,30 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
|
||||
appBar: AppBar(
|
||||
title: Text(isEditing ? 'Modifica Task' : 'Nuovo Task'),
|
||||
actions: [
|
||||
// 🥷 1. BOTTONE COMPLETAMENTO RAPIDO (Solo se in edit e non già completato)
|
||||
if (isEditing && state.taskStatus != TaskStatus.completed)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () {
|
||||
context.read<TaskFormCubit>().updateTaskStatus(
|
||||
TaskStatus.completed,
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.check_circle_outline),
|
||||
label: const Text('Completa'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.green.shade600,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 🥷 2. LOADER O BOTTONE SALVA
|
||||
if (state.status == TaskFormStatus.submitting)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
@@ -133,13 +158,18 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
|
||||
),
|
||||
)
|
||||
else
|
||||
TextButton.icon(
|
||||
onPressed: state.isFormValid ? () => cubit.saveTask() : null,
|
||||
icon: const Icon(Icons.save),
|
||||
label: const Text('Salva'),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.orange,
|
||||
disabledForegroundColor: Colors.grey,
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: TextButton.icon(
|
||||
onPressed: state.isFormValid
|
||||
? () => cubit.saveTask()
|
||||
: null,
|
||||
icon: const Icon(Icons.save),
|
||||
label: const Text('Salva'),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.orange,
|
||||
disabledForegroundColor: Colors.grey,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -264,6 +294,45 @@ class _TaskFormScreenState extends State<TaskFormScreen> {
|
||||
),
|
||||
onChanged: cubit.updateDescription,
|
||||
),
|
||||
if (state.id != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<TaskStatus>(
|
||||
// Leggiamo lo stato attuale dal Cubit (o usiamo un default per i nuovi task)
|
||||
initialValue: state.taskStatus,
|
||||
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Stato Attuale',
|
||||
prefixIcon: const Icon(Icons.flag_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Theme.of(context).colorScheme.surface,
|
||||
),
|
||||
|
||||
// Mappiamo tutti i valori dell'enum in elementi della tendina
|
||||
items: TaskStatus.values.map((TaskStatus status) {
|
||||
return DropdownMenuItem<TaskStatus>(
|
||||
value: status,
|
||||
child: Text(
|
||||
status
|
||||
.displayName, // Usa la property displayName del tuo enum!
|
||||
style: TextStyle(
|
||||
fontWeight: status == state.taskStatus
|
||||
? FontWeight.bold
|
||||
: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
|
||||
onChanged: (TaskStatus? newStatus) {
|
||||
if (newStatus != null && newStatus != state.taskStatus) {
|
||||
context.read<TaskFormCubit>().updateTaskStatus(newStatus);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// --- SCADENZA ---
|
||||
|
||||
@@ -17,11 +17,15 @@ class TicketListCubit extends Cubit<TicketListState> {
|
||||
loadTickets(refresh: true);
|
||||
}
|
||||
|
||||
int _fetchId = 0;
|
||||
|
||||
/// Recupera i ticket. Se reset = true, svuota la lista e riparte da offset 0.
|
||||
Future<void> loadTickets({bool refresh = false}) async {
|
||||
if (state.isLoading) return;
|
||||
if (state.isLoading && !refresh) return;
|
||||
if (!refresh && state.hasReachedMax) return;
|
||||
|
||||
final currentFetchId = ++_fetchId;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoading: true,
|
||||
@@ -43,6 +47,8 @@ class TicketListCubit extends Cubit<TicketListState> {
|
||||
staffIdFilter: state.staffIdFilter,
|
||||
);
|
||||
|
||||
if (currentFetchId != _fetchId) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
tickets: refresh ? newTickets : [...state.tickets, ...newTickets],
|
||||
@@ -51,6 +57,7 @@ class TicketListCubit extends Cubit<TicketListState> {
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (currentFetchId != _fetchId) return;
|
||||
emit(state.copyWith(isLoading: false, errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,44 @@ class TicketShippingCubit extends Cubit<TicketShippingState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> createQuickProvider({
|
||||
required String name,
|
||||
required String address,
|
||||
String city = '',
|
||||
String zipCode = '',
|
||||
String province = '',
|
||||
}) async {
|
||||
emit(state.copyWith(status: TicketShippingStatus.loading));
|
||||
try {
|
||||
final newProvider = await _repository.createQuickRepairCenter(
|
||||
name: name,
|
||||
address: address,
|
||||
city: city,
|
||||
zipCode: zipCode,
|
||||
province: province,
|
||||
);
|
||||
|
||||
final updatedProviders = List<ProviderModel>.from(state.availableProviders)
|
||||
..add(newProvider);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketShippingStatus.initial,
|
||||
availableProviders: updatedProviders,
|
||||
),
|
||||
);
|
||||
|
||||
selectProvider(newProvider.id!);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: TicketShippingStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void selectProvider(String providerId) {
|
||||
final ProviderModel provider = state.availableProviders.firstWhere(
|
||||
(p) => p.id == providerId,
|
||||
|
||||
@@ -59,9 +59,21 @@ class TicketRepository {
|
||||
query = query.eq('staff_id', staffIdFilter);
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.isNotEmpty) {
|
||||
// Filtra sui campi della tabella principale O su quelli della tabella joinata
|
||||
query = query.or('customer.name.ilike.%$searchTerm%');
|
||||
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
|
||||
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
|
||||
final matchingCustomerIds = await _findMatchingCustomerIds(cleanTerm);
|
||||
final List<String> orConditions = [
|
||||
'request.ilike.%$cleanTerm%',
|
||||
'reference_id.ilike.%$cleanTerm%',
|
||||
'public_notes.ilike.%$cleanTerm%',
|
||||
'internal_notes.ilike.%$cleanTerm%',
|
||||
'target_sn.ilike.%$cleanTerm%',
|
||||
'source_sn.ilike.%$cleanTerm%',
|
||||
];
|
||||
if (matchingCustomerIds.isNotEmpty) {
|
||||
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
|
||||
}
|
||||
query = query.or(orConditions.join(','));
|
||||
}
|
||||
|
||||
final response = await query
|
||||
@@ -74,6 +86,23 @@ class TicketRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<String>> _findMatchingCustomerIds(String searchTerm) async {
|
||||
try {
|
||||
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
|
||||
final companyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
var customerQuery = _supabase.from(Tables.customers).select('id');
|
||||
if (companyId != null && companyId.isNotEmpty) {
|
||||
customerQuery = customerQuery.eq('company_id', companyId);
|
||||
}
|
||||
final response = await customerQuery
|
||||
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%')
|
||||
.limit(100);
|
||||
return (response as List).map((c) => c['id'].toString()).toList();
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI TUTTA L'AZIENDA ---
|
||||
Future<List<TicketModel>> fetchTickets({
|
||||
required String? companyId,
|
||||
@@ -123,9 +152,21 @@ class TicketRepository {
|
||||
query = query.eq('staff_id', staffIdFilter);
|
||||
}
|
||||
|
||||
if (searchTerm != null && searchTerm.isNotEmpty) {
|
||||
// Filtra sui campi della tabella principale O su quelli della tabella joinata
|
||||
query = query.or('customer.name.ilike.%$searchTerm%');
|
||||
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
|
||||
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
|
||||
final matchingCustomerIds = await _findMatchingCustomerIds(cleanTerm);
|
||||
final List<String> orConditions = [
|
||||
'request.ilike.%$cleanTerm%',
|
||||
'reference_id.ilike.%$cleanTerm%',
|
||||
'public_notes.ilike.%$cleanTerm%',
|
||||
'internal_notes.ilike.%$cleanTerm%',
|
||||
'target_sn.ilike.%$cleanTerm%',
|
||||
'source_sn.ilike.%$cleanTerm%',
|
||||
];
|
||||
if (matchingCustomerIds.isNotEmpty) {
|
||||
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
|
||||
}
|
||||
query = query.or(orConditions.join(','));
|
||||
}
|
||||
|
||||
final response = await query
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/features/tickets/models/shipping_document_model.dart';
|
||||
import 'package:flux/features/master_data/providers/models/provider_location_model.dart';
|
||||
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/tickets/models/ticket_model.dart';
|
||||
@@ -17,8 +19,8 @@ class TicketsShippingRepository {
|
||||
Future<List<ProviderModel>> fetchRepairCenters() async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from('provider')
|
||||
.select('*, provider_locations (*)')
|
||||
.from(Tables.providers)
|
||||
.select('*, ${Tables.providerLocations} (*)')
|
||||
.eq('is_active', true)
|
||||
.order('name');
|
||||
|
||||
@@ -35,13 +37,63 @@ class TicketsShippingRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<ProviderModel> createQuickRepairCenter({
|
||||
required String name,
|
||||
required String address,
|
||||
String city = '',
|
||||
String zipCode = '',
|
||||
String province = '',
|
||||
}) async {
|
||||
try {
|
||||
final provider = ProviderModel(
|
||||
companyId: _companyId,
|
||||
name: name,
|
||||
isActive: true,
|
||||
roles: const [ProviderRole.repairCenter],
|
||||
);
|
||||
|
||||
final savedRow = await _supabase
|
||||
.from(Tables.providers)
|
||||
.insert(provider.toMap())
|
||||
.select()
|
||||
.single();
|
||||
|
||||
final savedProvider = ProviderModel.fromMap(savedRow);
|
||||
|
||||
final location = ProviderLocationModel(
|
||||
providerId: savedProvider.id!,
|
||||
companyId: _companyId,
|
||||
name: 'Sede Principale',
|
||||
address: address,
|
||||
city: city,
|
||||
zipCode: zipCode,
|
||||
province: province,
|
||||
isMain: true,
|
||||
);
|
||||
|
||||
final locationRow = await _supabase
|
||||
.from(Tables.providerLocations)
|
||||
.insert(location.toMap())
|
||||
.select()
|
||||
.single();
|
||||
|
||||
final savedLocation = ProviderLocationModel.fromMap(locationRow);
|
||||
|
||||
return savedProvider.copyWith(
|
||||
locations: [savedLocation],
|
||||
);
|
||||
} catch (e) {
|
||||
throw ('Errore creazione centro di riparazione rapido: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<ShippingDocumentModel>> fetchShipmentDocumentsForTicket(
|
||||
String ticketId,
|
||||
) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from('shipping_documents')
|
||||
.select('*, attachments (*)')
|
||||
.from(Tables.shippingDocuments)
|
||||
.select('*, ${Tables.attachments} (*)')
|
||||
.contains('ticket_ids', [ticketId]);
|
||||
|
||||
return (response as List)
|
||||
@@ -57,8 +109,8 @@ class TicketsShippingRepository {
|
||||
Future<List<ShippingDocumentModel>> fetchCompanyShipmentDocuments() async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from('shipping_documents')
|
||||
.select('*, attachments (*)')
|
||||
.from(Tables.shippingDocuments)
|
||||
.select('*, ${Tables.attachments} (*)')
|
||||
.eq('company_id', _companyId);
|
||||
|
||||
return (response as List)
|
||||
@@ -76,8 +128,8 @@ class TicketsShippingRepository {
|
||||
) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from('shipping_documents')
|
||||
.select('*, attachments (*)')
|
||||
.from(Tables.shippingDocuments)
|
||||
.select('*, ${Tables.attachments} (*)')
|
||||
.eq('id', documentId)
|
||||
.single();
|
||||
|
||||
@@ -99,7 +151,7 @@ class TicketsShippingRepository {
|
||||
// 1. Inseriamo prima il Documento di Trasporto (DDT) su Postgres
|
||||
// Il modello iniziale non ha ancora gli allegati popolati, quindi passiamo il toMap standard
|
||||
final savedDocument = await _supabase
|
||||
.from('shipping_documents')
|
||||
.from(Tables.shippingDocuments)
|
||||
.insert(document.toMap())
|
||||
.select('id')
|
||||
.single();
|
||||
@@ -123,7 +175,7 @@ class TicketsShippingRepository {
|
||||
|
||||
// 4. Aggiorniamo lo stato di TUTTI i ticket inclusi nel DDT e li colleghiamo all'ID del DDT
|
||||
await _supabase
|
||||
.from('ticket')
|
||||
.from(Tables.tickets)
|
||||
.update({
|
||||
'ticket_status': newTicketStatus.value,
|
||||
'shipping_document_id': documentId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
@@ -20,6 +21,7 @@ class TicketListScreen extends StatefulWidget {
|
||||
class _TicketListScreenState extends State<TicketListScreen> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
Timer? _debounce;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -33,8 +35,19 @@ class _TicketListScreenState extends State<TicketListScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
void _onSearchChanged(String text) {
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 400), () {
|
||||
if (!mounted) return;
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
searchTerm: text,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
_scrollController.dispose();
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
@@ -68,11 +81,12 @@ class _TicketListScreenState extends State<TicketListScreen> {
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Cerca per nome cliente...',
|
||||
hintText: 'Cerca per cliente, richiesta o riferimento...',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
_debounce?.cancel();
|
||||
_searchController.clear();
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
clearSearch: true,
|
||||
@@ -83,7 +97,9 @@ class _TicketListScreenState extends State<TicketListScreen> {
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
onChanged: _onSearchChanged,
|
||||
onSubmitted: (value) {
|
||||
_debounce?.cancel();
|
||||
context.read<TicketListCubit>().updateFilters(
|
||||
searchTerm: value,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
typedef QuickProviderData = ({
|
||||
String name,
|
||||
String address,
|
||||
String city,
|
||||
String zipCode,
|
||||
String province,
|
||||
});
|
||||
|
||||
class QuickProviderDialog extends StatefulWidget {
|
||||
const QuickProviderDialog({super.key});
|
||||
|
||||
static Future<QuickProviderData?> show(BuildContext context) {
|
||||
return showDialog<QuickProviderData>(
|
||||
context: context,
|
||||
builder: (context) => const QuickProviderDialog(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
State<QuickProviderDialog> createState() => _QuickProviderDialogState();
|
||||
}
|
||||
|
||||
class _QuickProviderDialogState extends State<QuickProviderDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nameController = TextEditingController();
|
||||
final _addressController = TextEditingController();
|
||||
final _cityController = TextEditingController();
|
||||
final _zipController = TextEditingController();
|
||||
final _provinceController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_addressController.dispose();
|
||||
_cityController.dispose();
|
||||
_zipController.dispose();
|
||||
_provinceController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
Navigator.of(context).pop<QuickProviderData>((
|
||||
name: _nameController.text.trim(),
|
||||
address: _addressController.text.trim(),
|
||||
city: _cityController.text.trim(),
|
||||
zipCode: _zipController.text.trim(),
|
||||
province: _provinceController.text.trim().toUpperCase(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
title: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
child: Icon(Icons.domain_add, color: theme.colorScheme.primary),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Nuovo Centro Riparazioni',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SingleChildScrollView(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nome Laboratorio *',
|
||||
hintText: 'Es: riparazioni.it / Laboratorio Centrale',
|
||||
prefixIcon: Icon(Icons.storefront),
|
||||
),
|
||||
validator: (v) => v == null || v.trim().isEmpty
|
||||
? 'Campo obbligatorio'
|
||||
: null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _addressController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Indirizzo Spedizione *',
|
||||
hintText: 'Es: Via Roma 15',
|
||||
prefixIcon: Icon(Icons.location_on),
|
||||
),
|
||||
validator: (v) => v == null || v.trim().isEmpty
|
||||
? 'Campo obbligatorio'
|
||||
: null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextFormField(
|
||||
controller: _cityController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Città',
|
||||
hintText: 'Es: Milano',
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _zipController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'CAP',
|
||||
hintText: '20100',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _provinceController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prov.',
|
||||
hintText: 'MI',
|
||||
),
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
maxLength: 2,
|
||||
buildCounter: (
|
||||
_, {
|
||||
required currentLength,
|
||||
required isFocused,
|
||||
maxLength,
|
||||
}) => null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _submit,
|
||||
icon: const Icon(Icons.check),
|
||||
label: const Text('Salva e Seleziona'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -160,32 +160,39 @@ class TicketListCard extends StatelessWidget {
|
||||
// CASO 2: Più allegati. Mostriamo una BottomSheet fulminea per far scegliere all'utente.
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: attachments.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = attachments[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
file.extension == 'pdf'
|
||||
? Icons.picture_as_pdf
|
||||
: Icons.image,
|
||||
),
|
||||
title: Text(file.name),
|
||||
subtitle: Text(
|
||||
'${(file.fileSize / 1024).toStringAsFixed(1)} KB',
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.pop(
|
||||
context,
|
||||
); // Chiude la scelta
|
||||
_openFile(
|
||||
context: context,
|
||||
file: file,
|
||||
); // Apre il viewer
|
||||
},
|
||||
);
|
||||
},
|
||||
builder: (context) => Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(28),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: attachments.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = attachments[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
file.extension == 'pdf'
|
||||
? Icons.picture_as_pdf
|
||||
: Icons.image,
|
||||
),
|
||||
title: Text(file.name),
|
||||
subtitle: Text(
|
||||
'${(file.fileSize / 1024).toStringAsFixed(1)} KB',
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.pop(
|
||||
context,
|
||||
); // Chiude la scelta
|
||||
_openFile(
|
||||
context: context,
|
||||
file: file,
|
||||
); // Apre il viewer
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_shipping_cubit.dart';
|
||||
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||||
import 'package:flux/features/tickets/ui/widgets/quick_provider_dialog.dart';
|
||||
|
||||
class TicketShippingModal extends StatefulWidget {
|
||||
final List<String> ticketIds;
|
||||
@@ -24,18 +25,18 @@ class _TicketShippingModalState extends State<TicketShippingModal> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
||||
top: 24,
|
||||
left: 24,
|
||||
right: 24,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
|
||||
),
|
||||
child: BlocConsumer<TicketShippingCubit, TicketShippingState>(
|
||||
return Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
||||
top: 24,
|
||||
left: 24,
|
||||
right: 24,
|
||||
),
|
||||
child: BlocConsumer<TicketShippingCubit, TicketShippingState>(
|
||||
listener: (context, state) {
|
||||
if (state.status == TicketShippingStatus.success) {
|
||||
Navigator.pop(context, true);
|
||||
@@ -129,11 +130,12 @@ class _TicketShippingModalState extends State<TicketShippingModal> {
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -170,21 +172,49 @@ class _TicketShippingModalState extends State<TicketShippingModal> {
|
||||
BuildContext context,
|
||||
TicketShippingState state,
|
||||
) {
|
||||
return DropdownButtonFormField<String>(
|
||||
initialValue: state.document.providerId.isEmpty
|
||||
? null
|
||||
: state.document.providerId,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Seleziona Centro Riparazioni",
|
||||
prefixIcon: Icon(Icons.store),
|
||||
),
|
||||
items: state.availableProviders
|
||||
.map((p) => DropdownMenuItem(value: p.id, child: Text(p.name)))
|
||||
.toList(),
|
||||
onChanged: (val) => val != null
|
||||
? context.read<TicketShippingCubit>().selectProvider(val)
|
||||
: null,
|
||||
validator: (v) => v == null || v.isEmpty ? 'Campo obbligatorio' : null,
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<String>(
|
||||
key: ValueKey('provider_${state.document.providerId}'),
|
||||
initialValue: state.document.providerId.isEmpty
|
||||
? null
|
||||
: state.document.providerId,
|
||||
decoration: const InputDecoration(
|
||||
labelText: "Seleziona Centro Riparazioni",
|
||||
prefixIcon: Icon(Icons.store),
|
||||
),
|
||||
items: state.availableProviders
|
||||
.map((p) => DropdownMenuItem(value: p.id, child: Text(p.name)))
|
||||
.toList(),
|
||||
onChanged: (val) => val != null
|
||||
? context.read<TicketShippingCubit>().selectProvider(val)
|
||||
: null,
|
||||
validator: (v) => v == null || v.isEmpty ? 'Campo obbligatorio' : null,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4.0),
|
||||
child: IconButton.filledTonal(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: "Aggiungi nuovo centro riparazioni",
|
||||
onPressed: () async {
|
||||
final data = await QuickProviderDialog.show(context);
|
||||
if (data != null && context.mounted) {
|
||||
context.read<TicketShippingCubit>().createQuickProvider(
|
||||
name: data.name,
|
||||
address: data.address,
|
||||
city: data.city,
|
||||
zipCode: data.zipCode,
|
||||
province: data.province,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -193,6 +223,7 @@ class _TicketShippingModalState extends State<TicketShippingModal> {
|
||||
TicketShippingState state,
|
||||
) {
|
||||
return DropdownButtonFormField<String>(
|
||||
key: ValueKey('location_${state.document.destinationLocationId}'),
|
||||
initialValue: state.document.destinationLocationId.isEmpty
|
||||
? null
|
||||
: state.document.destinationLocationId,
|
||||
|
||||
@@ -93,7 +93,7 @@ class TicketPdfService {
|
||||
),
|
||||
if (isForCustomer) ...[
|
||||
pw.Text(
|
||||
"${company.address}, ${company.city}",
|
||||
"${company.address}, ${company.city} - ${company.email} - ${company.phone}",
|
||||
style: const pw.TextStyle(fontSize: 10),
|
||||
),
|
||||
pw.Text(
|
||||
@@ -118,10 +118,12 @@ class TicketPdfService {
|
||||
color: PdfColors.grey700,
|
||||
),
|
||||
),
|
||||
|
||||
pw.Text(
|
||||
"Rif: ${ticket.referenceId}",
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 14),
|
||||
),
|
||||
|
||||
pw.Text(
|
||||
"Data: ${ticket.createdAt?.toString().substring(0, 10) ?? ''}",
|
||||
style: const pw.TextStyle(fontSize: 10),
|
||||
@@ -155,14 +157,24 @@ class TicketPdfService {
|
||||
boldFont,
|
||||
),
|
||||
),
|
||||
pw.Expanded(
|
||||
child: _infoBlock(
|
||||
"CONTATTO ALTERNATIVO",
|
||||
ticket.alternativePhoneNumber ?? 'N/D',
|
||||
font,
|
||||
boldFont,
|
||||
if (ticket.customer?.phoneNumber != null)
|
||||
pw.Expanded(
|
||||
child: _infoBlock(
|
||||
"TELEFONO",
|
||||
ticket.customer?.phoneNumber ?? 'N/D',
|
||||
font,
|
||||
boldFont,
|
||||
),
|
||||
),
|
||||
if (ticket.alternativePhoneNumber != null)
|
||||
pw.Expanded(
|
||||
child: _infoBlock(
|
||||
"CONTATTO ALTERNATIVO",
|
||||
ticket.alternativePhoneNumber ?? 'N/D',
|
||||
font,
|
||||
boldFont,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ class TicketShippingPdfService {
|
||||
build: (pw.Context context) {
|
||||
return [
|
||||
pw.TableHelper.fromTextArray(
|
||||
headers: ['Rif. Ticket', 'Modello', 'Difetto / Note', 'Q.tà'],
|
||||
headers: ['Prodotto', 'Difetto', 'Q.tà'],
|
||||
headerStyle: pw.TextStyle(
|
||||
fontWeight: pw.FontWeight.bold,
|
||||
color: PdfColors.white,
|
||||
@@ -134,12 +134,24 @@ class TicketShippingPdfService {
|
||||
headerDecoration: const pw.BoxDecoration(
|
||||
color: PdfColors.blueGrey800,
|
||||
),
|
||||
cellAlignment: pw.Alignment.centerLeft,
|
||||
columnWidths: {
|
||||
0: const pw.FlexColumnWidth(3),
|
||||
1: const pw.FlexColumnWidth(4),
|
||||
2: const pw.FixedColumnWidth(45),
|
||||
},
|
||||
cellAlignments: {
|
||||
0: pw.Alignment.centerLeft,
|
||||
1: pw.Alignment.centerLeft,
|
||||
2: pw.Alignment.center,
|
||||
},
|
||||
headerAlignments: {
|
||||
0: pw.Alignment.centerLeft,
|
||||
1: pw.Alignment.centerLeft,
|
||||
2: pw.Alignment.center,
|
||||
},
|
||||
data: tickets.map((t) {
|
||||
return [
|
||||
t.id?.substring(0, 8).toUpperCase() ??
|
||||
'-', // Magari hai un ID progressivo migliore
|
||||
t.targetModelName ?? 'Sconosciuto',
|
||||
'${t.targetModelName ?? 'Modello sconosciuto'} - Rif. Ticket ${t.referenceId ?? 'Sconosciuto'}',
|
||||
t.request,
|
||||
'1', // Tipicamente 1 per ogni ticket
|
||||
];
|
||||
|
||||
+81
-113
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
@@ -7,58 +8,40 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flux/core/services/notification_service.dart';
|
||||
import 'package:flux/core/utils/version_check_service.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/features/auth/bloc/auth_cubit.dart';
|
||||
import 'package:flux/features/company/data/company_repository.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/settings/data/settings_repository.dart';
|
||||
import 'package:flux/features/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tickets/data/tickets_shipping_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/settings/blocs/settings_cubit.dart';
|
||||
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
||||
import 'package:flux/features/tracking/data/tracking_repository.dart';
|
||||
import 'package:flux/firebase_options.dart';
|
||||
import 'package:flux/l10n/app_localizations.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/data/core_repository.dart';
|
||||
import 'package:flux/core/routes/app_router.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/core/theme/bloc/theme_bloc.dart';
|
||||
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
||||
import 'package:flux/features/customers/data/customer_repository.dart';
|
||||
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
|
||||
import 'package:flux/features/master_data/products/data/product_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/data/provider_repository.dart';
|
||||
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||
import 'package:flux/features/master_data/store/data/store_repository.dart';
|
||||
import 'package:flux/features/settings/ui/settings.dart';
|
||||
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
String? initialRecoveryFragment;
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await dotenv.load(fileName: ".env");
|
||||
await init();
|
||||
final initialUri = Uri.base;
|
||||
if (initialUri.fragment.contains('access_token=')) {
|
||||
initialRecoveryFragment = initialUri.fragment;
|
||||
}
|
||||
await dotenv.load(fileName: ".env");
|
||||
|
||||
// Inizializza le dipendenze PRIMA di lanciare l'app
|
||||
await setupLocator();
|
||||
// RIMUOVE IL CARATTERE # DAGLI URL WEB!
|
||||
usePathUrlStrategy();
|
||||
// Lo Scudo Ninja: Inizializziamo Firebase SOLO sulle piattaforme supportate
|
||||
@@ -75,92 +58,39 @@ void main() async {
|
||||
runApp(
|
||||
MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<AuthCubit>(create: (context) => AuthCubit()),
|
||||
BlocProvider<AuthCubit>(create: (_) => sl<AuthCubit>()),
|
||||
BlocProvider<ThemeBloc>(
|
||||
create: (context) => ThemeBloc()..add(LoadThemeEvent()),
|
||||
create: (_) => sl<ThemeBloc>()..add(LoadThemeEvent()),
|
||||
),
|
||||
// Il Vigile Urbano viene inizializzato!
|
||||
BlocProvider<SessionCubit>(create: (_) => GetIt.I<SessionCubit>()),
|
||||
BlocProvider<SessionCubit>(create: (_) => sl<SessionCubit>()),
|
||||
|
||||
// Cubit delle feature
|
||||
BlocProvider<StoreCubit>(create: (_) => StoreCubit()),
|
||||
BlocProvider<CustomersListCubit>(create: (_) => CustomersListCubit()),
|
||||
BlocProvider<ProductsCubit>(create: (_) => ProductsCubit()),
|
||||
BlocProvider<StoreCubit>(create: (_) => sl<StoreCubit>()),
|
||||
BlocProvider<CustomersListCubit>(
|
||||
create: (_) => sl<CustomersListCubit>(),
|
||||
),
|
||||
BlocProvider<ProductsCubit>(create: (_) => sl<ProductsCubit>()),
|
||||
BlocProvider<StaffCubit>(
|
||||
create: (_) => StaffCubit()
|
||||
create: (_) => sl<StaffCubit>()
|
||||
..loadStaffForStore(
|
||||
GetIt.I.get<SessionCubit>().state.currentStore!.id!,
|
||||
),
|
||||
),
|
||||
BlocProvider<OperationListCubit>(create: (_) => OperationListCubit()),
|
||||
BlocProvider<ProviderListCubit>(create: (_) => ProviderListCubit()),
|
||||
BlocProvider<SettingsCubit>(create: (_) => SettingsCubit()),
|
||||
BlocProvider<TicketListCubit>(create: (_) => TicketListCubit()),
|
||||
BlocProvider<OperationListCubit>(create: (_) => OperationListCubit()),
|
||||
BlocProvider<TrackingCubit>(create: (_) => TrackingCubit()),
|
||||
BlocProvider<NotesCubit>(create: (_) => NotesCubit()),
|
||||
BlocProvider<OperationListCubit>(
|
||||
create: (_) => sl<OperationListCubit>(),
|
||||
),
|
||||
BlocProvider<ProviderListCubit>(create: (_) => sl<ProviderListCubit>()),
|
||||
BlocProvider<SettingsCubit>(create: (_) => sl<SettingsCubit>()),
|
||||
BlocProvider<TicketListCubit>(create: (_) => sl<TicketListCubit>()),
|
||||
BlocProvider<TrackingCubit>(create: (_) => sl<TrackingCubit>()),
|
||||
BlocProvider<NotesCubit>(create: (_) => sl<NotesCubit>()),
|
||||
],
|
||||
child: const FluxApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setupLocator() async {
|
||||
final GetIt getIt = GetIt.instance;
|
||||
|
||||
getIt.registerSingleton<SharedPreferences>(
|
||||
await SharedPreferences.getInstance(),
|
||||
);
|
||||
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
anonKey: dotenv.env['SUPABASE_ANON_KEY'] ?? '',
|
||||
);
|
||||
//await Supabase.instance.client.auth.signOut();
|
||||
getIt.registerSingleton<SupabaseClient>(Supabase.instance.client);
|
||||
|
||||
// Settings
|
||||
getIt.registerLazySingleton<AppSettings>(() => AppSettings());
|
||||
|
||||
// Repositories
|
||||
getIt.registerLazySingleton<CoreRepository>(
|
||||
() => CoreRepository(),
|
||||
); // <-- NUOVO
|
||||
getIt.registerLazySingleton<StoreRepository>(() => StoreRepository());
|
||||
getIt.registerLazySingleton<CustomerRepository>(() => CustomerRepository());
|
||||
getIt.registerLazySingleton<ProductRepository>(() => ProductRepository());
|
||||
getIt.registerLazySingleton<StaffRepository>(() => StaffRepository());
|
||||
getIt.registerLazySingleton<OperationsRepository>(
|
||||
() => OperationsRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<ProviderRepository>(() => ProviderRepository());
|
||||
getIt.registerLazySingleton<AttachmentsRepository>(
|
||||
() => AttachmentsRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<TicketRepository>(() => TicketRepository());
|
||||
getIt.registerLazySingleton<DocumentSequenceRepository>(
|
||||
() => DocumentSequenceRepository(),
|
||||
);
|
||||
|
||||
// NOTA: CompanyRepository l'ho tolto perché la logica della Company
|
||||
// ora è gestita dal CoreRepository durante l'Onboarding.
|
||||
// Se ti serve per altro, rimettilo pure!
|
||||
|
||||
// Inizializziamo il SessionCubit (che prende CoreRepository e SharedPreferences)
|
||||
// Usiamo registerSingleton così viene creato subito e inizia ad ascoltare Supabase Auth.
|
||||
getIt.registerSingleton<SessionCubit>(
|
||||
SessionCubit(getIt<CoreRepository>(), getIt<SharedPreferences>()),
|
||||
);
|
||||
getIt.registerLazySingleton<CompanyRepository>(() => CompanyRepository());
|
||||
getIt.registerLazySingleton<TrackingRepository>(() => TrackingRepository());
|
||||
getIt.registerLazySingleton<TicketsShippingRepository>(
|
||||
() => TicketsShippingRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<NotesRepository>(() => NotesRepository());
|
||||
getIt.registerLazySingleton<TasksRepository>(() => TasksRepository());
|
||||
getIt.registerLazySingleton<SettingsRepository>(() => SettingsRepository());
|
||||
}
|
||||
|
||||
class FluxApp extends StatefulWidget {
|
||||
const FluxApp({super.key});
|
||||
|
||||
@@ -176,7 +106,7 @@ class _FluxAppState extends State<FluxApp> {
|
||||
super.initState();
|
||||
// Creiamo il router passandogli il Cubit per i redirect
|
||||
_router = AppRouter.createRouter(context.read<SessionCubit>());
|
||||
GetIt.I.get<SessionCubit>().setIsMobileDevice(isMobileDevice(context));
|
||||
sl<SessionCubit>().setIsMobileDevice(isMobileDevice(context));
|
||||
}
|
||||
|
||||
bool isMobileDevice(BuildContext context) {
|
||||
@@ -304,21 +234,69 @@ class GlobalUpdateChecker extends StatefulWidget {
|
||||
State<GlobalUpdateChecker> createState() => _GlobalUpdateCheckerState();
|
||||
}
|
||||
|
||||
class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker> {
|
||||
class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker>
|
||||
with WidgetsBindingObserver {
|
||||
bool _mustUpdate = false;
|
||||
String? _updateUrl;
|
||||
StreamSubscription? _versionSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_checkVersionAndBlock();
|
||||
// 🥷 1. Registriamo questo widget per ascoltare i cicli vitali dell'app
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_startRealtimeVersionCheck();
|
||||
}
|
||||
|
||||
Future<void> _checkVersionAndBlock() async {
|
||||
@override
|
||||
void dispose() {
|
||||
// 🥷 2. Rimuoviamo l'observer quando il widget muore (mai, in questo caso, ma è buona norma)
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_stopRealtimeVersionCheck();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// 🥷 3. IL VERO GESTORE DEL CICLO VITALE
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
super.didChangeAppLifecycleState(state);
|
||||
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
// L'app è tornata attiva: riaccendiamo il radar
|
||||
_startRealtimeVersionCheck();
|
||||
} else if (state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.hidden) {
|
||||
// L'app è andata in background: spegniamo il socket per evitare crash
|
||||
_stopRealtimeVersionCheck();
|
||||
}
|
||||
}
|
||||
|
||||
void _startRealtimeVersionCheck() {
|
||||
// Sicurezza: cancelliamo eventuali vecchi abbonamenti rimasti appesi
|
||||
_stopRealtimeVersionCheck();
|
||||
|
||||
// Facciamo un check immediato non appena rientriamo in app
|
||||
_checkVersion();
|
||||
|
||||
// Riapriamo il rubinetto di Supabase
|
||||
_versionSubscription = GetIt.I<SupabaseClient>()
|
||||
.from('app_config') // <-- Sostituisci col nome reale della tua tabella
|
||||
.stream(primaryKey: ['id'])
|
||||
.listen((_) {
|
||||
_checkVersion();
|
||||
});
|
||||
}
|
||||
|
||||
void _stopRealtimeVersionCheck() {
|
||||
// Chiudiamo gentilmente il socket
|
||||
_versionSubscription?.cancel();
|
||||
_versionSubscription = null;
|
||||
}
|
||||
|
||||
Future<void> _checkVersion() async {
|
||||
final updateUrl = await VersionCheckService().checkForceUpdate();
|
||||
|
||||
if (updateUrl != null && mounted) {
|
||||
// Invece di aprire un dialog, cambiamo lo stato e attiviamo lo "Scudo"
|
||||
setState(() {
|
||||
_mustUpdate = true;
|
||||
_updateUrl = updateUrl;
|
||||
@@ -328,21 +306,15 @@ class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 1. Se l'app è aggiornata, mostriamo solo l'app normale
|
||||
if (!_mustUpdate) return widget.child;
|
||||
|
||||
// 2. Se l'app è vecchia, sovrapponiamo il blocco con uno Stack
|
||||
return Stack(
|
||||
children: [
|
||||
// L'app sotto continua ad esistere, ma è inaccessibile
|
||||
widget.child,
|
||||
|
||||
// IL BLOCCO INVALICABILE SOPRA A TUTTO
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
color: Colors.black.withValues(alpha: 0.85), // Sfondo oscurante
|
||||
color: Colors.black.withValues(alpha: 0.85),
|
||||
child: Center(
|
||||
// Usiamo Material per ereditare correttamente temi, font e colori
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: Container(
|
||||
@@ -386,7 +358,7 @@ class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker> {
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
kIsWeb
|
||||
? "È stata rilasciata una nuova versione dell'applicazione. Ricarica la pagina per continuare."
|
||||
? "È stata rilasciata una nuova versione dell'applicazione. Ricarica la pagina per scaricare il nuovo codice."
|
||||
: "Per continuare ad utilizzare l'applicazione è necessario scaricare e installare l'ultimo aggiornamento.",
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
@@ -399,18 +371,14 @@ class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker> {
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
),
|
||||
onPressed: () async {
|
||||
// Trick cross-platform per fare il reload
|
||||
await launchUrl(
|
||||
Uri.parse(Uri.base.toString()),
|
||||
webOnlyWindowName: '_self',
|
||||
);
|
||||
onPressed: () {
|
||||
// Hard reload aggirando la cache!
|
||||
html.window.location.reload();
|
||||
},
|
||||
)
|
||||
else
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.download),
|
||||
|
||||
label: const Text("SCARICA AGGIORNAMENTO"),
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/data/core_repository.dart';
|
||||
import 'package:flux/core/theme/bloc/theme_bloc.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/features/auth/bloc/auth_cubit.dart';
|
||||
import 'package:flux/features/company/data/company_repository.dart';
|
||||
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
||||
import 'package:flux/features/customers/data/customer_repository.dart';
|
||||
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
|
||||
import 'package:flux/features/master_data/products/data/product_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/master_data/providers/data/provider_repository.dart';
|
||||
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||
import 'package:flux/features/master_data/store/data/store_repository.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/settings/blocs/settings_cubit.dart';
|
||||
import 'package:flux/features/settings/data/settings_repository.dart';
|
||||
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
|
||||
import 'package:flux/features/settings/ui/settings.dart';
|
||||
import 'package:flux/features/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tickets/data/tickets_shipping_repository.dart';
|
||||
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
||||
import 'package:flux/features/tracking/data/tracking_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
final sl = GetIt.instance;
|
||||
|
||||
Future<void> init() async {
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? '',
|
||||
);
|
||||
sl.registerSingleton<SupabaseClient>(Supabase.instance.client);
|
||||
sl.registerSingleton<SharedPreferences>(
|
||||
await SharedPreferences.getInstance(),
|
||||
);
|
||||
sl.registerLazySingleton<AppSettings>(() => AppSettings());
|
||||
|
||||
// Repositories
|
||||
sl.registerLazySingleton<CoreRepository>(() => CoreRepository());
|
||||
sl.registerLazySingleton<StoreRepository>(() => StoreRepository());
|
||||
sl.registerLazySingleton<CustomerRepository>(() => CustomerRepository());
|
||||
sl.registerLazySingleton<ProductRepository>(() => ProductRepository());
|
||||
sl.registerLazySingleton<StaffRepository>(() => StaffRepository());
|
||||
sl.registerLazySingleton<OperationsRepository>(() => OperationsRepository());
|
||||
sl.registerLazySingleton<ProviderRepository>(() => ProviderRepository());
|
||||
sl.registerLazySingleton<AttachmentsRepository>(
|
||||
() => AttachmentsRepository(),
|
||||
);
|
||||
sl.registerLazySingleton<CompanyRepository>(() => CompanyRepository());
|
||||
sl.registerLazySingleton<SettingsRepository>(() => SettingsRepository());
|
||||
sl.registerLazySingleton<TicketRepository>(() => TicketRepository());
|
||||
sl.registerLazySingleton<TicketsShippingRepository>(
|
||||
() => TicketsShippingRepository(),
|
||||
);
|
||||
sl.registerLazySingleton<TasksRepository>(() => TasksRepository());
|
||||
sl.registerLazySingleton<TrackingRepository>(() => TrackingRepository());
|
||||
sl.registerLazySingleton<NotesRepository>(() => NotesRepository());
|
||||
sl.registerLazySingleton<DocumentSequenceRepository>(
|
||||
() => DocumentSequenceRepository(),
|
||||
);
|
||||
|
||||
//Cubit globali
|
||||
sl.registerLazySingleton<SessionCubit>(
|
||||
() => SessionCubit(sl<CoreRepository>(), sl<SharedPreferences>()),
|
||||
);
|
||||
sl.registerLazySingleton<ThemeBloc>(() => ThemeBloc());
|
||||
sl.registerLazySingleton<StaffCubit>(() => StaffCubit());
|
||||
sl.registerLazySingleton<StoreCubit>(() => StoreCubit());
|
||||
sl.registerLazySingleton<ProviderListCubit>(() => ProviderListCubit());
|
||||
sl.registerLazySingleton<SettingsCubit>(() => SettingsCubit());
|
||||
sl.registerLazySingleton<AuthCubit>(() => AuthCubit());
|
||||
|
||||
//Cubit specifici
|
||||
sl.registerFactory<CustomersListCubit>(() => CustomersListCubit());
|
||||
sl.registerFactory<ProductsCubit>(() => ProductsCubit());
|
||||
sl.registerFactory<OperationListCubit>(() => OperationListCubit());
|
||||
sl.registerFactory<TicketListCubit>(() => TicketListCubit());
|
||||
sl.registerFactory<TrackingCubit>(() => TrackingCubit());
|
||||
sl.registerFactory<NotesCubit>(() => NotesCubit());
|
||||
}
|
||||
@@ -38,5 +38,8 @@ end
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.each do |target|
|
||||
flutter_additional_macos_build_settings(target)
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.15'
|
||||
end
|
||||
end
|
||||
end
|
||||
+135
-3
@@ -1,28 +1,160 @@
|
||||
PODS:
|
||||
- app_links (6.4.1):
|
||||
- FlutterMacOS
|
||||
- file_picker (0.0.1):
|
||||
- FlutterMacOS
|
||||
- file_selector_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
- Firebase/CoreOnly (12.15.0):
|
||||
- FirebaseCore (~> 12.15.0)
|
||||
- Firebase/Messaging (12.15.0):
|
||||
- Firebase/CoreOnly
|
||||
- FirebaseMessaging (~> 12.15.0)
|
||||
- firebase_core (4.11.0):
|
||||
- Firebase/CoreOnly (~> 12.15.0)
|
||||
- FlutterMacOS
|
||||
- firebase_messaging (16.4.1):
|
||||
- Firebase/CoreOnly (~> 12.15.0)
|
||||
- Firebase/Messaging (~> 12.15.0)
|
||||
- firebase_core
|
||||
- FlutterMacOS
|
||||
- FirebaseCore (12.15.0):
|
||||
- FirebaseCoreInternal (~> 12.15.0)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/Logger (~> 8.1)
|
||||
- FirebaseCoreInternal (12.15.0):
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- FirebaseInstallations (12.15.0):
|
||||
- FirebaseCore (~> 12.15.0)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/UserDefaults (~> 8.1)
|
||||
- PromisesObjC (~> 2.4)
|
||||
- FirebaseMessaging (12.15.0):
|
||||
- FirebaseCore (~> 12.15.0)
|
||||
- FirebaseInstallations (~> 12.15.0)
|
||||
- GoogleDataTransport (~> 10.1)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/Reachability (~> 8.1)
|
||||
- GoogleUtilities/UserDefaults (~> 8.1)
|
||||
- nanopb (~> 3.30910.0)
|
||||
- FlutterMacOS (1.0.0)
|
||||
- GoogleDataTransport (10.1.1):
|
||||
- nanopb (~> 3.30910.0)
|
||||
- PromisesObjC (~> 2.4)
|
||||
- GoogleUtilities/AppDelegateSwizzler (8.1.2):
|
||||
- GoogleUtilities/Environment
|
||||
- GoogleUtilities/Logger
|
||||
- GoogleUtilities/Network
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Environment (8.1.2):
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Logger (8.1.2):
|
||||
- GoogleUtilities/Environment
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Network (8.1.2):
|
||||
- GoogleUtilities/Logger
|
||||
- "GoogleUtilities/NSData+zlib"
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Reachability
|
||||
- "GoogleUtilities/NSData+zlib (8.1.2)":
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Privacy (8.1.2)
|
||||
- GoogleUtilities/Reachability (8.1.2):
|
||||
- GoogleUtilities/Logger
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/UserDefaults (8.1.2):
|
||||
- GoogleUtilities/Logger
|
||||
- GoogleUtilities/Privacy
|
||||
- nanopb (3.30910.0):
|
||||
- nanopb/decode (= 3.30910.0)
|
||||
- nanopb/encode (= 3.30910.0)
|
||||
- nanopb/decode (3.30910.0)
|
||||
- nanopb/encode (3.30910.0)
|
||||
- package_info_plus (0.0.1):
|
||||
- FlutterMacOS
|
||||
- pdfx (1.0.0):
|
||||
- FlutterMacOS
|
||||
- printing (1.0.0):
|
||||
- FlutterMacOS
|
||||
- PromisesObjC (2.4.1)
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- url_launcher_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
|
||||
DEPENDENCIES:
|
||||
- app_links (from `Flutter/ephemeral/.symlinks/plugins/app_links/macos`)
|
||||
- file_picker (from `Flutter/ephemeral/.symlinks/plugins/file_picker/macos`)
|
||||
- file_selector_macos (from `Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos`)
|
||||
- firebase_core (from `Flutter/ephemeral/.symlinks/plugins/firebase_core/macos`)
|
||||
- firebase_messaging (from `Flutter/ephemeral/.symlinks/plugins/firebase_messaging/macos`)
|
||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
|
||||
- pdfx (from `Flutter/ephemeral/.symlinks/plugins/pdfx/macos`)
|
||||
- printing (from `Flutter/ephemeral/.symlinks/plugins/printing/macos`)
|
||||
- shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- Firebase
|
||||
- FirebaseCore
|
||||
- FirebaseCoreInternal
|
||||
- FirebaseInstallations
|
||||
- FirebaseMessaging
|
||||
- GoogleDataTransport
|
||||
- GoogleUtilities
|
||||
- nanopb
|
||||
- PromisesObjC
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
app_links:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/app_links/macos
|
||||
file_picker:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/file_picker/macos
|
||||
file_selector_macos:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos
|
||||
firebase_core:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/firebase_core/macos
|
||||
firebase_messaging:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/firebase_messaging/macos
|
||||
FlutterMacOS:
|
||||
:path: Flutter/ephemeral
|
||||
package_info_plus:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos
|
||||
pdfx:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/pdfx/macos
|
||||
printing:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/printing/macos
|
||||
shared_preferences_foundation:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin
|
||||
url_launcher_macos:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
app_links: 05a6ec2341985eb05e9f97dc63f5837c39895c3f
|
||||
file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a
|
||||
file_selector_macos: 9e9e068e90ebee155097d00e89ae91edb2374db7
|
||||
Firebase: a8539b633d474fbeb654c7043f9c1649e274045b
|
||||
firebase_core: 4922bf7ac16c97fb67008a1a00842059b345b0d9
|
||||
firebase_messaging: 6c506190a7499e67e644957961f86efe1ac1c3e3
|
||||
FirebaseCore: 2e86a4ea1684d4381707069e4a6d89ac808e901e
|
||||
FirebaseCoreInternal: 6ab6a02c94446c026d2cf35cf5383842ebaa4992
|
||||
FirebaseInstallations: eb29ccbf64eaedf86fd5b2ccc7fabde567660b52
|
||||
FirebaseMessaging: 40017d7bc8457ee295b0f41d480a80fdabc9994e
|
||||
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
|
||||
GoogleDataTransport: a24e58982ab3ba2f64d79613e027fe7f57e88539
|
||||
GoogleUtilities: 766ace00c6b10d8148408f329d10c4f051931850
|
||||
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
|
||||
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
||||
pdfx: 1e79f57f7a6ce2f4a4c30f21fa54d3dc82441b51
|
||||
printing: c4cf83c78fd684f9bc318e6aadc18972aa48f617
|
||||
printing: 7916ffaaede65713863e621de9a4742d9fa723b9
|
||||
PromisesObjC: 752c3227f599e3467650e47ea36f433eeb10c273
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd
|
||||
|
||||
PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009
|
||||
PODFILE CHECKSUM: 180da7a1dbc1d932db021ebc8007656e7c46dd99
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
COCOAPODS: 1.17.0
|
||||
@@ -248,6 +248,7 @@
|
||||
33CC110E2044A8840003C045 /* Bundle Framework */,
|
||||
3399D490228B24CF009A79C7 /* ShellScript */,
|
||||
E13C7961A1538309550A7824 /* [CP] Embed Pods Frameworks */,
|
||||
AC0584CA1EFD6A4D37AEE7BD /* [CP] Copy Pods Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -397,6 +398,23 @@
|
||||
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
AC0584CA1EFD6A4D37AEE7BD /* [CP] Copy Pods Resources */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist",
|
||||
);
|
||||
name = "[CP] Copy Pods Resources";
|
||||
outputFileListPaths = (
|
||||
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
E13C7961A1538309550A7824 /* [CP] Embed Pods Frameworks */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "abseil-cpp-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/abseil-cpp-binary.git",
|
||||
"state" : {
|
||||
"revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5",
|
||||
"version" : "1.2024072200.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "app-check",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/app-check.git",
|
||||
"state" : {
|
||||
"revision" : "61b85103a1aeed8218f17c794687781505fbbef5",
|
||||
"version" : "11.2.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "firebase-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/firebase-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "8d5b4189f1f482df8d5c58c9985ea70491ef5382",
|
||||
"version" : "12.14.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "google-ads-on-device-conversion-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "9bfcc6cf435b2e7c5562c1900b8680c594fa9a64",
|
||||
"version" : "3.6.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleappmeasurement",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleAppMeasurement.git",
|
||||
"state" : {
|
||||
"revision" : "219e564a8510e983e675c94f77f7f7c50049f22d",
|
||||
"version" : "12.14.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googledatatransport",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleDataTransport.git",
|
||||
"state" : {
|
||||
"revision" : "617af071af9aa1d6a091d59a202910ac482128f9",
|
||||
"version" : "10.1.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleutilities",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleUtilities.git",
|
||||
"state" : {
|
||||
"revision" : "60da361632d0de02786f709bdc0c4df340f7613e",
|
||||
"version" : "8.1.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "grpc-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/grpc-binary.git",
|
||||
"state" : {
|
||||
"revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6",
|
||||
"version" : "1.69.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "gtm-session-fetcher",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/gtm-session-fetcher.git",
|
||||
"state" : {
|
||||
"revision" : "c0ac7575d70050c2973ba2318bd5af47f8e8153a",
|
||||
"version" : "5.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "interop-ios-for-google-sdks",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/interop-ios-for-google-sdks.git",
|
||||
"state" : {
|
||||
"revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",
|
||||
"version" : "101.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "leveldb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/leveldb.git",
|
||||
"state" : {
|
||||
"revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1",
|
||||
"version" : "1.22.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nanopb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/nanopb.git",
|
||||
"state" : {
|
||||
"revision" : "b7e1104502eca3a213b46303391ca4d3bc8ddec1",
|
||||
"version" : "2.30910.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "promises",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/promises.git",
|
||||
"state" : {
|
||||
"revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
|
||||
"version" : "2.4.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "abseil-cpp-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/abseil-cpp-binary.git",
|
||||
"state" : {
|
||||
"revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5",
|
||||
"version" : "1.2024072200.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "app-check",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/app-check.git",
|
||||
"state" : {
|
||||
"revision" : "61b85103a1aeed8218f17c794687781505fbbef5",
|
||||
"version" : "11.2.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "firebase-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/firebase-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "8d5b4189f1f482df8d5c58c9985ea70491ef5382",
|
||||
"version" : "12.14.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "google-ads-on-device-conversion-ios-sdk",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk",
|
||||
"state" : {
|
||||
"revision" : "9bfcc6cf435b2e7c5562c1900b8680c594fa9a64",
|
||||
"version" : "3.6.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleappmeasurement",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleAppMeasurement.git",
|
||||
"state" : {
|
||||
"revision" : "219e564a8510e983e675c94f77f7f7c50049f22d",
|
||||
"version" : "12.14.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googledatatransport",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleDataTransport.git",
|
||||
"state" : {
|
||||
"revision" : "617af071af9aa1d6a091d59a202910ac482128f9",
|
||||
"version" : "10.1.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "googleutilities",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/GoogleUtilities.git",
|
||||
"state" : {
|
||||
"revision" : "60da361632d0de02786f709bdc0c4df340f7613e",
|
||||
"version" : "8.1.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "grpc-binary",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/grpc-binary.git",
|
||||
"state" : {
|
||||
"revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6",
|
||||
"version" : "1.69.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "gtm-session-fetcher",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/gtm-session-fetcher.git",
|
||||
"state" : {
|
||||
"revision" : "c0ac7575d70050c2973ba2318bd5af47f8e8153a",
|
||||
"version" : "5.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "interop-ios-for-google-sdks",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/interop-ios-for-google-sdks.git",
|
||||
"state" : {
|
||||
"revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",
|
||||
"version" : "101.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "leveldb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/leveldb.git",
|
||||
"state" : {
|
||||
"revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1",
|
||||
"version" : "1.22.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nanopb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/firebase/nanopb.git",
|
||||
"state" : {
|
||||
"revision" : "b7e1104502eca3a213b46303391ca4d3bc8ddec1",
|
||||
"version" : "2.30910.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "promises",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/google/promises.git",
|
||||
"state" : {
|
||||
"revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
|
||||
"version" : "2.4.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
+120
-80
@@ -5,18 +5,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: _flutterfire_internals
|
||||
sha256: "8f89e371e2883de35cdc78f648e725fa4da5f3b6c927269f00fa68f1ea92b598"
|
||||
sha256: "78f98c1f9c4dbbd22c2bb7b7f17c4a5c06150e8b2cb791a0947979ad0d3dabd5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.71"
|
||||
version: "1.3.73"
|
||||
app_links:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: app_links
|
||||
sha256: "3462d9defc61565fde4944858b59bec5be2b9d5b05f20aed190adb3ad08a7abc"
|
||||
sha256: f8db46d2ea9ff6f3a37191a7fd5b7813da1253ace8c32c1b9eadace41d1188ea
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.0"
|
||||
version: "7.2.1"
|
||||
app_links_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -29,10 +29,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: app_links_platform_interface
|
||||
sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f"
|
||||
sha256: "7546f09a6e93f4a2df2fe2bd40a5c6c64310ac461b036d82b43033be7a59f809"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
version: "2.0.4"
|
||||
app_links_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -105,6 +105,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.1"
|
||||
charcode:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: charcode
|
||||
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
checked_yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -133,10 +141,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: code_assets
|
||||
sha256: dad6bf6b9f4f378b0a69edbf42584d336efd1a9ce15deb1ba591cbb1b5ff440f
|
||||
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
version: "1.2.1"
|
||||
collection:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -157,10 +165,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cross_file
|
||||
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
|
||||
sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.5+2"
|
||||
version: "0.3.5+4"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -169,6 +177,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.7"
|
||||
csslib:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: csslib
|
||||
sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.2"
|
||||
dart_jsonwebtoken:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -181,18 +197,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dbus
|
||||
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
|
||||
sha256: "792974a4007974fbc5c1b5433eb2330a9db3e368c3f906253af4c007d0f49a91"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.12"
|
||||
version: "0.7.13"
|
||||
equatable:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: equatable
|
||||
sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b"
|
||||
sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.8"
|
||||
version: "2.1.0"
|
||||
extension:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -269,50 +285,50 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: firebase_core
|
||||
sha256: "93a5bde9775fd5adcc937f39dfa04ae0bc89c4d79bea6abc49de3f7b049d9ff6"
|
||||
sha256: d2625088d8f8836a7a74a7eb94a5372d70ad88382602ba2dcc02805c294d0d16
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.9.0"
|
||||
version: "4.11.0"
|
||||
firebase_core_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_core_platform_interface
|
||||
sha256: "4a120366dbf7d5a8ee9438978530b664b855728fb8dcc3a201017660817e555b"
|
||||
sha256: "913e7c96ef83a80ad7e1c3f8a059167b3de23b5d5e07fa3ed8f11abe24de98b6"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
version: "7.1.0"
|
||||
firebase_core_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_core_web
|
||||
sha256: "7c98f10b8c8e5adedc0b810b66a877120696675e2c22d9ca9caca092da0d9e57"
|
||||
sha256: "30ba3ae56f5beb2cea836033201570612c911661889f815eca73b6056c7b55bf"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.7.0"
|
||||
version: "3.9.0"
|
||||
firebase_messaging:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: firebase_messaging
|
||||
sha256: "8d0dc81a31cd030170508dc3e89bfd14355b20a1b991340af5f018e37daab5d7"
|
||||
sha256: ce21a510e5a9aed67a0404476981e19ec0361a0301eeba547dc93dc2e7dec99a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "16.2.2"
|
||||
version: "16.4.1"
|
||||
firebase_messaging_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_messaging_platform_interface
|
||||
sha256: "37abb0b0535c5497605ee94c12470e1ebbbe47e71a22d0c20bffcc912311f8cb"
|
||||
sha256: e10f6d521e7ed663d0ea2f4ec7de4c6729f8c2ce25d32faf6d6b4219da8515c2
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.7.11"
|
||||
version: "4.9.0"
|
||||
firebase_messaging_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_messaging_web
|
||||
sha256: "54e22b43e2c26a2728a3f68c188de0f9011993ae19ae959a06d476dad935c776"
|
||||
sha256: "7ab45dfaf8efcd1a769baa9b8debbd0da281f5d3fc07274296b564396a980292"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.7"
|
||||
version: "4.2.1"
|
||||
fixnum:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -367,10 +383,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_plugin_android_lifecycle
|
||||
sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0"
|
||||
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.34"
|
||||
version: "2.0.35"
|
||||
flutter_staggered_grid_view:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -409,10 +425,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: functions_client
|
||||
sha256: "94074d62167ae634127ef6095f536835063a7dc80f2b1aa306d2346ff9023996"
|
||||
sha256: e9685e9ab852a8b8e0579c867f6c9155da27317b294b3df796a536b8b8e0d253
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.0"
|
||||
version: "2.6.4"
|
||||
get_it:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -425,10 +441,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: go_router
|
||||
sha256: "92d8cee7c57dff0a6c409c05597b460002434eccf7424a712283225b3962d03f"
|
||||
sha256: "5922b2861e2235a3504896f0d6fa07d84141b480cf52eecd2f42cd25585a9e8a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "17.2.3"
|
||||
version: "17.3.0"
|
||||
google_fonts:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -441,10 +457,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: gotrue
|
||||
sha256: "7a4172601553e61716f5c3dd243aa3297e13308e07eb85b7853c941ba585dcf5"
|
||||
sha256: "360bba9606e58d5acc59a033ab64ae3cf571a6868f7a7267cb8e9a204b7bf1b2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.20.0"
|
||||
version: "2.26.0"
|
||||
gtk:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -457,10 +473,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: hooks
|
||||
sha256: a41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31
|
||||
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "2.0.2"
|
||||
html:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: html
|
||||
sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.15.6"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -481,26 +505,26 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: image
|
||||
sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce
|
||||
sha256: "6300175e00616bbc832e2fc91bfa4d776af5402c81c7151bee6905bb08473c52"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.8.0"
|
||||
version: "4.9.1"
|
||||
image_picker:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: image_picker
|
||||
sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac"
|
||||
sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.2"
|
||||
version: "1.2.3"
|
||||
image_picker_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: image_picker_android
|
||||
sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f
|
||||
sha256: "6f3a1995eafb000333174fae92202622033b0ee7fd917a6cd3730295264df84a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.8.13+17"
|
||||
version: "0.8.13+19"
|
||||
image_picker_for_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -709,6 +733,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.1"
|
||||
passkeys_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: passkeys_platform_interface
|
||||
sha256: "9610bd136b3382500390912ddd8517ee99505228b1af7b507b9c907f7e99a47d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.8.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -729,10 +761,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider
|
||||
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
|
||||
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.5"
|
||||
version: "2.1.6"
|
||||
path_provider_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -753,18 +785,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_linux
|
||||
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
|
||||
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.1"
|
||||
version: "2.2.2"
|
||||
path_provider_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_platform_interface
|
||||
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
|
||||
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
version: "2.1.3"
|
||||
path_provider_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -777,10 +809,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: pdf
|
||||
sha256: e47a275b267873d5944ad5f5ff0dcc7ac2e36c02b3046a0ffac9b72fd362c44b
|
||||
sha256: "517df47af468734a23c8b513c0c6a8a62357403ab1b8ab7fad1606576a9dbdd0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.12.0"
|
||||
version: "3.13.0"
|
||||
pdf_widget_wrapper:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -802,10 +834,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: permission_handler
|
||||
sha256: bc917da36261b00137bbc8896bf1482169cd76f866282368948f032c8c1caae1
|
||||
sha256: fe54465bcc62a4564c6e4db337bbaded6c0c0fa6e10487414436d163114784f6
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "12.0.1"
|
||||
version: "12.0.3"
|
||||
permission_handler_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -818,10 +850,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: permission_handler_apple
|
||||
sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023
|
||||
sha256: "79dfa1df734798aa3cfdad166d3a3698c206d8813de13516ea1071b5d7e2f420"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "9.4.7"
|
||||
version: "9.4.10"
|
||||
permission_handler_html:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -898,18 +930,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: postgrest
|
||||
sha256: "9d61b3d4a88fcf9424d400127c54d49ed1b56ec30838fc0a33a64f31d4e694cc"
|
||||
sha256: "10e3f195e131eec944fa872644aed89b33b5be998f3fc77c87325db3927bc646"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
version: "2.8.0"
|
||||
printing:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: printing
|
||||
sha256: "689170c9ddb1bda85826466ba80378aa8993486d3c959a71cd7d2d80cb606692"
|
||||
sha256: f6cd14c768c1352dd37a958a3ee351aa9ce305b398218d3acd86389d5f7ecad1
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.14.3"
|
||||
version: "5.15.0"
|
||||
provider:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -946,10 +978,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: realtime_client
|
||||
sha256: "7dfccf372d2f55aacfeefb6186f65a06f3ffae383fe042dbeef9d85d33487576"
|
||||
sha256: "0cfbe0047e2591eba348938e9b4e620d5b1a8df6c374757e8eb8645252b8387f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.3"
|
||||
version: "2.11.0"
|
||||
record_use:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -986,10 +1018,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_android
|
||||
sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53
|
||||
sha256: "93ae5884a9df5d3bb696825bceb3a17590754548b5d740eba51500afc8d088f5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.23"
|
||||
version: "2.4.26"
|
||||
shared_preferences_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1055,10 +1087,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: storage_client
|
||||
sha256: "4801e8ca219a35e51cbb30589aba5306667ae8935b792504595a45273cef0b18"
|
||||
sha256: "221263cfbe0c01575b7d7fe7543e44abff380eb4d38d936372844a1caa85ba12"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.2"
|
||||
version: "2.6.0"
|
||||
stream_channel:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1079,26 +1111,26 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: supabase
|
||||
sha256: "40e5a8833c8834e140ef53b60a6181849667eba9ca125acb7f8e24c6a769d418"
|
||||
sha256: "3879996256325fcc9abb03b62b12c07e4eaae2e008e1bf043cc1525184159a43"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.10.6"
|
||||
version: "2.14.0"
|
||||
supabase_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: supabase_flutter
|
||||
sha256: c02ce58abcaf86cb8055ad40bfd98bbf5b93fed3b5b56b8220d88ed03842818b
|
||||
sha256: c9916c1cd512ebf3107ec0f83c9dca13d2e1e789629c2a5df896586bff46ce5f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.12.4"
|
||||
version: "2.16.0"
|
||||
synchronized:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: synchronized
|
||||
sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5"
|
||||
sha256: "93b153dcb6a26dcddee6ca087dd634b53e38c10b5aa163e8e49501a776456153"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.4.0+1"
|
||||
version: "3.4.1"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1131,6 +1163,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
universal_html:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: universal_html
|
||||
sha256: c0bcae5c733c60f26c7dfc88b10b0fd27cbcc45cb7492311cdaa6067e21c9cd4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
universal_io:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -1159,10 +1199,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_android
|
||||
sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c"
|
||||
sha256: b413d49b73867ac08dd2f9890efd3cc11f2a0e577618d50843440a1fb3776c32
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.3.30"
|
||||
version: "6.3.32"
|
||||
url_launcher_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1239,10 +1279,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_graphics_compiler
|
||||
sha256: b9b3f391857781aa96acacef96066f2f49b4cd03cf9fce3ca4d8da2ef5ea129e
|
||||
sha256: "142a9146f447d15b10bdc00e21d5f4d83e5b32bb5f8f8f5a04c75311344923a3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.3"
|
||||
version: "1.2.6"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1303,10 +1343,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xml
|
||||
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
|
||||
sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.6.1"
|
||||
version: "7.0.1"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1319,10 +1359,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yet_another_json_isolate
|
||||
sha256: fe45897501fa156ccefbfb9359c9462ce5dec092f05e8a56109db30be864f01e
|
||||
sha256: eaa26beb5990b25a49d942374fd5a0c5aa67a837e03b14b4c26134aaa1ed01a9
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
version: "2.1.1"
|
||||
sdks:
|
||||
dart: ">=3.11.3 <4.0.0"
|
||||
flutter: ">=3.38.4"
|
||||
dart: ">=3.12.0 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
+4
-1
@@ -1,7 +1,7 @@
|
||||
name: flux
|
||||
description: "Gestione attività negozio di telefonia"
|
||||
publish_to: 'none'
|
||||
version: 1.1.14+32
|
||||
version: 1.3.4+50
|
||||
|
||||
environment:
|
||||
sdk: ^3.11.3
|
||||
@@ -41,6 +41,7 @@ dependencies:
|
||||
flutter_staggered_grid_view: ^0.7.0
|
||||
firebase_core: ^4.9.0
|
||||
firebase_messaging: ^16.2.2
|
||||
universal_html: ^2.3.0
|
||||
|
||||
dependency_overrides:
|
||||
pdfx:
|
||||
@@ -55,6 +56,8 @@ dev_dependencies:
|
||||
flutter_lints: ^6.0.0
|
||||
|
||||
flutter:
|
||||
config:
|
||||
enable-swift-package-manager: false
|
||||
uses-material-design: true
|
||||
generate: true
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apiKey, content-type',
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
|
||||
try {
|
||||
const payload = await req.json()
|
||||
const { table, type, record } = payload
|
||||
|
||||
// 🥷 1. FILTRO EVENTI: Agiamo solo sui nuovi allegati
|
||||
if (table !== 'attachments' || type !== 'INSERT') {
|
||||
return new Response(JSON.stringify({ message: "Ignorato: non è un INSERT su attachments." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// Se l'allegato ha GIÀ un customer_id, l'operatore l'ha caricato direttamente
|
||||
// dalla scheda cliente. Non serve sprecare soldi con l'AI.
|
||||
if (record.customer_id) {
|
||||
return new Response(JSON.stringify({ message: "Customer già presente, analisi saltata." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// Se non è collegato a un ticket, a un'operazione o a una nota, non abbiamo
|
||||
// modo di risalire al proprietario, quindi fermiamo tutto.
|
||||
if (!record.operation_id && !record.ticket_id && !record.note_id) {
|
||||
return new Response(JSON.stringify({ message: "Nessuna entità collegata da cui estrarre il customer." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// 🥷 2. FILTRO FORMATI: Passiamo a OpenAI solo immagini vere (niente zip o pdf per ora)
|
||||
// Nota: OpenAI supporta anche i PDF in vision, ma le immagini sono più sicure/economiche per i documenti.
|
||||
const validExtensions = ['jpg', 'jpeg', 'png', 'webp']
|
||||
const ext = record.extension?.replace('.', '').toLowerCase()
|
||||
|
||||
if (!validExtensions.includes(ext)) {
|
||||
return new Response(JSON.stringify({ message: "Formato non supportato da Vision." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
)
|
||||
|
||||
// 🥷 3. GENERAZIONE URL SICURO
|
||||
// Dal momento che il tuo storage bucket è (spero) privato, dobbiamo creare un URL
|
||||
// temporaneo firmato da passare a OpenAI, valido solo per i prossimi 60 secondi.
|
||||
const { data: urlData, error: urlError } = await supabase.storage
|
||||
.from('documents')
|
||||
.createSignedUrl(record.storage_path, 60)
|
||||
|
||||
if (urlError || !urlData) throw new Error(`Errore generazione URL: ${urlError?.message}`)
|
||||
|
||||
const imageUrl = urlData.signedUrl
|
||||
|
||||
// 🥷 4. L'INTERROGAZIONE ALL'AI (Il cuore del sistema)
|
||||
console.log(`Analizzo immagine ${record.id} con OpenAI...`)
|
||||
|
||||
const openAiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${Deno.env.get('OPENAI_API_KEY')}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "gpt-4o-mini", // Il modello super veloce ed economico
|
||||
response_format: { type: "json_object" }, // Vogliamo solo codice, niente chiacchiere
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Questa immagine è una foto o una scansione di un documento d'identità personale valido (es. carta d'identità, patente di guida, passaporto, tessera sanitaria, codice fiscale)? Rispondi ESCLUSIVAMENTE con un JSON in questo formato: { \"is_id\": true } oppure { \"is_id\": false }"
|
||||
},
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: { "url": imageUrl }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
const aiData = await openAiResponse.json()
|
||||
const resultText = aiData.choices[0].message.content
|
||||
const result = JSON.parse(resultText)
|
||||
|
||||
// 🥷 5. LA LOGICA DI SMISTAMENTO
|
||||
if (result.is_id === true) {
|
||||
console.log(`🎯 Documento rilevato! Cerco il padrone...`)
|
||||
|
||||
let targetCustomerId = null
|
||||
|
||||
// Andiamo a pescare il customer_id esplorando l'albero delle relazioni
|
||||
if (record.operation_id) {
|
||||
const { data } = await supabase.from('operations').select('customer_id').eq('id', record.operation_id).single()
|
||||
targetCustomerId = data?.customer_id
|
||||
} else if (record.ticket_id) {
|
||||
const { data } = await supabase.from('tickets').select('customer_id').eq('id', record.ticket_id).single()
|
||||
targetCustomerId = data?.customer_id
|
||||
} else if (record.note_id) {
|
||||
// Se le note hanno una FK verso i clienti:
|
||||
const { data } = await supabase.from('notes').select('customer_id').eq('id', record.note_id).single()
|
||||
targetCustomerId = data?.customer_id
|
||||
}
|
||||
|
||||
// Se abbiamo trovato il proprietario, facciamo l'update dell'allegato!
|
||||
if (targetCustomerId) {
|
||||
await supabase
|
||||
.from('attachments')
|
||||
.update({ customer_id: targetCustomerId })
|
||||
.eq('id', record.id)
|
||||
|
||||
console.log(`✅ Allegato aggiornato. Legato al cliente: ${targetCustomerId}`)
|
||||
} else {
|
||||
console.log(`⚠️ Documento rilevato, ma non c'è nessun cliente legato all'entità genitore.`)
|
||||
}
|
||||
} else {
|
||||
console.log(`L'immagine non è un documento (è uno scontrino, una foto di un router, ecc.).`)
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true, is_id: result.is_id }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error("ERRORE FATALE NELLA FUNZIONE:", error)
|
||||
return new Response(JSON.stringify({ error: error.toString() }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -11,173 +11,186 @@ serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
|
||||
try {
|
||||
const bodyText = await req.text();
|
||||
const payload = JSON.parse(bodyText);
|
||||
const bodyText = await req.text()
|
||||
const payload = JSON.parse(bodyText)
|
||||
|
||||
// Estraggo i dati dal payload standard di Supabase
|
||||
const tableName = payload.table;
|
||||
const record = payload.record;
|
||||
const tableName = payload.table
|
||||
const eventType = payload.type
|
||||
const record = payload.record
|
||||
const old_record = payload.old_record
|
||||
|
||||
if (!tableName || !record) {
|
||||
throw new Error("Payload non valido, manca table o record.");
|
||||
throw new Error("Payload non valido, manca table o record.")
|
||||
}
|
||||
|
||||
let event_type = '';
|
||||
let target_staff_id = '';
|
||||
let title = '';
|
||||
let description = '';
|
||||
let reference_id = '';
|
||||
|
||||
// Inizializziamo il client Supabase subito, ci serve per le query
|
||||
const supabaseClient = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
)
|
||||
|
||||
// SMISTAMENTO IN BASE ALLA TABELLA
|
||||
if (tableName === 'task_assignments') {
|
||||
event_type = 'task_assigned';
|
||||
target_staff_id = record.staff_id;
|
||||
reference_id = record.task_id;
|
||||
title = 'Nuovo Task Assegnato';
|
||||
|
||||
// 1. Peschiamo i dettagli completi del task
|
||||
const { data: taskData } = await supabaseClient
|
||||
.from('tasks')
|
||||
.select('*')
|
||||
.eq('id', reference_id)
|
||||
.single();
|
||||
|
||||
// 2. Peschiamo il nome del creatore
|
||||
let creatorName = "Admin";
|
||||
if (taskData?.created_by_id) {
|
||||
const { data: creatorData } = await supabaseClient
|
||||
.from('staff_members')
|
||||
.select('first_name, last_name')
|
||||
.eq('id', taskData.created_by_id)
|
||||
.single();
|
||||
|
||||
if (creatorData) {
|
||||
creatorName = `${creatorData.first_name} ${creatorData.last_name}`.trim();
|
||||
}
|
||||
// =========================================================================
|
||||
// 🥷 1. IDENTIFICARE ESTRARRE I BERSAGLI (CHI DEVO NOTIFICARE?)
|
||||
// =========================================================================
|
||||
let usersToNotify: string[] = []
|
||||
let notificationTitle = ''
|
||||
let notificationBody = ''
|
||||
let referenceId = ''
|
||||
let fluxEventType = '' // 'task_assigned', 'task_completed', etc.
|
||||
|
||||
// SCENARIO A: ASSEGNAZIONE TASK
|
||||
if (tableName === 'task_assignments' && eventType === 'INSERT') {
|
||||
const assigneeId = record.staff_id
|
||||
const assignerId = record.assigned_by_id
|
||||
referenceId = record.task_id
|
||||
fluxEventType = 'task_assigned'
|
||||
|
||||
if (assigneeId === assignerId) {
|
||||
return new Response(JSON.stringify({ message: "Auto-assegnazione ignorata." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// 3. Formattiamo la data (se esiste)
|
||||
let dueDateStr = 'Nessuna scadenza';
|
||||
usersToNotify.push(assigneeId)
|
||||
|
||||
// Costruiamo i testi
|
||||
const { data: taskData } = await supabaseClient.from('tasks').select('title, description, due_date').eq('id', referenceId).single()
|
||||
const { data: assignerData } = await supabaseClient.from('staff_members').select('first_name, last_name').eq('id', assignerId).single()
|
||||
|
||||
const taskTitle = taskData?.title || 'Senza titolo'
|
||||
const taskDesc = taskData?.description || 'Nessuna descrizione'
|
||||
const assignerName = assignerData ? `${assignerData.first_name} ${assignerData.last_name}`.trim() : 'Un collega'
|
||||
|
||||
let dueDateStr = 'Nessuna scadenza'
|
||||
if (taskData?.due_date) {
|
||||
const d = new Date(taskData.due_date);
|
||||
dueDateStr = d.toLocaleDateString('it-IT');
|
||||
dueDateStr = new Date(taskData.due_date).toLocaleDateString('it-IT')
|
||||
}
|
||||
|
||||
// 4. Costruiamo il Body multilinea per Android
|
||||
const taskTitle = taskData?.title || 'Senza titolo';
|
||||
const taskDesc = taskData?.description || 'Nessuna descrizione fornita.';
|
||||
notificationTitle = 'Nuovo Task Assegnato'
|
||||
notificationBody = `${taskTitle}\n\nCreato da: ${assignerName}\nScadenza: ${dueDateStr}\nDettagli: ${taskDesc}`
|
||||
}
|
||||
|
||||
// SCENARIO B: COMPLETAMENTO TASK
|
||||
else if (tableName === 'tasks' && eventType === 'UPDATE') {
|
||||
const justCompleted = record.status === 'completed' && old_record.status !== 'completed';
|
||||
|
||||
description = `${taskTitle}\n\nCreato da: ${creatorName}\nScadenza: ${dueDateStr}\nDettagli: ${taskDesc}`;
|
||||
}
|
||||
if (!justCompleted) {
|
||||
return new Response(JSON.stringify({ message: "Update ignorato (non è un completamento)." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// 1. Leggiamo le preferenze specifiche di questo dipendente
|
||||
const { data: settings, error: settingsError } = await supabaseClient
|
||||
.from('staff_notification_settings')
|
||||
.select('*')
|
||||
.eq('staff_id', target_staff_id)
|
||||
.single()
|
||||
const completerId = record.updated_by_id
|
||||
referenceId = record.id
|
||||
fluxEventType = 'task_completed' // Nota: assicurati di avere questa colonna o un fallback nelle preferenze
|
||||
|
||||
if (settingsError || !settings) throw new Error('Preferenze utente non trovate')
|
||||
|
||||
// 2. Determiniamo QUALI canali usare in base all'evento e agli switch dell'utente
|
||||
let sendPush = false
|
||||
let sendEmail = false
|
||||
|
||||
switch (event_type) {
|
||||
case 'task_assigned':
|
||||
sendPush = settings.task_assigned_push
|
||||
sendEmail = settings.task_assigned_email
|
||||
break
|
||||
case 'note_invited':
|
||||
sendPush = settings.note_invited_push
|
||||
sendEmail = settings.note_invited_email
|
||||
break
|
||||
case 'new_operation':
|
||||
sendPush = settings.new_operation_push
|
||||
sendEmail = settings.new_operation_email
|
||||
break
|
||||
case 'new_ticket':
|
||||
sendPush = settings.new_ticket_push
|
||||
sendEmail = settings.new_ticket_email
|
||||
break
|
||||
default:
|
||||
throw new Error('Tipo evento non riconosciuto')
|
||||
}
|
||||
|
||||
// Se l'utente ha spento tutto, interrompiamo subito risparmiando risorse
|
||||
if (!sendPush && !sendEmail) {
|
||||
return new Response(JSON.stringify({ message: 'L\'utente ha disattivato le notifiche per questo evento.' }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200
|
||||
})
|
||||
}
|
||||
|
||||
// Se arriviamo qui, dobbiamo inviare qualcosa. Prepariamo i dati dell'utente.
|
||||
const { data: staffMember } = await supabaseClient
|
||||
.from('staff_members')
|
||||
.select('email, first_name')
|
||||
.eq('id', target_staff_id)
|
||||
.single()
|
||||
|
||||
// 3. LOGICA PUSH (FCM)
|
||||
if (sendPush) {
|
||||
const firebaseSecret = Deno.env.get('FIREBASE_SERVICE_ACCOUNT');
|
||||
const { data: assignments } = await supabaseClient.from('task_assignments').select('staff_id').eq('task_id', referenceId)
|
||||
|
||||
if (!firebaseSecret) {
|
||||
console.error("ERRORE: Secret FIREBASE_SERVICE_ACCOUNT mancante nel progetto!");
|
||||
} else {
|
||||
const credentials = JSON.parse(firebaseSecret);
|
||||
const jwtClient = new JWT({
|
||||
email: credentials.client_email,
|
||||
key: credentials.private_key,
|
||||
scopes: ['https://www.googleapis.com/auth/firebase.messaging'],
|
||||
});
|
||||
const fcmAccessToken = (await jwtClient.getAccessToken()).token;
|
||||
if (assignments && assignments.length > 0) {
|
||||
usersToNotify = assignments.map(a => a.staff_id).filter(id => id !== completerId)
|
||||
}
|
||||
|
||||
const { data: devices } = await supabaseClient
|
||||
.from('staff_devices')
|
||||
.select('fcm_token')
|
||||
.eq('staff_id', target_staff_id);
|
||||
if (usersToNotify.length === 0) {
|
||||
return new Response(JSON.stringify({ message: "Nessun altro assegnatario da notificare per la chiusura." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
if (devices && devices.length > 0) {
|
||||
const { data: completerData } = await supabaseClient.from('staff_members').select('first_name, last_name').eq('id', completerId).single()
|
||||
const completerName = completerData ? `${completerData.first_name} ${completerData.last_name}`.trim() : 'Un collega'
|
||||
const taskTitle = record.title || 'Senza titolo'
|
||||
|
||||
notificationTitle = 'Task Completato ✅'
|
||||
notificationBody = `${completerName} ha appena chiuso il task: ${taskTitle}`
|
||||
}
|
||||
|
||||
// SCENARIO C: ALTRI EVENTI (Es. note_invited, ecc. Mettili qui quando ti serviranno)
|
||||
else {
|
||||
return new Response(JSON.stringify({ message: "Tabella o evento non gestito." }), { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// 🥷 2. MOTORE DI INVIO MASSIVO PER I BERSAGLI IDENTIFICATI
|
||||
// =========================================================================
|
||||
|
||||
// Inizializziamo FCM una volta sola per risparmiare tempo se ci sono push da mandare
|
||||
const firebaseSecret = Deno.env.get('FIREBASE_SERVICE_ACCOUNT')
|
||||
let fcmAccessToken = ''
|
||||
let fcmProjectId = ''
|
||||
|
||||
if (firebaseSecret) {
|
||||
const credentials = JSON.parse(firebaseSecret)
|
||||
fcmProjectId = credentials.project_id
|
||||
const jwtClient = new JWT({
|
||||
email: credentials.client_email,
|
||||
key: credentials.private_key,
|
||||
scopes: ['https://www.googleapis.com/auth/firebase.messaging'],
|
||||
})
|
||||
fcmAccessToken = (await jwtClient.getAccessToken()).token ?? ''
|
||||
}
|
||||
|
||||
const resendApiKey = Deno.env.get('RESEND_API_KEY')
|
||||
|
||||
let pushSentCount = 0;
|
||||
let emailSentCount = 0;
|
||||
|
||||
// Cicliamo tutti gli utenti che meritano la notifica
|
||||
for (const targetStaffId of usersToNotify) {
|
||||
|
||||
// A) Leggiamo le preferenze dello specifico utente
|
||||
const { data: settings } = await supabaseClient
|
||||
.from('staff_notification_settings')
|
||||
.select('*')
|
||||
.eq('staff_id', targetStaffId)
|
||||
.single()
|
||||
|
||||
if (!settings) continue; // Salta se non ha le preferenze
|
||||
|
||||
let sendPush = false
|
||||
let sendEmail = false
|
||||
|
||||
// B) Traduciamo l'evento nelle sue preferenze
|
||||
// (Se aggiungi 'task_completed' al DB settings, mettilo qui. Per ora riuso le preesistenti se manca)
|
||||
switch (fluxEventType) {
|
||||
case 'task_assigned':
|
||||
sendPush = settings.task_assigned_push
|
||||
sendEmail = settings.task_assigned_email
|
||||
break
|
||||
case 'task_completed':
|
||||
// Se nel DB hai aggiunto task_completed_push usa quello.
|
||||
// Altrimenti puoi fare fallback su task_assigned_push per testare.
|
||||
sendPush = settings.task_assigned_push
|
||||
sendEmail = settings.task_assigned_email
|
||||
break
|
||||
// Aggiungi qui gli altri case (note_invited, new_operation)
|
||||
}
|
||||
|
||||
if (!sendPush && !sendEmail) continue; // Questo utente non vuole essere disturbato
|
||||
|
||||
// Recuperiamo nome ed email per questo specifico utente
|
||||
const { data: staffMember } = await supabaseClient.from('staff_members').select('email, first_name').eq('id', targetStaffId).single()
|
||||
|
||||
// C) INVIO PUSH (FCM)
|
||||
if (sendPush && fcmAccessToken) {
|
||||
const { data: devices } = await supabaseClient.from('staff_devices').select('fcm_token').eq('staff_id', targetStaffId)
|
||||
|
||||
if (devices) {
|
||||
for (const device of devices) {
|
||||
try {
|
||||
const res = await fetch(`https://fcm.googleapis.com/v1/projects/${credentials.project_id}/messages:send`, {
|
||||
const res = await fetch(`https://fcm.googleapis.com/v1/projects/${fcmProjectId}/messages:send`, {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${fcmAccessToken}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: {
|
||||
token: device.fcm_token,
|
||||
notification: { title, body: description },
|
||||
data: { click_action: 'FLUTTER_NOTIFICATION_CLICK', eventType: event_type, referenceId: reference_id },
|
||||
notification: { title: notificationTitle, body: notificationBody },
|
||||
data: { click_action: 'FLUTTER_NOTIFICATION_CLICK', eventType: fluxEventType, referenceId: referenceId },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
// QUI È DOVE CATTURIAMO LA RISPOSTA DI GOOGLE
|
||||
const fcmResponseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
console.error("FCM HA RIFIUTATO LA NOTIFICA:", fcmResponseData);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error('Errore di rete durante invio Push:', err);
|
||||
}
|
||||
if (res.ok) pushSentCount++;
|
||||
else console.error("FCM HA RIFIUTATO LA NOTIFICA:", await res.json());
|
||||
} catch (err) { console.error('Errore rete FCM:', err) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. LOGICA EMAIL (Resend)
|
||||
if (sendEmail && staffMember?.email) {
|
||||
const resendApiKey = Deno.env.get('RESEND_API_KEY')
|
||||
if (resendApiKey) {
|
||||
// D) INVIO EMAIL (Resend)
|
||||
if (sendEmail && resendApiKey && staffMember?.email) {
|
||||
try {
|
||||
await fetch('https://api.resend.com/emails', {
|
||||
method: 'POST',
|
||||
@@ -185,20 +198,24 @@ serve(async (req) => {
|
||||
body: JSON.stringify({
|
||||
from: 'FLUX Notifiche <onboarding@resend.dev>',
|
||||
to: staffMember.email,
|
||||
subject: title,
|
||||
html: `<p>Ciao ${staffMember.first_name},</p><p>${description}</p><p><br>Il team FLUX</p>`,
|
||||
subject: notificationTitle,
|
||||
html: `<p>Ciao ${staffMember.first_name},</p><p>${notificationBody.replace(/\n/g, '<br>')}</p><p><br>Il team FLUX</p>`,
|
||||
}),
|
||||
})
|
||||
emailSentCount++;
|
||||
} catch (err) { console.error('Errore invio Email:', err) }
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true, push_sent: sendPush, email_sent: sendEmail }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200
|
||||
})
|
||||
return new Response(JSON.stringify({
|
||||
success: true,
|
||||
targets_found: usersToNotify.length,
|
||||
push_sent: pushSentCount,
|
||||
email_sent: emailSentCount
|
||||
}), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 })
|
||||
|
||||
} catch (error) {
|
||||
console.error("ERRORE FATALE NELLA FUNZIONE:", error);
|
||||
console.error("ERRORE FATALE NELLA FUNZIONE:", error)
|
||||
return new Response(JSON.stringify({ error: error.message }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user