Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53496a2a9d | ||
|
|
0cc7c76df9 | ||
|
|
ca67d86a71 | ||
|
|
33e309909e | ||
|
|
ab64bf0621 | ||
|
|
dcb19cf839 | ||
|
|
bc9e0769cd | ||
|
|
7dd8a3ac71 | ||
|
|
70db03066b | ||
|
|
addb06a61a | ||
|
|
5e505d96b3 | ||
|
|
66c7094ada | ||
|
|
bd496ad37f | ||
|
|
771f1f921b | ||
|
|
2c02dfcf8b | ||
|
|
89e5d4014d | ||
|
|
8e396a7885 | ||
|
|
9b7b4beaa8 | ||
|
|
531b3ba3f2 | ||
|
|
d0036b729d |
No files matched your search
@@ -18,6 +18,11 @@ jobs:
|
||||
run: |
|
||||
Set-Content -Path ".env" -Value "${{ secrets.ENV_FILE_CONTENT }}"
|
||||
|
||||
- name: Pulizia Cache Dart e Download Dipendenze
|
||||
run: |
|
||||
if (Test-Path ".dart_tool") { Remove-Item -Recurse -Force ".dart_tool" }
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter Windows
|
||||
run: flutter build windows --release
|
||||
|
||||
@@ -52,16 +57,22 @@ jobs:
|
||||
- name: Aggiorna Link Windows su Supabase
|
||||
run: |
|
||||
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
|
||||
$headers = @{
|
||||
"apikey" = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Authorization" = "Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
"Content-Type" = "application/json"
|
||||
$apiKey = "${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if ([string]::IsNullOrWhiteSpace($apiKey)) {
|
||||
$apiKey = "sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
}
|
||||
$body = (@{
|
||||
$body = @{
|
||||
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
|
||||
latest_version = $TagVersion
|
||||
} | ConvertTo-Json)
|
||||
Invoke-RestMethod -Uri "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.windows" -Method Patch -Headers $headers -Body $body -UserAgent "flux-runner"
|
||||
} | ConvertTo-Json -Compress
|
||||
|
||||
[System.IO.File]::WriteAllText("$PWD\payload.json", $body, (New-Object System.Text.UTF8Encoding($false)))
|
||||
curl.exe -i -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.windows" `
|
||||
-H "apikey: $apiKey" `
|
||||
-H "Authorization: Bearer $apiKey" `
|
||||
-H "Content-Type: application/json" `
|
||||
--data-binary "@payload.json"
|
||||
Remove-Item -Force "$PWD\payload.json"
|
||||
|
||||
- name: Pulisci Workspace Windows
|
||||
if: always()
|
||||
@@ -83,6 +94,11 @@ jobs:
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Pulizia Cache e Fetch Dipendenze
|
||||
run: |
|
||||
rm -rf .dart_tool
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter Web
|
||||
run: flutter build web --release
|
||||
|
||||
@@ -97,9 +113,13 @@ jobs:
|
||||
- name: Aggiorna Versione Web su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.web" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.web" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"latest_version\": \"$TagVersion\"}"
|
||||
|
||||
@@ -118,6 +138,11 @@ jobs:
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Pulizia Cache e Fetch Dipendenze
|
||||
run: |
|
||||
rm -rf .dart_tool
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter Linux
|
||||
run: flutter build linux --release
|
||||
|
||||
@@ -165,9 +190,13 @@ jobs:
|
||||
- name: Aggiorna Link Linux su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.AppImage" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.AppImage" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\", \"latest_version\": \"$TagVersion\"}"
|
||||
|
||||
@@ -186,6 +215,11 @@ jobs:
|
||||
${{ secrets.ENV_FILE_CONTENT }}
|
||||
EOF
|
||||
|
||||
- name: Pulizia Cache e Fetch Dipendenze
|
||||
run: |
|
||||
rm -rf .dart_tool
|
||||
flutter pub get
|
||||
|
||||
- name: Build Flutter macOS
|
||||
run: flutter build macos --release
|
||||
|
||||
@@ -210,8 +244,12 @@ jobs:
|
||||
- name: Aggiorna Link macOS su Supabase
|
||||
run: |
|
||||
TagVersion="${GITHUB_REF_NAME#v}"
|
||||
curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" \
|
||||
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
|
||||
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
|
||||
if [ -z "$API_KEY" ]; then
|
||||
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
|
||||
fi
|
||||
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.macos" \
|
||||
-H "apikey: $API_KEY" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}"
|
||||
@@ -18,6 +18,7 @@ import 'package:flux/features/customers/models/customer_model.dart';
|
||||
import 'package:flux/features/customers/ui/customer_detail_screen.dart';
|
||||
import 'package:flux/features/customers/ui/customer_form_screen.dart';
|
||||
import 'package:flux/features/customers/ui/customers_list_screen.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart';
|
||||
@@ -47,6 +48,7 @@ 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/financing_form_screen.dart';
|
||||
import 'package:flux/features/operations/ui/operation_form_screen.dart';
|
||||
import 'package:flux/features/operations/ui/operation_list_screen.dart';
|
||||
import 'package:flux/features/settings/blocs/reminder_defaults_cubit.dart';
|
||||
@@ -96,8 +98,13 @@ class AppRouter {
|
||||
final isGoingToSetPassword = state.matchedLocation == '/set-password';
|
||||
|
||||
// 1. LA PASSATOIA VIP (DEVE ESSERE IN CIMA)
|
||||
// Usiamo state.uri.path perché state.matchedLocation a volte fa i capricci coi deep link iniziali
|
||||
final isPublicRoute = state.uri.path.startsWith('/upload');
|
||||
// Usiamo sia state.uri.path che state.matchedLocation per sicurezza con i deep link
|
||||
final path = state.uri.path;
|
||||
final matched = state.matchedLocation;
|
||||
final isPublicRoute = path.startsWith('/upload') ||
|
||||
path.startsWith('/financing') ||
|
||||
matched.startsWith('/upload') ||
|
||||
matched.startsWith('/financing');
|
||||
|
||||
if (isPublicRoute) {
|
||||
// Ritorna null esplicitamente per dire al router "Rimani qui e non fare altri controlli"
|
||||
@@ -153,6 +160,14 @@ class AppRouter {
|
||||
child: const OnboardingScreen(),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/financing/:sessionId',
|
||||
name: Routes.financing,
|
||||
builder: (context, state) {
|
||||
final sessionId = state.pathParameters['sessionId'] ?? '';
|
||||
return FinancingFormScreen(sessionId: sessionId);
|
||||
},
|
||||
),
|
||||
|
||||
// --- CORE APP (DENTRO LA SHELL CON NAVIGATION BAR/RAIL) ---
|
||||
ShellRoute(
|
||||
@@ -204,6 +219,12 @@ class AppRouter {
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
BlocProvider<DashboardDailyRicontattiCubit>(
|
||||
create: (context) => DashboardDailyRicontattiCubit(
|
||||
companyId: sessionCubit.state.company?.id,
|
||||
storeId: sessionCubit.state.currentStore?.id,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: const HomeScreen(),
|
||||
);
|
||||
|
||||
@@ -30,4 +30,5 @@ class Routes {
|
||||
static const String targets = 'targets';
|
||||
static const String targetForm = 'target-form';
|
||||
static const String targetDetail = 'target-detail';
|
||||
static const String financing = 'financing';
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
/// Utilità per la gestione delle immagini e normalizzazione dell'orientamento EXIF.
|
||||
class ImageUtils {
|
||||
/// Verifica se l'estensione corrisponde a un'immagine supportata.
|
||||
static bool isImageExtension(String? extension) {
|
||||
if (extension == null) return false;
|
||||
final ext = extension.toLowerCase().replaceAll('.', '');
|
||||
return ['jpg', 'jpeg', 'png', 'webp', 'bmp'].contains(ext);
|
||||
}
|
||||
|
||||
/// Verifica se un nome file o percorso è un'immagine supportata.
|
||||
static bool isImagePath(String path) {
|
||||
final dotIndex = path.lastIndexOf('.');
|
||||
if (dotIndex == -1 || dotIndex == path.length - 1) return false;
|
||||
return isImageExtension(path.substring(dotIndex + 1));
|
||||
}
|
||||
|
||||
/// Ruota fisicamente i pixel dell'immagine se contiene metadati EXIF di orientamento
|
||||
/// (tipico delle fotocamere degli smartphone), resettando l'orientamento a 1 (normale).
|
||||
/// Se l'immagine è già dritta o non possiede metadati EXIF, restituisce i byte originali.
|
||||
static Uint8List normalizeOrientation(Uint8List bytes, {String? extension}) {
|
||||
try {
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) return bytes;
|
||||
|
||||
// Se non ha tag di orientamento o è già orientata dritta (1)
|
||||
if (!image.exif.imageIfd.hasOrientation || image.exif.imageIfd.orientation == 1) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Applica la rotazione fisica dei pixel e resetta il tag EXIF
|
||||
final baked = img.bakeOrientation(image);
|
||||
|
||||
final ext = extension?.toLowerCase().replaceAll('.', '');
|
||||
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
|
||||
|
||||
if (isPng) {
|
||||
return Uint8List.fromList(img.encodePng(baked));
|
||||
} else {
|
||||
return Uint8List.fromList(img.encodeJpg(baked, quality: 92));
|
||||
}
|
||||
} catch (_) {
|
||||
// In caso di errore di parsing/decodifica, restituisce i byte inalterati
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ruota fisicamente i byte di un'immagine di un numero di quarti di giro (90° * quarterTurns).
|
||||
static Uint8List rotateBytes(
|
||||
Uint8List bytes, {
|
||||
required int quarterTurns,
|
||||
String? extension,
|
||||
}) {
|
||||
final turns = quarterTurns % 4;
|
||||
if (turns == 0) return bytes;
|
||||
|
||||
try {
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) return bytes;
|
||||
|
||||
final angle = turns * 90;
|
||||
final rotated = img.copyRotate(image, angle: angle);
|
||||
|
||||
final ext = extension?.toLowerCase().replaceAll('.', '');
|
||||
final isPng = ext == 'png' || (ext == null && image.hasAlpha);
|
||||
|
||||
if (isPng) {
|
||||
return Uint8List.fromList(img.encodePng(rotated));
|
||||
} else {
|
||||
return Uint8List.fromList(img.encodeJpg(rotated, quality: 92));
|
||||
}
|
||||
} catch (_) {
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
|
||||
part 'image_upload_state.dart';
|
||||
@@ -18,9 +19,29 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
|
||||
);
|
||||
}
|
||||
|
||||
void clearFiles() {
|
||||
emit(state.copyWith(status: ImageUploadStatus.initial, stagedFiles: []));
|
||||
}
|
||||
|
||||
void addFiles(List<PlatformFile> files) {
|
||||
final List<PlatformFile> processedFiles = files.map((file) {
|
||||
if (file.bytes != null && ImageUtils.isImagePath(file.name)) {
|
||||
final normalizedBytes = ImageUtils.normalizeOrientation(
|
||||
file.bytes!,
|
||||
extension: file.extension,
|
||||
);
|
||||
return PlatformFile(
|
||||
name: file.name,
|
||||
size: normalizedBytes.length,
|
||||
bytes: normalizedBytes,
|
||||
path: file.path,
|
||||
);
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
|
||||
List<PlatformFile> newFiles = List.from(state.stagedFiles);
|
||||
newFiles.addAll(files);
|
||||
newFiles.addAll(processedFiles);
|
||||
emit(
|
||||
state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
|
||||
);
|
||||
@@ -43,12 +64,19 @@ class ImageUploadCubit extends Cubit<ImageUploadState> {
|
||||
stagedFiles: files,
|
||||
),
|
||||
);
|
||||
|
||||
final rawBytes = await photo.readAsBytes();
|
||||
final normalizedBytes = ImageUtils.normalizeOrientation(
|
||||
rawBytes,
|
||||
extension: 'jpg',
|
||||
);
|
||||
|
||||
final List<PlatformFile> newFiles = List.from(files);
|
||||
newFiles.removeLast();
|
||||
final PlatformFile loadedFile = PlatformFile(
|
||||
name: photo.name,
|
||||
size: await photo.length(),
|
||||
bytes: await photo.readAsBytes(),
|
||||
size: normalizedBytes.length,
|
||||
bytes: normalizedBytes,
|
||||
path: photo.path,
|
||||
);
|
||||
newFiles.add(loadedFile);
|
||||
|
||||
@@ -49,45 +49,77 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Upload: $title'),
|
||||
automaticallyImplyLeading:
|
||||
state.status != ImageUploadStatus.uploading,
|
||||
title: Text(title),
|
||||
centerTitle: true,
|
||||
automaticallyImplyLeading: false,
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
// --- SEZIONE PULSANTI (Fotocamera / Galleria) ---
|
||||
// --- BARRA SUPERIORE: ANNULLA / INVIA ---
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 10.0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// ANNULLA
|
||||
Expanded(
|
||||
child: ElevatedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCamera(context),
|
||||
icon: const Icon(Icons.camera_alt),
|
||||
label: const Text('SCATTA'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 16,
|
||||
flex: 2,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCancel(context),
|
||||
icon: const Icon(Icons.close, size: 20),
|
||||
label: const Text(
|
||||
'Annulla',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.red.shade700,
|
||||
side: BorderSide(color: Colors.red.shade300),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// INVIA
|
||||
Expanded(
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleFilePicker(context),
|
||||
icon: const Icon(Icons.folder),
|
||||
label: const Text("GALLERIA"),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 16,
|
||||
flex: 3,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: FilledButton.icon(
|
||||
onPressed:
|
||||
state.stagedFiles.isEmpty ||
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _submitAllFiles(context),
|
||||
icon: const Icon(Icons.cloud_upload, size: 20),
|
||||
label: Text(
|
||||
state.stagedFiles.isEmpty
|
||||
? 'Invia'
|
||||
: 'Invia (${state.stagedFiles.length})',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -96,27 +128,52 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(),
|
||||
const Divider(height: 1),
|
||||
|
||||
// --- SEZIONE ANTEPRIME (La GridView Magica) ---
|
||||
// --- SEZIONE ANTEPRIME ---
|
||||
Expanded(
|
||||
child: state.stagedFiles.isEmpty
|
||||
? const Center(
|
||||
child: Text(
|
||||
"Nessun file selezionato.\nScatta una foto o scegli dalla galleria.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.grey),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.add_photo_alternate_outlined,
|
||||
size: 64,
|
||||
color: Colors.grey,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
"Nessun file selezionato",
|
||||
style: TextStyle(
|
||||
fontSize: 17,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
"Tocca 'Scatta' o 'Galleria' in basso per aggiungere foto o documenti.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: GridView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate:
|
||||
const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount:
|
||||
3, // 3 colonne stile galleria
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
),
|
||||
crossAxisCount: 3,
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
),
|
||||
itemCount: state.stagedFiles.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = state.stagedFiles[index];
|
||||
@@ -145,7 +202,6 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// L'ANTEPRIMA
|
||||
Container(
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
@@ -159,19 +215,10 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: isImg
|
||||
? (file.bytes != null
|
||||
// Se abbiamo i bytes (es. scatto da fotocamera) usiamo quelli (a prova di Web!)
|
||||
? Image.memory(
|
||||
file.bytes!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
// Altrimenti andiamo di file fisico
|
||||
: const Center(
|
||||
child:
|
||||
CircularProgressIndicator(
|
||||
color: Colors.blue,
|
||||
),
|
||||
))
|
||||
? Image.memory(
|
||||
file.bytes!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
: const Column(
|
||||
mainAxisAlignment:
|
||||
MainAxisAlignment.center,
|
||||
@@ -194,11 +241,9 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// IL PULSANTE CESTINO (In alto a destra)
|
||||
Positioned(
|
||||
top: -8,
|
||||
right: -8,
|
||||
top: -6,
|
||||
right: -6,
|
||||
child: GestureDetector(
|
||||
onTap: () => context
|
||||
.read<ImageUploadCubit>()
|
||||
@@ -222,42 +267,113 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
),
|
||||
// --- SEZIONE INVIA E CHIUDI ---
|
||||
|
||||
// --- SEZIONE INFERIORE (A portata di pollice: Scatta e Galleria) ---
|
||||
SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
height: 56,
|
||||
child: ElevatedButton.icon(
|
||||
// Il pulsante si accende SOLO se ci sono file nel carrello
|
||||
onPressed:
|
||||
state.stagedFiles.isEmpty ||
|
||||
state.status == ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _submitAllFiles(context),
|
||||
icon: const Icon(Icons.cloud_upload),
|
||||
label: Text(
|
||||
"INVIA ${state.stagedFiles.length} FILE E CHIUDI",
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 12.0,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.06),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, -2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// SCATTA
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
height: 56,
|
||||
child: FilledButton.icon(
|
||||
onPressed:
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleCamera(context),
|
||||
icon: const Icon(Icons.camera_alt, size: 24),
|
||||
label: const Text(
|
||||
'Scatta',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
foregroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.onPrimary,
|
||||
const SizedBox(width: 12),
|
||||
// GALLERIA
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
height: 56,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed:
|
||||
state.status ==
|
||||
ImageUploadStatus.uploading
|
||||
? null
|
||||
: () => _handleFilePicker(context),
|
||||
icon: const Icon(
|
||||
Icons.photo_library,
|
||||
size: 24,
|
||||
),
|
||||
label: const Text(
|
||||
'Galleria',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (state.status == ImageUploadStatus.uploading)
|
||||
Container(
|
||||
color: Colors.black45,
|
||||
child: const Center(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Caricamento in corso...',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -266,6 +382,40 @@ class ImageUploadScreen extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
void _handleCancel(BuildContext context) {
|
||||
final cubit = context.read<ImageUploadCubit>();
|
||||
if (cubit.state.stagedFiles.isNotEmpty) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Annullare caricamento?'),
|
||||
content: const Text('I file selezionati verranno rimossi.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('No, continua'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
|
||||
onPressed: () {
|
||||
Navigator.pop(ctx);
|
||||
cubit.clearFiles();
|
||||
if (Navigator.of(context).canPop()) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
},
|
||||
child: const Text('Sì, annulla'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
if (Navigator.of(context).canPop()) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- LOGICA FOTOCAMERA E LIBRERIA ---
|
||||
Future<void> _handleCamera(BuildContext context) async {
|
||||
final ImageUploadCubit imageUploadCubit = context.read<ImageUploadCubit>();
|
||||
|
||||
@@ -43,6 +43,21 @@ class UploadSuccessScreen extends StatelessWidget {
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 16, color: Colors.black54),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
if (Navigator.of(context).canPop())
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.add_photo_alternate),
|
||||
label: const Text('Carica altri file per questa pratica'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.green.shade800,
|
||||
side: BorderSide(color: Colors.green.shade600),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 20,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,7 +2,7 @@ import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/core/utils/functions.dart';
|
||||
import 'package:pdfx/pdfx.dart';
|
||||
import 'package:pdfrx/pdfrx.dart';
|
||||
import 'package:internet_file/internet_file.dart';
|
||||
|
||||
class PdfViewerWidget extends StatefulWidget {
|
||||
@@ -20,7 +20,7 @@ class PdfViewerWidget extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
late PdfControllerPinch _pdfController;
|
||||
Uint8List? _pdfData;
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
|
||||
@@ -45,11 +45,12 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
throw Exception("Nessun documento trovato");
|
||||
}
|
||||
|
||||
_pdfController = PdfControllerPinch(
|
||||
document: PdfDocument.openData(pdfData),
|
||||
);
|
||||
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_pdfData = pdfData;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
@@ -60,12 +61,6 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pdfController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
@@ -87,7 +82,10 @@ class _PdfViewerWidgetState extends State<PdfViewerWidget> {
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
body: PdfViewPinch(controller: _pdfController),
|
||||
body: PdfViewer.data(
|
||||
_pdfData!,
|
||||
sourceName: widget.storagePath ?? 'document.pdf',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
class QrUploadDialog extends StatelessWidget {
|
||||
class QrUploadDialog extends StatefulWidget {
|
||||
final String deepLinkUrl;
|
||||
final String title;
|
||||
|
||||
@@ -14,20 +14,33 @@ class QrUploadDialog extends StatelessWidget {
|
||||
required this.title,
|
||||
});
|
||||
|
||||
@override
|
||||
State<QrUploadDialog> createState() => _QrUploadDialogState();
|
||||
}
|
||||
|
||||
class _QrUploadDialogState extends State<QrUploadDialog> {
|
||||
int _initialFileCount = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Memorizziamo quanti file c'erano al momento dell'apertura per contare solo i nuovi ricevuti
|
||||
_initialFileCount = context.read<AttachmentsBloc>().state.allFiles.length;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Usiamo i colori del tema per renderlo coerente col tuo design
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
|
||||
listenWhen: (previous, current) =>
|
||||
previous.allFiles.length < current.allFiles.length,
|
||||
current.allFiles.length > previous.allFiles.length,
|
||||
listener: (context, state) {
|
||||
final newCount = state.allFiles.length;
|
||||
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'File caricato con successo via QR Code! 📄 ($newCount allegati in totale)',
|
||||
'Nuovo file ricevuto via QR Code! 📄 ($sessionReceived in questa sessione)',
|
||||
),
|
||||
duration: const Duration(seconds: 2),
|
||||
backgroundColor: Colors.green.shade700,
|
||||
@@ -35,7 +48,7 @@ class QrUploadDialog extends StatelessWidget {
|
||||
);
|
||||
},
|
||||
builder: (context, state) {
|
||||
final fileCount = state.allFiles.length;
|
||||
final sessionReceived = (state.allFiles.length - _initialFileCount).clamp(0, 99999);
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
@@ -51,7 +64,7 @@ class QrUploadDialog extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
title,
|
||||
widget.title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
@@ -62,7 +75,7 @@ class QrUploadDialog extends StatelessWidget {
|
||||
width: 350,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min, // Fondamentale per i dialog
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
"Inquadra questo codice con la fotocamera del tuo telefono per scattare e caricare i documenti direttamente qui.",
|
||||
@@ -73,12 +86,11 @@ class QrUploadDialog extends StatelessWidget {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors
|
||||
.white, // Lo sfondo bianco salva la vita sui temi scuri
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: QrImageView(
|
||||
data: deepLinkUrl,
|
||||
data: widget.deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 200.0,
|
||||
embeddedImage: const AssetImage(
|
||||
@@ -94,31 +106,38 @@ class QrUploadDialog extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
fileCount > 0
|
||||
sessionReceived > 0
|
||||
? Icons.check_circle_outline
|
||||
: Icons.hourglass_empty,
|
||||
size: 18,
|
||||
color: fileCount > 0
|
||||
color: sessionReceived > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
fileCount > 0
|
||||
? "$fileCount file ricevuti! (In ascolto...)"
|
||||
sessionReceived > 0
|
||||
? "$sessionReceived file ricevuti! (In ascolto...)"
|
||||
: "In attesa di file...",
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: fileCount > 0
|
||||
color: sessionReceived > 0
|
||||
? Colors.green
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_initialFileCount > 0 && sessionReceived == 0) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"($_initialFileCount file già presenti nella pratica)",
|
||||
style: const TextStyle(fontSize: 11, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(), // Per far capire che è "in ascolto"
|
||||
const LinearProgressIndicator(),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/widgets/qr_upload_dialog.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
@@ -13,8 +14,10 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:pdf/widgets.dart' as pw;
|
||||
import 'package:pdfx/pdfx.dart' as px; // Isoliamo pdfx
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:pdfrx/pdfrx.dart' as pdfrx;
|
||||
|
||||
class _ExportItem {
|
||||
final Uint8List bytes;
|
||||
@@ -151,13 +154,55 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
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 if (ext == 'pdf' && file.bytes != null) {
|
||||
Widget pdfThumb;
|
||||
try {
|
||||
final doc = await pdfrx.PdfDocument.openData(
|
||||
file.bytes!,
|
||||
sourceName: file.name,
|
||||
);
|
||||
if (doc.pages.isNotEmpty) {
|
||||
final page = doc.pages.first;
|
||||
final pageImg = await page.render(
|
||||
fullWidth: 300,
|
||||
fullHeight: (300.0 * (page.height / page.width)).roundToDouble(),
|
||||
);
|
||||
if (pageImg != null) {
|
||||
final uiImg = await pageImg.createImage();
|
||||
final bd = await uiImg.toByteData(format: ui.ImageByteFormat.png);
|
||||
if (bd != null) {
|
||||
pdfThumb = Image.memory(bd.buffer.asUint8List(), fit: BoxFit.contain);
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
uiImg.dispose();
|
||||
pageImg.dispose();
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
await doc.dispose();
|
||||
} catch (_) {
|
||||
pdfThumb = const Center(
|
||||
child: Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
|
||||
);
|
||||
}
|
||||
previewWidget = pdfThumb;
|
||||
} else {
|
||||
previewWidget = const Center(
|
||||
child: Icon(Icons.insert_drive_file, size: 80, color: Colors.blue),
|
||||
previewWidget = Center(
|
||||
child: Icon(
|
||||
ext == 'pdf' ? Icons.picture_as_pdf : Icons.insert_drive_file,
|
||||
size: 80,
|
||||
color: ext == 'pdf' ? Colors.red : Colors.blue,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -171,6 +216,8 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
? widget.titleForUpload
|
||||
: '${widget.titleForUpload}_${i + 1}';
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
final finalName = await showDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
@@ -313,12 +360,168 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
DeleteSpecificAttachmentEvent(targetFile),
|
||||
);
|
||||
},
|
||||
onViewModeChanged: (targetFile, newMode) {
|
||||
operationFilesBloc.add(
|
||||
UpdateAttachmentViewModeEvent(targetFile, newMode),
|
||||
);
|
||||
},
|
||||
onAttachmentUpdated: (updatedFile) {
|
||||
operationFilesBloc.add(
|
||||
AttachmentUpdatedEvent(updatedFile),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _downloadFileWeb(String fileName, Uint8List bytes) {
|
||||
final blob = html.Blob([bytes]);
|
||||
final url = html.Url.createObjectUrlFromBlob(blob);
|
||||
html.AnchorElement(href: url)
|
||||
..setAttribute('download', fileName)
|
||||
..click();
|
||||
html.Url.revokeObjectUrl(url);
|
||||
}
|
||||
|
||||
Future<void> _downloadSelectedFiles(
|
||||
List<AttachmentModel> selectedFiles,
|
||||
) async {
|
||||
if (selectedFiles.isEmpty) return;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => const Center(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text('Download allegati in corso...'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final List<({String name, Uint8List bytes})> downloadedList = [];
|
||||
|
||||
for (final file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
|
||||
if (fileBytes != null && fileBytes.isNotEmpty) {
|
||||
String fullName = file.name;
|
||||
final ext = file.extension.toLowerCase().replaceAll('.', '');
|
||||
if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) {
|
||||
fullName = '$fullName.$ext';
|
||||
}
|
||||
downloadedList.add((name: fullName, bytes: fileBytes));
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pop(context); // Chiude il loader
|
||||
}
|
||||
|
||||
if (downloadedList.isEmpty) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Nessun file scaricabile trovato.')),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (kIsWeb) {
|
||||
for (int i = 0; i < downloadedList.length; i++) {
|
||||
final item = downloadedList[i];
|
||||
_downloadFileWeb(item.name, item.bytes);
|
||||
if (downloadedList.length > 1) {
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
}
|
||||
}
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
downloadedList.length == 1
|
||||
? 'Download avviato: ${downloadedList.first.name}'
|
||||
: '${downloadedList.length} file scaricati!',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Desktop / Mobile
|
||||
if (downloadedList.length == 1) {
|
||||
final item = downloadedList.first;
|
||||
final String? savePath = await FilePicker.saveFile(
|
||||
dialogTitle: 'Salva file',
|
||||
fileName: item.name,
|
||||
initialDirectory: _exportDirectory,
|
||||
bytes: item.bytes,
|
||||
);
|
||||
|
||||
if (savePath != null) {
|
||||
final targetFile = File(savePath);
|
||||
await targetFile.writeAsBytes(item.bytes);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('File salvato in: $savePath')),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final String? selectedDirectory = await FilePicker.getDirectoryPath(
|
||||
dialogTitle:
|
||||
'Seleziona cartella dove salvare i file (${downloadedList.length})',
|
||||
initialDirectory: _exportDirectory,
|
||||
);
|
||||
|
||||
if (selectedDirectory != null) {
|
||||
for (final item in downloadedList) {
|
||||
final targetFile = File('$selectedDirectory/${item.name}');
|
||||
await targetFile.writeAsBytes(item.bytes);
|
||||
}
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${downloadedList.length} file salvati in: $selectedDirectory',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
if (Navigator.canPop(context)) Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Errore durante il download: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportMergedPdf(List<AttachmentModel> selectedFiles) async {
|
||||
if (!kIsWeb && (_exportDirectory == null || _exportDirectory!.isEmpty)) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -341,11 +544,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
for (var file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
@@ -353,23 +558,35 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
if (fileBytes == null) continue;
|
||||
|
||||
if (file.extension == 'pdf') {
|
||||
final document = await px.PdfDocument.openData(fileBytes);
|
||||
for (int i = 1; i <= document.pagesCount; i++) {
|
||||
final page = await document.getPage(i);
|
||||
final document = await pdfrx.PdfDocument.openData(
|
||||
fileBytes,
|
||||
sourceName: file.name,
|
||||
);
|
||||
for (final page in document.pages) {
|
||||
final pageImage = await page.render(
|
||||
width: page.width * 2,
|
||||
height: page.height * 2,
|
||||
format: px.PdfPageImageFormat.jpeg,
|
||||
fullWidth: page.width * 2,
|
||||
fullHeight: page.height * 2,
|
||||
);
|
||||
if (pageImage != null) {
|
||||
allPagesAsImages.add(pageImage.bytes);
|
||||
final uiImage = await pageImage.createImage();
|
||||
final byteData = await uiImage.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
if (byteData != null) {
|
||||
allPagesAsImages.add(byteData.buffer.asUint8List());
|
||||
}
|
||||
uiImage.dispose();
|
||||
pageImage.dispose();
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
await document.close();
|
||||
await document.dispose();
|
||||
} else {
|
||||
// È un'immagine
|
||||
allPagesAsImages.add(fileBytes);
|
||||
// È un'immagine: normalizziamo l'orientamento EXIF per il PDF
|
||||
final safeBytes = ImageUtils.normalizeOrientation(
|
||||
fileBytes,
|
||||
extension: file.extension,
|
||||
);
|
||||
allPagesAsImages.add(safeBytes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,7 +643,7 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
|
||||
// 5. SALVATAGGIO SUL DISCO
|
||||
if (kIsWeb) {
|
||||
// Trigger download web
|
||||
_downloadFileWeb('$finalName.pdf', mergedPdfBytes);
|
||||
} else {
|
||||
final fileToSave = File('$_exportDirectory/$finalName.pdf');
|
||||
await fileToSave.writeAsBytes(mergedPdfBytes);
|
||||
@@ -472,11 +689,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
for (var file in selectedFiles) {
|
||||
Uint8List? fileBytes;
|
||||
|
||||
final targetPath = file.effectiveStoragePath;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
fileBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
} else if (targetPath != null && targetPath.isNotEmpty) {
|
||||
fileBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
storagePath: targetPath,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
@@ -487,38 +706,49 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
final baseName = file.name;
|
||||
|
||||
if (file.extension == 'pdf') {
|
||||
final document = await px.PdfDocument.openData(fileBytes);
|
||||
final document = await pdfrx.PdfDocument.openData(
|
||||
fileBytes,
|
||||
sourceName: file.name,
|
||||
);
|
||||
final isMulti =
|
||||
document.pagesCount > 1; // Controlliamo se è multipagina!
|
||||
|
||||
for (int i = 1; i <= document.pagesCount; i++) {
|
||||
final page = await document.getPage(i);
|
||||
document.pages.length > 1; // Controlliamo se è multipagina!
|
||||
|
||||
for (final page in document.pages) {
|
||||
final pageImage = await page.render(
|
||||
width: page.width * 2,
|
||||
height: page.height * 2,
|
||||
format: px.PdfPageImageFormat.jpeg,
|
||||
fullWidth: page.width * 2,
|
||||
fullHeight: page.height * 2,
|
||||
);
|
||||
|
||||
if (pageImage != null) {
|
||||
// Salviamo l'immagine CON il suo contesto storico
|
||||
itemsToExport.add(
|
||||
_ExportItem(
|
||||
bytes: pageImage.bytes,
|
||||
sourceName: baseName,
|
||||
isMultiPage: isMulti,
|
||||
pageIndex: i,
|
||||
),
|
||||
final uiImage = await pageImage.createImage();
|
||||
final byteData = await uiImage.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
if (byteData != null) {
|
||||
// Salviamo l'immagine CON il suo contesto storico
|
||||
itemsToExport.add(
|
||||
_ExportItem(
|
||||
bytes: byteData.buffer.asUint8List(),
|
||||
sourceName: baseName,
|
||||
isMultiPage: isMulti,
|
||||
pageIndex: page.pageNumber,
|
||||
),
|
||||
);
|
||||
}
|
||||
uiImage.dispose();
|
||||
pageImage.dispose();
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
await document.close();
|
||||
await document.dispose();
|
||||
} else {
|
||||
// SE È UN'IMMAGINE, la salviamo come singola pagina
|
||||
// SE È UN'IMMAGINE, la salviamo normalizzando l'orientamento
|
||||
final safeBytes = ImageUtils.normalizeOrientation(
|
||||
fileBytes,
|
||||
extension: file.extension,
|
||||
);
|
||||
itemsToExport.add(
|
||||
_ExportItem(
|
||||
bytes: fileBytes,
|
||||
bytes: safeBytes,
|
||||
sourceName: baseName,
|
||||
isMultiPage: false,
|
||||
pageIndex: 1,
|
||||
@@ -567,7 +797,7 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
final singlePdfBytes = await pdf.save();
|
||||
|
||||
if (kIsWeb) {
|
||||
// Trigger download web
|
||||
_downloadFileWeb('$finalName.pdf', singlePdfBytes);
|
||||
} else {
|
||||
final fileToSave = File('$_exportDirectory/$finalName.pdf');
|
||||
await fileToSave.writeAsBytes(singlePdfBytes);
|
||||
@@ -595,7 +825,17 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocBuilder<AttachmentsBloc, AttachmentsState>(
|
||||
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
|
||||
listener: (context, state) {
|
||||
if (state.status == AttachmentsStatus.failure && state.error != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.error!),
|
||||
backgroundColor: theme.colorScheme.error,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final allFiles = state.allFiles;
|
||||
final selectedFiles = state.selectedFiles;
|
||||
@@ -762,12 +1002,56 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
],
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Loader di upload
|
||||
// Indicatori di stato nell'action bar
|
||||
if (state.status == AttachmentsStatus.uploading)
|
||||
const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Caricamento file...',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (state.status == AttachmentsStatus.loading &&
|
||||
allFiles.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'Aggiornamento...',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: theme.colorScheme.primary,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Azioni visibili SOLO se c'è una selezione!
|
||||
@@ -801,6 +1085,15 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
);
|
||||
},
|
||||
),
|
||||
// Bottone Scarica Selezionati
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.teal,
|
||||
),
|
||||
icon: const Icon(Icons.download),
|
||||
label: Text('Scarica (${selectedFiles.length})'),
|
||||
onPressed: () => _downloadSelectedFiles(selectedFiles),
|
||||
),
|
||||
// IL NUOVO BOTTONE ESPORTA CON MENU A TENDINA
|
||||
PopupMenuButton<String>(
|
||||
tooltip: 'Opzioni di esportazione',
|
||||
@@ -855,8 +1148,115 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 3. GRIGLIA DEI FILE
|
||||
if (allFiles.isEmpty)
|
||||
// 3. GRIGLIA DEI FILE O STATO DI CARICAMENTO
|
||||
if (state.status == AttachmentsStatus.loading ||
|
||||
(state.status == AttachmentsStatus.initial &&
|
||||
widget.parentId != null &&
|
||||
widget.parentId!.isNotEmpty))
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 36,
|
||||
horizontal: 24,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(
|
||||
alpha: 0.35,
|
||||
),
|
||||
border: Border.all(
|
||||
color: theme.dividerColor.withValues(alpha: 0.6),
|
||||
style: BorderStyle.solid,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 32,
|
||||
height: 32,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 3,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Caricamento allegati in corso...',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurface,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Sincronizzazione documenti in archivio',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(
|
||||
alpha: 0.8,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (state.status == AttachmentsStatus.failure &&
|
||||
allFiles.isEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.errorContainer.withValues(
|
||||
alpha: 0.25,
|
||||
),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.error.withValues(alpha: 0.5),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 36,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Errore durante il recupero degli allegati',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
if (state.error != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
state.error!,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
context.read<AttachmentsBloc>().add(
|
||||
LoadAttachmentsEvent(parentId: widget.parentId),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Riprova'),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else if (allFiles.isEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(32),
|
||||
@@ -893,7 +1293,6 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
itemCount: allFiles.length,
|
||||
itemBuilder: (context, index) {
|
||||
final file = allFiles[index];
|
||||
final isPdf = file.extension == 'pdf';
|
||||
final isSelected = selectedFiles.contains(file);
|
||||
final isLocal =
|
||||
file.localBytes !=
|
||||
@@ -939,28 +1338,12 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
),
|
||||
child: isPdf
|
||||
? const Icon(
|
||||
Icons.picture_as_pdf,
|
||||
size: 48,
|
||||
color: Colors.red,
|
||||
)
|
||||
: isLocal
|
||||
? ClipRRect(
|
||||
borderRadius:
|
||||
const BorderRadius.vertical(
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
child: Image.memory(
|
||||
file.localBytes!,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.image,
|
||||
size: 48,
|
||||
color: Colors.blue,
|
||||
), // Da remoto metterai il tuo NetworkImage se vuoi
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(8),
|
||||
),
|
||||
child: _AttachmentThumbnail(file: file),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Nome File
|
||||
@@ -1047,3 +1430,240 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AttachmentThumbnail extends StatefulWidget {
|
||||
final AttachmentModel file;
|
||||
|
||||
const _AttachmentThumbnail({required this.file});
|
||||
|
||||
@override
|
||||
State<_AttachmentThumbnail> createState() => _AttachmentThumbnailState();
|
||||
}
|
||||
|
||||
class _AttachmentThumbnailState extends State<_AttachmentThumbnail> {
|
||||
static final Map<String, Uint8List> _thumbnailCache = {};
|
||||
|
||||
Uint8List? _bytes;
|
||||
bool _isLoading = true;
|
||||
|
||||
String get _cacheKey {
|
||||
if (widget.file.thumbnailPath != null &&
|
||||
widget.file.thumbnailPath!.isNotEmpty) {
|
||||
return 'thumb_${widget.file.thumbnailPath}';
|
||||
}
|
||||
return widget.file.id ??
|
||||
widget.file.storagePath ??
|
||||
'${widget.file.name}_${widget.file.fileSize}';
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadThumbnail();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _AttachmentThumbnail oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.file.id != oldWidget.file.id ||
|
||||
widget.file.thumbnailPath != oldWidget.file.thumbnailPath ||
|
||||
widget.file.storagePath != oldWidget.file.storagePath ||
|
||||
widget.file.localBytes != oldWidget.file.localBytes) {
|
||||
_loadThumbnail();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadThumbnail() async {
|
||||
final key = _cacheKey;
|
||||
if (_thumbnailCache.containsKey(key)) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = _thumbnailCache[key];
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final file = widget.file;
|
||||
|
||||
// ⚡ Se il worker sul server ha generato il thumbnail (WebP), lo scarichiamo direttamente!
|
||||
if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty) {
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final thumbBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.thumbnailPath!,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
if (thumbBytes.isNotEmpty) {
|
||||
_thumbnailCache[key] = thumbBytes;
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = thumbBytes;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint(
|
||||
'Impossibile scaricare thumbnail da ${file.thumbnailPath}, procedo con fallback: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List? sourceBytes;
|
||||
|
||||
if (file.localBytes != null) {
|
||||
sourceBytes = file.localBytes;
|
||||
} else if (file.storagePath != null && file.storagePath!.isNotEmpty) {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
sourceBytes = await repository.downloadAttachmentBytes(
|
||||
storagePath: file.storagePath!,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
}
|
||||
|
||||
if (sourceBytes == null || sourceBytes.isEmpty) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Uint8List? finalThumbnailBytes;
|
||||
final isPdf =
|
||||
file.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
if (isPdf) {
|
||||
final document = await pdfrx.PdfDocument.openData(
|
||||
sourceBytes,
|
||||
sourceName: file.name,
|
||||
);
|
||||
if (document.pages.isNotEmpty) {
|
||||
final page = document.pages.first;
|
||||
const renderWidth = 300.0;
|
||||
final renderHeight =
|
||||
(300.0 * (page.height / page.width)).roundToDouble();
|
||||
final pageImage = await page.render(
|
||||
fullWidth: renderWidth,
|
||||
fullHeight: renderHeight,
|
||||
);
|
||||
if (pageImage != null) {
|
||||
final uiImage = await pageImage.createImage();
|
||||
final byteData = await uiImage.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
if (byteData != null) {
|
||||
finalThumbnailBytes = byteData.buffer.asUint8List();
|
||||
}
|
||||
uiImage.dispose();
|
||||
pageImage.dispose();
|
||||
}
|
||||
}
|
||||
await document.dispose();
|
||||
} else {
|
||||
finalThumbnailBytes = ImageUtils.normalizeOrientation(
|
||||
sourceBytes,
|
||||
extension: file.extension,
|
||||
);
|
||||
}
|
||||
|
||||
if (finalThumbnailBytes != null) {
|
||||
_thumbnailCache[key] = finalThumbnailBytes;
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_bytes = finalThumbnailBytes;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isPdf =
|
||||
widget.file.extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
if (_bytes != null) {
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Image.memory(
|
||||
_bytes!,
|
||||
fit: BoxFit.cover,
|
||||
filterQuality: FilterQuality.medium,
|
||||
),
|
||||
if (isPdf)
|
||||
Positioned(
|
||||
bottom: 6,
|
||||
left: 6,
|
||||
child: Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.9),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 3,
|
||||
offset: Offset(0, 1),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.picture_as_pdf, size: 10, color: Colors.white),
|
||||
SizedBox(width: 3),
|
||||
Text(
|
||||
'PDF',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_isLoading) {
|
||||
return Center(
|
||||
child: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: isPdf ? Colors.red : Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: Icon(
|
||||
isPdf ? Icons.picture_as_pdf : Icons.image,
|
||||
size: 48,
|
||||
color: isPdf ? Colors.red : Colors.blue,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,9 @@ class StaffSection extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
final staffMembers = state.storeStaff;
|
||||
final staffMembers = state.storeStaff
|
||||
.where((staff) => staff.isActive || staff.id == selectedStaffId)
|
||||
.toList();
|
||||
|
||||
// FIX: Feedback visivo se la lista è vuota
|
||||
if (staffMembers.isEmpty) {
|
||||
|
||||
@@ -61,7 +61,21 @@ class StaffSelectorModal extends StatelessWidget {
|
||||
if (state.status == StaffStatus.loading) {
|
||||
return const CircularProgressIndicator();
|
||||
}
|
||||
final staffList = state.storeStaff;
|
||||
final rawList = state.storeStaff.isNotEmpty
|
||||
? state.storeStaff
|
||||
: state.allStaff;
|
||||
final staffList = rawList.where((s) => s.isActive).toList();
|
||||
|
||||
if (staffList.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24.0),
|
||||
child: Text(
|
||||
'Nessun collaboratore attivo trovato.',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return _buildStaffGrid(context, staffList);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
@@ -16,6 +16,7 @@ part 'attachments_state.dart';
|
||||
|
||||
class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
final _repository = GetIt.I.get<AttachmentsRepository>();
|
||||
StreamSubscription<List<AttachmentModel>>? _realtimeSubscription;
|
||||
|
||||
AttachmentsBloc({String? parentId, required AttachmentParentType parentType})
|
||||
: super(
|
||||
@@ -36,6 +37,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
on<DeleteSpecificAttachmentEvent>(_onDeleteSpecificAttachment);
|
||||
on<SelectAllAttachmentsEvent>(_onSelectAllAttachments);
|
||||
on<ClearAttachmentSelectionEvent>(_onClearAttachmentSelection);
|
||||
on<RemoteAttachmentsUpdatedEvent>(_onRemoteAttachmentsUpdated);
|
||||
on<UpdateAttachmentViewModeEvent>(_onUpdateAttachmentViewMode);
|
||||
on<AttachmentUpdatedEvent>(_onAttachmentUpdated);
|
||||
|
||||
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
|
||||
if (parentId != null && currentCompanyId != null) {
|
||||
@@ -43,6 +47,12 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_realtimeSubscription?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
|
||||
FutureOr<void> _onParentEntitySaved(
|
||||
ParentEntitySavedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
@@ -65,7 +75,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
bytes: file.localBytes,
|
||||
);
|
||||
|
||||
// Chiamiamo il metodo generico passando il parentId e il TYPE
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: event.newParentId,
|
||||
parentType: state.parentType,
|
||||
@@ -96,26 +105,75 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
final currentId = event.parentId ?? state.parentId;
|
||||
if (currentId == null || currentId.isEmpty) return;
|
||||
|
||||
if (currentId != null) {
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
emit(
|
||||
state.copyWith(
|
||||
parentId: currentId,
|
||||
status:
|
||||
state.remoteFiles.isEmpty
|
||||
? AttachmentsStatus.loading
|
||||
: state.status,
|
||||
),
|
||||
);
|
||||
|
||||
await emit.forEach(
|
||||
_repository.getFilesStream(
|
||||
currentId,
|
||||
state.parentType,
|
||||
), // Passiamo il tipo!
|
||||
onData: (List<AttachmentModel> data) =>
|
||||
state.copyWith(status: AttachmentsStatus.ready, remoteFiles: data),
|
||||
onError: (error, stackTrace) => state.copyWith(
|
||||
status: AttachmentsStatus.failure,
|
||||
error: error.toString(),
|
||||
// 1. Caricamento immediato via REST (Robusto e istantaneo)
|
||||
try {
|
||||
final remoteList = await _repository.getFiles(
|
||||
currentId,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: remoteList,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint("Avviso REST getFiles: $e");
|
||||
if (state.remoteFiles.isEmpty) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.failure,
|
||||
error: "Impossibile recuperare gli allegati: $e",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Iscrizione Realtime in background (senza bloccare la coda eventi)
|
||||
await _realtimeSubscription?.cancel();
|
||||
try {
|
||||
_realtimeSubscription = _repository
|
||||
.getFilesStream(currentId, state.parentType)
|
||||
.listen(
|
||||
(data) {
|
||||
add(RemoteAttachmentsUpdatedEvent(data));
|
||||
},
|
||||
onError: (error) {
|
||||
debugPrint("Avviso stream Realtime AttachmentsBloc: $error");
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint("Avviso inizializzazione Realtime: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void _onAddAttachments(
|
||||
void _onRemoteAttachmentsUpdated(
|
||||
RemoteAttachmentsUpdatedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: event.files,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
FutureOr<void> _onAddAttachments(
|
||||
AddAttachmentsEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
@@ -132,32 +190,48 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
|
||||
if (currentId == null) {
|
||||
final newLocalFiles = event.files.map((file) {
|
||||
// FISCHIO SALVAVITA PER DESKTOP: se i bytes sono nulli, li leggiamo dal path fisico!
|
||||
Uint8List? rawBytes = file.bytes;
|
||||
if (rawBytes == null && file.path != null) {
|
||||
rawBytes = File(file.path!).readAsBytesSync();
|
||||
}
|
||||
// Normalizziamo i file garantendo la presenza dei byte (fondamentale su desktop)
|
||||
final processedFiles =
|
||||
event.files.map((file) {
|
||||
Uint8List? rawBytes = file.bytes;
|
||||
if (rawBytes == null && file.path != null && !kIsWeb) {
|
||||
try {
|
||||
final f = File(file.path!);
|
||||
if (f.existsSync()) {
|
||||
rawBytes = f.readAsBytesSync();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
return AttachmentModel(
|
||||
id: null,
|
||||
companyId: currentCompanyId,
|
||||
operationId: state.parentType == AttachmentParentType.operation
|
||||
? ''
|
||||
: null,
|
||||
ticketId: state.parentType == AttachmentParentType.ticket ? '' : null,
|
||||
customerId: state.parentType == AttachmentParentType.customer
|
||||
? ''
|
||||
: null,
|
||||
name: file.name.fileNameWithoutExtension(),
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: rawBytes, // Ora i byte ci sono al 100% anche su Mac!
|
||||
);
|
||||
}).toList();
|
||||
return PlatformFile(
|
||||
name: file.name,
|
||||
size: file.size > 0 ? file.size : (rawBytes?.length ?? 0),
|
||||
bytes: rawBytes,
|
||||
path: file.path,
|
||||
readStream: file.readStream,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
// BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria)
|
||||
if (currentId == null || currentId.isEmpty) {
|
||||
final newLocalFiles =
|
||||
processedFiles.map((file) {
|
||||
return AttachmentModel(
|
||||
id: null,
|
||||
companyId: currentCompanyId,
|
||||
operationId:
|
||||
state.parentType == AttachmentParentType.operation ? '' : null,
|
||||
ticketId:
|
||||
state.parentType == AttachmentParentType.ticket ? '' : null,
|
||||
customerId:
|
||||
state.parentType == AttachmentParentType.customer ? '' : null,
|
||||
name: file.name.fileNameWithoutExtension(),
|
||||
extension: file.name.fileExtension(),
|
||||
storagePath: '',
|
||||
fileSize: file.size,
|
||||
localBytes: file.bytes,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -171,18 +245,31 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
// BIVIO 2: PRATICA ESISTENTE (Upload immediato)
|
||||
emit(state.copyWith(status: AttachmentsStatus.uploading));
|
||||
try {
|
||||
final List<Future<void>> uploadTasks = event.files.map((file) {
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: currentId,
|
||||
parentType: state.parentType,
|
||||
pickedFile: file,
|
||||
companyId: currentCompanyId,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
}).toList();
|
||||
final List<Future<void>> uploadTasks =
|
||||
processedFiles.map((file) {
|
||||
return _repository.uploadAndRegisterFile(
|
||||
parentId: currentId,
|
||||
parentType: state.parentType,
|
||||
pickedFile: file,
|
||||
companyId: currentCompanyId,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
await Future.wait(uploadTasks);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
|
||||
// Aggiornamento immediato via REST (garantisce visualizzazione immediata anche senza WebSocket)
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
currentId,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -223,11 +310,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
// 2. Gestione Foto Fotocamera (XFile)
|
||||
if (event.photos != null) {
|
||||
for (var photo in event.photos!) {
|
||||
// Leggiamo i byte asincronamente
|
||||
final bytes = await photo.readAsBytes();
|
||||
final fileSize = await photo.length();
|
||||
|
||||
// Lo travestiamo da PlatformFile per passarlo al Repository!
|
||||
final fakePlatformFile = PlatformFile(
|
||||
name: photo.name,
|
||||
size: fileSize,
|
||||
@@ -247,9 +332,18 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
}
|
||||
}
|
||||
|
||||
// Esecuzione parallela di tutti i documenti e foto
|
||||
await Future.wait(uploadTasks);
|
||||
emit(state.copyWith(status: AttachmentsStatus.success));
|
||||
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.success,
|
||||
remoteFiles: updatedFiles,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -268,7 +362,22 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
currentContextType: state.parentType,
|
||||
bucket: _getBucketForParentType,
|
||||
);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
|
||||
if (state.parentId != null) {
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
selectedFiles: [],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(status: AttachmentsStatus.failure, error: e.toString()),
|
||||
@@ -293,7 +402,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
SelectAllAttachmentsEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
// Prendiamo TUTTI i file (locali e remoti) e li buttiamo nei selezionati
|
||||
emit(state.copyWith(selectedFiles: state.allFiles));
|
||||
}
|
||||
|
||||
@@ -301,7 +409,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
ClearAttachmentSelectionEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
// Svuotiamo brutalmente la lista
|
||||
emit(state.copyWith(selectedFiles: []));
|
||||
}
|
||||
|
||||
@@ -311,38 +418,36 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
) async {
|
||||
if (state.selectedFiles.isEmpty) return;
|
||||
|
||||
// BIVIO 1: PRATICA/TICKET NON ANCORA SALVATA (Modalità Locale)
|
||||
if (state.parentId == null) {
|
||||
final updatedLocalFiles = state.localFiles.map((file) {
|
||||
if (state.selectedFiles.contains(file)) {
|
||||
// Assegniamo dinamicamente l'ID in base all'entità scelta
|
||||
switch (event.targetType) {
|
||||
case AttachmentParentType.customer:
|
||||
return file.copyWith(customerId: event.targetId);
|
||||
case AttachmentParentType.ticket:
|
||||
return file.copyWith(ticketId: event.targetId);
|
||||
case AttachmentParentType.operation:
|
||||
return file.copyWith(operationId: event.targetId);
|
||||
case AttachmentParentType.shippingDocument:
|
||||
return file.copyWith(shippingDocumentId: event.targetId);
|
||||
case AttachmentParentType.note:
|
||||
return file.copyWith(noteId: event.targetId);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.map((file) {
|
||||
if (state.selectedFiles.contains(file)) {
|
||||
switch (event.targetType) {
|
||||
case AttachmentParentType.customer:
|
||||
return file.copyWith(customerId: event.targetId);
|
||||
case AttachmentParentType.ticket:
|
||||
return file.copyWith(ticketId: event.targetId);
|
||||
case AttachmentParentType.operation:
|
||||
return file.copyWith(operationId: event.targetId);
|
||||
case AttachmentParentType.shippingDocument:
|
||||
return file.copyWith(shippingDocumentId: event.targetId);
|
||||
case AttachmentParentType.note:
|
||||
return file.copyWith(noteId: event.targetId);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}).toList();
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
localFiles: updatedLocalFiles,
|
||||
selectedFiles: [], // Svuotiamo la selezione
|
||||
selectedFiles: [],
|
||||
status: AttachmentsStatus.ready,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 2: PRATICA/TICKET ESISTENTE (Modalità Remota su DB)
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
try {
|
||||
final List<Future<void>> linkTasks = [];
|
||||
@@ -361,8 +466,17 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
|
||||
await Future.wait(linkTasks);
|
||||
|
||||
// Lo stream aggiornerà automaticamente la UI
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: []));
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
selectedFiles: [],
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -377,23 +491,35 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
RenameAttachmentEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
// BIVIO 1: File Locale (Bozza)
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(name: event.newName);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(name: event.newName);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
return;
|
||||
}
|
||||
|
||||
// BIVIO 2: File Remoto (Salvato su DB)
|
||||
emit(state.copyWith(status: AttachmentsStatus.loading));
|
||||
try {
|
||||
await _repository.renameAttachment(event.file.id!, event.newName);
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
if (state.parentId != null) {
|
||||
final updatedFiles = await _repository.getFiles(
|
||||
state.parentId!,
|
||||
state.parentType,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: AttachmentsStatus.ready,
|
||||
remoteFiles: updatedFiles,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(state.copyWith(status: AttachmentsStatus.ready));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -409,13 +535,68 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles
|
||||
.where((f) => f != event.file)
|
||||
.toList();
|
||||
final updatedLocalFiles =
|
||||
state.localFiles.where((f) => f != event.file).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _onUpdateAttachmentViewMode(
|
||||
UpdateAttachmentViewModeEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) async {
|
||||
if (event.file.localBytes != null) {
|
||||
final updatedLocalFiles = state.localFiles.map((f) {
|
||||
if (f == event.file) {
|
||||
return f.copyWith(viewMode: event.viewMode);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(localFiles: updatedLocalFiles));
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.file.id == null) return;
|
||||
|
||||
try {
|
||||
final updatedRemoteFiles = state.remoteFiles.map((f) {
|
||||
if (f.id == event.file.id) {
|
||||
return f.copyWith(viewMode: event.viewMode);
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
emit(state.copyWith(remoteFiles: updatedRemoteFiles));
|
||||
|
||||
await _repository.updateAttachmentViewMode(event.file.id!, event.viewMode);
|
||||
} catch (e) {
|
||||
debugPrint("Errore aggiornamento viewMode in DB: $e");
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _onAttachmentUpdated(
|
||||
AttachmentUpdatedEvent event,
|
||||
Emitter<AttachmentsState> emit,
|
||||
) {
|
||||
final updatedRemote = state.remoteFiles.map((f) {
|
||||
if (f.id == event.file.id) {
|
||||
return event.file;
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
|
||||
final updatedLocal = state.localFiles.map((f) {
|
||||
if (f.id == event.file.id || (f.id == null && f.name == event.file.name)) {
|
||||
return event.file;
|
||||
}
|
||||
return f;
|
||||
}).toList();
|
||||
|
||||
emit(state.copyWith(
|
||||
remoteFiles: updatedRemote,
|
||||
localFiles: updatedLocal,
|
||||
));
|
||||
}
|
||||
|
||||
Bucket get _getBucketForParentType {
|
||||
switch (state.parentType) {
|
||||
case AttachmentParentType.customer:
|
||||
|
||||
@@ -71,3 +71,28 @@ class DeleteSpecificAttachmentEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
const DeleteSpecificAttachmentEvent(this.file);
|
||||
}
|
||||
|
||||
class RemoteAttachmentsUpdatedEvent extends AttachmentsEvent {
|
||||
final List<AttachmentModel> files;
|
||||
const RemoteAttachmentsUpdatedEvent(this.files);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [files];
|
||||
}
|
||||
|
||||
class UpdateAttachmentViewModeEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
final AttachmentViewMode viewMode;
|
||||
const UpdateAttachmentViewModeEvent(this.file, this.viewMode);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [file, viewMode];
|
||||
}
|
||||
|
||||
class AttachmentUpdatedEvent extends AttachmentsEvent {
|
||||
final AttachmentModel file;
|
||||
const AttachmentUpdatedEvent(this.file);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [file];
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'dart:typed_data';
|
||||
import 'dart:io';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
|
||||
@@ -47,6 +49,28 @@ class AttachmentsRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// RECUPERA I FILE IN MODALITÀ REST (Immediato e affidabile)
|
||||
Future<List<AttachmentModel>> getFiles(
|
||||
String parentId,
|
||||
AttachmentParentType parentType,
|
||||
) async {
|
||||
try {
|
||||
final columnName = _getColumnNameForParent(parentType);
|
||||
|
||||
final response = await _supabase
|
||||
.from(Tables.attachments)
|
||||
.select()
|
||||
.eq(columnName, parentId)
|
||||
.order('created_at', ascending: true);
|
||||
|
||||
return (response as List)
|
||||
.map((map) => AttachmentModel.fromMap(map as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception("Impossibile recuperare gli allegati dal DB: $e");
|
||||
}
|
||||
}
|
||||
|
||||
/// RECUPERA I FILE IN TEMPO REALE
|
||||
Stream<List<AttachmentModel>> getFilesStream(
|
||||
String parentId,
|
||||
@@ -75,7 +99,6 @@ class AttachmentsRepository {
|
||||
String? rawFileName, // Alternativa: nome del file
|
||||
}) async {
|
||||
// 🛡️ L'ASSERT NINJA: O c'è il pickedFile, o ci sono i byte e il nome.
|
||||
// L'assert funziona solo in debug, ma è perfetto per beccare subito errori di chiamata!
|
||||
assert(
|
||||
pickedFile != null || (rawBytes != null && rawFileName != null),
|
||||
'Devi passare o un PlatformFile, oppure rawBytes e rawFileName!',
|
||||
@@ -88,25 +111,35 @@ class AttachmentsRepository {
|
||||
final int finalFileSize;
|
||||
|
||||
if (pickedFile != null) {
|
||||
if (pickedFile.bytes == null) {
|
||||
Uint8List? fileBytes = pickedFile.bytes;
|
||||
// Se su Desktop i bytes sono nulli ma abbiamo il path, leggiamo direttamente da disco
|
||||
if (fileBytes == null && pickedFile.path != null && !kIsWeb) {
|
||||
try {
|
||||
final f = File(pickedFile.path!);
|
||||
if (f.existsSync()) {
|
||||
fileBytes = f.readAsBytesSync();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (fileBytes == null) {
|
||||
throw Exception(
|
||||
"I bytes del file sono vuoti! Ricarica la pagina senza cache.",
|
||||
);
|
||||
}
|
||||
finalBytes = pickedFile.bytes!;
|
||||
finalBytes = fileBytes;
|
||||
finalFileName = pickedFile.name;
|
||||
finalFileSize = pickedFile.size;
|
||||
finalFileSize = pickedFile.size > 0 ? pickedFile.size : finalBytes.length;
|
||||
} else {
|
||||
// Se pickedFile è null, grazie all'assert sappiamo che questi non lo sono
|
||||
finalBytes = rawBytes!;
|
||||
finalFileName = rawFileName!;
|
||||
finalFileSize = finalBytes.length; // Calcoliamo la size dai byte reali
|
||||
finalFileSize = finalBytes.length;
|
||||
}
|
||||
|
||||
// 2. Estraiamo l'estensione e puliamo il nome
|
||||
final extension = finalFileName.contains('.')
|
||||
? finalFileName.split('.').last
|
||||
: ''; // Fallback se il file non ha estensione
|
||||
: '';
|
||||
|
||||
final cleanName = finalFileName
|
||||
.replaceAll(RegExp(r'[^\w\s\.-]'), '')
|
||||
@@ -123,7 +156,10 @@ class AttachmentsRepository {
|
||||
.uploadBinary(
|
||||
storagePath,
|
||||
finalBytes,
|
||||
fileOptions: FileOptions(contentType: _guessContentType(extension)),
|
||||
fileOptions: FileOptions(
|
||||
contentType: _guessContentType(extension),
|
||||
upsert: true,
|
||||
),
|
||||
);
|
||||
|
||||
// 5. Creiamo la mappa per il DB dinamicamente
|
||||
@@ -185,10 +221,17 @@ class AttachmentsRepository {
|
||||
// B. Nessuno usa più questo file! ELIMINAZIONE FISICA TOTALE.
|
||||
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
|
||||
|
||||
if (file.storagePath != null) {
|
||||
await _supabase.storage.from(bucket.value).remove([
|
||||
final pathsToRemove = <String>[
|
||||
if (file.storagePath != null && file.storagePath!.isNotEmpty)
|
||||
file.storagePath!,
|
||||
]);
|
||||
if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty)
|
||||
file.thumbnailPath!,
|
||||
if (file.croppedStoragePath != null &&
|
||||
file.croppedStoragePath!.isNotEmpty)
|
||||
file.croppedStoragePath!,
|
||||
];
|
||||
if (pathsToRemove.isNotEmpty) {
|
||||
await _supabase.storage.from(bucket.value).remove(pathsToRemove);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,7 +259,6 @@ class AttachmentsRepository {
|
||||
required String targetId,
|
||||
}) async {
|
||||
try {
|
||||
// Facciamo un semplice UPDATE aggiungendo l'ID nella colonna giusta
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({targetType.dbColumn: targetId})
|
||||
@@ -226,9 +268,107 @@ class AttachmentsRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// AGGIORNA LA MODALITÀ DI VISUALIZZAZIONE PREFERITA (cropped / original)
|
||||
Future<void> updateAttachmentViewMode(
|
||||
String fileId,
|
||||
AttachmentViewMode viewMode,
|
||||
) async {
|
||||
try {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'view_mode': viewMode.value})
|
||||
.eq('id', fileId);
|
||||
} catch (e) {
|
||||
throw Exception(
|
||||
"Errore nell'aggiornamento della modalità di visualizzazione: $e",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Salva la rotazione permanente del file originale aggiornando storage_path con un nuovo timestamp.
|
||||
/// Questo farà scattare il trigger Postgres per il worker Python (autocrop e thumbnail).
|
||||
Future<AttachmentModel> rotateAttachment({
|
||||
required AttachmentModel attachment,
|
||||
required int quarterTurns,
|
||||
required Bucket bucket,
|
||||
}) async {
|
||||
final turns = quarterTurns % 4;
|
||||
if (turns == 0) return attachment;
|
||||
if (attachment.storagePath == null || attachment.storagePath!.isEmpty) {
|
||||
throw Exception("Impossibile ruotare: storagePath mancante.");
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Recuperiamo i byte originali
|
||||
Uint8List originalBytes;
|
||||
if (attachment.localBytes != null) {
|
||||
originalBytes = attachment.localBytes!;
|
||||
} else {
|
||||
originalBytes = await downloadAttachmentBytes(
|
||||
storagePath: attachment.storagePath!,
|
||||
bucket: bucket,
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Ruotiamo fisicamente i pixel
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
originalBytes,
|
||||
quarterTurns: turns,
|
||||
extension: attachment.extension,
|
||||
);
|
||||
|
||||
// 3. Generiamo il nuovo storagePath con un nuovo timestamp per evitare cache e triggerare l'update
|
||||
final oldPath = attachment.storagePath!;
|
||||
final lastSlash = oldPath.lastIndexOf('/');
|
||||
final dir = lastSlash != -1 ? oldPath.substring(0, lastSlash) : '';
|
||||
final filename =
|
||||
lastSlash != -1 ? oldPath.substring(lastSlash + 1) : oldPath;
|
||||
final nameWithoutTimestamp =
|
||||
filename.replaceFirst(RegExp(r'^\d+_'), '');
|
||||
final newTimestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final newStoragePath = dir.isNotEmpty
|
||||
? '$dir/${newTimestamp}_$nameWithoutTimestamp'
|
||||
: '${newTimestamp}_$nameWithoutTimestamp';
|
||||
|
||||
// 4. Carichiamo il nuovo file ruotato nello storage
|
||||
await _supabase.storage
|
||||
.from(bucket.value)
|
||||
.uploadBinary(
|
||||
newStoragePath,
|
||||
rotatedBytes,
|
||||
fileOptions: FileOptions(
|
||||
contentType: _guessContentType(attachment.extension),
|
||||
upsert: true,
|
||||
),
|
||||
);
|
||||
|
||||
// 5. Aggiorniamo il record su Postgres (triggera il worker Python)
|
||||
final updateData = {
|
||||
'storage_path': newStoragePath,
|
||||
'file_size': rotatedBytes.length,
|
||||
};
|
||||
|
||||
if (attachment.id != null) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update(updateData)
|
||||
.eq('id', attachment.id!);
|
||||
}
|
||||
|
||||
// 6. Restituiamo il modello aggiornato
|
||||
return attachment.copyWith(
|
||||
storagePath: newStoragePath,
|
||||
fileSize: rotatedBytes.length,
|
||||
localBytes: rotatedBytes,
|
||||
);
|
||||
} catch (e) {
|
||||
throw Exception("Errore durante il salvataggio della rotazione: $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper per indovinare il content-type base
|
||||
String _guessContentType(String extension) {
|
||||
switch (extension.toLowerCase()) {
|
||||
switch (extension.toLowerCase().replaceAll('.', '')) {
|
||||
case 'pdf':
|
||||
return 'application/pdf';
|
||||
case 'png':
|
||||
@@ -236,6 +376,28 @@ class AttachmentsRepository {
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return 'image/jpeg';
|
||||
case 'webp':
|
||||
return 'image/webp';
|
||||
case 'heic':
|
||||
return 'image/heic';
|
||||
case 'heif':
|
||||
return 'image/heif';
|
||||
case 'gif':
|
||||
return 'image/gif';
|
||||
case 'svg':
|
||||
return 'image/svg+xml';
|
||||
case 'txt':
|
||||
return 'text/plain';
|
||||
case 'csv':
|
||||
return 'text/csv';
|
||||
case 'doc':
|
||||
return 'application/msword';
|
||||
case 'docx':
|
||||
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
case 'xls':
|
||||
return 'application/vnd.ms-excel';
|
||||
case 'xlsx':
|
||||
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
|
||||
@@ -2,6 +2,22 @@ import 'dart:typed_data';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
enum AttachmentViewMode {
|
||||
cropped('cropped'),
|
||||
original('original');
|
||||
|
||||
final String value;
|
||||
const AttachmentViewMode(this.value);
|
||||
|
||||
static AttachmentViewMode? fromString(String? val) {
|
||||
if (val == null) return null;
|
||||
final clean = val.trim().toLowerCase();
|
||||
if (clean == 'cropped') return AttachmentViewMode.cropped;
|
||||
if (clean == 'original') return AttachmentViewMode.original;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class AttachmentModel extends Equatable {
|
||||
final String? id;
|
||||
final DateTime? createdAt;
|
||||
@@ -13,6 +29,9 @@ class AttachmentModel extends Equatable {
|
||||
final String name;
|
||||
final String extension;
|
||||
final String? storagePath;
|
||||
final String? thumbnailPath;
|
||||
final String? croppedStoragePath;
|
||||
final AttachmentViewMode? viewMode;
|
||||
final int fileSize;
|
||||
final Uint8List? localBytes;
|
||||
final String companyId;
|
||||
@@ -28,11 +47,21 @@ class AttachmentModel extends Equatable {
|
||||
required this.name,
|
||||
required this.extension,
|
||||
this.storagePath,
|
||||
this.thumbnailPath,
|
||||
this.croppedStoragePath,
|
||||
this.viewMode,
|
||||
required this.fileSize,
|
||||
this.localBytes,
|
||||
required this.companyId,
|
||||
});
|
||||
|
||||
factory AttachmentModel.empty() => const AttachmentModel(
|
||||
name: '',
|
||||
extension: '',
|
||||
fileSize: 0,
|
||||
companyId: '',
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
@@ -45,6 +74,9 @@ class AttachmentModel extends Equatable {
|
||||
name,
|
||||
extension,
|
||||
storagePath,
|
||||
thumbnailPath,
|
||||
croppedStoragePath,
|
||||
viewMode,
|
||||
fileSize,
|
||||
localBytes,
|
||||
companyId,
|
||||
@@ -54,6 +86,25 @@ class AttachmentModel extends Equatable {
|
||||
|
||||
bool get isPdf => extension.toLowerCase().replaceAll('.', '') == 'pdf';
|
||||
|
||||
String? get effectiveStoragePath {
|
||||
if (viewMode == AttachmentViewMode.cropped) {
|
||||
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
|
||||
return croppedStoragePath;
|
||||
}
|
||||
return storagePath;
|
||||
} else if (viewMode == AttachmentViewMode.original) {
|
||||
if (storagePath != null && storagePath!.isNotEmpty) {
|
||||
return storagePath;
|
||||
}
|
||||
return croppedStoragePath;
|
||||
}
|
||||
// Default fallback quando viewMode non è specificato
|
||||
if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) {
|
||||
return croppedStoragePath;
|
||||
}
|
||||
return storagePath;
|
||||
}
|
||||
|
||||
String get sizeFormatted {
|
||||
if (fileSize <= 0) return "0 B";
|
||||
const suffixes = ["B", "KB", "MB", "GB", "TB"];
|
||||
@@ -74,6 +125,9 @@ class AttachmentModel extends Equatable {
|
||||
String? name,
|
||||
String? extension,
|
||||
String? storagePath,
|
||||
String? thumbnailPath,
|
||||
String? croppedStoragePath,
|
||||
AttachmentViewMode? viewMode,
|
||||
int? fileSize,
|
||||
Uint8List? localBytes,
|
||||
String? companyId,
|
||||
@@ -88,6 +142,9 @@ class AttachmentModel extends Equatable {
|
||||
name: name ?? this.name,
|
||||
extension: extension ?? this.extension,
|
||||
storagePath: storagePath ?? this.storagePath,
|
||||
thumbnailPath: thumbnailPath ?? this.thumbnailPath,
|
||||
croppedStoragePath: croppedStoragePath ?? this.croppedStoragePath,
|
||||
viewMode: viewMode ?? this.viewMode,
|
||||
fileSize: fileSize ?? this.fileSize,
|
||||
localBytes: localBytes ?? this.localBytes,
|
||||
companyId: companyId ?? this.companyId,
|
||||
@@ -107,6 +164,9 @@ class AttachmentModel extends Equatable {
|
||||
name: map['name'] as String,
|
||||
extension: map['extension'] as String,
|
||||
storagePath: map['storage_path'] as String?,
|
||||
thumbnailPath: map['thumbnail_path'] as String?,
|
||||
croppedStoragePath: map['cropped_storage_path'] as String?,
|
||||
viewMode: AttachmentViewMode.fromString(map['view_mode'] as String?),
|
||||
fileSize: map['file_size'] is int
|
||||
? map['file_size']
|
||||
: int.tryParse(map['file_size']?.toString() ?? '0') ?? 0,
|
||||
@@ -127,6 +187,9 @@ class AttachmentModel extends Equatable {
|
||||
'note_id': noteId,
|
||||
'file_size': fileSize,
|
||||
'company_id': companyId,
|
||||
'thumbnail_path': thumbnailPath,
|
||||
'cropped_storage_path': croppedStoragePath,
|
||||
'view_mode': viewMode?.value,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:flux/core/utils/functions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:pdfx/pdfx.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:pdfrx/pdfrx.dart';
|
||||
import 'package:internet_file/internet_file.dart';
|
||||
|
||||
class AttachmentViewerScreen extends StatefulWidget {
|
||||
@@ -13,6 +21,8 @@ class AttachmentViewerScreen extends StatefulWidget {
|
||||
final Function(AttachmentModel attachment, String newName)? onRenameAttachment;
|
||||
final VoidCallback? onDelete;
|
||||
final Function(AttachmentModel attachment)? onDeleteAttachment;
|
||||
final Function(AttachmentModel attachment, AttachmentViewMode viewMode)? onViewModeChanged;
|
||||
final Function(AttachmentModel attachment)? onAttachmentUpdated;
|
||||
|
||||
const AttachmentViewerScreen({
|
||||
super.key,
|
||||
@@ -23,6 +33,8 @@ class AttachmentViewerScreen extends StatefulWidget {
|
||||
this.onRenameAttachment,
|
||||
this.onDelete,
|
||||
this.onDeleteAttachment,
|
||||
this.onViewModeChanged,
|
||||
this.onAttachmentUpdated,
|
||||
}) : assert(
|
||||
attachment != null || (attachments != null && attachments.length > 0),
|
||||
'Devi fornire un allegato o una lista di allegati non vuota.',
|
||||
@@ -37,11 +49,14 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
late int _currentIndex;
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
PdfControllerPinch? _pdfController;
|
||||
bool _isLoading = true;
|
||||
bool _isSavingRotation = false;
|
||||
String? _errorMessage;
|
||||
Uint8List? _fileBytes;
|
||||
int _loadToken = 0;
|
||||
int _rotationTurns = 0;
|
||||
bool _showCropped = true;
|
||||
final Map<String, Uint8List> _bytesCache = {};
|
||||
|
||||
AttachmentModel get _currentAttachment => _items[_currentIndex];
|
||||
bool get isPdf =>
|
||||
@@ -50,6 +65,33 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
bool get canGoPrevious => _currentIndex > 0;
|
||||
bool get canGoNext => _currentIndex < _items.length - 1;
|
||||
|
||||
bool get _hasCropped =>
|
||||
_currentAttachment.croppedStoragePath != null &&
|
||||
_currentAttachment.croppedStoragePath!.isNotEmpty;
|
||||
bool get _hasOriginal =>
|
||||
_currentAttachment.storagePath != null &&
|
||||
_currentAttachment.storagePath!.isNotEmpty;
|
||||
bool get canToggleCrop => !isPdf && _hasCropped && _hasOriginal;
|
||||
|
||||
String? get _activeStoragePath {
|
||||
final item = _currentAttachment;
|
||||
if (_showCropped && _hasCropped) {
|
||||
return item.croppedStoragePath;
|
||||
}
|
||||
return item.storagePath;
|
||||
}
|
||||
|
||||
bool _computeInitialShowCropped(AttachmentModel attachment) {
|
||||
if (attachment.viewMode == AttachmentViewMode.original) {
|
||||
return false;
|
||||
}
|
||||
if (attachment.viewMode == AttachmentViewMode.cropped) {
|
||||
return true;
|
||||
}
|
||||
return attachment.croppedStoragePath != null &&
|
||||
attachment.croppedStoragePath!.isNotEmpty;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -64,6 +106,10 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
_currentIndex = 0;
|
||||
}
|
||||
|
||||
if (_items.isNotEmpty) {
|
||||
_showCropped = _computeInitialShowCropped(_currentAttachment);
|
||||
}
|
||||
|
||||
_loadFile();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@@ -76,7 +122,6 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
@override
|
||||
void dispose() {
|
||||
_focusNode.dispose();
|
||||
_pdfController?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -92,17 +137,116 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
|
||||
void _changeFile(int newIndex) {
|
||||
if (newIndex < 0 || newIndex >= _items.length) return;
|
||||
_pdfController?.dispose();
|
||||
_pdfController = null;
|
||||
final newAttachment = _items[newIndex];
|
||||
setState(() {
|
||||
_currentIndex = newIndex;
|
||||
_showCropped = _computeInitialShowCropped(newAttachment);
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
_fileBytes = null;
|
||||
_rotationTurns = 0;
|
||||
});
|
||||
_loadFile();
|
||||
}
|
||||
|
||||
void _toggleCropView() {
|
||||
if (!canToggleCrop) return;
|
||||
final nextShowCropped = !_showCropped;
|
||||
final nextMode = nextShowCropped
|
||||
? AttachmentViewMode.cropped
|
||||
: AttachmentViewMode.original;
|
||||
final nextPath = nextShowCropped
|
||||
? _currentAttachment.croppedStoragePath
|
||||
: _currentAttachment.storagePath;
|
||||
|
||||
final updatedAttachment = _currentAttachment.copyWith(viewMode: nextMode);
|
||||
|
||||
setState(() {
|
||||
_showCropped = nextShowCropped;
|
||||
_items[_currentIndex] = updatedAttachment;
|
||||
_rotationTurns = 0;
|
||||
});
|
||||
|
||||
if (widget.onViewModeChanged != null) {
|
||||
widget.onViewModeChanged!(updatedAttachment, nextMode);
|
||||
} else if (updatedAttachment.id != null) {
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
repository.updateAttachmentViewMode(updatedAttachment.id!, nextMode);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (nextPath != null && _bytesCache.containsKey(nextPath)) {
|
||||
setState(() {
|
||||
_fileBytes = _bytesCache[nextPath];
|
||||
_isLoading = false;
|
||||
_errorMessage = null;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
_loadFile();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _saveRotation() async {
|
||||
final turns = _rotationTurns % 4;
|
||||
if (turns == 0 || _isSavingRotation) return;
|
||||
|
||||
setState(() {
|
||||
_isSavingRotation = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final repository = GetIt.I.get<AttachmentsRepository>();
|
||||
final updated = await repository.rotateAttachment(
|
||||
attachment: _currentAttachment,
|
||||
quarterTurns: turns,
|
||||
bucket: Bucket.documents,
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
_items[_currentIndex] = updated;
|
||||
_rotationTurns = 0;
|
||||
_showCropped = false; // Mostra l'originale ruotato appena salvato
|
||||
_isSavingRotation = false;
|
||||
if (updated.storagePath != null && updated.localBytes != null) {
|
||||
_bytesCache[updated.storagePath!] = updated.localBytes!;
|
||||
}
|
||||
if (updated.localBytes != null) {
|
||||
_fileBytes = updated.localBytes;
|
||||
}
|
||||
});
|
||||
|
||||
widget.onAttachmentUpdated?.call(updated);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Rotazione salvata! Il server aggiornerà ritaglio e anteprima.',
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
duration: Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isSavingRotation = false;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Errore durante il salvataggio della rotazione: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyDownEvent) {
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
|
||||
@@ -128,26 +272,51 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
Uint8List? bytes;
|
||||
if (item.localBytes != null) {
|
||||
bytes = item.localBytes;
|
||||
} else if (item.storagePath != null &&
|
||||
item.storagePath!.isNotEmpty) {
|
||||
final signedUrl = await getSignedUrl(item.storagePath!);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
final path = _activeStoragePath;
|
||||
if (path != null && path.isNotEmpty) {
|
||||
if (_bytesCache.containsKey(path)) {
|
||||
bytes = _bytesCache[path];
|
||||
} else {
|
||||
try {
|
||||
final signedUrl = await getSignedUrl(path);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
} catch (e) {
|
||||
// Se fallisce il ritaglio e abbiamo l'originale, proviamo l'originale come fallback
|
||||
if (_showCropped && _hasOriginal && item.storagePath != path) {
|
||||
final signedUrl = await getSignedUrl(item.storagePath!);
|
||||
bytes = await InternetFile.get(signedUrl);
|
||||
_showCropped = false;
|
||||
} else {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isPdf) {
|
||||
bytes = ImageUtils.normalizeOrientation(
|
||||
bytes,
|
||||
extension: item.extension,
|
||||
);
|
||||
}
|
||||
|
||||
_bytesCache[path] = bytes;
|
||||
}
|
||||
} else {
|
||||
throw Exception("Nessun documento trovato o byte mancanti.");
|
||||
}
|
||||
}
|
||||
|
||||
if (token != _loadToken || !mounted) return;
|
||||
|
||||
PdfControllerPinch? controller;
|
||||
if (isPdf && bytes != null) {
|
||||
controller = PdfControllerPinch(
|
||||
document: PdfDocument.openData(bytes),
|
||||
if (bytes != null && !isPdf && item.localBytes != null) {
|
||||
bytes = ImageUtils.normalizeOrientation(
|
||||
bytes,
|
||||
extension: item.extension,
|
||||
);
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_fileBytes = bytes;
|
||||
_pdfController = controller;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -253,6 +422,56 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _downloadCurrentFile() async {
|
||||
final bytes = _fileBytes;
|
||||
if (bytes == null || bytes.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('File non ancora caricato o non disponibile.'),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
String fullName = _currentAttachment.name;
|
||||
final ext = _currentAttachment.extension.toLowerCase().replaceAll('.', '');
|
||||
if (_showCropped && canToggleCrop) {
|
||||
fullName = '${fullName}_cropped';
|
||||
}
|
||||
if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) {
|
||||
fullName = '$fullName.$ext';
|
||||
}
|
||||
|
||||
if (kIsWeb) {
|
||||
final blob = html.Blob([bytes]);
|
||||
final url = html.Url.createObjectUrlFromBlob(blob);
|
||||
html.AnchorElement(href: url)
|
||||
..setAttribute('download', fullName)
|
||||
..click();
|
||||
html.Url.revokeObjectUrl(url);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Download avviato: $fullName')),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
final savePath = await FilePicker.saveFile(
|
||||
dialogTitle: 'Salva file',
|
||||
fileName: fullName,
|
||||
bytes: bytes,
|
||||
);
|
||||
if (savePath != null) {
|
||||
final targetFile = File(savePath);
|
||||
await targetFile.writeAsBytes(bytes);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('File salvato in: $savePath')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Focus(
|
||||
@@ -273,14 +492,111 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
style: const TextStyle(fontSize: 16),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (hasMultipleFiles)
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (hasMultipleFiles) ...[
|
||||
Text(
|
||||
'${_currentIndex + 1} di ${_items.length}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
if (canToggleCrop)
|
||||
const Text(
|
||||
' • ',
|
||||
style: TextStyle(fontSize: 12, color: Colors.white70),
|
||||
),
|
||||
],
|
||||
if (canToggleCrop)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: _showCropped
|
||||
? Colors.amber.withValues(alpha: 0.2)
|
||||
: Colors.white10,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(
|
||||
color: _showCropped
|
||||
? Colors.amberAccent
|
||||
: Colors.white30,
|
||||
width: 0.8,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
_showCropped ? 'Ritaglio automatico' : 'Originale',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: _showCropped
|
||||
? Colors.amberAccent
|
||||
: Colors.white70,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
if (canToggleCrop)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
_showCropped
|
||||
? Icons.photo_size_select_actual_outlined
|
||||
: Icons.crop,
|
||||
color: _showCropped ? Colors.amberAccent : Colors.white,
|
||||
),
|
||||
tooltip: _showCropped
|
||||
? 'Passa alla foto originale'
|
||||
: 'Passa al ritaglio automatico',
|
||||
onPressed: _toggleCropView,
|
||||
),
|
||||
if (!isPdf)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.rotate_right),
|
||||
tooltip: 'Ruota',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_rotationTurns = (_rotationTurns + 1) % 4;
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!isPdf && _rotationTurns % 4 != 0)
|
||||
_isSavingRotation
|
||||
? const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 10),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
|
||||
child: FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.green.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: const Icon(Icons.check, size: 16),
|
||||
label: const Text(
|
||||
'Salva',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
onPressed: _saveRotation,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
tooltip: 'Scarica',
|
||||
onPressed: _downloadCurrentFile,
|
||||
),
|
||||
if (widget.onRename != null || widget.onRenameAttachment != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
@@ -357,12 +673,24 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
if (isPdf && _pdfController != null) {
|
||||
return PdfViewPinch(controller: _pdfController!);
|
||||
if (isPdf && _fileBytes != null) {
|
||||
return PdfViewer.data(
|
||||
_fileBytes!,
|
||||
sourceName: '${_currentAttachment.id}_${_currentAttachment.name}.pdf',
|
||||
params: const PdfViewerParams(
|
||||
backgroundColor: Colors.transparent,
|
||||
enableKeyboardNavigation: false,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return InteractiveViewer(
|
||||
maxScale: 5.0,
|
||||
child: Center(child: Image.memory(_fileBytes!)),
|
||||
child: Center(
|
||||
child: RotatedBox(
|
||||
quarterTurns: _rotationTurns,
|
||||
child: Image.memory(_fileBytes!),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,7 +352,9 @@ class _FileCard extends StatelessWidget {
|
||||
height: MediaQuery.of(context).size.height * 0.8,
|
||||
child: file.isPdf
|
||||
? PdfViewerWidget(storagePath: file.storagePath)
|
||||
: ImageViewerWidget(storagePath: file.storagePath),
|
||||
: ImageViewerWidget(
|
||||
storagePath: file.effectiveStoragePath,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import 'dashboard_daily_ricontatti_state.dart';
|
||||
|
||||
class DashboardDailyRicontattiCubit extends Cubit<DashboardDailyRicontattiState> {
|
||||
final OperationsRepository _operationsRepository;
|
||||
final StaffRepository _staffRepository;
|
||||
|
||||
String? companyId;
|
||||
String? storeId;
|
||||
|
||||
StreamSubscription<void>? _operationsSubscription;
|
||||
Timer? _pollingTimer;
|
||||
|
||||
DashboardDailyRicontattiCubit({
|
||||
this.companyId,
|
||||
this.storeId,
|
||||
OperationsRepository? operationsRepository,
|
||||
StaffRepository? staffRepository,
|
||||
}) : _operationsRepository =
|
||||
operationsRepository ?? GetIt.I.get<OperationsRepository>(),
|
||||
_staffRepository = staffRepository ?? GetIt.I.get<StaffRepository>(),
|
||||
super(
|
||||
DashboardDailyRicontattiState(
|
||||
date: DateTime.now(),
|
||||
),
|
||||
);
|
||||
|
||||
void updateContext({
|
||||
String? newCompanyId,
|
||||
String? newStoreId,
|
||||
}) {
|
||||
bool changed = false;
|
||||
if (newCompanyId != null && newCompanyId != companyId) {
|
||||
companyId = newCompanyId;
|
||||
changed = true;
|
||||
}
|
||||
if (newStoreId != null && newStoreId != storeId) {
|
||||
storeId = newStoreId;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
void startListening() {
|
||||
emit(state.copyWith(status: DashboardDailyRicontattiStatus.loading));
|
||||
stopListening();
|
||||
|
||||
_loadDailyRicontattiSilently();
|
||||
|
||||
// 1. Ascolto notifiche di creazione/modifica operazioni in real-time
|
||||
_operationsSubscription =
|
||||
_operationsRepository.onOperationsChanged.listen((_) {
|
||||
_loadDailyRicontattiSilently();
|
||||
});
|
||||
|
||||
// 2. Polling periodico ogni 30 secondi
|
||||
_pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
_loadDailyRicontattiSilently();
|
||||
});
|
||||
}
|
||||
|
||||
void stopListening() {
|
||||
_operationsSubscription?.cancel();
|
||||
_operationsSubscription = null;
|
||||
_pollingTimer?.cancel();
|
||||
_pollingTimer = null;
|
||||
}
|
||||
|
||||
void refresh() {
|
||||
_loadDailyRicontattiSilently();
|
||||
}
|
||||
|
||||
Future<void> _loadDailyRicontattiSilently() async {
|
||||
if (companyId == null || storeId == null) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.initial,
|
||||
summaries: [],
|
||||
totalRicontattiToday: 0,
|
||||
totalRicontattiMonth: 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final now = DateTime.now();
|
||||
final todayStart = DateTime(now.year, now.month, now.day, 0, 0, 0);
|
||||
final todayEnd = DateTime(now.year, now.month, now.day, 23, 59, 59, 999);
|
||||
|
||||
// 1. Recupero staff del negozio
|
||||
final allStaff = await _staffRepository.getStaffMembers(
|
||||
companyId!,
|
||||
storeId: storeId,
|
||||
);
|
||||
|
||||
// 1. Escludiamo i collaboratori con qualifica Manager o Tester, o disattivati
|
||||
final Set<String> excludedStaffIds = {};
|
||||
for (final s in allStaff) {
|
||||
if (s.isExcludedFromRicontattiFocus && s.id != null) {
|
||||
excludedStaffIds.add(s.id!);
|
||||
}
|
||||
}
|
||||
|
||||
final activeEligibleStaff = allStaff
|
||||
.where((s) => !s.isExcludedFromRicontattiFocus)
|
||||
.toList();
|
||||
|
||||
// 2. Recupero conteggi mensili per addetto del negozio
|
||||
final monthlyCountsByStaff =
|
||||
await _operationsRepository.getMonthlyRicontattiCountsByStaff(
|
||||
companyId: companyId!,
|
||||
storeId: storeId!,
|
||||
month: now,
|
||||
);
|
||||
|
||||
// 3. Recupero operazioni create oggi nel negozio
|
||||
final paginatedOps = await _operationsRepository.fetchPaginatedOperations(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
dateRange: DateTimeRange(start: todayStart, end: todayEnd),
|
||||
page: 1,
|
||||
itemsPerPage: 150,
|
||||
onlyShowInDashboard: false,
|
||||
);
|
||||
|
||||
// 4. Filtro per tipo Ricontatto
|
||||
final ricontattiOps = paginatedOps.operations.where((op) {
|
||||
return op.details.any((d) => d.type == OperationType.ricontatto);
|
||||
}).toList();
|
||||
|
||||
// 5. Raggruppamento per addetto ammissibile
|
||||
final List<StaffDailyRicontattiSummary> summaries = [];
|
||||
final Set<String> processedStaffIds = Set<String>.from(excludedStaffIds);
|
||||
|
||||
for (final staff in activeEligibleStaff) {
|
||||
final staffId = staff.id ?? '';
|
||||
processedStaffIds.add(staffId);
|
||||
|
||||
final staffOps = ricontattiOps.where((op) => op.staffId == staffId).toList();
|
||||
|
||||
int staffCount = 0;
|
||||
for (final op in staffOps) {
|
||||
final countInOp = op.details.where((d) => d.type == OperationType.ricontatto).length;
|
||||
staffCount += countInOp > 0 ? countInOp : 1;
|
||||
}
|
||||
|
||||
final staffMonthCount = monthlyCountsByStaff[staffId] ?? 0;
|
||||
|
||||
summaries.add(
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: staffId,
|
||||
staffName: staff.name,
|
||||
jobTitle: staff.jobTitle,
|
||||
systemRole: staff.systemRole,
|
||||
count: staffCount,
|
||||
monthCount: staffMonthCount,
|
||||
operations: staffOps,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Verifica se ci sono operazioni attribuite a staff non presente nella lista
|
||||
for (final op in ricontattiOps) {
|
||||
final opStaffId = op.staffId ?? '';
|
||||
if (opStaffId.isNotEmpty && !processedStaffIds.contains(opStaffId)) {
|
||||
processedStaffIds.add(opStaffId);
|
||||
final staffOps = ricontattiOps.where((o) => o.staffId == opStaffId).toList();
|
||||
|
||||
int staffCount = 0;
|
||||
for (final o in staffOps) {
|
||||
final countInOp = o.details.where((d) => d.type == OperationType.ricontatto).length;
|
||||
staffCount += countInOp > 0 ? countInOp : 1;
|
||||
}
|
||||
final staffMonthCount = monthlyCountsByStaff[opStaffId] ?? 0;
|
||||
|
||||
summaries.add(
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: opStaffId,
|
||||
staffName: op.staffDisplayName ?? 'Operatore',
|
||||
count: staffCount,
|
||||
monthCount: staffMonthCount,
|
||||
operations: staffOps,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Calcolo totali coerenti con gli addetti visibili
|
||||
int grandTotal = 0;
|
||||
int grandMonthTotal = 0;
|
||||
for (final s in summaries) {
|
||||
grandTotal += s.count;
|
||||
grandMonthTotal += s.monthCount;
|
||||
}
|
||||
|
||||
// 8. Ordinamento: per numero di ricontatti oggi decrescente, poi per mese decrescente, poi per nome
|
||||
summaries.sort((a, b) {
|
||||
final countCmp = b.count.compareTo(a.count);
|
||||
if (countCmp != 0) return countCmp;
|
||||
final monthCmp = b.monthCount.compareTo(a.monthCount);
|
||||
if (monthCmp != 0) return monthCmp;
|
||||
return a.staffName.toLowerCase().compareTo(b.staffName.toLowerCase());
|
||||
});
|
||||
|
||||
if (isClosed) return;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.success,
|
||||
summaries: summaries,
|
||||
totalRicontattiToday: grandTotal,
|
||||
totalRicontattiMonth: grandMonthTotal,
|
||||
date: now,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} catch (e, stack) {
|
||||
debugPrint('Errore in DashboardDailyRicontattiCubit: $e\n$stack');
|
||||
if (isClosed) return;
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardDailyRicontattiStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
stopListening();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
|
||||
enum DashboardDailyRicontattiStatus { initial, loading, success, failure }
|
||||
|
||||
class DashboardDailyRicontattiState extends Equatable {
|
||||
final DashboardDailyRicontattiStatus status;
|
||||
final List<StaffDailyRicontattiSummary> summaries;
|
||||
final int totalRicontattiToday;
|
||||
final int totalRicontattiMonth;
|
||||
final DateTime date;
|
||||
final String? errorMessage;
|
||||
|
||||
const DashboardDailyRicontattiState({
|
||||
this.status = DashboardDailyRicontattiStatus.initial,
|
||||
this.summaries = const [],
|
||||
this.totalRicontattiToday = 0,
|
||||
this.totalRicontattiMonth = 0,
|
||||
required this.date,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
/// Numero di addetti che hanno raggiunto l'obiettivo (>= 2)
|
||||
int get staffWithGoal => summaries.where((s) => s.hasReachedGoal).length;
|
||||
|
||||
/// Numero di addetti che hanno registrato almeno 1 ricontatto (= 1)
|
||||
int get staffWithOne => summaries.where((s) => s.hasStarted).length;
|
||||
|
||||
/// Numero di addetti a 0
|
||||
int get staffAtZero => summaries.where((s) => s.isZero).length;
|
||||
|
||||
/// Totale addetti monitorati
|
||||
int get activeStaffCount => summaries.length;
|
||||
|
||||
DashboardDailyRicontattiState copyWith({
|
||||
DashboardDailyRicontattiStatus? status,
|
||||
List<StaffDailyRicontattiSummary>? summaries,
|
||||
int? totalRicontattiToday,
|
||||
int? totalRicontattiMonth,
|
||||
DateTime? date,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DashboardDailyRicontattiState(
|
||||
status: status ?? this.status,
|
||||
summaries: summaries ?? this.summaries,
|
||||
totalRicontattiToday:
|
||||
totalRicontattiToday ?? this.totalRicontattiToday,
|
||||
totalRicontattiMonth:
|
||||
totalRicontattiMonth ?? this.totalRicontattiMonth,
|
||||
date: date ?? this.date,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
summaries,
|
||||
totalRicontattiToday,
|
||||
totalRicontattiMonth,
|
||||
date,
|
||||
errorMessage,
|
||||
];
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
/// Modello di riepilogo giornaliero dei ricontatti per singolo addetto.
|
||||
class StaffDailyRicontattiSummary extends Equatable {
|
||||
final String staffId;
|
||||
final String staffName;
|
||||
final String? jobTitle;
|
||||
final SystemRole systemRole;
|
||||
final int count;
|
||||
final int monthCount;
|
||||
final List<OperationModel> operations;
|
||||
|
||||
const StaffDailyRicontattiSummary({
|
||||
required this.staffId,
|
||||
required this.staffName,
|
||||
this.jobTitle,
|
||||
this.systemRole = SystemRole.user,
|
||||
required this.count,
|
||||
this.monthCount = 0,
|
||||
this.operations = const [],
|
||||
});
|
||||
|
||||
/// Ha raggiunto l'obiettivo consigliato (almeno 2 ricontatti al giorno)
|
||||
bool get hasReachedGoal => count >= 2;
|
||||
|
||||
/// Ha iniziato la raccolta (1 ricontatto preso)
|
||||
bool get hasStarted => count == 1;
|
||||
|
||||
/// Non ha ancora registrato alcun ricontatto oggi
|
||||
bool get isZero => count == 0;
|
||||
|
||||
StaffDailyRicontattiSummary copyWith({
|
||||
String? staffId,
|
||||
String? staffName,
|
||||
String? jobTitle,
|
||||
SystemRole? systemRole,
|
||||
int? count,
|
||||
int? monthCount,
|
||||
List<OperationModel>? operations,
|
||||
}) {
|
||||
return StaffDailyRicontattiSummary(
|
||||
staffId: staffId ?? this.staffId,
|
||||
staffName: staffName ?? this.staffName,
|
||||
jobTitle: jobTitle ?? this.jobTitle,
|
||||
systemRole: systemRole ?? this.systemRole,
|
||||
count: count ?? this.count,
|
||||
monthCount: monthCount ?? this.monthCount,
|
||||
operations: operations ?? this.operations,
|
||||
);
|
||||
}
|
||||
|
||||
factory StaffDailyRicontattiSummary.empty() {
|
||||
return const StaffDailyRicontattiSummary(
|
||||
staffId: '',
|
||||
staffName: '',
|
||||
count: 0,
|
||||
monthCount: 0,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
staffId,
|
||||
staffName,
|
||||
jobTitle,
|
||||
systemRole,
|
||||
count,
|
||||
monthCount,
|
||||
operations,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,867 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class DashboardDailyRicontattiCard extends StatelessWidget {
|
||||
const DashboardDailyRicontattiCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Visibile a chi ha qualifica Manager o Titolare (o Admin di sistema)
|
||||
final staff = context.watch<SessionCubit>().state.currentStaffMember;
|
||||
final canView = staff?.canViewRicontattiFocus ?? false;
|
||||
|
||||
if (!canView) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return BlocBuilder<DashboardDailyRicontattiCubit,
|
||||
DashboardDailyRicontattiState>(
|
||||
builder: (context, state) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: Colors.amber.shade600.withValues(alpha: 0.35),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.amber.shade700.withValues(alpha: 0.06),
|
||||
blurRadius: 18,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context, theme, state),
|
||||
Divider(
|
||||
height: 1,
|
||||
color: theme.dividerColor.withValues(alpha: 0.15),
|
||||
),
|
||||
if (state.status == DashboardDailyRicontattiStatus.loading &&
|
||||
state.summaries.isEmpty)
|
||||
_buildLoading(theme)
|
||||
else if (state.status == DashboardDailyRicontattiStatus.failure)
|
||||
_buildError(context, theme, state)
|
||||
else if (state.summaries.isEmpty)
|
||||
_buildEmpty(theme)
|
||||
else ...[
|
||||
_buildOverviewStats(context, theme, state),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(18, 0, 18, 18),
|
||||
child: _buildStaffGrid(context, theme, state.summaries),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(18.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
Colors.amber.shade600,
|
||||
Colors.orange.shade700,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.amber.shade700.withValues(alpha: 0.3),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.event_repeat_rounded,
|
||||
color: Colors.white,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
'FOCUS RICONTATTI DI OGGI',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 3,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'MANAGER',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.amber.shade900,
|
||||
letterSpacing: 0.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
'Raccolta situazioni da ricontattare & bollette (chi sta facendo e chi no)',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Total today & month pill badge
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade500.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Colors.amber.shade600.withValues(alpha: 0.4),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'${state.totalRicontattiToday}',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
'oggi',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.amber.shade800,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'(mese: ${state.totalRicontattiMonth})',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.amber.shade900.withValues(alpha: 0.85),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
IconButton(
|
||||
tooltip: 'Aggiorna ora',
|
||||
icon: const Icon(Icons.refresh_rounded, size: 20),
|
||||
onPressed: () =>
|
||||
context.read<DashboardDailyRicontattiCubit>().refresh(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildOverviewStats(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state,
|
||||
) {
|
||||
final hasZeros = state.staffAtZero > 0;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(18, 14, 18, 14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_buildStatChip(
|
||||
icon: Icons.check_circle_rounded,
|
||||
color: Colors.green.shade600,
|
||||
bgColor: Colors.green.shade50,
|
||||
label: '>= 2 Ricontatti',
|
||||
count: state.staffWithGoal,
|
||||
),
|
||||
_buildStatChip(
|
||||
icon: Icons.hourglass_top_rounded,
|
||||
color: Colors.blue.shade600,
|
||||
bgColor: Colors.blue.shade50,
|
||||
label: '1 Ricontatto',
|
||||
count: state.staffWithOne,
|
||||
),
|
||||
_buildStatChip(
|
||||
icon: Icons.warning_amber_rounded,
|
||||
color: Colors.deepOrange.shade600,
|
||||
bgColor: Colors.deepOrange.shade50,
|
||||
label: '0 Ricontatti',
|
||||
count: state.staffAtZero,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (hasZeros) ...[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.deepOrange.shade50.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: Colors.deepOrange.shade200,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline_rounded,
|
||||
size: 16,
|
||||
color: Colors.deepOrange.shade800,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${state.staffAtZero} ${state.staffAtZero == 1 ? "addetto non ha" : "addetti non hanno"} ancora raccolto alcun ricontatto oggi.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.deepOrange.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatChip({
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required Color bgColor,
|
||||
required String label,
|
||||
required int count,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: color),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'$count',
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStaffGrid(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
List<StaffDailyRicontattiSummary> summaries,
|
||||
) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Calcola quante colonne in base alla larghezza disponibile
|
||||
final double width = constraints.maxWidth;
|
||||
final int crossAxisCount = width > 1100
|
||||
? 4
|
||||
: width > 750
|
||||
? 3
|
||||
: width > 480
|
||||
? 2
|
||||
: 1;
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: summaries.length,
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: crossAxisCount,
|
||||
mainAxisSpacing: 10,
|
||||
crossAxisSpacing: 10,
|
||||
mainAxisExtent: 104,
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final summary = summaries[index];
|
||||
return _StaffItemCard(summary: summary);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoading(ThemeData theme) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(32.0),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildError(
|
||||
BuildContext context,
|
||||
ThemeData theme,
|
||||
DashboardDailyRicontattiState state,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: theme.colorScheme.error, size: 32),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Impossibile caricare i dati dei ricontatti',
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextButton.icon(
|
||||
onPressed: () =>
|
||||
context.read<DashboardDailyRicontattiCubit>().refresh(),
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Riprova'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmpty(ThemeData theme) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Nessun addetto attivo registrato per questo negozio.',
|
||||
style: TextStyle(fontStyle: FontStyle.italic),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffItemCard extends StatelessWidget {
|
||||
final StaffDailyRicontattiSummary summary;
|
||||
|
||||
const _StaffItemCard({required this.summary});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
// Stile in base al conteggio
|
||||
final bool hasGoal = summary.hasReachedGoal;
|
||||
final bool hasOne = summary.hasStarted;
|
||||
final bool isZero = summary.isZero;
|
||||
|
||||
final Color primaryColor = hasGoal
|
||||
? Colors.green.shade600
|
||||
: hasOne
|
||||
? Colors.blue.shade600
|
||||
: Colors.grey.shade500;
|
||||
|
||||
final Color cardBg = hasGoal
|
||||
? Colors.green.shade50.withValues(alpha: 0.3)
|
||||
: hasOne
|
||||
? Colors.blue.shade50.withValues(alpha: 0.3)
|
||||
: theme.colorScheme.surface;
|
||||
|
||||
final Color borderColor = hasGoal
|
||||
? Colors.green.shade400
|
||||
: hasOne
|
||||
? Colors.blue.shade300
|
||||
: theme.dividerColor.withValues(alpha: 0.25);
|
||||
|
||||
final String initials = _getInitials(summary.staffName);
|
||||
|
||||
return InkWell(
|
||||
onTap: () => _handleTap(context),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: cardBg,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(
|
||||
color: borderColor,
|
||||
width: isZero ? 1.0 : 1.5,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// Avatar con iniziali
|
||||
CircleAvatar(
|
||||
radius: 20,
|
||||
backgroundColor: primaryColor.withValues(alpha: 0.15),
|
||||
child: Text(
|
||||
initials,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: primaryColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Nome e stato
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
summary.staffName,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: isZero
|
||||
? context.primaryText.withValues(alpha: 0.75)
|
||||
: context.primaryText,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
_buildStatusChip(hasGoal, hasOne, isZero),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Grande numero conteggio e riepilogo mese tra parentesi
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
children: [
|
||||
Text(
|
||||
'${summary.count}',
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
height: 1.0,
|
||||
color: hasGoal
|
||||
? Colors.green.shade700
|
||||
: hasOne
|
||||
? Colors.blue.shade700
|
||||
: Colors.grey.shade400,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'oggi',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: hasGoal
|
||||
? Colors.green.shade700
|
||||
: hasOne
|
||||
? Colors.blue.shade700
|
||||
: Colors.grey.shade500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.6),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'(mese: ${summary.monthCount})',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.85),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(bool hasGoal, bool hasOne, bool isZero) {
|
||||
if (hasGoal) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.star_rounded, size: 13, color: Colors.green.shade700),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
'Obiettivo preso',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.green.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (hasOne) {
|
||||
return Text(
|
||||
'1 raccolto',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.blue.shade700,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Text(
|
||||
'0 ricontatti',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.deepOrange.shade600,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _getInitials(String name) {
|
||||
final parts = name.trim().split(RegExp(r'\s+'));
|
||||
if (parts.isEmpty || parts[0].isEmpty) return '?';
|
||||
if (parts.length == 1) return parts[0][0].toUpperCase();
|
||||
return '${parts[0][0]}${parts[1][0]}'.toUpperCase();
|
||||
}
|
||||
|
||||
void _handleTap(BuildContext context) {
|
||||
if (summary.operations.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${summary.staffName} non ha ancora registrato ricontatti oggi (${summary.monthCount} nel mese).',
|
||||
),
|
||||
duration: const Duration(seconds: 2),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mostra bottom sheet di dettaglio con le operazioni prese oggi dall'addetto
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (sheetContext) => _StaffOperationsSheet(summary: summary),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffOperationsSheet extends StatelessWidget {
|
||||
final StaffDailyRicontattiSummary summary;
|
||||
|
||||
const _StaffOperationsSheet({required this.summary});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final timeFormat = DateFormat('HH:mm');
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
padding: EdgeInsets.only(
|
||||
top: 16,
|
||||
left: 20,
|
||||
right: 20,
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
||||
),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.75,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 4,
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.dividerColor.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.person_rounded,
|
||||
color: Colors.amber.shade900,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
summary.staffName,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${summary.count} ${summary.count == 1 ? "ricontatto oggi" : "ricontatti oggi"} • (${summary.monthCount} nel mese)',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Divider(height: 1, color: theme.dividerColor.withValues(alpha: 0.2)),
|
||||
const SizedBox(height: 12),
|
||||
Flexible(
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
itemCount: summary.operations.length,
|
||||
separatorBuilder: (context, _) => Divider(
|
||||
height: 16,
|
||||
color: theme.dividerColor.withValues(alpha: 0.1),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final op = summary.operations[index];
|
||||
final ricontattoDetails = op.details
|
||||
.where((d) => d.type == OperationType.ricontatto)
|
||||
.toList();
|
||||
|
||||
final timeStr = op.createdAt != null
|
||||
? timeFormat.format(op.createdAt!)
|
||||
: '--:--';
|
||||
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
context.pushNamed(
|
||||
Routes.operationForm,
|
||||
extra: (createdBy: null, operation: op),
|
||||
pathParameters: {'id': op.id!},
|
||||
);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 8.0,
|
||||
horizontal: 4.0,
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
timeStr,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
op.customer?.name ?? 'Cliente non specificato',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: ricontattoDetails.map((detail) {
|
||||
final label = detail.subType != null &&
|
||||
detail.subType!.isNotEmpty
|
||||
? detail.subType!
|
||||
: 'Ricontatto';
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
if (op.note.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
op.note,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Icon(
|
||||
Icons.chevron_right_rounded,
|
||||
size: 20,
|
||||
color: Colors.grey,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+12
@@ -79,6 +79,18 @@ class DashboardStoreTicketListCubit
|
||||
|
||||
Future<void> _loadTicketsSilently() async {
|
||||
try {
|
||||
if (companyId == null || companyId!.isEmpty) {
|
||||
if (!isClosed) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: DashboardStoreTicketListStatus.initial,
|
||||
tickets: [],
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final tickets = await _repository.fetchTickets(
|
||||
companyId: companyId!,
|
||||
storeId: storeId,
|
||||
|
||||
@@ -6,6 +6,8 @@ import 'package:flux/core/routes/routes.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/core/widgets/staff_selector_modal.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart';
|
||||
import 'package:flux/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart';
|
||||
import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart';
|
||||
@@ -79,6 +81,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
context.read<DashboardNoteListCubit>().stopListening();
|
||||
context.read<DashboardTargetProgressCubit>().stopListening();
|
||||
context.read<DashboardExpiringContractsCubit>().stopListening();
|
||||
context.read<DashboardDailyRicontattiCubit>().stopListening();
|
||||
}
|
||||
|
||||
void _startListeners() {
|
||||
@@ -88,12 +91,17 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
newStaffId: sessionState.currentStaffMember?.id,
|
||||
);
|
||||
context.read<DashboardDailyRicontattiCubit>().updateContext(
|
||||
newCompanyId: sessionState.company?.id,
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
);
|
||||
context.read<DashboardStoreOperationListCubit>().startListening();
|
||||
context.read<DashboardTaskListCubit>().startListening();
|
||||
context.read<DashboardStoreTicketListCubit>().startListening();
|
||||
context.read<DashboardNoteListCubit>().startListening();
|
||||
context.read<DashboardTargetProgressCubit>().startListening();
|
||||
context.read<DashboardExpiringContractsCubit>().startListening();
|
||||
context.read<DashboardDailyRicontattiCubit>().startListening();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -137,10 +145,27 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
newStaffId: sessionState.currentStaffMember?.id,
|
||||
);
|
||||
context.read<DashboardDailyRicontattiCubit>().updateContext(
|
||||
newCompanyId: sessionState.company?.id,
|
||||
newStoreId: sessionState.currentStore?.id,
|
||||
);
|
||||
},
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
// --- HERO TARGET DEL GIORNO (TUTTA LARGHEZZA IN CIMA) ---
|
||||
// --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) ---
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
|
||||
child: _buildQuickActions(context),
|
||||
),
|
||||
),
|
||||
|
||||
// --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) ---
|
||||
const SliverToBoxAdapter(
|
||||
child: DashboardDailyRicontattiCard(),
|
||||
),
|
||||
|
||||
// --- 3. HERO TARGET DEL GIORNO ---
|
||||
const SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0),
|
||||
@@ -148,17 +173,9 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
),
|
||||
),
|
||||
|
||||
// --- QUICK ACTIONS: AZIONI RAPIDE ---
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
child: _buildQuickActions(context),
|
||||
),
|
||||
),
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 8)),
|
||||
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 32)),
|
||||
|
||||
// --- I WIDGET DELLA DASHBOARD (Responsive Grid) ---
|
||||
// --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) ---
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
sliver: SliverGrid(
|
||||
|
||||
@@ -24,21 +24,23 @@ class StaffRepository {
|
||||
${Tables.stores}(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId);
|
||||
.eq('company_id', companyId)
|
||||
.order('name', ascending: true);
|
||||
|
||||
if (storeId != null) {
|
||||
filterBuilder = filterBuilder.or(
|
||||
'store_id.eq.$storeId,store_id.is.null',
|
||||
);
|
||||
}
|
||||
final response = await filterBuilder;
|
||||
|
||||
var transformBuilder = filterBuilder.order('name', ascending: true);
|
||||
|
||||
final response = await transformBuilder;
|
||||
|
||||
return (response as List)
|
||||
final list = (response as List)
|
||||
.map((s) => StaffMemberModel.fromMap(s))
|
||||
.toList();
|
||||
|
||||
if (storeId != null) {
|
||||
return list
|
||||
.where((s) =>
|
||||
s.assignedStoreIds.isEmpty || s.assignedStoreIds.contains(storeId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
return list;
|
||||
} on Exception catch (e) {
|
||||
debugPrint('Errore nel recupero della lista di staff: $e');
|
||||
throw Exception('Errore nel recupero della lista di staff: $e');
|
||||
|
||||
@@ -77,6 +77,35 @@ class StaffMemberModel extends Equatable {
|
||||
);
|
||||
}
|
||||
|
||||
/// Indica se il collaboratore ha la qualifica di Manager o Titolare (tramite jobTitle)
|
||||
bool get isManagerOrTitolare {
|
||||
final title = (jobTitle ?? '').trim().toLowerCase();
|
||||
return title.contains('manager') || title.contains('titolare');
|
||||
}
|
||||
|
||||
/// Discriminante per vedere o meno il Focus Ricontatti: Manager e Titolare (o Admin di sistema)
|
||||
bool get canViewRicontattiFocus {
|
||||
if (isManagerOrTitolare) return true;
|
||||
if (systemRole == SystemRole.admin) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Discriminante per non comparire tra gli utenti "controllati" (addetti):
|
||||
/// Manager, Titolari, Tester o collaboratori disattivati
|
||||
bool get isExcludedFromControlledStaff {
|
||||
if (!isActive) return true;
|
||||
final title = (jobTitle ?? '').trim().toLowerCase();
|
||||
if (title.contains('manager') ||
|
||||
title.contains('titolare') ||
|
||||
title.contains('tester')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Alias retrocompatibile
|
||||
bool get isExcludedFromRicontattiFocus => isExcludedFromControlledStaff;
|
||||
|
||||
factory StaffMemberModel.empty() {
|
||||
return const StaffMemberModel(
|
||||
companyId: '',
|
||||
|
||||
@@ -142,24 +142,64 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
myRole == SystemRole.admin || myRole == SystemRole.manager;
|
||||
final hasEmail = member.email != null && member.email!.trim().isNotEmpty;
|
||||
|
||||
final bool isActive = member.isActive;
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
color: isActive ? null : context.surface.withValues(alpha: 0.6),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: BorderSide(color: context.accent.withValues(alpha: 0.1)),
|
||||
side: BorderSide(
|
||||
color: isActive
|
||||
? context.accent.withValues(alpha: 0.1)
|
||||
: Colors.red.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.all(12),
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: context.accent.withValues(alpha: 0.1),
|
||||
backgroundColor: isActive
|
||||
? context.accent.withValues(alpha: 0.1)
|
||||
: Colors.grey.withValues(alpha: 0.2),
|
||||
child: Text(
|
||||
member.name[0].toUpperCase(),
|
||||
style: TextStyle(color: context.accent),
|
||||
style: TextStyle(
|
||||
color: isActive ? context.accent : Colors.grey,
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
member.name,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
title: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
member.name,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isActive ? null : context.secondaryText,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (!isActive) ...[
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: const Text(
|
||||
'DISATTIVATO',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -177,19 +217,18 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
Text(
|
||||
'Qualifica: ${member.jobTitle!}',
|
||||
style: TextStyle(
|
||||
color: context.accent,
|
||||
color: isActive ? context.accent : Colors.grey,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
// MODIFICA UX: Menu a tendina per le azioni (Salva spazio e previene overflow)
|
||||
trailing: canManageStaff && hasEmail
|
||||
trailing: canManageStaff
|
||||
? PopupMenuButton<String>(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
onSelected: (value) {
|
||||
if (value == 'invite_reset') {
|
||||
onSelected: (value) async {
|
||||
if (value == 'invite_reset' && hasEmail) {
|
||||
if (!member.hasJoined) {
|
||||
context.read<StaffCubit>().inviteStaffMember(
|
||||
member: member,
|
||||
@@ -207,22 +246,97 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
} else {
|
||||
context.read<StaffCubit>().resetPassword(member.email!);
|
||||
}
|
||||
} else if (value == 'toggle_active') {
|
||||
final newActiveState = !member.isActive;
|
||||
final confirm = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(
|
||||
newActiveState
|
||||
? "Riattivare ${member.name}?"
|
||||
: "Disattivare ${member.name}?",
|
||||
),
|
||||
content: Text(
|
||||
newActiveState
|
||||
? "L'addetto tornerà attivo e selezionabile per nuove operazioni, ticket e gare."
|
||||
: "L'addetto non comparirà più nella selezione per nuove operazioni o ticket e non comparirà nelle gare e nelle loro ripartizioni. I dati storici rimarranno intatti.",
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text("Annulla"),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor:
|
||||
newActiveState ? Colors.green : Colors.red,
|
||||
),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text(
|
||||
newActiveState ? "Riattiva" : "Disattiva",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirm != true || !mounted) return;
|
||||
|
||||
context.read<StaffCubit>().saveStaffMember(
|
||||
member.copyWith(isActive: newActiveState),
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
newActiveState
|
||||
? "${member.name} riattivato con successo!"
|
||||
: "${member.name} disattivato con successo.",
|
||||
),
|
||||
backgroundColor:
|
||||
newActiveState ? Colors.green : Colors.orange.shade800,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
if (hasEmail)
|
||||
PopupMenuItem(
|
||||
value: 'invite_reset',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
!member.hasJoined ? Icons.send : Icons.lock_reset,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
!member.hasJoined
|
||||
? "Re-invia Invito"
|
||||
: "Reset Password",
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'invite_reset',
|
||||
value: 'toggle_active',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
!member.hasJoined ? Icons.send : Icons.lock_reset,
|
||||
member.isActive
|
||||
? Icons.person_off_outlined
|
||||
: Icons.person_add_alt_outlined,
|
||||
size: 20,
|
||||
color: member.isActive ? Colors.redAccent : Colors.green,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
!member.hasJoined
|
||||
? "Re-invia Invito"
|
||||
: "Reset Password",
|
||||
member.isActive
|
||||
? "Disattiva Addetto"
|
||||
: "Riattiva Addetto",
|
||||
style: TextStyle(
|
||||
color:
|
||||
member.isActive ? Colors.redAccent : Colors.green,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -241,6 +355,7 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
final emailController = TextEditingController(text: member?.email);
|
||||
final phoneController = TextEditingController(text: member?.phoneNumber);
|
||||
final jobTitleController = TextEditingController(text: member?.jobTitle);
|
||||
bool isActive = member?.isActive ?? true;
|
||||
|
||||
SystemRole selectedRole = member?.systemRole ?? SystemRole.user;
|
||||
List<String> tempSelectedStores =
|
||||
@@ -345,7 +460,31 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// SWITCH ATTIVO / DISATTIVATO
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: isActive,
|
||||
title: const Text(
|
||||
"Collaboratore Attivo",
|
||||
style: TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
subtitle: Text(
|
||||
isActive
|
||||
? "Visibile per nuove operazioni, ticket e gare"
|
||||
: "Disattivato (invisibile per nuove operazioni, ticket e gare)",
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: context.secondaryText,
|
||||
),
|
||||
),
|
||||
activeThumbColor: context.accent,
|
||||
onChanged: (val) {
|
||||
setModalState(() => isActive = val);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
const Text(
|
||||
"Assegna ai Negozi",
|
||||
@@ -412,6 +551,7 @@ class _StaffScreenState extends State<StaffScreen> {
|
||||
phoneNumber: phoneController.text.trim(),
|
||||
jobTitle: jobTitleController.text.trim(),
|
||||
systemRole: selectedRole,
|
||||
isActive: isActive,
|
||||
companyId: GetIt.I
|
||||
.get<SessionCubit>()
|
||||
.state
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
import 'package:flux/features/operations/models/paginated_operations.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
@@ -314,4 +315,58 @@ class OperationsRepository {
|
||||
}
|
||||
return earliest;
|
||||
}
|
||||
|
||||
/// Recupera il conteggio dei ricontatti registrati nel mese per ciascun addetto del negozio
|
||||
Future<Map<String, int>> getMonthlyRicontattiCountsByStaff({
|
||||
required String companyId,
|
||||
required String storeId,
|
||||
required DateTime month,
|
||||
}) async {
|
||||
try {
|
||||
final monthStart = DateTime(month.year, month.month, 1, 0, 0, 0);
|
||||
final monthEnd = DateTime(month.year, month.month + 1, 0, 23, 59, 59, 999);
|
||||
|
||||
final response = await _supabase
|
||||
.from(Tables.operations)
|
||||
.select('''
|
||||
id,
|
||||
staff_id,
|
||||
${Tables.operationDetails}(
|
||||
type
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId)
|
||||
.eq('store_id', storeId)
|
||||
.neq('status', 'failure')
|
||||
.gte('created_at', monthStart.toIso8601String())
|
||||
.lte('created_at', monthEnd.toIso8601String());
|
||||
|
||||
final operations = response as List<dynamic>;
|
||||
final Map<String, int> staffCounts = {};
|
||||
|
||||
for (final op in operations) {
|
||||
final staffId = op['staff_id'] as String?;
|
||||
if (staffId == null || staffId.isEmpty) continue;
|
||||
|
||||
final details = op[Tables.operationDetails] as List<dynamic>? ?? [];
|
||||
int ricontattiInOp = 0;
|
||||
for (final detail in details) {
|
||||
final typeVal = detail['type']?.toString();
|
||||
if (typeVal != null &&
|
||||
OperationType.fromValue(typeVal) == OperationType.ricontatto) {
|
||||
ricontattiInOp++;
|
||||
}
|
||||
}
|
||||
|
||||
if (ricontattiInOp > 0) {
|
||||
staffCounts[staffId] = (staffCounts[staffId] ?? 0) + ricontattiInOp;
|
||||
}
|
||||
}
|
||||
|
||||
return staffCounts;
|
||||
} catch (e) {
|
||||
debugPrint('Errore nel recupero conteggi ricontatti del mese: $e');
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
class FinancingTranslations {
|
||||
static const List<FinancingLanguage> supportedLanguages = [
|
||||
FinancingLanguage(code: 'it', name: 'Italiano', flag: '🇮🇹', isRtl: false),
|
||||
FinancingLanguage(code: 'en', name: 'English', flag: '🇬🇧', isRtl: false),
|
||||
FinancingLanguage(code: 'fr', name: 'Français', flag: '🇫🇷', isRtl: false),
|
||||
FinancingLanguage(code: 'es', name: 'Español', flag: '🇪🇸', isRtl: false),
|
||||
FinancingLanguage(code: 'ar', name: 'العربية', flag: '🇸🇦', isRtl: true),
|
||||
FinancingLanguage(code: 'uk', name: 'Українська', flag: '🇺🇦', isRtl: false),
|
||||
FinancingLanguage(code: 'ru', name: 'Русский', flag: '🇷🇺', isRtl: false),
|
||||
FinancingLanguage(code: 'mk', name: 'Македонски', flag: '🇲🇰', isRtl: false),
|
||||
FinancingLanguage(code: 'sq', name: 'Shqip', flag: '🇦🇱', isRtl: false),
|
||||
];
|
||||
|
||||
static const List<String> canonicalMaritalStatuses = [
|
||||
'Celibe / Nubile',
|
||||
'Coniugato/a',
|
||||
'Separato/a',
|
||||
'Divorziato/a',
|
||||
'Vedovo/a',
|
||||
];
|
||||
|
||||
static const List<String> canonicalIncomeRanges = [
|
||||
'Fino a 2.000 €',
|
||||
'Da 2.000 € a 5.000 €',
|
||||
'Oltre 5.000 €',
|
||||
];
|
||||
|
||||
static FinancingStrings getStrings(String langCode) {
|
||||
switch (langCode) {
|
||||
case 'en':
|
||||
return const FinancingStrings(
|
||||
title: 'Financing Details',
|
||||
subtitle: 'Please fill in the information below required for your financing application.',
|
||||
maritalStatusLabel: 'Marital Status',
|
||||
maritalOptions: ['Single', 'Married', 'Separated', 'Divorced', 'Widowed'],
|
||||
occupationLabel: 'Occupation',
|
||||
occupationHint: 'e.g. Employee, Factory Worker, Self-employed...',
|
||||
incomeLabel: 'Net Monthly Income',
|
||||
incomeOptions: ['Up to €2,000', 'From €2,000 to €5,000', 'Over €5,000'],
|
||||
submitButton: 'Submit Information',
|
||||
errorRequired: 'Please complete all fields before submitting.',
|
||||
successTitle: 'Information Submitted!',
|
||||
successSubtitle: 'Thank you! Your information has been safely received by our store. You can close this page.',
|
||||
);
|
||||
case 'fr':
|
||||
return const FinancingStrings(
|
||||
title: 'Informations de Financement',
|
||||
subtitle: 'Veuillez renseigner les informations requises pour votre demande de financement.',
|
||||
maritalStatusLabel: 'État Civil',
|
||||
maritalOptions: ['Célibataire', 'Marié(e)', 'Séparé(e)', 'Divorcé(e)', 'Veuf / Veuve'],
|
||||
occupationLabel: 'Profession',
|
||||
occupationHint: 'Ex. Employé, Ouvrier, Artisan, Indépendant...',
|
||||
incomeLabel: 'Revenu Mensuel Net',
|
||||
incomeOptions: ['Jusqu\'à 2 000 €', 'De 2 000 € à 5 000 €', 'Plus de 5 000 €'],
|
||||
submitButton: 'Envoyer les données',
|
||||
errorRequired: 'Veuillez remplir tous les champs avant de soumettre.',
|
||||
successTitle: 'Données transmises avec succès !',
|
||||
successSubtitle: 'Merci ! Les informations ont été reçues par notre conseiller. Vous pouvez fermer cette page.',
|
||||
);
|
||||
case 'es':
|
||||
return const FinancingStrings(
|
||||
title: 'Datos para Financiación',
|
||||
subtitle: 'Completa los siguientes datos necesarios para la solicitud de financiación.',
|
||||
maritalStatusLabel: 'Estado Civil',
|
||||
maritalOptions: ['Soltero/a', 'Casado/a', 'Separado/a', 'Divorciado/a', 'Viudo/a'],
|
||||
occupationLabel: 'Profesión',
|
||||
occupationHint: 'Ej. Empleado, Obrero, Autónomo, Comerciante...',
|
||||
incomeLabel: 'Ingreso Mensual Neto',
|
||||
incomeOptions: ['Hasta 2.000 €', 'De 2.000 € a 5.000 €', 'Más de 5.000 €'],
|
||||
submitButton: 'Enviar Datos',
|
||||
errorRequired: 'Por favor, completa todos los campos antes de enviar.',
|
||||
successTitle: '¡Datos enviados con éxito!',
|
||||
successSubtitle: '¡Gracias! Nuestro asesor ha recibido tus datos. Ya puedes cerrar esta pantalla.',
|
||||
);
|
||||
case 'ar':
|
||||
return const FinancingStrings(
|
||||
title: 'بيانات التمويل',
|
||||
subtitle: 'يرجى تعبئة البيانات التالية المطلوبة لإتمام معاملة التمويل.',
|
||||
maritalStatusLabel: 'الحالة الاجتماعية',
|
||||
maritalOptions: ['أعزب / عزباء', 'متزوج / متزوجة', 'منفصل / منفصلة', 'مطلق / مطلقة', 'أرمل / أرملة'],
|
||||
occupationLabel: 'المهنة',
|
||||
occupationHint: 'مثال: موظف، عامل، تاجر، عمل حر...',
|
||||
incomeLabel: 'الدخل الشهري الصافي',
|
||||
incomeOptions: ['حتى 2,000 يورو', 'من 2,000 إلى 5,000 يورو', 'أكثر من 5,000 يورو'],
|
||||
submitButton: 'إرسال البيانات',
|
||||
errorRequired: 'يرجى ملء جميع الحقول قبل الإرسال.',
|
||||
successTitle: 'تم إرسال البيانات بنجاح!',
|
||||
successSubtitle: 'شكراً لك! لقد استلم موظفنا البيانات بنجاح. يمكنك إغلاق هذه الصفحة الآن.',
|
||||
);
|
||||
case 'uk':
|
||||
return const FinancingStrings(
|
||||
title: 'Дані для фінансування',
|
||||
subtitle: 'Будь ласка, заповніть наступні дані, необхідні для оформлення фінансування.',
|
||||
maritalStatusLabel: 'Сімейний стан',
|
||||
maritalOptions: ['Неодружений / Незаміжня', 'Одружений / Заміжня', 'Розлучений / Розлучена', 'Проживає окремо', 'Вдівець / Вдова'],
|
||||
occupationLabel: 'Професія / Посада',
|
||||
occupationHint: 'Наприклад: Службовець, Робітник, ФОП...',
|
||||
incomeLabel: 'Чистий щомісячний дохід',
|
||||
incomeOptions: ['До 2 000 €', 'Від 2 000 € до 5 000 €', 'Понад 5 000 €'],
|
||||
submitButton: 'Надіслати дані',
|
||||
errorRequired: 'Будь ласка, заповніть усі поля перед відправленням.',
|
||||
successTitle: 'Дані успішно надіслано!',
|
||||
successSubtitle: 'Дякуємо! Наш фахівець отримав ваші дані. Ви можете закрити цю сторінку.',
|
||||
);
|
||||
case 'ru':
|
||||
return const FinancingStrings(
|
||||
title: 'Данные для финансирования',
|
||||
subtitle: 'Пожалуйста, заполните следующие данные, необходимые для оформления финансирования.',
|
||||
maritalStatusLabel: 'Семейное положение',
|
||||
maritalOptions: ['Холост / Не замужем', 'Женат / Замужем', 'Проживает раздельно', 'Разведен / Разведена', 'Вдовец / Вдова'],
|
||||
occupationLabel: 'Профессия / Должность',
|
||||
occupationHint: 'Например: Служащий, Рабочий, Предприниматель...',
|
||||
incomeLabel: 'Чистый ежемесячный доход',
|
||||
incomeOptions: ['До 2 000 €', 'От 2 000 € до 5 000 €', 'Более 5 000 €'],
|
||||
submitButton: 'Отправить данные',
|
||||
errorRequired: 'Пожалуйста, заполните все поля перед отправкой.',
|
||||
successTitle: 'Данные успешно отправлены!',
|
||||
successSubtitle: 'Спасибо! Наш сотрудник получил ваши данные. Вы можете закрыть эту страницу.',
|
||||
);
|
||||
case 'mk':
|
||||
return const FinancingStrings(
|
||||
title: 'Податоци за финансирање',
|
||||
subtitle: 'Ве молиме пополнете ги следните податоци потребни за апликацијата за финансирање.',
|
||||
maritalStatusLabel: 'Брачна состојба',
|
||||
maritalOptions: ['Неженет / Немажена', 'Оженет / Мажена', 'Разделен / Разделена', 'Разведен / Разведена', 'Вдовец / Вдовица'],
|
||||
occupationLabel: 'Професија',
|
||||
occupationHint: 'Пр. Вработен, Работник, Трговец...',
|
||||
incomeLabel: 'Нето месечен приход',
|
||||
incomeOptions: ['До 2.000 €', 'Од 2.000 € до 5.000 €', 'Над 5.000 €'],
|
||||
submitButton: 'Испрати податоци',
|
||||
errorRequired: 'Ве молиме пополнете ги сите полиња пред испраќање.',
|
||||
successTitle: 'Податоците се успешно испратени!',
|
||||
successSubtitle: 'Ви благодариме! Нашиот оператор ги прими вашите податоци. Можете да го затворите овој прозорец.',
|
||||
);
|
||||
case 'sq':
|
||||
return const FinancingStrings(
|
||||
title: 'Të dhënat për Financim',
|
||||
subtitle: 'Ju lutemi plotësoni të dhënat e mëposhtme të nevojshme për kërkesën për financim.',
|
||||
maritalStatusLabel: 'Gjendja Civile',
|
||||
maritalOptions: ['Beqar / Beqare', 'I/E martuar', 'I/E ndarë', 'I/E divorcuar', 'I/E ve'],
|
||||
occupationLabel: 'Profesioni',
|
||||
occupationHint: 'P.sh. Punonjës, Punëtor, Tregtar, Vetëpunësuar...',
|
||||
incomeLabel: 'Të Ardhurat Mujore Neto',
|
||||
incomeOptions: ['Deri në 2.000 €', 'Nga 2.000 € në 5.000 €', 'Mbi 5.000 €'],
|
||||
submitButton: 'Dërgo të Dhënat',
|
||||
errorRequired: 'Ju lutemi plotësoni të gjitha fushat para dërgimit.',
|
||||
successTitle: 'Të dhënat u dërguan me sukses!',
|
||||
successSubtitle: 'Faleminderit! Operatori ynë i pranoi të dhënat tuaja. Mund ta mbyllni këtë faqe.',
|
||||
);
|
||||
case 'it':
|
||||
default:
|
||||
return const FinancingStrings(
|
||||
title: 'Dati per Finanziamento',
|
||||
subtitle: 'Compila i seguenti dati necessari per la pratica di finanziamento.',
|
||||
maritalStatusLabel: 'Stato Civile',
|
||||
maritalOptions: ['Celibe / Nubile', 'Coniugato/a', 'Separato/a', 'Divorziato/a', 'Vedovo/a'],
|
||||
occupationLabel: 'Professione',
|
||||
occupationHint: 'Es. Impiegato, Operaio, Commerciante, Autonomo...',
|
||||
incomeLabel: 'Reddito Mensile Netto',
|
||||
incomeOptions: ['Fino a 2.000 €', 'Da 2.000 € a 5.000 €', 'Oltre 5.000 €'],
|
||||
submitButton: 'Invia Dati',
|
||||
errorRequired: 'Per favore compila tutti i campi prima di inviare.',
|
||||
successTitle: 'Dati inviati con successo!',
|
||||
successSubtitle: 'Grazie! Le informazioni sono state ricevute dal nostro operatore. Puoi chiudere questa schermata.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static String formatNoteText({
|
||||
required int maritalStatusIndex,
|
||||
required String occupation,
|
||||
required int incomeRangeIndex,
|
||||
required String languageName,
|
||||
}) {
|
||||
final marital = (maritalStatusIndex >= 0 && maritalStatusIndex < canonicalMaritalStatuses.length)
|
||||
? canonicalMaritalStatuses[maritalStatusIndex]
|
||||
: 'Non specificato';
|
||||
|
||||
final income = (incomeRangeIndex >= 0 && incomeRangeIndex < canonicalIncomeRanges.length)
|
||||
? canonicalIncomeRanges[incomeRangeIndex]
|
||||
: 'Non specificato';
|
||||
|
||||
final cleanOccupation = occupation.trim().isNotEmpty ? occupation.trim() : 'Non specificata';
|
||||
|
||||
return '''
|
||||
[DATI FINANZIAMENTO]
|
||||
• Stato civile: $marital
|
||||
• Professione: $cleanOccupation
|
||||
• Reddito mensile: $income
|
||||
(Compilato dal cliente via QR - Lingua: $languageName)''';
|
||||
}
|
||||
}
|
||||
|
||||
class FinancingLanguage {
|
||||
final String code;
|
||||
final String name;
|
||||
final String flag;
|
||||
final bool isRtl;
|
||||
|
||||
const FinancingLanguage({
|
||||
required this.code,
|
||||
required this.name,
|
||||
required this.flag,
|
||||
required this.isRtl,
|
||||
});
|
||||
}
|
||||
|
||||
class FinancingStrings {
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final String maritalStatusLabel;
|
||||
final List<String> maritalOptions;
|
||||
final String occupationLabel;
|
||||
final String occupationHint;
|
||||
final String incomeLabel;
|
||||
final List<String> incomeOptions;
|
||||
final String submitButton;
|
||||
final String errorRequired;
|
||||
final String successTitle;
|
||||
final String successSubtitle;
|
||||
|
||||
const FinancingStrings({
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.maritalStatusLabel,
|
||||
required this.maritalOptions,
|
||||
required this.occupationLabel,
|
||||
required this.occupationHint,
|
||||
required this.incomeLabel,
|
||||
required this.incomeOptions,
|
||||
required this.submitButton,
|
||||
required this.errorRequired,
|
||||
required this.successTitle,
|
||||
required this.successSubtitle,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class FinancingFormScreen extends StatefulWidget {
|
||||
final String sessionId;
|
||||
|
||||
const FinancingFormScreen({
|
||||
super.key,
|
||||
required this.sessionId,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FinancingFormScreen> createState() => _FinancingFormScreenState();
|
||||
}
|
||||
|
||||
class _FinancingFormScreenState extends State<FinancingFormScreen> {
|
||||
FinancingLanguage _currentLang = FinancingTranslations.supportedLanguages.first; // Default Italiano
|
||||
final _occupationController = TextEditingController();
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
int? _selectedMaritalIndex;
|
||||
int? _selectedIncomeIndex;
|
||||
|
||||
bool _isSubmitting = false;
|
||||
bool _isSuccess = false;
|
||||
String? _errorMessage;
|
||||
|
||||
RealtimeChannel? _channel;
|
||||
StreamSubscription? _ackSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initRealtimeChannel();
|
||||
}
|
||||
|
||||
void _initRealtimeChannel() {
|
||||
if (widget.sessionId.isEmpty) return;
|
||||
try {
|
||||
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
|
||||
_channel?.onBroadcast(
|
||||
event: 'ack',
|
||||
callback: (payload) {
|
||||
if (mounted && _isSubmitting) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_isSuccess = true;
|
||||
});
|
||||
}
|
||||
},
|
||||
).subscribe();
|
||||
} catch (e) {
|
||||
debugPrint('Errore init channel financing: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ackSubscription?.cancel();
|
||||
if (_channel != null) {
|
||||
Supabase.instance.client.removeChannel(_channel!);
|
||||
}
|
||||
_occupationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final strings = FinancingTranslations.getStrings(_currentLang.code);
|
||||
|
||||
if (_selectedMaritalIndex == null ||
|
||||
_selectedIncomeIndex == null ||
|
||||
_occupationController.text.trim().isEmpty) {
|
||||
setState(() {
|
||||
_errorMessage = strings.errorRequired;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_errorMessage = null;
|
||||
_isSubmitting = true;
|
||||
});
|
||||
|
||||
final formattedText = FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: _selectedMaritalIndex!,
|
||||
occupation: _occupationController.text.trim(),
|
||||
incomeRangeIndex: _selectedIncomeIndex!,
|
||||
languageName: _currentLang.name,
|
||||
);
|
||||
|
||||
try {
|
||||
if (_channel == null) {
|
||||
_channel = Supabase.instance.client.channel('financing_${widget.sessionId}');
|
||||
_channel?.subscribe();
|
||||
}
|
||||
|
||||
await _channel?.sendBroadcastMessage(
|
||||
event: 'submit',
|
||||
payload: {
|
||||
'maritalStatusIndex': _selectedMaritalIndex,
|
||||
'occupation': _occupationController.text.trim(),
|
||||
'incomeRangeIndex': _selectedIncomeIndex,
|
||||
'languageCode': _currentLang.code,
|
||||
'languageName': _currentLang.name,
|
||||
'formattedText': formattedText,
|
||||
},
|
||||
);
|
||||
|
||||
// Timeout di sicurezza: se entro 3 secondi non riceviamo ack specifico,
|
||||
// consideriamo comunque la trasmissione completata con successo
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (mounted && _isSubmitting) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_isSuccess = true;
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
_errorMessage = 'Errore di connessione: $e';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final strings = FinancingTranslations.getStrings(_currentLang.code);
|
||||
|
||||
return Directionality(
|
||||
textDirection: _currentLang.isRtl ? TextDirection.rtl : TextDirection.ltr,
|
||||
child: Scaffold(
|
||||
backgroundColor: const Color(0xFFF8FAFC),
|
||||
appBar: AppBar(
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.white,
|
||||
centerTitle: true,
|
||||
title: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.account_balance_wallet_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Flexible(
|
||||
child: Text(
|
||||
strings.title,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF1E293B),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: _isSuccess
|
||||
? _buildSuccessView(strings, theme)
|
||||
: _buildFormView(strings, theme),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSuccessView(FinancingStrings strings, ThemeData theme) {
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
width: 90,
|
||||
height: 90,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.shade50,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.green.shade200, width: 2),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.check_circle_rounded,
|
||||
color: Colors.green.shade600,
|
||||
size: 56,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
strings.successTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF0F172A),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
strings.successSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
color: Colors.grey.shade700,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.blue.shade100),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: Colors.blue.shade700, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
'Sessione completata',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.blue.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFormView(FinancingStrings strings, ThemeData theme) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 540),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// SELETTORE LINGUA
|
||||
_buildLanguageSelector(),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// DESCRIZIONE
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.privacy_tip_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
strings.subtitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
color: Color(0xFF475569),
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 1. STATO CIVILE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.favorite_border,
|
||||
title: strings.maritalStatusLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildChoiceList(
|
||||
options: strings.maritalOptions,
|
||||
selectedIndex: _selectedMaritalIndex,
|
||||
onSelected: (idx) {
|
||||
setState(() => _selectedMaritalIndex = idx);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 2. PROFESSIONE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.work_outline,
|
||||
title: strings.occupationLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
TextFormField(
|
||||
controller: _occupationController,
|
||||
textInputAction: TextInputAction.done,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
decoration: InputDecoration(
|
||||
hintText: strings.occupationHint,
|
||||
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.primary,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
onChanged: (_) {
|
||||
if (_errorMessage != null) {
|
||||
setState(() => _errorMessage = null);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 3. REDDITO MENSILE
|
||||
_buildSectionHeader(
|
||||
icon: Icons.euro_symbol_outlined,
|
||||
title: strings.incomeLabel,
|
||||
theme: theme,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildChoiceList(
|
||||
options: strings.incomeOptions,
|
||||
selectedIndex: _selectedIncomeIndex,
|
||||
onSelected: (idx) {
|
||||
setState(() => _selectedIncomeIndex = idx);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// MESSAGGIO DI ERRORE
|
||||
if (_errorMessage != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.shade50,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: Colors.red.shade200),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Colors.red.shade700, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: TextStyle(
|
||||
color: Colors.red.shade800,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// PULSANTE INVIO
|
||||
SizedBox(
|
||||
height: 54,
|
||||
child: FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
elevation: 1,
|
||||
),
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.send_rounded, size: 20),
|
||||
label: Text(
|
||||
_isSubmitting ? '...' : strings.submitButton,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLanguageSelector() {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 4.0, bottom: 8.0),
|
||||
child: Text(
|
||||
'Seleziona lingua / Choose language:',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF64748B),
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 42,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: FinancingTranslations.supportedLanguages.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(width: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final lang = FinancingTranslations.supportedLanguages[index];
|
||||
final isSelected = lang.code == _currentLang.code;
|
||||
|
||||
return ChoiceChip(
|
||||
showCheckmark: false,
|
||||
labelPadding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
avatar: Text(lang.flag, style: const TextStyle(fontSize: 16)),
|
||||
label: Text(
|
||||
lang.name,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
|
||||
color: isSelected ? Colors.white : const Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedColor: Theme.of(context).colorScheme.primary,
|
||||
backgroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
side: BorderSide(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFFCBD5E1),
|
||||
),
|
||||
),
|
||||
onSelected: (selected) {
|
||||
if (selected) {
|
||||
setState(() {
|
||||
_currentLang = lang;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSectionHeader({
|
||||
required IconData icon,
|
||||
required String title,
|
||||
required ThemeData theme,
|
||||
}) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icon, size: 20, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChoiceList({
|
||||
required List<String> options,
|
||||
required int? selectedIndex,
|
||||
required ValueChanged<int> onSelected,
|
||||
}) {
|
||||
return Column(
|
||||
children: List.generate(options.length, (index) {
|
||||
final label = options[index];
|
||||
final isSelected = selectedIndex == index;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8.0),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: () => onSelected(index),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary.withValues(alpha: 0.08)
|
||||
: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFFCBD5E1),
|
||||
width: isSelected ? 2 : 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isSelected
|
||||
? Icons.radio_button_checked
|
||||
: Icons.radio_button_off,
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFF94A3B8),
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: const Color(0xFF1E293B),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/ui/widgets/financing_qr_dialog.dart';
|
||||
import 'package:flux/features/operations/ui/widgets/operation_details_section.dart';
|
||||
|
||||
class OperationFormScreen extends StatefulWidget {
|
||||
@@ -629,6 +630,19 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
title: 'Note Interne',
|
||||
icon: Icons.notes,
|
||||
themeColor: Colors.teal,
|
||||
headerTrailing: OutlinedButton.icon(
|
||||
icon: const Icon(Icons.qr_code_2, size: 18),
|
||||
label: const Text('Dati Finanziamento'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.teal,
|
||||
side: const BorderSide(color: Colors.teal),
|
||||
visualDensity: VisualDensity.compact,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onPressed: _showFinancingQrDialog,
|
||||
),
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _notesController,
|
||||
@@ -649,6 +663,32 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void _showFinancingQrDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogCtx) => FinancingQrDialog(
|
||||
onDataReceived: (formattedData) {
|
||||
setState(() {
|
||||
final existing = _notesController.text.trim();
|
||||
if (existing.isEmpty) {
|
||||
_notesController.text = formattedData;
|
||||
} else {
|
||||
_notesController.text = '$existing\n\n$formattedData';
|
||||
}
|
||||
});
|
||||
_flushControllersToCubit();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Dati finanziamento inseriti nelle note!'),
|
||||
backgroundColor: Colors.teal,
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardAllegati(OperationFormState state) {
|
||||
return _buildCard(
|
||||
title: 'Allegati e Documenti',
|
||||
@@ -679,6 +719,7 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
required IconData icon,
|
||||
required Color themeColor,
|
||||
required List<Widget> children,
|
||||
Widget? headerTrailing,
|
||||
}) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 24),
|
||||
@@ -703,13 +744,16 @@ class _OperationFormScreenState extends State<OperationFormScreen> {
|
||||
child: Icon(icon, color: themeColor),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: themeColor,
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: themeColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
?headerTrailing,
|
||||
],
|
||||
),
|
||||
const Divider(height: 32),
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
class FinancingQrDialog extends StatefulWidget {
|
||||
final ValueChanged<String> onDataReceived;
|
||||
|
||||
const FinancingQrDialog({
|
||||
super.key,
|
||||
required this.onDataReceived,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FinancingQrDialog> createState() => _FinancingQrDialogState();
|
||||
}
|
||||
|
||||
class _FinancingQrDialogState extends State<FinancingQrDialog> {
|
||||
late final String _sessionId;
|
||||
late final String _deepLinkUrl;
|
||||
RealtimeChannel? _channel;
|
||||
|
||||
bool _isReceived = false;
|
||||
Map<String, dynamic>? _receivedPayload;
|
||||
bool _copied = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sessionId = const Uuid().v4();
|
||||
_deepLinkUrl = 'https://flux.catelli.it/financing/$_sessionId';
|
||||
_setupRealtimeChannel();
|
||||
}
|
||||
|
||||
void _setupRealtimeChannel() {
|
||||
try {
|
||||
_channel = Supabase.instance.client.channel('financing_$_sessionId');
|
||||
_channel?.onBroadcast(
|
||||
event: 'submit',
|
||||
callback: (payload) {
|
||||
if (!mounted) return;
|
||||
|
||||
// Invia risposta di conferma (ACK) allo smartphone del cliente
|
||||
_channel?.sendBroadcastMessage(
|
||||
event: 'ack',
|
||||
payload: {'status': 'ok'},
|
||||
);
|
||||
|
||||
final maritalIndex = payload['maritalStatusIndex'] as int? ?? 0;
|
||||
final occupation = payload['occupation'] as String? ?? '';
|
||||
final incomeIndex = payload['incomeRangeIndex'] as int? ?? 0;
|
||||
final languageName = payload['languageName'] as String? ?? 'Italiano';
|
||||
|
||||
final formattedText = payload['formattedText'] as String? ??
|
||||
FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: maritalIndex,
|
||||
occupation: occupation,
|
||||
incomeRangeIndex: incomeIndex,
|
||||
languageName: languageName,
|
||||
);
|
||||
|
||||
widget.onDataReceived(formattedText);
|
||||
|
||||
setState(() {
|
||||
_isReceived = true;
|
||||
_receivedPayload = {
|
||||
'marital': (maritalIndex >= 0 &&
|
||||
maritalIndex <
|
||||
FinancingTranslations.canonicalMaritalStatuses.length)
|
||||
? FinancingTranslations.canonicalMaritalStatuses[maritalIndex]
|
||||
: 'N/D',
|
||||
'occupation': occupation,
|
||||
'income': (incomeIndex >= 0 &&
|
||||
incomeIndex <
|
||||
FinancingTranslations.canonicalIncomeRanges.length)
|
||||
? FinancingTranslations.canonicalIncomeRanges[incomeIndex]
|
||||
: 'N/D',
|
||||
'language': languageName,
|
||||
};
|
||||
});
|
||||
},
|
||||
).subscribe();
|
||||
} catch (e) {
|
||||
debugPrint('Errore setup realtime channel: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_channel != null) {
|
||||
Supabase.instance.client.removeChannel(_channel!);
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _copyToClipboard() {
|
||||
Clipboard.setData(ClipboardData(text: _deepLinkUrl));
|
||||
setState(() => _copied = true);
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (mounted) setState(() => _copied = false);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
title: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Icon(Icons.qr_code_2, color: Colors.teal, size: 28),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
const Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Dati Finanziamento',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
|
||||
),
|
||||
Text(
|
||||
'Raccolta via smartphone cliente',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 380,
|
||||
child: SingleChildScrollView(
|
||||
child: _isReceived
|
||||
? _buildReceivedContent(theme)
|
||||
: _buildQrContent(theme),
|
||||
),
|
||||
),
|
||||
actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
actions: [
|
||||
if (!_isReceived) ...[
|
||||
OutlinedButton.icon(
|
||||
onPressed: _copyToClipboard,
|
||||
icon: Icon(_copied ? Icons.check : Icons.copy, size: 16),
|
||||
label: Text(_copied ? 'Link Copiato!' : 'Copia Link'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
] else ...[
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.teal),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.check, size: 18),
|
||||
label: const Text('Chiudi (Dati inseriti nelle note)'),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQrContent(ThemeData theme) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Fai inquadrare questo codice al cliente con la fotocamera del suo telefono.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade50,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.amber.shade200),
|
||||
),
|
||||
child: Text(
|
||||
'🌐 Il cliente potrà scegliere la lingua (IT, EN, FR, ES, AR, UK, RU, MK, SQ)',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.amber.shade900,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.grey.shade200),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.04),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: QrImageView(
|
||||
data: _deepLinkUrl,
|
||||
version: QrVersions.auto,
|
||||
size: 210.0,
|
||||
embeddedImage: const AssetImage('assets/images/logo.png'),
|
||||
embeddedImageStyle: const QrEmbeddedImageStyle(
|
||||
size: Size(40, 40),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.teal),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
'In attesa che il cliente compili i dati...',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: Colors.grey.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildReceivedContent(ThemeData theme) {
|
||||
final marital = _receivedPayload?['marital'] ?? '';
|
||||
final occupation = _receivedPayload?['occupation'] ?? '';
|
||||
final income = _receivedPayload?['income'] ?? '';
|
||||
final lang = _receivedPayload?['language'] ?? '';
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.shade50,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.teal.shade200),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: Colors.teal, size: 28),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Dati ricevuti con successo! 🎉',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
color: Colors.teal.shade900,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
const Divider(height: 1),
|
||||
const SizedBox(height: 12),
|
||||
_buildInfoRow('Stato civile', marital),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Professione', occupation),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Reddito mensile', income),
|
||||
const SizedBox(height: 8),
|
||||
_buildInfoRow('Lingua cliente', lang),
|
||||
const SizedBox(height: 14),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.notes, size: 18, color: Colors.teal.shade700),
|
||||
const SizedBox(width: 8),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'I dati sono stati automaticamente inseriti nel campo note dell\'operazione.',
|
||||
style: TextStyle(fontSize: 12, color: Colors.black87),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(String label, String value) {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 110,
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.black54,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,10 +53,10 @@ class TargetFormCubit extends Cubit<TargetFormState> {
|
||||
final storeId = target.storeId ?? defaultStoreId;
|
||||
final storeStaff = await _loadStoreStaff(companyId, storeId);
|
||||
|
||||
// Costruisci o allinea individualTargets per ogni membro dello staff
|
||||
// Costruisci o allinea individualTargets per ogni membro dello staff attivo
|
||||
final List<IndividualTargetModel> individuals = [];
|
||||
for (final staff in storeStaff) {
|
||||
if (staff.id == null) continue;
|
||||
if (staff.id == null || !staff.isActive) continue;
|
||||
final existing = target.individualTargets.firstWhere(
|
||||
(it) => it.staffId == staff.id,
|
||||
orElse:
|
||||
@@ -119,9 +119,8 @@ class TargetFormCubit extends Cubit<TargetFormState> {
|
||||
}
|
||||
|
||||
// 5. Se trovati addetti assegnati al negozio, ritorniamo quelli attivi
|
||||
final activeStoreStaff = staff.where((s) => s.isActive).toList();
|
||||
if (activeStoreStaff.isNotEmpty) {
|
||||
return activeStoreStaff;
|
||||
if (staff.isNotEmpty) {
|
||||
return staff.where((s) => s.isActive).toList();
|
||||
}
|
||||
|
||||
// 6. Fallback: controlliamo se in allStaff di StaffCubit qualcuno ha questo store associato
|
||||
@@ -163,7 +162,7 @@ class TargetFormCubit extends Cubit<TargetFormState> {
|
||||
|
||||
final List<IndividualTargetModel> individuals = [];
|
||||
for (final staff in storeStaff) {
|
||||
if (staff.id == null) continue;
|
||||
if (staff.id == null || !staff.isActive) continue;
|
||||
individuals.add(
|
||||
IndividualTargetModel(
|
||||
companyId: state.target.companyId,
|
||||
|
||||
@@ -138,9 +138,15 @@ class TargetProgressService {
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Costruzione avanzamento per singoli addetti
|
||||
// 4. Costruzione avanzamento per singoli addetti (solo addetti attivi)
|
||||
final staffProgressMap = <String, TargetProgressModel>{};
|
||||
final individualTargetsList = target.individualTargets;
|
||||
final individualTargetsList = target.individualTargets
|
||||
.where((it) => it.staff == null || it.staff!.isActive)
|
||||
.toList();
|
||||
final inactiveStaffIds = target.individualTargets
|
||||
.where((it) => it.staff != null && !it.staff!.isActive)
|
||||
.map((it) => it.staffId)
|
||||
.toSet();
|
||||
|
||||
final bool hasExplicitIndividualTargets = individualTargetsList.any(
|
||||
(it) => it.metrics.totalLevel1 > 0 || it.metrics.totalLevel2 > 0,
|
||||
@@ -200,6 +206,7 @@ class TargetProgressService {
|
||||
|
||||
// Se ci sono addetti con operazioni che non compaiono in individualTargets, creiamo la loro scheda
|
||||
for (final sId in staffCounts.keys) {
|
||||
if (inactiveStaffIds.contains(sId)) continue;
|
||||
if (!staffProgressMap.containsKey(sId)) {
|
||||
final sCounts = staffCounts[sId] ?? {};
|
||||
final sCategories = <String, CategoryProgress>{};
|
||||
|
||||
@@ -703,7 +703,9 @@ class _TargetDetailScreenState extends State<TargetDetailScreen>
|
||||
TargetProgressModel progress,
|
||||
bool isDesktop,
|
||||
) {
|
||||
final staffMembers = target.individualTargets;
|
||||
final staffMembers = target.individualTargets
|
||||
.where((it) => it.staff == null || it.staff!.isActive)
|
||||
.toList();
|
||||
|
||||
if (staffMembers.isEmpty) {
|
||||
return Center(
|
||||
|
||||
@@ -96,6 +96,9 @@ class TaskFormCubit extends Cubit<TaskFormState> {
|
||||
final Map<String, List<StaffMemberModel>> grouped = {};
|
||||
|
||||
for (var staff in staffList) {
|
||||
if (!staff.isActive && !state.selectedStaffIds.contains(staff.id)) {
|
||||
continue;
|
||||
}
|
||||
if (!state.isGlobal) {
|
||||
final belongsToCurrentStore = staff.assignedStores.any(
|
||||
(store) => store.id == _currentStoreId,
|
||||
|
||||
@@ -49,8 +49,14 @@ class TicketRepository {
|
||||
assigned_to:${Tables.staffMembers}!ticket_assigned_to_id_fkey (*),
|
||||
target_model:${Tables.models}!ticket_model_id_1_fkey (*),
|
||||
source_model:${Tables.models}!ticket_model_id_2_fkey (*)
|
||||
''')
|
||||
.eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!);
|
||||
''');
|
||||
|
||||
final currentStoreId =
|
||||
GetIt.I.get<SessionCubit>().state.currentStore?.id;
|
||||
if (currentStoreId == null) {
|
||||
return [];
|
||||
}
|
||||
query = query.eq('store_id', currentStoreId);
|
||||
|
||||
// Filtro Range Date
|
||||
if (dateRange != null) {
|
||||
@@ -191,12 +197,15 @@ class TicketRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream dei ticket che necessitano attenzione (es. in scadenza oggi o in ritardo)
|
||||
Stream<List<TicketModel>> getAttentionNeededTicketsStream() {
|
||||
final storeId = GetIt.I.get<SessionCubit>().state.currentStore?.id;
|
||||
if (storeId == null) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
return _supabase
|
||||
.from(_tableName)
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!)
|
||||
.eq('store_id', storeId)
|
||||
// Purtroppo lo stream accetta solo filtri base, quindi ci facciamo
|
||||
// mandare i dati e li filtriamo con la potenza di Dart!
|
||||
.limit(300)
|
||||
|
||||
@@ -53,6 +53,16 @@ class TicketListCard extends StatelessWidget {
|
||||
DeleteSpecificAttachmentEvent(targetFile),
|
||||
);
|
||||
},
|
||||
onViewModeChanged: (targetFile, newMode) {
|
||||
operationFilesBloc.add(
|
||||
UpdateAttachmentViewModeEvent(targetFile, newMode),
|
||||
);
|
||||
},
|
||||
onAttachmentUpdated: (updatedFile) {
|
||||
operationFilesBloc.add(
|
||||
AttachmentUpdatedEvent(updatedFile),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
+13
-5
@@ -49,7 +49,11 @@ void main() async {
|
||||
return true; // Contrassegna l'errore come gestito ed evita il crash dell'app
|
||||
};
|
||||
|
||||
await dotenv.load(fileName: ".env");
|
||||
try {
|
||||
await dotenv.load(fileName: ".env");
|
||||
} catch (e) {
|
||||
debugPrint('⚠️ Impossibile caricare il file .env: $e');
|
||||
}
|
||||
await init();
|
||||
final initialUri = Uri.base;
|
||||
if (initialUri.fragment.contains('access_token=')) {
|
||||
@@ -85,10 +89,14 @@ void main() async {
|
||||
),
|
||||
BlocProvider<ProductsCubit>(create: (_) => sl<ProductsCubit>()),
|
||||
BlocProvider<StaffCubit>(
|
||||
create: (_) => sl<StaffCubit>()
|
||||
..loadStaffForStore(
|
||||
GetIt.I.get<SessionCubit>().state.currentStore!.id!,
|
||||
),
|
||||
create: (_) {
|
||||
final cubit = sl<StaffCubit>();
|
||||
final storeId = sl<SessionCubit>().state.currentStore?.id;
|
||||
if (storeId != null) {
|
||||
cubit.loadStaffForStore(storeId);
|
||||
}
|
||||
return cubit;
|
||||
},
|
||||
),
|
||||
BlocProvider<OperationListCubit>(
|
||||
create: (_) => sl<OperationListCubit>(),
|
||||
|
||||
@@ -39,9 +39,16 @@ import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
final sl = GetIt.instance;
|
||||
|
||||
Future<void> init() async {
|
||||
final envUrl = dotenv.env['SUPABASE_URL']?.trim();
|
||||
final envKey = dotenv.env['SUPABASE_PUBLISHABLE_KEY']?.trim();
|
||||
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? '',
|
||||
url: (envUrl != null && envUrl.isNotEmpty)
|
||||
? envUrl
|
||||
: 'https://supabaseapi.catelli.it',
|
||||
publishableKey: (envKey != null && envKey.isNotEmpty)
|
||||
? envKey
|
||||
: 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo',
|
||||
);
|
||||
sl.registerSingleton<SupabaseClient>(Supabase.instance.client);
|
||||
sl.registerSingleton<SharedPreferences>(
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <app_links_linux/app_links_plugin_linux.h>
|
||||
#include <file_selector_linux/file_selector_plugin.h>
|
||||
#include <gtk/gtk_plugin.h>
|
||||
#include <printing/printing_plugin.h>
|
||||
#include <url_launcher_linux/url_launcher_plugin.h>
|
||||
|
||||
void fl_register_plugins(FlPluginRegistry* registry) {
|
||||
g_autoptr(FlPluginRegistrar) app_links_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "AppLinksPluginLinux");
|
||||
app_links_plugin_linux_register_with_registrar(app_links_linux_registrar);
|
||||
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
|
||||
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
|
||||
g_autoptr(FlPluginRegistrar) gtk_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "GtkPlugin");
|
||||
gtk_plugin_register_with_registrar(gtk_registrar);
|
||||
g_autoptr(FlPluginRegistrar) printing_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "PrintingPlugin");
|
||||
printing_plugin_register_with_registrar(printing_registrar);
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
app_links_linux
|
||||
file_selector_linux
|
||||
gtk
|
||||
printing
|
||||
url_launcher_linux
|
||||
)
|
||||
|
||||
@@ -12,7 +12,7 @@ import firebase_core
|
||||
import firebase_messaging
|
||||
import package_info_plus
|
||||
import path_provider_foundation
|
||||
import pdfx
|
||||
import pdfium_flutter
|
||||
import printing
|
||||
import shared_preferences_foundation
|
||||
import url_launcher_macos
|
||||
@@ -25,7 +25,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin"))
|
||||
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
|
||||
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
|
||||
PdfxPlugin.register(with: registry.registrar(forPlugin: "PdfxPlugin"))
|
||||
PDFiumFlutterPlugin.register(with: registry.registrar(forPlugin: "PDFiumFlutterPlugin"))
|
||||
PrintingPlugin.register(with: registry.registrar(forPlugin: "PrintingPlugin"))
|
||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
|
||||
|
||||
+5
-5
@@ -76,7 +76,7 @@ PODS:
|
||||
- path_provider_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- pdfx (1.0.0):
|
||||
- pdfium_flutter (0.1.5):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- printing (1.0.0):
|
||||
@@ -97,7 +97,7 @@ DEPENDENCIES:
|
||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
|
||||
- path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`)
|
||||
- pdfx (from `Flutter/ephemeral/.symlinks/plugins/pdfx/darwin`)
|
||||
- pdfium_flutter (from `Flutter/ephemeral/.symlinks/plugins/pdfium_flutter/darwin`)
|
||||
- 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`)
|
||||
@@ -131,8 +131,8 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos
|
||||
path_provider_foundation:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin
|
||||
pdfx:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/pdfx/darwin
|
||||
pdfium_flutter:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/pdfium_flutter/darwin
|
||||
printing:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/printing/macos
|
||||
shared_preferences_foundation:
|
||||
@@ -157,7 +157,7 @@ SPEC CHECKSUMS:
|
||||
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
|
||||
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
pdfx: 824a9108791a81e400da7d1a903ab73668365072
|
||||
pdfium_flutter: f29beeb612293cc42df95beee223a4925ce2458e
|
||||
printing: 7916ffaaede65713863e621de9a4742d9fa723b9
|
||||
PromisesObjC: 752c3227f599e3467650e47ea36f433eeb10c273
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
|
||||
+91
-44
@@ -13,18 +13,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: app_links
|
||||
sha256: f8db46d2ea9ff6f3a37191a7fd5b7813da1253ace8c32c1b9eadace41d1188ea
|
||||
sha256: "08ba88bf19d9edea33130cb71c8ced2cb982b4e00b82efef4a434d1357bc69c3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.2.1"
|
||||
version: "7.2.2"
|
||||
app_links_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: app_links_linux
|
||||
sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81
|
||||
sha256: "9ccb5802085a1e57bb07b6256fd1d61a78c7ec104944d4965e62938b4fefd9cb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.3"
|
||||
version: "1.0.4"
|
||||
app_links_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -37,10 +37,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: app_links_web
|
||||
sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555
|
||||
sha256: "382d32c6f486f15b1d7f5d6a37a70a481a4fc08382eef419d373169921a3e765"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.4"
|
||||
version: "1.0.5"
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -137,6 +137,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.3"
|
||||
code_assets:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: code_assets
|
||||
sha256: "828110d598123b5ea96c00c9f3c72105bf79f8ee36c20a39b26209ade421ec57"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
collection:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -177,6 +185,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.2"
|
||||
cupertino_ui:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cupertino_ui
|
||||
sha256: ea0b8170b40a86262b2fc21ac0625303f52df209dbf6fccc2b98b27eff44f6ce
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
dart_jsonwebtoken:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -201,14 +217,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
extension:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: extension
|
||||
sha256: "1d6cc5a2d173407284780b68fd94f2b547184d4190ca7dbf6d0bf43eb43c29d8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -453,11 +461,11 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.27.2"
|
||||
gtk:
|
||||
hooks:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: gtk
|
||||
sha256: "4ff85b2a16724029dd9e5bbb5a94b6918f9973f74ba571c949d2002801879cf5"
|
||||
name: hooks
|
||||
sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
@@ -486,7 +494,7 @@ packages:
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
image:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: image
|
||||
sha256: a1e7f4951e538a568e14b856702afc9ae1d2f4b202daced8d22c1b9cd211ce89
|
||||
@@ -661,6 +669,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.13.0"
|
||||
material_ui:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: material_ui
|
||||
sha256: "98ab9eda579ecae623e4b376c603035c5def78ce706f735f30bd632af5814695"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -797,15 +813,38 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.4"
|
||||
pdfx:
|
||||
pdfium_dart:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pdfium_dart
|
||||
sha256: e296a26c030e6e0fb34b32ce7481a3cfa0c2d35ce80f6269551c685759f4c91f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
pdfium_flutter:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pdfium_flutter
|
||||
sha256: "59897274513984b347fc98e7bf71ba457678daea8b5568cd7c688979aeb77765"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
pdfrx:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "packages/pdfx"
|
||||
ref: main
|
||||
resolved-ref: "452979e49fa00df9d964422ff1bc9f1f6b122d16"
|
||||
url: "https://github.com/ScerIO/packages.flutter.git"
|
||||
source: git
|
||||
version: "2.11.0"
|
||||
name: pdfrx
|
||||
sha256: "52e78d84a706e5d63d2502689fe8e800d823bc780ac4341b2d3683a4d726505a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.6.5"
|
||||
pdfrx_engine:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pdfrx_engine
|
||||
sha256: f74ca9ea4ec722545f054a1d6ee1bf01222409ecd9458e5945c0cc5feaa3d2c6
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.1"
|
||||
permission_handler:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -862,14 +901,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.1.0"
|
||||
photo_view:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: photo_view
|
||||
sha256: "1fc3d970a91295fbd1364296575f854c9863f225505c28c46e0a03e48960c75e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.15.0"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -926,6 +957,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.1.5+1"
|
||||
pub_semver:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pub_semver
|
||||
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.1"
|
||||
qr:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -950,14 +989,30 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
record_use:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: record_use
|
||||
sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
rxdart:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: rxdart
|
||||
sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.28.0"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: shared_preferences
|
||||
sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf
|
||||
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.5"
|
||||
version: "2.5.6"
|
||||
shared_preferences_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1131,14 +1186,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.1"
|
||||
universal_platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: universal_platform
|
||||
sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
url_launcher:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -1317,4 +1364,4 @@ packages:
|
||||
version: "2.1.1"
|
||||
sdks:
|
||||
dart: ">=3.13.0 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
flutter: ">=3.47.0"
|
||||
+3
-7
@@ -1,7 +1,7 @@
|
||||
name: flux
|
||||
description: "Gestione attività negozio di telefonia"
|
||||
publish_to: 'none'
|
||||
version: 2.0.13+69
|
||||
version: 2.5.1+85
|
||||
|
||||
environment:
|
||||
sdk: ^3.11.3
|
||||
@@ -23,9 +23,9 @@ dependencies:
|
||||
go_router: ^17.2.0
|
||||
google_fonts: ^8.0.2
|
||||
image_picker: ^1.2.1
|
||||
image: ^4.10.1
|
||||
internet_file: ^1.3.0
|
||||
intl: ^0.20.2
|
||||
pdfx: ^2.9.2
|
||||
permission_handler: ^12.0.1
|
||||
qr_flutter: ^4.1.0
|
||||
shared_preferences: ^2.5.5
|
||||
@@ -42,13 +42,9 @@ dependencies:
|
||||
firebase_core: ^4.9.0
|
||||
firebase_messaging: ^16.2.2
|
||||
universal_html: ^2.3.0
|
||||
pdfrx: ^2.6.5
|
||||
|
||||
dependency_overrides:
|
||||
pdfx:
|
||||
git:
|
||||
url: https://github.com/ScerIO/packages.flutter.git
|
||||
ref: main
|
||||
path: packages/pdfx
|
||||
path_provider_foundation: 2.5.1
|
||||
|
||||
dev_dependencies:
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/core/utils/image_utils.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
void main() {
|
||||
group('ImageUtils Tests', () {
|
||||
test('rotateBytes with quarterTurns 0 or 4 returns original bytes', () {
|
||||
final dummy = Uint8List.fromList([1, 2, 3, 4]);
|
||||
expect(ImageUtils.rotateBytes(dummy, quarterTurns: 0), equals(dummy));
|
||||
expect(ImageUtils.rotateBytes(dummy, quarterTurns: 4), equals(dummy));
|
||||
});
|
||||
|
||||
test('rotateBytes correctly rotates an image by 90 degrees', () {
|
||||
// Creiamo un'immagine 10x20 (larghezza 10, altezza 20)
|
||||
final testImg = img.Image(width: 10, height: 20);
|
||||
final encodedPng = Uint8List.fromList(img.encodePng(testImg));
|
||||
|
||||
// Ruotiamo di 1 quarto (90°)
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
encodedPng,
|
||||
quarterTurns: 1,
|
||||
extension: 'png',
|
||||
);
|
||||
|
||||
final decoded = img.decodeImage(rotatedBytes);
|
||||
expect(decoded, isNotNull);
|
||||
// Dopo 90 gradi di rotazione, larghezza e altezza devono invertirsi (20x10)
|
||||
expect(decoded!.width, 20);
|
||||
expect(decoded.height, 10);
|
||||
});
|
||||
|
||||
test('rotateBytes correctly rotates an image by 180 degrees', () {
|
||||
final testImg = img.Image(width: 15, height: 30);
|
||||
final encodedPng = Uint8List.fromList(img.encodePng(testImg));
|
||||
|
||||
final rotatedBytes = ImageUtils.rotateBytes(
|
||||
encodedPng,
|
||||
quarterTurns: 2,
|
||||
extension: 'png',
|
||||
);
|
||||
|
||||
final decoded = img.decodeImage(rotatedBytes);
|
||||
expect(decoded, isNotNull);
|
||||
expect(decoded!.width, 15);
|
||||
expect(decoded.height, 30);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
|
||||
void main() {
|
||||
group('AttachmentModel Tests', () {
|
||||
test('empty() creates a valid default empty instance', () {
|
||||
final empty = AttachmentModel.empty();
|
||||
expect(empty.name, '');
|
||||
expect(empty.extension, '');
|
||||
expect(empty.fileSize, 0);
|
||||
expect(empty.companyId, '');
|
||||
expect(empty.thumbnailPath, isNull);
|
||||
expect(empty.croppedStoragePath, isNull);
|
||||
expect(empty.storagePath, isNull);
|
||||
expect(empty.viewMode, isNull);
|
||||
});
|
||||
|
||||
test('fromMap and toMap handle thumbnailPath, croppedStoragePath, and viewMode correctly', () {
|
||||
final map = {
|
||||
'id': 'att-123',
|
||||
'created_at': '2026-10-15T10:00:00.000Z',
|
||||
'customer_id': 'cust-1',
|
||||
'operation_id': 'op-1',
|
||||
'ticket_id': 'tick-1',
|
||||
'shipping_document_id': 'ship-1',
|
||||
'note_id': 'note-1',
|
||||
'name': 'documento_test',
|
||||
'extension': 'jpg',
|
||||
'storage_path': 'company/operation/op-1/orig.jpg',
|
||||
'thumbnail_path': 'company/operation/op-1/thumb.webp',
|
||||
'cropped_storage_path': 'company/operation/op-1/crop.jpg',
|
||||
'view_mode': 'cropped',
|
||||
'file_size': 204800,
|
||||
'company_id': 'comp-99',
|
||||
};
|
||||
|
||||
final model = AttachmentModel.fromMap(map);
|
||||
|
||||
expect(model.id, 'att-123');
|
||||
expect(model.name, 'documento_test');
|
||||
expect(model.extension, 'jpg');
|
||||
expect(model.storagePath, 'company/operation/op-1/orig.jpg');
|
||||
expect(model.thumbnailPath, 'company/operation/op-1/thumb.webp');
|
||||
expect(model.croppedStoragePath, 'company/operation/op-1/crop.jpg');
|
||||
expect(model.viewMode, AttachmentViewMode.cropped);
|
||||
expect(model.fileSize, 204800);
|
||||
expect(model.companyId, 'comp-99');
|
||||
|
||||
final serialized = model.toMap();
|
||||
expect(serialized['thumbnail_path'], 'company/operation/op-1/thumb.webp');
|
||||
expect(serialized['cropped_storage_path'], 'company/operation/op-1/crop.jpg');
|
||||
expect(serialized['storage_path'], 'company/operation/op-1/orig.jpg');
|
||||
expect(serialized['view_mode'], 'cropped');
|
||||
});
|
||||
|
||||
test('effectiveStoragePath resolves properly according to viewMode', () {
|
||||
const orig = 'company/orig.jpg';
|
||||
const crop = 'company/crop.jpg';
|
||||
|
||||
// 1. viewMode = cropped -> crop
|
||||
final croppedModel = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
expect(croppedModel.effectiveStoragePath, crop);
|
||||
|
||||
// 2. viewMode = original -> orig
|
||||
final originalModel = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
expect(originalModel.effectiveStoragePath, orig);
|
||||
|
||||
// 3. viewMode = null -> defaults to crop if available
|
||||
final defaultWithCrop = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
croppedStoragePath: crop,
|
||||
);
|
||||
expect(defaultWithCrop.effectiveStoragePath, crop);
|
||||
|
||||
// 4. viewMode = cropped but croppedStoragePath is null -> fallback to orig
|
||||
final fallbackToOrig = AttachmentModel.empty().copyWith(
|
||||
storagePath: orig,
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
expect(fallbackToOrig.effectiveStoragePath, orig);
|
||||
});
|
||||
|
||||
test('copyWith properly updates thumbnailPath, croppedStoragePath, and viewMode', () {
|
||||
final initial = AttachmentModel.empty().copyWith(
|
||||
name: 'test',
|
||||
extension: 'png',
|
||||
companyId: 'comp-1',
|
||||
);
|
||||
|
||||
final updated = initial.copyWith(
|
||||
thumbnailPath: 'thumbs/1.webp',
|
||||
croppedStoragePath: 'crops/1.png',
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
|
||||
expect(updated.thumbnailPath, 'thumbs/1.webp');
|
||||
expect(updated.croppedStoragePath, 'crops/1.png');
|
||||
expect(updated.viewMode, AttachmentViewMode.original);
|
||||
expect(updated.name, 'test');
|
||||
});
|
||||
|
||||
test('Equatable props comparison works as expected', () {
|
||||
final a = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
final b = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.cropped,
|
||||
);
|
||||
final c = AttachmentModel.empty().copyWith(
|
||||
id: '1',
|
||||
thumbnailPath: 'thumb.webp',
|
||||
croppedStoragePath: 'crop.jpg',
|
||||
viewMode: AttachmentViewMode.original,
|
||||
);
|
||||
|
||||
expect(a, equals(b));
|
||||
expect(a, isNot(equals(c)));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart';
|
||||
import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart';
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_type.dart';
|
||||
|
||||
void main() {
|
||||
group('StaffDailyRicontattiSummary', () {
|
||||
test('correctly evaluates hasReachedGoal, hasStarted, isZero', () {
|
||||
const summaryZero = StaffDailyRicontattiSummary(
|
||||
staffId: '1',
|
||||
staffName: 'Mario Rossi',
|
||||
count: 0,
|
||||
);
|
||||
expect(summaryZero.isZero, isTrue);
|
||||
expect(summaryZero.hasStarted, isFalse);
|
||||
expect(summaryZero.hasReachedGoal, isFalse);
|
||||
|
||||
const summaryOne = StaffDailyRicontattiSummary(
|
||||
staffId: '2',
|
||||
staffName: 'Luigi Bianchi',
|
||||
count: 1,
|
||||
);
|
||||
expect(summaryOne.isZero, isFalse);
|
||||
expect(summaryOne.hasStarted, isTrue);
|
||||
expect(summaryOne.hasReachedGoal, isFalse);
|
||||
|
||||
const summaryTwo = StaffDailyRicontattiSummary(
|
||||
staffId: '3',
|
||||
staffName: 'Anna Verdi',
|
||||
count: 2,
|
||||
);
|
||||
expect(summaryTwo.isZero, isFalse);
|
||||
expect(summaryTwo.hasStarted, isFalse);
|
||||
expect(summaryTwo.hasReachedGoal, isTrue);
|
||||
|
||||
const summaryFive = StaffDailyRicontattiSummary(
|
||||
staffId: '4',
|
||||
staffName: 'Paolo Neri',
|
||||
count: 5,
|
||||
);
|
||||
expect(summaryFive.isZero, isFalse);
|
||||
expect(summaryFive.hasStarted, isFalse);
|
||||
expect(summaryFive.hasReachedGoal, isTrue);
|
||||
});
|
||||
|
||||
test('copyWith updates fields as expected', () {
|
||||
const original = StaffDailyRicontattiSummary(
|
||||
staffId: '1',
|
||||
staffName: 'Mario',
|
||||
count: 0,
|
||||
systemRole: SystemRole.user,
|
||||
);
|
||||
|
||||
final updated = original.copyWith(
|
||||
count: 3,
|
||||
monthCount: 15,
|
||||
systemRole: SystemRole.manager,
|
||||
);
|
||||
|
||||
expect(updated.count, equals(3));
|
||||
expect(updated.monthCount, equals(15));
|
||||
expect(updated.systemRole, equals(SystemRole.manager));
|
||||
expect(updated.staffName, equals('Mario'));
|
||||
expect(updated.staffId, equals('1'));
|
||||
});
|
||||
});
|
||||
|
||||
group('DashboardDailyRicontattiState', () {
|
||||
test('computes staffWithGoal, staffWithOne, staffAtZero correctly', () {
|
||||
final state = DashboardDailyRicontattiState(
|
||||
date: DateTime(2026, 10, 9),
|
||||
summaries: const [
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: '1',
|
||||
staffName: 'Mario',
|
||||
count: 3, // >= 2
|
||||
monthCount: 18,
|
||||
),
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: '2',
|
||||
staffName: 'Luigi',
|
||||
count: 2, // >= 2
|
||||
monthCount: 12,
|
||||
),
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: '3',
|
||||
staffName: 'Anna',
|
||||
count: 1, // == 1
|
||||
monthCount: 9,
|
||||
),
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: '4',
|
||||
staffName: 'Paolo',
|
||||
count: 0, // == 0
|
||||
monthCount: 5,
|
||||
),
|
||||
StaffDailyRicontattiSummary(
|
||||
staffId: '5',
|
||||
staffName: 'Giulia',
|
||||
count: 0, // == 0
|
||||
monthCount: 0,
|
||||
),
|
||||
],
|
||||
totalRicontattiToday: 6,
|
||||
totalRicontattiMonth: 44,
|
||||
);
|
||||
|
||||
expect(state.activeStaffCount, equals(5));
|
||||
expect(state.staffWithGoal, equals(2));
|
||||
expect(state.staffWithOne, equals(1));
|
||||
expect(state.staffAtZero, equals(2));
|
||||
expect(state.totalRicontattiToday, equals(6));
|
||||
expect(state.totalRicontattiMonth, equals(44));
|
||||
});
|
||||
});
|
||||
|
||||
group('OperationType.ricontatto', () {
|
||||
test('resolves from string accurately', () {
|
||||
expect(OperationType.fromValue('ricontatto'), equals(OperationType.ricontatto));
|
||||
expect(OperationType.fromValue('Ricontatto'), equals(OperationType.ricontatto));
|
||||
expect(OperationType.fromValue('RICONTATTO'), equals(OperationType.ricontatto));
|
||||
});
|
||||
});
|
||||
|
||||
group('StaffMemberModel jobTitle discriminants', () {
|
||||
test('canViewRicontattiFocus identifies Manager and Titolare by jobTitle', () {
|
||||
final manager = StaffMemberModel.empty().copyWith(jobTitle: 'Manager');
|
||||
final titolare = StaffMemberModel.empty().copyWith(jobTitle: 'Titolare');
|
||||
final storeManager = StaffMemberModel.empty().copyWith(jobTitle: 'Store Manager');
|
||||
final addetto = StaffMemberModel.empty().copyWith(
|
||||
jobTitle: 'Addetto Vendite',
|
||||
systemRole: SystemRole.user,
|
||||
);
|
||||
final admin = StaffMemberModel.empty().copyWith(
|
||||
jobTitle: 'Tecnico',
|
||||
systemRole: SystemRole.admin,
|
||||
);
|
||||
|
||||
expect(manager.canViewRicontattiFocus, isTrue);
|
||||
expect(titolare.canViewRicontattiFocus, isTrue);
|
||||
expect(storeManager.canViewRicontattiFocus, isTrue);
|
||||
expect(addetto.canViewRicontattiFocus, isFalse);
|
||||
expect(admin.canViewRicontattiFocus, isTrue);
|
||||
});
|
||||
|
||||
test('excludes Manager, Titolare, Tester from controlled staff', () {
|
||||
final manager = StaffMemberModel.empty().copyWith(jobTitle: 'Manager');
|
||||
final titolare = StaffMemberModel.empty().copyWith(jobTitle: 'Titolare');
|
||||
final tester = StaffMemberModel.empty().copyWith(jobTitle: 'Tester');
|
||||
final betaTester = StaffMemberModel.empty().copyWith(jobTitle: 'BETA TESTER');
|
||||
final inactive = StaffMemberModel.empty().copyWith(
|
||||
jobTitle: 'Addetto',
|
||||
isActive: false,
|
||||
);
|
||||
|
||||
expect(manager.isExcludedFromControlledStaff, isTrue);
|
||||
expect(titolare.isExcludedFromControlledStaff, isTrue);
|
||||
expect(tester.isExcludedFromControlledStaff, isTrue);
|
||||
expect(betaTester.isExcludedFromControlledStaff, isTrue);
|
||||
expect(inactive.isExcludedFromControlledStaff, isTrue);
|
||||
});
|
||||
|
||||
test('addetto with systemRole manager is still controlled staff', () {
|
||||
// systemRole indica permessi app, jobTitle indica il ruolo operativo in negozio
|
||||
final addettoWithAdminPerms = StaffMemberModel.empty().copyWith(
|
||||
jobTitle: 'Addetto Vendite',
|
||||
systemRole: SystemRole.manager,
|
||||
isActive: true,
|
||||
);
|
||||
expect(addettoWithAdminPerms.isExcludedFromControlledStaff, isFalse);
|
||||
expect(addettoWithAdminPerms.isManagerOrTitolare, isFalse);
|
||||
expect(addettoWithAdminPerms.canViewRicontattiFocus, isFalse);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flux/features/operations/models/financing_translations.dart';
|
||||
|
||||
void main() {
|
||||
group('FinancingTranslations', () {
|
||||
test('contains all 9 requested languages', () {
|
||||
final supportedCodes = FinancingTranslations.supportedLanguages.map((l) => l.code).toSet();
|
||||
expect(
|
||||
supportedCodes,
|
||||
containsAll([
|
||||
'it',
|
||||
'en',
|
||||
'fr',
|
||||
'es',
|
||||
'ar',
|
||||
'uk',
|
||||
'ru',
|
||||
'mk',
|
||||
'sq',
|
||||
]),
|
||||
);
|
||||
expect(FinancingTranslations.supportedLanguages.length, 9);
|
||||
});
|
||||
|
||||
test('Arabic is marked as RTL', () {
|
||||
final ar = FinancingTranslations.supportedLanguages.firstWhere((l) => l.code == 'ar');
|
||||
expect(ar.isRtl, isTrue);
|
||||
|
||||
final it = FinancingTranslations.supportedLanguages.firstWhere((l) => l.code == 'it');
|
||||
expect(it.isRtl, isFalse);
|
||||
});
|
||||
|
||||
test('formatNoteText outputs canonical Italian labels regardless of language', () {
|
||||
final noteText = FinancingTranslations.formatNoteText(
|
||||
maritalStatusIndex: 0, // Celibe / Nubile
|
||||
occupation: 'Ingegnere Informatico',
|
||||
incomeRangeIndex: 1, // Da 2.000 € a 5.000 €
|
||||
languageName: 'العربية (Arabo)',
|
||||
);
|
||||
|
||||
expect(noteText, contains('[DATI FINANZIAMENTO]'));
|
||||
expect(noteText, contains('Stato civile: Celibe / Nubile'));
|
||||
expect(noteText, contains('Professione: Ingegnere Informatico'));
|
||||
expect(noteText, contains('Reddito mensile: Da 2.000 € a 5.000 €'));
|
||||
expect(noteText, contains('Lingua: العربية (Arabo)'));
|
||||
});
|
||||
|
||||
test('each language has exactly 5 marital status and 3 income range options', () {
|
||||
for (final lang in FinancingTranslations.supportedLanguages) {
|
||||
final strings = FinancingTranslations.getStrings(lang.code);
|
||||
expect(strings.maritalOptions.length, 5, reason: 'Language ${lang.code} should have 5 marital options');
|
||||
expect(strings.incomeOptions.length, 3, reason: 'Language ${lang.code} should have 3 income options');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
<base href="$FLUTTER_BASE_HREF">
|
||||
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
|
||||
<meta name="description" content="Gestione attività negozio di telefonia">
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
#include <app_links/app_links_plugin_c_api.h>
|
||||
#include <file_selector_windows/file_selector_windows.h>
|
||||
#include <firebase_core/firebase_core_plugin_c_api.h>
|
||||
#include <pdfx/pdfx_plugin.h>
|
||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||
#include <printing/printing_plugin.h>
|
||||
#include <url_launcher_windows/url_launcher_windows.h>
|
||||
@@ -21,8 +20,6 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
registry->GetRegistrarForPlugin("FileSelectorWindows"));
|
||||
FirebaseCorePluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FirebaseCorePluginCApi"));
|
||||
PdfxPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("PdfxPlugin"));
|
||||
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
|
||||
PrintingPluginRegisterWithRegistrar(
|
||||
|
||||
@@ -6,7 +6,6 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
||||
app_links
|
||||
file_selector_windows
|
||||
firebase_core
|
||||
pdfx
|
||||
permission_handler_windows
|
||||
printing
|
||||
url_launcher_windows
|
||||
|
||||
Reference in new issue
Block a user