Commit a6797435 authored by DatHV's avatar DatHV
Browse files

refactor print, log, request

parent f0334970
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/base/app_navigator.dart'; import 'package:mypoint_flutter_app/base/app_navigator.dart';
import 'package:mypoint_flutter_app/resources/base_color.dart'; import 'package:mypoint_flutter_app/resources/base_color.dart';
...@@ -40,14 +39,6 @@ class MyApp extends StatelessWidget { ...@@ -40,14 +39,6 @@ class MyApp extends StatelessWidget {
primaryColor: BaseColor.primary500, primaryColor: BaseColor.primary500,
), ),
locale: const Locale('vi'), locale: const Locale('vi'),
supportedLocales: const [
Locale('vi', 'VN'), // Vietnamese
],
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: SplashScreen(), home: SplashScreen(),
getPages: RouterPage.pages(), getPages: RouterPage.pages(),
); );
......
import 'package:mypoint_flutter_app/base/base_response_model.dart';
import 'package:mypoint_flutter_app/configs/api_paths.dart';
import 'package:mypoint_flutter_app/configs/callbacks.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../../screen/affiliate/model/affiliate_brand_model.dart';
import '../../screen/affiliate/model/affiliate_category_model.dart';
import '../../screen/affiliate/model/affiliate_product_top_sale_model.dart';
import '../../screen/affiliate/model/cashback_overview_model.dart';
import '../../screen/affiliate_brand_detail/models/affiliate_brand_detail_model.dart';
class AffiliateApi {
AffiliateApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<List<AffiliateCategoryModel>>>
affiliateCategoryGetList() async {
final token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return client.requestNormal(
APIPaths.affiliateCategoryGetList,
Method.POST,
body,
(data) {
final list = data as List<dynamic>;
return list.map((e) => AffiliateCategoryModel.fromJson(e)).toList();
},
);
}
Future<BaseResponseModel<List<AffiliateBrandModel>>> affiliateBrandGetList({
String? categoryCode,
}) async {
final token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
if ((categoryCode ?? '').isNotEmpty) {
body['category_code'] = categoryCode!;
}
return client.requestNormal(
APIPaths.affiliateBrandGetList,
Method.POST,
body,
(data) {
final list = data as List<dynamic>;
return list.map((e) => AffiliateBrandModel.fromJson(e)).toList();
},
);
}
Future<BaseResponseModel<List<AffiliateProductTopSaleModel>>>
affiliateProductTopSale() async {
final token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return client.requestNormal(
APIPaths.affiliateProductTopSale,
Method.POST,
body,
(data) {
final list = data as List<dynamic>;
return list
.map((e) => AffiliateProductTopSaleModel.fromJson(e))
.toList();
},
);
}
Future<BaseResponseModel<CashbackOverviewModel>> getCashBackOverview() async {
return client.requestNormal(APIPaths.getCashbackOverview, Method.GET, {}, (
data,
) {
return CashbackOverviewModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<AffiliateBrandDetailModel>> getAffiliateBrandDetail(
String brandId,
) async {
final token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "brand_id": brandId};
return client.requestNormal(
APIPaths.affiliateBrandGetDetail,
Method.POST,
body,
(data) {
return AffiliateBrandDetailModel.fromJson(data as Json);
},
);
}
}
import '../../base/base_response_model.dart';
import '../../configs/api_paths.dart';
import '../../configs/callbacks.dart';
import '../restful_api_client.dart';
import '../../screen/game/models/game_bundle_item_model.dart';
import '../../screen/game/models/game_bundle_response.dart';
class GameApi {
GameApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<GameBundleResponse>> getGames() {
return client.requestNormal(
APIPaths.getGames,
Method.GET,
const {},
(data) => GameBundleResponse.fromJson(data as Json),
);
}
Future<BaseResponseModel<GameBundleItemModel>> getGameDetail(String id) {
final path = APIPaths.getGameDetail.replaceAll('%@', id);
return client.requestNormal(
path,
Method.POST,
const {},
(data) => GameBundleItemModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<GameBundleItemModel>> submitGameCard(
String gameId,
String itemId,
) {
final path = APIPaths.submitGameCard
.replaceFirst('%@', gameId)
.replaceFirst('%@', itemId);
return client.requestNormal(
path,
Method.POST,
const {},
(data) => GameBundleItemModel.fromJson(data as Json),
);
}
}
import '../../base/base_response_model.dart';
import '../../configs/api_paths.dart';
import '../../configs/callbacks.dart';
import '../../networking/restful_api_client.dart';
import '../../preference/data_preference.dart';
import '../../screen/location_address/models/district_address_model.dart';
import '../../screen/location_address/models/province_address_model.dart';
class LocationApi {
LocationApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<ProvinceAddressResponse>> locationProvinceGetList() {
final token = DataPreference.instance.token ?? '';
final body = {'access_token': token, 'country_code2': 'VN'};
return client.requestNormal(
APIPaths.locationProvinceGetList,
Method.POST,
body,
(data) => ProvinceAddressResponse.fromJson(data as Json),
);
}
Future<BaseResponseModel<DistrictAddressResponse>> locationDistrictGetList(
String provinceCode,
) {
final token = DataPreference.instance.token ?? '';
final body = {'access_token': token, 'province_code': provinceCode};
return client.requestNormal(
APIPaths.locationDistrictGetList,
Method.POST,
body,
(data) => DistrictAddressResponse.fromJson(data as Json),
);
}
}
import '../../base/base_response_model.dart';
import '../../configs/api_paths.dart';
import '../../configs/callbacks.dart';
import '../../networking/restful_api_client.dart';
import '../../preference/data_preference.dart';
import '../../screen/home/models/notification_unread_model.dart';
import '../../screen/notification/models/category_notify_item_model.dart';
import '../../screen/notification/models/notification_detail_model.dart';
import '../../screen/notification/models/notification_list_data_model.dart';
class NotificationApi {
NotificationApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<List<CategoryNotifyItemModel>>> getNotificationCategories() {
return client.requestNormal(APIPaths.getNotificationCategories, Method.GET, const {}, (data) {
final list = data as List<dynamic>;
return list.map((item) => CategoryNotifyItemModel.fromJson(item)).toList();
});
}
Future<BaseResponseModel<NotificationListDataModel>> getNotifications(Json body) {
return client.requestNormal(
APIPaths.getNotifications,
Method.POST,
body,
(data) => NotificationListDataModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<EmptyCodable>> deleteNotification(String id) {
final token = DataPreference.instance.token ?? '';
return client.requestNormal(APIPaths.deleteNotification, Method.POST, {
'notification_id': id,
'lang': 'vi',
'access_token': token,
}, (data) => EmptyCodable.fromJson(data as Json));
}
Future<BaseResponseModel<EmptyCodable>> deleteAllNotifications() {
final token = DataPreference.instance.token ?? '';
final body = {'access_token': token};
return client.requestNormal(
APIPaths.deleteAllNotifications,
Method.POST,
body,
(data) => EmptyCodable.fromJson(data as Json),
);
}
Future<BaseResponseModel<EmptyCodable>> notificationMarkAsSeen() {
final token = DataPreference.instance.token ?? '';
final body = {'access_token': token};
return client.requestNormal(
APIPaths.notificationMarkAsSeen,
Method.POST,
body,
(data) => EmptyCodable.fromJson(data as Json),
);
}
Future<BaseResponseModel<NotificationDetailResponseModel>> getNotificationDetail(String id) {
final token = DataPreference.instance.token ?? '';
final body = {'notification_id': id, 'mark_as_seen': '1', 'access_token': token};
return client.requestNormal(
APIPaths.notificationGetDetail,
Method.POST,
body,
(data) => NotificationDetailResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<NotificationUnreadData>> getNotificationUnread() {
final token = DataPreference.instance.token ?? '';
final body = {'access_token': token};
return client.requestNormal(
APIPaths.getNotificationUnread,
Method.POST,
body,
(data) => NotificationUnreadData.fromJson(data as Json),
);
}
}
import '../../base/base_response_model.dart';
import '../../configs/api_paths.dart';
import '../../configs/callbacks.dart';
import '../../networking/restful_api_client.dart';
import '../../preference/data_preference.dart';
import '../../screen/data_network_service/product_network_data_model.dart';
import '../../screen/home/models/my_product_model.dart';
import '../../screen/mobile_card/models/mobile_service_redeem_data.dart';
import '../../screen/mobile_card/models/product_mobile_card_model.dart';
import '../../screen/mobile_card/models/usable_voucher_model.dart';
import '../../screen/topup/models/brand_network_model.dart';
import '../../screen/traffic_service/traffic_service_model.dart';
import '../../screen/transaction/model/order_product_payment_response_model.dart';
import '../../screen/transaction/model/payment_bank_account_info_model.dart';
import '../../screen/transaction/model/payment_method_model.dart';
import '../../screen/transaction/model/preview_order_payment_model.dart';
import '../../screen/voucher/models/like_product_response_model.dart';
import '../../screen/voucher/models/my_mobile_card_response.dart';
import '../../screen/voucher/models/my_product_status_type.dart';
import '../../screen/voucher/models/product_brand_model.dart';
import '../../screen/voucher/models/product_model.dart';
import '../../screen/voucher/models/product_store_model.dart';
import '../../screen/voucher/models/product_type.dart';
import '../../screen/voucher/models/search_product_response_model.dart';
class ProductApi {
ProductApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<List<ProductModel>>> getProducts(Json body) {
return client.requestNormal(APIPaths.getProducts, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<SearchProductResponseModel>> getSearchProducts(Json body) {
return client.requestNormal(
APIPaths.getSearchProducts,
Method.POST,
body,
(data) => SearchProductResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<List<ProductModel>>> productsCustomerLikes(Json body) {
return client.requestNormal(APIPaths.productsCustomerLikes, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<ProductModel>> getProduct(int id) {
final path = APIPaths.getProductDetail.replaceAll('%@', id.toString());
return client.requestNormal(path, Method.GET, const {}, (data) => ProductModel.fromJson(data as Json));
}
Future<BaseResponseModel<ProductModel>> getCustomerProductDetail(int id) {
final path = APIPaths.getCustomerProductDetail.replaceAll('%@', id.toString());
return client.requestNormal(path, Method.GET, const {}, (data) => ProductModel.fromJson(data as Json));
}
Future<BaseResponseModel<List<ProductStoreModel>>> getProductStores(int id) {
final body = {'product_id': id, 'size': 20, 'index': 0};
return client.requestNormal(APIPaths.getProductStores, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductStoreModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<LikeProductResponseModel>> likeProduct(int id) {
final body = {'product_id': id};
return client.requestNormal(APIPaths.productCustomerLikes, Method.POST, body, (data) {
return LikeProductResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> unlikeProduct(int id) {
final path = APIPaths.productCustomerUnlikes.replaceAll('%@', id.toString());
return client.requestNormal(path, Method.DELETE, const {}, (data) => EmptyCodable.fromJson(data as Json));
}
Future<BaseResponseModel<List<EmptyCodable>>> verifyOrderProduct(Json body) {
return client.requestNormal(APIPaths.verifyOrderProduct, Method.POST, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => EmptyCodable.fromJson(e)).toList();
});
}
Future<BaseResponseModel<PreviewOrderPaymentModel>> getPreviewOrderInfo(Json body) {
return client.requestNormal(
APIPaths.getPreviewOrderInfo,
Method.POST,
body,
(data) => PreviewOrderPaymentModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<List<PaymentBankAccountInfoModel>>> getPreviewOrderBankAccounts() {
return client.requestNormal(APIPaths.getPreviewOrderBankAccounts, Method.GET, const {}, (data) {
final list = data as List<dynamic>;
return list.map((e) => PaymentBankAccountInfoModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<PaymentMethodModel>>> getPreviewPaymentMethods() {
return client.requestNormal(APIPaths.getPreviewPaymentMethods, Method.GET, const {}, (data) {
final list = data as List<dynamic>;
return list.map((e) => PaymentMethodModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<OrderProductPaymentResponseModel>> orderSubmitPayment({
required List<ProductModel> products,
required int quantity,
required String requestId,
int? point,
int? cash,
PaymentMethodModel? method,
int? paymentTokenId,
bool? saveToken,
String? metadata,
String? targetPhoneNumber,
}) {
final items =
products.map((product) {
return {
'product_id': product.id,
'product_type': product.type ?? '',
'quantity': quantity,
'target_phone_number': targetPhoneNumber ?? '',
};
}).toList();
final Map<String, dynamic> params = {'request_id': requestId, 'items': items, 'flow': '21'};
final firstProduct = products.first;
if (firstProduct.previewFlashSale?.isFlashSalePrice == true && firstProduct.previewFlashSale?.id != null) {
params['flash_sale_id'] = firstProduct.previewFlashSale!.id;
}
if (method != null) {
params['payment_method'] = method.code;
}
if (point != null && point != 0) {
params['pay_point'] = point;
}
if (cash != null && cash != 0) {
params['pay_cash'] = cash;
}
if (paymentTokenId != null) {
params['payment_token_id'] = paymentTokenId;
}
if (saveToken != null) {
params['save_token'] = saveToken;
}
if (metadata != null) {
params['metadata'] = metadata;
}
return client.requestNormal(APIPaths.orderSubmitPayment, Method.POST, params, (data) {
return OrderProductPaymentResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<MyProductModel>>> getCustomerProducts(Json body) {
return client.requestNormal(APIPaths.getCustomerProducts, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => MyProductModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<ProductBrandModel>>> getTopUpBrands(ProductType type) {
final body = {'type': type.value};
return client.requestNormal(APIPaths.getTopUpBrands, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductBrandModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<ProductBrandModel>>> productTopUpBrands() {
final body = {'topup_type': 'PRODUCT_MODEL_MOBILE_SERVICE', 'page_size': '999', 'page_index': 0};
return client.requestNormal(APIPaths.productTopUpsBrands, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductBrandModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<BrandNameCheckResponse>> checkMobileNetwork(String phone) {
final body = {'phone': phone};
return client.requestNormal(APIPaths.checkMobileNetwork, Method.GET, body, (data) {
return BrandNameCheckResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<ProductMobileCardResponse>> productMobileCardGetList() {
final token = DataPreference.instance.token ?? '';
final body = {'start': 0, 'limit': 200, 'access_token': token};
return client.requestNormal(APIPaths.productMobileCardGetList, Method.POST, body, (data) {
return ProductMobileCardResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<MobileServiceRedeemData>> redeemMobileCard(String productId) {
final token = DataPreference.instance.token ?? '';
final body = {'product_id': productId, 'get_customer_balance': '1', 'access_token': token};
return client.requestNormal(APIPaths.redeemMobileCard, Method.POST, body, (data) {
return MobileServiceRedeemData.fromJson(data as Json);
});
}
Future<BaseResponseModel<RedeemProductResponseModel>> getMobileCardCode(String itemId) {
final token = DataPreference.instance.token ?? '';
final body = {'product_item_id': itemId, 'access_token': token};
return client.requestNormal(APIPaths.getMobileCardCode, Method.POST, body, (data) {
return RedeemProductResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<TopUpNetworkDataModel>>> getNetworkProducts(String brandId) {
final body = {
'brand_id': brandId,
'topup_type': 'PRODUCT_MODEL_MOBILE_SERVICE',
'page_size': '999',
'page_index': 0,
};
return client.requestNormal(APIPaths.getNetworkProducts, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => TopUpNetworkDataModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<EmptyCodable>> redeemProductTopUps(int productId, String phoneNumber) {
final token = DataPreference.instance.token ?? '';
final body = {
'access_token': token,
'product_id': productId,
'quantity': 1,
'phone_number': phoneNumber,
'lang': 'vi',
};
return client.requestNormal(APIPaths.redeemProductTopUps, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<MyVoucherResponse>> getMyMobileCards(MyProductStatusType status, Json body) {
final token = DataPreference.instance.token ?? '';
body['access_token'] = token;
body['product_model_code'] = 'PRODUCT_MODEL_MOBILE_CARD';
body['list_order'] = 'DESC';
var path = '';
switch (status) {
case MyProductStatusType.waiting:
path = APIPaths.getMyProductGetWaitingList;
case MyProductStatusType.used:
path = APIPaths.getMyProductGetUsedList;
case MyProductStatusType.expired:
path = APIPaths.getMyProductGetExpiredList;
}
return client.requestNormal(path, Method.POST, body, (data) {
return MyVoucherResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> myProductMarkAsUsed(String id) {
final token = DataPreference.instance.token ?? '';
final body = {'product_item_id': id, 'lang': 'vi', 'access_token': token};
return client.requestNormal(APIPaths.myProductMarkAsUsed, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> myProductMarkAsNotUsedYet(String id) {
final token = DataPreference.instance.token ?? '';
final body = {'product_item_id': id, 'lang': 'vi', 'access_token': token};
return client.requestNormal(APIPaths.myProductMarkAsNotUsedYet, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<TrafficServiceResponseModel>> getProductVnTraSold(Json body) {
return client.requestNormal(APIPaths.getProductVnTraSold, Method.GET, body, (data) {
return TrafficServiceResponseModel.fromJson(data as Json);
});
}
}
import '../../base/base_response_model.dart';
import '../../configs/api_paths.dart';
import '../../configs/callbacks.dart';
import '../../networking/restful_api_client.dart';
import '../../preference/data_preference.dart';
import '../../screen/faqs/faqs_model.dart';
import '../../screen/pageDetail/model/campaign_detail_model.dart';
import '../../screen/pageDetail/model/detail_page_rule_type.dart';
class WebsiteApi {
WebsiteApi(this.client);
final RestfulAPIClient client;
Future<BaseResponseModel<CampaignDetailResponseModel>> websitePageGetDetail(String id) {
final token = DataPreference.instance.token ?? '';
final body = {'website_page_id': id, 'access_token': token};
return client.requestNormal(
APIPaths.websitePageGetDetail,
Method.POST,
body,
(data) => CampaignDetailResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<CampaignDetailResponseModel>> websitePage(DetailPageRuleType rule) {
final body = {'code': rule.key};
return client.requestNormal(
APIPaths.websitePage,
Method.GET,
body,
(data) => CampaignDetailResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<FAQItemModelResponse>> websiteFolderGetPageList(Json body) {
return client.requestNormal(
APIPaths.websiteFolderGetPageList,
Method.POST,
body,
(data) => FAQItemModelResponse.fromJson(data as Json),
);
}
}
...@@ -20,6 +20,7 @@ class AuthInterceptor extends Interceptor { ...@@ -20,6 +20,7 @@ class AuthInterceptor extends Interceptor {
APIPaths.login, APIPaths.login,
APIPaths.refreshToken, APIPaths.refreshToken,
APIPaths.logout, APIPaths.logout,
APIPaths.deleteNotification,
'assets', 'assets',
]; ];
......
import 'dart:async'; import 'dart:async';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/base/app_loading.dart'; import 'package:mypoint_flutter_app/base/app_loading.dart';
import '../../base/app_navigator.dart'; import '../../base/app_navigator.dart';
import '../dio_http_service.dart'; import '../dio_http_service.dart';
...@@ -14,17 +15,17 @@ class ExceptionInterceptor extends Interceptor { ...@@ -14,17 +15,17 @@ class ExceptionInterceptor extends Interceptor {
final apiError = ErrorMapper.map(err); final apiError = ErrorMapper.map(err);
err.requestOptions.extra['mapped_error'] = apiError; err.requestOptions.extra['mapped_error'] = apiError;
// return handler.next(err); // return handler.next(err);
print('ExceptionInterceptor: onError: $apiError'); debugPrint('ExceptionInterceptor: onError: $apiError');
final extra = err.requestOptions.extra; final extra = err.requestOptions.extra;
final silent = extra['silent'] == true; final silent = extra['silent'] == true;
// Nếu không phải network error hoặc không thể retry -> forward // Nếu không phải network error hoặc không thể retry -> forward
if (!ErrorMapper.isNetworkError(err)) return handler.next(err); if (!ErrorMapper.isNetworkError(err)) return handler.next(err);
if (silent) return handler.next(err); if (silent) return handler.next(err);
print('ExceptionInterceptor: onError: $apiError'); debugPrint('ExceptionInterceptor: onError: $apiError');
// Chỉ cho phép retry với GET hoặc request được mark allow_retry // Chỉ cho phép retry với GET hoặc request được mark allow_retry
final allowRetry = _shouldAllowRetry(err.requestOptions); final allowRetry = _shouldAllowRetry(err.requestOptions);
if (!allowRetry) return handler.next(err); if (!allowRetry) return handler.next(err);
print('ExceptionInterceptor: onError: $_isPrompting'); debugPrint('ExceptionInterceptor: onError: $_isPrompting');
if (_isPrompting) return handler.next(err); if (_isPrompting) return handler.next(err);
_isPrompting = true; _isPrompting = true;
// ask user retry // ask user retry
......
import 'dart:convert'; import 'dart:convert';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:logger/logger.dart'; import 'package:logger/logger.dart';
......
...@@ -72,9 +72,7 @@ class RequestInterceptor extends Interceptor { ...@@ -72,9 +72,7 @@ class RequestInterceptor extends Interceptor {
} }
options.data = jsonEncode(body); options.data = jsonEncode(body);
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('⚠️ RequestInterceptor: failed to normalize JSON body - $e');
print('⚠️ RequestInterceptor: failed to normalize JSON body - $e');
}
} }
} }
} }
...@@ -118,8 +118,6 @@ class RestfulAPIClient { ...@@ -118,8 +118,6 @@ class RestfulAPIClient {
} }
void _debug(Object e) { void _debug(Object e) {
if (kDebugMode) { debugPrint('=== API DEBUG === $e');
print('=== API DEBUG === $e');
}
} }
} }
import 'dart:io'; import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/configs/api_paths.dart'; import 'package:mypoint_flutter_app/configs/api_paths.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/extensions/string_extension.dart'; import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client.dart'; import 'package:mypoint_flutter_app/networking/restful_api_client.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart'; import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/screen/game/models/game_bundle_response.dart';
import 'package:mypoint_flutter_app/screen/voucher/models/product_model.dart'; import 'package:mypoint_flutter_app/screen/voucher/models/product_model.dart';
import '../configs/callbacks.dart'; import '../configs/callbacks.dart';
import '../configs/device_info.dart'; import '../configs/device_info.dart';
...@@ -21,75 +19,58 @@ import '../screen/history_point/models/transaction_summary_by_date_model.dart'; ...@@ -21,75 +19,58 @@ import '../screen/history_point/models/transaction_summary_by_date_model.dart';
import '../screen/register_campaign/model/verify_register_model.dart'; import '../screen/register_campaign/model/verify_register_model.dart';
import '../screen/splash/models/update_response_model.dart'; import '../screen/splash/models/update_response_model.dart';
import '../preference/point/header_home_model.dart'; import '../preference/point/header_home_model.dart';
import '../screen/affiliate/model/affiliate_brand_model.dart';
import '../screen/affiliate/model/affiliate_category_model.dart';
import '../screen/affiliate/model/affiliate_product_top_sale_model.dart';
import '../screen/affiliate/model/cashback_overview_model.dart';
import '../screen/affiliate_brand_detail/models/affiliate_brand_detail_model.dart';
import '../screen/bank_account_manager/bank_account_info_model.dart'; import '../screen/bank_account_manager/bank_account_info_model.dart';
import '../screen/campaign7day/models/campaign_7day_info_model.dart'; import '../screen/campaign7day/models/campaign_7day_info_model.dart';
import '../screen/campaign7day/models/campaign_7day_mission_model.dart'; import '../screen/campaign7day/models/campaign_7day_mission_model.dart';
import '../screen/campaign7day/models/campaign_7day_reward_model.dart'; import '../screen/campaign7day/models/campaign_7day_reward_model.dart';
import '../screen/daily_checkin/daily_checkin_models.dart'; import '../screen/daily_checkin/daily_checkin_models.dart';
import '../screen/data_network_service/product_network_data_model.dart';
import '../screen/device_manager/device_manager_model.dart'; import '../screen/device_manager/device_manager_model.dart';
import '../screen/electric_payment/models/customer_contract_object_model.dart'; import '../screen/electric_payment/models/customer_contract_object_model.dart';
import '../screen/electric_payment/models/electric_payment_response_model.dart'; import '../screen/electric_payment/models/electric_payment_response_model.dart';
import '../screen/faqs/faqs_model.dart';
import '../screen/flash_sale/models/flash_sale_category_model.dart'; import '../screen/flash_sale/models/flash_sale_category_model.dart';
import '../screen/flash_sale/models/flash_sale_detail_response.dart'; import '../screen/flash_sale/models/flash_sale_detail_response.dart';
import '../screen/game/models/game_bundle_item_model.dart';
import '../screen/history_point_cashback/models/history_point_cashback_model.dart'; import '../screen/history_point_cashback/models/history_point_cashback_model.dart';
import '../screen/home/models/achievement_model.dart'; import '../screen/home/models/achievement_model.dart';
import '../screen/home/models/hover_data_model.dart'; import '../screen/home/models/hover_data_model.dart';
import '../screen/home/models/main_section_config_model.dart'; import '../screen/home/models/main_section_config_model.dart';
import '../screen/home/models/my_product_model.dart';
import '../screen/home/models/notification_unread_model.dart';
import '../screen/home/models/pipi_detail_model.dart'; import '../screen/home/models/pipi_detail_model.dart';
import '../screen/interested_categories/models/interested_categories_model.dart'; import '../screen/interested_categories/models/interested_categories_model.dart';
import '../screen/invite_friend_campaign/models/invite_friend_campaign_model.dart'; import '../screen/invite_friend_campaign/models/invite_friend_campaign_model.dart';
import '../screen/location_address/models/district_address_model.dart';
import '../screen/location_address/models/province_address_model.dart';
import '../screen/membership/models/membership_info_response.dart'; import '../screen/membership/models/membership_info_response.dart';
import '../screen/mobile_card/models/mobile_service_redeem_data.dart';
import '../screen/mobile_card/models/product_mobile_card_model.dart';
import '../screen/mobile_card/models/usable_voucher_model.dart';
import '../screen/notification/models/category_notify_item_model.dart';
import '../screen/notification/models/notification_detail_model.dart';
import '../screen/notification/models/notification_list_data_model.dart';
import '../screen/onboarding/model/check_phone_response_model.dart'; import '../screen/onboarding/model/check_phone_response_model.dart';
import '../screen/onboarding/model/onboarding_info_model.dart'; import '../screen/onboarding/model/onboarding_info_model.dart';
import '../screen/otp/model/create_otp_response_model.dart'; import '../screen/otp/model/create_otp_response_model.dart';
import '../screen/otp/model/otp_verify_response_model.dart'; import '../screen/otp/model/otp_verify_response_model.dart';
import '../screen/pageDetail/model/campaign_detail_model.dart';
import '../screen/pageDetail/model/detail_page_rule_type.dart';
import '../screen/popup_manager/popup_manager_model.dart'; import '../screen/popup_manager/popup_manager_model.dart';
import '../screen/quiz_campaign/quiz_campaign_model.dart'; import '../screen/quiz_campaign/quiz_campaign_model.dart';
import '../screen/register_campaign/model/registration_form_package_model.dart'; import '../screen/register_campaign/model/registration_form_package_model.dart';
import '../screen/topup/models/brand_network_model.dart';
import '../screen/traffic_service/traffic_service_model.dart'; import '../screen/traffic_service/traffic_service_model.dart';
import '../screen/transaction/history/transaction_category_model.dart'; import '../screen/transaction/history/transaction_category_model.dart';
import '../screen/transaction/history/transaction_history_model.dart'; import '../screen/transaction/history/transaction_history_model.dart';
import '../screen/transaction/history/transaction_history_response_model.dart'; import '../screen/transaction/history/transaction_history_response_model.dart';
import '../screen/transaction/model/order_product_payment_response_model.dart'; export 'api/affiliate_api.dart';
import '../screen/transaction/model/payment_bank_account_info_model.dart'; export 'api/website_api.dart';
import '../screen/transaction/model/payment_method_model.dart'; export 'api/notification_api.dart';
import '../screen/transaction/model/preview_order_payment_model.dart'; export 'api/location_api.dart';
import '../screen/voucher/models/like_product_response_model.dart'; export 'api/product_api.dart';
import '../screen/voucher/models/my_mobile_card_response.dart';
import '../screen/voucher/models/my_product_status_type.dart';
import '../screen/voucher/models/product_brand_model.dart';
import '../screen/voucher/models/product_store_model.dart';
import '../screen/voucher/models/product_type.dart';
import '../screen/voucher/models/search_product_response_model.dart';
extension RestfulAPIClientAllRequest on RestfulAPIClient { extension RestfulAPIClientAllRequest on RestfulAPIClient {
Future<BaseResponseModel<UpdateResponseModel>> checkUpdateApp() async { Future<BaseResponseModel<UpdateResponseModel>> checkUpdateApp() async {
final operatingSystem = Platform.operatingSystem; final operatingSystem = Platform.operatingSystem;
final version = await AppInfoHelper.version; final version = await AppInfoHelper.version;
final buildNumber = await AppInfoHelper.buildNumber; final buildNumber = await AppInfoHelper.buildNumber;
final body = {"operating_system": operatingSystem, "software_model": "MyPoint", "version": version, "build_number": buildNumber}; final body = {
return requestNormal(APIPaths.checkUpdate, Method.POST, body, (data) => UpdateResponseModel.fromJson(data as Json)); "operating_system": operatingSystem,
"software_model": "MyPoint",
"version": version,
"build_number": buildNumber,
};
return requestNormal(
APIPaths.checkUpdate,
Method.POST,
body,
(data) => UpdateResponseModel.fromJson(data as Json),
);
} }
Future<BaseResponseModel<OnboardingInfoModel>> getOnboardingInfo() async { Future<BaseResponseModel<OnboardingInfoModel>> getOnboardingInfo() async {
...@@ -101,10 +82,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -101,10 +82,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<CheckPhoneResponseModel>> checkPhoneNumber(String phone) async { Future<BaseResponseModel<CheckPhoneResponseModel>> checkPhoneNumber(
String phone,
) async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
var key = "$phone+_=$deviceKey/*8854"; var key = "$phone+_=$deviceKey/*8854";
final body = {"device_key": deviceKey, "phone_number": phone, "key": key.toSha256()}; final body = {
"device_key": deviceKey,
"phone_number": phone,
"key": key.toSha256(),
};
return requestNormal( return requestNormal(
APIPaths.checkPhoneNumber, APIPaths.checkPhoneNumber,
Method.POST, Method.POST,
...@@ -113,7 +100,10 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -113,7 +100,10 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<OTPVerifyResponseModel>> verifyOTP(String otp, String mfaToken) async { Future<BaseResponseModel<OTPVerifyResponseModel>> verifyOTP(
String otp,
String mfaToken,
) async {
final body = {"otp": otp, "mfaToken": mfaToken}; final body = {"otp": otp, "mfaToken": mfaToken};
return requestNormal( return requestNormal(
APIPaths.verifyOtpWithAction, APIPaths.verifyOtpWithAction,
...@@ -123,7 +113,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -123,7 +113,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<OTPResendResponseModel>> resendOTP(String mfaToken) async { Future<BaseResponseModel<OTPResendResponseModel>> resendOTP(
String mfaToken,
) async {
final body = {"mfaToken": mfaToken}; final body = {"mfaToken": mfaToken};
return requestNormal( return requestNormal(
APIPaths.retryOtpWithAction, APIPaths.retryOtpWithAction,
...@@ -133,7 +125,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -133,7 +125,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<CreateOTPResponseModel>> requestOtpDeleteAccount() async { Future<BaseResponseModel<CreateOTPResponseModel>>
requestOtpDeleteAccount() async {
return requestNormal( return requestNormal(
APIPaths.otpDeleteAccountRequest, APIPaths.otpDeleteAccountRequest,
Method.POST, Method.POST,
...@@ -142,19 +135,39 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -142,19 +135,39 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<CreateOTPResponseModel>> verifyDeleteAccount(String otp) async { Future<BaseResponseModel<CreateOTPResponseModel>> verifyDeleteAccount(
return requestNormal(APIPaths.verifyDeleteAccount, Method.POST, { String otp,
"otp": otp, ) async {
}, (data) => CreateOTPResponseModel.fromJson(data as Json)); return requestNormal(
APIPaths.verifyDeleteAccount,
Method.POST,
{"otp": otp},
(data) => CreateOTPResponseModel.fromJson(data as Json),
);
} }
Future<BaseResponseModel<EmptyCodable>> signup(String phone, String password) async { Future<BaseResponseModel<EmptyCodable>> signup(
String phone,
String password,
) async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final body = {"username": phone, "password": password.toSha256(), "device_key": deviceKey}; final body = {
return requestNormal(APIPaths.signup, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json)); "username": phone,
"password": password.toSha256(),
"device_key": deviceKey,
};
return requestNormal(
APIPaths.signup,
Method.POST,
body,
(data) => EmptyCodable.fromJson(data as Json),
);
} }
Future<BaseResponseModel<LoginTokenResponseModel>> login(String phone, String password) async { Future<BaseResponseModel<LoginTokenResponseModel>> login(
String phone,
String password,
) async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final body = { final body = {
"username": phone, "username": phone,
...@@ -162,24 +175,37 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -162,24 +175,37 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
"device_key": deviceKey, "device_key": deviceKey,
"workspace_code": "8854", "workspace_code": "8854",
}; };
return requestNormal(APIPaths.login, Method.POST, body, (data) => LoginTokenResponseModel.fromJson(data as Json)); return requestNormal(
APIPaths.login,
Method.POST,
body,
(data) => LoginTokenResponseModel.fromJson(data as Json),
);
} }
Future<BaseResponseModel<EmptyCodable>> logout() async { Future<BaseResponseModel<EmptyCodable>> logout() async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
var phone = DataPreference.instance.phone ?? ""; var phone = DataPreference.instance.phone ?? "";
final body = { final body = {"username": phone, "device_key": deviceKey, "lang": "vi"};
"username": phone, return requestNormal(
"device_key": deviceKey, APIPaths.logout,
"lang": "vi", Method.POST,
}; body,
return requestNormal(APIPaths.logout, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json)); (data) => EmptyCodable.fromJson(data as Json),
);
} }
Future<BaseResponseModel<LoginTokenResponseModel>> loginWithBiometric(String phone) async { Future<BaseResponseModel<LoginTokenResponseModel>> loginWithBiometric(
String phone,
) async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
var bioToken = await DataPreference.instance.getBioToken(phone) ?? ""; var bioToken = await DataPreference.instance.getBioToken(phone) ?? "";
final body = {"username": phone, "bioToken": bioToken, "deviceKey": deviceKey, "workspaceCode": "8854"}; final body = {
"username": phone,
"bioToken": bioToken,
"deviceKey": deviceKey,
"workspaceCode": "8854",
};
return requestNormal( return requestNormal(
APIPaths.loginWithBiometric, APIPaths.loginWithBiometric,
Method.POST, Method.POST,
...@@ -189,7 +215,12 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -189,7 +215,12 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
} }
Future<BaseResponseModel<ProfileResponseModel>> getUserProfile() async { Future<BaseResponseModel<ProfileResponseModel>> getUserProfile() async {
return requestNormal(APIPaths.getUserInfo, Method.GET, {}, (data) => ProfileResponseModel.fromJson(data as Json)); return requestNormal(
APIPaths.getUserInfo,
Method.GET,
{},
(data) => ProfileResponseModel.fromJson(data as Json),
);
} }
Future<BaseResponseModel<TokenRefreshResponseModel>> refreshToken() async { Future<BaseResponseModel<TokenRefreshResponseModel>> refreshToken() async {
...@@ -200,11 +231,23 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -200,11 +231,23 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
"refresh_token": refreshToken, "refresh_token": refreshToken,
'lang': 'vi', 'lang': 'vi',
}; };
return requestNormal(APIPaths.refreshToken, Method.POST, body, (data) => TokenRefreshResponseModel.fromJson(data as Json)); return requestNormal(
APIPaths.refreshToken,
Method.POST,
body,
(data) => TokenRefreshResponseModel.fromJson(data as Json),
);
} }
Future<BaseResponseModel<CreateOTPResponseModel>> otpCreateNew(String ownerId) async { Future<BaseResponseModel<CreateOTPResponseModel>> otpCreateNew(
final body = {"owner_id": ownerId, "ttl": Constants.otpTtl, "resend_after_second": Constants.otpTtl, 'lang': 'vi'}; String ownerId,
) async {
final body = {
"owner_id": ownerId,
"ttl": Constants.otpTtl,
"resend_after_second": Constants.otpTtl,
'lang': 'vi',
};
return requestNormal( return requestNormal(
APIPaths.otpCreateNew, APIPaths.otpCreateNew,
Method.POST, Method.POST,
...@@ -233,37 +276,10 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -233,37 +276,10 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<CampaignDetailResponseModel>> websitePageGetDetail(String id) async { Future<BaseResponseModel<EmptyCodable>> accountPasswordReset(
String? token = DataPreference.instance.token ?? ""; String phone,
final body = {"website_page_id": id, "access_token": token}; String password,
return requestNormal( ) async {
APIPaths.websitePageGetDetail,
Method.POST,
body,
(data) => CampaignDetailResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<CampaignDetailResponseModel>> websitePage(DetailPageRuleType rule) async {
final body = {"code": rule.key};
return requestNormal(
APIPaths.websitePage,
Method.GET,
body,
(data) => CampaignDetailResponseModel.fromJson(data as Json),
);
}
Future<BaseResponseModel<FAQItemModelResponse>> websiteFolderGetPageList(Json body) async {
return requestNormal(
APIPaths.websiteFolderGetPageList,
Method.POST,
body,
(data) => FAQItemModelResponse.fromJson(data as Json),
);
}
Future<BaseResponseModel<EmptyCodable>> accountPasswordReset(String phone, String password) async {
final body = {"login_name": phone, "password": password.toSha256()}; final body = {"login_name": phone, "password": password.toSha256()};
return requestNormal( return requestNormal(
APIPaths.accountPasswordReset, APIPaths.accountPasswordReset,
...@@ -273,9 +289,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -273,9 +289,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<EmptyCodable>> accountPasswordChange(String phone, String password) async { Future<BaseResponseModel<EmptyCodable>> accountPasswordChange(
String phone,
String password,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"login_name": phone, "password": password.toSha256(), "access_token": token}; final body = {
"login_name": phone,
"password": password.toSha256(),
"access_token": token,
};
return requestNormal( return requestNormal(
APIPaths.accountPasswordChange, APIPaths.accountPasswordChange,
Method.POST, Method.POST,
...@@ -284,9 +307,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -284,9 +307,16 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<EmptyCodable>> accountLoginForPasswordChange(String phone, String password) async { Future<BaseResponseModel<EmptyCodable>> accountLoginForPasswordChange(
String phone,
String password,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"login_name": phone, "password": password.toSha256(), "access_token": token}; final body = {
"login_name": phone,
"password": password.toSha256(),
"access_token": token,
};
return requestNormal( return requestNormal(
APIPaths.accountLoginForPasswordChange, APIPaths.accountLoginForPasswordChange,
Method.POST, Method.POST,
...@@ -295,7 +325,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -295,7 +325,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<BiometricRegisterResponseModel>> accountBioCredential() async { Future<BaseResponseModel<BiometricRegisterResponseModel>>
accountBioCredential() async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final body = {"deviceKey": deviceKey}; final body = {"deviceKey": deviceKey};
return requestNormal( return requestNormal(
...@@ -306,7 +337,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -306,7 +337,8 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
); );
} }
Future<BaseResponseModel<BiometricRegisterResponseModel>> registerBiometric() async { Future<BaseResponseModel<BiometricRegisterResponseModel>>
registerBiometric() async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final body = {"deviceKey": deviceKey}; final body = {"deviceKey": deviceKey};
return requestNormal( return requestNormal(
...@@ -321,257 +353,41 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -321,257 +353,41 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final path = "${APIPaths.unRegisterBiometric}/$deviceKey"; final path = "${APIPaths.unRegisterBiometric}/$deviceKey";
final body = {"deviceKey": deviceKey}; final body = {"deviceKey": deviceKey};
return requestNormal(path, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
}
Future<BaseResponseModel<HeaderHomeModel>> getHomeHeaderData() async {
return requestNormal(APIPaths.headerHome, Method.GET, {}, (data) => HeaderHomeModel.fromJson(data as Json));
}
Future<BaseResponseModel<List<ProductModel>>> getProducts(Json body) async {
return requestNormal(APIPaths.getProducts, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<SearchProductResponseModel>> getSearchProducts(Json body) async {
return requestNormal( return requestNormal(
APIPaths.getSearchProducts, path,
Method.POST, Method.POST,
body, body,
(data) => SearchProductResponseModel.fromJson(data as Json), (data) => EmptyCodable.fromJson(data as Json),
); );
} }
Future<BaseResponseModel<List<ProductModel>>> productsCustomerLikes(Json body) async { Future<BaseResponseModel<HeaderHomeModel>> getHomeHeaderData() async {
return requestNormal(APIPaths.productsCustomerLikes, Method.GET, body, (data) { return requestNormal(
final list = data as List<dynamic>; APIPaths.headerHome,
return list.map((e) => ProductModel.fromJson(e)).toList(); Method.GET,
}); {},
} (data) => HeaderHomeModel.fromJson(data as Json),
);
Future<BaseResponseModel<ProductModel>> getProduct(int id) async {
final path = APIPaths.getProductDetail.replaceAll("%@", id.toString());
return requestNormal(path, Method.GET, {}, (data) => ProductModel.fromJson(data as Json));
}
Future<BaseResponseModel<ProductModel>> getCustomerProductDetail(int id) async {
final path = APIPaths.getCustomerProductDetail.replaceAll("%@", id.toString());
return requestNormal(path, Method.GET, {}, (data) => ProductModel.fromJson(data as Json));
}
Future<BaseResponseModel<List<ProductStoreModel>>> getProductStores(int id) async {
final body = {"product_id": id, "size": 20, "index": 0};
return requestNormal(APIPaths.getProductStores, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductStoreModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<LikeProductResponseModel>> likeProduct(int id) async {
final body = {"product_id": id};
return requestNormal(APIPaths.productCustomerLikes, Method.POST, body, (data) {
return LikeProductResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> unlikeProduct(int id) async {
final path = APIPaths.productCustomerUnlikes.replaceAll("%@", id.toString());
return requestNormal(path, Method.DELETE, {}, (data) => EmptyCodable.fromJson(data as Json));
}
Future<BaseResponseModel<GameBundleResponse>> getGames() async {
return requestNormal(APIPaths.getGames, Method.GET, {}, (data) {
return GameBundleResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<EmptyCodable>>> verifyOrderProduct(Json body) async {
return requestNormal(APIPaths.verifyOrderProduct, Method.POST, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => EmptyCodable.fromJson(e)).toList();
});
}
Future<BaseResponseModel<GameBundleItemModel>> getGameDetail(String id) async {
final path = APIPaths.getGameDetail.replaceAll("%@", id);
return requestNormal(path, Method.POST, {}, (data) {
return GameBundleItemModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<GameBundleItemModel>> submitGameCard(String gameId, String itemId) async {
final path = APIPaths.submitGameCard.replaceFirst("%@", gameId).replaceFirst("%@", itemId);
return requestNormal(path, Method.POST, {}, (data) {
return GameBundleItemModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<AffiliateCategoryModel>>> affiliateCategoryGetList() async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return requestNormal(APIPaths.affiliateCategoryGetList, Method.POST, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => AffiliateCategoryModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<AffiliateBrandModel>>> affiliateBrandGetList({String? categoryCode}) async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
if ((categoryCode ?? '').isNotEmpty) {
body['category_code'] = categoryCode!;
}
return requestNormal(APIPaths.affiliateBrandGetList, Method.POST, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => AffiliateBrandModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<AffiliateProductTopSaleModel>>> affiliateProductTopSale() async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return requestNormal(APIPaths.affiliateProductTopSale, Method.POST, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => AffiliateProductTopSaleModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<CashbackOverviewModel>> getCashBackOverview() async {
return requestNormal(APIPaths.getCashbackOverview, Method.GET, {}, (data) {
return CashbackOverviewModel.fromJson(data as Json);
});
} }
Future<BaseResponseModel<RegistrationFormPackageModel>> getRegistrationForm(String id) async { Future<BaseResponseModel<RegistrationFormPackageModel>> getRegistrationForm(
String id,
) async {
final path = APIPaths.getRegistrationForm.replaceAll("%@", id); final path = APIPaths.getRegistrationForm.replaceAll("%@", id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return RegistrationFormPackageModel.fromJson(data as Json); return RegistrationFormPackageModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<PreviewOrderPaymentModel>> getPreviewOrderInfo(Json body) async { Future<BaseResponseModel<TransactionHistoryModel>> getTransactionHistoryDetail(
return requestNormal(APIPaths.getPreviewOrderInfo, Method.POST, body, (data) { String id,
return PreviewOrderPaymentModel.fromJson(data as Json); ) async {
});
}
Future<BaseResponseModel<List<PaymentBankAccountInfoModel>>> getPreviewOrderBankAccounts() async {
return requestNormal(APIPaths.getPreviewOrderBankAccounts, Method.GET, {}, (data) {
final list = data as List<dynamic>;
return list.map((e) => PaymentBankAccountInfoModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<PaymentMethodModel>>> getPreviewPaymentMethods() async {
return requestNormal(APIPaths.getPreviewPaymentMethods, Method.GET, {}, (data) {
final list = data as List<dynamic>;
return list.map((e) => PaymentMethodModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<CategoryNotifyItemModel>>> getNotificationCategories() async {
return requestNormal(APIPaths.getNotificationCategories, Method.GET, {}, (data) {
final list = data as List<dynamic>;
return list.map((e) => CategoryNotifyItemModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<NotificationListDataModel>> getNotifications(Json body) async {
return requestNormal(APIPaths.getNotifications, Method.POST, body, (data) {
return NotificationListDataModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> deleteNotification(String id) async {
return requestNormal(APIPaths.deleteNotification, Method.POST, {"notification_id__": id}, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> deleteAllNotifications() async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return requestNormal(APIPaths.deleteAllNotifications, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> notificationMarkAsSeen() async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return requestNormal(APIPaths.notificationMarkAsSeen, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<NotificationDetailResponseModel>> getNotificationDetail(String id) async {
String? token = DataPreference.instance.token ?? "";
final body = {"notification_id": id, "mark_as_seen": "1", "access_token": token};
return requestNormal(APIPaths.notificationGetDetail, Method.POST, body, (data) {
return NotificationDetailResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<TransactionHistoryModel>> getTransactionHistoryDetail(String id) async {
final path = APIPaths.getTransactionHistoryDetail.replaceAll("%@", id); final path = APIPaths.getTransactionHistoryDetail.replaceAll("%@", id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return TransactionHistoryModel.fromJson(data as Json); return TransactionHistoryModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<OrderProductPaymentResponseModel>> orderSubmitPayment({
required List<ProductModel> products,
required int quantity,
required String requestId,
int? point,
int? cash,
PaymentMethodModel? method,
int? paymentTokenId,
bool? saveToken,
String? metadata,
String? targetPhoneNumber,
}) async {
final items =
products.map((product) {
return {
'product_id': product.id,
'product_type': product.type ?? '',
'quantity': quantity,
'target_phone_number': targetPhoneNumber ?? '',
};
}).toList();
final Map<String, dynamic> params = {'request_id': requestId, 'items': items, 'flow': '21'};
// flash_sale
final firstProduct = products.first;
if (firstProduct.previewFlashSale?.isFlashSalePrice == true && firstProduct.previewFlashSale?.id != null) {
params['flash_sale_id'] = firstProduct.previewFlashSale!.id;
}
// Optional parameters
if (method != null) {
params['payment_method'] = method.code;
}
if (point != null && point != 0) {
params['pay_point'] = point;
}
if (cash != null && cash != 0) {
params['pay_cash'] = cash;
}
if (paymentTokenId != null) {
params['payment_token_id'] = paymentTokenId;
}
if (saveToken != null) {
params['save_token'] = saveToken;
}
if (metadata != null) {
params['metadata'] = metadata;
}
return requestNormal(APIPaths.orderSubmitPayment, Method.POST, params, (data) {
return OrderProductPaymentResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<PipiDetailResponseModel>> getPipiDetail() async { Future<BaseResponseModel<PipiDetailResponseModel>> getPipiDetail() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token}; final body = {"access_token": token};
...@@ -580,15 +396,20 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -580,15 +396,20 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<List<MainSectionConfigModel>>> getSectionLayoutHome() async { Future<BaseResponseModel<List<MainSectionConfigModel>>>
getSectionLayoutHome() async {
return requestNormal(APIPaths.getSectionLayoutHome, Method.GET, {}, (data) { return requestNormal(APIPaths.getSectionLayoutHome, Method.GET, {}, (data) {
final list = data as List<dynamic>; final list = data as List<dynamic>;
return list.map((e) => MainSectionConfigModel.fromJson(e)).toList(); return list.map((e) => MainSectionConfigModel.fromJson(e)).toList();
}); });
} }
Future<BaseResponseModel<AchievementListResponse>> getAchievementList(Json body) async { Future<BaseResponseModel<AchievementListResponse>> getAchievementList(
return requestNormal(APIPaths.achievementGetList, Method.POST, body, (data) { Json body,
) async {
return requestNormal(APIPaths.achievementGetList, Method.POST, body, (
data,
) {
return AchievementListResponse.fromJson(data as Json); return AchievementListResponse.fromJson(data as Json);
}); });
} }
...@@ -599,161 +420,71 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -599,161 +420,71 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<NotificationUnreadData>> getNotificationUnread() async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token};
return requestNormal(APIPaths.getNotificationUnread, Method.POST, body, (data) {
return NotificationUnreadData.fromJson(data as Json);
});
}
Future<BaseResponseModel<HeaderHomeModel>> getDynamicHeaderHome() async { Future<BaseResponseModel<HeaderHomeModel>> getDynamicHeaderHome() async {
return requestNormal(APIPaths.getDynamicHeaderHome, Method.GET, {}, (data) { return requestNormal(APIPaths.getDynamicHeaderHome, Method.GET, {}, (data) {
return HeaderHomeModel.fromJson(data as Json); return HeaderHomeModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<List<MyProductModel>>> getCustomerProducts(Json body) async { Future<BaseResponseModel<EmptyCodable>> updateWorkerSiteProfile(
return requestNormal(APIPaths.getCustomerProducts, Method.GET, body, (data) { Json body,
final list = data as List<dynamic>; ) async {
return list.map((e) => MyProductModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<EmptyCodable>> updateWorkerSiteProfile(Json body) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
body["access_token"] = token; body["access_token"] = token;
return requestNormal(APIPaths.updateWorkerSiteProfile, Method.POST, body, (data) { return requestNormal(APIPaths.updateWorkerSiteProfile, Method.POST, body, (
data,
) {
return EmptyCodable.fromJson(data as Json); return EmptyCodable.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<ProvinceAddressResponse>> locationProvinceGetList() async { Future<BaseResponseModel<MembershipInfoResponse>>
String? token = DataPreference.instance.token ?? ""; getMembershipLevelInfo() async {
final body = {"access_token": token, "country_code2": "VN"};
return requestNormal(APIPaths.locationProvinceGetList, Method.POST, body, (data) {
return ProvinceAddressResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<DistrictAddressResponse>> locationDistrictGetList(String provinceCode) async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "province_code": provinceCode};
return requestNormal(APIPaths.locationDistrictGetList, Method.POST, body, (data) {
return DistrictAddressResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<MembershipInfoResponse>> getMembershipLevelInfo() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "lang": "vi"}; final body = {"access_token": token, "lang": "vi"};
return requestNormal(APIPaths.getMembershipLevelInfo, Method.POST, body, (data) { return requestNormal(APIPaths.getMembershipLevelInfo, Method.POST, body, (
data,
) {
return MembershipInfoResponse.fromJson(data as Json); return MembershipInfoResponse.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<List<ProductBrandModel>>> getTopUpBrands(ProductType type) async { Future<BaseResponseModel<HistoryPointCashBackResponse>>
final body = {"type": type.value}; historyPointCashBackRequest(Json body) async {
return requestNormal(APIPaths.getTopUpBrands, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductBrandModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<List<ProductBrandModel>>> productTopUpBrands() async {
final body = {"topup_type": "PRODUCT_MODEL_MOBILE_SERVICE", "page_size": "999", "page_index": 0};
return requestNormal(APIPaths.productTopUpsBrands, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => ProductBrandModel.fromJson(e)).toList();
});
}
// productTopUpsBrands
Future<BaseResponseModel<BrandNameCheckResponse>> checkMobileNetwork(String phone) async {
final body = {"phone": phone};
return requestNormal(APIPaths.checkMobileNetwork, Method.GET, body, (data) {
return BrandNameCheckResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<ProductMobileCardResponse>> productMobileCardGetList() async {
String? token = DataPreference.instance.token ?? "";
final body = {"start": 0, "limit": 200, "access_token": token};
return requestNormal(APIPaths.productMobileCardGetList, Method.POST, body, (data) {
return ProductMobileCardResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<MobileServiceRedeemData>> redeemMobileCard(String productId) async {
String? token = DataPreference.instance.token ?? "";
final body = {"product_id": productId, "get_customer_balance": "1", "access_token": token};
return requestNormal(APIPaths.redeemMobileCard, Method.POST, body, (data) {
return MobileServiceRedeemData.fromJson(data as Json);
});
}
Future<BaseResponseModel<RedeemProductResponseModel>> getMobileCardCode(String itemId) async {
String? token = DataPreference.instance.token ?? "";
final body = {"product_item_id": itemId, "access_token": token};
return requestNormal(APIPaths.getMobileCardCode, Method.POST, body, (data) {
return RedeemProductResponseModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<TopUpNetworkDataModel>>> getNetworkProducts(String brandId) async {
final body = {
"brand_id": brandId,
"topup_type": "PRODUCT_MODEL_MOBILE_SERVICE",
"page_size": "999",
"page_index": 0,
};
return requestNormal(APIPaths.getNetworkProducts, Method.GET, body, (data) {
final list = data as List<dynamic>;
return list.map((e) => TopUpNetworkDataModel.fromJson(e)).toList();
});
}
Future<BaseResponseModel<EmptyCodable>> redeemProductTopUps(int productId, String phoneNumber) async {
String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "product_id": productId, "quantity": 1, "phone_number": phoneNumber, "lang": "vi"};
return requestNormal(APIPaths.redeemProductTopUps, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<HistoryPointCashBackResponse>> historyPointCashBackRequest(Json body) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
body["access_token"] = token; body["access_token"] = token;
return requestNormal(APIPaths.historyCashBackPoint, Method.GET, body, (data) { return requestNormal(APIPaths.historyCashBackPoint, Method.GET, body, (
data,
) {
return HistoryPointCashBackResponse.fromJson(data as Json); return HistoryPointCashBackResponse.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<AffiliateBrandDetailModel>> getAffiliateBrandDetail(String brandId) async { Future<BaseResponseModel<InviteFriendDetailModel>>
String? token = DataPreference.instance.token ?? ""; getCampaignInviteFriend() async {
final body = {"access_token": token, "brand_id": brandId};
return requestNormal(APIPaths.affiliateBrandGetDetail, Method.POST, body, (data) {
return AffiliateBrandDetailModel.fromJson(data as Json);
});
}
Future<BaseResponseModel<InviteFriendDetailModel>> getCampaignInviteFriend() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token}; final body = {"access_token": token};
return requestNormal(APIPaths.campaignInviteFriend, Method.GET, body, (data) { return requestNormal(APIPaths.campaignInviteFriend, Method.GET, body, (
data,
) {
return InviteFriendDetailModel.fromJson(data as Json); return InviteFriendDetailModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<CampaignInviteFriendDetail>> getDetailCampaignInviteFriend() async { Future<BaseResponseModel<CampaignInviteFriendDetail>>
getDetailCampaignInviteFriend() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token}; final body = {"access_token": token};
return requestNormal(APIPaths.inviteFriendCampaigns, Method.GET, body, (data) { return requestNormal(APIPaths.inviteFriendCampaigns, Method.GET, body, (
data,
) {
return CampaignInviteFriendDetail.fromJson(data as Json); return CampaignInviteFriendDetail.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<InviteFriendResponse>> phoneInviteFriend(String phone) async { Future<BaseResponseModel<InviteFriendResponse>> phoneInviteFriend(
String phone,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'username': phone}; final body = {"access_token": token, 'username': phone};
return requestNormal(APIPaths.phoneInviteFriend, Method.POST, body, (data) { return requestNormal(APIPaths.phoneInviteFriend, Method.POST, body, (data) {
...@@ -764,7 +495,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -764,7 +495,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
Future<BaseResponseModel<CheckInDataModel>> rewardOpportunityGetList() async { Future<BaseResponseModel<CheckInDataModel>> rewardOpportunityGetList() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'number_day': '7'}; final body = {"access_token": token, 'number_day': '7'};
return requestNormal(APIPaths.rewardOpportunityGetList, Method.POST, body, (data) { return requestNormal(APIPaths.rewardOpportunityGetList, Method.POST, body, (
data,
) {
return CheckInDataModel.fromJson(data as Json); return CheckInDataModel.fromJson(data as Json);
}); });
} }
...@@ -772,84 +505,119 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -772,84 +505,119 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
Future<BaseResponseModel<SubmitCheckInData>> submitCheckIn() async { Future<BaseResponseModel<SubmitCheckInData>> submitCheckIn() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token}; final body = {"access_token": token};
return requestNormal(APIPaths.rewardOpportunityOpenRequest, Method.POST, body, (data) { return requestNormal(
return SubmitCheckInData.fromJson(data as Json); APIPaths.rewardOpportunityOpenRequest,
}); Method.POST,
body,
(data) {
return SubmitCheckInData.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<TransactionHistoryResponse>> getTransactionHistoryResponse(Json body) async { Future<BaseResponseModel<TransactionHistoryResponse>>
return requestNormal(APIPaths.getTransactionOrderHistory, Method.GET, body, (data) { getTransactionHistoryResponse(Json body) async {
return TransactionHistoryResponse.fromJson(data as Json); return requestNormal(
}); APIPaths.getTransactionOrderHistory,
Method.GET,
body,
(data) {
return TransactionHistoryResponse.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<List<TransactionCategoryModel>>> getTransactionHistoryCategories() async { Future<BaseResponseModel<List<TransactionCategoryModel>>>
return requestNormal(APIPaths.orderHistoryCategories, Method.GET, {}, (data) { getTransactionHistoryCategories() async {
return requestNormal(APIPaths.orderHistoryCategories, Method.GET, {}, (
data,
) {
final list = data as List<dynamic>; final list = data as List<dynamic>;
return list.map((e) => TransactionCategoryModel.fromJson(e)).toList(); return list.map((e) => TransactionCategoryModel.fromJson(e)).toList();
}); });
} }
Future<BaseResponseModel<CustomerContractModel>> customerContractRequestSearch(String maKH) async { Future<BaseResponseModel<CustomerContractModel>>
customerContractRequestSearch(String maKH) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'ma_khang': maKH}; final body = {"access_token": token, 'ma_khang': maKH};
return requestNormal(APIPaths.customerContractRequestSearch, Method.POST, body, (data) { return requestNormal(
return CustomerContractModel.fromJson(data as Json); APIPaths.customerContractRequestSearch,
}); Method.POST,
body,
(data) {
return CustomerContractModel.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<List<CustomerContractModel>>> customerContractSearchHistoryGetList() async { Future<BaseResponseModel<List<CustomerContractModel>>>
customerContractSearchHistoryGetList() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token}; final body = {"access_token": token};
return requestNormal(APIPaths.customerContractSearchHistoryGetList, Method.POST, body, (data) { return requestNormal(
final list = data as List<dynamic>; APIPaths.customerContractSearchHistoryGetList,
return list.map((e) => CustomerContractModel.fromJson(e)).toList(); Method.POST,
}); body,
(data) {
final list = data as List<dynamic>;
return list.map((e) => CustomerContractModel.fromJson(e)).toList();
},
);
} }
Future<BaseResponseModel<bool>> customerContractDelete(String maKHs) async { Future<BaseResponseModel<bool>> customerContractDelete(String maKHs) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'ma_khang': maKHs}; final body = {"access_token": token, 'ma_khang': maKHs};
return requestNormal(APIPaths.customerContractDelete, Method.POST, body, (data) { return requestNormal(APIPaths.customerContractDelete, Method.POST, body, (
data,
) {
return data == true; return data == true;
}); });
} }
Future<BaseResponseModel<HealthBookResponseModel>> getHealthBookCards(Json body) async { Future<BaseResponseModel<HealthBookResponseModel>> getHealthBookCards(
Json body,
) async {
return requestNormal(APIPaths.getHealthBookCards, Method.GET, body, (data) { return requestNormal(APIPaths.getHealthBookCards, Method.GET, body, (data) {
return HealthBookResponseModel.fromJson(data as Json); return HealthBookResponseModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<HealthBookCardItemModel>> getDetailHealthBookCard(String id) async { Future<BaseResponseModel<HealthBookCardItemModel>> getDetailHealthBookCard(
String id,
) async {
final path = APIPaths.detailHealthBookCardDetail.replaceAll("%@", id); final path = APIPaths.detailHealthBookCardDetail.replaceAll("%@", id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return HealthBookCardItemModel.fromJson(data as Json); return HealthBookCardItemModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<TrafficServiceResponseModel>> getProductVnTraSold(Json body) async { Future<BaseResponseModel<TrafficServiceDetailModel>> getDetailMyPackageVnTra(
return requestNormal(APIPaths.getProductVnTraSold, Method.GET, body, (data) { String id,
return TrafficServiceResponseModel.fromJson(data as Json); ) async {
});
}
Future<BaseResponseModel<TrafficServiceDetailModel>> getDetailMyPackageVnTra(String id) async {
final path = APIPaths.detailMyPackageVnTra.replaceAll("%@", id); final path = APIPaths.detailMyPackageVnTra.replaceAll("%@", id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return TrafficServiceDetailModel.fromJson(data as Json); return TrafficServiceDetailModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<EmptyCodable>> submitPerformMission(Campaign7DayMissionModel mission, String id) async { Future<BaseResponseModel<EmptyCodable>> submitPerformMission(
final path = APIPaths.submitCampaignMission.replaceFirst('%@', id).replaceFirst('%@', mission.id.toString()); Campaign7DayMissionModel mission,
String id,
) async {
final path = APIPaths.submitCampaignMission
.replaceFirst('%@', id)
.replaceFirst('%@', mission.id.toString());
return requestNormal(path, Method.POST, {}, (data) { return requestNormal(path, Method.POST, {}, (data) {
return EmptyCodable.fromJson(data as Json); return EmptyCodable.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<List<Campaign7DayRewardModel>>> getCampaignRewards(String id) async { Future<BaseResponseModel<List<Campaign7DayRewardModel>>> getCampaignRewards(
String id,
) async {
final path = APIPaths.getCampaignReward.replaceFirst('%@', id); final path = APIPaths.getCampaignReward.replaceFirst('%@', id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
final list = data as List<dynamic>; final list = data as List<dynamic>;
...@@ -857,7 +625,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -857,7 +625,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<List<String>>> getCampaignLiveTransactions(String id) async { Future<BaseResponseModel<List<String>>> getCampaignLiveTransactions(
String id,
) async {
final path = APIPaths.getCampaignLiveTransactions.replaceFirst('%@', id); final path = APIPaths.getCampaignLiveTransactions.replaceFirst('%@', id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
if (data is List) { if (data is List) {
...@@ -867,40 +637,56 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -867,40 +637,56 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<Campaign7DayInfoModel>> getCampaignMissions(String id) async { Future<BaseResponseModel<Campaign7DayInfoModel>> getCampaignMissions(
String id,
) async {
final path = APIPaths.getCampaignMissions.replaceFirst('%@', id); final path = APIPaths.getCampaignMissions.replaceFirst('%@', id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return Campaign7DayInfoModel.fromJson(data as Json); return Campaign7DayInfoModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<SurveyCampaignInfoModel>> getCampaignQuizSurvey(String id) async { Future<BaseResponseModel<SurveyCampaignInfoModel>> getCampaignQuizSurvey(
String id,
) async {
final path = APIPaths.getQuizCampaign.replaceFirst('%@', id); final path = APIPaths.getQuizCampaign.replaceFirst('%@', id);
return requestNormal(path, Method.GET, {}, (data) { return requestNormal(path, Method.GET, {}, (data) {
return SurveyCampaignInfoModel.fromJson(data as Json); return SurveyCampaignInfoModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<QuizCampaignSubmitResponseModel>> quizSubmitCampaign(String id, Json body) async { Future<BaseResponseModel<QuizCampaignSubmitResponseModel>> quizSubmitCampaign(
String id,
Json body,
) async {
final path = APIPaths.quizSubmitCampaign.replaceFirst('%@', id); final path = APIPaths.quizSubmitCampaign.replaceFirst('%@', id);
return requestNormal(path, Method.POST, body, (data) { return requestNormal(path, Method.POST, body, (data) {
return QuizCampaignSubmitResponseModel.fromJson(data as Json); return QuizCampaignSubmitResponseModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<List<FlashSaleCategoryModel>>> getFlashSaleCategories(String groupId) async { Future<BaseResponseModel<List<FlashSaleCategoryModel>>>
getFlashSaleCategories(String groupId) async {
final path = APIPaths.getFlashSaleGroup.replaceFirst('%@', groupId); final path = APIPaths.getFlashSaleGroup.replaceFirst('%@', groupId);
return requestNormal(path, Method.GET, const {}, (data) { return requestNormal(path, Method.GET, const {}, (data) {
if (data is List) { if (data is List) {
return data.whereType<Map<String, dynamic>>().map(FlashSaleCategoryModel.fromJson).toList(); return data
.whereType<Map<String, dynamic>>()
.map(FlashSaleCategoryModel.fromJson)
.toList();
} }
if (data is Map<String, dynamic>) { if (data is Map<String, dynamic>) {
final categories = data['categories'] ?? data['data'] ?? data['items']; final categories = data['categories'] ?? data['data'] ?? data['items'];
if (categories is List) { if (categories is List) {
return categories.whereType<Map<String, dynamic>>().map(FlashSaleCategoryModel.fromJson).toList(); return categories
.whereType<Map<String, dynamic>>()
.map(FlashSaleCategoryModel.fromJson)
.toList();
} }
if (data.containsKey('_id')) { if (data.containsKey('_id')) {
return [FlashSaleCategoryModel.fromJson(Map<String, dynamic>.from(data))]; return [
FlashSaleCategoryModel.fromJson(Map<String, dynamic>.from(data)),
];
} }
} }
return <FlashSaleCategoryModel>[]; return <FlashSaleCategoryModel>[];
...@@ -939,7 +725,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -939,7 +725,9 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<DevicesLogoutListResponse>> getLogoutDevices(Json body) async { Future<BaseResponseModel<DevicesLogoutListResponse>> getLogoutDevices(
Json body,
) async {
return requestNormal(APIPaths.getLogoutDevices, Method.GET, body, (data) { return requestNormal(APIPaths.getLogoutDevices, Method.GET, body, (data) {
return DevicesLogoutListResponse.fromJson(data as Json); return DevicesLogoutListResponse.fromJson(data as Json);
}); });
...@@ -950,31 +738,43 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -950,31 +738,43 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
return requestNormal(path, Method.DELETE, {}, (data) => data as String); return requestNormal(path, Method.DELETE, {}, (data) => data as String);
} }
Future<BaseResponseModel<InterestedCategoriesResponse>> categoryTopLevelGetList() async { Future<BaseResponseModel<InterestedCategoriesResponse>>
categoryTopLevelGetList() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "lang": "vi"}; final body = {"access_token": token, "lang": "vi"};
return requestNormal(APIPaths.categoryTopLevelGetList, Method.POST, body, (data) { return requestNormal(APIPaths.categoryTopLevelGetList, Method.POST, body, (
data,
) {
return InterestedCategoriesResponse.fromJson(data as Json); return InterestedCategoriesResponse.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<EmptyCodable>> submitCategorySubscribe(String code) async { Future<BaseResponseModel<EmptyCodable>> submitCategorySubscribe(
String code,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'category_codes': code}; final body = {"access_token": token, 'category_codes': code};
return requestNormal(APIPaths.categorySubscribeList, Method.POST, body, (data) { return requestNormal(APIPaths.categorySubscribeList, Method.POST, body, (
data,
) {
return EmptyCodable.fromJson(data as Json); return EmptyCodable.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<EmptyCodable>> submitCategoryUnsubscribeList(String code) async { Future<BaseResponseModel<EmptyCodable>> submitCategoryUnsubscribeList(
String code,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, 'category_codes': code}; final body = {"access_token": token, 'category_codes': code};
return requestNormal(APIPaths.categoryUnsubscribeList, Method.POST, body, (data) { return requestNormal(APIPaths.categoryUnsubscribeList, Method.POST, body, (
data,
) {
return EmptyCodable.fromJson(data as Json); return EmptyCodable.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<ElectricPaymentResponseModel>> customerEvnPaymentGatewayRequest( Future<BaseResponseModel<ElectricPaymentResponseModel>>
customerEvnPaymentGatewayRequest(
CustomerContractModel contract, CustomerContractModel contract,
String paymentMethod, String paymentMethod,
) async { ) async {
...@@ -986,12 +786,18 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -986,12 +786,18 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
'amount': contract.amount ?? 0, 'amount': contract.amount ?? 0,
'payment_method': paymentMethod, 'payment_method': paymentMethod,
}; };
return requestNormal(APIPaths.customerEvnPaymentGatewayRequest, Method.POST, body, (data) { return requestNormal(
return ElectricPaymentResponseModel.fromJson(data as Json); APIPaths.customerEvnPaymentGatewayRequest,
}); Method.POST,
body,
(data) {
return ElectricPaymentResponseModel.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<List<PopupManagerModel>>> getPopupManagerCommonScreen() async { Future<BaseResponseModel<List<PopupManagerModel>>>
getPopupManagerCommonScreen() async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
final body = {"access_token": token, "lang": "vi"}; final body = {"access_token": token, "lang": "vi"};
return requestNormal(APIPaths.getPopup, Method.POST, body, (data) { return requestNormal(APIPaths.getPopup, Method.POST, body, (data) {
...@@ -1000,33 +806,20 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -1000,33 +806,20 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
}); });
} }
Future<BaseResponseModel<MyVoucherResponse>> getMyMobileCards(MyProductStatusType status, Json body) async { Future<BaseResponseModel<List<BankAccountInfoModel>>>
String? token = DataPreference.instance.token ?? ""; getOrderPaymentMyAccounts() async {
body["access_token"] = token; return requestNormal(APIPaths.orderPaymentMyAccounts, Method.GET, {}, (
body["product_model_code"] = "PRODUCT_MODEL_MOBILE_CARD"; data,
body["list_order"] = "DESC"; ) {
var path = '';
switch (status) {
case MyProductStatusType.waiting:
path = APIPaths.getMyProductGetWaitingList;
case MyProductStatusType.used:
path = APIPaths.getMyProductGetUsedList;
case MyProductStatusType.expired:
path = APIPaths.getMyProductGetExpiredList;
}
return requestNormal(path, Method.POST, body, (data) {
return MyVoucherResponse.fromJson(data as Json);
});
}
Future<BaseResponseModel<List<BankAccountInfoModel>>> getOrderPaymentMyAccounts() async {
return requestNormal(APIPaths.orderPaymentMyAccounts, Method.GET, {}, (data) {
final list = data as List<dynamic>; final list = data as List<dynamic>;
return list.map((e) => BankAccountInfoModel.fromJson(e)).toList(); return list.map((e) => BankAccountInfoModel.fromJson(e)).toList();
}); });
} }
Future<BaseResponseModel<String>> setDefaultBankAccount(String id, bool isDefault) async { Future<BaseResponseModel<String>> setDefaultBankAccount(
String id,
bool isDefault,
) async {
final path = APIPaths.bankAccountSetDefault.replaceFirst('%@', id); final path = APIPaths.bankAccountSetDefault.replaceFirst('%@', id);
final body = {"is_default": isDefault ? 1 : 0}; final body = {"is_default": isDefault ? 1 : 0};
return requestNormal(path, Method.POST, body, (data) => data as String); return requestNormal(path, Method.POST, body, (data) => data as String);
...@@ -1037,30 +830,47 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -1037,30 +830,47 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
return requestNormal(path, Method.DELETE, {}, (data) => data as String); return requestNormal(path, Method.DELETE, {}, (data) => data as String);
} }
Future<BaseResponseModel<TransactionSummaryByDateModel>> transactionGetSummaryByDate(Json body) async { Future<BaseResponseModel<TransactionSummaryByDateModel>>
transactionGetSummaryByDate(Json body) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
body["access_token"] = token; body["access_token"] = token;
return requestNormal(APIPaths.transactionGetSummaryByDate, Method.POST, body, (data) { return requestNormal(
return TransactionSummaryByDateModel.fromJson(data as Json); APIPaths.transactionGetSummaryByDate,
}); Method.POST,
body,
(data) {
return TransactionSummaryByDateModel.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<ListHistoryResponseModel>> transactionHistoryGetList(Json body) async { Future<BaseResponseModel<ListHistoryResponseModel>> transactionHistoryGetList(
Json body,
) async {
String? token = DataPreference.instance.token ?? ""; String? token = DataPreference.instance.token ?? "";
body["access_token"] = token; body["access_token"] = token;
return requestNormal(APIPaths.transactionHistoryGetList, Method.POST, body, (data) { return requestNormal(
return ListHistoryResponseModel.fromJson(data as Json); APIPaths.transactionHistoryGetList,
}); Method.POST,
body,
(data) {
return ListHistoryResponseModel.fromJson(data as Json);
},
);
} }
Future<BaseResponseModel<DirectionalScreen>> getDirectionOfflineBrand(String id) async { Future<BaseResponseModel<DirectionalScreen>> getDirectionOfflineBrand(
String id,
) async {
final body = {"bank_account": id}; final body = {"bank_account": id};
return requestNormal(APIPaths.getOfflineBrand, Method.GET, body, (data) { return requestNormal(APIPaths.getOfflineBrand, Method.GET, body, (data) {
return DirectionalScreen.fromJson(data as Json); return DirectionalScreen.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<EmptyCodable>> pushNotificationDeviceUpdateToken(String token) async { Future<BaseResponseModel<EmptyCodable>> pushNotificationDeviceUpdateToken(
String token,
) async {
var deviceKey = await DeviceInfo.getDeviceId(); var deviceKey = await DeviceInfo.getDeviceId();
final details = await DeviceInfo.getDetails(); final details = await DeviceInfo.getDetails();
String? accessToken = DataPreference.instance.token ?? ""; String? accessToken = DataPreference.instance.token ?? "";
...@@ -1071,59 +881,53 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient { ...@@ -1071,59 +881,53 @@ extension RestfulAPIClientAllRequest on RestfulAPIClient {
body["lang"] = 'vi'; body["lang"] = 'vi';
body["software_type"] = "Application"; body["software_type"] = "Application";
body["software_model"] = "MyPoint"; body["software_model"] = "MyPoint";
return requestNormal(APIPaths.pushNotificationDeviceUpdateToken, Method.POST, body, (data) { return requestNormal(
return EmptyCodable.fromJson(data as Json); APIPaths.pushNotificationDeviceUpdateToken,
}); Method.POST,
} body,
(data) {
Future<BaseResponseModel<EmptyCodable>> myProductMarkAsUsed(String id) async { return EmptyCodable.fromJson(data as Json);
String? accessToken = DataPreference.instance.token ?? ""; },
final body = { );
"product_item_id": id,
"lang": "vi",
"access_token": accessToken,
};
return requestNormal(APIPaths.myProductMarkAsUsed, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
}
Future<BaseResponseModel<EmptyCodable>> myProductMarkAsNotUsedYet(String id) async {
String? accessToken = DataPreference.instance.token ?? "";
final body = {
"product_item_id": id,
"lang": "vi",
"access_token": accessToken,
};
return requestNormal(APIPaths.myProductMarkAsNotUsedYet, Method.POST, body, (data) {
return EmptyCodable.fromJson(data as Json);
});
} }
Future<BaseResponseModel<DirectionalScreen>> getDirectionScreen(String path) async { Future<BaseResponseModel<DirectionalScreen>> getDirectionScreen(
String path,
) async {
var path_ = path.startsWith('/') ? path : '/$path'; var path_ = path.startsWith('/') ? path : '/$path';
return requestNormal(path_, Method.GET, {}, (data) { return requestNormal(path_, Method.GET, {}, (data) {
return DirectionalScreen.fromJson(data as Json); return DirectionalScreen.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<EmptyCodable>> submitShareContent(String path) async { Future<BaseResponseModel<EmptyCodable>> submitShareContent(
String path,
) async {
var path_ = path.startsWith('/') ? path : '/$path'; var path_ = path.startsWith('/') ? path : '/$path';
return requestNormal(path_, Method.GET, {}, (data) { return requestNormal(path_, Method.GET, {}, (data) {
return EmptyCodable.fromJson(data as Json); return EmptyCodable.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<VerifyRegisterCampaignModel>> verifyRegisterForm(String path, Json body) async { Future<BaseResponseModel<VerifyRegisterCampaignModel>> verifyRegisterForm(
String path,
Json body,
) async {
var path_ = path.startsWith('/') ? path : '/$path'; var path_ = path.startsWith('/') ? path : '/$path';
return requestNormal(path_, Method.POST, body, (data) { return requestNormal(path_, Method.POST, body, (data) {
return VerifyRegisterCampaignModel.fromJson(data as Json); return VerifyRegisterCampaignModel.fromJson(data as Json);
}); });
} }
Future<BaseResponseModel<SubmitViewVoucherCompletedResponse>> submitCampaignViewVoucherComplete() async { Future<BaseResponseModel<SubmitViewVoucherCompletedResponse>>
return requestNormal(APIPaths.submitCampaignViewVoucherComplete, Method.POST, {}, (data) { submitCampaignViewVoucherComplete() async {
return SubmitViewVoucherCompletedResponse.fromJson(data as Json); return requestNormal(
}); APIPaths.submitCampaignViewVoucherComplete,
Method.POST,
{},
(data) {
return SubmitViewVoucherCompletedResponse.fromJson(data as Json);
},
);
} }
} }
...@@ -23,9 +23,7 @@ class DataPreference { ...@@ -23,9 +23,7 @@ class DataPreference {
try { try {
_loginToken = LoginTokenResponseModel.fromJson(jsonDecode(tokenJson)); _loginToken = LoginTokenResponseModel.fromJson(jsonDecode(tokenJson));
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to parse login token: $e');
print('Failed to parse login token: $e');
}
// Clear invalid token // Clear invalid token
await prefs.remove('login_token'); await prefs.remove('login_token');
} }
...@@ -36,17 +34,13 @@ class DataPreference { ...@@ -36,17 +34,13 @@ class DataPreference {
_profile = ProfileResponseModel.fromJson(jsonDecode(profileJson)); _profile = ProfileResponseModel.fromJson(jsonDecode(profileJson));
phoneNumberUsedForLoginScreen = _profile?.workerSite?.phoneNumber ?? ""; phoneNumberUsedForLoginScreen = _profile?.workerSite?.phoneNumber ?? "";
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to parse user profile: $e');
print('Failed to parse user profile: $e');
}
// Clear invalid profile // Clear invalid profile
await prefs.remove('user_profile'); await prefs.remove('user_profile');
} }
} }
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('DataPreference init failed: $e');
print('DataPreference init failed: $e');
}
} }
} }
String get displayName { String get displayName {
...@@ -109,9 +103,7 @@ class DataPreference { ...@@ -109,9 +103,7 @@ class DataPreference {
try { try {
return jsonDecode(jsonString) as String?; return jsonDecode(jsonString) as String?;
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('Failed to parse bio token for $phone: $e');
print('Failed to parse bio token for $phone: $e');
}
// Clear invalid bio token // Clear invalid bio token
await prefs.remove('biometric_login_token_$phone'); await prefs.remove('biometric_login_token_$phone');
return null; return null;
...@@ -119,9 +111,7 @@ class DataPreference { ...@@ -119,9 +111,7 @@ class DataPreference {
} }
return null; return null;
} catch (e) { } catch (e) {
if (kDebugMode) { debugPrint('getBioToken failed for $phone: $e');
print('getBioToken failed for $phone: $e');
}
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';
class AffiliateOverviewPopup extends StatelessWidget { class AffiliateOverviewPopup extends StatelessWidget {
final List<String> descriptions; final List<String> descriptions;
......
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_all_request.dart'; import 'package:mypoint_flutter_app/networking/api/affiliate_api.dart' deferred as affiliate_api;
import '../../base/base_response_model.dart';
import '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import 'model/affiliate_brand_model.dart'; import 'model/affiliate_brand_model.dart';
import 'model/affiliate_category_model.dart'; import 'model/affiliate_category_model.dart';
...@@ -16,10 +17,22 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -16,10 +17,22 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
final Rxn<CashbackOverviewModel> overview = Rxn<CashbackOverviewModel>(); final Rxn<CashbackOverviewModel> overview = Rxn<CashbackOverviewModel>();
void Function((List<AffiliateBrandModel>, String) data)? onShowAffiliateBrandPopup; void Function((List<AffiliateBrandModel>, String) data)? onShowAffiliateBrandPopup;
bool _affiliateLibLoaded = false;
Future<void> _ensureAffiliateLibraryLoaded() async {
if (_affiliateLibLoaded) return;
await affiliate_api.loadLibrary();
_affiliateLibLoaded = true;
}
Future<BaseResponseModel<T>> _callAffiliate<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
await _ensureAffiliateLibraryLoaded();
final api = affiliate_api.AffiliateApi(client);
return fn(api);
}
bool get isDataAvailable { bool get isDataAvailable {
return affiliateBrands.isNotEmpty || return affiliateBrands.isNotEmpty || affiliateCategories.isNotEmpty || affiliateProducts.isNotEmpty;
affiliateCategories.isNotEmpty ||
affiliateProducts.isNotEmpty;
} }
Future<void> refreshData({bool isShowLoading = true}) async { Future<void> refreshData({bool isShowLoading = true}) async {
...@@ -36,7 +49,7 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -36,7 +49,7 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
Future<void> _getAffiliateBrandGetList() async { Future<void> _getAffiliateBrandGetList() async {
await callApi<List<AffiliateBrandModel>>( await callApi<List<AffiliateBrandModel>>(
request: () => client.affiliateBrandGetList(), request: () => _callAffiliate((api) => api.affiliateBrandGetList()),
onSuccess: (data, _) { onSuccess: (data, _) {
affiliateBrands.assignAll(data); affiliateBrands.assignAll(data);
}, },
...@@ -49,12 +62,9 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -49,12 +62,9 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
Future<void> _getAffiliateCategoryGetList() async { Future<void> _getAffiliateCategoryGetList() async {
await callApi<List<AffiliateCategoryModel>>( await callApi<List<AffiliateCategoryModel>>(
request: () => client.affiliateCategoryGetList(), request: () => _callAffiliate((api) => api.affiliateCategoryGetList()),
onSuccess: (data, _) { onSuccess: (data, _) {
final category = AffiliateCategoryModel( final category = AffiliateCategoryModel(code: AffiliateCategoryType.other, name: "Khác");
code: AffiliateCategoryType.other,
name: "Khác",
);
final results = data; final results = data;
allAffiliateCategories.assignAll(results); allAffiliateCategories.assignAll(results);
...@@ -72,11 +82,11 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -72,11 +82,11 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
Future<void> _getAffiliateProductTopSale() async { Future<void> _getAffiliateProductTopSale() async {
await callApi<List<AffiliateProductTopSaleModel>>( await callApi<List<AffiliateProductTopSaleModel>>(
request: () => client.affiliateProductTopSale(), request: () => _callAffiliate((api) => api.affiliateProductTopSale()),
onSuccess: (data, _) { onSuccess: (data, _) {
affiliateProducts.assignAll(data); affiliateProducts.assignAll(data);
}, },
onFailure: (msg, _, __) async { onFailure: (msg, _, _) async {
affiliateProducts.clear(); affiliateProducts.clear();
}, },
withLoading: false, withLoading: false,
...@@ -85,7 +95,7 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -85,7 +95,7 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
Future<void> _getAffiliateOverview() async { Future<void> _getAffiliateOverview() async {
await callApi<CashbackOverviewModel>( await callApi<CashbackOverviewModel>(
request: () => client.getCashBackOverview(), request: () => _callAffiliate((api) => api.getCashBackOverview()),
onSuccess: (data, _) { onSuccess: (data, _) {
overview.value = data; overview.value = data;
}, },
...@@ -98,7 +108,10 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -98,7 +108,10 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
Future<void> affiliateBrandGetListBuyCategory(AffiliateCategoryModel category) async { Future<void> affiliateBrandGetListBuyCategory(AffiliateCategoryModel category) async {
await callApi<List<AffiliateBrandModel>>( await callApi<List<AffiliateBrandModel>>(
request: () => client.affiliateBrandGetList(categoryCode: AffiliateCategoryModel.codeToJson(category.code)), request:
() => _callAffiliate(
(api) => api.affiliateBrandGetList(categoryCode: AffiliateCategoryModel.codeToJson(category.code)),
),
onSuccess: (data, _) { onSuccess: (data, _) {
if (data.isNotEmpty) { if (data.isNotEmpty) {
onShowAffiliateBrandPopup?.call((data, category.name ?? '')); onShowAffiliateBrandPopup?.call((data, category.name ?? ''));
...@@ -106,4 +119,4 @@ class AffiliateTabViewModel extends RestfulApiViewModel { ...@@ -106,4 +119,4 @@ class AffiliateTabViewModel extends RestfulApiViewModel {
}, },
); );
} }
} }
\ No newline at end of file
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:mypoint_flutter_app/configs/constants.dart'; import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/api/affiliate_api.dart'
deferred as affiliate_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 '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import 'models/affiliate_brand_detail_model.dart'; import 'models/affiliate_brand_detail_model.dart';
class AffiliateBrandDetailViewModel extends RestfulApiViewModel { class AffiliateBrandDetailViewModel extends RestfulApiViewModel {
final String brandId; final String brandId;
AffiliateBrandDetailViewModel(this.brandId); AffiliateBrandDetailViewModel(this.brandId);
void Function(String message)? onShowAlertError; void Function(String message)? onShowAlertError;
final Rxn<AffiliateBrandDetailModel> brandDetailData = Rxn<AffiliateBrandDetailModel>(); final Rxn<AffiliateBrandDetailModel> brandDetailData =
Rxn<AffiliateBrandDetailModel>();
bool _affiliateLibLoaded = false;
Future<void> _ensureAffiliateLibraryLoaded() async {
if (_affiliateLibLoaded) return;
await affiliate_api.loadLibrary();
_affiliateLibLoaded = true;
}
@override @override
void onInit() { void onInit() {
...@@ -19,7 +32,11 @@ class AffiliateBrandDetailViewModel extends RestfulApiViewModel { ...@@ -19,7 +32,11 @@ class AffiliateBrandDetailViewModel extends RestfulApiViewModel {
Future<void> _fetchDetail() async { Future<void> _fetchDetail() async {
await callApi<AffiliateBrandDetailModel>( await callApi<AffiliateBrandDetailModel>(
request: () => client.getAffiliateBrandDetail(brandId), request: () async {
await _ensureAffiliateLibraryLoaded();
final api = affiliate_api.AffiliateApi(client);
return api.getAffiliateBrandDetail(brandId);
},
onSuccess: (data, _) { onSuccess: (data, _) {
brandDetailData.value = data; brandDetailData.value = data;
}, },
......
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/affiliate_api.dart'
deferred as affiliate_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 '../../networking/restful_api_viewmodel.dart'; import '../../networking/restful_api_viewmodel.dart';
import '../affiliate/model/affiliate_brand_model.dart'; import '../affiliate/model/affiliate_brand_model.dart';
import '../affiliate/model/affiliate_category_model.dart'; import '../affiliate/model/affiliate_category_model.dart';
class AffiliateCategoryGridViewModel extends RestfulApiViewModel { class AffiliateCategoryGridViewModel extends RestfulApiViewModel {
void Function((List<AffiliateBrandModel>, String) data)? onShowAffiliateBrandPopup; void Function((List<AffiliateBrandModel>, String) data)?
onShowAffiliateBrandPopup;
void Function(String message)? onShowAlertError; void Function(String message)? onShowAlertError;
Future<void> affiliateBrandGetListBuyCategory(AffiliateCategoryModel category) async { bool _affiliateLibLoaded = false;
Future<void> _ensureAffiliateLibraryLoaded() async {
if (_affiliateLibLoaded) return;
await affiliate_api.loadLibrary();
_affiliateLibLoaded = true;
}
Future<void> affiliateBrandGetListBuyCategory(
AffiliateCategoryModel category,
) async {
await callApi<List<AffiliateBrandModel>>( await callApi<List<AffiliateBrandModel>>(
request: () => client.affiliateBrandGetList( request: () async {
categoryCode: AffiliateCategoryModel.codeToJson(category.code), await _ensureAffiliateLibraryLoaded();
), final api = affiliate_api.AffiliateApi(client);
return api.affiliateBrandGetList(
categoryCode: AffiliateCategoryModel.codeToJson(category.code),
);
},
onSuccess: (data, _) { onSuccess: (data, _) {
if (data.isNotEmpty) { if (data.isNotEmpty) {
onShowAffiliateBrandPopup?.call((data, category.name ?? '')); onShowAffiliateBrandPopup?.call((data, category.name ?? ''));
...@@ -24,4 +41,4 @@ class AffiliateCategoryGridViewModel extends RestfulApiViewModel { ...@@ -24,4 +41,4 @@ class AffiliateCategoryGridViewModel extends RestfulApiViewModel {
}, },
); );
} }
} }
\ No newline at end of file
import 'package:flutter/foundation.dart';
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/widgets/custom_empty_widget.dart'; import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
...@@ -35,7 +36,7 @@ class _BankAccountManagerScreenState extends State<BankAccountManagerScreen> { ...@@ -35,7 +36,7 @@ class _BankAccountManagerScreenState extends State<BankAccountManagerScreen> {
await Get.to(() => BankAccountDetailScreen( await Get.to(() => BankAccountDetailScreen(
model: viewModel.bankAccounts.value[index], model: viewModel.bankAccounts.value[index],
)); ));
print("reload getBankAccountList"); debugPrint("reload getBankAccountList");
viewModel.getBankAccountList(); viewModel.getBankAccountList();
}), }),
), ),
......
import 'package:flutter/foundation.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart'; import 'package:local_auth/local_auth.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';
...@@ -27,7 +28,7 @@ class BiometricViewModel extends RestfulApiViewModel { ...@@ -27,7 +28,7 @@ class BiometricViewModel extends RestfulApiViewModel {
biometricType.value = BiometricType.fingerprint; biometricType.value = BiometricType.fingerprint;
} }
} catch (e) { } catch (e) {
print("Lỗi kiểm tra sinh trắc học: $e"); debugPrint("Lỗi kiểm tra sinh trắc học: $e");
} }
} }
......
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