Commit a6797435 authored by DatHV's avatar DatHV
Browse files

refactor print, log, request

parent f0334970
import 'package:get/get_rx/src/rx_types/rx_types.dart'; import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart'; import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_model.dart'; import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_model.dart';
import '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import '../../base/base_response_model.dart';
class TrafficServiceViewModel extends RestfulApiViewModel { class TrafficServiceViewModel extends RestfulApiViewModel {
var trafficData = Rxn<TrafficServiceResponseModel>(); var trafficData = Rxn<TrafficServiceResponseModel>();
void Function(String message)? onShowAlertError; void Function(String message)? onShowAlertError;
var trafficServiceDetail = Rxn<TrafficServiceDetailModel>(); var trafficServiceDetail = Rxn<TrafficServiceDetailModel>();
RxInt selectedIndex = 0.obs; RxInt selectedIndex = 0.obs;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
List<HeaderFilterOrderModel> get headerFilterOrder { List<HeaderFilterOrderModel> get headerFilterOrder {
return [ return [
...@@ -35,7 +50,7 @@ class TrafficServiceViewModel extends RestfulApiViewModel { ...@@ -35,7 +50,7 @@ class TrafficServiceViewModel extends RestfulApiViewModel {
body['size'] = 10000; body['size'] = 10000;
showLoading(); showLoading();
try { try {
final response = await client.getProductVnTraSold(body); final response = await _callProductApi((api) => api.getProductVnTraSold(body));
hideLoading(); hideLoading();
if (response.isSuccess) { if (response.isSuccess) {
trafficData.value = response.data; trafficData.value = response.data;
...@@ -63,4 +78,4 @@ class TrafficServiceViewModel extends RestfulApiViewModel { ...@@ -63,4 +78,4 @@ class TrafficServiceViewModel extends RestfulApiViewModel {
onShowAlertError?.call("Error fetching product detail: $error"); onShowAlertError?.call("Error fetching product detail: $error");
} }
} }
} }
\ No newline at end of file
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart'; import 'package:mypoint_flutter_app/shared/router_gage.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../../base/base_response_model.dart';
import '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import '../../configs/constants.dart'; import '../../configs/constants.dart';
import '../../preference/contact_storage_service.dart'; import '../../preference/contact_storage_service.dart';
import '../../preference/data_preference.dart'; import '../../preference/data_preference.dart';
import '../voucher/models/product_model.dart'; import '../voucher/models/product_model.dart';
import '../webview/payment_web_view_screen.dart'; import '../webview/payment_web_view_screen.dart';
import '../webview/web_view_screen.dart';
import 'model/payment_bank_account_info_model.dart'; import 'model/payment_bank_account_info_model.dart';
import 'model/payment_method_model.dart'; import 'model/payment_method_model.dart';
import 'model/preview_order_payment_model.dart'; import 'model/preview_order_payment_model.dart';
...@@ -28,6 +27,19 @@ class TransactionDetailViewModel extends RestfulApiViewModel { ...@@ -28,6 +27,19 @@ class TransactionDetailViewModel extends RestfulApiViewModel {
final RxBool usePoints = true.obs; final RxBool usePoints = true.obs;
var selectedPaymentMethodIndex = -1.obs; var selectedPaymentMethodIndex = -1.obs;
void Function(String message)? onShowAlertError; void Function(String message)? onShowAlertError;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
int get finalTotal { int get finalTotal {
final totalPrice = previewData.value?.totalPrice ?? 0; final totalPrice = previewData.value?.totalPrice ?? 0;
...@@ -45,7 +57,7 @@ class TransactionDetailViewModel extends RestfulApiViewModel { ...@@ -45,7 +57,7 @@ class TransactionDetailViewModel extends RestfulApiViewModel {
isLoading.value = false; isLoading.value = false;
} }
void requestPaymentProduct() { Future<void> requestPaymentProduct() async {
showLoading(); showLoading();
final requestId = Uuid().v4(); final requestId = Uuid().v4();
int? point = usePoints.value ? previewData.value?.pointData?.point : 0; int? point = usePoints.value ? previewData.value?.pointData?.point : 0;
...@@ -58,10 +70,11 @@ class TransactionDetailViewModel extends RestfulApiViewModel { ...@@ -58,10 +70,11 @@ class TransactionDetailViewModel extends RestfulApiViewModel {
selectedBankAccount = paymentBankAccounts.value[selectedPaymentMethodIndex - definedCodeIndexBankAccount]; selectedBankAccount = paymentBankAccounts.value[selectedPaymentMethodIndex - definedCodeIndexBankAccount];
} else if (selectedPaymentMethodIndex >= 0) { } else if (selectedPaymentMethodIndex >= 0) {
selectedPaymentMethod = paymentMethods.value[selectedPaymentMethodIndex]; selectedPaymentMethod = paymentMethods.value[selectedPaymentMethodIndex];
saveToken = selectedPaymentMethod?.saveToken == true && selectedPaymentMethod?.needSaveTokenWhenOrder == true; saveToken = selectedPaymentMethod.saveToken == true && selectedPaymentMethod.needSaveTokenWhenOrder == true;
} }
client try {
.orderSubmitPayment( final response = await _callProductApi(
(api) => api.orderSubmitPayment(
products: [product], products: [product],
quantity: quantity, quantity: quantity,
requestId: requestId, requestId: requestId,
...@@ -72,41 +85,44 @@ class TransactionDetailViewModel extends RestfulApiViewModel { ...@@ -72,41 +85,44 @@ class TransactionDetailViewModel extends RestfulApiViewModel {
saveToken: saveToken, saveToken: saveToken,
metadata: metaData, metadata: metaData,
targetPhoneNumber: targetPhoneNumber, targetPhoneNumber: targetPhoneNumber,
) ),
.then((value) { );
hideLoading(); if (response.isSuccess) {
if (value.isSuccess) { final data = response.data;
final data = value.data; if ((data?.paymentUrl ?? "").isNotEmpty) {
if ((data?.paymentUrl ?? "").isNotEmpty) { if ((targetPhoneNumber ?? "").isNotEmpty) {
if ((targetPhoneNumber ?? "").isNotEmpty) { ContactStorageService().saveUsedContact(targetPhoneNumber ?? "");
ContactStorageService().saveUsedContact(targetPhoneNumber ?? "");
}
Get.toNamed(
paymentWebViewScreen,
arguments: PaymentWebViewInput(
url: data?.paymentUrl ?? "",
isContract: false,
orderId: data?.id ?? "",
showAlertBack: true,
callback: (result) {
if (result == PaymentProcess.success) {
Get.offNamed(
transactionHistoryDetailScreen,
arguments: {"orderId": data?.id ?? "", "canBack": true},
);
}
},
)
);
} else if ((data?.redeemId ?? "").isNotEmpty && (data?.id ?? "").isNotEmpty) {
Get.offNamed(transactionHistoryDetailScreen, arguments: {"orderId": data?.id ?? "", "canBack": true});
} else {
onShowAlertError?.call(value.errorMessage ?? Constants.commonError);
}
} else {
onShowAlertError?.call(value.errorMessage ?? Constants.commonError);
} }
}); Get.toNamed(
paymentWebViewScreen,
arguments: PaymentWebViewInput(
url: data?.paymentUrl ?? "",
isContract: false,
orderId: data?.id ?? "",
showAlertBack: true,
callback: (result) {
if (result == PaymentProcess.success) {
Get.offNamed(
transactionHistoryDetailScreen,
arguments: {"orderId": data?.id ?? "", "canBack": true},
);
}
},
),
);
} else if ((data?.redeemId ?? "").isNotEmpty && (data?.id ?? "").isNotEmpty) {
Get.offNamed(transactionHistoryDetailScreen, arguments: {"orderId": data?.id ?? "", "canBack": true});
} else {
onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
}
} else {
onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
}
} catch (error) {
onShowAlertError?.call(Constants.commonError);
} finally {
hideLoading();
}
} }
Future<void> _getPreviewOrderPayment() async { Future<void> _getPreviewOrderPayment() async {
...@@ -125,28 +141,28 @@ class TransactionDetailViewModel extends RestfulApiViewModel { ...@@ -125,28 +141,28 @@ class TransactionDetailViewModel extends RestfulApiViewModel {
if ((metaData ?? '').isNotEmpty) { if ((metaData ?? '').isNotEmpty) {
body["metadata"] = metaData; body["metadata"] = metaData;
} }
final response = await client.getPreviewOrderInfo(body); final response = await _callProductApi((api) => api.getPreviewOrderInfo(body));
previewData.value = response.data; previewData.value = response.data;
} catch (error) { } catch (error) {
print("Error fetching preview order payment: $error"); debugPrint("Error fetching preview order payment: $error");
} }
} }
Future<void> _getPaymentMethods() async { Future<void> _getPaymentMethods() async {
try { try {
final response = await client.getPreviewPaymentMethods(); final response = await _callProductApi((api) => api.getPreviewPaymentMethods());
paymentMethods.value = response.data ?? []; paymentMethods.value = response.data ?? [];
} catch (error) { } catch (error) {
print("Error fetching payment methods: $error"); debugPrint("Error fetching payment methods: $error");
} }
} }
Future<void> _getPaymentBankAccounts() async { Future<void> _getPaymentBankAccounts() async {
try { try {
final response = await client.getPreviewOrderBankAccounts(); final response = await _callProductApi((api) => api.getPreviewOrderBankAccounts());
paymentBankAccounts.value = response.data ?? []; paymentBankAccounts.value = response.data ?? [];
} catch (error) { } catch (error) {
print("Error fetching payment bank accounts: $error"); debugPrint("Error fetching payment bank accounts: $error");
} }
} }
} }
import 'dart:math'; import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart'; import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart'; import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/screen/voucher/detail/store_list_section.dart'; import 'package:mypoint_flutter_app/screen/voucher/detail/store_list_section.dart';
...@@ -355,7 +356,7 @@ class _VoucherDetailScreenState extends BaseState<VoucherDetailScreen> with Basi ...@@ -355,7 +356,7 @@ class _VoucherDetailScreenState extends BaseState<VoucherDetailScreen> with Basi
Future<void> _launchUri(Uri uri) async { Future<void> _launchUri(Uri uri) async {
if (await canLaunchUrl(uri)) { if (await canLaunchUrl(uri)) {
print('Launching $uri'); debugPrint('Launching $uri');
await launchUrl(uri); await launchUrl(uri);
} else { } else {
throw 'Could not launch $uri'; throw 'Could not launch $uri';
...@@ -536,8 +537,8 @@ class _VoucherDetailScreenState extends BaseState<VoucherDetailScreen> with Basi ...@@ -536,8 +537,8 @@ class _VoucherDetailScreenState extends BaseState<VoucherDetailScreen> with Basi
Future<void> _handleRedeemProduct() async { Future<void> _handleRedeemProduct() async {
final point = await UserPointManager().fetchUserPoint(withLoading: true) ?? 0; final point = await UserPointManager().fetchUserPoint(withLoading: true) ?? 0;
final amountToBePaid = _viewModel.product.value?.amountToBePaid ?? 0; final amountToBePaid = _viewModel.product.value?.amountToBePaid ?? 0;
print('amountToBePaid: $amountToBePaid'); debugPrint('amountToBePaid: $amountToBePaid');
print('UserPointManager().point: $point'); debugPrint('UserPointManager().point: $point');
if (point < amountToBePaid) { if (point < amountToBePaid) {
showAlertError(content: "Bạn không đủ điểm để đổi ưu đãi này"); showAlertError(content: "Bạn không đủ điểm để đổi ưu đãi này");
return; return;
......
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../../../base/base_response_model.dart';
import '../../../networking/restful_api_viewmodel.dart'; import '../../../networking/restful_api_viewmodel.dart';
import '../../../configs/constants.dart'; import '../../../configs/constants.dart';
import '../../../shared/router_gage.dart'; import '../../../shared/router_gage.dart';
...@@ -23,6 +25,19 @@ class VoucherDetailViewModel extends RestfulApiViewModel { ...@@ -23,6 +25,19 @@ class VoucherDetailViewModel extends RestfulApiViewModel {
var quantity = 1.obs; var quantity = 1.obs;
bool get isMyProduct => customerProductId != null; bool get isMyProduct => customerProductId != null;
int? get _id => productId ?? product.value?.id; int? get _id => productId ?? product.value?.id;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
@override @override
void onInit() { void onInit() {
...@@ -37,11 +52,11 @@ class VoucherDetailViewModel extends RestfulApiViewModel { ...@@ -37,11 +52,11 @@ class VoucherDetailViewModel extends RestfulApiViewModel {
if (value == null) return; if (value == null) return;
try { try {
if (value!.liked == true) { if (value!.liked == true) {
await client.unlikeProduct(value?.likeId ?? 0); await _callProductApi((api) => api.unlikeProduct(value?.likeId ?? 0));
value?.likeId = 0; value?.likeId = 0;
liked.value = false; liked.value = false;
} else { } else {
final response = await client.likeProduct(_id!); final response = await _callProductApi((api) => api.likeProduct(_id!));
value?.likeId = response.data?.id; value?.likeId = response.data?.id;
liked.value = (response.data?.id ?? 0) != 0; liked.value = (response.data?.id ?? 0) != 0;
} }
...@@ -54,7 +69,10 @@ class VoucherDetailViewModel extends RestfulApiViewModel { ...@@ -54,7 +69,10 @@ class VoucherDetailViewModel extends RestfulApiViewModel {
if (isLoading.value) return; if (isLoading.value) return;
try { try {
isLoading.value = true; isLoading.value = true;
final response = isMyProduct ? await client.getCustomerProductDetail(customerProductId ?? 0) : await client.getProduct(productId ?? 0); final response =
isMyProduct
? await _callProductApi((api) => api.getCustomerProductDetail(customerProductId ?? 0))
: await _callProductApi((api) => api.getProduct(productId ?? 0));
product.value = response.data; product.value = response.data;
liked.value = product.value?.liked == true; liked.value = product.value?.liked == true;
} catch (error) { } catch (error) {
...@@ -70,12 +88,12 @@ class VoucherDetailViewModel extends RestfulApiViewModel { ...@@ -70,12 +88,12 @@ class VoucherDetailViewModel extends RestfulApiViewModel {
Future<void> _getProductStores() async { Future<void> _getProductStores() async {
if (_id == null) return; if (_id == null) return;
try { try {
final response = await client.getProductStores(_id!); final response = await _callProductApi((api) => api.getProductStores(_id!));
stores.value = response.data ?? []; stores.value = response.data ?? [];
stores.refresh(); stores.refresh();
} catch (error) { } catch (error) {
onShowAlertError?.call("Error product stores: $error"); onShowAlertError?.call("Error product stores: $error");
print("Error product stores: $error"); debugPrint("Error product stores: $error");
} finally {} } finally {}
} }
...@@ -89,36 +107,44 @@ class VoucherDetailViewModel extends RestfulApiViewModel { ...@@ -89,36 +107,44 @@ class VoucherDetailViewModel extends RestfulApiViewModel {
} }
} }
showLoading(); showLoading();
client.verifyOrderProduct(body).then((value) { try {
hideLoading(); final response = await _callProductApi((api) => api.verifyOrderProduct(body));
if (!value.isSuccess) { if (!response.isSuccess) {
onShowAlertError?.call(value.errorMessage ?? Constants.commonError); onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
} else { } else {
verified.call(); verified.call();
} }
}); } catch (error) {
onShowAlertError?.call(Constants.commonError);
} finally {
hideLoading();
}
} }
void redeemProduct() { Future<void> redeemProduct() async {
showLoading(); showLoading();
final requestId = Uuid().v4(); final requestId = Uuid().v4();
client try {
.orderSubmitPayment( final response = await _callProductApi(
(api) => api.orderSubmitPayment(
products: [product.value!], products: [product.value!],
quantity: 1, quantity: 1,
requestId: requestId, requestId: requestId,
point: product.value?.amountToBePaid ?? 0, point: product.value?.amountToBePaid ?? 0,
) ),
.then((value) { );
hideLoading(); if (response.isSuccess && (response.data?.id ?? "").isNotEmpty) {
if (value.isSuccess && (value.data?.id ?? "").isNotEmpty) { Get.offNamed(
Get.offNamed( transactionHistoryDetailScreen,
transactionHistoryDetailScreen, arguments: {"orderId": response.data?.id ?? "", "canBack": false},
arguments: {"orderId": value.data?.id ?? "", "canBack": false}, );
); } else {
} else { onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
onShowAlertError?.call(value.errorMessage ?? Constants.commonError); }
} } catch (error) {
}); onShowAlertError?.call(Constants.commonError);
} finally {
hideLoading();
}
} }
} }
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
...@@ -11,7 +12,7 @@ class RechargeSheet extends StatelessWidget { ...@@ -11,7 +12,7 @@ class RechargeSheet extends StatelessWidget {
Future<void> _dialUssd(String ussd) async { Future<void> _dialUssd(String ussd) async {
final uri = Uri(scheme: 'tel', path: ussd.replaceAll('#', Uri.encodeComponent('#'))); final uri = Uri(scheme: 'tel', path: ussd.replaceAll('#', Uri.encodeComponent('#')));
print('Dialing USSD: $uri'); debugPrint('Dialing USSD: $uri');
if (await canLaunchUrl(uri)) { if (await canLaunchUrl(uri)) {
await launchUrl(uri); await launchUrl(uri);
} }
......
...@@ -3,10 +3,11 @@ import 'package:get/get.dart'; ...@@ -3,10 +3,11 @@ import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart'; import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart'; import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import '../../../configs/constants.dart'; import '../../../configs/constants.dart';
import '../../../networking/restful_api_viewmodel.dart'; import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_model.dart'; import '../../mobile_card/models/usable_voucher_model.dart';
import '../../../base/base_response_model.dart';
class MyMobileCardDetailViewModel extends RestfulApiViewModel { class MyMobileCardDetailViewModel extends RestfulApiViewModel {
String itemId; String itemId;
...@@ -19,19 +20,36 @@ class MyMobileCardDetailViewModel extends RestfulApiViewModel { ...@@ -19,19 +20,36 @@ class MyMobileCardDetailViewModel extends RestfulApiViewModel {
String get code => dataCard.value?.codeSecret ?? ''; String get code => dataCard.value?.codeSecret ?? '';
String get serial => dataCard.value?.serial ?? ''; String get serial => dataCard.value?.serial ?? '';
String get valueText => (int.tryParse(dataCard.value?.prices?.firstOrNull?.originalPrice ?? '') ?? 0).money(CurrencyUnit.vnd); String get valueText => (int.tryParse(dataCard.value?.prices?.firstOrNull?.originalPrice ?? '') ?? 0).money(CurrencyUnit.vnd);
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
Future<void> getMobileCardDetail() async { Future<void> getMobileCardDetail() async {
showLoading(); showLoading();
final response = await client.getMobileCardCode(itemId); try {
final data = response.data?.item; final response = await _callProductApi((api) => api.getMobileCardCode(itemId));
if (response.isSuccess && data != null) { final data = response.data?.item;
if (response.isSuccess && data != null) {
dataCard.value = data;
isUsed.value = makeUsedCardDetail();
return;
}
onShowAlertError?.call(response.message ?? Constants.commonError);
} catch (error) {
onShowAlertError?.call(Constants.commonError);
} finally {
hideLoading(); hideLoading();
dataCard.value = data;
isUsed.value = makeUsedCardDetail();
return;
} }
hideLoading();
onShowAlertError?.call(response.message ?? Constants.commonError);
} }
bool makeUsedCardDetail() { bool makeUsedCardDetail() {
...@@ -45,14 +63,17 @@ class MyMobileCardDetailViewModel extends RestfulApiViewModel { ...@@ -45,14 +63,17 @@ class MyMobileCardDetailViewModel extends RestfulApiViewModel {
final newState = !isUsed.value; final newState = !isUsed.value;
showLoading(); showLoading();
try { try {
final response = newState ? await client.myProductMarkAsUsed(itemId) : await client.myProductMarkAsNotUsedYet(itemId); final response =
newState
? await _callProductApi((api) => api.myProductMarkAsUsed(itemId))
: await _callProductApi((api) => api.myProductMarkAsNotUsedYet(itemId));
if (response.isSuccess) { if (response.isSuccess) {
isUsed.value = newState; isUsed.value = newState;
} }
} catch (_) { } catch (_) {
onShowAlertError?.call(Constants.commonError);
} finally { } finally {
hideLoading(); hideLoading();
} }
} }
} }
\ No newline at end of file
import 'package:get/get_rx/src/rx_types/rx_types.dart'; import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart'; import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import '../../../networking/restful_api_viewmodel.dart'; import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_model.dart'; import '../../mobile_card/models/usable_voucher_model.dart';
import '../models/my_product_status_type.dart'; import '../models/my_product_status_type.dart';
import '../../../base/base_response_model.dart';
class MyMobileCardListViewModel extends RestfulApiViewModel { class MyMobileCardListViewModel extends RestfulApiViewModel {
final RxInt selectedTabIndex = 0.obs; final RxInt selectedTabIndex = 0.obs;
var myCardModels = <UsableVoucherModel>[].obs; var myCardModels = <UsableVoucherModel>[].obs;
void Function(String message)? onShowAlertError; void Function(String message)? onShowAlertError;
void Function(UsableVoucherModel data)? onRedeemProductMobileSuccess; void Function(UsableVoucherModel data)? onRedeemProductMobileSuccess;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
@override @override
void onInit() { void onInit() {
...@@ -31,28 +45,42 @@ class MyMobileCardListViewModel extends RestfulApiViewModel { ...@@ -31,28 +45,42 @@ class MyMobileCardListViewModel extends RestfulApiViewModel {
"size": '20', "size": '20',
}; };
final status = selectedTabIndex.value == 0 ? MyProductStatusType.waiting : MyProductStatusType.used; final status = selectedTabIndex.value == 0 ? MyProductStatusType.waiting : MyProductStatusType.used;
final response = await client.getMyMobileCards(status, body); try {
if (!response.isSuccess) { final response = await _callProductApi((api) => api.getMyMobileCards(status, body));
onShowAlertError?.call(response.errorMessage ?? Constants.commonError); if (!response.isSuccess) {
} onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
final result = response.data?.listItems ?? []; }
if (isRefresh) { final result = response.data?.listItems ?? [];
hideLoading(); if (isRefresh) {
myCardModels.clear(); myCardModels.clear();
}
myCardModels.addAll(result);
} catch (error) {
if (isRefresh) {
myCardModels.clear();
}
onShowAlertError?.call(Constants.commonError);
} finally {
if (isRefresh) {
hideLoading();
}
} }
myCardModels.addAll(result);
} }
Future<void> getMobileCardDetail(String itemId) async { Future<void> getMobileCardDetail(String itemId) async {
showLoading(); showLoading();
final response = await client.getMobileCardCode(itemId); try {
final data = response.data?.item; final response = await _callProductApi((api) => api.getMobileCardCode(itemId));
if (response.isSuccess && data != null) { final data = response.data?.item;
if (response.isSuccess && data != null) {
onRedeemProductMobileSuccess?.call(data);
return;
}
onShowAlertError?.call(response.message ?? Constants.commonError);
} catch (error) {
onShowAlertError?.call(Constants.commonError);
} finally {
hideLoading(); hideLoading();
onRedeemProductMobileSuccess?.call(data);
return;
} }
hideLoading();
onShowAlertError?.call(response.message ?? Constants.commonError);
} }
} }
\ No newline at end of file
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
import 'package:mypoint_flutter_app/extensions/date_format.dart'; import 'package:mypoint_flutter_app/extensions/date_format.dart';
import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart'; import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart';
...@@ -139,7 +140,7 @@ class ProductModel { ...@@ -139,7 +140,7 @@ class ProductModel {
extend += space; extend += space;
extend += 18; extend += 18;
} }
print("extendSpaceFlashSaleItem $extend"); debugPrint("extendSpaceFlashSaleItem $extend");
return extend; return extend;
} }
......
import 'package:flutter/cupertino.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart'; import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../../networking/restful_api_viewmodel.dart'; import '../../../networking/restful_api_viewmodel.dart';
import '../../home/models/my_product_model.dart'; import '../../home/models/my_product_model.dart';
import '../../../base/base_response_model.dart';
class MyProductListViewModel extends RestfulApiViewModel { class MyProductListViewModel extends RestfulApiViewModel {
final RxInt selectedTabIndex = 0.obs; final RxInt selectedTabIndex = 0.obs;
var myProducts = <MyProductModel>[].obs; var myProducts = <MyProductModel>[].obs;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
@override @override
void onInit() { void onInit() {
...@@ -19,7 +33,7 @@ class MyProductListViewModel extends RestfulApiViewModel { ...@@ -19,7 +33,7 @@ class MyProductListViewModel extends RestfulApiViewModel {
freshData(isRefresh: true); freshData(isRefresh: true);
} }
void freshData({bool isRefresh = false}) { Future<void> freshData({bool isRefresh = false}) async {
final body = { final body = {
"index": isRefresh ? 0 : myProducts.length, "index": isRefresh ? 0 : myProducts.length,
"size": 20, "size": 20,
...@@ -29,20 +43,23 @@ class MyProductListViewModel extends RestfulApiViewModel { ...@@ -29,20 +43,23 @@ class MyProductListViewModel extends RestfulApiViewModel {
if (isRefresh) { if (isRefresh) {
showLoading(); showLoading();
} }
try {
client.getCustomerProducts(body).then((response) { final response = await _callProductApi((api) => api.getCustomerProducts(body));
final result = response.data ?? []; final result = response.data ?? [];
if (isRefresh) { if (isRefresh) {
hideLoading(); myProducts.assignAll(result);
myProducts.clear(); } else {
myProducts.addAll(result);
} }
myProducts.addAll(result); } catch (error) {
}).catchError((error) {
hideLoading();
if (isRefresh) { if (isRefresh) {
myProducts.clear(); myProducts.clear();
} }
print('Error fetching products: $error'); debugPrint('Error fetching products: $error');
}); } finally {
if (isRefresh) {
hideLoading();
}
}
} }
} }
\ No newline at end of file
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../../base/base_response_model.dart'; import '../../../base/base_response_model.dart';
import '../../../networking/restful_api_viewmodel.dart'; import '../../../networking/restful_api_viewmodel.dart';
...@@ -24,6 +26,19 @@ class VoucherListViewModel extends RestfulApiViewModel { ...@@ -24,6 +26,19 @@ class VoucherListViewModel extends RestfulApiViewModel {
/// Đánh dấu đã hoàn tất lần tải đầu tiên (có dữ liệu) để UI có thể bắt đầu countdown /// Đánh dấu đã hoàn tất lần tải đầu tiên (có dữ liệu) để UI có thể bắt đầu countdown
final firstLoadDone = false.obs; final firstLoadDone = false.obs;
void Function(BaseResponseModel<SubmitViewVoucherCompletedResponse> response)? submitCampaignViewVoucherResponse; void Function(BaseResponseModel<SubmitViewVoucherCompletedResponse> response)? submitCampaignViewVoucherResponse;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
@override @override
void onInit() { void onInit() {
...@@ -71,14 +86,14 @@ class VoucherListViewModel extends RestfulApiViewModel { ...@@ -71,14 +86,14 @@ class VoucherListViewModel extends RestfulApiViewModel {
try { try {
isLoading.value = true; isLoading.value = true;
isLoadMore.value = true; isLoadMore.value = true;
final result = await client.productsCustomerLikes(body); final result = await _callProductApi((api) => api.productsCustomerLikes(body));
final fetchedData = result.data ?? []; final fetchedData = result.data ?? [];
if (fetchedData.isEmpty || fetchedData.length < _pageSize) { if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
_hasMore = false; _hasMore = false;
} }
products.addAll(fetchedData); products.addAll(fetchedData);
} catch (error) { } catch (error) {
print("Error fetching products: $error"); debugPrint("Error fetching products: $error");
} finally { } finally {
hideLoading(); hideLoading();
isLoading.value = false; isLoading.value = false;
...@@ -113,7 +128,7 @@ class VoucherListViewModel extends RestfulApiViewModel { ...@@ -113,7 +128,7 @@ class VoucherListViewModel extends RestfulApiViewModel {
try { try {
isLoading.value = true; isLoading.value = true;
isLoadMore.value = true; isLoadMore.value = true;
final result = await client.getSearchProducts(body); final result = await _callProductApi((api) => api.getSearchProducts(body));
final fetchedData = result.data?.products ?? []; final fetchedData = result.data?.products ?? [];
totalResult.value = result.data?.total ?? 0; totalResult.value = result.data?.total ?? 0;
if (fetchedData.isEmpty || fetchedData.length < _pageSize) { if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
...@@ -121,7 +136,7 @@ class VoucherListViewModel extends RestfulApiViewModel { ...@@ -121,7 +136,7 @@ class VoucherListViewModel extends RestfulApiViewModel {
} }
products.addAll(fetchedData); products.addAll(fetchedData);
} catch (error) { } catch (error) {
print("Error fetching products: $error"); debugPrint("Error fetching products: $error");
} finally { } finally {
hideLoading(); hideLoading();
isLoading.value = false; isLoading.value = false;
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/screen/voucher/models/product_type.dart'; import 'package:mypoint_flutter_app/screen/voucher/models/product_type.dart';
import '../../base/base_response_model.dart';
import '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import 'models/product_model.dart'; import 'models/product_model.dart';
...@@ -9,6 +10,19 @@ class VoucherTabViewModel extends RestfulApiViewModel { ...@@ -9,6 +10,19 @@ class VoucherTabViewModel extends RestfulApiViewModel {
final RxList<ProductModel> hotProducts = <ProductModel>[].obs; final RxList<ProductModel> hotProducts = <ProductModel>[].obs;
final RxList<ProductModel> allProducts = <ProductModel>[].obs; final RxList<ProductModel> allProducts = <ProductModel>[].obs;
final RxBool isLoadMore = false.obs; final RxBool isLoadMore = false.obs;
bool _productApiLoaded = false;
Future<void> _ensureProductApiLoaded() async {
if (_productApiLoaded) return;
await product_api.loadLibrary();
_productApiLoaded = true;
}
Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureProductApiLoaded();
final api = product_api.ProductApi(client);
return fn(api);
}
bool get _isDataAvailable { bool get _isDataAvailable {
return hotProducts.isNotEmpty || allProducts.isNotEmpty; return hotProducts.isNotEmpty || allProducts.isNotEmpty;
...@@ -37,10 +51,10 @@ class VoucherTabViewModel extends RestfulApiViewModel { ...@@ -37,10 +51,10 @@ class VoucherTabViewModel extends RestfulApiViewModel {
"catalog_code": "HOT", "catalog_code": "HOT",
}; };
try { try {
final result = await client.getProducts(body); final result = await _callProductApi((api) => api.getProducts(body));
hotProducts.value = result.data ?? []; hotProducts.value = result.data ?? [];
} catch (error) { } catch (error) {
print("Error fetching hot products: $error"); debugPrint("Error fetching hot products: $error");
} }
} }
...@@ -62,7 +76,7 @@ class VoucherTabViewModel extends RestfulApiViewModel { ...@@ -62,7 +76,7 @@ class VoucherTabViewModel extends RestfulApiViewModel {
try { try {
isLoadMore.value = true; isLoadMore.value = true;
final result = await client.getProducts(body); final result = await _callProductApi((api) => api.getProducts(body));
final fetchedData = result.data ?? []; final fetchedData = result.data ?? [];
if (fetchedData.isEmpty || fetchedData.length < _pageSize) { if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
_hasMore = false; _hasMore = false;
...@@ -73,9 +87,9 @@ class VoucherTabViewModel extends RestfulApiViewModel { ...@@ -73,9 +87,9 @@ class VoucherTabViewModel extends RestfulApiViewModel {
allProducts.addAll(fetchedData); allProducts.addAll(fetchedData);
} }
} catch (error) { } catch (error) {
print("Error fetching all products: $error"); debugPrint("Error fetching all products: $error");
} finally { } finally {
isLoadMore.value = false; isLoadMore.value = false;
} }
} }
} }
\ No newline at end of file
...@@ -132,9 +132,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba ...@@ -132,9 +132,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba
'MyPoint', 'MyPoint',
onMessageReceived: (JavaScriptMessage message) { onMessageReceived: (JavaScriptMessage message) {
final data = message.message; final data = message.message;
if (kDebugMode) { debugPrint('📩 JS Message: $data');
debugPrint('📩 JS Message: $data');
}
if (data.contains('payment_result')) { if (data.contains('payment_result')) {
if (data.contains('success')) { if (data.contains('success')) {
_onPaymentResult(PaymentProcess.success); _onPaymentResult(PaymentProcess.success);
...@@ -243,9 +241,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba ...@@ -243,9 +241,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba
NavigationDecision _handleNavigation(NavigationRequest request) { NavigationDecision _handleNavigation(NavigationRequest request) {
final url = request.url; final url = request.url;
if (kDebugMode) { debugPrint("➡️ Navigating: $url");
debugPrint("➡️ Navigating: $url");
}
if (paymentSuccessUrls.any((success) => url.startsWith(success))) { if (paymentSuccessUrls.any((success) => url.startsWith(success))) {
_onPaymentResult(PaymentProcess.success); _onPaymentResult(PaymentProcess.success);
return NavigationDecision.prevent; return NavigationDecision.prevent;
...@@ -261,9 +257,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba ...@@ -261,9 +257,7 @@ class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with Ba
launchUrl(uri, mode: LaunchMode.externalApplication); launchUrl(uri, mode: LaunchMode.externalApplication);
return NavigationDecision.prevent; return NavigationDecision.prevent;
} }
if (kDebugMode) { debugPrint("🔗 Handling URL scheme: ${uri?.scheme}");
debugPrint("🔗 Handling URL scheme: ${uri?.scheme}");
}
// Xử lý chung mypointapp:// và các scheme ngoài http/https // Xử lý chung mypointapp:// và các scheme ngoài http/https
if (uri != null) { if (uri != null) {
// mypointapp://open?click_action_type=PAYMENT_SUCCESS|PAYMENT_FAIL // mypointapp://open?click_action_type=PAYMENT_SUCCESS|PAYMENT_FAIL
......
...@@ -102,9 +102,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -102,9 +102,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
onWebResourceError: (error) { onWebResourceError: (error) {
AppLoading().hide(); AppLoading().hide();
if (error.description != 'about:blank') { if (error.description != 'about:blank') {
if (kDebugMode) { debugPrint('WebView error: ${error.description}');
print('WebView error: ${error.description}');
}
// Có thể hiển thị lỗi nếu cần // Có thể hiển thị lỗi nếu cần
showAlertError(content: error.description); showAlertError(content: error.description);
} }
...@@ -123,9 +121,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -123,9 +121,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
} }
return inputUrl; return inputUrl;
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to format URL: $inputUrl - $e');
print('Failed to format URL: $inputUrl - $e');
}
return inputUrl; return inputUrl;
} }
} }
...@@ -196,14 +192,10 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -196,14 +192,10 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
if (await canLaunchUrl(uri)) { if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication); await launchUrl(uri, mode: LaunchMode.externalApplication);
} else { } else {
if (kDebugMode) { debugPrint('Could not launch URL: ${input.url}');
print('Could not launch URL: ${input.url}');
}
} }
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Error launching URL: $e');
print('Error launching URL: $e');
}
} }
} }
...@@ -226,26 +218,20 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -226,26 +218,20 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
launchUrl(uri); launchUrl(uri);
return NavigationDecision.prevent; return NavigationDecision.prevent;
} }
if (kDebugMode) { debugPrint('🔗 Handling navigation to URL: $url');
print('🔗 Handling navigation to URL: $url');
}
if (_isReissuingNavigation) { if (_isReissuingNavigation) {
_isReissuingNavigation = false; _isReissuingNavigation = false;
return NavigationDecision.navigate; return NavigationDecision.navigate;
} }
if (_shouldAttachHeaders(url)) { if (_shouldAttachHeaders(url)) {
if (kDebugMode) { debugPrint('🔄 Reissuing navigation with headers to URL: $url');
print('🔄 Reissuing navigation with headers to URL: $url');
}
try { try {
final target = Uri.parse(url); final target = Uri.parse(url);
_loadWithHeaders(target); _loadWithHeaders(target);
return NavigationDecision.prevent; return NavigationDecision.prevent;
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to reissue navigation with headers: $e');
print('Failed to reissue navigation with headers: $e');
}
} }
} }
final uri = Uri.tryParse(url); final uri = Uri.tryParse(url);
...@@ -270,9 +256,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -270,9 +256,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
return NavigationDecision.prevent; return NavigationDecision.prevent;
} }
} }
if (kDebugMode) { debugPrint('✅ Allowing navigation to URL: $url');
print('✅ Allowing navigation to URL: $url');
}
return NavigationDecision.navigate; return NavigationDecision.navigate;
} }
...@@ -300,11 +284,9 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -300,11 +284,9 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
try { try {
await _loadWithHeaders(uri); await _loadWithHeaders(uri);
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint(
print( 'WebView load with headers failed: $e. Retrying without headers.',
'WebView load with headers failed: $e. Retrying without headers.', );
);
}
await _webViewController?.loadRequest(uri); await _webViewController?.loadRequest(uri);
} }
} }
...@@ -347,11 +329,9 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -347,11 +329,9 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
return; return;
} }
_isReissuingNavigation = true; _isReissuingNavigation = true;
if (kDebugMode) { debugPrint(
print( '➡️ Loading with headers: ${uri.toString()}, headers: $_authHeaders',
'➡️ Loading with headers: ${uri.toString()}, headers: $_authHeaders', );
);
}
await _webViewController?.loadRequest(uri, headers: _authHeaders!); await _webViewController?.loadRequest(uri, headers: _authHeaders!);
} }
...@@ -396,9 +376,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -396,9 +376,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
success ? 'Ảnh đã được lưu vào thư viện.' : 'Không thể lưu ảnh.', success ? 'Ảnh đã được lưu vào thư viện.' : 'Không thể lưu ảnh.',
); );
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to save base64 image: $e');
print('Failed to save base64 image: $e');
}
_showSnack('Không thể lưu ảnh.'); _showSnack('Không thể lưu ảnh.');
} }
} }
...@@ -425,7 +403,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> ...@@ -425,7 +403,7 @@ class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen>
if (status.isGranted || status.isLimited) return true; if (status.isGranted || status.isLimited) return true;
} }
if (status.isPermanentlyDenied && kDebugMode) { if (status.isPermanentlyDenied && kDebugMode) {
print('Media permission permanently denied.'); debugPrint('Media permission permanently denied.');
} }
return false; return false;
} }
......
import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/base/base_response_model.dart'; import 'package:mypoint_flutter_app/base/base_response_model.dart';
import 'package:mypoint_flutter_app/configs/constants.dart'; import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart'; import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
...@@ -44,7 +45,7 @@ class LoginService extends RestfulApiViewModel { ...@@ -44,7 +45,7 @@ class LoginService extends RestfulApiViewModel {
final authResponse = await client.login(phone, password); final authResponse = await client.login(phone, password);
if (!authResponse.isSuccess || authResponse.data == null) { if (!authResponse.isSuccess || authResponse.data == null) {
print('Login failed: ${authResponse.errorMessage}'); debugPrint('Login failed: ${authResponse.errorMessage}');
return _handleAuthError(authResponse); return _handleAuthError(authResponse);
} }
...@@ -152,7 +153,7 @@ class LoginService extends RestfulApiViewModel { ...@@ -152,7 +153,7 @@ class LoginService extends RestfulApiViewModel {
await PushTokenService.uploadIfLogged(); await PushTokenService.uploadIfLogged();
} catch (e) { } catch (e) {
// Log error but don't fail login // Log error but don't fail login
print('Warning: Failed to upload FCM token: $e'); debugPrint('Warning: Failed to upload FCM token: $e');
} }
} }
......
...@@ -13,9 +13,7 @@ class LogoutService { ...@@ -13,9 +13,7 @@ class LogoutService {
try { try {
await _client.logout(); await _client.logout();
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('LogoutService.logout failed: $e');
print('LogoutService.logout failed: $e');
}
} }
} }
} }
...@@ -37,7 +37,7 @@ class TokenRefreshService extends RestfulApiViewModel { ...@@ -37,7 +37,7 @@ class TokenRefreshService extends RestfulApiViewModel {
await _handleRefreshFailure(); await _handleRefreshFailure();
} }
} catch (e) { } catch (e) {
print('Token refresh error: $e'); debugPrint('Token refresh error: $e');
await _handleRefreshFailure(); await _handleRefreshFailure();
} finally { } finally {
_isRefreshing = false; _isRefreshing = false;
...@@ -52,7 +52,7 @@ class TokenRefreshService extends RestfulApiViewModel { ...@@ -52,7 +52,7 @@ class TokenRefreshService extends RestfulApiViewModel {
await DataPreference.instance.saveUserProfile(response.data!); await DataPreference.instance.saveUserProfile(response.data!);
} }
} catch (e) { } catch (e) {
print('Get user profile after refresh error: $e'); debugPrint('Get user profile after refresh error: $e');
} }
} }
......
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/news/news_list_screen.dart'; import 'package:mypoint_flutter_app/screen/news/news_list_screen.dart';
import 'package:mypoint_flutter_app/screen/qr_code/qr_code_screen.dart'; import 'package:mypoint_flutter_app/screen/qr_code/qr_code_screen.dart';
import '../screen/achievement/achievement_list_screen.dart'; import '../deferred/deferred_routes.dart';
import '../screen/affiliate/affiliate_tab_screen.dart';
import '../screen/affiliate_brand_detail/affiliate_brand_detail_screen.dart'; import '../screen/affiliate_brand_detail/affiliate_brand_detail_screen.dart';
import '../screen/affiliate_brand_detail/affiliate_brand_list_screen.dart'; import '../screen/affiliate_brand_detail/affiliate_brand_list_screen.dart';
import '../screen/affiliate_brand_detail/affiliate_category_grid_screen.dart'; import '../screen/affiliate_brand_detail/affiliate_category_grid_screen.dart';
import '../screen/bank_account_manager/bank_account_manager_screen.dart';
import '../screen/campaign7day/campaign_7day_screen.dart';
import '../screen/contacts/contacts_list_screen.dart'; import '../screen/contacts/contacts_list_screen.dart';
import '../screen/daily_checkin/daily_checkin_screen.dart';
import '../screen/data_network_service/data_network_service_screen.dart';
import '../screen/device_manager/device_manager_screen.dart';
import '../screen/electric_payment/electric_payment_history_screen.dart';
import '../screen/electric_payment/electric_payment_screen.dart';
import '../screen/flash_sale/flash_sale_screen.dart';
import '../screen/game/game_cards/game_card_screen.dart'; import '../screen/game/game_cards/game_card_screen.dart';
import '../screen/game/game_tab_screen.dart'; import '../screen/game/game_tab_screen.dart';
import '../screen/health_book/health_book_card_detail.dart'; import '../screen/health_book/health_book_card_detail.dart';
import '../screen/health_book/health_book_screen.dart';
import '../screen/history_point/history_point_screen.dart';
import '../screen/history_point_cashback/history_point_cashback_screen.dart';
import '../screen/interested_categories/interestied_categories_screen.dart'; import '../screen/interested_categories/interestied_categories_screen.dart';
import '../screen/invite_friend_campaign/invite_friend_campaign_screen.dart';
import '../screen/location_address/location_address_screen.dart';
import '../screen/login/login_screen.dart'; import '../screen/login/login_screen.dart';
import '../screen/main_tab_screen/main_tab_screen.dart'; import '../screen/main_tab_screen/main_tab_screen.dart';
import '../screen/membership/membership_screen.dart';
import '../screen/mobile_card/product_mobile_card_screen.dart';
import '../screen/notification/notification_detail_screen.dart'; import '../screen/notification/notification_detail_screen.dart';
import '../screen/notification/notification_screen.dart'; import '../screen/notification/notification_screen.dart';
import '../screen/onboarding/onboarding_screen.dart'; import '../screen/onboarding/onboarding_screen.dart';
import '../screen/order_menu/order_menu_screen.dart';
import '../screen/pageDetail/campaign_detail_screen.dart'; import '../screen/pageDetail/campaign_detail_screen.dart';
import '../screen/personal/personal_edit_screen.dart'; import '../screen/personal/personal_edit_screen.dart';
import '../screen/quiz_campaign/quiz_campaign_screen.dart';
import '../screen/register_campaign/register_form_input_screen.dart'; import '../screen/register_campaign/register_form_input_screen.dart';
import '../screen/setting/setting_screen.dart'; import '../screen/setting/setting_screen.dart';
import '../screen/splash/splash_screen.dart'; import '../screen/splash/splash_screen.dart';
import '../screen/support/support_screen.dart'; import '../screen/support/support_screen.dart';
import '../screen/topup/topup_screen.dart'; import '../screen/topup/topup_screen.dart';
import '../screen/traffic_service/traffic_service_detail_screen.dart';
import '../screen/traffic_service/traffic_service_screen.dart';
import '../screen/transaction/history/transaction_history_detail_screen.dart'; import '../screen/transaction/history/transaction_history_detail_screen.dart';
import '../screen/transaction/transaction_detail_screen.dart'; import '../screen/transaction/transaction_detail_screen.dart';
import '../screen/transaction/transactions_history_screen.dart';
import '../screen/voucher/detail/voucher_detail_screen.dart'; import '../screen/voucher/detail/voucher_detail_screen.dart';
import '../screen/voucher/mobile_card/my_mobile_card_detail_widget.dart'; import '../screen/voucher/mobile_card/my_mobile_card_detail_widget.dart';
import '../screen/voucher/mobile_card/my_mobile_card_list_widget.dart'; import '../screen/voucher/mobile_card/my_mobile_card_list_widget.dart';
import '../screen/voucher/my_voucher/my_product_list_widget.dart'; import '../screen/voucher/my_voucher/my_product_list_widget.dart';
import '../screen/voucher/voucher_list/voucher_list_screen.dart'; import '../screen/voucher/voucher_list/voucher_list_screen.dart';
import '../screen/vplay_game_center/vplay_game_center_screen.dart';
import '../screen/webview/payment_web_view_screen.dart';
import '../screen/webview/web_view_screen.dart'; import '../screen/webview/web_view_screen.dart';
const splashScreen = '/splash'; const splashScreen = '/splash';
const onboardingScreen = '/onboarding'; const onboardingScreen = '/onboarding';
...@@ -129,54 +106,54 @@ class RouterPage { ...@@ -129,54 +106,54 @@ class RouterPage {
), ),
GetPage(name: settingScreen, page: () => SettingScreen()), GetPage(name: settingScreen, page: () => SettingScreen()),
GetPage(name: vouchersScreen, page: () => VoucherListScreen()), GetPage(name: vouchersScreen, page: () => VoucherListScreen()),
GetPage(name: flashSaleScreen, page: () => const FlashSaleScreen()), GetPage(name: flashSaleScreen, page: () => const FlashSaleDeferredScreen()),
GetPage(name: voucherDetailScreen, page: () => VoucherDetailScreen()), GetPage(name: voucherDetailScreen, page: () => const VoucherDetailDeferredScreen()),
GetPage(name: gameCardScreen, page: () => GameCardScreen()), GetPage(name: gameCardScreen, page: () => const GameCardScreen()),
GetPage(name: registerFormInputScreen, page: () => RegisterFormInputScreen()), GetPage(name: registerFormInputScreen, page: () => RegisterFormInputScreen()),
GetPage(name: transactionDetailScreen, page: () => TransactionDetailScreen()), GetPage(name: transactionDetailScreen, page: () => const TransactionDetailDeferredScreen()),
GetPage(name: baseWebViewScreen, page: () => BaseWebViewScreen()), GetPage(name: baseWebViewScreen, page: () => BaseWebViewScreen()),
GetPage(name: paymentWebViewScreen, page: () => PaymentWebViewScreen()), GetPage(name: paymentWebViewScreen, page: () => const PaymentWebViewDeferredScreen()),
GetPage(name: transactionHistoryDetailScreen, page: () => TransactionHistoryDetailScreen()), GetPage(name: transactionHistoryDetailScreen, page: () => const TransactionHistoryDetailDeferredScreen()),
GetPage(name: supportScreen, page: () => SupportScreen()), GetPage(name: supportScreen, page: () => const SupportDeferredScreen()),
GetPage(name: notificationScreen, page: () => NotificationScreen()), GetPage(name: notificationScreen, page: () => NotificationScreen()),
GetPage(name: campaignDetailScreen, page: () => CampaignDetailScreen()), GetPage(name: campaignDetailScreen, page: () => CampaignDetailScreen()),
GetPage(name: newsListScreen, page: () => NewsListScreen()), GetPage(name: newsListScreen, page: () => const NewsListDeferredScreen()),
GetPage(name: achievementListScreen, page: () => AchievementListScreen()), GetPage(name: achievementListScreen, page: () => const AchievementListDeferredScreen()),
GetPage(name: vplayGameCenterScreen, page: () => VplayGameCenterScreen()), GetPage(name: vplayGameCenterScreen, page: () => const VplayGameCenterDeferredScreen()),
GetPage(name: myVoucherListScreen, page: () => MyVoucherListScreen()), GetPage(name: myVoucherListScreen, page: () => const MyVoucherListDeferredScreen()),
GetPage(name: personalEditScreen, page: () => PersonalEditScreen()), GetPage(name: personalEditScreen, page: () => PersonalEditScreen()),
GetPage(name: orderMenuScreen, page: () => OrderMenuScreen()), GetPage(name: orderMenuScreen, page: () => const OrderMenuDeferredScreen()),
GetPage(name: locationAddressScreen, page: () => LocationAddressScreen()), GetPage(name: locationAddressScreen, page: () => const LocationAddressDeferredScreen()),
GetPage(name: membershipScreen, page: () => MembershipScreen()), GetPage(name: membershipScreen, page: () => const MembershipDeferredScreen()),
GetPage(name: phoneTopUpScreen, page: () => PhoneTopUpScreen()), GetPage(name: phoneTopUpScreen, page: () => const PhoneTopUpDeferredScreen()),
GetPage(name: productMobileCardScreen, page: () => ProductMobileCardScreen()), GetPage(name: productMobileCardScreen, page: () => const ProductMobileCardDeferredScreen()),
GetPage(name: dataNetworkServiceScreen, page: () => DataNetworkServiceScreen()), GetPage(name: dataNetworkServiceScreen, page: () => const DataNetworkServiceDeferredScreen()),
GetPage(name: affiliateTabScreen, page: () => AffiliateTabScreen()), GetPage(name: affiliateTabScreen, page: () => const AffiliateTabDeferredScreen()),
GetPage(name: gameTabScreen, page: () => GameTabScreen()), GetPage(name: gameTabScreen, page: () => const GameTabScreen()),
GetPage(name: historyPointCashBackScreen, page: () => HistoryPointCashBackScreen()), GetPage(name: historyPointCashBackScreen, page: () => const HistoryPointCashBackDeferredScreen()),
GetPage(name: affiliateBrandDetailScreen, page: () => AffiliateBrandDetailScreen()), GetPage(name: affiliateBrandDetailScreen, page: () => const AffiliateBrandDetailDeferredScreen()),
GetPage(name: affiliateBrandListScreen, page: () => AffiliateBrandListScreen()), GetPage(name: affiliateBrandListScreen, page: () => const AffiliateBrandListDeferredScreen()),
GetPage(name: affiliateCategoryGridScreen, page: () => AffiliateCategoryGridScreen()), GetPage(name: affiliateCategoryGridScreen, page: () => const AffiliateCategoryGridDeferredScreen()),
GetPage(name: inviteFriendCampaignScreen, page: () => InviteFriendCampaignScreen()), GetPage(name: inviteFriendCampaignScreen, page: () => const InviteFriendDeferredScreen()),
GetPage(name: contactsListScreen, page: () => ContactsListScreen()), GetPage(name: contactsListScreen, page: () => const ContactsListDeferredScreen()),
GetPage(name: dailyCheckInScreen, page: () => DailyCheckInScreen()), GetPage(name: dailyCheckInScreen, page: () => const DailyCheckInDeferredScreen()),
GetPage(name: transactionHistoryScreen, page: () => TransactionHistoryScreen()), GetPage(name: transactionHistoryScreen, page: () => const TransactionHistoryDeferredScreen()),
GetPage(name: electricPaymentScreen, page: () => ElectricPaymentScreen()), GetPage(name: electricPaymentScreen, page: () => const ElectricPaymentDeferredScreen()),
GetPage(name: electricPaymentHistoryScreen, page: () => ElectricPaymentHistoryScreen()), GetPage(name: electricPaymentHistoryScreen, page: () => const ElectricPaymentHistoryDeferredScreen()),
GetPage(name: trafficServiceScreen, page: () => TrafficServiceScreen()), GetPage(name: trafficServiceScreen, page: () => const TrafficServiceDeferredScreen()),
GetPage(name: trafficServiceDetailScreen, page: () => TrafficServiceDetailScreen()), GetPage(name: trafficServiceDetailScreen, page: () => const TrafficServiceDetailDeferredScreen()),
GetPage(name: campaignSevenDayScreen, page: () => Campaign7DayScreen()), GetPage(name: campaignSevenDayScreen, page: () => const Campaign7DayDeferredScreen()),
GetPage(name: surveyQuestionScreen, page: () => SurveyQuestionScreen()), GetPage(name: surveyQuestionScreen, page: () => const SurveyQuestionDeferredScreen()),
GetPage(name: deviceManagerScreen, page: () => DeviceManagerScreen()), GetPage(name: deviceManagerScreen, page: () => const DeviceManagerDeferredScreen()),
GetPage(name: myMobileCardListScreen, page: () => MyMobileCardListScreen()), GetPage(name: myMobileCardListScreen, page: () => const MyMobileCardListDeferredScreen()),
GetPage(name: interestCategoriesScreen, page: () => InterestCategoriesScreen()), GetPage(name: interestCategoriesScreen, page: () => const InterestCategoriesDeferredScreen()),
GetPage(name: bankAccountManagerScreen, page: () => BankAccountManagerScreen()), GetPage(name: bankAccountManagerScreen, page: () => const BankAccountManagerDeferredScreen()),
GetPage(name: historyPointScreen, page: () => HistoryPointScreen()), GetPage(name: historyPointScreen, page: () => const HistoryPointDeferredScreen()),
GetPage(name: qrCodeScreen, page: () => QRCodeScreen()), GetPage(name: qrCodeScreen, page: () => const QRCodeDeferredScreen()),
GetPage(name: myMobileCardDetailScreen, page: () => MyMobileCardDetailScreen()), GetPage(name: myMobileCardDetailScreen, page: () => const MyMobileCardDetailDeferredScreen()),
GetPage(name: healthBookScreen, page: () => HealthBookScreen()), GetPage(name: healthBookScreen, page: () => const HealthBookDeferredScreen()),
GetPage(name: healthBookCardDetail, page: () => HealthBookCardDetail()), GetPage(name: healthBookCardDetail, page: () => const HealthBookCardDetailDeferredScreen()),
GetPage(name: notificationDetailScreen, page: () => NotificationDetailScreen()), GetPage(name: notificationDetailScreen, page: () => NotificationDetailScreen()),
]; ];
} }
} }
\ No newline at end of file
...@@ -9,7 +9,7 @@ Future<void> webInitializeXAppSDK() async { ...@@ -9,7 +9,7 @@ Future<void> webInitializeXAppSDK() async {
try { try {
await XAppSDKService().initialize(); await XAppSDKService().initialize();
} catch (e) { } catch (e) {
print('❌ Error initializing x-app-sdk: $e'); debugPrint('❌ Error initializing x-app-sdk: $e');
} }
} }
...@@ -18,7 +18,7 @@ Future<String?> webGetToken() async { ...@@ -18,7 +18,7 @@ Future<String?> webGetToken() async {
try { try {
return await XAppSDKService().getToken(); return await XAppSDKService().getToken();
} catch (e) { } catch (e) {
print('❌ Error getting token: $e'); debugPrint('❌ Error getting token: $e');
return null; return null;
} }
} }
...@@ -28,7 +28,7 @@ Future<bool> webCloseApp([Map<String, dynamic>? data]) async { ...@@ -28,7 +28,7 @@ Future<bool> webCloseApp([Map<String, dynamic>? data]) async {
try { try {
return await XAppSDKService().closeApp(data); return await XAppSDKService().closeApp(data);
} catch (e) { } catch (e) {
print('❌ Error closing app: $e'); debugPrint('❌ Error closing app: $e');
return false; return false;
} }
} }
...@@ -38,7 +38,7 @@ bool webIsSDKInitialized() { ...@@ -38,7 +38,7 @@ bool webIsSDKInitialized() {
try { try {
return XAppSDKService().isInitialized; return XAppSDKService().isInitialized;
} catch (e) { } catch (e) {
print('❌ Error checking SDK status: $e'); debugPrint('❌ Error checking SDK status: $e');
return false; return false;
} }
} }
...@@ -48,7 +48,7 @@ String? webGetCachedToken() { ...@@ -48,7 +48,7 @@ String? webGetCachedToken() {
try { try {
return XAppSDKService().cachedToken; return XAppSDKService().cachedToken;
} catch (e) { } catch (e) {
print('❌ Error getting cached token: $e'); debugPrint('❌ Error getting cached token: $e');
return null; return null;
} }
} }
...@@ -58,7 +58,7 @@ String? webGetLastError() { ...@@ -58,7 +58,7 @@ String? webGetLastError() {
try { try {
return XAppSDKService().lastError; return XAppSDKService().lastError;
} catch (e) { } catch (e) {
print('❌ Error getting last error: $e'); debugPrint('❌ Error getting last error: $e');
return null; return null;
} }
} }
...@@ -68,7 +68,7 @@ void webClearTokenCache() { ...@@ -68,7 +68,7 @@ void webClearTokenCache() {
try { try {
XAppSDKService().clearToken(); XAppSDKService().clearToken();
} catch (e) { } catch (e) {
print('❌ Error clearing token cache: $e'); debugPrint('❌ Error clearing token cache: $e');
} }
} }
...@@ -77,7 +77,7 @@ void webResetSDK() { ...@@ -77,7 +77,7 @@ void webResetSDK() {
try { try {
XAppSDKService().reset(); XAppSDKService().reset();
} catch (e) { } catch (e) {
print('❌ Error resetting SDK: $e'); debugPrint('❌ Error resetting SDK: $e');
} }
} }
...@@ -85,7 +85,7 @@ Future<dynamic> webConfigUIApp(Map<String, dynamic> config) async { ...@@ -85,7 +85,7 @@ Future<dynamic> webConfigUIApp(Map<String, dynamic> config) async {
try { try {
return await XAppSDKService().configUIApp(config); return await XAppSDKService().configUIApp(config);
} catch (e) { } catch (e) {
print('❌ Error configuring UI app: $e'); debugPrint('❌ Error configuring UI app: $e');
return null; return null;
} }
} }
...@@ -94,7 +94,7 @@ Future<dynamic> webCallPhone(String phoneNumber) async { ...@@ -94,7 +94,7 @@ Future<dynamic> webCallPhone(String phoneNumber) async {
try { try {
return await XAppSDKService().callPhone(phoneNumber); return await XAppSDKService().callPhone(phoneNumber);
} catch (e) { } catch (e) {
print('❌ Error calling phone: $e'); debugPrint('❌ Error calling phone: $e');
return null; return null;
} }
} }
...@@ -105,7 +105,7 @@ Future<dynamic> webSendSms(String phoneNumber) async { ...@@ -105,7 +105,7 @@ Future<dynamic> webSendSms(String phoneNumber) async {
try { try {
return await XAppSDKService().sendSms(phoneNumber); return await XAppSDKService().sendSms(phoneNumber);
} catch (e) { } catch (e) {
print('❌ Error sending SMS: $e'); debugPrint('❌ Error sending SMS: $e');
return null; return null;
} }
} }
...@@ -116,7 +116,7 @@ Future<dynamic> webVibrate() async { ...@@ -116,7 +116,7 @@ Future<dynamic> webVibrate() async {
try { try {
return await XAppSDKService().vibrate(); return await XAppSDKService().vibrate();
} catch (e) { } catch (e) {
print('❌ Error vibrating device: $e'); debugPrint('❌ Error vibrating device: $e');
return null; return null;
} }
} }
...@@ -125,7 +125,7 @@ Future<dynamic> webCurrentLocation() async { ...@@ -125,7 +125,7 @@ Future<dynamic> webCurrentLocation() async {
try { try {
return await XAppSDKService().currentLocation(); return await XAppSDKService().currentLocation();
} catch (e) { } catch (e) {
print('❌ Error getting current location: $e'); debugPrint('❌ Error getting current location: $e');
return null; return null;
} }
} }
...@@ -134,7 +134,7 @@ Future<dynamic> webRequestLocationPermission() async { ...@@ -134,7 +134,7 @@ Future<dynamic> webRequestLocationPermission() async {
try { try {
return await XAppSDKService().requestLocationPermission(); return await XAppSDKService().requestLocationPermission();
} catch (e) { } catch (e) {
print('❌ Error requesting location permission: $e'); debugPrint('❌ Error requesting location permission: $e');
return null; return null;
} }
} }
...@@ -143,7 +143,7 @@ Future<dynamic> webOpenPickerImage(dynamic type) async { ...@@ -143,7 +143,7 @@ Future<dynamic> webOpenPickerImage(dynamic type) async {
try { try {
return await XAppSDKService().openPickerImage(type); return await XAppSDKService().openPickerImage(type);
} catch (e) { } catch (e) {
print('❌ Error opening image picker: $e'); debugPrint('❌ Error opening image picker: $e');
return null; return null;
} }
} }
...@@ -152,7 +152,7 @@ Future<dynamic> webOpenPickerFile([dynamic options]) async { ...@@ -152,7 +152,7 @@ Future<dynamic> webOpenPickerFile([dynamic options]) async {
try { try {
return await XAppSDKService().openPickerFile(options); return await XAppSDKService().openPickerFile(options);
} catch (e) { } catch (e) {
print('❌ Error opening file picker: $e'); debugPrint('❌ Error opening file picker: $e');
return null; return null;
} }
} }
...@@ -161,7 +161,7 @@ Future<dynamic> webPaymentRequest(Map<String, dynamic> payload) async { ...@@ -161,7 +161,7 @@ Future<dynamic> webPaymentRequest(Map<String, dynamic> payload) async {
try { try {
return await XAppSDKService().paymentRequest(payload); return await XAppSDKService().paymentRequest(payload);
} catch (e) { } catch (e) {
print('❌ Error creating payment request: $e'); debugPrint('❌ Error creating payment request: $e');
return null; return null;
} }
} }
...@@ -172,7 +172,7 @@ Future<VoidCallback?> webListenNotificationEvent( ...@@ -172,7 +172,7 @@ Future<VoidCallback?> webListenNotificationEvent(
try { try {
return await XAppSDKService().listenNotificationEvent(onEvent); return await XAppSDKService().listenNotificationEvent(onEvent);
} catch (e) { } catch (e) {
print('❌ Error registering notification listener: $e'); debugPrint('❌ Error registering notification listener: $e');
return null; return null;
} }
} }
...@@ -183,7 +183,7 @@ Future<VoidCallback?> webListenPaymentEvent( ...@@ -183,7 +183,7 @@ Future<VoidCallback?> webListenPaymentEvent(
try { try {
return await XAppSDKService().listenPaymentEvent(onEvent); return await XAppSDKService().listenPaymentEvent(onEvent);
} catch (e) { } catch (e) {
print('❌ Error registering payment listener: $e'); debugPrint('❌ Error registering payment listener: $e');
return null; return null;
} }
} }
...@@ -192,7 +192,7 @@ Future<dynamic> webPermissionsRequest(dynamic type) async { ...@@ -192,7 +192,7 @@ Future<dynamic> webPermissionsRequest(dynamic type) async {
try { try {
return await XAppSDKService().permissionsRequest(type); return await XAppSDKService().permissionsRequest(type);
} catch (e) { } catch (e) {
print('❌ Error requesting permission: $e'); debugPrint('❌ Error requesting permission: $e');
return null; return null;
} }
} }
...@@ -204,7 +204,7 @@ Future<dynamic> webSaveStore(dynamic data) async { ...@@ -204,7 +204,7 @@ Future<dynamic> webSaveStore(dynamic data) async {
try { try {
return await XAppSDKService().saveStore(data); return await XAppSDKService().saveStore(data);
} catch (e) { } catch (e) {
print('❌ Error saving store data: $e'); debugPrint('❌ Error saving store data: $e');
return null; return null;
} }
} }
...@@ -213,7 +213,7 @@ Future<dynamic> webGetStore() async { ...@@ -213,7 +213,7 @@ Future<dynamic> webGetStore() async {
try { try {
return await XAppSDKService().getStore(); return await XAppSDKService().getStore();
} catch (e) { } catch (e) {
print('❌ Error getting store data: $e'); debugPrint('❌ Error getting store data: $e');
return null; return null;
} }
} }
...@@ -222,7 +222,7 @@ Future<dynamic> webClearStore() async { ...@@ -222,7 +222,7 @@ Future<dynamic> webClearStore() async {
try { try {
return await XAppSDKService().clearStore(); return await XAppSDKService().clearStore();
} catch (e) { } catch (e) {
print('❌ Error clearing store: $e'); debugPrint('❌ Error clearing store: $e');
return null; return null;
} }
} }
...@@ -231,7 +231,7 @@ Future<dynamic> webGetInfo(dynamic key) async { ...@@ -231,7 +231,7 @@ Future<dynamic> webGetInfo(dynamic key) async {
try { try {
return await XAppSDKService().getInfo(key); return await XAppSDKService().getInfo(key);
} catch (e) { } catch (e) {
print('❌ Error getting info: $e'); debugPrint('❌ Error getting info: $e');
return null; return null;
} }
} }
...@@ -28,7 +28,7 @@ class XAppSDKService { ...@@ -28,7 +28,7 @@ class XAppSDKService {
/// Initialize the SDK service /// Initialize the SDK service
Future<void> initialize() async { Future<void> initialize() async {
if (!kIsWeb) { if (!kIsWeb) {
print('⚠️ XAppSDKService: initialize() called on non-web platform'); debugPrint('⚠️ XAppSDKService: initialize() called on non-web platform');
return; return;
} }
if (_isInitialized && _sdkModule != null) { if (_isInitialized && _sdkModule != null) {
...@@ -36,20 +36,20 @@ class XAppSDKService { ...@@ -36,20 +36,20 @@ class XAppSDKService {
} }
try { try {
print('🔍 XAppSDKService: Initializing...'); debugPrint('🔍 XAppSDKService: Initializing...');
final module = await _loadSdkModule(); final module = await _loadSdkModule();
if (module == null) { if (module == null) {
_lastError = 'x-app-sdk module could not be loaded'; _lastError = 'x-app-sdk module could not be loaded';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return; return;
} }
_sdkModule = module; _sdkModule = module;
_isInitialized = true; _isInitialized = true;
_lastError = null; _lastError = null;
print('✅ XAppSDKService: Initialized successfully'); debugPrint('✅ XAppSDKService: Initialized successfully');
} catch (e) { } catch (e) {
_lastError = 'Failed to initialize SDK: $e'; _lastError = 'Failed to initialize SDK: $e';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
} }
} }
...@@ -59,7 +59,7 @@ class XAppSDKService { ...@@ -59,7 +59,7 @@ class XAppSDKService {
return null; return null;
} }
print('🔍 XAppSDKService: Getting token...'); debugPrint('🔍 XAppSDKService: Getting token...');
try { try {
final result = await _invokeSdkMethod( final result = await _invokeSdkMethod(
'getToken', 'getToken',
...@@ -78,22 +78,22 @@ class XAppSDKService { ...@@ -78,22 +78,22 @@ class XAppSDKService {
_lastError = null; _lastError = null;
final preview = final preview =
tokenString.length > 8 ? tokenString.substring(0, 8) : tokenString; tokenString.length > 8 ? tokenString.substring(0, 8) : tokenString;
print( debugPrint(
'✅ XAppSDKService: Token retrieved successfully: $preview...'); '✅ XAppSDKService: Token retrieved successfully: $preview...');
return _cachedToken; return _cachedToken;
} else { } else {
final details = final details =
errorMessage?.isNotEmpty == true ? ' - $errorMessage' : ''; errorMessage?.isNotEmpty == true ? ' - $errorMessage' : '';
_lastError = 'SDK returned status: $status$details'; _lastError = 'SDK returned status: $status$details';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
} }
} else { } else {
_lastError ??= 'getToken returned null'; _lastError ??= 'getToken returned null';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
} }
} catch (e) { } catch (e) {
_lastError = 'Error getting token: $e'; _lastError = 'Error getting token: $e';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
} }
return null; return null;
...@@ -102,18 +102,18 @@ class XAppSDKService { ...@@ -102,18 +102,18 @@ class XAppSDKService {
/// Close app and return to Super App /// Close app and return to Super App
Future<bool> closeApp([Map<String, dynamic>? data]) async { Future<bool> closeApp([Map<String, dynamic>? data]) async {
if (!await _ensureSdkReady()) { if (!await _ensureSdkReady()) {
print('❌ XAppSDKService: closeApp skipped - SDK not ready'); debugPrint('❌ XAppSDKService: closeApp skipped - SDK not ready');
_fallbackClose(); _fallbackClose();
return false; return false;
} }
if (_browserMode) { if (_browserMode) {
print('ℹ️ XAppSDKService: Running in browser mode, falling back from closeApp'); debugPrint('ℹ️ XAppSDKService: Running in browser mode, falling back from closeApp');
_fallbackClose(); _fallbackClose();
return false; return false;
} }
print('🔍 XAppSDKService: Closing app...'); debugPrint('🔍 XAppSDKService: Closing app...');
final result = await _invokeSdkMethod( final result = await _invokeSdkMethod(
'closeApp', 'closeApp',
args: data != null ? <dynamic>[data] : const <dynamic>[], args: data != null ? <dynamic>[data] : const <dynamic>[],
...@@ -124,15 +124,15 @@ class XAppSDKService { ...@@ -124,15 +124,15 @@ class XAppSDKService {
final success = _lastError == null && _isSuccessResult(result); final success = _lastError == null && _isSuccessResult(result);
if (success) { if (success) {
if (data != null) { if (data != null) {
print('✅ XAppSDKService: App closed with data: $data'); debugPrint('✅ XAppSDKService: App closed with data: $data');
} else { } else {
print('✅ XAppSDKService: App closed successfully'); debugPrint('✅ XAppSDKService: App closed successfully');
} }
return true; return true;
} }
final reason = _lastError ?? 'closeApp returned non-success result'; final reason = _lastError ?? 'closeApp returned non-success result';
print('❌ XAppSDKService: $reason'); debugPrint('❌ XAppSDKService: $reason');
_fallbackClose(); _fallbackClose();
return false; return false;
} }
...@@ -183,7 +183,7 @@ class XAppSDKService { ...@@ -183,7 +183,7 @@ class XAppSDKService {
try { try {
onEvent(event); onEvent(event);
} catch (error, stackTrace) { } catch (error, stackTrace) {
print( debugPrint(
'❌ XAppSDKService: Error in notification listener: $error'); '❌ XAppSDKService: Error in notification listener: $error');
debugPrintStack(stackTrace: stackTrace); debugPrintStack(stackTrace: stackTrace);
} }
...@@ -205,7 +205,7 @@ class XAppSDKService { ...@@ -205,7 +205,7 @@ class XAppSDKService {
try { try {
onEvent(event); onEvent(event);
} catch (error, stackTrace) { } catch (error, stackTrace) {
print('❌ XAppSDKService: Error in payment listener: $error'); debugPrint('❌ XAppSDKService: Error in payment listener: $error');
debugPrintStack(stackTrace: stackTrace); debugPrintStack(stackTrace: stackTrace);
} }
}), }),
...@@ -241,7 +241,7 @@ class XAppSDKService { ...@@ -241,7 +241,7 @@ class XAppSDKService {
void clearToken() { void clearToken() {
_cachedToken = null; _cachedToken = null;
_lastError = null; _lastError = null;
print('🧹 XAppSDKService: Token cache cleared'); debugPrint('🧹 XAppSDKService: Token cache cleared');
} }
/// Reset service state /// Reset service state
...@@ -258,18 +258,18 @@ class XAppSDKService { ...@@ -258,18 +258,18 @@ class XAppSDKService {
callMethod(loader, 'resetCachedModule', <dynamic>[]); callMethod(loader, 'resetCachedModule', <dynamic>[]);
} }
} catch (_) {} } catch (_) {}
print('🔄 XAppSDKService: Service reset'); debugPrint('🔄 XAppSDKService: Service reset');
} }
Future<bool> _ensureSdkReady() async { Future<bool> _ensureSdkReady() async {
if (!kIsWeb) { if (!kIsWeb) {
print('⚠️ XAppSDKService: SDK requested on non-web platform'); debugPrint('⚠️ XAppSDKService: SDK requested on non-web platform');
return false; return false;
} }
if (_isInitialized && _sdkModule != null) { if (_isInitialized && _sdkModule != null) {
return true; return true;
} }
print( debugPrint(
'⚠️ XAppSDKService: SDK not initialized, attempting to initialize...'); '⚠️ XAppSDKService: SDK not initialized, attempting to initialize...');
await initialize(); await initialize();
return _isInitialized && _sdkModule != null; return _isInitialized && _sdkModule != null;
...@@ -304,13 +304,13 @@ class XAppSDKService { ...@@ -304,13 +304,13 @@ class XAppSDKService {
final sdk = await _loadSdkModule(); final sdk = await _loadSdkModule();
if (sdk == null) { if (sdk == null) {
_lastError = 'x-app-sdk not available'; _lastError = 'x-app-sdk not available';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
if (!_hasProperty(sdk, methodName)) { if (!_hasProperty(sdk, methodName)) {
_lastError = '$methodName method not found in SDK'; _lastError = '$methodName method not found in SDK';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
...@@ -334,7 +334,7 @@ class XAppSDKService { ...@@ -334,7 +334,7 @@ class XAppSDKService {
return result; return result;
} catch (e) { } catch (e) {
_lastError = 'Error invoking $methodName: $e'; _lastError = 'Error invoking $methodName: $e';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
} }
...@@ -359,17 +359,17 @@ class XAppSDKService { ...@@ -359,17 +359,17 @@ class XAppSDKService {
) { ) {
if (disposer == null) { if (disposer == null) {
if (_lastError != null) { if (_lastError != null) {
print( debugPrint(
'❌ XAppSDKService: Failed to register $methodName listener - $_lastError'); '❌ XAppSDKService: Failed to register $methodName listener - $_lastError');
} else { } else {
print( debugPrint(
'⚠️ XAppSDKService: $methodName did not return a disposer function'); '⚠️ XAppSDKService: $methodName did not return a disposer function');
} }
return null; return null;
} }
_listenerDisposers.add(disposer); _listenerDisposers.add(disposer);
print('🔔 XAppSDKService: $methodName listener registered'); debugPrint('🔔 XAppSDKService: $methodName listener registered');
return () { return () {
_invokeJsFunction(disposer); _invokeJsFunction(disposer);
...@@ -389,7 +389,7 @@ class XAppSDKService { ...@@ -389,7 +389,7 @@ class XAppSDKService {
// Ignore non-Promise results. // Ignore non-Promise results.
} }
} catch (e) { } catch (e) {
print('❌ XAppSDKService: Failed to invoke JS callback: $e'); debugPrint('❌ XAppSDKService: Failed to invoke JS callback: $e');
} }
} }
...@@ -411,9 +411,9 @@ class XAppSDKService { ...@@ -411,9 +411,9 @@ class XAppSDKService {
} else { } else {
html.window.close(); html.window.close();
} }
print('✅ XAppSDKService: Fallback close executed'); debugPrint('✅ XAppSDKService: Fallback close executed');
} catch (fallbackError) { } catch (fallbackError) {
print('❌ XAppSDKService: Fallback close failed: $fallbackError'); debugPrint('❌ XAppSDKService: Fallback close failed: $fallbackError');
} }
} }
...@@ -465,14 +465,14 @@ class XAppSDKService { ...@@ -465,14 +465,14 @@ class XAppSDKService {
final loader = getProperty(html.window, '__xAppSdkLoader'); final loader = getProperty(html.window, '__xAppSdkLoader');
if (loader == null) { if (loader == null) {
_lastError = 'x-app-sdk loader not found on global scope'; _lastError = 'x-app-sdk loader not found on global scope';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
final hasLoadFunction = _hasProperty(loader, 'loadXAppSdkModule'); final hasLoadFunction = _hasProperty(loader, 'loadXAppSdkModule');
if (!hasLoadFunction) { if (!hasLoadFunction) {
_lastError = 'x-app-sdk loader missing loadXAppSdkModule'; _lastError = 'x-app-sdk loader missing loadXAppSdkModule';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
...@@ -482,19 +482,19 @@ class XAppSDKService { ...@@ -482,19 +482,19 @@ class XAppSDKService {
); );
if (module == null) { if (module == null) {
_lastError = 'x-app-sdk module resolved to null'; _lastError = 'x-app-sdk module resolved to null';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
final source = getProperty(module, '__xAppSdkSource'); final source = getProperty(module, '__xAppSdkSource');
if (source != null) { if (source != null) {
print('🔗 XAppSDKService: Module loaded from $source'); debugPrint('🔗 XAppSDKService: Module loaded from $source');
} }
if (!_hasProperty(module, 'getToken') || if (!_hasProperty(module, 'getToken') ||
!_hasProperty(module, 'closeApp')) { !_hasProperty(module, 'closeApp')) {
_lastError = 'x-app-sdk module missing required exports'; _lastError = 'x-app-sdk module missing required exports';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
...@@ -503,7 +503,7 @@ class XAppSDKService { ...@@ -503,7 +503,7 @@ class XAppSDKService {
return _sdkModule; return _sdkModule;
} catch (e) { } catch (e) {
_lastError = 'Failed to load x-app-sdk module: $e'; _lastError = 'Failed to load x-app-sdk module: $e';
print('❌ XAppSDKService: $_lastError'); debugPrint('❌ XAppSDKService: $_lastError');
return null; return null;
} }
} }
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../../resources/base_color.dart'; import '../../resources/base_color.dart';
import '../image_loader.dart'; import '../image_loader.dart';
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment