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