Files
flux/lib/features/company/data/company_repository.dart

98 lines
2.8 KiB
Dart
Raw Permalink Normal View History

2026-05-08 12:28:14 +02:00
import 'dart:typed_data';
2026-05-20 11:03:33 +02:00
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/company_model.dart';
class CompanyRepository {
final SupabaseClient _supabase = Supabase.instance.client;
Future<CompanyModel> createCompany(CompanyModel company) async {
try {
// .select().single() trasforma la risposta nell'oggetto appena inserito
final response = await _supabase
2026-05-20 11:03:33 +02:00
.from(Tables.companies)
.insert(company.toMap())
.select()
.single();
return CompanyModel.fromMap(response);
} on PostgrestException catch (e) {
throw e.message;
} catch (e) {
throw e.toString();
}
}
2026-05-08 12:28:14 +02:00
Future<CompanyModel> updateCompany(CompanyModel company) async {
try {
final response = await _supabase
2026-05-20 11:03:33 +02:00
.from(Tables.companies)
2026-05-08 12:28:14 +02:00
.update(company.toMap())
.eq('id', company.id!)
.select()
.single();
return CompanyModel.fromMap(response);
} on PostgrestException catch (e) {
throw e.message;
} catch (e) {
throw e.toString();
}
}
Future<String> uploadCompanyLogo({
required String companyId,
required Uint8List fileBytes,
required String fileName,
}) async {
try {
// 1. Prepariamo il path.
// Organizziamo per companyId e aggiungiamo un timestamp per evitare cache del browser
// quando l'utente cambia logo più volte.
final extension = fileName.split('.').last;
final timestamp = DateTime.now().millisecondsSinceEpoch;
final filePath = '$companyId/logo_$timestamp.$extension';
// 2. Caricamento fisico dei bytes
// Usiamo uploadBinary che è perfetto per Uint8List
await _supabase.storage
.from('company_logos')
.uploadBinary(
filePath,
fileBytes,
fileOptions: const FileOptions(
cacheControl: '3600',
upsert:
true, // Se esiste già un file con lo stesso nome, lo sovrascrive
),
);
// 3. Otteniamo l'URL pubblico.
// Nota: il bucket 'company_logos' deve essere impostato come PUBLIC su Supabase
final String publicUrl = _supabase.storage
.from('company_logos')
.getPublicUrl(filePath);
return publicUrl;
} catch (e) {
throw Exception("Errore durante l'upload del logo: $e");
}
}
Future<CompanyModel?> getCompany() async {
try {
final userId = _supabase.auth.currentUser?.id;
final response = await _supabase
2026-05-20 11:03:33 +02:00
.from(Tables.companies)
.select()
.eq('user_id', userId as Object)
.maybeSingle();
return response != null ? CompanyModel.fromMap(response) : null;
} catch (e) {
return null;
}
}
}