EnakPoint & EnakCoin wallet, PIN, outlet, order, community, reward
- Wallet EnakPoint & EnakCoin: beranda, riwayat, saldo kedaluwarsa, kode bayar, tukar EnakCoin, transfer - PIN (buat, ganti, lupa), outlet, riwayat order, game spin - Halaman community, webview, coming soon, dan ikon menu beranda baru - Redesign Reward Saya: kartu tiket, filter chip, detail kode + QR - Hapus customer point loader, menu, dan checkout lama - Base URL ke enaklo-pos-api.altru.id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5954510b93
commit
f5e3075205
@@ -0,0 +1,94 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../common/api/api_client.dart';
|
||||
import '../../../common/api/api_failure.dart';
|
||||
import '../../../common/function/app_function.dart';
|
||||
import '../../../common/url/api_path.dart';
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../wallet_dtos.dart';
|
||||
import '../wallet_response.dart';
|
||||
|
||||
/// Outlet (§4.4) dan riwayat order (§4.5).
|
||||
@injectable
|
||||
class CustomerRemoteDataProvider {
|
||||
final ApiClient _apiClient;
|
||||
final String _logName = 'CustomerRemoteDataProvider';
|
||||
|
||||
CustomerRemoteDataProvider(this._apiClient);
|
||||
|
||||
Future<DC<WalletFailure, List<OutletDto>>> fetchOutlets() => _request(
|
||||
'fetchOutlets',
|
||||
() => _apiClient.get(ApiPath.outlets, headers: getAuthorizationHeader()),
|
||||
(response) => ((response.data as Map)['data'] as List? ?? [])
|
||||
.map((e) => OutletDto.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, CustomerOrderPageDto>> fetchOrders({
|
||||
required int page,
|
||||
required int limit,
|
||||
}) => _request(
|
||||
'fetchOrders',
|
||||
() => _apiClient.get(
|
||||
ApiPath.orders,
|
||||
headers: getAuthorizationHeader(),
|
||||
params: {'page': page, 'limit': limit},
|
||||
),
|
||||
_parseOrderPage,
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, CustomerOrderDto>> fetchOrderDetail(String id) =>
|
||||
_request(
|
||||
'fetchOrderDetail',
|
||||
() => _apiClient.get(
|
||||
'${ApiPath.orders}/$id',
|
||||
headers: getAuthorizationHeader(),
|
||||
),
|
||||
(response) => CustomerOrderDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
/// `data` bisa berupa list langsung dengan `pagination` di envelope, atau
|
||||
/// objek `{ data, pagination }`.
|
||||
CustomerOrderPageDto _parseOrderPage(Response response) {
|
||||
final body = response.data as Map;
|
||||
final payload = body['data'];
|
||||
final rawItems = payload is Map ? payload['data'] : payload;
|
||||
final rawPagination = payload is Map
|
||||
? payload['pagination']
|
||||
: body['pagination'];
|
||||
|
||||
return CustomerOrderPageDto(
|
||||
items: (rawItems as List? ?? [])
|
||||
.map(
|
||||
(e) =>
|
||||
CustomerOrderDto.fromJson(Map<String, dynamic>.from(e as Map)),
|
||||
)
|
||||
.toList(),
|
||||
pagination: rawPagination is Map
|
||||
? WalletPaginationDto.fromJson(
|
||||
Map<String, dynamic>.from(rawPagination),
|
||||
)
|
||||
: const WalletPaginationDto(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<DC<WalletFailure, T>> _request<T>(
|
||||
String name,
|
||||
Future<Response> Function() call,
|
||||
T Function(Response response) parse,
|
||||
) async {
|
||||
try {
|
||||
final response = await call();
|
||||
final failure = parseWalletFailure(response);
|
||||
if (failure != null) return DC.error(failure);
|
||||
return DC.data(parse(response));
|
||||
} on ApiFailure catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return DC.error(WalletFailure.serverError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../common/api/api_client.dart';
|
||||
import '../../../common/api/api_failure.dart';
|
||||
import '../../../common/function/app_function.dart';
|
||||
import '../../../common/url/api_path.dart';
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../wallet_response.dart';
|
||||
|
||||
@injectable
|
||||
class DeviceLocalDataProvider {
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
static const _deviceIdKey = 'device_id';
|
||||
static const _registeredKey = 'device_registered';
|
||||
|
||||
DeviceLocalDataProvider(this._storage);
|
||||
|
||||
/// ID unik & stabil per instalasi; dibuat sekali lalu disimpan.
|
||||
Future<String> deviceId() async {
|
||||
final saved = await _storage.read(key: _deviceIdKey);
|
||||
if (saved != null && saved.isNotEmpty) return saved;
|
||||
|
||||
final created = generateUuidV4();
|
||||
await _storage.write(key: _deviceIdKey, value: created);
|
||||
return created;
|
||||
}
|
||||
|
||||
Future<bool> isRegistered() async =>
|
||||
await _storage.read(key: _registeredKey) == 'true';
|
||||
|
||||
Future<void> setRegistered(bool value) =>
|
||||
_storage.write(key: _registeredKey, value: value.toString());
|
||||
}
|
||||
|
||||
@injectable
|
||||
class DeviceRemoteDataProvider {
|
||||
final ApiClient _apiClient;
|
||||
final String _logName = 'DeviceRemoteDataProvider';
|
||||
|
||||
DeviceRemoteDataProvider(this._apiClient);
|
||||
|
||||
Future<DC<WalletFailure, Unit>> register({
|
||||
required String deviceId,
|
||||
required String fcmToken,
|
||||
required String platform,
|
||||
required String appVersion,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _apiClient.put(
|
||||
ApiPath.devices,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {
|
||||
'device_id': deviceId,
|
||||
'fcm_token': fcmToken,
|
||||
'platform': platform,
|
||||
'app_version': appVersion,
|
||||
},
|
||||
);
|
||||
final failure = parseWalletFailure(response);
|
||||
if (failure != null) return DC.error(failure);
|
||||
return DC.data(unit);
|
||||
} on ApiFailure catch (e, s) {
|
||||
log('register', name: _logName, error: e, stackTrace: s);
|
||||
return DC.error(WalletFailure.serverError(e));
|
||||
}
|
||||
}
|
||||
|
||||
Future<DC<WalletFailure, Unit>> unregister({required String deviceId}) async {
|
||||
try {
|
||||
final response = await _apiClient.delete(
|
||||
'${ApiPath.devices}/$deviceId',
|
||||
headers: getAuthorizationHeader(),
|
||||
);
|
||||
final failure = parseWalletFailure(response);
|
||||
if (failure != null) return DC.error(failure);
|
||||
return DC.data(unit);
|
||||
} on ApiFailure catch (e, s) {
|
||||
log('unregister', name: _logName, error: e, stackTrace: s);
|
||||
return DC.error(WalletFailure.serverError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../common/api/api_client.dart';
|
||||
import '../../../common/api/api_failure.dart';
|
||||
import '../../../common/api/interceptors/sensitive_aware_log_interceptor.dart';
|
||||
import '../../../common/function/app_function.dart';
|
||||
import '../../../common/url/api_path.dart';
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../wallet_dtos.dart';
|
||||
import '../wallet_response.dart';
|
||||
|
||||
@injectable
|
||||
class PinRemoteDataProvider {
|
||||
final ApiClient _apiClient;
|
||||
final String _logName = 'PinRemoteDataProvider';
|
||||
|
||||
PinRemoteDataProvider(this._apiClient);
|
||||
|
||||
Future<DC<WalletFailure, PinStatusDto>> fetchStatus() => _request(
|
||||
'fetchStatus',
|
||||
() => _apiClient.get(ApiPath.pinStatus, headers: getAuthorizationHeader()),
|
||||
(response) => PinStatusDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, PinOtpDto>> requestOtp(PinOtpPurpose purpose) =>
|
||||
_request(
|
||||
'requestOtp',
|
||||
() => _apiClient.post(
|
||||
ApiPath.pinOtp,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {'purpose': purpose.apiValue},
|
||||
),
|
||||
(response) => PinOtpDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, PinStatusDto>> setup({
|
||||
required String otpToken,
|
||||
required String otpCode,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _request(
|
||||
'setup',
|
||||
() => _apiClient.post(
|
||||
ApiPath.pin,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {
|
||||
'otp_token': otpToken,
|
||||
'otp_code': otpCode,
|
||||
'pin': pin,
|
||||
'confirm_pin': confirmPin,
|
||||
},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(response) => PinStatusDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, Unit>> change({
|
||||
required String oldPin,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _request(
|
||||
'change',
|
||||
() => _apiClient.put(
|
||||
ApiPath.pin,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {'old_pin': oldPin, 'pin': pin, 'confirm_pin': confirmPin},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(_) => unit,
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, Unit>> reset({
|
||||
required String otpToken,
|
||||
required String otpCode,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _request(
|
||||
'reset',
|
||||
() => _apiClient.post(
|
||||
ApiPath.pinReset,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {
|
||||
'otp_token': otpToken,
|
||||
'otp_code': otpCode,
|
||||
'pin': pin,
|
||||
'confirm_pin': confirmPin,
|
||||
},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(_) => unit,
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, T>> _request<T>(
|
||||
String name,
|
||||
Future<Response> Function() call,
|
||||
T Function(Response response) parse,
|
||||
) async {
|
||||
try {
|
||||
final response = await call();
|
||||
final failure = parseWalletFailure(response);
|
||||
if (failure != null) return DC.error(failure);
|
||||
return DC.data(parse(response));
|
||||
} on ApiFailure catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return DC.error(WalletFailure.serverError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../common/api/api_client.dart';
|
||||
import '../../../common/api/api_failure.dart';
|
||||
import '../../../common/api/interceptors/sensitive_aware_log_interceptor.dart';
|
||||
import '../../../common/extension/extension.dart';
|
||||
import '../../../common/function/app_function.dart';
|
||||
import '../../../common/url/api_path.dart';
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../wallet_dtos.dart';
|
||||
import '../wallet_response.dart';
|
||||
|
||||
@injectable
|
||||
class WalletRemoteDataProvider {
|
||||
final ApiClient _apiClient;
|
||||
final String _logName = 'WalletRemoteDataProvider';
|
||||
|
||||
WalletRemoteDataProvider(this._apiClient);
|
||||
|
||||
Future<DC<WalletFailure, WalletSummaryDto>> fetchWallet() => _request(
|
||||
'fetchWallet',
|
||||
() => _apiClient.get(ApiPath.wallet, headers: getAuthorizationHeader()),
|
||||
(response) => WalletSummaryDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, WalletTransactionPageDto>> fetchTransactions({
|
||||
required int page,
|
||||
required int limit,
|
||||
WalletCurrency? currency,
|
||||
List<WalletTransactionType> types = const [],
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
}) => _request(
|
||||
'fetchTransactions',
|
||||
() => _apiClient.get(
|
||||
ApiPath.walletTransactions,
|
||||
headers: getAuthorizationHeader(),
|
||||
params: {
|
||||
'page': page,
|
||||
'limit': limit,
|
||||
if (currency != null) 'currency': currency.apiValue,
|
||||
if (types.isNotEmpty) 'type': types.map((e) => e.apiValue).join(','),
|
||||
if (from != null) 'from': from.toServerDate,
|
||||
if (to != null) 'to': to.toServerDate,
|
||||
},
|
||||
),
|
||||
_parseTransactionPage,
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, WalletExpiringDto>> fetchExpiring() => _request(
|
||||
'fetchExpiring',
|
||||
() => _apiClient.get(
|
||||
ApiPath.walletExpiring,
|
||||
headers: getAuthorizationHeader(),
|
||||
),
|
||||
(response) => WalletExpiringDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, PaymentCodeDto>> createPaymentCode({
|
||||
required String pin,
|
||||
}) => _request(
|
||||
'createPaymentCode',
|
||||
() => _apiClient.post(
|
||||
ApiPath.walletPaymentCode,
|
||||
headers: getAuthorizationHeader(),
|
||||
data: {'pin': pin},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(response) => PaymentCodeDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, ExchangePreviewDto>> previewExchange({
|
||||
required int coins,
|
||||
}) => _request(
|
||||
'previewExchange',
|
||||
() => _apiClient.get(
|
||||
ApiPath.walletExchangePreview,
|
||||
headers: getAuthorizationHeader(),
|
||||
params: {'coins': coins},
|
||||
),
|
||||
(response) => ExchangePreviewDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, ExchangeResultDto>> exchange({
|
||||
required int coins,
|
||||
required String pin,
|
||||
required String idempotencyKey,
|
||||
}) => _request(
|
||||
'exchange',
|
||||
() => _apiClient.post(
|
||||
ApiPath.walletExchange,
|
||||
headers: {...getAuthorizationHeader(), 'Idempotency-Key': idempotencyKey},
|
||||
data: {'coins': coins, 'pin': pin},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(response) => ExchangeResultDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, TransferRecipientDto>> checkRecipient({
|
||||
required String phone,
|
||||
}) => _request(
|
||||
'checkRecipient',
|
||||
() => _apiClient.get(
|
||||
ApiPath.walletTransferRecipient,
|
||||
headers: getAuthorizationHeader(),
|
||||
params: {'phone': phone},
|
||||
),
|
||||
(response) => TransferRecipientDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
Future<DC<WalletFailure, TransferResultDto>> transfer({
|
||||
required WalletCurrency currency,
|
||||
required int amount,
|
||||
required String recipientPhone,
|
||||
required String pin,
|
||||
required String idempotencyKey,
|
||||
}) => _request(
|
||||
'transfer',
|
||||
() => _apiClient.post(
|
||||
ApiPath.walletTransfer,
|
||||
headers: {...getAuthorizationHeader(), 'Idempotency-Key': idempotencyKey},
|
||||
data: {
|
||||
'currency': currency.apiValue,
|
||||
'amount': amount,
|
||||
'recipient_phone': recipientPhone,
|
||||
'pin': pin,
|
||||
},
|
||||
extra: {kSensitiveRequest: true},
|
||||
),
|
||||
(response) => TransferResultDto.fromJson(walletDataOf(response)),
|
||||
);
|
||||
|
||||
/// `data` bisa berupa list langsung dengan `pagination` di envelope, atau
|
||||
/// objek `{ data, pagination }`.
|
||||
WalletTransactionPageDto _parseTransactionPage(Response response) {
|
||||
final body = response.data as Map;
|
||||
final payload = body['data'];
|
||||
final rawItems = payload is Map ? payload['data'] : payload;
|
||||
final rawPagination = payload is Map
|
||||
? payload['pagination']
|
||||
: body['pagination'];
|
||||
|
||||
return WalletTransactionPageDto(
|
||||
items: (rawItems as List? ?? [])
|
||||
.map(
|
||||
(e) => WalletTransactionDto.fromJson(
|
||||
Map<String, dynamic>.from(e as Map),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
pagination: rawPagination is Map
|
||||
? WalletPaginationDto.fromJson(
|
||||
Map<String, dynamic>.from(rawPagination),
|
||||
)
|
||||
: const WalletPaginationDto(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<DC<WalletFailure, T>> _request<T>(
|
||||
String name,
|
||||
Future<Response> Function() call,
|
||||
T Function(Response response) parse,
|
||||
) async {
|
||||
try {
|
||||
final response = await call();
|
||||
final failure = parseWalletFailure(response);
|
||||
if (failure != null) return DC.error(failure);
|
||||
return DC.data(parse(response));
|
||||
} on ApiFailure catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return DC.error(WalletFailure.serverError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
/// Satu DTO untuk daftar dan detail order; field detail kosong di daftar.
|
||||
@freezed
|
||||
abstract class CustomerOrderDto with _$CustomerOrderDto {
|
||||
const factory CustomerOrderDto({
|
||||
@JsonKey(name: 'id') String? id,
|
||||
@JsonKey(name: 'order_number') String? orderNumber,
|
||||
@JsonKey(name: 'outlet_name') String? outletName,
|
||||
@JsonKey(name: 'order_type') String? orderType,
|
||||
@JsonKey(name: 'status') String? status,
|
||||
@JsonKey(name: 'payment_status') String? paymentStatus,
|
||||
@JsonKey(name: 'total_amount') int? totalAmount,
|
||||
@JsonKey(name: 'item_count') int? itemCount,
|
||||
@JsonKey(name: 'is_void') bool? isVoid,
|
||||
@JsonKey(name: 'is_refund') bool? isRefund,
|
||||
@JsonKey(name: 'points_earned') int? pointsEarned,
|
||||
@JsonKey(name: 'coins_earned') int? coinsEarned,
|
||||
@JsonKey(name: 'created_at') String? createdAt,
|
||||
// Detail
|
||||
@JsonKey(name: 'table_number') String? tableNumber,
|
||||
@JsonKey(name: 'subtotal') int? subtotal,
|
||||
@JsonKey(name: 'discount_amount') int? discountAmount,
|
||||
@JsonKey(name: 'tax_amount') int? taxAmount,
|
||||
@JsonKey(name: 'refund_amount') int? refundAmount,
|
||||
@JsonKey(name: 'items') List<CustomerOrderItemDto>? items,
|
||||
@JsonKey(name: 'payments') List<CustomerOrderPaymentDto>? payments,
|
||||
}) = _CustomerOrderDto;
|
||||
|
||||
factory CustomerOrderDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$CustomerOrderDtoFromJson(json);
|
||||
|
||||
const CustomerOrderDto._();
|
||||
|
||||
CustomerOrder toDomain() => CustomerOrder(
|
||||
id: id ?? '',
|
||||
orderNumber: orderNumber ?? '',
|
||||
outletName: outletName ?? '',
|
||||
orderType: orderType ?? '',
|
||||
status: status ?? '',
|
||||
paymentStatus: paymentStatus ?? '',
|
||||
totalAmount: totalAmount ?? 0,
|
||||
itemCount: itemCount ?? 0,
|
||||
isVoid: isVoid ?? false,
|
||||
isRefund: isRefund ?? false,
|
||||
pointsEarned: pointsEarned ?? 0,
|
||||
coinsEarned: coinsEarned ?? 0,
|
||||
createdAt: _parseDateTime(createdAt),
|
||||
);
|
||||
|
||||
CustomerOrderDetail toDetailDomain() => CustomerOrderDetail(
|
||||
order: toDomain(),
|
||||
tableNumber: (tableNumber?.isEmpty ?? true) ? null : tableNumber,
|
||||
subtotal: subtotal ?? 0,
|
||||
discountAmount: discountAmount ?? 0,
|
||||
taxAmount: taxAmount ?? 0,
|
||||
refundAmount: refundAmount ?? 0,
|
||||
items: items?.map((e) => e.toDomain()).toList() ?? [],
|
||||
payments: payments?.map((e) => e.toDomain()).toList() ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class CustomerOrderItemDto with _$CustomerOrderItemDto {
|
||||
const factory CustomerOrderItemDto({
|
||||
@JsonKey(name: 'id') String? id,
|
||||
@JsonKey(name: 'product_name') String? productName,
|
||||
@JsonKey(name: 'variant_name') String? variantName,
|
||||
@JsonKey(name: 'quantity') int? quantity,
|
||||
@JsonKey(name: 'weight') double? weight,
|
||||
@JsonKey(name: 'unit_name') String? unitName,
|
||||
@JsonKey(name: 'unit_price') int? unitPrice,
|
||||
@JsonKey(name: 'total_price') int? totalPrice,
|
||||
@JsonKey(name: 'refund_quantity') int? refundQuantity,
|
||||
}) = _CustomerOrderItemDto;
|
||||
|
||||
factory CustomerOrderItemDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$CustomerOrderItemDtoFromJson(json);
|
||||
|
||||
const CustomerOrderItemDto._();
|
||||
|
||||
CustomerOrderItem toDomain() => CustomerOrderItem(
|
||||
id: id ?? '',
|
||||
productName: productName ?? '',
|
||||
variantName: (variantName?.isEmpty ?? true) ? null : variantName,
|
||||
quantity: quantity ?? 0,
|
||||
weight: weight,
|
||||
unitName: unitName,
|
||||
unitPrice: unitPrice ?? 0,
|
||||
totalPrice: totalPrice ?? 0,
|
||||
refundQuantity: refundQuantity ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class CustomerOrderPaymentDto with _$CustomerOrderPaymentDto {
|
||||
const factory CustomerOrderPaymentDto({
|
||||
@JsonKey(name: 'id') String? id,
|
||||
@JsonKey(name: 'method_name') String? methodName,
|
||||
@JsonKey(name: 'method_type') String? methodType,
|
||||
@JsonKey(name: 'amount') int? amount,
|
||||
@JsonKey(name: 'refund_amount') int? refundAmount,
|
||||
@JsonKey(name: 'points_used') int? pointsUsed,
|
||||
}) = _CustomerOrderPaymentDto;
|
||||
|
||||
factory CustomerOrderPaymentDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$CustomerOrderPaymentDtoFromJson(json);
|
||||
|
||||
const CustomerOrderPaymentDto._();
|
||||
|
||||
CustomerOrderPayment toDomain() => CustomerOrderPayment(
|
||||
id: id ?? '',
|
||||
methodName: methodName ?? '',
|
||||
methodType: methodType ?? '',
|
||||
amount: amount ?? 0,
|
||||
refundAmount: refundAmount ?? 0,
|
||||
pointsUsed: pointsUsed,
|
||||
);
|
||||
}
|
||||
|
||||
class CustomerOrderPageDto {
|
||||
final List<CustomerOrderDto> items;
|
||||
final WalletPaginationDto pagination;
|
||||
|
||||
const CustomerOrderPageDto({required this.items, required this.pagination});
|
||||
|
||||
CustomerOrderPage toDomain() => CustomerOrderPage(
|
||||
items: items.map((e) => e.toDomain()).toList(),
|
||||
page: pagination.page ?? 1,
|
||||
totalPages: pagination.totalPages ?? 1,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ExchangePreviewDto with _$ExchangePreviewDto {
|
||||
const factory ExchangePreviewDto({
|
||||
@JsonKey(name: 'coin_amount') int? coinAmount,
|
||||
@JsonKey(name: 'point_amount') int? pointAmount,
|
||||
@JsonKey(name: 'coin_balance') int? coinBalance,
|
||||
@JsonKey(name: 'coins') int? coins,
|
||||
@JsonKey(name: 'points') int? points,
|
||||
@JsonKey(name: 'valid') bool? valid,
|
||||
@JsonKey(name: 'reason') String? reason,
|
||||
}) = _ExchangePreviewDto;
|
||||
|
||||
factory ExchangePreviewDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExchangePreviewDtoFromJson(json);
|
||||
|
||||
const ExchangePreviewDto._();
|
||||
|
||||
ExchangePreview toDomain() => ExchangePreview(
|
||||
coinAmount: coinAmount ?? 0,
|
||||
pointAmount: pointAmount ?? 0,
|
||||
coinBalance: coinBalance ?? 0,
|
||||
coins: coins ?? 0,
|
||||
points: points ?? 0,
|
||||
valid: valid ?? false,
|
||||
reason: reason,
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ExchangeResultDto with _$ExchangeResultDto {
|
||||
const factory ExchangeResultDto({
|
||||
@JsonKey(name: 'coins') int? coins,
|
||||
@JsonKey(name: 'points') int? points,
|
||||
@JsonKey(name: 'coin_balance') int? coinBalance,
|
||||
@JsonKey(name: 'point_balance') int? pointBalance,
|
||||
@JsonKey(name: 'lots') List<WalletLotDto>? lots,
|
||||
@JsonKey(name: 'replayed') bool? replayed,
|
||||
}) = _ExchangeResultDto;
|
||||
|
||||
factory ExchangeResultDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExchangeResultDtoFromJson(json);
|
||||
|
||||
const ExchangeResultDto._();
|
||||
|
||||
ExchangeResult toDomain() => ExchangeResult(
|
||||
coins: coins ?? 0,
|
||||
points: points ?? 0,
|
||||
coinBalance: coinBalance ?? 0,
|
||||
pointBalance: pointBalance ?? 0,
|
||||
lots: lots?.map((e) => e.toDomain()).toList() ?? [],
|
||||
replayed: replayed ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class WalletLotDto with _$WalletLotDto {
|
||||
const factory WalletLotDto({
|
||||
@JsonKey(name: 'amount') int? amount,
|
||||
@JsonKey(name: 'expires_at') String? expiresAt,
|
||||
}) = _WalletLotDto;
|
||||
|
||||
factory WalletLotDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$WalletLotDtoFromJson(json);
|
||||
|
||||
const WalletLotDto._();
|
||||
|
||||
WalletLot toDomain() =>
|
||||
WalletLot(amount: amount ?? 0, expiresAt: _parseDateTime(expiresAt));
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class OutletDto with _$OutletDto {
|
||||
const factory OutletDto({
|
||||
@JsonKey(name: 'id') String? id,
|
||||
@JsonKey(name: 'name') String? name,
|
||||
@JsonKey(name: 'address') String? address,
|
||||
@JsonKey(name: 'accepts_point_payment') bool? acceptsPointPayment,
|
||||
@JsonKey(name: 'earns_points') bool? earnsPoints,
|
||||
@JsonKey(name: 'earns_coins') bool? earnsCoins,
|
||||
}) = _OutletDto;
|
||||
|
||||
factory OutletDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$OutletDtoFromJson(json);
|
||||
|
||||
const OutletDto._();
|
||||
|
||||
Outlet toDomain() => Outlet(
|
||||
id: id ?? '',
|
||||
name: name ?? '',
|
||||
address: (address?.trim().isEmpty ?? true) ? null : address!.trim(),
|
||||
acceptsPointPayment: acceptsPointPayment ?? false,
|
||||
earnsPoints: earnsPoints ?? false,
|
||||
earnsCoins: earnsCoins ?? false,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class PaymentCodeDto with _$PaymentCodeDto {
|
||||
const factory PaymentCodeDto({
|
||||
@JsonKey(name: 'code') String? code,
|
||||
@JsonKey(name: 'qr_payload') String? qrPayload,
|
||||
@JsonKey(name: 'expires_at') String? expiresAt,
|
||||
}) = _PaymentCodeDto;
|
||||
|
||||
factory PaymentCodeDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$PaymentCodeDtoFromJson(json);
|
||||
|
||||
const PaymentCodeDto._();
|
||||
|
||||
PaymentCode toDomain() => PaymentCode(
|
||||
code: code ?? '',
|
||||
qrPayload: qrPayload ?? '',
|
||||
// Kode berlaku 2 menit; dipakai hanya bila server tidak mengirim expires_at.
|
||||
expiresAt:
|
||||
_parseDateTime(expiresAt) ??
|
||||
DateTime.now().add(const Duration(minutes: 2)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class PinStatusDto with _$PinStatusDto {
|
||||
const factory PinStatusDto({
|
||||
@JsonKey(name: 'has_pin') bool? hasPin,
|
||||
@JsonKey(name: 'locked_until') String? lockedUntil,
|
||||
@JsonKey(name: 'transfer_blocked_until') String? transferBlockedUntil,
|
||||
}) = _PinStatusDto;
|
||||
|
||||
factory PinStatusDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$PinStatusDtoFromJson(json);
|
||||
|
||||
const PinStatusDto._();
|
||||
|
||||
PinStatus toDomain() => PinStatus(
|
||||
hasPin: hasPin ?? false,
|
||||
lockedUntil: _parseDateTime(lockedUntil),
|
||||
transferBlockedUntil: _parseDateTime(transferBlockedUntil),
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class PinOtpDto with _$PinOtpDto {
|
||||
const factory PinOtpDto({
|
||||
@JsonKey(name: 'purpose') String? purpose,
|
||||
@JsonKey(name: 'otp_token') String? otpToken,
|
||||
@JsonKey(name: 'expires_at') String? expiresAt,
|
||||
}) = _PinOtpDto;
|
||||
|
||||
factory PinOtpDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$PinOtpDtoFromJson(json);
|
||||
|
||||
const PinOtpDto._();
|
||||
|
||||
PinOtp toDomain() => PinOtp(
|
||||
purpose: purpose == PinOtpPurpose.reset.apiValue
|
||||
? PinOtpPurpose.reset
|
||||
: PinOtpPurpose.setup,
|
||||
otpToken: otpToken ?? '',
|
||||
expiresAt: _parseDateTime(expiresAt),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class TransferRecipientDto with _$TransferRecipientDto {
|
||||
const factory TransferRecipientDto({
|
||||
@JsonKey(name: 'name') String? name,
|
||||
@JsonKey(name: 'phone_number') String? phoneNumber,
|
||||
}) = _TransferRecipientDto;
|
||||
|
||||
factory TransferRecipientDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$TransferRecipientDtoFromJson(json);
|
||||
|
||||
const TransferRecipientDto._();
|
||||
|
||||
TransferRecipient toDomain() =>
|
||||
TransferRecipient(name: name ?? '', phoneNumber: phoneNumber ?? '');
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class TransferResultDto with _$TransferResultDto {
|
||||
const factory TransferResultDto({
|
||||
@JsonKey(name: 'currency') String? currency,
|
||||
@JsonKey(name: 'amount') int? amount,
|
||||
@JsonKey(name: 'recipient') TransferRecipientDto? recipient,
|
||||
@JsonKey(name: 'lots') List<WalletLotDto>? lots,
|
||||
@JsonKey(name: 'balance') int? balance,
|
||||
@JsonKey(name: 'replayed') bool? replayed,
|
||||
}) = _TransferResultDto;
|
||||
|
||||
factory TransferResultDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$TransferResultDtoFromJson(json);
|
||||
|
||||
const TransferResultDto._();
|
||||
|
||||
TransferResult toDomain() => TransferResult(
|
||||
currency: WalletCurrency.fromApi(currency),
|
||||
amount: amount ?? 0,
|
||||
recipient:
|
||||
recipient?.toDomain() ??
|
||||
const TransferRecipient(name: '', phoneNumber: ''),
|
||||
lots: lots?.map((e) => e.toDomain()).toList() ?? [],
|
||||
balance: balance ?? 0,
|
||||
replayed: replayed ?? false,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class WalletExpiringDto with _$WalletExpiringDto {
|
||||
const factory WalletExpiringDto({
|
||||
@JsonKey(name: 'point') List<ExpiringAmountDto>? point,
|
||||
@JsonKey(name: 'coin') List<ExpiringAmountDto>? coin,
|
||||
}) = _WalletExpiringDto;
|
||||
|
||||
factory WalletExpiringDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$WalletExpiringDtoFromJson(json);
|
||||
|
||||
const WalletExpiringDto._();
|
||||
|
||||
WalletExpiring toDomain() =>
|
||||
WalletExpiring(point: _sorted(point), coin: _sorted(coin));
|
||||
|
||||
/// Paling dekat di atas.
|
||||
List<ExpiringAmount> _sorted(List<ExpiringAmountDto>? list) =>
|
||||
(list ?? []).map((e) => e.toDomain()).whereType<ExpiringAmount>().toList()
|
||||
..sort((a, b) => a.date.compareTo(b.date));
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class WalletSummaryDto with _$WalletSummaryDto {
|
||||
const factory WalletSummaryDto({
|
||||
@JsonKey(name: 'point_balance') int? pointBalance,
|
||||
@JsonKey(name: 'coin_balance') int? coinBalance,
|
||||
@JsonKey(name: 'point_value') int? pointValue,
|
||||
@JsonKey(name: 'point_discount_value') int? pointDiscountValue,
|
||||
@JsonKey(name: 'nearest_expiring') NearestExpiringDto? nearestExpiring,
|
||||
@JsonKey(name: 'recent_transactions')
|
||||
List<WalletTransactionDto>? recentTransactions,
|
||||
}) = _WalletSummaryDto;
|
||||
|
||||
factory WalletSummaryDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$WalletSummaryDtoFromJson(json);
|
||||
|
||||
const WalletSummaryDto._();
|
||||
|
||||
WalletSummary toDomain() => WalletSummary(
|
||||
pointBalance: pointBalance ?? 0,
|
||||
coinBalance: coinBalance ?? 0,
|
||||
pointValue: pointValue ?? 0,
|
||||
pointDiscountValue: pointDiscountValue ?? 0,
|
||||
nearestExpiringPoint: nearestExpiring?.point?.toDomain(),
|
||||
nearestExpiringCoin: nearestExpiring?.coin?.toDomain(),
|
||||
recentTransactions:
|
||||
recentTransactions?.map((e) => e.toDomain()).toList() ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class NearestExpiringDto with _$NearestExpiringDto {
|
||||
const factory NearestExpiringDto({
|
||||
@JsonKey(name: 'point') ExpiringAmountDto? point,
|
||||
@JsonKey(name: 'coin') ExpiringAmountDto? coin,
|
||||
}) = _NearestExpiringDto;
|
||||
|
||||
factory NearestExpiringDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$NearestExpiringDtoFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ExpiringAmountDto with _$ExpiringAmountDto {
|
||||
const factory ExpiringAmountDto({
|
||||
@JsonKey(name: 'amount') int? amount,
|
||||
@JsonKey(name: 'date') String? date,
|
||||
}) = _ExpiringAmountDto;
|
||||
|
||||
factory ExpiringAmountDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExpiringAmountDtoFromJson(json);
|
||||
|
||||
const ExpiringAmountDto._();
|
||||
|
||||
ExpiringAmount? toDomain() {
|
||||
final parsed = _parseDate(date);
|
||||
if (parsed == null) return null;
|
||||
return ExpiringAmount(amount: amount ?? 0, date: parsed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
part of '../wallet_dtos.dart';
|
||||
|
||||
@freezed
|
||||
abstract class WalletTransactionDto with _$WalletTransactionDto {
|
||||
const factory WalletTransactionDto({
|
||||
@JsonKey(name: 'id') String? id,
|
||||
@JsonKey(name: 'currency') String? currency,
|
||||
@JsonKey(name: 'type') String? type,
|
||||
@JsonKey(name: 'amount') int? amount,
|
||||
@JsonKey(name: 'balance_after') int? balanceAfter,
|
||||
@JsonKey(name: 'description') String? description,
|
||||
@JsonKey(name: 'group_id') String? groupId,
|
||||
@JsonKey(name: 'expires_at') String? expiresAt,
|
||||
@JsonKey(name: 'created_at') String? createdAt,
|
||||
}) = _WalletTransactionDto;
|
||||
|
||||
factory WalletTransactionDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$WalletTransactionDtoFromJson(json);
|
||||
|
||||
const WalletTransactionDto._();
|
||||
|
||||
WalletTransaction toDomain() => WalletTransaction(
|
||||
id: id ?? '',
|
||||
currency: WalletCurrency.fromApi(currency),
|
||||
type: WalletTransactionType.fromApi(type),
|
||||
amount: amount ?? 0,
|
||||
balanceAfter: balanceAfter ?? 0,
|
||||
description: description ?? '',
|
||||
groupId: groupId,
|
||||
expiresAt: _parseDateTime(expiresAt),
|
||||
createdAt: _parseDateTime(createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class WalletPaginationDto with _$WalletPaginationDto {
|
||||
const factory WalletPaginationDto({
|
||||
@JsonKey(name: 'page') int? page,
|
||||
@JsonKey(name: 'limit') int? limit,
|
||||
@JsonKey(name: 'total_count') int? totalCount,
|
||||
@JsonKey(name: 'total_pages') int? totalPages,
|
||||
}) = _WalletPaginationDto;
|
||||
|
||||
factory WalletPaginationDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$WalletPaginationDtoFromJson(json);
|
||||
}
|
||||
|
||||
class WalletTransactionPageDto {
|
||||
final List<WalletTransactionDto> items;
|
||||
final WalletPaginationDto pagination;
|
||||
|
||||
const WalletTransactionPageDto({
|
||||
required this.items,
|
||||
required this.pagination,
|
||||
});
|
||||
|
||||
WalletTransactionPage toDomain() => WalletTransactionPage(
|
||||
items: items.map((e) => e.toDomain()).toList(),
|
||||
page: pagination.page ?? 1,
|
||||
totalPages: pagination.totalPages ?? 1,
|
||||
totalCount: pagination.totalCount ?? items.length,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../datasources/device_data_provider.dart';
|
||||
|
||||
@Injectable(as: IDeviceRepository)
|
||||
class DeviceRepository implements IDeviceRepository {
|
||||
final DeviceLocalDataProvider _localDataProvider;
|
||||
final DeviceRemoteDataProvider _remoteDataProvider;
|
||||
|
||||
final String _logName = 'DeviceRepository';
|
||||
|
||||
DeviceRepository(this._localDataProvider, this._remoteDataProvider);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, Unit>> register({
|
||||
required String fcmToken,
|
||||
required String platform,
|
||||
required String appVersion,
|
||||
}) async {
|
||||
try {
|
||||
final result = await _remoteDataProvider.register(
|
||||
deviceId: await _localDataProvider.deviceId(),
|
||||
fcmToken: fcmToken,
|
||||
platform: platform,
|
||||
appVersion: appVersion,
|
||||
);
|
||||
if (result.hasError) return left(result.error!);
|
||||
|
||||
await _localDataProvider.setRegistered(true);
|
||||
return right(unit);
|
||||
} catch (e, s) {
|
||||
log('register', name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, Unit>> unregister() async {
|
||||
try {
|
||||
if (!await _localDataProvider.isRegistered()) return right(unit);
|
||||
|
||||
final result = await _remoteDataProvider.unregister(
|
||||
deviceId: await _localDataProvider.deviceId(),
|
||||
);
|
||||
if (result.hasError) return left(result.error!);
|
||||
|
||||
await _localDataProvider.setRegistered(false);
|
||||
return right(unit);
|
||||
} catch (e, s) {
|
||||
log('unregister', name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../datasources/customer_remote_data_provider.dart';
|
||||
|
||||
@Injectable(as: IOrderRepository)
|
||||
class OrderRepository implements IOrderRepository {
|
||||
final CustomerRemoteDataProvider _remoteDataProvider;
|
||||
|
||||
final String _logName = 'OrderRepository';
|
||||
|
||||
OrderRepository(this._remoteDataProvider);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, CustomerOrderPage>> getOrders({
|
||||
required int page,
|
||||
int limit = 20,
|
||||
}) => _run(
|
||||
'getOrders',
|
||||
() => _remoteDataProvider.fetchOrders(page: page, limit: limit),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, CustomerOrderDetail>> getOrderDetail(
|
||||
String id,
|
||||
) => _run(
|
||||
'getOrderDetail',
|
||||
() => _remoteDataProvider.fetchOrderDetail(id),
|
||||
(dto) => dto.toDetailDomain(),
|
||||
);
|
||||
|
||||
Future<Either<WalletFailure, R>> _run<D, R>(
|
||||
String name,
|
||||
Future<DC<WalletFailure, D>> Function() call,
|
||||
R Function(D dto) toDomain,
|
||||
) async {
|
||||
try {
|
||||
final result = await call();
|
||||
if (result.hasError) return left(result.error!);
|
||||
return right(toDomain(result.data as D));
|
||||
} catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../datasources/customer_remote_data_provider.dart';
|
||||
|
||||
@Injectable(as: IOutletRepository)
|
||||
class OutletRepository implements IOutletRepository {
|
||||
final CustomerRemoteDataProvider _remoteDataProvider;
|
||||
|
||||
final String _logName = 'OutletRepository';
|
||||
|
||||
OutletRepository(this._remoteDataProvider);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, List<Outlet>>> getOutlets() async {
|
||||
try {
|
||||
final result = await _remoteDataProvider.fetchOutlets();
|
||||
if (result.hasError) return left(result.error!);
|
||||
return right(result.data!.map((e) => e.toDomain()).toList());
|
||||
} catch (e, s) {
|
||||
log('getOutlets', name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../datasources/pin_remote_data_provider.dart';
|
||||
|
||||
@Injectable(as: IPinRepository)
|
||||
class PinRepository implements IPinRepository {
|
||||
final PinRemoteDataProvider _remoteDataProvider;
|
||||
|
||||
final String _logName = 'PinRepository';
|
||||
|
||||
PinRepository(this._remoteDataProvider);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, PinStatus>> getStatus() => _run(
|
||||
'getStatus',
|
||||
_remoteDataProvider.fetchStatus,
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, PinOtp>> requestOtp(PinOtpPurpose purpose) =>
|
||||
_run(
|
||||
'requestOtp',
|
||||
() => _remoteDataProvider.requestOtp(purpose),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, PinStatus>> setup({
|
||||
required String otpToken,
|
||||
required String otpCode,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _run(
|
||||
'setup',
|
||||
() => _remoteDataProvider.setup(
|
||||
otpToken: otpToken,
|
||||
otpCode: otpCode,
|
||||
pin: pin,
|
||||
confirmPin: confirmPin,
|
||||
),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, Unit>> change({
|
||||
required String oldPin,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _run(
|
||||
'change',
|
||||
() => _remoteDataProvider.change(
|
||||
oldPin: oldPin,
|
||||
pin: pin,
|
||||
confirmPin: confirmPin,
|
||||
),
|
||||
(value) => value,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, Unit>> reset({
|
||||
required String otpToken,
|
||||
required String otpCode,
|
||||
required String pin,
|
||||
required String confirmPin,
|
||||
}) => _run(
|
||||
'reset',
|
||||
() => _remoteDataProvider.reset(
|
||||
otpToken: otpToken,
|
||||
otpCode: otpCode,
|
||||
pin: pin,
|
||||
confirmPin: confirmPin,
|
||||
),
|
||||
(value) => value,
|
||||
);
|
||||
|
||||
Future<Either<WalletFailure, R>> _run<D, R>(
|
||||
String name,
|
||||
Future<DC<WalletFailure, D>> Function() call,
|
||||
R Function(D dto) toDomain,
|
||||
) async {
|
||||
try {
|
||||
final result = await call();
|
||||
if (result.hasError) return left(result.error!);
|
||||
return right(toDomain(result.data as D));
|
||||
} catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:data_channel/data_channel.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/wallet/wallet.dart';
|
||||
import '../datasources/wallet_remote_data_provider.dart';
|
||||
|
||||
@Injectable(as: IWalletRepository)
|
||||
class WalletRepository implements IWalletRepository {
|
||||
final WalletRemoteDataProvider _remoteDataProvider;
|
||||
|
||||
final String _logName = 'WalletRepository';
|
||||
|
||||
WalletRepository(this._remoteDataProvider);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, WalletSummary>> getWallet() => _run(
|
||||
'getWallet',
|
||||
_remoteDataProvider.fetchWallet,
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, WalletTransactionPage>> getTransactions({
|
||||
required int page,
|
||||
int limit = 20,
|
||||
WalletCurrency? currency,
|
||||
List<WalletTransactionType> types = const [],
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
}) => _run(
|
||||
'getTransactions',
|
||||
() => _remoteDataProvider.fetchTransactions(
|
||||
page: page,
|
||||
limit: limit,
|
||||
currency: currency,
|
||||
types: types,
|
||||
from: from,
|
||||
to: to,
|
||||
),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, WalletExpiring>> getExpiring() => _run(
|
||||
'getExpiring',
|
||||
_remoteDataProvider.fetchExpiring,
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, PaymentCode>> createPaymentCode({
|
||||
required String pin,
|
||||
}) => _run(
|
||||
'createPaymentCode',
|
||||
() => _remoteDataProvider.createPaymentCode(pin: pin),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, ExchangePreview>> previewExchange({
|
||||
required int coins,
|
||||
}) => _run(
|
||||
'previewExchange',
|
||||
() => _remoteDataProvider.previewExchange(coins: coins),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, ExchangeResult>> exchange({
|
||||
required int coins,
|
||||
required String pin,
|
||||
required String idempotencyKey,
|
||||
}) => _run(
|
||||
'exchange',
|
||||
() => _remoteDataProvider.exchange(
|
||||
coins: coins,
|
||||
pin: pin,
|
||||
idempotencyKey: idempotencyKey,
|
||||
),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, TransferRecipient>> checkRecipient({
|
||||
required String phone,
|
||||
}) => _run(
|
||||
'checkRecipient',
|
||||
() => _remoteDataProvider.checkRecipient(phone: phone),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<WalletFailure, TransferResult>> transfer({
|
||||
required WalletCurrency currency,
|
||||
required int amount,
|
||||
required String recipientPhone,
|
||||
required String pin,
|
||||
required String idempotencyKey,
|
||||
}) => _run(
|
||||
'transfer',
|
||||
() => _remoteDataProvider.transfer(
|
||||
currency: currency,
|
||||
amount: amount,
|
||||
recipientPhone: recipientPhone,
|
||||
pin: pin,
|
||||
idempotencyKey: idempotencyKey,
|
||||
),
|
||||
(dto) => dto.toDomain(),
|
||||
);
|
||||
|
||||
Future<Either<WalletFailure, R>> _run<D, R>(
|
||||
String name,
|
||||
Future<DC<WalletFailure, D>> Function() call,
|
||||
R Function(D dto) toDomain,
|
||||
) async {
|
||||
try {
|
||||
final result = await call();
|
||||
if (result.hasError) return left(result.error!);
|
||||
return right(toDomain(result.data as D));
|
||||
} catch (e, s) {
|
||||
log(name, name: _logName, error: e, stackTrace: s);
|
||||
return left(const WalletFailure.unexpectedError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import '../../domain/wallet/wallet.dart';
|
||||
|
||||
part 'wallet_dtos.freezed.dart';
|
||||
part 'wallet_dtos.g.dart';
|
||||
|
||||
part 'dto/wallet_summary_dto.dart';
|
||||
part 'dto/wallet_transaction_dto.dart';
|
||||
part 'dto/wallet_expiring_dto.dart';
|
||||
part 'dto/payment_code_dto.dart';
|
||||
part 'dto/exchange_dto.dart';
|
||||
part 'dto/transfer_dto.dart';
|
||||
part 'dto/pin_dto.dart';
|
||||
part 'dto/outlet_dto.dart';
|
||||
part 'dto/customer_order_dto.dart';
|
||||
|
||||
DateTime? _parseDateTime(String? value) =>
|
||||
value == null ? null : DateTime.tryParse(value);
|
||||
|
||||
/// Tanggal `yyyy-MM-dd` (WIB) sebagai tanggal kalender, tanpa konversi zona.
|
||||
DateTime? _parseDate(String? value) {
|
||||
if (value == null) return null;
|
||||
final parsed = DateTime.tryParse(value);
|
||||
if (parsed == null) return null;
|
||||
return DateTime(parsed.year, parsed.month, parsed.day);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,373 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'wallet_dtos.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_WalletSummaryDto _$WalletSummaryDtoFromJson(Map<String, dynamic> json) =>
|
||||
_WalletSummaryDto(
|
||||
pointBalance: (json['point_balance'] as num?)?.toInt(),
|
||||
coinBalance: (json['coin_balance'] as num?)?.toInt(),
|
||||
pointValue: (json['point_value'] as num?)?.toInt(),
|
||||
pointDiscountValue: (json['point_discount_value'] as num?)?.toInt(),
|
||||
nearestExpiring: json['nearest_expiring'] == null
|
||||
? null
|
||||
: NearestExpiringDto.fromJson(
|
||||
json['nearest_expiring'] as Map<String, dynamic>,
|
||||
),
|
||||
recentTransactions: (json['recent_transactions'] as List<dynamic>?)
|
||||
?.map((e) => WalletTransactionDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WalletSummaryDtoToJson(_WalletSummaryDto instance) =>
|
||||
<String, dynamic>{
|
||||
'point_balance': instance.pointBalance,
|
||||
'coin_balance': instance.coinBalance,
|
||||
'point_value': instance.pointValue,
|
||||
'point_discount_value': instance.pointDiscountValue,
|
||||
'nearest_expiring': instance.nearestExpiring,
|
||||
'recent_transactions': instance.recentTransactions,
|
||||
};
|
||||
|
||||
_NearestExpiringDto _$NearestExpiringDtoFromJson(Map<String, dynamic> json) =>
|
||||
_NearestExpiringDto(
|
||||
point: json['point'] == null
|
||||
? null
|
||||
: ExpiringAmountDto.fromJson(json['point'] as Map<String, dynamic>),
|
||||
coin: json['coin'] == null
|
||||
? null
|
||||
: ExpiringAmountDto.fromJson(json['coin'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$NearestExpiringDtoToJson(_NearestExpiringDto instance) =>
|
||||
<String, dynamic>{'point': instance.point, 'coin': instance.coin};
|
||||
|
||||
_ExpiringAmountDto _$ExpiringAmountDtoFromJson(Map<String, dynamic> json) =>
|
||||
_ExpiringAmountDto(
|
||||
amount: (json['amount'] as num?)?.toInt(),
|
||||
date: json['date'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ExpiringAmountDtoToJson(_ExpiringAmountDto instance) =>
|
||||
<String, dynamic>{'amount': instance.amount, 'date': instance.date};
|
||||
|
||||
_WalletTransactionDto _$WalletTransactionDtoFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _WalletTransactionDto(
|
||||
id: json['id'] as String?,
|
||||
currency: json['currency'] as String?,
|
||||
type: json['type'] as String?,
|
||||
amount: (json['amount'] as num?)?.toInt(),
|
||||
balanceAfter: (json['balance_after'] as num?)?.toInt(),
|
||||
description: json['description'] as String?,
|
||||
groupId: json['group_id'] as String?,
|
||||
expiresAt: json['expires_at'] as String?,
|
||||
createdAt: json['created_at'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WalletTransactionDtoToJson(
|
||||
_WalletTransactionDto instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'currency': instance.currency,
|
||||
'type': instance.type,
|
||||
'amount': instance.amount,
|
||||
'balance_after': instance.balanceAfter,
|
||||
'description': instance.description,
|
||||
'group_id': instance.groupId,
|
||||
'expires_at': instance.expiresAt,
|
||||
'created_at': instance.createdAt,
|
||||
};
|
||||
|
||||
_WalletPaginationDto _$WalletPaginationDtoFromJson(Map<String, dynamic> json) =>
|
||||
_WalletPaginationDto(
|
||||
page: (json['page'] as num?)?.toInt(),
|
||||
limit: (json['limit'] as num?)?.toInt(),
|
||||
totalCount: (json['total_count'] as num?)?.toInt(),
|
||||
totalPages: (json['total_pages'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WalletPaginationDtoToJson(
|
||||
_WalletPaginationDto instance,
|
||||
) => <String, dynamic>{
|
||||
'page': instance.page,
|
||||
'limit': instance.limit,
|
||||
'total_count': instance.totalCount,
|
||||
'total_pages': instance.totalPages,
|
||||
};
|
||||
|
||||
_WalletExpiringDto _$WalletExpiringDtoFromJson(Map<String, dynamic> json) =>
|
||||
_WalletExpiringDto(
|
||||
point: (json['point'] as List<dynamic>?)
|
||||
?.map((e) => ExpiringAmountDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
coin: (json['coin'] as List<dynamic>?)
|
||||
?.map((e) => ExpiringAmountDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WalletExpiringDtoToJson(_WalletExpiringDto instance) =>
|
||||
<String, dynamic>{'point': instance.point, 'coin': instance.coin};
|
||||
|
||||
_PaymentCodeDto _$PaymentCodeDtoFromJson(Map<String, dynamic> json) =>
|
||||
_PaymentCodeDto(
|
||||
code: json['code'] as String?,
|
||||
qrPayload: json['qr_payload'] as String?,
|
||||
expiresAt: json['expires_at'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$PaymentCodeDtoToJson(_PaymentCodeDto instance) =>
|
||||
<String, dynamic>{
|
||||
'code': instance.code,
|
||||
'qr_payload': instance.qrPayload,
|
||||
'expires_at': instance.expiresAt,
|
||||
};
|
||||
|
||||
_ExchangePreviewDto _$ExchangePreviewDtoFromJson(Map<String, dynamic> json) =>
|
||||
_ExchangePreviewDto(
|
||||
coinAmount: (json['coin_amount'] as num?)?.toInt(),
|
||||
pointAmount: (json['point_amount'] as num?)?.toInt(),
|
||||
coinBalance: (json['coin_balance'] as num?)?.toInt(),
|
||||
coins: (json['coins'] as num?)?.toInt(),
|
||||
points: (json['points'] as num?)?.toInt(),
|
||||
valid: json['valid'] as bool?,
|
||||
reason: json['reason'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ExchangePreviewDtoToJson(_ExchangePreviewDto instance) =>
|
||||
<String, dynamic>{
|
||||
'coin_amount': instance.coinAmount,
|
||||
'point_amount': instance.pointAmount,
|
||||
'coin_balance': instance.coinBalance,
|
||||
'coins': instance.coins,
|
||||
'points': instance.points,
|
||||
'valid': instance.valid,
|
||||
'reason': instance.reason,
|
||||
};
|
||||
|
||||
_ExchangeResultDto _$ExchangeResultDtoFromJson(Map<String, dynamic> json) =>
|
||||
_ExchangeResultDto(
|
||||
coins: (json['coins'] as num?)?.toInt(),
|
||||
points: (json['points'] as num?)?.toInt(),
|
||||
coinBalance: (json['coin_balance'] as num?)?.toInt(),
|
||||
pointBalance: (json['point_balance'] as num?)?.toInt(),
|
||||
lots: (json['lots'] as List<dynamic>?)
|
||||
?.map((e) => WalletLotDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
replayed: json['replayed'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ExchangeResultDtoToJson(_ExchangeResultDto instance) =>
|
||||
<String, dynamic>{
|
||||
'coins': instance.coins,
|
||||
'points': instance.points,
|
||||
'coin_balance': instance.coinBalance,
|
||||
'point_balance': instance.pointBalance,
|
||||
'lots': instance.lots,
|
||||
'replayed': instance.replayed,
|
||||
};
|
||||
|
||||
_WalletLotDto _$WalletLotDtoFromJson(Map<String, dynamic> json) =>
|
||||
_WalletLotDto(
|
||||
amount: (json['amount'] as num?)?.toInt(),
|
||||
expiresAt: json['expires_at'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WalletLotDtoToJson(_WalletLotDto instance) =>
|
||||
<String, dynamic>{
|
||||
'amount': instance.amount,
|
||||
'expires_at': instance.expiresAt,
|
||||
};
|
||||
|
||||
_TransferRecipientDto _$TransferRecipientDtoFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _TransferRecipientDto(
|
||||
name: json['name'] as String?,
|
||||
phoneNumber: json['phone_number'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$TransferRecipientDtoToJson(
|
||||
_TransferRecipientDto instance,
|
||||
) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'phone_number': instance.phoneNumber,
|
||||
};
|
||||
|
||||
_TransferResultDto _$TransferResultDtoFromJson(Map<String, dynamic> json) =>
|
||||
_TransferResultDto(
|
||||
currency: json['currency'] as String?,
|
||||
amount: (json['amount'] as num?)?.toInt(),
|
||||
recipient: json['recipient'] == null
|
||||
? null
|
||||
: TransferRecipientDto.fromJson(
|
||||
json['recipient'] as Map<String, dynamic>,
|
||||
),
|
||||
lots: (json['lots'] as List<dynamic>?)
|
||||
?.map((e) => WalletLotDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
balance: (json['balance'] as num?)?.toInt(),
|
||||
replayed: json['replayed'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$TransferResultDtoToJson(_TransferResultDto instance) =>
|
||||
<String, dynamic>{
|
||||
'currency': instance.currency,
|
||||
'amount': instance.amount,
|
||||
'recipient': instance.recipient,
|
||||
'lots': instance.lots,
|
||||
'balance': instance.balance,
|
||||
'replayed': instance.replayed,
|
||||
};
|
||||
|
||||
_PinStatusDto _$PinStatusDtoFromJson(Map<String, dynamic> json) =>
|
||||
_PinStatusDto(
|
||||
hasPin: json['has_pin'] as bool?,
|
||||
lockedUntil: json['locked_until'] as String?,
|
||||
transferBlockedUntil: json['transfer_blocked_until'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$PinStatusDtoToJson(_PinStatusDto instance) =>
|
||||
<String, dynamic>{
|
||||
'has_pin': instance.hasPin,
|
||||
'locked_until': instance.lockedUntil,
|
||||
'transfer_blocked_until': instance.transferBlockedUntil,
|
||||
};
|
||||
|
||||
_PinOtpDto _$PinOtpDtoFromJson(Map<String, dynamic> json) => _PinOtpDto(
|
||||
purpose: json['purpose'] as String?,
|
||||
otpToken: json['otp_token'] as String?,
|
||||
expiresAt: json['expires_at'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$PinOtpDtoToJson(_PinOtpDto instance) =>
|
||||
<String, dynamic>{
|
||||
'purpose': instance.purpose,
|
||||
'otp_token': instance.otpToken,
|
||||
'expires_at': instance.expiresAt,
|
||||
};
|
||||
|
||||
_OutletDto _$OutletDtoFromJson(Map<String, dynamic> json) => _OutletDto(
|
||||
id: json['id'] as String?,
|
||||
name: json['name'] as String?,
|
||||
address: json['address'] as String?,
|
||||
acceptsPointPayment: json['accepts_point_payment'] as bool?,
|
||||
earnsPoints: json['earns_points'] as bool?,
|
||||
earnsCoins: json['earns_coins'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$OutletDtoToJson(_OutletDto instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
'address': instance.address,
|
||||
'accepts_point_payment': instance.acceptsPointPayment,
|
||||
'earns_points': instance.earnsPoints,
|
||||
'earns_coins': instance.earnsCoins,
|
||||
};
|
||||
|
||||
_CustomerOrderDto _$CustomerOrderDtoFromJson(Map<String, dynamic> json) =>
|
||||
_CustomerOrderDto(
|
||||
id: json['id'] as String?,
|
||||
orderNumber: json['order_number'] as String?,
|
||||
outletName: json['outlet_name'] as String?,
|
||||
orderType: json['order_type'] as String?,
|
||||
status: json['status'] as String?,
|
||||
paymentStatus: json['payment_status'] as String?,
|
||||
totalAmount: (json['total_amount'] as num?)?.toInt(),
|
||||
itemCount: (json['item_count'] as num?)?.toInt(),
|
||||
isVoid: json['is_void'] as bool?,
|
||||
isRefund: json['is_refund'] as bool?,
|
||||
pointsEarned: (json['points_earned'] as num?)?.toInt(),
|
||||
coinsEarned: (json['coins_earned'] as num?)?.toInt(),
|
||||
createdAt: json['created_at'] as String?,
|
||||
tableNumber: json['table_number'] as String?,
|
||||
subtotal: (json['subtotal'] as num?)?.toInt(),
|
||||
discountAmount: (json['discount_amount'] as num?)?.toInt(),
|
||||
taxAmount: (json['tax_amount'] as num?)?.toInt(),
|
||||
refundAmount: (json['refund_amount'] as num?)?.toInt(),
|
||||
items: (json['items'] as List<dynamic>?)
|
||||
?.map((e) => CustomerOrderItemDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
payments: (json['payments'] as List<dynamic>?)
|
||||
?.map(
|
||||
(e) => CustomerOrderPaymentDto.fromJson(e as Map<String, dynamic>),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CustomerOrderDtoToJson(_CustomerOrderDto instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'order_number': instance.orderNumber,
|
||||
'outlet_name': instance.outletName,
|
||||
'order_type': instance.orderType,
|
||||
'status': instance.status,
|
||||
'payment_status': instance.paymentStatus,
|
||||
'total_amount': instance.totalAmount,
|
||||
'item_count': instance.itemCount,
|
||||
'is_void': instance.isVoid,
|
||||
'is_refund': instance.isRefund,
|
||||
'points_earned': instance.pointsEarned,
|
||||
'coins_earned': instance.coinsEarned,
|
||||
'created_at': instance.createdAt,
|
||||
'table_number': instance.tableNumber,
|
||||
'subtotal': instance.subtotal,
|
||||
'discount_amount': instance.discountAmount,
|
||||
'tax_amount': instance.taxAmount,
|
||||
'refund_amount': instance.refundAmount,
|
||||
'items': instance.items,
|
||||
'payments': instance.payments,
|
||||
};
|
||||
|
||||
_CustomerOrderItemDto _$CustomerOrderItemDtoFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _CustomerOrderItemDto(
|
||||
id: json['id'] as String?,
|
||||
productName: json['product_name'] as String?,
|
||||
variantName: json['variant_name'] as String?,
|
||||
quantity: (json['quantity'] as num?)?.toInt(),
|
||||
weight: (json['weight'] as num?)?.toDouble(),
|
||||
unitName: json['unit_name'] as String?,
|
||||
unitPrice: (json['unit_price'] as num?)?.toInt(),
|
||||
totalPrice: (json['total_price'] as num?)?.toInt(),
|
||||
refundQuantity: (json['refund_quantity'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CustomerOrderItemDtoToJson(
|
||||
_CustomerOrderItemDto instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'product_name': instance.productName,
|
||||
'variant_name': instance.variantName,
|
||||
'quantity': instance.quantity,
|
||||
'weight': instance.weight,
|
||||
'unit_name': instance.unitName,
|
||||
'unit_price': instance.unitPrice,
|
||||
'total_price': instance.totalPrice,
|
||||
'refund_quantity': instance.refundQuantity,
|
||||
};
|
||||
|
||||
_CustomerOrderPaymentDto _$CustomerOrderPaymentDtoFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _CustomerOrderPaymentDto(
|
||||
id: json['id'] as String?,
|
||||
methodName: json['method_name'] as String?,
|
||||
methodType: json['method_type'] as String?,
|
||||
amount: (json['amount'] as num?)?.toInt(),
|
||||
refundAmount: (json['refund_amount'] as num?)?.toInt(),
|
||||
pointsUsed: (json['points_used'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CustomerOrderPaymentDtoToJson(
|
||||
_CustomerOrderPaymentDto instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'method_name': instance.methodName,
|
||||
'method_type': instance.methodType,
|
||||
'amount': instance.amount,
|
||||
'refund_amount': instance.refundAmount,
|
||||
'points_used': instance.pointsUsed,
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../domain/wallet/wallet.dart';
|
||||
|
||||
/// Hitung mundur bawaan bila server menjawab `429` tanpa header `Retry-After`.
|
||||
const int kDefaultOtpRetrySeconds = 60;
|
||||
|
||||
/// Membaca envelope `{ success, data, errors }`. Mengembalikan `null` bila
|
||||
/// sukses, atau [WalletFailure] yang sesuai bila gagal.
|
||||
WalletFailure? parseWalletFailure(Response response) {
|
||||
if (response.statusCode == 401) return const WalletFailure.unauthorized();
|
||||
|
||||
final body = response.data;
|
||||
if (body is! Map) return _failureFromStatus(response);
|
||||
if (body['success'] == true) return null;
|
||||
|
||||
// Error PIN: `data` berisi `code` dan field tambahan.
|
||||
final data = body['data'];
|
||||
if (data is Map) {
|
||||
final pinFailure = _pinFailure(data['code']?.toString(), data);
|
||||
if (pinFailure != null) return pinFailure;
|
||||
}
|
||||
|
||||
final errors = body['errors'];
|
||||
final first = errors is List && errors.isNotEmpty && errors.first is Map
|
||||
? errors.first as Map
|
||||
: null;
|
||||
final code = first?['code']?.toString();
|
||||
|
||||
switch (code) {
|
||||
case '303':
|
||||
case '310':
|
||||
return const WalletFailure.invalidRequest();
|
||||
case '304':
|
||||
return WalletFailure.rejected(first?['cause']?.toString() ?? '');
|
||||
case '404':
|
||||
return const WalletFailure.notFound();
|
||||
case '429':
|
||||
return WalletFailure.tooManyRequests(_retryAfterSeconds(response));
|
||||
case '900':
|
||||
return const WalletFailure.internalError();
|
||||
}
|
||||
|
||||
return _pinFailure(code, const {}) ?? _failureFromStatus(response);
|
||||
}
|
||||
|
||||
/// Isi `data` dari envelope sukses. Beberapa endpoint (mis. `/wallet`)
|
||||
/// membungkus lagi payload-nya dalam `{ status, message, data }`, jadi lapisan
|
||||
/// itu ikut dikupas.
|
||||
Map<String, dynamic> walletDataOf(Response response) {
|
||||
final data = response.data['data'] as Map;
|
||||
final isInnerEnvelope =
|
||||
data.containsKey('status') &&
|
||||
data.containsKey('message') &&
|
||||
data['data'] is Map;
|
||||
return Map<String, dynamic>.from(isInnerEnvelope ? data['data'] : data);
|
||||
}
|
||||
|
||||
WalletFailure? _pinFailure(String? code, Map data) {
|
||||
switch (code) {
|
||||
case 'PIN_NOT_SET':
|
||||
return const WalletFailure.pinNotSet();
|
||||
case 'PIN_INVALID':
|
||||
return WalletFailure.pinInvalid(_toInt(data['remaining_attempts']));
|
||||
case 'PIN_LOCKED':
|
||||
return WalletFailure.pinLocked(_toDateTime(data['locked_until']));
|
||||
case 'TRANSFER_BLOCKED':
|
||||
return WalletFailure.transferBlocked(
|
||||
_toDateTime(data['transfer_blocked_until']),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
WalletFailure _failureFromStatus(Response response) {
|
||||
final status = response.statusCode ?? 0;
|
||||
if (status == 404) return const WalletFailure.notFound();
|
||||
if (status == 429) {
|
||||
return WalletFailure.tooManyRequests(_retryAfterSeconds(response));
|
||||
}
|
||||
if (status >= 500) return const WalletFailure.internalError();
|
||||
return const WalletFailure.unexpectedError();
|
||||
}
|
||||
|
||||
int _retryAfterSeconds(Response response) =>
|
||||
int.tryParse(response.headers.value('retry-after') ?? '') ??
|
||||
kDefaultOtpRetrySeconds;
|
||||
|
||||
int? _toInt(Object? value) =>
|
||||
value is int ? value : int.tryParse(value?.toString() ?? '');
|
||||
|
||||
DateTime? _toDateTime(Object? value) =>
|
||||
value == null ? null : DateTime.tryParse(value.toString());
|
||||
Reference in New Issue
Block a user