/// Offline learning scenario. This module never constructs a real HTTP client. /// All payer details, keys, PNG bytes, URLs and confirmations are demonstration data. library; import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:qr_partner_example/qr_api.dart'; import 'package:qr_partner_example/webhook_verifier.dart'; const demoApiBase = 'https://api.cashwell.example/api/v1'; const demoOrderId = '0123456789abcdef0123'; const demoExternalId = 'merchant-order-123'; const _demoKey = 'DEMO_ONLY_NOT_A_REAL_API_KEY'; const _demoSigningSecret = 'DEMO_ONLY_NOT_A_REAL_WEBHOOK_SECRET'; const _demoIdempotencyKey = 'create:merchant-order-123'; final _demoClock = DateTime.utc(2026, 11, 21, 12); void _require(bool value, String message) { if (!value) throw StateError(message); } Map _copy(Map value) => jsonDecode(jsonEncode(value)) as Map; Map _request() => { 'external_id': demoExternalId, 'full_name': 'Иванов Иван Иванович', 'bank': 'Сбербанк', 'amount_rub': '1000.00', }; Map _order(String status) => { 'id': demoOrderId, 'external_id': demoExternalId, 'status': status, // Actual API generation_status may stay ready after payment is confirmed. 'generation_status': status == 'creating' ? 'queued' : 'ready', 'payment_status': status == 'paid' ? 'paid' : status == 'needs_review' ? 'needs_review' : 'pending', 'amount_rub': '1000.00', 'trader_rate': '91.5628', 'expected_usdt': '10.92146592', 'created_at': 1795262400.0, 'updated_at': status == 'creating' ? 1795262400.0 : 1795262403.0, 'expires_at': 1795263300.0, 'payment_url': status == 'ready' ? 'https://payments.example/pay/demo-only' : null, 'qr_url': status == 'ready' ? '/api/v1/orders/$demoOrderId/qr' : null, }; enum DemoEventResult { accepted, duplicate, olderSequence, invalidSignature } /// A private JSON snapshot illustrates a single-process restart. A production /// integration needs one DB transaction for inbox, sequence and business state. class DemoSnapshot { final File file; Map document; DemoSnapshot._(this.file, this.document); static Future open(File file) async => DemoSnapshot._(file, await file.exists() ? jsonDecode(await file.readAsString()) as Map : { 'mapping': {}, 'inbox': {'seen': {}, 'orders': {}}, 'confirmed_orders': {}, 'confirmation_count': 0, 'reconciliation_hold': false, }); Future save() async { await file.parent.create(recursive: true); final temporary = File('${file.path}.tmp'); await temporary.writeAsString(jsonEncode(document), flush: true); await temporary.rename(file.path); } Future receive({required List bytes, required String timestamp, required String signature, required String eventId}) async { Map event; try { event = verifyWebhook(body: bytes, timestamp: timestamp, signature: signature, eventId: eventId, secret: _demoSigningSecret, now: _demoClock); } on FormatException { // Authentication failed: do not persist an inbox ID or business change. return DemoEventResult.invalidSignature; } final next = _copy(document); final inbox = WebhookInbox(next['inbox'] as Map); final duplicate = (inbox.document['seen'] as Map).containsKey(eventId); final accepted = inbox.accept(event); if (!accepted) { // An older, previously unseen ID is remembered too, without rolling back // the order or executing the business confirmation again. final old = document; document = next; try { await save(); } catch (_) { document = old; rethrow; } return duplicate ? DemoEventResult.duplicate : DemoEventResult.olderSequence; } final order = event['data'] as Map; final mapping = next['mapping'] as Map; _require(order['id'] == mapping['api_order_id'] && order['external_id'] == mapping['external_id'], 'The webhook must belong to the saved trader/order mapping.'); final status = order['status']; final confirmations = next['confirmed_orders'] as Map; if (status == 'needs_review') { // Preserve the already recorded fact; hold reconciliation for GET/operator // review. Do not automatically transfer money or erase a previous payout. next['reconciliation_hold'] = true; } else if (status == 'paid') { if (!confirmations.containsKey(order['id'])) { confirmations[order['id']] = { 'external_id': order['external_id'], 'amount_rub': order['amount_rub'], 'expected_usdt': order['expected_usdt'], }; next['confirmation_count'] = (next['confirmation_count'] as int) + 1; } next['reconciliation_hold'] = false; } // One atomic file replacement represents the single DB transaction needed // in production. Its scope includes inbox + sequence + business confirmation. final old = document; document = next; try { await save(); } catch (_) { document = old; rethrow; } return DemoEventResult.accepted; } } class DemoReport { final int postAttempts; final int createdInvoices; final int rateLimitResponses; final int pngBytes; final int confirmationCount; final bool restartPreserved; final bool duplicateIgnored; final bool olderIgnored; final bool invalidSignatureRejected; final bool reviewHeld; final bool reconfirmationDidNotDuplicate; final String finalStatus; final String expectedUsdt; final List requestTargets; final List postBodies; final List idempotencyKeys; DemoReport({required this.postAttempts, required this.createdInvoices, required this.rateLimitResponses, required this.pngBytes, required this.confirmationCount, required this.restartPreserved, required this.duplicateIgnored, required this.olderIgnored, required this.invalidSignatureRejected, required this.reviewHeld, required this.reconfirmationDidNotDuplicate, required this.finalStatus, required this.expectedUsdt, required List requestTargets, required List postBodies, required List idempotencyKeys}) : requestTargets = List.unmodifiable(requestTargets), postBodies = List.unmodifiable(postBodies), idempotencyKeys = List.unmodifiable(idempotencyKeys); } /// Runs with a MockClient and fixed example origin, irrespective of environment. /// No real invoice, Telegram message, payment or USDT transfer is performed. /// An optional [stateDirectory] lets a test inspect the persisted dummy snapshot. Future runLifecycleDemo({Directory? stateDirectory, void Function(String)? log}) async { final ownedDirectory = stateDirectory == null; final directory = stateDirectory ?? await Directory.systemTemp.createTemp('cashwell-offline-lifecycle-'); await directory.create(recursive: true); final stateFile = File('${directory.path}/demo-state.json'); var state = await DemoSnapshot.open(stateFile); _require((state.document['mapping'] as Map).isEmpty, 'Use a new demonstration state directory, not existing business data.'); state.document['mapping'] = { 'external_id': demoExternalId, 'idempotency_key': _demoIdempotencyKey, 'request': _request(), 'trader_id': 'demo-trader-7', 'telegram_chat_id': 123456789, 'api_order_id': null, }; await state.save(); log?.call('ДЕМО: только MockClient; реальные счета, запросы и переводы не выполняются.'); log?.call('1. Сохранили данные, external_id, ключ повтора и владельца заявки до POST.'); var attempts = 0, invoices = 0, getAttempts = 0, limited = 0; var canonicalStatus = 'creating'; var canonicalSequence = 1; final targets = [], bodies = [], keys = []; final png = base64Decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC' 'AAAAC0lEQVR42mP8/x8AAwMCAO+j1ioAAAAASUVORK5CYII='); final client = MockClient((request) async { targets.add(request.url.toString()); _require(request.url.scheme == 'https' && request.url.host == 'api.cashwell.example', 'The mock must not accept a different API origin.'); _require(request.headers['authorization'] == 'Bearer $_demoKey', 'Only the dummy server-side Bearer belongs on these requests.'); _require(!request.followRedirects, 'Authenticated requests must not follow redirects.'); if (request.method == 'POST' && request.url.path == '/api/v1/orders') { attempts++; bodies.add(request.body); keys.add(request.headers['idempotency-key'] ?? ''); final saved = jsonDecode(await stateFile.readAsString()) as Map; _require(jsonEncode(saved['mapping']['request']) == request.body && saved['mapping']['idempotency_key'] == request.headers['idempotency-key'], 'The original data and retry identity must be durable before POST.'); if (invoices == 0) { invoices++; log?.call('2. Счёт принят в mock, но первый HTTP-ответ потерян. Повторяем прежнее тело и ключ.'); throw http.ClientException('Demonstration lost response'); } return http.Response(jsonEncode(_order(canonicalStatus)), 202, headers: {'content-type': 'application/json'}); } if (request.method == 'GET' && request.url.path == '/api/v1/orders/$demoOrderId') { getAttempts++; if (getAttempts == 1) { limited++; log?.call('4. Mock вернул 429 / Retry-After: 1. Клиент ждёт секунду и повторяет GET.'); return http.Response('{"error":{"code":"rate_limit_exceeded","message":"Demo limit"}}', 429, headers: {'content-type': 'application/json', 'retry-after': '1'}); } if (canonicalStatus != 'paid' && canonicalStatus != 'needs_review') { canonicalStatus = getAttempts == 2 ? 'creating' : 'ready'; } return http.Response(jsonEncode(_order(canonicalStatus)), 200, headers: {'content-type': 'application/json'}); } if (request.method == 'GET' && request.url.path == '/api/v1/orders/$demoOrderId/qr') { _require(canonicalStatus == 'ready', 'A PNG is available only while ready.'); // A one-pixel test PNG, deliberately not a scannable payment QR. return http.Response.bytes(png, 200, headers: {'content-type': 'image/png'}); } if (request.method == 'GET' && request.url.path == '/api/v1/balance') { return http.Response(jsonEncode({ 'total_orders': 1, 'successful_orders': canonicalStatus == 'paid' ? 1 : 0, 'successful_amount_kopeks': canonicalStatus == 'paid' ? 100000 : 0, 'conflict_orders': 0, 'expected_usdt': '10.92146592', 'expected_usdt_known_amount': '10.92146592', 'expected_usdt_missing_orders': 0, 'paid_usdt': '0', 'payable_usdt': '10.92146592', 'payable_usdt_known_amount': '10.92146592', 'balance_usdt': '10.92146592', 'overpaid_usdt': '0', 'complete': true, }), 200, headers: {'content-type': 'application/json'}); } throw StateError('Unexpected request in offline scenario.'); }); final api = QrApi(demoApiBase, _demoKey, client: client, retryDelay: Duration.zero); try { final original = state.document['mapping'] as Map; final request = original['request'] as Map; var order = await api.createOrder(externalId: original['external_id'] as String, fullName: request['full_name'] as String, bank: request['bank'] as String, amountRub: request['amount_rub'] as String, idempotencyKey: original['idempotency_key'] as String); _require(order.status == 'creating', 'A queued creation must remain unpaid.'); original['api_order_id'] = order.id; await state.save(); state = await DemoSnapshot.open(stateFile); // new process reads the same mapping _require((state.document['mapping'] as Map)['api_order_id'] == order.id, 'The API ID must survive restart.'); log?.call('3. Повтор вернул тот же ID. После перезапуска восстановили связь заявки с трейдером.'); order = await api.waitForOrder(order.id, interval: Duration.zero); _require(order.status == 'ready' && order.expectedUsdt == '10.92146592', 'The returned immutable decimal quote must be preserved.'); final image = await api.downloadQr(order); log?.call('5. ready: скачали тестовый PNG с Bearer; ссылка оплаты — payments.example.'); log?.call(' 1000.00 ₽ / 91.5628 ₽ за USDT → ${order.expectedUsdt} USDT из ответа API.'); Future deliver(String eventId, int sequence, String status, {bool corrupt = false}) async { // Delivery order does not rewrite the provider's newer canonical state. if (sequence > canonicalSequence) { canonicalSequence = sequence; canonicalStatus = status; } final timestamp = '${_demoClock.millisecondsSinceEpoch ~/ 1000}'; final bytes = utf8.encode(jsonEncode({ 'id': eventId, 'type': 'order.updated', 'created_at': 1795262405.0, 'sequence': sequence, 'data': _order(status), })); final signature = 'sha256=${Hmac(sha256, utf8.encode(_demoSigningSecret)) .convert([...utf8.encode('$timestamp.'), ...bytes])}'; return state.receive(bytes: corrupt ? [...bytes, 32] : bytes, timestamp: timestamp, signature: signature, eventId: eventId); } final beforeInvalid = await stateFile.readAsString(); final invalid = await deliver('evt_demo_invalid', 2, 'paid', corrupt: true); final invalidRejected = invalid == DemoEventResult.invalidSignature && beforeInvalid == await stateFile.readAsString(); _require(invalidRejected, 'An invalid HMAC must not change durable business state.'); _require(await deliver('evt_demo_paid', 2, 'paid') == DemoEventResult.accepted, 'The first valid paid event must be accepted.'); log?.call('6. Проверили HMAC над исходными байтами; paid записан вместе с inbox и sequence.'); state = await DemoSnapshot.open(stateFile); final restartPreserved = state.document['confirmation_count'] == 1; final duplicateIgnored = await deliver('evt_demo_paid', 2, 'paid') == DemoEventResult.duplicate; final olderIgnored = await deliver('evt_demo_delayed_ready', 1, 'ready') == DemoEventResult.olderSequence; _require(restartPreserved && duplicateIgnored && olderIgnored, 'Restart, retries and old sequence must not duplicate or revert confirmation.'); _require((await api.getOrder(order.id)).status == 'paid', 'A delayed webhook must not regress the canonical GET result.'); log?.call('7. После перезапуска повтор paid и запоздавший ready не изменили подтверждение.'); await deliver('evt_demo_review', 3, 'needs_review'); final reviewHeld = state.document['reconciliation_hold'] == true; await deliver('evt_demo_reconfirmed', 4, 'paid'); final reconfirmationDidNotDuplicate = state.document['confirmation_count'] == 1 && state.document['reconciliation_hold'] == false; _require(reviewHeld && reconfirmationDidNotDuplicate, 'A new paid sequence after review is not a second business operation.'); log?.call('8. needs_review поставил сверку на паузу; повторное подтверждение не создало второе начисление.'); final finalOrder = await api.getOrder(order.id); final balance = await api.balance(); _require(finalOrder.status == 'paid' && finalOrder.qrUrl == null && finalOrder.paymentUrl == null && balance['complete'] == true, 'Canonical GET confirms paid and no longer offers payment artifacts.'); log?.call('9. GET подтвердил paid; QR/ссылка скрыты. Учебный остаток: ${balance['payable_usdt']} USDT.'); log?.call(' Реальная выплата USDT не выполнялась. Бизнес-подтверждений этой заявки: 1.'); return DemoReport(postAttempts: attempts, createdInvoices: invoices, rateLimitResponses: limited, pngBytes: image.length, confirmationCount: state.document['confirmation_count'] as int, restartPreserved: restartPreserved, duplicateIgnored: duplicateIgnored, olderIgnored: olderIgnored, invalidSignatureRejected: invalidRejected, reviewHeld: reviewHeld, reconfirmationDidNotDuplicate: reconfirmationDidNotDuplicate, finalStatus: finalOrder.status, expectedUsdt: finalOrder.expectedUsdt!, requestTargets: targets, postBodies: bodies, idempotencyKeys: keys); } finally { api.close(); if (ownedDirectory) await directory.delete(recursive: true); } }