98 lines
2.8 KiB
Dart
98 lines
2.8 KiB
Dart
import 'package:aioa_mobile/core/auth/authenticated_http_client.dart';
|
|
import 'package:aioa_mobile/core/config/runtime_config.dart';
|
|
import 'dart:typed_data';
|
|
|
|
import 'package:aioa_mobile/features/form/data/leave_attachment_repository.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
|
|
final leaveAttachmentRepositoryProvider = Provider<LeaveAttachmentRepository>(
|
|
(ref) => LeaveAttachmentRepository(
|
|
client: ref.watch(authenticatedHttpClientProvider),
|
|
baseUrl: RuntimeConfig.apiBaseUrl,
|
|
),
|
|
);
|
|
|
|
class LeaveAttachmentState {
|
|
const LeaveAttachmentState({
|
|
this.items = const [],
|
|
this.uploading = false,
|
|
this.progress = 0,
|
|
this.error,
|
|
});
|
|
|
|
final List<LeaveAttachmentItem> items;
|
|
final bool uploading;
|
|
final double progress;
|
|
final String? error;
|
|
|
|
LeaveAttachmentState copyWith({
|
|
List<LeaveAttachmentItem>? items,
|
|
bool? uploading,
|
|
double? progress,
|
|
String? error,
|
|
bool clearError = false,
|
|
}) => LeaveAttachmentState(
|
|
items: items ?? this.items,
|
|
uploading: uploading ?? this.uploading,
|
|
progress: progress ?? this.progress,
|
|
error: clearError ? null : error ?? this.error,
|
|
);
|
|
}
|
|
|
|
final leaveAttachmentProvider =
|
|
NotifierProvider.family<
|
|
LeaveAttachmentController,
|
|
LeaveAttachmentState,
|
|
String
|
|
>((leaveRequestId) => LeaveAttachmentController(leaveRequestId));
|
|
|
|
class LeaveAttachmentController extends Notifier<LeaveAttachmentState> {
|
|
LeaveAttachmentController(this._leaveRequestId);
|
|
|
|
final String _leaveRequestId;
|
|
|
|
@override
|
|
LeaveAttachmentState build() => const LeaveAttachmentState();
|
|
|
|
Future<void> load() async {
|
|
try {
|
|
final items = await ref
|
|
.read(leaveAttachmentRepositoryProvider)
|
|
.list(_leaveRequestId);
|
|
state = state.copyWith(items: items, clearError: true);
|
|
} on LeaveAttachmentException catch (error) {
|
|
state = state.copyWith(error: error.message);
|
|
}
|
|
}
|
|
|
|
Future<void> upload({
|
|
required String fileName,
|
|
required String contentType,
|
|
required Uint8List bytes,
|
|
}) async {
|
|
if (state.uploading) return;
|
|
state = state.copyWith(uploading: true, progress: 0, clearError: true);
|
|
try {
|
|
final item = await ref
|
|
.read(leaveAttachmentRepositoryProvider)
|
|
.upload(
|
|
leaveRequestId: _leaveRequestId,
|
|
fileName: fileName,
|
|
contentType: contentType,
|
|
bytes: bytes,
|
|
onProgress: (progress) {
|
|
state = state.copyWith(progress: progress);
|
|
},
|
|
);
|
|
state = state.copyWith(
|
|
items: [...state.items, item],
|
|
uploading: false,
|
|
progress: 1,
|
|
clearError: true,
|
|
);
|
|
} on LeaveAttachmentException catch (error) {
|
|
state = state.copyWith(uploading: false, error: error.message);
|
|
}
|
|
}
|
|
}
|