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:
efrilm
2026-10-01 01:43:22 +07:00
co-authored by Claude Opus 5.5
parent 5954510b93
commit f5e3075205
253 changed files with 47212 additions and 17437 deletions
File diff suppressed because it is too large Load Diff
+82 -95
View File
@@ -6,8 +6,8 @@ part of 'auth_dtos.dart';
// JsonSerializableGenerator
// **************************************************************************
_$CheckPhoneDtoImpl _$$CheckPhoneDtoImplFromJson(Map<String, dynamic> json) =>
_$CheckPhoneDtoImpl(
_CheckPhoneDto _$CheckPhoneDtoFromJson(Map<String, dynamic> json) =>
_CheckPhoneDto(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
@@ -15,95 +15,85 @@ _$CheckPhoneDtoImpl _$$CheckPhoneDtoImplFromJson(Map<String, dynamic> json) =>
: CheckPhoneDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$CheckPhoneDtoImplToJson(_$CheckPhoneDtoImpl instance) =>
Map<String, dynamic> _$CheckPhoneDtoToJson(_CheckPhoneDto instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$CheckPhoneDataDtoImpl _$$CheckPhoneDataDtoImplFromJson(
Map<String, dynamic> json,
) => _$CheckPhoneDataDtoImpl(phoneNumber: json['phone_number'] as String?);
_CheckPhoneDataDto _$CheckPhoneDataDtoFromJson(Map<String, dynamic> json) =>
_CheckPhoneDataDto(phoneNumber: json['phone_number'] as String?);
Map<String, dynamic> _$$CheckPhoneDataDtoImplToJson(
_$CheckPhoneDataDtoImpl instance,
) => <String, dynamic>{'phone_number': instance.phoneNumber};
Map<String, dynamic> _$CheckPhoneDataDtoToJson(_CheckPhoneDataDto instance) =>
<String, dynamic>{'phone_number': instance.phoneNumber};
_$RegisterDtoImpl _$$RegisterDtoImplFromJson(Map<String, dynamic> json) =>
_$RegisterDtoImpl(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: RegisterDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$RegisterDtoImplToJson(_$RegisterDtoImpl instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$RegisterDataDtoImpl _$$RegisterDataDtoImplFromJson(
Map<String, dynamic> json,
) => _$RegisterDataDtoImpl(
registrationToken: json['registration_token'] as String?,
otpToken: json['otp_token'] as String?,
expiresIn: (json['expires_in'] as num?)?.toInt(),
_RegisterDto _$RegisterDtoFromJson(Map<String, dynamic> json) => _RegisterDto(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: RegisterDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$RegisterDataDtoImplToJson(
_$RegisterDataDtoImpl instance,
) => <String, dynamic>{
'registration_token': instance.registrationToken,
'otp_token': instance.otpToken,
'expires_in': instance.expiresIn,
};
_$VerifyDtoImpl _$$VerifyDtoImplFromJson(Map<String, dynamic> json) =>
_$VerifyDtoImpl(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: VerifyDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$VerifyDtoImplToJson(_$VerifyDtoImpl instance) =>
Map<String, dynamic> _$RegisterDtoToJson(_RegisterDto instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$VerifyDataDtoImpl _$$VerifyDataDtoImplFromJson(Map<String, dynamic> json) =>
_$VerifyDataDtoImpl(
_RegisterDataDto _$RegisterDataDtoFromJson(Map<String, dynamic> json) =>
_RegisterDataDto(
registrationToken: json['registration_token'] as String?,
otpToken: json['otp_token'] as String?,
expiresIn: (json['expires_in'] as num?)?.toInt(),
);
Map<String, dynamic> _$$VerifyDataDtoImplToJson(_$VerifyDataDtoImpl instance) =>
Map<String, dynamic> _$RegisterDataDtoToJson(_RegisterDataDto instance) =>
<String, dynamic>{
'registration_token': instance.registrationToken,
'otp_token': instance.otpToken,
'expires_in': instance.expiresIn,
};
_VerifyDto _$VerifyDtoFromJson(Map<String, dynamic> json) => _VerifyDto(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: VerifyDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$VerifyDtoToJson(_VerifyDto instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_VerifyDataDto _$VerifyDataDtoFromJson(Map<String, dynamic> json) =>
_VerifyDataDto(registrationToken: json['registration_token'] as String?);
Map<String, dynamic> _$VerifyDataDtoToJson(_VerifyDataDto instance) =>
<String, dynamic>{'registration_token': instance.registrationToken};
_$LoginDtoImpl _$$LoginDtoImplFromJson(Map<String, dynamic> json) =>
_$LoginDtoImpl(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: LoginDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
_LoginDto _$LoginDtoFromJson(Map<String, dynamic> json) => _LoginDto(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: LoginDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$LoginDtoImplToJson(_$LoginDtoImpl instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
Map<String, dynamic> _$LoginDtoToJson(_LoginDto instance) => <String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$LoginDataDtoImpl _$$LoginDataDtoImplFromJson(Map<String, dynamic> json) =>
_$LoginDataDtoImpl(
_LoginDataDto _$LoginDataDtoFromJson(Map<String, dynamic> json) =>
_LoginDataDto(
accessToken: json['access_token'] as String?,
refreshToken: json['refresh_token'] as String?,
user: json['user'] == null
@@ -111,53 +101,50 @@ _$LoginDataDtoImpl _$$LoginDataDtoImplFromJson(Map<String, dynamic> json) =>
: UserDto.fromJson(json['user'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$LoginDataDtoImplToJson(_$LoginDataDtoImpl instance) =>
Map<String, dynamic> _$LoginDataDtoToJson(_LoginDataDto instance) =>
<String, dynamic>{
'access_token': instance.accessToken,
'refresh_token': instance.refreshToken,
'user': instance.user,
};
_$UserDtoImpl _$$UserDtoImplFromJson(Map<String, dynamic> json) =>
_$UserDtoImpl(
id: json['id'] as String?,
name: json['name'] as String?,
phoneNumber: json['phone_number'] as String?,
birthDate: json['birth_date'] as String?,
);
_UserDto _$UserDtoFromJson(Map<String, dynamic> json) => _UserDto(
id: json['id'] as String?,
name: json['name'] as String?,
phoneNumber: json['phone_number'] as String?,
birthDate: json['birth_date'] as String?,
);
Map<String, dynamic> _$$UserDtoImplToJson(_$UserDtoImpl instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'phone_number': instance.phoneNumber,
'birth_date': instance.birthDate,
};
Map<String, dynamic> _$UserDtoToJson(_UserDto instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'phone_number': instance.phoneNumber,
'birth_date': instance.birthDate,
};
_$ResendDtoImpl _$$ResendDtoImplFromJson(Map<String, dynamic> json) =>
_$ResendDtoImpl(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: ResendDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
_ResendDto _$ResendDtoFromJson(Map<String, dynamic> json) => _ResendDto(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: ResendDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$ResendDtoImplToJson(_$ResendDtoImpl instance) =>
Map<String, dynamic> _$ResendDtoToJson(_ResendDto instance) =>
<String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$ResendDataDtoImpl _$$ResendDataDtoImplFromJson(Map<String, dynamic> json) =>
_$ResendDataDtoImpl(
_ResendDataDto _$ResendDataDtoFromJson(Map<String, dynamic> json) =>
_ResendDataDto(
otpToken: json['otp_token'] as String?,
expiresIn: (json['expires_in'] as num?)?.toInt(),
nextResendIn: (json['next_resend_in'] as num?)?.toInt(),
);
Map<String, dynamic> _$$ResendDataDtoImplToJson(_$ResendDataDtoImpl instance) =>
Map<String, dynamic> _$ResendDataDtoToJson(_ResendDataDto instance) =>
<String, dynamic>{
'otp_token': instance.otpToken,
'expires_in': instance.expiresIn,
@@ -17,6 +17,42 @@ class AuthRemoteDataProvider {
AuthRemoteDataProvider(this._apiClient);
static const _defaultErrorMessage = 'Terjadi kesalahan coba lagi nanti';
Map? _firstError(dynamic body) {
final errors = body is Map ? body['errors'] : null;
if (errors is! List || errors.isEmpty || errors.first is! Map) return null;
return errors.first as Map;
}
/// Kode bisa dikirim sebagai string ("304") maupun int (304).
String? _errorCode(dynamic body) => _firstError(body)?['code']?.toString();
/// Pesan untuk error validasi (`303`/`310`) dan aturan bisnis (`304`).
String _errorMessage(dynamic body) {
final error = _firstError(body);
final code = error?['code']?.toString();
final cause = error?['cause']?.toString() ?? '';
final lower = cause.toLowerCase();
if (lower.contains('password') &&
(lower.contains('min') ||
lower.contains('least') ||
lower.contains('short'))) {
final length = RegExp(r'\d+').firstMatch(cause)?.group(0);
return length == null
? 'Kata sandi terlalu pendek'
: 'Kata sandi minimal $length karakter';
}
if ((code == '303' || code == '304' || code == '310') &&
cause.isNotEmpty) {
return cause;
}
return _defaultErrorMessage;
}
Future<DC<AuthFailure, CheckPhoneDto>> checkPhone({
required String phoneNumber,
}) async {
@@ -160,33 +196,14 @@ class AuthRemoteDataProvider {
);
if (response.data['success'] == false) {
if ((response.data['errors'] as List).isNotEmpty) {
if (response.data['errors'][0]['code'] == 900) {
return DC.error(
AuthFailure.dynamicErrorMessage(
'Invalid Registration, Lakukan kembali dari awal',
),
);
} else if (response.data['errors'][0]['code'] == "304") {
return DC.error(
AuthFailure.dynamicErrorMessage(
response.data['errors'][0]['cause'],
),
);
} else {
return DC.error(
AuthFailure.dynamicErrorMessage(
'Terjadi kesalahan coba lagi nanti',
),
);
}
} else {
return DC.error(
AuthFailure.dynamicErrorMessage(
'Terjadi kesalahan coba lagi nanti',
),
);
}
final code = _errorCode(response.data);
return DC.error(
AuthFailure.dynamicErrorMessage(
code == '900'
? 'Invalid Registration, Lakukan kembali dari awal'
: _errorMessage(response.data),
),
);
}
final dto = LoginDto.fromJson(response.data['data']);
@@ -1,7 +1,7 @@
part of '../auth_dtos.dart';
@freezed
class CheckPhoneDto with _$CheckPhoneDto {
abstract class CheckPhoneDto with _$CheckPhoneDto {
const CheckPhoneDto._();
const factory CheckPhoneDto({
@@ -20,7 +20,7 @@ class CheckPhoneDto with _$CheckPhoneDto {
}
@freezed
class CheckPhoneDataDto with _$CheckPhoneDataDto {
abstract class CheckPhoneDataDto with _$CheckPhoneDataDto {
const factory CheckPhoneDataDto({
@JsonKey(name: 'phone_number') String? phoneNumber,
}) = _CheckPhoneDataDto;
+3 -3
View File
@@ -1,7 +1,7 @@
part of '../auth_dtos.dart';
@freezed
class LoginDto with _$LoginDto {
abstract class LoginDto with _$LoginDto {
const factory LoginDto({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@@ -24,7 +24,7 @@ class LoginDto with _$LoginDto {
}
@freezed
class LoginDataDto with _$LoginDataDto {
abstract class LoginDataDto with _$LoginDataDto {
const factory LoginDataDto({
@JsonKey(name: 'access_token') String? accessToken,
@JsonKey(name: 'refresh_token') String? refreshToken,
@@ -36,7 +36,7 @@ class LoginDataDto with _$LoginDataDto {
}
@freezed
class UserDto with _$UserDto {
abstract class UserDto with _$UserDto {
const factory UserDto({
@JsonKey(name: 'id') String? id,
@JsonKey(name: 'name') String? name,
@@ -1,7 +1,7 @@
part of '../auth_dtos.dart';
@freezed
class RegisterDto with _$RegisterDto {
abstract class RegisterDto with _$RegisterDto {
const RegisterDto._();
const factory RegisterDto({
@@ -24,7 +24,7 @@ class RegisterDto with _$RegisterDto {
}
@freezed
class RegisterDataDto with _$RegisterDataDto {
abstract class RegisterDataDto with _$RegisterDataDto {
const factory RegisterDataDto({
@JsonKey(name: 'registration_token') String? registrationToken,
@JsonKey(name: 'otp_token') String? otpToken,
+2 -2
View File
@@ -1,7 +1,7 @@
part of '../auth_dtos.dart';
@freezed
class ResendDto with _$ResendDto {
abstract class ResendDto with _$ResendDto {
const factory ResendDto({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@@ -24,7 +24,7 @@ class ResendDto with _$ResendDto {
}
@freezed
class ResendDataDto with _$ResendDataDto {
abstract class ResendDataDto with _$ResendDataDto {
const factory ResendDataDto({
@JsonKey(name: 'otp_token') String? otpToken,
@JsonKey(name: 'expires_in') int? expiresIn,
+2 -2
View File
@@ -1,7 +1,7 @@
part of '../auth_dtos.dart';
@freezed
class VerifyDto with _$VerifyDto {
abstract class VerifyDto with _$VerifyDto {
const factory VerifyDto({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@@ -22,7 +22,7 @@ class VerifyDto with _$VerifyDto {
}
@freezed
class VerifyDataDto with _$VerifyDataDto {
abstract class VerifyDataDto with _$VerifyDataDto {
const factory VerifyDataDto({
@JsonKey(name: 'registration_token') String? registrationToken,
}) = _VerifyDataDto;
@@ -1,8 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../domain/customer/customer.dart';
part 'customer_dtos.freezed.dart';
part 'customer_dtos.g.dart';
part 'dtos/customer_point_dto.dart';
@@ -1,443 +0,0 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'customer_dtos.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models',
);
CustomerPointDto _$CustomerPointDtoFromJson(Map<String, dynamic> json) {
return _CustomerPointDto.fromJson(json);
}
/// @nodoc
mixin _$CustomerPointDto {
@JsonKey(name: 'status')
String? get status => throw _privateConstructorUsedError;
@JsonKey(name: 'message')
String? get message => throw _privateConstructorUsedError;
@JsonKey(name: 'data')
CustomerPointDataDto? get data => throw _privateConstructorUsedError;
/// Serializes this CustomerPointDto to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$CustomerPointDtoCopyWith<CustomerPointDto> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $CustomerPointDtoCopyWith<$Res> {
factory $CustomerPointDtoCopyWith(
CustomerPointDto value,
$Res Function(CustomerPointDto) then,
) = _$CustomerPointDtoCopyWithImpl<$Res, CustomerPointDto>;
@useResult
$Res call({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@JsonKey(name: 'data') CustomerPointDataDto? data,
});
$CustomerPointDataDtoCopyWith<$Res>? get data;
}
/// @nodoc
class _$CustomerPointDtoCopyWithImpl<$Res, $Val extends CustomerPointDto>
implements $CustomerPointDtoCopyWith<$Res> {
_$CustomerPointDtoCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? status = freezed,
Object? message = freezed,
Object? data = freezed,
}) {
return _then(
_value.copyWith(
status: freezed == status
? _value.status
: status // ignore: cast_nullable_to_non_nullable
as String?,
message: freezed == message
? _value.message
: message // ignore: cast_nullable_to_non_nullable
as String?,
data: freezed == data
? _value.data
: data // ignore: cast_nullable_to_non_nullable
as CustomerPointDataDto?,
)
as $Val,
);
}
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$CustomerPointDataDtoCopyWith<$Res>? get data {
if (_value.data == null) {
return null;
}
return $CustomerPointDataDtoCopyWith<$Res>(_value.data!, (value) {
return _then(_value.copyWith(data: value) as $Val);
});
}
}
/// @nodoc
abstract class _$$CustomerPointDtoImplCopyWith<$Res>
implements $CustomerPointDtoCopyWith<$Res> {
factory _$$CustomerPointDtoImplCopyWith(
_$CustomerPointDtoImpl value,
$Res Function(_$CustomerPointDtoImpl) then,
) = __$$CustomerPointDtoImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@JsonKey(name: 'data') CustomerPointDataDto? data,
});
@override
$CustomerPointDataDtoCopyWith<$Res>? get data;
}
/// @nodoc
class __$$CustomerPointDtoImplCopyWithImpl<$Res>
extends _$CustomerPointDtoCopyWithImpl<$Res, _$CustomerPointDtoImpl>
implements _$$CustomerPointDtoImplCopyWith<$Res> {
__$$CustomerPointDtoImplCopyWithImpl(
_$CustomerPointDtoImpl _value,
$Res Function(_$CustomerPointDtoImpl) _then,
) : super(_value, _then);
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? status = freezed,
Object? message = freezed,
Object? data = freezed,
}) {
return _then(
_$CustomerPointDtoImpl(
status: freezed == status
? _value.status
: status // ignore: cast_nullable_to_non_nullable
as String?,
message: freezed == message
? _value.message
: message // ignore: cast_nullable_to_non_nullable
as String?,
data: freezed == data
? _value.data
: data // ignore: cast_nullable_to_non_nullable
as CustomerPointDataDto?,
),
);
}
}
/// @nodoc
@JsonSerializable()
class _$CustomerPointDtoImpl extends _CustomerPointDto {
const _$CustomerPointDtoImpl({
@JsonKey(name: 'status') this.status,
@JsonKey(name: 'message') this.message,
@JsonKey(name: 'data') this.data,
}) : super._();
factory _$CustomerPointDtoImpl.fromJson(Map<String, dynamic> json) =>
_$$CustomerPointDtoImplFromJson(json);
@override
@JsonKey(name: 'status')
final String? status;
@override
@JsonKey(name: 'message')
final String? message;
@override
@JsonKey(name: 'data')
final CustomerPointDataDto? data;
@override
String toString() {
return 'CustomerPointDto(status: $status, message: $message, data: $data)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$CustomerPointDtoImpl &&
(identical(other.status, status) || other.status == status) &&
(identical(other.message, message) || other.message == message) &&
(identical(other.data, data) || other.data == data));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, status, message, data);
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$CustomerPointDtoImplCopyWith<_$CustomerPointDtoImpl> get copyWith =>
__$$CustomerPointDtoImplCopyWithImpl<_$CustomerPointDtoImpl>(
this,
_$identity,
);
@override
Map<String, dynamic> toJson() {
return _$$CustomerPointDtoImplToJson(this);
}
}
abstract class _CustomerPointDto extends CustomerPointDto {
const factory _CustomerPointDto({
@JsonKey(name: 'status') final String? status,
@JsonKey(name: 'message') final String? message,
@JsonKey(name: 'data') final CustomerPointDataDto? data,
}) = _$CustomerPointDtoImpl;
const _CustomerPointDto._() : super._();
factory _CustomerPointDto.fromJson(Map<String, dynamic> json) =
_$CustomerPointDtoImpl.fromJson;
@override
@JsonKey(name: 'status')
String? get status;
@override
@JsonKey(name: 'message')
String? get message;
@override
@JsonKey(name: 'data')
CustomerPointDataDto? get data;
/// Create a copy of CustomerPointDto
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$CustomerPointDtoImplCopyWith<_$CustomerPointDtoImpl> get copyWith =>
throw _privateConstructorUsedError;
}
CustomerPointDataDto _$CustomerPointDataDtoFromJson(Map<String, dynamic> json) {
return _CustomerPointDataDto.fromJson(json);
}
/// @nodoc
mixin _$CustomerPointDataDto {
@JsonKey(name: 'total_points')
int? get totalPoints => throw _privateConstructorUsedError;
@JsonKey(name: 'last_updated')
String? get lastUpdated => throw _privateConstructorUsedError;
/// Serializes this CustomerPointDataDto to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of CustomerPointDataDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$CustomerPointDataDtoCopyWith<CustomerPointDataDto> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $CustomerPointDataDtoCopyWith<$Res> {
factory $CustomerPointDataDtoCopyWith(
CustomerPointDataDto value,
$Res Function(CustomerPointDataDto) then,
) = _$CustomerPointDataDtoCopyWithImpl<$Res, CustomerPointDataDto>;
@useResult
$Res call({
@JsonKey(name: 'total_points') int? totalPoints,
@JsonKey(name: 'last_updated') String? lastUpdated,
});
}
/// @nodoc
class _$CustomerPointDataDtoCopyWithImpl<
$Res,
$Val extends CustomerPointDataDto
>
implements $CustomerPointDataDtoCopyWith<$Res> {
_$CustomerPointDataDtoCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of CustomerPointDataDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? totalPoints = freezed, Object? lastUpdated = freezed}) {
return _then(
_value.copyWith(
totalPoints: freezed == totalPoints
? _value.totalPoints
: totalPoints // ignore: cast_nullable_to_non_nullable
as int?,
lastUpdated: freezed == lastUpdated
? _value.lastUpdated
: lastUpdated // ignore: cast_nullable_to_non_nullable
as String?,
)
as $Val,
);
}
}
/// @nodoc
abstract class _$$CustomerPointDataDtoImplCopyWith<$Res>
implements $CustomerPointDataDtoCopyWith<$Res> {
factory _$$CustomerPointDataDtoImplCopyWith(
_$CustomerPointDataDtoImpl value,
$Res Function(_$CustomerPointDataDtoImpl) then,
) = __$$CustomerPointDataDtoImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({
@JsonKey(name: 'total_points') int? totalPoints,
@JsonKey(name: 'last_updated') String? lastUpdated,
});
}
/// @nodoc
class __$$CustomerPointDataDtoImplCopyWithImpl<$Res>
extends _$CustomerPointDataDtoCopyWithImpl<$Res, _$CustomerPointDataDtoImpl>
implements _$$CustomerPointDataDtoImplCopyWith<$Res> {
__$$CustomerPointDataDtoImplCopyWithImpl(
_$CustomerPointDataDtoImpl _value,
$Res Function(_$CustomerPointDataDtoImpl) _then,
) : super(_value, _then);
/// Create a copy of CustomerPointDataDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? totalPoints = freezed, Object? lastUpdated = freezed}) {
return _then(
_$CustomerPointDataDtoImpl(
totalPoints: freezed == totalPoints
? _value.totalPoints
: totalPoints // ignore: cast_nullable_to_non_nullable
as int?,
lastUpdated: freezed == lastUpdated
? _value.lastUpdated
: lastUpdated // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
/// @nodoc
@JsonSerializable()
class _$CustomerPointDataDtoImpl implements _CustomerPointDataDto {
const _$CustomerPointDataDtoImpl({
@JsonKey(name: 'total_points') this.totalPoints,
@JsonKey(name: 'last_updated') this.lastUpdated,
});
factory _$CustomerPointDataDtoImpl.fromJson(Map<String, dynamic> json) =>
_$$CustomerPointDataDtoImplFromJson(json);
@override
@JsonKey(name: 'total_points')
final int? totalPoints;
@override
@JsonKey(name: 'last_updated')
final String? lastUpdated;
@override
String toString() {
return 'CustomerPointDataDto(totalPoints: $totalPoints, lastUpdated: $lastUpdated)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$CustomerPointDataDtoImpl &&
(identical(other.totalPoints, totalPoints) ||
other.totalPoints == totalPoints) &&
(identical(other.lastUpdated, lastUpdated) ||
other.lastUpdated == lastUpdated));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, totalPoints, lastUpdated);
/// Create a copy of CustomerPointDataDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$CustomerPointDataDtoImplCopyWith<_$CustomerPointDataDtoImpl>
get copyWith =>
__$$CustomerPointDataDtoImplCopyWithImpl<_$CustomerPointDataDtoImpl>(
this,
_$identity,
);
@override
Map<String, dynamic> toJson() {
return _$$CustomerPointDataDtoImplToJson(this);
}
}
abstract class _CustomerPointDataDto implements CustomerPointDataDto {
const factory _CustomerPointDataDto({
@JsonKey(name: 'total_points') final int? totalPoints,
@JsonKey(name: 'last_updated') final String? lastUpdated,
}) = _$CustomerPointDataDtoImpl;
factory _CustomerPointDataDto.fromJson(Map<String, dynamic> json) =
_$CustomerPointDataDtoImpl.fromJson;
@override
@JsonKey(name: 'total_points')
int? get totalPoints;
@override
@JsonKey(name: 'last_updated')
String? get lastUpdated;
/// Create a copy of CustomerPointDataDto
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$CustomerPointDataDtoImplCopyWith<_$CustomerPointDataDtoImpl>
get copyWith => throw _privateConstructorUsedError;
}
@@ -1,39 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'customer_dtos.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$CustomerPointDtoImpl _$$CustomerPointDtoImplFromJson(
Map<String, dynamic> json,
) => _$CustomerPointDtoImpl(
status: json['status'] as String?,
message: json['message'] as String?,
data: json['data'] == null
? null
: CustomerPointDataDto.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$CustomerPointDtoImplToJson(
_$CustomerPointDtoImpl instance,
) => <String, dynamic>{
'status': instance.status,
'message': instance.message,
'data': instance.data,
};
_$CustomerPointDataDtoImpl _$$CustomerPointDataDtoImplFromJson(
Map<String, dynamic> json,
) => _$CustomerPointDataDtoImpl(
totalPoints: (json['total_points'] as num?)?.toInt(),
lastUpdated: json['last_updated'] as String?,
);
Map<String, dynamic> _$$CustomerPointDataDtoImplToJson(
_$CustomerPointDataDtoImpl instance,
) => <String, dynamic>{
'total_points': instance.totalPoints,
'last_updated': instance.lastUpdated,
};
@@ -1,50 +0,0 @@
import 'dart:developer';
import 'package:data_channel/data_channel.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/customer/customer.dart';
import '../customer_dtos.dart';
@injectable
class CustomerRemoteDataProvider {
final ApiClient _apiClient;
final String _logName = "CustomerRemoteDataProvider";
CustomerRemoteDataProvider(this._apiClient);
Future<DC<CustomerFailure, CustomerPointDto>> fetchCustomerPoint() async {
try {
final response = await _apiClient.get(
ApiPath.customerPoint,
headers: getAuthorizationHeader(),
);
if (response.data['code'] == 401) {
return DC.error(
CustomerFailure.serverError(
ApiFailure.unauthorized('Session Expired'),
),
);
}
if (response.data['status'] == false) {
return DC.error(
CustomerFailure.dynamicErrorMessage(
'Terjadi kesalahan coba lagi nanti',
),
);
}
final dto = CustomerPointDto.fromJson(response.data['data']);
return DC.data(dto);
} on ApiFailure catch (e, s) {
log('fetchCustomerPoint', name: _logName, error: e, stackTrace: s);
return DC.error(CustomerFailure.serverError(e));
}
}
}
@@ -1,34 +0,0 @@
part of '../customer_dtos.dart';
@freezed
class CustomerPointDto with _$CustomerPointDto {
const factory CustomerPointDto({
@JsonKey(name: 'status') String? status,
@JsonKey(name: 'message') String? message,
@JsonKey(name: 'data') CustomerPointDataDto? data,
}) = _CustomerPointDto;
factory CustomerPointDto.fromJson(Map<String, dynamic> json) =>
_$CustomerPointDtoFromJson(json);
const CustomerPointDto._();
/// mapping ke domain
CustomerPoint toDomain() => CustomerPoint(
status: status ?? '',
message: message ?? '',
totalPoints: data?.totalPoints ?? 0,
lastUpdated: data?.lastUpdated ?? '',
);
}
@freezed
class CustomerPointDataDto with _$CustomerPointDataDto {
const factory CustomerPointDataDto({
@JsonKey(name: 'total_points') int? totalPoints,
@JsonKey(name: 'last_updated') String? lastUpdated,
}) = _CustomerPointDataDto;
factory CustomerPointDataDto.fromJson(Map<String, dynamic> json) =>
_$CustomerPointDataDtoFromJson(json);
}
@@ -1,33 +0,0 @@
import 'dart:developer';
import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';
import '../../../domain/customer/customer.dart';
import '../datasources/remote_data_provider.dart';
@Injectable(as: ICustomerRepository)
class CustomerRepository implements ICustomerRepository {
final CustomerRemoteDataProvider _remoteDataProvider;
final String _logName = 'CustomerRepository';
CustomerRepository(this._remoteDataProvider);
@override
Future<Either<CustomerFailure, CustomerPoint>> getPoints() async {
try {
final result = await _remoteDataProvider.fetchCustomerPoint();
if (result.hasError) {
return left(result.error!);
}
final data = result.data!.toDomain();
return right(data);
} catch (e, s) {
log('getPoints', name: _logName, error: e, stackTrace: s);
return left(const CustomerFailure.unexpectedError());
}
}
}
@@ -44,4 +44,38 @@ class GameRemoteDataProvider {
return DC.error(GameFailure.serverError(e));
}
}
Future<DC<GameFailure, SpinResultDto>> spin({required String gameId}) async {
try {
final response = await _apiClient.post(
ApiPath.spin,
headers: getAuthorizationHeader(),
data: {'spin_id': gameId},
);
if (response.data is! Map || response.data['success'] != true) {
final errors = response.data is Map ? response.data['errors'] : null;
final code = errors is List && errors.isNotEmpty && errors.first is Map
? errors.first['code']?.toString()
: null;
return DC.error(
GameFailure.dynamicErrorMessage(
code == '304'
? 'EnakCoin kurang, game sedang tidak aktif, atau hadiah baru '
'saja habis. EnakCoin kamu tidak terpotong, silakan coba lagi.'
: 'Terjadi kesalahan, coba lagi',
),
);
}
final dto = SpinResultDto.fromJson(
Map<String, dynamic>.from(response.data['data'] as Map),
);
return DC.data(dto);
} on ApiFailure catch (e, s) {
log('spin', name: _logName, error: e, stackTrace: s);
return DC.error(GameFailure.serverError(e));
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
part of '../game_dtos.dart';
@freezed
class GameDto with _$GameDto {
abstract class GameDto with _$GameDto {
const factory GameDto({
@JsonKey(name: 'id') String? id,
@JsonKey(name: 'name') String? name,
@@ -1,7 +1,7 @@
part of '../game_dtos.dart';
@freezed
class GamePrizeDto with _$GamePrizeDto {
abstract class GamePrizeDto with _$GamePrizeDto {
const factory GamePrizeDto({
@JsonKey(name: 'id') String? id,
@JsonKey(name: 'game_id') String? gameId,
@@ -0,0 +1,47 @@
part of '../game_dtos.dart';
@freezed
abstract class SpinResultDto with _$SpinResultDto {
const factory SpinResultDto({
@JsonKey(name: 'game_play') GamePlayDto? gamePlay,
@JsonKey(name: 'prize_won') PrizeWonDto? prizeWon,
@JsonKey(name: 'coins_remaining') int? coinsRemaining,
}) = _SpinResultDto;
factory SpinResultDto.fromJson(Map<String, dynamic> json) =>
_$SpinResultDtoFromJson(json);
const SpinResultDto._();
SpinResult toDomain() => SpinResult(
gamePlayId: gamePlay?.id ?? '',
coinsUsed: gamePlay?.coinsUsed ?? 0,
prizeId: prizeWon?.id ?? '',
prizeName: prizeWon?.name ?? '',
coinsRemaining: coinsRemaining ?? 0,
);
}
@freezed
abstract class GamePlayDto with _$GamePlayDto {
const factory GamePlayDto({
@JsonKey(name: 'id') String? id,
@JsonKey(name: 'game_id') String? gameId,
@JsonKey(name: 'coins_used') int? coinsUsed,
@JsonKey(name: 'created_at') String? createdAt,
}) = _GamePlayDto;
factory GamePlayDto.fromJson(Map<String, dynamic> json) =>
_$GamePlayDtoFromJson(json);
}
@freezed
abstract class PrizeWonDto with _$PrizeWonDto {
const factory PrizeWonDto({
@JsonKey(name: 'id') String? id,
@JsonKey(name: 'name') String? name,
}) = _PrizeWonDto;
factory PrizeWonDto.fromJson(Map<String, dynamic> json) =>
_$PrizeWonDtoFromJson(json);
}
+1
View File
@@ -7,3 +7,4 @@ part 'game_dtos.g.dart';
part 'dto/game_dto.dart';
part 'dto/game_prize_dto.dart';
part 'dto/spin_result_dto.dart';
File diff suppressed because it is too large Load Diff
+64 -27
View File
@@ -6,34 +6,32 @@ part of 'game_dtos.dart';
// JsonSerializableGenerator
// **************************************************************************
_$GameDtoImpl _$$GameDtoImplFromJson(Map<String, dynamic> json) =>
_$GameDtoImpl(
id: json['id'] as String?,
name: json['name'] as String?,
type: json['type'] as String?,
isActive: json['is_active'] as bool?,
metadata: json['metadata'] as Map<String, dynamic>?,
prizes: (json['prizes'] as List<dynamic>?)
?.map((e) => GamePrizeDto.fromJson(e as Map<String, dynamic>))
.toList(),
createdAt: json['created_at'] as String?,
updatedAt: json['updated_at'] as String?,
);
_GameDto _$GameDtoFromJson(Map<String, dynamic> json) => _GameDto(
id: json['id'] as String?,
name: json['name'] as String?,
type: json['type'] as String?,
isActive: json['is_active'] as bool?,
metadata: json['metadata'] as Map<String, dynamic>?,
prizes: (json['prizes'] as List<dynamic>?)
?.map((e) => GamePrizeDto.fromJson(e as Map<String, dynamic>))
.toList(),
createdAt: json['created_at'] as String?,
updatedAt: json['updated_at'] as String?,
);
Map<String, dynamic> _$$GameDtoImplToJson(_$GameDtoImpl instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'type': instance.type,
'is_active': instance.isActive,
'metadata': instance.metadata,
'prizes': instance.prizes,
'created_at': instance.createdAt,
'updated_at': instance.updatedAt,
};
Map<String, dynamic> _$GameDtoToJson(_GameDto instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'type': instance.type,
'is_active': instance.isActive,
'metadata': instance.metadata,
'prizes': instance.prizes,
'created_at': instance.createdAt,
'updated_at': instance.updatedAt,
};
_$GamePrizeDtoImpl _$$GamePrizeDtoImplFromJson(Map<String, dynamic> json) =>
_$GamePrizeDtoImpl(
_GamePrizeDto _$GamePrizeDtoFromJson(Map<String, dynamic> json) =>
_GamePrizeDto(
id: json['id'] as String?,
gameId: json['game_id'] as String?,
name: json['name'] as String?,
@@ -42,7 +40,7 @@ _$GamePrizeDtoImpl _$$GamePrizeDtoImplFromJson(Map<String, dynamic> json) =>
updatedAt: json['updated_at'] as String?,
);
Map<String, dynamic> _$$GamePrizeDtoImplToJson(_$GamePrizeDtoImpl instance) =>
Map<String, dynamic> _$GamePrizeDtoToJson(_GamePrizeDto instance) =>
<String, dynamic>{
'id': instance.id,
'game_id': instance.gameId,
@@ -51,3 +49,42 @@ Map<String, dynamic> _$$GamePrizeDtoImplToJson(_$GamePrizeDtoImpl instance) =>
'created_at': instance.createdAt,
'updated_at': instance.updatedAt,
};
_SpinResultDto _$SpinResultDtoFromJson(Map<String, dynamic> json) =>
_SpinResultDto(
gamePlay: json['game_play'] == null
? null
: GamePlayDto.fromJson(json['game_play'] as Map<String, dynamic>),
prizeWon: json['prize_won'] == null
? null
: PrizeWonDto.fromJson(json['prize_won'] as Map<String, dynamic>),
coinsRemaining: (json['coins_remaining'] as num?)?.toInt(),
);
Map<String, dynamic> _$SpinResultDtoToJson(_SpinResultDto instance) =>
<String, dynamic>{
'game_play': instance.gamePlay,
'prize_won': instance.prizeWon,
'coins_remaining': instance.coinsRemaining,
};
_GamePlayDto _$GamePlayDtoFromJson(Map<String, dynamic> json) => _GamePlayDto(
id: json['id'] as String?,
gameId: json['game_id'] as String?,
coinsUsed: (json['coins_used'] as num?)?.toInt(),
createdAt: json['created_at'] as String?,
);
Map<String, dynamic> _$GamePlayDtoToJson(_GamePlayDto instance) =>
<String, dynamic>{
'id': instance.id,
'game_id': instance.gameId,
'coins_used': instance.coinsUsed,
'created_at': instance.createdAt,
};
_PrizeWonDto _$PrizeWonDtoFromJson(Map<String, dynamic> json) =>
_PrizeWonDto(id: json['id'] as String?, name: json['name'] as String?);
Map<String, dynamic> _$PrizeWonDtoToJson(_PrizeWonDto instance) =>
<String, dynamic>{'id': instance.id, 'name': instance.name};
@@ -31,4 +31,20 @@ class GameRepository implements IGameRepository {
return left(const GameFailure.unexpectedError());
}
}
@override
Future<Either<GameFailure, SpinResult>> spin({required String gameId}) async {
try {
final result = await _remoteDataProvider.spin(gameId: gameId);
if (result.hasError) {
return left(result.error!);
}
return right(result.data!.toDomain());
} catch (e, s) {
log('spin', name: _logName, error: e, stackTrace: s);
return left(const GameFailure.unexpectedError());
}
}
}
@@ -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());