| 1 | import 'package:cake_wallet/entities/country.dart'; |
| 2 | import 'package:cw_core/utils/print_verbose.dart'; |
| 3 | |
| 4 | import 'cake_pay_card.dart'; |
| 5 | |
| 6 | class CakePayVendor { |
| 7 | final int id; |
| 8 | final String name; |
| 9 | final bool available; |
| 10 | final String? cakeWarnings; |
| 11 | final String country; |
| 12 | final CakePayCard? card; |
| 13 | |
| 14 | CakePayVendor({ |
| 15 | required this.id, |
| 16 | required this.name, |
| 17 | required this.available, |
| 18 | this.cakeWarnings, |
| 19 | required this.country, |
| 20 | this.card, |
| 21 | }); |
| 22 | |
| 23 | factory CakePayVendor.fromJson(Map<String, dynamic> json) { |
| 24 | final name = stripHtmlIfNeeded(json['name'] as String); |
| 25 | |
| 26 | final parsedCountry = json['country'] as String; |
| 27 | final country = Country.normalizeName(parsedCountry); |
| 28 | |
| 29 | var cardsJson = json['cards'] as List?; |
| 30 | CakePayCard? cardForVendor; |
| 31 | |
| 32 | if (cardsJson != null && cardsJson.isNotEmpty) { |
| 33 | try { |
| 34 | final cards = cardsJson |
| 35 | .map((cardJson) => CakePayCard.fromJson(cardJson as Map<String, dynamic>)) |
| 36 | .toList(); |
| 37 | final cardsForSelectedCountry = |
| 38 | cards.where((card) => Country.normalizeName(card.country ?? '') == country).toList(); |
| 39 | |
| 40 | if (cardsForSelectedCountry.isNotEmpty) { |
| 41 | final isPrepaid = |
| 42 | cardsForSelectedCountry.every((card) => card.type == CakePayCardType.prepaid); |
| 43 | |
| 44 | if (isPrepaid) { |
| 45 | final firstCard = cardsForSelectedCountry.first; |
| 46 | final prepaidRanges = cardsForSelectedCountry.map(PrepaidRange.fromCard).toList() |
| 47 | ..sort((a, b) => a.minValue.compareTo(b.minValue)); |
| 48 | |
| 49 | cardForVendor = firstCard.copyWith(prepaidRange: prepaidRanges); |
| 50 | } else { |
| 51 | cardForVendor = cardsForSelectedCountry.first; |
| 52 | } |
| 53 | } |
| 54 | } catch (e) { |
| 55 | printV('Error parsing card for vendor: $e'); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return CakePayVendor( |
| 60 | id: json['id'] as int, |
| 61 | name: name, |
| 62 | available: json['available'] as bool? ?? false, |
| 63 | cakeWarnings: json['cake_warnings'] as String?, |
| 64 | country: country, |
| 65 | card: cardForVendor, |
| 66 | ); |
| 67 | } |
| 68 | |
| 69 | static String stripHtmlIfNeeded(String text) { |
| 70 | return text.replaceAll(RegExp(r'<[^>]*>|&[^;]+;'), ' '); |
| 71 | } |
| 72 | } |