From d5745847bf7425ec7f94fa7a0d04c91a742bbb16 Mon Sep 17 00:00:00 2001 From: "Mirza.Shafique@cloudsolutions.com.sa" <5093@Shf> Date: Sun, 28 Apr 2024 11:38:56 +0300 Subject: [PATCH] subscription updates --- lib/classes/consts.dart | 8 +- lib/extensions/string_extensions.dart | 82 ++++++-- .../branch_detail_model.dart | 2 +- .../branch_user_selection_model.dart | 32 +++ .../subscription_model.dart | 121 +++++++----- lib/models/user_models/branch_user.dart | 37 ++-- lib/repositories/subscription_repo.dart | 165 ++++++++++++++++ lib/utils/enums.dart | 6 + lib/view_models/payment_view_model.dart | 21 ++ lib/view_models/subscriptions_view_model.dart | 182 ++++++++++++++++++ lib/views/payments/payment_methods_view.dart | 18 +- 11 files changed, 587 insertions(+), 87 deletions(-) create mode 100644 lib/models/subscriptions_models/branch_user_selection_model.dart create mode 100644 lib/repositories/subscription_repo.dart create mode 100644 lib/view_models/subscriptions_view_model.dart diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 06438d3..86b080c 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -100,7 +100,7 @@ class ApiConsts { static String vehicleDetailsMaster = "${baseUrlServices}api/Master"; static String vehicleAdsDurationGet = "${baseUrlServices}api/Advertisement/AdsDuration_Get"; static String vehicleAdsSpecialServicesGet = "${baseUrlServices}api/Common/SpecialService_Get"; - static String vehicleAdsSingleStepCreate = "${baseUrlServices}api/Advertisement/AdsSingleStep_Create"; + static String vehicleAdsSingleStepCreate = "${baseUrlServices}api/Advertisement/AdsSingl`eStep_Create"; static String vehicleAdsGet = "${baseUrlServices}api/Advertisement/Ads_Get"; static String myAdsReserveGet = "${baseUrlServices}api/Advertisement/AdsReserve_Get"; static String reserveAdsBankDetailsGet = "${baseUrlServices}api/Advertisement/MCBankAccountAd_Get"; @@ -113,7 +113,12 @@ class ApiConsts { static String adsReserveCreate = "${baseUrlServices}api/Advertisement/AdsReserve_Create"; //Subscription + static String getMySubscriptions = "${baseUrlServices}api/ServiceProviders/ProviderSubscription_Get"; static String getAllSubscriptions = "${baseUrlServices}api/Common/Subscription_Get"; + static String getSubscriptionBySP = "${baseUrlServices}api/Common/SubscriptionBySP_Get"; + static String calculationUpgradePrice = "${baseUrlServices}api/ServiceProviders/CalculationUpgradePrice"; + static String payFortOrder_ProviderSubscription_Create = "${baseUrlServices}api/Payment/PayFortOrder_ProviderSubscription_Create"; + static String getSPBranchUser_Get = "${baseUrlServices}api/ServiceProviders/SPBranchUser_Get"; // Payment static String paymentWebViewUrl = "https://ms.hmg.com/pay/PaymentHome"; @@ -124,7 +129,6 @@ class ApiConsts { static String duplicateItems = "${baseUrlServices}api/ServiceProviders/ServiceItemCopy_Create"; //Branch Users - static String getAllProviderDealers = "${baseUrlServices}api/ServiceProviders/DealershipUserBranchWise_Get"; // /api/ServiceProviders/BranchUser_Get diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 36172f3..3795963 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -5,18 +5,18 @@ import 'package:mc_common_app/theme/colors.dart'; import 'package:mc_common_app/utils/enums.dart'; extension EmailValidator on String { - Widget toText( - {Color? color, - bool isBold = false, - double? fontSize, - bool isUnderLine = false, - bool isItalic = false, - TextDecoration? textDecoration, - double letterSpacing = -0.4, - TextAlign? textAlign, - FontWeight? fontWeight, - double? height, - int? maxLines}) => + Widget toText({Color? color, + bool isBold = false, + double? fontSize, + bool isUnderLine = false, + bool isItalic = false, + TextDecoration? textDecoration, + double letterSpacing = -0.4, + TextAlign? textAlign, + FontWeight? fontWeight, + double? height, + Color? decorationColor, + int? maxLines}) => AutoSizeText( this, textAlign: textAlign, @@ -24,7 +24,10 @@ extension EmailValidator on String { style: TextStyle( fontStyle: isItalic ? FontStyle.italic : null, height: height, - decoration: isUnderLine ? TextDecoration.underline : textDecoration ?? TextDecoration.none, + decoration: isUnderLine ? TextDecoration.underline : textDecoration ?? + TextDecoration.none, + decorationColor + : decorationColor, fontSize: fontSize ?? 10, fontWeight: isBold ? FontWeight.bold : fontWeight ?? FontWeight.w600, color: color ?? MyColors.darkTextColor, @@ -33,7 +36,9 @@ extension EmailValidator on String { ); bool isValidEmail() { - return RegExp(r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$').hasMatch(this); + return RegExp( + r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$') + .hasMatch(this); } bool isNum() { @@ -141,7 +146,9 @@ extension FormatDate on String { String date = split("T")[0]; String time = split("T")[1]; var dates = date.split("-"); - return "${dates[2]} ${getMonth(int.parse(dates[1]))} ${dates[0]} ${DateFormat('hh:mm a', "en_US").format(DateFormat('hh:mm:ss', "en_US").parse(time))}"; + return "${dates[2]} ${getMonth( + int.parse(dates[1]))} ${dates[0]} ${DateFormat('hh:mm a', "en_US") + .format(DateFormat('hh:mm:ss', "en_US").parse(time))}"; } String toFormattedDateWithoutTime() { @@ -757,3 +764,48 @@ extension ChatTypeEnumToInt on ChatTypeEnum { } } } + +extension SubscriptionTypeEnumExt on int { + SubscriptionTypeEnum toSubscriptionTypeEnum() { + if (this == 2) { + return SubscriptionTypeEnum.upgrade; + } else if (this == 3) { + return SubscriptionTypeEnum.downgrade; + } + return SubscriptionTypeEnum.current; + } +} + +extension SubscriptionTypeEnumToInt on SubscriptionTypeEnum { + int getIdSubscriptionTypeEnum() { + switch (this) { + case SubscriptionTypeEnum.current: + return 1; + case SubscriptionTypeEnum.upgrade: + return 2; + case SubscriptionTypeEnum.downgrade: + return 3; + + default: + return 1; + } + } +} + +extension SubscriptionTypeEnumToString on SubscriptionTypeEnum { + String getStringSubscriptionTypeEnum() { + switch (this) { + case SubscriptionTypeEnum.current: + return "Current"; + case SubscriptionTypeEnum.upgrade: + return "Upgrade"; + case SubscriptionTypeEnum.downgrade: + return "Downgrade"; + + default: + return "Current"; + } + } +} + + diff --git a/lib/models/provider_branches_models/branch_detail_model.dart b/lib/models/provider_branches_models/branch_detail_model.dart index 2ffa413..7748a81 100644 --- a/lib/models/provider_branches_models/branch_detail_model.dart +++ b/lib/models/provider_branches_models/branch_detail_model.dart @@ -65,7 +65,7 @@ class BranchDetailModel { distanceKm: json["distanceKM"]?.toDouble(), openTime: json["openTime"], closeTime: json["closeTime"], - branchStatus: (json['branchStatus'] as int).toBranchStatusEnum(), + branchStatus: json.containsKey("branchStatus")?(json['branchStatus'] as int).toBranchStatusEnum():null, statusId: json["branchStatus"], statusText: json["statusText"], branchServices: json["serviceProviderServices"] == null ? [] : List< diff --git a/lib/models/subscriptions_models/branch_user_selection_model.dart b/lib/models/subscriptions_models/branch_user_selection_model.dart new file mode 100644 index 0000000..e5028a1 --- /dev/null +++ b/lib/models/subscriptions_models/branch_user_selection_model.dart @@ -0,0 +1,32 @@ +class BranchSelectionModel { + int branchId; + String branchName; + bool isSelected; + bool isOpend; + List usersList; + + BranchSelectionModel + + ({ + + required + + this + + . + branchId, + required this.branchName, + required this.isSelected, + this.isOpend = false, + required this.usersList, + }); +} + +class UserSelectionModel { + int userId; + String userName; + bool isSelected; + + UserSelectionModel( + {required this.userId, required this.userName, required this.isSelected}); +} diff --git a/lib/models/subscriptions_models/subscription_model.dart b/lib/models/subscriptions_models/subscription_model.dart index d192566..66d79f8 100644 --- a/lib/models/subscriptions_models/subscription_model.dart +++ b/lib/models/subscriptions_models/subscription_model.dart @@ -4,7 +4,12 @@ import 'dart:convert'; -Subscription subscriptionFromJson(String str) => Subscription.fromJson(json.decode(str)); +import 'package:mc_common_app/extensions/string_extensions.dart'; + +import '../../utils/enums.dart'; + +Subscription subscriptionFromJson(String str) => + Subscription.fromJson(json.decode(str)); String subscriptionToJson(Subscription data) => json.encode(data.toJson()); @@ -21,19 +26,25 @@ class SubscriptionModel { List? data; String? message; - factory SubscriptionModel.fromJson(Map json) => SubscriptionModel( - messageStatus: json["messageStatus"], - totalItemsCount: json["totalItemsCount"], - data: json["data"] == null ? [] : List.from(json["data"]!.map((x) => Subscription.fromJson(x))), - message: json["message"], - ); + factory SubscriptionModel.fromJson(Map json) => + SubscriptionModel( + messageStatus: json["messageStatus"], + totalItemsCount: json["totalItemsCount"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => Subscription.fromJson(x))), + message: json["message"], + ); Map toJson() => { - "messageStatus": messageStatus, - "totalItemsCount": totalItemsCount, - "data": data == null ? [] : List.from(data!.map((x) => x.toJson())), - "message": message, - }; + "messageStatus": messageStatus, + "totalItemsCount": totalItemsCount, + "data": data == null + ? [] + : List.from(data!.map((x) => x.toJson())), + "message": message, + }; } class Subscription { @@ -57,6 +68,7 @@ class Subscription { this.dateEnd, this.isExpired, this.isActive, + this.subscriptionTypeEnum, }); int? id; @@ -78,48 +90,53 @@ class Subscription { DateTime? dateEnd; bool? isExpired; bool? isActive; + SubscriptionTypeEnum? subscriptionTypeEnum; factory Subscription.fromJson(Map json) => Subscription( - id: json["id"], - name: json["name"], - description: json["description"], - durationName: json["durationName"], - durationDays: json["durationDays"], - price: json["price"]?.toDouble(), - currency: json["currency"], - numberOfBranches: json["numberOfBranches"], - numberOfSubUsers: json["numberOfSubUsers"], - numberOfAds: json["numberOfAds"], - countryId: json["countryID"], - countryName: json["countryName"]!, - isSubscribed: json["isSubscribed"], - subscriptionAppliedId: json["subscriptionAppliedID"], - serviceProviderId: json["serviceProviderID"], - dateStart: json["dateStart"] == null ? null : DateTime.parse(json["dateStart"]), - dateEnd: json["dateEnd"] == null ? null : DateTime.parse(json["dateEnd"]), - isExpired: json["isExpired"], - isActive: json["isActive"], - ); + id: json["id"], + name: json["name"], + description: json["description"], + durationName: json["durationName"], + durationDays: json["durationDays"], + price: json["price"]?.toDouble(), + currency: json["currency"], + numberOfBranches: json["numberOfBranches"], + numberOfSubUsers: json["numberOfSubUsers"], + numberOfAds: json["numberOfAds"], + countryId: json["countryID"], + countryName: json["countryName"], + isSubscribed: json["isSubscribed"], + subscriptionAppliedId: json["subscriptionAppliedID"], + serviceProviderId: + json["serviceProviderID"], + dateStart: + json["dateStart"] == null ? null : DateTime.parse(json["dateStart"]), + dateEnd: json["dateEnd"] == null ? null : DateTime.parse(json["dateEnd"]), + isExpired: json["isExpired"], + isActive: json["isActive"], + subscriptionTypeEnum: json["subscriptionType"] == null + ? null + : ((json['subscriptionType']) as int).toSubscriptionTypeEnum()); Map toJson() => { - "id": id, - "name": name, - "description": description, - "durationName": durationName, - "durationDays": durationDays, - "price": price, - "currency": currency, - "numberOfBranches": numberOfBranches, - "numberOfSubUsers": numberOfSubUsers, - "numberOfAds": numberOfAds, - "countryID": countryId, - "countryName": countryName, - "isSubscribed": isSubscribed, - "subscriptionAppliedID": subscriptionAppliedId, - "serviceProviderID": serviceProviderId, - "dateStart": dateStart?.toIso8601String(), - "dateEnd": dateEnd?.toIso8601String(), - "isExpired": isExpired, - "isActive": isActive, - }; + "id": id, + "name": name, + "description": description, + "durationName": durationName, + "durationDays": durationDays, + "price": price, + "currency": currency, + "numberOfBranches": numberOfBranches, + "numberOfSubUsers": numberOfSubUsers, + "numberOfAds": numberOfAds, + "countryID": countryId, + "countryName": countryName, + "isSubscribed": isSubscribed, + "subscriptionAppliedID": subscriptionAppliedId, + "serviceProviderID": serviceProviderId, + "dateStart": dateStart?.toIso8601String(), + "dateEnd": dateEnd?.toIso8601String(), + "isExpired": isExpired, + "isActive": isActive, + }; } diff --git a/lib/models/user_models/branch_user.dart b/lib/models/user_models/branch_user.dart index 4e6edfa..1195288 100644 --- a/lib/models/user_models/branch_user.dart +++ b/lib/models/user_models/branch_user.dart @@ -3,11 +3,12 @@ class BranchUser { String? userId; int? serviceProviderId; int? dealershipUserID; - String firstName; - String lastName; - String mobileNo; - String email; - bool isBranchUser; + String? firstName; + String? lastName; + String? mobileNo; + String? email; + bool? isBranchUser; + int? serviceProviderBranchID; BranchUser({ required this.id, @@ -19,19 +20,27 @@ class BranchUser { required this.mobileNo, required this.email, required this.isBranchUser, + this.serviceProviderBranchID, }); - factory BranchUser.fromJson(Map json) => - BranchUser( + factory BranchUser.fromJson(Map json) => BranchUser( id: json["id"], userId: json.containsKey("userID") ? json["userID"] : null, - serviceProviderId: json.containsKey("serviceProviderID") ? json["serviceProviderID"] : null, - dealershipUserID: json.containsKey("dealershipUserID") ? json["dealershipUserID"] : null, - firstName: json["firstName"], - lastName: json["lastName"], - mobileNo: json["mobileNo"], - email: json["email"], - isBranchUser: json.containsKey("isBranchUser") ? json["isBranchUser"] : false, + serviceProviderId: json.containsKey("serviceProviderID") + ? json["serviceProviderID"] + : null, + dealershipUserID: json.containsKey("dealershipUserID") + ? json["dealershipUserID"] + : null, + firstName: json.containsKey("firstName") ? json["firstName"] : null, + lastName: json.containsKey("lastName") ? json["lastName"] : null, + mobileNo: json.containsKey("mobileNo") ? json["mobileNo"] : null, + email: json.containsKey("email") ? json["email"] : null, + isBranchUser: + json.containsKey("isBranchUser") ? json["isBranchUser"] : false, + serviceProviderBranchID: json.containsKey("serviceProviderBranchID") + ? json["serviceProviderBranchID"] + : null, ); Map toJson() => diff --git a/lib/repositories/subscription_repo.dart b/lib/repositories/subscription_repo.dart new file mode 100644 index 0000000..7f5f289 --- /dev/null +++ b/lib/repositories/subscription_repo.dart @@ -0,0 +1,165 @@ +import 'package:mc_common_app/api/api_client.dart'; +import 'package:mc_common_app/classes/app_state.dart'; +import 'package:mc_common_app/classes/consts.dart'; +import 'package:mc_common_app/config/dependencies.dart'; +import 'package:mc_common_app/models/general_models/generic_resp_model.dart'; +import 'package:mc_common_app/models/general_models/m_response.dart'; +import 'package:mc_common_app/models/provider_branches_models/branch_detail_model.dart'; +import 'package:mc_common_app/models/subscriptions_models/branch_user_selection_model.dart'; +import 'package:mc_common_app/models/subscriptions_models/subscription_model.dart'; +import 'package:mc_common_app/models/user_models/branch_user.dart'; + +abstract class SubscriptionRepo { + Future getAllSubscriptions(String? serviceProviderID); + + Future getMySubscriptions(String? serviceProviderID); + + Future getSubscriptionBySP( + String? serviceProviderID, bool isRenew); + + Future calculationUpgradePrice( + String? serviceProviderID, String? newSubscription); + + Future payForProviderSubscription(Map map); + + Future> getSPBranchUser_Get( + Map map); +} + +class SubscriptionRepoImp extends SubscriptionRepo { + @override + Future getAllSubscriptions( + String? serviceProviderID) async { + String t = AppState().getUser.data!.accessToken ?? ""; + Map queryParameters = {}; + if (serviceProviderID != null) { + queryParameters = { + "ID": serviceProviderID, + }; + } + + return await injector.get().getJsonForObject( + (json) => SubscriptionModel.fromJson(json), + ApiConsts.getAllSubscriptions, + token: t, + queryParameters: queryParameters); + } + + @override + Future getSubscriptionBySP( + String? serviceProviderID, bool isRenew) async { + String t = AppState().getUser.data!.accessToken ?? ""; + Map queryParameters = {}; + if (serviceProviderID != null) { + queryParameters = { + "ProviderID": serviceProviderID, + "IsRenew": isRenew.toString(), + }; + } + + return await injector.get().getJsonForObject( + (json) => SubscriptionModel.fromJson(json), + ApiConsts.getSubscriptionBySP, + token: t, + queryParameters: queryParameters, + ); + } + + @override + Future calculationUpgradePrice( + String? serviceProviderID, String? newSubscription) async { + String t = AppState().getUser.data!.accessToken ?? ""; + Map queryParameters = {}; + if (serviceProviderID != null) { + queryParameters = { + "ServiceProviderID": serviceProviderID, + "NewSubscription": newSubscription!, + }; + } + + return await injector.get().getJsonForObject( + (json) => MResponse.fromJson(json), + ApiConsts.calculationUpgradePrice, + token: t, + queryParameters: queryParameters, + ); + } + + @override + Future payForProviderSubscription(Map map) async { + String t = AppState().getUser.data!.accessToken ?? ""; + + return await injector.get().postJsonForObject( + (json) => MResponse.fromJson(json), + ApiConsts.payFortOrder_ProviderSubscription_Create, + map, + token: t, + ); + } + + @override + Future> getSPBranchUser_Get( + Map map) async { + String t = AppState().getUser.data!.accessToken ?? ""; + + GenericRespModel genericRespModel = + await injector.get().getJsonForObject( + (json) => GenericRespModel.fromJson(json), + ApiConsts.getSPBranchUser_Get, + token: t, + queryParameters: map, + ); + + List branchList = []; + + if (genericRespModel.data != null) { + List branches = []; + List branchUsers = []; + + // List.from(json["data"]!.map((x) => BranchUsersDatum.fromJson(x)) + branches = List.from(genericRespModel.data["branches"] + ["data"]! + .map((x) => BranchDetailModel.fromJson(x))); + branchUsers = List.from(genericRespModel.data["branchUsers"] + ["data"]! + .map((x) => BranchUser.fromJson(x))); + for (int i = 0; i < branches.length; i++) { + List availableUsers = []; + for (int j = 0; j < branchUsers.length; j++) { + if (branches[i].id == branchUsers[j].serviceProviderBranchID) { + availableUsers.add(UserSelectionModel( + userId: branchUsers[j].id, + userName: + ("${branchUsers[j].firstName ?? ""} ${branchUsers[j].lastName}"), + isSelected: false)); + } + } + branchList.add(BranchSelectionModel( + branchId: branches[i].id ?? 0, + branchName: branches[i].branchName ?? "", + isSelected: false, + usersList: availableUsers)); + } + } + return branchList; + } + + @override + Future getMySubscriptions( + String? serviceProviderID) async { + String t = AppState().getUser.data!.accessToken ?? ""; + Map queryParameters = {}; + if (serviceProviderID != null) { + queryParameters = { + "ID": serviceProviderID, + }; + } + + + return await injector.get().getJsonForObject( + (json) => SubscriptionModel.fromJson(json), + ApiConsts.getAllSubscriptions, + token: t, + queryParameters: queryParameters); + } +} diff --git a/lib/utils/enums.dart b/lib/utils/enums.dart index 79c33c6..d2123cd 100644 --- a/lib/utils/enums.dart +++ b/lib/utils/enums.dart @@ -193,3 +193,9 @@ enum ChatTypeEnum { ads, requestOffer, } + +enum SubscriptionTypeEnum { + current, + upgrade, + downgrade, +} diff --git a/lib/view_models/payment_view_model.dart b/lib/view_models/payment_view_model.dart index 7e1ea9d..75aff78 100644 --- a/lib/view_models/payment_view_model.dart +++ b/lib/view_models/payment_view_model.dart @@ -9,6 +9,10 @@ import 'package:mc_common_app/services/payments_service.dart'; import 'package:mc_common_app/utils/enums.dart'; import 'package:mc_common_app/utils/navigator.dart'; import 'package:mc_common_app/utils/utils.dart'; +import 'package:mc_common_app/view_models/subscriptions_view_model.dart'; +import 'package:provider/provider.dart'; + +import '../classes/app_state.dart'; class PaymentVM extends ChangeNotifier { final PaymentService paymentService; @@ -49,6 +53,8 @@ class PaymentVM extends ChangeNotifier { } Future onContinuePressed(BuildContext context, {required PaymentTypes paymentType}) async { + + switch (selectedPaymentMethod) { case PaymentMethods.mada: // TODO: Handle this case. @@ -163,6 +169,7 @@ class PaymentVM extends ChangeNotifier { // TOD0: we have to take payment confirmation methods from Backend team and make success callbacks like onAdsPaymentSuccess switch (paymentTypeEnum) { case PaymentTypes.subscription: + onSubscriptionSuccess(context); break; case PaymentTypes.appointment: log("Appointment Payment has been Succeeded"); @@ -182,6 +189,20 @@ class PaymentVM extends ChangeNotifier { ); } + onSubscriptionSuccess(BuildContext context){ + pop(context); + pop(context); + pop(context); + context.read().getMySubscriptions( + AppState() + .getUser + .data + ?.userInfo + ?.providerId + .toString() ?? + ""); + } + Future onVisaCardSelected(BuildContext context, PaymentTypes paymentType) async { currentPaymentType = paymentType; switch (currentPaymentType) { diff --git a/lib/view_models/subscriptions_view_model.dart b/lib/view_models/subscriptions_view_model.dart new file mode 100644 index 0000000..d89c5a9 --- /dev/null +++ b/lib/view_models/subscriptions_view_model.dart @@ -0,0 +1,182 @@ +import 'dart:convert'; + + +import 'package:mc_common_app/classes/app_state.dart'; +import 'package:mc_common_app/models/general_models/m_response.dart'; +import 'package:mc_common_app/models/subscriptions_models/branch_user_selection_model.dart'; +import 'package:mc_common_app/models/subscriptions_models/subscription_model.dart'; +import 'package:mc_common_app/utils/enums.dart'; +import 'package:mc_common_app/view_models/base_view_model.dart'; +import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; + +import '../repositories/subscription_repo.dart'; + +class SubscriptionsVM extends BaseVM { + final SubscriptionRepo subscriptionRepo; + + SubscriptionsVM({required this.subscriptionRepo}); + + //All Subscriptions + int selectedIndex = 0; + late DropValue selectedMothlyTab; + List monthlyTabs = []; + late SubscriptionModel allSubscriptions; + List tempSubscriptions = []; + + //My Subscriptions + + //All Subscriptions + getAllAvailableSubscriptions(String? serviceProviderID) async { + selectedIndex = 0; + setState(ViewState.busy); + allSubscriptions = + await subscriptionRepo.getAllSubscriptions(serviceProviderID); + if (allSubscriptions.messageStatus == 1) { + monthlyTabs.clear(); + var idSet = {}; + for (var d in allSubscriptions.data ?? []) { + if (idSet.add(d.durationDays ?? 0)) { + monthlyTabs.add(DropValue( + d.durationDays, _convertDaysToMonths(d.durationDays ?? 0), "")); + } + } + monthlyTabs.sort((a, b) => a.value.compareTo(b.value)); + selectedMothlyTab = monthlyTabs.first; + filterSubscriptions(); + setState(ViewState.idle); + } else { + setState(ViewState.error); + } + } + + getSubscriptionBySP(String serviceProviderID, bool isRenew) async { + selectedIndex = 0; + setState(ViewState.busy); + allSubscriptions = + await subscriptionRepo.getSubscriptionBySP(serviceProviderID, isRenew); + if (allSubscriptions.messageStatus == 1) { + monthlyTabs.clear(); + var idSet = {}; + for (var d in allSubscriptions.data ?? []) { + if (idSet.add(d.durationDays ?? 0)) { + monthlyTabs.add(DropValue( + d.durationDays, _convertDaysToMonths(d.durationDays ?? 0), "")); + } + } + monthlyTabs.sort((a, b) => a.value.compareTo(b.value)); + selectedMothlyTab = monthlyTabs.first; + filterSubscriptions(); + setState(ViewState.idle); + } else { + setState(ViewState.error); + } + } + + String newPrice = ""; + + calculationUpgradePrice( + String? serviceProviderID, String? newSubscription) async { + setState(ViewState.busy); + MResponse mResponse = await subscriptionRepo.calculationUpgradePrice( + serviceProviderID, newSubscription); + if (mResponse.messageStatus == 1) { + setState(ViewState.idle); + newPrice = mResponse.data.toString(); + } else { + setState(ViewState.error); + } + } + + Future payForSubscription( + int subscriptionId, bool isStartNow, bool isReview, String amount, + {bool isDegrade = false, + List? listOfBranches, + List? listOfUsers}) async { + Map map; + if (isDegrade) { + map = { + // "id": subscription.id.toString(), + // "payFortOrderID": 0, + "providerID": + AppState().getUser.data?.userInfo?.providerId.toString() ?? "", + "subscriptionID": subscriptionId.toString(), + "isStartNow": isStartNow.toString(), + "subscriptionAmount": amount, + "isRenew": isReview.toString(), + "listOfBranches": listOfBranches, + "listOfUsers": listOfUsers + }; + } else { + map = { + // "id": subscription.id.toString(), + // "payFortOrderID": 0, + "providerID": + AppState().getUser.data?.userInfo?.providerId.toString() ?? "", + "subscriptionID": subscriptionId.toString(), + "isStartNow": isStartNow.toString(), + "subscriptionAmount": amount, + "isRenew": isReview.toString() + // "listOfBranches": [], + // "listOfUsers": [] + }; + } + MResponse mResponse = + await subscriptionRepo.payForProviderSubscription(map); + return mResponse; + } + + List? branchSelectionList; + + getSPBranchUser_Get() async { + branchSelectionList = null; + Map map = { + // "id": subscription.id.toString(), + // "payFortOrderID": 0, + "providerID": + AppState().getUser.data?.userInfo?.providerId.toString() ?? "", + // "listOfBranches": [], + // "listOfUsers": [] + }; + branchSelectionList = await subscriptionRepo.getSPBranchUser_Get(map); + if (branchSelectionList!.isNotEmpty) { + branchSelectionList!.first.isOpend = true; + } + setState(ViewState.idle); + } + + String _convertDaysToMonths(int days) { + final int months = days ~/ 30; + final int remainingDays = days % 30; + + String _result = months > 0 + ? '$months Month${months > 1 ? 's' : ''}${remainingDays > 0 ? ' & ' : ''}' + : ''; + _result += remainingDays > 0 + ? '$remainingDays Day${remainingDays > 1 ? 's' : ''}' + : ''; + return _result; + } + + filterSubscriptions() { + tempSubscriptions.clear(); + for (var element in allSubscriptions.data!) { + if (selectedMothlyTab.id == element.durationDays) { + tempSubscriptions.add(element); + } + } + } + + //My Subscriptions + getMySubscriptions(String? serviceProviderID) async { + selectedIndex = 0; + setState(ViewState.busy); + // allSubscriptions = await subscriptionRepo.getAllSubscriptions(serviceProviderID); + allSubscriptions = await subscriptionRepo.getMySubscriptions(serviceProviderID); + if (allSubscriptions.messageStatus == 1) { + // allSubscriptions.data!.sort((a, b) => a.value.compareTo(b.value)); + setState(ViewState.idle); + } else { + setState(ViewState.error); + } + } +} diff --git a/lib/views/payments/payment_methods_view.dart b/lib/views/payments/payment_methods_view.dart index f16e003..95215c1 100644 --- a/lib/views/payments/payment_methods_view.dart +++ b/lib/views/payments/payment_methods_view.dart @@ -12,8 +12,11 @@ import 'package:provider/provider.dart'; class PaymentMethodsView extends StatelessWidget { final PaymentTypes paymentType; + final Function? onTempContinue; - const PaymentMethodsView({Key? key, required this.paymentType}) : super(key: key); + const PaymentMethodsView( + {Key? key, required this.paymentType, this.onTempContinue}) + : super(key: key); @override Widget build(BuildContext context) { @@ -69,8 +72,17 @@ class PaymentMethodsView extends StatelessWidget { child: ShowFillButton( maxHeight: 55, title: "Continue", - onPressed: () { - context.read().onContinuePressed(context, paymentType: paymentType); + onPressed: () async { + bool isNeedToCallPayment = true; + if (onTempContinue != null) { + isNeedToCallPayment = await onTempContinue!(); + } + if (isNeedToCallPayment) { + context.read().onContinuePressed( + context, + paymentType: paymentType, + ); + } }, backgroundColor: MyColors.darkPrimaryColor, ),