71 lines
1.9 KiB
Dart
71 lines
1.9 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
|
|
class DocumentSequenceState {
|
|
final List<DocumentSequence> sequences;
|
|
final bool isLoading;
|
|
final String? error;
|
|
|
|
DocumentSequenceState({
|
|
this.sequences = const [],
|
|
this.isLoading = false,
|
|
this.error,
|
|
});
|
|
}
|
|
|
|
class DocumentSequenceCubit extends Cubit<DocumentSequenceState> {
|
|
final String companyId;
|
|
final _supabase = Supabase.instance.client;
|
|
|
|
DocumentSequenceCubit(this.companyId) : super(DocumentSequenceState());
|
|
|
|
Future<void> loadSequences() async {
|
|
emit(DocumentSequenceState(isLoading: true));
|
|
try {
|
|
final data = await _supabase
|
|
.from('document_sequences')
|
|
.select()
|
|
.eq('company_id', companyId);
|
|
|
|
final list = (data as List)
|
|
.map((e) => DocumentSequence.fromMap(e))
|
|
.toList();
|
|
emit(DocumentSequenceState(sequences: list));
|
|
} catch (e) {
|
|
emit(DocumentSequenceState(error: e.toString()));
|
|
}
|
|
}
|
|
|
|
void updateLocalSequence(String docType, {String? prefix, int? nextValue}) {
|
|
final newList = state.sequences.map((s) {
|
|
if (s.docType == docType) {
|
|
return s.copyWith(prefix: prefix, nextValue: nextValue);
|
|
}
|
|
return s;
|
|
}).toList();
|
|
emit(DocumentSequenceState(sequences: newList));
|
|
}
|
|
|
|
Future<void> saveSequences() async {
|
|
try {
|
|
for (var seq in state.sequences) {
|
|
await _supabase.from('document_sequences').upsert({
|
|
'company_id': companyId,
|
|
'doc_type': seq.docType,
|
|
'next_value': seq.nextValue,
|
|
'prefix': seq.prefix,
|
|
});
|
|
}
|
|
// Opzionale: mostra un feedback di successo
|
|
} catch (e) {
|
|
emit(
|
|
DocumentSequenceState(
|
|
sequences: state.sequences,
|
|
error: "Errore nel salvataggio",
|
|
),
|
|
);
|
|
}
|
|
}
|
|
}
|