68 lines
1.8 KiB
Dart
68 lines
1.8 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:collection/collection.dart';
|
|
|
|
import 'package:pshared/models/payment/source.dart';
|
|
import 'package:pshared/provider/payment/source.dart';
|
|
|
|
|
|
class PaymentSourceController extends ChangeNotifier {
|
|
PaymentSourceProvider? _provider;
|
|
String? _selectedSourceKey;
|
|
|
|
List<PaymentSource> get sources => _provider?.sources ?? const [];
|
|
|
|
PaymentSource? get selectedSource {
|
|
final key = _selectedSourceKey;
|
|
if (key == null) return null;
|
|
return sources.firstWhereOrNull((source) => source.key == key);
|
|
}
|
|
|
|
void update(PaymentSourceProvider provider) {
|
|
_provider = provider;
|
|
final nextSources = provider.sources;
|
|
final nextSelectedKey = _resolveSelectedKey(
|
|
currentKey: _selectedSourceKey,
|
|
sources: nextSources,
|
|
);
|
|
|
|
if (nextSelectedKey == _selectedSourceKey) return;
|
|
_selectedSourceKey = nextSelectedKey;
|
|
notifyListeners();
|
|
}
|
|
|
|
void selectSource(PaymentSource source) {
|
|
if (_selectedSourceKey == source.key) return;
|
|
_selectedSourceKey = source.key;
|
|
notifyListeners();
|
|
}
|
|
|
|
void selectWalletByRef(String walletRef) {
|
|
final source = sources.firstWhereOrNull(
|
|
(s) => s.type == PaymentSourceType.wallet && s.id == walletRef,
|
|
);
|
|
if (source == null) return;
|
|
selectSource(source);
|
|
}
|
|
|
|
void selectLedgerByRef(String ledgerAccountRef) {
|
|
final source = sources.firstWhereOrNull(
|
|
(s) => s.type == PaymentSourceType.ledger && s.id == ledgerAccountRef,
|
|
);
|
|
if (source == null) return;
|
|
selectSource(source);
|
|
}
|
|
|
|
String? _resolveSelectedKey({
|
|
required String? currentKey,
|
|
required List<PaymentSource> sources,
|
|
}) {
|
|
if (sources.isEmpty) return null;
|
|
if (currentKey != null &&
|
|
sources.any((source) => source.key == currentKey)) {
|
|
return currentKey;
|
|
}
|
|
return sources.first.key;
|
|
}
|
|
}
|