Quotation

This commit is contained in:
Arseni
2026-01-21 21:52:36 +03:00
parent 1e5ff51e07
commit 6284625977
40 changed files with 1085 additions and 346 deletions

View File

@@ -10,12 +10,13 @@ import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/payment/amount.dart';
import 'package:pshared/provider/payment/flow.dart';
import 'package:pshared/provider/payment/provider.dart';
import 'package:pshared/provider/payment/quotation.dart';
import 'package:pshared/provider/payment/quotation/quotation.dart';
import 'package:pshared/provider/recipient/provider.dart';
import 'package:pshared/provider/recipient/pmethods.dart';
import 'package:pweb/app/router/pages.dart';
import 'package:pweb/app/router/payout_routes.dart';
import 'package:pweb/providers/quotation/quotation.dart';
import 'package:pshared/models/payment/wallet.dart';
import 'package:pweb/pages/address_book/form/page.dart';
import 'package:pweb/pages/address_book/page/page.dart';
@@ -57,6 +58,10 @@ RouteBase payoutShellRoute() => ShellRoute(
update: (_, organization, payment, wallet, flow, recipients, methods, provider) =>
provider!..update(organization, payment, wallet, flow, recipients, methods),
),
ChangeNotifierProxyProvider<QuotationProvider, QuotationController>(
create: (_) => QuotationController(),
update: (_, quotation, controller) => controller!..update(quotation),
),
ChangeNotifierProxyProvider2<OrganizationsProvider, QuotationProvider, PaymentProvider>(
create: (_) => PaymentProvider(),
update: (context, organization, quotation, provider) => provider!..update(

View File

@@ -438,6 +438,29 @@
"payout": "Payout",
"sendTo": "Send Payout To",
"send": "Send Payout",
"quoteUnavailable": "Waiting for a quote...",
"quoteUpdating": "Refreshing quote...",
"quoteExpiresIn": "Quote expires in {time}",
"@quoteExpiresIn": {
"placeholders": {
"time": {
"type": "String"
}
}
},
"quoteActive": "Quote is active",
"quoteExpired": "Quote expired, request a new one",
"quoteAutoRefresh": "Auto-refresh quote",
"quoteAutoRefreshHint": "Keeps the quote current while you prepare the payout",
"quoteAutoRefreshEnabled": "Auto-refresh is on",
"quoteAutoRefreshDisabled": "Auto-refresh is off",
"quoteEnableAutoRefresh": "Enable auto-refresh",
"quoteDisableAutoRefresh": "Disable auto-refresh",
"quoteRefresh": "Refresh quote",
"quoteRefreshRequired": "Refresh the quote to enable payout",
"quoteErrorGeneric": "Could not refresh quote, try again later",
"toggleOn": "On",
"toggleOff": "Off",
"refreshBalance": "Refresh balance",
"recipientPaysFee": "Recipient pays the fee",

View File

@@ -438,6 +438,29 @@
"payout": "Выплата",
"sendTo": "Отправить выплату",
"send": "Отправить выплату",
"quoteUnavailable": "Ожидание котировки...",
"quoteUpdating": "Обновляем котировку...",
"quoteExpiresIn": "Котировка истекает через {time}",
"@quoteExpiresIn": {
"placeholders": {
"time": {
"type": "String"
}
}
},
"quoteActive": "Котировка активна",
"quoteExpired": "Срок котировки истек, запросите новую",
"quoteAutoRefresh": "Автообновление котировки",
"quoteAutoRefreshHint": "Поддерживает котировку актуальной во время подготовки выплаты",
"quoteAutoRefreshEnabled": "Автообновление включено",
"quoteAutoRefreshDisabled": "Автообновление выключено",
"quoteEnableAutoRefresh": "Включить автообновление",
"quoteDisableAutoRefresh": "Выключить автообновление",
"quoteRefresh": "Обновить котировку",
"quoteRefreshRequired": "Обновите котировку, чтобы продолжить выплату",
"quoteErrorGeneric": "Не удалось обновить котировку, повторите позже",
"toggleOn": "Вкл",
"toggleOff": "Выкл",
"refreshBalance": "Обновить баланс",
"recipientPaysFee": "Получатель оплачивает комиссию",

View File

@@ -0,0 +1 @@
enum ButtonState { enabled, disabled, loading }

View File

@@ -48,51 +48,54 @@ class _DashboardPageState extends State<DashboardPage> {
}
@override
Widget build(BuildContext context) => PageViewLoader(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
flex: 0,
child: TransactionRefButton(
onTap: () => _setActive(true),
isActive: _showContainerSingle,
label: AppLocalizations.of(context)!.sendSingle,
icon: Icons.person_add,
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return PageViewLoader(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
flex: 0,
child: TransactionRefButton(
onTap: () => _setActive(true),
isActive: _showContainerSingle,
label: l10n.sendSingle,
icon: Icons.person_add,
),
),
),
const SizedBox(width: AppSpacing.small),
Expanded(
flex: 0,
child: TransactionRefButton(
onTap: () => _setActive(false),
isActive: _showContainerMultiple,
label: AppLocalizations.of(context)!.sendMultiple,
icon: Icons.group_add,
const SizedBox(width: AppSpacing.small),
Expanded(
flex: 0,
child: TransactionRefButton(
onTap: () => _setActive(false),
isActive: _showContainerMultiple,
label: l10n.sendMultiple,
icon: Icons.group_add,
),
),
),
],
),
const SizedBox(height: AppSpacing.medium),
BalanceWidget(
onTopUp: widget.onTopUp,
),
const SizedBox(height: AppSpacing.small),
if (_showContainerMultiple) TitleMultiplePayout(),
const SizedBox(height: AppSpacing.medium),
if (_showContainerSingle)
SinglePayoutForm(
onRecipientSelected: widget.onRecipientSelected,
onGoToPayment: widget.onGoToPaymentWithoutRecipient,
],
),
if (_showContainerMultiple) MultiplePayoutForm(),
],
const SizedBox(height: AppSpacing.medium),
BalanceWidget(
onTopUp: widget.onTopUp,
),
const SizedBox(height: AppSpacing.small),
if (_showContainerMultiple) TitleMultiplePayout(),
const SizedBox(height: AppSpacing.medium),
if (_showContainerSingle)
SinglePayoutForm(
onRecipientSelected: widget.onRecipientSelected,
onGoToPayment: widget.onGoToPaymentWithoutRecipient,
),
if (_showContainerMultiple) MultiplePayoutForm(),
],
),
),
),
),
);
);
}
}

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:pweb/pages/dashboard/payouts/amount.dart';
import 'package:pweb/pages/dashboard/payouts/fee_payer.dart';
import 'package:pweb/pages/dashboard/payouts/quote_status/quote_status.dart';
import 'package:pweb/pages/dashboard/payouts/summary/widget.dart';
import 'package:pweb/generated/i18n/app_localizations.dart';
@@ -36,8 +37,9 @@ class PaymentFormWidget extends StatelessWidget {
const SizedBox(height: _largeSpacing),
const PaymentSummary(spacing: _extraSpacing),
const SizedBox(height: _mediumSpacing),
const QuoteStatus(spacing: _smallSpacing),
],
);
}
}

View File

@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pshared/models/payment/quote/status_type.dart';
import 'package:pweb/providers/quotation/quotation.dart';
import 'package:pweb/pages/dashboard/payouts/quote_status/widgets/body.dart';
import 'package:pweb/utils/quote_duration_format.dart';
import 'package:pweb/generated/i18n/app_localizations.dart';
class QuoteStatus extends StatelessWidget {
final double spacing;
const QuoteStatus({super.key, required this.spacing});
@override
Widget build(BuildContext context) {
final loc = AppLocalizations.of(context)!;
final controller = context.watch<QuotationController>();
final timeLeft = controller.timeLeft;
final isLoading = controller.isLoading;
final statusType = controller.quoteStatus;
final autoRefreshMode = controller.autoRefreshMode;
String statusText;
String? helperText;
switch (statusType) {
case QuoteStatusType.loading:
statusText = loc.quoteUpdating;
break;
case QuoteStatusType.error:
statusText = loc.quoteErrorGeneric;
break;
case QuoteStatusType.missing:
statusText = loc.quoteUnavailable;
break;
case QuoteStatusType.expired:
statusText = loc.quoteExpired;
helperText = loc.quoteRefreshRequired;
break;
case QuoteStatusType.active:
statusText = timeLeft == null
? loc.quoteActive
: loc.quoteExpiresIn(formatQuoteDuration(timeLeft));
break;
}
final canRefresh = controller.canRefresh && !isLoading;
final showPrimaryRefresh = canRefresh &&
(statusType == QuoteStatusType.expired ||
statusType == QuoteStatusType.error ||
statusType == QuoteStatusType.missing);
return QuoteStatusBody(
spacing: spacing,
statusType: statusType,
statusText: statusText,
helperText: helperText,
isLoading: isLoading,
canRefresh: canRefresh,
showPrimaryRefresh: showPrimaryRefresh,
autoRefreshMode: autoRefreshMode,
onAutoRefreshModeChanged: controller.setAutoRefreshMode,
onRefresh: controller.refreshQuotation,
);
}
}

View File

@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import 'package:pshared/models/payment/quote/status_type.dart';
import 'package:pshared/models/auto_refresh_mode.dart';
import 'package:pweb/pages/dashboard/payouts/quote_status/widgets/refresh_section.dart';
import 'package:pweb/pages/dashboard/payouts/quote_status/widgets/card.dart';
class QuoteStatusBody extends StatelessWidget {
final double spacing;
final QuoteStatusType statusType;
final String statusText;
final String? helperText;
final bool isLoading;
final bool canRefresh;
final bool showPrimaryRefresh;
final AutoRefreshMode autoRefreshMode;
final ValueChanged<AutoRefreshMode> onAutoRefreshModeChanged;
final VoidCallback onRefresh;
const QuoteStatusBody({
super.key,
required this.spacing,
required this.statusType,
required this.statusText,
required this.helperText,
required this.isLoading,
required this.canRefresh,
required this.showPrimaryRefresh,
required this.autoRefreshMode,
required this.onAutoRefreshModeChanged,
required this.onRefresh,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
QuoteStatusCard(
statusType: statusType,
isLoading: isLoading,
statusText: statusText,
helperText: helperText,
canRefresh: canRefresh,
showPrimaryRefresh: showPrimaryRefresh,
onRefresh: onRefresh,
),
SizedBox(height: spacing),
QuoteAutoRefreshSection(
autoRefreshMode: autoRefreshMode,
canRefresh: canRefresh,
onModeChanged: onAutoRefreshModeChanged,
),
],
);
}
}

View File

@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import 'package:pshared/models/payment/quote/status_type.dart';
import 'package:pweb/generated/i18n/app_localizations.dart';
class QuoteStatusCard extends StatelessWidget {
final QuoteStatusType statusType;
final bool isLoading;
final String statusText;
final String? helperText;
final bool canRefresh;
final bool showPrimaryRefresh;
final VoidCallback onRefresh;
const QuoteStatusCard({
super.key,
required this.statusType,
required this.isLoading,
required this.statusText,
required this.helperText,
required this.canRefresh,
required this.showPrimaryRefresh,
required this.onRefresh,
});
static const double _cardRadius = 12;
static const double _cardSpacing = 12;
static const double _iconSize = 18;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final foregroundColor = _resolveForegroundColor(theme, statusType);
final statusStyle = theme.textTheme.bodyMedium?.copyWith(color: foregroundColor);
final helperStyle = theme.textTheme.bodySmall?.copyWith(
color: foregroundColor.withValues(alpha: 0.8),
);
return Container(
padding: const EdgeInsets.all(_cardSpacing),
decoration: BoxDecoration(
color: _resolveCardColor(theme, statusType),
borderRadius: BorderRadius.circular(_cardRadius),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 2),
child: isLoading
? SizedBox(
width: _iconSize,
height: _iconSize,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(foregroundColor),
),
)
: Icon(
_resolveIcon(statusType),
size: _iconSize,
color: foregroundColor,
),
),
const SizedBox(width: _cardSpacing),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(statusText, style: statusStyle),
if (helperText != null) ...[
const SizedBox(height: 4),
Text(helperText!, style: helperStyle),
],
],
),
),
if (canRefresh)
Padding(
padding: const EdgeInsets.only(left: _cardSpacing),
child: showPrimaryRefresh
? ElevatedButton(
onPressed: canRefresh ? onRefresh : null,
child: Text(AppLocalizations.of(context)!.quoteRefresh),
)
: TextButton(
onPressed: canRefresh ? onRefresh : null,
child: Text(AppLocalizations.of(context)!.quoteRefresh),
),
),
],
),
);
}
Color _resolveCardColor(ThemeData theme, QuoteStatusType status) {
switch (status) {
case QuoteStatusType.loading:
return theme.colorScheme.secondaryContainer;
case QuoteStatusType.error:
case QuoteStatusType.expired:
return theme.colorScheme.errorContainer;
case QuoteStatusType.active:
return theme.colorScheme.primaryContainer;
case QuoteStatusType.missing:
return theme.colorScheme.surfaceContainerHighest;
}
}
Color _resolveForegroundColor(ThemeData theme, QuoteStatusType status) {
switch (status) {
case QuoteStatusType.loading:
return theme.colorScheme.onSecondaryContainer;
case QuoteStatusType.error:
case QuoteStatusType.expired:
return theme.colorScheme.onErrorContainer;
case QuoteStatusType.active:
return theme.colorScheme.onPrimaryContainer;
case QuoteStatusType.missing:
return theme.colorScheme.onSurfaceVariant;
}
}
IconData _resolveIcon(QuoteStatusType status) {
switch (status) {
case QuoteStatusType.loading:
return Icons.sync_rounded;
case QuoteStatusType.error:
return Icons.warning_amber_rounded;
case QuoteStatusType.expired:
return Icons.error_outline_rounded;
case QuoteStatusType.active:
return Icons.timer_outlined;
case QuoteStatusType.missing:
return Icons.info_outline_rounded;
}
}
}

View File

@@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
import 'package:pshared/models/auto_refresh_mode.dart';
import 'package:pweb/generated/i18n/app_localizations.dart';
class QuoteAutoRefreshSection extends StatelessWidget {
final AutoRefreshMode autoRefreshMode;
final bool canRefresh;
final ValueChanged<AutoRefreshMode> onModeChanged;
const QuoteAutoRefreshSection({
super.key,
required this.autoRefreshMode,
required this.canRefresh,
required this.onModeChanged,
});
static const double _autoRefreshSpacing = 8;
@override
Widget build(BuildContext context) {
final loc = AppLocalizations.of(context)!;
final theme = Theme.of(context);
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
autoRefreshMode == AutoRefreshMode.on
? loc.quoteAutoRefreshEnabled
: loc.quoteAutoRefreshDisabled,
style: theme.textTheme.bodyMedium,
),
const SizedBox(height: 2),
Text(
loc.quoteAutoRefreshHint,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.textTheme.bodySmall?.color?.withValues(alpha: 0.7),
),
),
],
),
),
const SizedBox(width: _autoRefreshSpacing),
ToggleButtons(
isSelected: [
autoRefreshMode == AutoRefreshMode.off,
autoRefreshMode == AutoRefreshMode.on,
],
onPressed: canRefresh
? (index) {
final nextMode =
index == 1 ? AutoRefreshMode.on : AutoRefreshMode.off;
if (nextMode == autoRefreshMode) return;
onModeChanged(nextMode);
}
: null,
borderRadius: BorderRadius.circular(999),
constraints: const BoxConstraints(minHeight: 32, minWidth: 56),
selectedColor: theme.colorScheme.onPrimary,
fillColor: theme.colorScheme.primary,
color: theme.colorScheme.onSurface,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(loc.toggleOff),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(loc.toggleOn),
),
],
),
],
);
}
}

View File

@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pshared/provider/payment/quotation.dart';
import 'package:pshared/provider/payment/quotation/quotation.dart';
import 'package:pweb/pages/dashboard/payouts/summary/row.dart';

View File

@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pshared/provider/payment/quotation.dart';
import 'package:pshared/provider/payment/quotation/quotation.dart';
import 'package:pweb/pages/dashboard/payouts/summary/row.dart';

View File

@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pshared/provider/payment/quotation.dart';
import 'package:pshared/provider/payment/quotation/quotation.dart';
import 'package:pweb/pages/dashboard/payouts/summary/row.dart';

View File

@@ -54,7 +54,7 @@ class PaymentPageContent extends StatelessWidget {
Widget build(BuildContext context) {
final dimensions = AppDimensions();
final loc = AppLocalizations.of(context)!;
return Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(

View File

@@ -50,7 +50,7 @@ class PaymentPageContent extends StatelessWidget {
Widget build(BuildContext context) {
final dimensions = AppDimensions();
final loc = AppLocalizations.of(context)!;
return Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:pweb/models/button_state.dart';
import 'package:pweb/utils/dimensions.dart';
import 'package:pweb/generated/i18n/app_localizations.dart';
@@ -7,38 +8,61 @@ import 'package:pweb/generated/i18n/app_localizations.dart';
class SendButton extends StatelessWidget {
final VoidCallback onPressed;
final ButtonState state;
const SendButton({super.key, required this.onPressed});
const SendButton({
super.key,
required this.onPressed,
this.state = ButtonState.enabled,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final dimensions = AppDimensions();
final isEnabled = state == ButtonState.enabled;
final isLoading = state == ButtonState.loading;
final backgroundColor = isEnabled || isLoading
? theme.colorScheme.primary
: theme.colorScheme.onSurface.withValues(alpha: 0.12);
final textColor = isEnabled || isLoading
? theme.colorScheme.onSecondary
: theme.colorScheme.onSurface.withValues(alpha: 0.38);
return Center(
child: SizedBox(
width: dimensions.buttonWidth,
height: dimensions.buttonHeight,
child: InkWell(
borderRadius: BorderRadius.circular(dimensions.borderRadiusSmall),
onTap: onPressed,
onTap: isEnabled ? onPressed : null,
child: Container(
decoration: BoxDecoration(
color: theme.colorScheme.primary,
color: backgroundColor,
borderRadius: BorderRadius.circular(dimensions.borderRadiusSmall),
),
child: Center(
child: Text(
AppLocalizations.of(context)!.send,
style: theme.textTheme.bodyLarge?.copyWith(
color: theme.colorScheme.onSecondary,
fontWeight: FontWeight.w600,
),
),
child: isLoading
? SizedBox(
width: dimensions.iconSizeMedium,
height: dimensions.iconSizeMedium,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(textColor),
),
)
: Text(
AppLocalizations.of(context)!.send,
style: theme.textTheme.bodyLarge?.copyWith(
color: textColor,
fontWeight: FontWeight.w600,
),
),
),
),
),
),
);
}
}
}

View File

@@ -0,0 +1,75 @@
import 'dart:async';
class QuotationAutoRefreshController {
bool _enabled = true;
Timer? _timer;
DateTime? _scheduledAt;
DateTime? _triggeredAt;
void setEnabled(bool enabled) {
if (_enabled == enabled) return;
_enabled = enabled;
}
void sync({
required bool isLoading,
required bool canRefresh,
required DateTime? expiresAt,
required Future<void> Function() onRefresh,
}) {
if (!_enabled || isLoading || !canRefresh) {
_clearTimer();
_scheduledAt = null;
_triggeredAt = null;
return;
}
if (expiresAt == null) {
_clearTimer();
_scheduledAt = null;
_triggeredAt = null;
return;
}
final delay = expiresAt.difference(DateTime.now().toUtc());
if (delay <= Duration.zero) {
if (_triggeredAt != null && _triggeredAt!.isAtSameMomentAs(expiresAt)) {
return;
}
_triggeredAt = expiresAt;
_clearTimer();
onRefresh();
return;
}
if (_scheduledAt != null &&
_scheduledAt!.isAtSameMomentAs(expiresAt) &&
_timer?.isActive == true) {
return;
}
_triggeredAt = null;
_clearTimer();
_scheduledAt = expiresAt;
_timer = Timer(delay, () {
onRefresh();
});
}
void reset() {
_enabled = false;
_scheduledAt = null;
_triggeredAt = null;
_clearTimer();
}
void dispose() {
_clearTimer();
}
void _clearTimer() {
_timer?.cancel();
_timer = null;
}
}

View File

@@ -0,0 +1,135 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:pshared/models/auto_refresh_mode.dart';
import 'package:pshared/models/payment/quote/status_type.dart';
import 'package:pshared/provider/payment/quotation/quotation.dart';
import 'package:pweb/providers/quotation/auto_refresh.dart';
class QuotationController extends ChangeNotifier {
QuotationProvider? _quotation;
AutoRefreshMode _autoRefreshMode = AutoRefreshMode.on;
final QuotationAutoRefreshController _autoRefreshController =
QuotationAutoRefreshController();
Timer? _ticker;
void update(QuotationProvider quotation) {
if (identical(_quotation, quotation)) return;
_quotation?.removeListener(_handleQuotationChanged);
_quotation = quotation;
_quotation?.addListener(_handleQuotationChanged);
_handleQuotationChanged();
}
bool get isLoading => _quotation?.isLoading ?? false;
Exception? get error => _quotation?.error;
bool get canRefresh => _quotation?.canRefresh ?? false;
bool get isReady => _quotation?.isReady ?? false;
AutoRefreshMode get autoRefreshMode => _autoRefreshMode;
DateTime? get quoteExpiresAt => _quotation?.quoteExpiresAt;
Duration? get timeLeft {
final expiresAt = quoteExpiresAt;
if (expiresAt == null) return null;
return expiresAt.difference(DateTime.now().toUtc());
}
bool get isExpired {
final remaining = timeLeft;
if (remaining == null) return false;
return remaining <= Duration.zero;
}
QuoteStatusType get quoteStatus {
if (isLoading) return QuoteStatusType.loading;
if (error != null) return QuoteStatusType.error;
if (_quotation?.quotation == null) return QuoteStatusType.missing;
if (isExpired) return QuoteStatusType.expired;
return QuoteStatusType.active;
}
bool get hasLiveQuote => isReady && _quotation?.quotation != null && !isExpired;
void setAutoRefreshMode(AutoRefreshMode mode) {
if (_autoRefreshMode == mode) return;
_autoRefreshMode = mode;
_syncAutoRefresh();
notifyListeners();
}
void refreshQuotation() {
_quotation?.refreshQuotation();
}
void _handleQuotationChanged() {
_syncAutoRefresh();
_syncTicker();
notifyListeners();
}
void _syncTicker() {
final expiresAt = quoteExpiresAt;
if (expiresAt == null) {
_stopTicker();
return;
}
final remaining = expiresAt.difference(DateTime.now().toUtc());
if (remaining <= Duration.zero) {
_stopTicker();
return;
}
_ticker ??= Timer.periodic(const Duration(seconds: 1), (_) {
final expiresAt = quoteExpiresAt;
if (expiresAt == null) {
_stopTicker();
return;
}
final remaining = expiresAt.difference(DateTime.now().toUtc());
if (remaining <= Duration.zero) {
_stopTicker();
}
notifyListeners();
});
}
void _stopTicker() {
_ticker?.cancel();
_ticker = null;
}
void _syncAutoRefresh() {
final quotation = _quotation;
if (quotation == null) {
_autoRefreshController.reset();
return;
}
final isAutoRefreshEnabled = _autoRefreshMode == AutoRefreshMode.on;
_autoRefreshController.setEnabled(isAutoRefreshEnabled);
final canAutoRefresh = isAutoRefreshEnabled && quotation.canRefresh;
_autoRefreshController.sync(
isLoading: quotation.isLoading,
canRefresh: canAutoRefresh,
expiresAt: quoteExpiresAt,
onRefresh: _refreshQuotation,
);
}
Future<void> _refreshQuotation() async {
await _quotation?.refreshQuotation();
}
@override
void dispose() {
_quotation?.removeListener(_handleQuotationChanged);
_autoRefreshController.dispose();
_stopTicker();
super.dispose();
}
}

View File

@@ -0,0 +1,31 @@
import 'package:duration/duration.dart';
String formatQuoteDuration(Duration duration) {
final clampedDuration = duration.isNegative ? Duration.zero : duration;
final pretty = prettyDuration(
clampedDuration,
tersity: DurationTersity.second,
upperTersity: DurationTersity.hour,
abbreviated: true,
delimiter: ':',
spacer: '',
);
final units = _extractHms(pretty);
final hours = units['h'] ?? 0;
final minutes = units['m'] ?? 0;
final seconds = units['s'] ?? 0;
if (hours > 0) {
return '${hours.toString()}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
}
return '${minutes.toString()}:${seconds.toString().padLeft(2, '0')}';
}
Map<String, int> _extractHms(String pretty) {
final matches = RegExp(r'(\d+)([hms])').allMatches(pretty);
final units = <String, int>{};
for (final match in matches) {
units[match.group(2)!] = int.parse(match.group(1)!);
}
return units;
}

View File

@@ -69,6 +69,7 @@ dependencies:
flutter_multi_formatter: ^2.13.7
dotted_border: ^3.1.0
qr_flutter: ^4.1.0
duration: ^4.0.3