checkDeadlines method

Future<List<DVDispute>> checkDeadlines()

Announces every open dispute whose evidence deadline has come within a warnBefore threshold not yet announced, as DV-COMMERCE-005, and returns those disputes.

A deadline that has passed is written on the timeline once. It is not a warning: there is no longer anything to act on. Run this on a schedule shorter than the smallest threshold.

Implementation

Future<List<DVDispute>> checkDeadlines() async {
  final DateTime now = _now;
  final List<DVDispute> warned = <DVDispute>[];
  for (final DVDispute dispute in await store.open()) {
    final DateTime? due = dispute.evidenceDueBy;
    if (due == null || !dispute.status.awaitingEvidence) continue;
    final Duration left = due.difference(now);
    if (left <= Duration.zero) {
      if (dispute.deadlinePassed) continue;
      _log.log(
        'The evidence deadline for dispute ${dispute.id} passed without a '
        'response',
        level: DVLogLevel.warn,
        context: <String, Object?>{'dispute': dispute.id},
      );
      await store.put(dispute.copyWith(
        deadlinePassed: true,
        timeline: <DVDisputeEntry>[
          ...dispute.timeline,
          DVDisputeEntry(
            at: now,
            source: 'deadline',
            message: 'The evidence deadline passed without a response; the '
                'dispute is lost by default unless the provider says '
                'otherwise',
          ),
        ],
      ));
      continue;
    }
    final Set<int> crossed = <int>{
      for (final Duration threshold in warnBefore)
        if (left <= threshold &&
            !dispute.warnedAtMinutes.contains(threshold.inMinutes))
          threshold.inMinutes,
    };
    if (crossed.isEmpty) continue;
    final List<String> missing = <String>[
      for (final DVEvidenceItem item in dispute.evidence)
        if (!item.provided) item.key,
    ];
    final String remaining = '${left.inHours}h';
    _log.log(
      'DV-COMMERCE-005: dispute ${dispute.id} for ${dispute.amount} needs '
      'evidence by ${due.toIso8601String()} ($remaining left); still '
      'missing: ${missing.isEmpty ? 'nothing' : missing.join(', ')}',
      level: DVLogLevel.warn,
      code: 'DV-COMMERCE-005',
      context: <String, Object?>{
        'dispute': dispute.id,
        'sale': dispute.saleId,
        'dueBy': due.toIso8601String(),
        'missing': missing,
      },
    );
    final DVDispute updated = dispute.copyWith(
      warnedAtMinutes: <int>{...dispute.warnedAtMinutes, ...crossed},
      timeline: <DVDisputeEntry>[
        ...dispute.timeline,
        DVDisputeEntry(
          at: now,
          source: 'deadline',
          message: 'Evidence is due in $remaining',
        ),
      ],
    );
    await store.put(updated);
    warned.add(updated);
  }
  return warned;
}