From 9b50be3b05644d691186648deef268826f79cf9d Mon Sep 17 00:00:00 2001 From: Faiz Hashmi Date: Tue, 30 Jul 2024 10:24:04 +0300 Subject: [PATCH] Debugging changes for request management chat --- assets/langs/ar-SA.json | 37 +- assets/langs/en-US.json | 179 +++--- lib/generated/codegen_loader.g.dart | 6 +- lib/generated/locale_keys.g.dart | 1 + lib/models/requests_models/request_model.dart | 4 +- lib/utils/enums.dart | 21 +- lib/view_models/ad_view_model.dart | 555 ++++++------------ lib/view_models/appointments_view_model.dart | 552 ++++++----------- lib/view_models/chat_view_model.dart | 122 ++-- lib/view_models/requests_view_model.dart | 123 ++-- lib/views/advertisement/ads_list.dart | 4 +- .../appointments/appointment_detail_view.dart | 3 +- lib/views/chat/chat_view.dart | 245 +++----- lib/views/profile/profile_view.dart | 79 +-- lib/views/requests/offer_list_page.dart | 34 +- lib/views/requests/widget/request_item.dart | 68 +-- 16 files changed, 711 insertions(+), 1322 deletions(-) diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index b6262f6..22b8589 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -186,7 +186,7 @@ "updateBranch": "تحديث فرع", "branches": "الفروع", "requests": "الطلبات", - "noBranchFound" : "لم يتم العثور على فرع", + "noBranchFound": "لم يتم العثور على فرع", "onlyProviderApp": "نأسف هذا التطبيق فقط لمقدمي الخدمات", "pickAddress": "اختر العنوان", "pickLocation": "اختر الموقع", @@ -202,19 +202,19 @@ "completeProfile2": "اكمل الملف الشخصي 2/3", "completeProfile3": "اكمل الملف الشخصي 3/3", "provider": "مزود", - "noRequeststoShow" : "لا توجد طلبات للعرض", + "noRequeststoShow": "لا توجد طلبات للعرض", "myBranches": "فروعي", - "mergeAppointments" : "دمج المواعيد", - "addService" : "أضف الخدمة", - "selectServicestoAdd" : "حدد الخدمات التي تريد إضافتها", + "mergeAppointments": "دمج المواعيد", + "addService": "أضف الخدمة", + "selectServicestoAdd": "حدد الخدمات التي تريد إضافتها", "noServiceFound": "لم يتم العثور على الخدمة", - "selectItems" : "اختيار العناصر", - "noItemSelectedYet" : "لم يتم تحديد أي عنصر بعد", - "totalAdditionalAmount" : "إجمالي المبلغ الإضافي", - "sar" : "ريال سعودي", - "cancel" : "يلغي", - "add" : "يضيف", - "itemsAddedSuccessfully" : "تمت إضافة العناصر بنجاح", + "selectItems": "اختيار العناصر", + "noItemSelectedYet": "لم يتم تحديد أي عنصر بعد", + "totalAdditionalAmount": "إجمالي المبلغ الإضافي", + "sar": "ريال سعودي", + "cancel": "يلغي", + "add": "يضيف", + "itemsAddedSuccessfully": "تمت إضافة العناصر بنجاح", "pleaseSelectItems": "يرجى اختيار العناصر", "totalAmount": "المبلغ الإجمالي", "searchItems": "البحث عن العناصر", @@ -566,15 +566,6 @@ "defineLicenses": "تحديد التراخيص", "logOut": "تسجيل الخروج", "customer": "العميل", - "accept": "قبول" - - - - - - - - - - + "accept": "قبول", + "requestAlreadyInProgress": "هذا الطلب قيد التقدم بالفعل." } \ No newline at end of file diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index ea99de6..5043cc8 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -423,93 +423,93 @@ "reserveAd": "Reserve Ad", "reservationAmount": "Reservation Amount", "belowAmountPayLater": "Below Amount that you will pay later", - "carPrice":"Car Price", - "vatExcluded":"VAT Excluded", - "carInsuranceService":"Car insurance Service", - "toBeDecided":"To be Decided", - "registrationCarPlates":"Registration & Car Plates", - "homeDeliveryService":"Home Delivery Service", - "specialServicechargesInsuranceDeliveryLocation":"Special service charges will be added based on desired insurance and delivery Location", - "estimated":"Estimated", - "servicesReservingAd":"Some services are mandatory while reserving Ad", - "completeReservation":"Complete Reservation", - "contact":"Contact", - "setDateandTime":"Set Date and Time", - "selectOffice":"Select Office", - "availableSlots":"Available Slots", - "bookAndPay":"Book and Pay", - "reservationAmounts":"Reservation Amounts", - "tax":"Tax", + "carPrice": "Car Price", + "vatExcluded": "VAT Excluded", + "carInsuranceService": "Car insurance Service", + "toBeDecided": "To be Decided", + "registrationCarPlates": "Registration & Car Plates", + "homeDeliveryService": "Home Delivery Service", + "specialServicechargesInsuranceDeliveryLocation": "Special service charges will be added based on desired insurance and delivery Location", + "estimated": "Estimated", + "servicesReservingAd": "Some services are mandatory while reserving Ad", + "completeReservation": "Complete Reservation", + "contact": "Contact", + "setDateandTime": "Set Date and Time", + "selectOffice": "Select Office", + "availableSlots": "Available Slots", + "bookAndPay": "Book and Pay", + "reservationAmounts": "Reservation Amounts", + "tax": "Tax", "adsFilter": "Ads Filter", - "searchByCity":"Search By City", - "selectCity":"Select City", - "searchByBrandName":"Search By Brand Name", - "selectVehicleBrand":"Select Vehicle Brand", - "searchByVehicleYear":"Search By Vehicle Year", - "selectYear":"Select Year", - "searchByAdOwner":"Search By Ad Owner", - "selectOwner":"Select Owner", - "search":"Search", - "clearFilters":"Clear Filters", - "book":"Book", - "markAsSold":"Mark As Sold", - "deactivateAd":"Deactivate Ad", - "doWantDeactivateAd":"Do you want to the Deactivate this Ad?", - "stoptheBuyers":"We will stop showing this ad to the buyers", - "cancelReservation":"Cancel Reservation", - "reasonForCancellation":"Reason for Cancellation", - "doWantCancelReservation":"Do you want to cancel the reservation", - "yourAdVisibletoBuy.":"Your ad reservation will be cancelled and this ad will be again visible to everyone to buy", - "completeDeal":"Complete Deal", - "uploadBankReceipt":"Upload Bank Receipt", - "notesForAdmin":"Notes For Admin", - "extendAd":"Extend Ad", - "updateAdDetails":"Do you want to update the Ad Details", - "durationExtendingAd":"You can change the ad duration and details before extending the ad", - "waitingAdminsResponse":"Waiting for Admins Response", - "cancelledByOwner":"Cancelled by Owner", - "cancelledByAdmin":"Cancelled by Admin", - "reservationTimeOver":"Reservation Time Over", - "paymentVerified":"Payment Verified", - "rejectedFormAdmin":"Rejected form Admin", - "waitingAdminPost":"Waiting for admin to post", - "waitingAdminsApproval":"Waiting for Admins Approval", - "sold":"Sold", - "noAdsShow":"No Ads to show", - "damagePartList":"Damage Part List", - "searchPart":"Search Part", - "addSpecialService":"Add Special Service", - "vehicleVar":"Vehicle", - "detailsVar":"Details", - "damageVar":"Damage", + "searchByCity": "Search By City", + "selectCity": "Select City", + "searchByBrandName": "Search By Brand Name", + "selectVehicleBrand": "Select Vehicle Brand", + "searchByVehicleYear": "Search By Vehicle Year", + "selectYear": "Select Year", + "searchByAdOwner": "Search By Ad Owner", + "selectOwner": "Select Owner", + "search": "Search", + "clearFilters": "Clear Filters", + "book": "Book", + "markAsSold": "Mark As Sold", + "deactivateAd": "Deactivate Ad", + "doWantDeactivateAd": "Do you want to the Deactivate this Ad?", + "stoptheBuyers": "We will stop showing this ad to the buyers", + "cancelReservation": "Cancel Reservation", + "reasonForCancellation": "Reason for Cancellation", + "doWantCancelReservation": "Do you want to cancel the reservation", + "yourAdVisibletoBuy.": "Your ad reservation will be cancelled and this ad will be again visible to everyone to buy", + "completeDeal": "Complete Deal", + "uploadBankReceipt": "Upload Bank Receipt", + "notesForAdmin": "Notes For Admin", + "extendAd": "Extend Ad", + "updateAdDetails": "Do you want to update the Ad Details", + "durationExtendingAd": "You can change the ad duration and details before extending the ad", + "waitingAdminsResponse": "Waiting for Admins Response", + "cancelledByOwner": "Cancelled by Owner", + "cancelledByAdmin": "Cancelled by Admin", + "reservationTimeOver": "Reservation Time Over", + "paymentVerified": "Payment Verified", + "rejectedFormAdmin": "Rejected form Admin", + "waitingAdminPost": "Waiting for admin to post", + "waitingAdminsApproval": "Waiting for Admins Approval", + "sold": "Sold", + "noAdsShow": "No Ads to show", + "damagePartList": "Damage Part List", + "searchPart": "Search Part", + "addSpecialService": "Add Special Service", + "vehicleVar": "Vehicle", + "detailsVar": "Details", + "damageVar": "Damage", "partsVar": "Parts", - "additional":"Additional", - "review":"Review", + "additional": "Additional", + "review": "Review", "adVar": "Ad", - "updateAd":"Update Ad", - "createAd":"Create Ad", - "next":"Next", - "submitAd":"Submit Ad", - "selectAdType":"Select Ad Type", - "validUntilSubscriptionExpiration":"Valid Until Subscription Expiration", - "adsRemaining ":"Ads Remaining", - "youLeftAdsGivenSubscription":"You have left with 05 out of 50 ads given in the subscription.", - "updateSubscription":"Update Subscription", - "workInProgress":"Work In Progress", - "visitCompleted":"Visit Completed", - "youWantCancelAppointment":"Do you want to cancel this appointment?", - "appointmentCancelledCannotUndoAction":"Your appointment will be cancelled and you cannot undo this action.", - "appointment":"Appointment", - "rescheduleAppointment":"Reschedule Appointment", - "payforAppointment":"Pay for Appointment", - "appointmentsFilter":"Appointments Filter", - "searchByProvider":"Search By Provider", - "selectProvider":"Select Provider", - "searchByBranch":"Search By Branch", - "searchByCategory":"Search By Category", - "selectCategory":"Select Category", - "searchByService":"Search By Service", - "selectServices":"Select Services", + "updateAd": "Update Ad", + "createAd": "Create Ad", + "next": "Next", + "submitAd": "Submit Ad", + "selectAdType": "Select Ad Type", + "validUntilSubscriptionExpiration": "Valid Until Subscription Expiration", + "adsRemaining ": "Ads Remaining", + "youLeftAdsGivenSubscription": "You have left with 05 out of 50 ads given in the subscription.", + "updateSubscription": "Update Subscription", + "workInProgress": "Work In Progress", + "visitCompleted": "Visit Completed", + "youWantCancelAppointment": "Do you want to cancel this appointment?", + "appointmentCancelledCannotUndoAction": "Your appointment will be cancelled and you cannot undo this action.", + "appointment": "Appointment", + "rescheduleAppointment": "Reschedule Appointment", + "payforAppointment": "Pay for Appointment", + "appointmentsFilter": "Appointments Filter", + "searchByProvider": "Search By Provider", + "selectProvider": "Select Provider", + "searchByBranch": "Search By Branch", + "searchByCategory": "Search By Category", + "selectCategory": "Select Category", + "searchByService": "Search By Service", + "selectServices": "Select Services", "modifyPackage": "Modify Package", "schedule": "Schedule", "serviceLocation": "Service Location:", @@ -527,13 +527,13 @@ "dateAndTime": "Date and Time", "timeLocation": "Time & Location", "serviceCharges": "Service Charges", - "locationCharges" : "Location Charges", + "locationCharges": "Location Charges", "payableNow": "Payable Now", "remainingAmount": "Remaining Amount", "branchesFilter": "Branches Filter", -"searchByDistance": "Search By Distance", + "searchByDistance": "Search By Distance", "searchByMinimumRatings": "Search By Minimum Ratings", -"chat": "Chat", + "chat": "Chat", "noRequestsShow": "No Requests to show.", "typeMessageHere": "Type your message here..", "reject": "Reject", @@ -561,11 +561,12 @@ "termPrivacy": "Term & Privacy", "inviteFriends": "Invite Friends", "more": "More", - "language" :"Language", + "language": "Language", "mySubscriptions": "My Subscriptions", "subscriptions": "Subscriptions", "defineLicenses": "Define Licenses", "logOut": "Log Out", "customer": "Customer", - "accept": "Accept" + "accept": "Accept", + "requestAlreadyInProgress": "This request is already in progress." } \ No newline at end of file diff --git a/lib/generated/codegen_loader.g.dart b/lib/generated/codegen_loader.g.dart index 8f4e664..c0acc33 100644 --- a/lib/generated/codegen_loader.g.dart +++ b/lib/generated/codegen_loader.g.dart @@ -582,7 +582,8 @@ class CodegenLoader extends AssetLoader{ "defineLicenses": "تحديد التراخيص", "logOut": "تسجيل الخروج", "customer": "العميل", - "accept": "قبول" + "accept": "قبول", + "requestAlreadyInProgress": "هذا الطلب قيد التقدم بالفعل." }; static const Map en_US = { "firstTimeLogIn": "First Time Log In", @@ -1153,7 +1154,8 @@ static const Map en_US = { "defineLicenses": "Define Licenses", "logOut": "Log Out", "customer": "Customer", - "accept": "Accept" + "accept": "Accept", + "requestAlreadyInProgress": "This request is already in progress." }; static const Map> mapLocales = {"ar_SA": ar_SA, "en_US": en_US}; } diff --git a/lib/generated/locale_keys.g.dart b/lib/generated/locale_keys.g.dart index 355108c..b02be9e 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -546,5 +546,6 @@ abstract class LocaleKeys { static const logOut = 'logOut'; static const customer = 'customer'; static const accept = 'accept'; + static const requestAlreadyInProgress = 'requestAlreadyInProgress'; } diff --git a/lib/models/requests_models/request_model.dart b/lib/models/requests_models/request_model.dart index 68e12c2..ed1d4cc 100644 --- a/lib/models/requests_models/request_model.dart +++ b/lib/models/requests_models/request_model.dart @@ -34,7 +34,7 @@ class RequestModel { List requestProviderItem; bool isActive; int createdBy; - DateTime createdOn; + String? createdOn; dynamic modifiedBy; dynamic modifiedOn; List chatMessages; @@ -110,7 +110,7 @@ class RequestModel { requestProviderItem: List.from(json["requestProviderItem"].map((x) => x)), isActive: json["isActive"], createdBy: json["createdBy"], - createdOn: DateTime.parse(json["createdOn"]), + createdOn: json["createdOn"], modifiedBy: json["modifiedBy"], modifiedOn: json["modifiedOn"], chatMessages: [], diff --git a/lib/utils/enums.dart b/lib/utils/enums.dart index d2123cd..b2b0cbe 100644 --- a/lib/utils/enums.dart +++ b/lib/utils/enums.dart @@ -5,6 +5,17 @@ // unverified, // } +// + +// + +class AppEnums { + static const int requestFilterEnumId = 16; // Requests Filter Enums + static const int myAdsFilterEnumId = 18; // My Ads Filter Enums + static const int exploreAdsFilterEnumId = 23; // Explore Ads Filter Enums + static const int appointmentsFilterEnumId = 13; // Appointments Filter Enums +} + enum VehicleType { car, motorCycle, @@ -78,15 +89,7 @@ enum PaymentMethods { tamara, } -enum PaymentTypes { - subscription, - appointment, - adReserve, - ads, - request, - extendAds, - partialAppointment -} +enum PaymentTypes { subscription, appointment, adReserve, ads, request, extendAds, partialAppointment } enum AdCreationSteps { vehicleDetails, diff --git a/lib/view_models/ad_view_model.dart b/lib/view_models/ad_view_model.dart index ff636b1..230d81f 100644 --- a/lib/view_models/ad_view_model.dart +++ b/lib/view_models/ad_view_model.dart @@ -36,10 +36,7 @@ class AdVM extends BaseVM { final CommonAppServices commonServices; - AdVM( - {required this.commonServices, - required this.commonRepo, - required this.adsRepo}); + AdVM({required this.commonServices, required this.commonRepo, required this.adsRepo}); AdCreationSteps currentProgressStep = AdCreationSteps.vehicleDetails; @@ -100,23 +97,19 @@ class AdVM extends BaseVM { List specialServiceCards = []; - void addNewSpecialServiceCard( - {required SpecialServiceCard specialServiceCard}) { - int index = vehicleAdsSpecialServices.indexWhere((element) => - element.name == specialServiceCard.serviceSelectedId!.selectedOption); + void addNewSpecialServiceCard({required SpecialServiceCard specialServiceCard}) { + int index = vehicleAdsSpecialServices.indexWhere((element) => element.name == specialServiceCard.serviceSelectedId!.selectedOption); if (index != -1) { vehicleAdsSpecialServices[index].isSelected = true; } specialServiceCards.add(specialServiceCard); - vehicleAdsSpecialServicesId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleAdsSpecialServicesId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); adSpecialServiceDate = ""; notifyListeners(); } void removeSpecialServiceCard(int index) { - String option = - specialServiceCards.elementAt(index).serviceSelectedId!.selectedOption; + String option = specialServiceCards.elementAt(index).serviceSelectedId!.selectedOption; for (var value in vehicleAdsSpecialServices) { if (value.name == option) { @@ -144,9 +137,7 @@ class AdVM extends BaseVM { } for (var damagePartDetail in vehicleDamageParts) { - if (damagePartDetail.partName! - .toLowerCase() - .contains(text.toLowerCase())) { + if (damagePartDetail.partName!.toLowerCase().contains(text.toLowerCase())) { vehiclePartsSearchResults.add(damagePartDetail); notifyListeners(); @@ -176,44 +167,36 @@ class AdVM extends BaseVM { List myAdsFilterOptions = []; populateAdsFilterList() async { - if (myAdsFilterOptions.isNotEmpty && exploreAdsFilterOptions.isNotEmpty) + if (myAdsFilterOptions.isNotEmpty && exploreAdsFilterOptions.isNotEmpty) { return; + } if (myAdsEnums.isEmpty) { - myAdsEnums = await commonRepo.getEnumTypeValues( - enumTypeID: 18); //18 is to get My Ad Filter Enums + myAdsEnums = await commonRepo.getEnumTypeValues(enumTypeID: AppEnums.myAdsFilterEnumId); } if (exploreAdsEnums.isEmpty) { - exploreAdsEnums = await commonRepo.getEnumTypeValues( - enumTypeID: 23); // 23 is to get Explore Ad Filter Enums + exploreAdsEnums = await commonRepo.getEnumTypeValues(enumTypeID: AppEnums.exploreAdsFilterEnumId); } exploreAdsFilterOptions.clear(); myAdsFilterOptions.clear(); for (int i = 0; i < myAdsEnums.length; i++) { - myAdsFilterOptions.add(FilterListModel( - title: myAdsEnums[i].enumValueStr, - isSelected: false, - id: myAdsEnums[i].enumValue)); + myAdsFilterOptions.add(FilterListModel(title: myAdsEnums[i].enumValueStr, isSelected: false, id: myAdsEnums[i].enumValue)); } - myAdsFilterOptions.insert( - 0, FilterListModel(title: "All Ads", isSelected: true, id: 0)); + myAdsFilterOptions.insert(0, FilterListModel(title: "All Ads", isSelected: true, id: 0)); for (int i = 0; i < exploreAdsEnums.length; i++) { - exploreAdsFilterOptions.add(FilterListModel( - title: "${exploreAdsEnums[i].enumValueStr} Ads", - isSelected: false, - id: exploreAdsEnums[i].enumValue)); + exploreAdsFilterOptions.add(FilterListModel(title: "${exploreAdsEnums[i].enumValueStr} Ads", isSelected: false, id: exploreAdsEnums[i].enumValue)); } - exploreAdsFilterOptions.insert( - 0, FilterListModel(title: "All Ads", isSelected: true, id: 0)); + exploreAdsFilterOptions.insert(0, FilterListModel(title: "All Ads", isSelected: true, id: 0)); + logger.i("myAdsEnums: ${myAdsEnums.length}"); + logger.i("exploreAdsEnums: ${exploreAdsEnums.length}"); notifyListeners(); } applyFilterOnExploreAds({required CreatedByRoleEnum createdByRoleFilter}) { if (exploreAdsFilterOptions.isEmpty) return; - int index = exploreAdsFilterOptions.indexWhere( - (element) => element.id.toCreatedByRoleEnum() == createdByRoleFilter); + int index = exploreAdsFilterOptions.indexWhere((element) => element.id.toCreatedByRoleEnum() == createdByRoleFilter); for (var value in exploreAdsFilterOptions) { value.isSelected = false; @@ -225,17 +208,14 @@ class AdVM extends BaseVM { return; } - exploreAdsFilteredList = exploreAds - .where((element) => element.createdByRoleEnum == createdByRoleFilter) - .toList(); + exploreAdsFilteredList = exploreAds.where((element) => element.createdByRoleEnum == createdByRoleFilter).toList(); notifyListeners(); } applyFilterOnMyAds({required AdPostStatus adPostStatusEnum}) { if (myAdsFilterOptions.isEmpty) return; - int index = myAdsFilterOptions - .indexWhere((element) => element.id.toAdPostEnum() == adPostStatusEnum); + int index = myAdsFilterOptions.indexWhere((element) => element.id.toAdPostEnum() == adPostStatusEnum); for (var value in myAdsFilterOptions) { value.isSelected = false; @@ -257,21 +237,15 @@ class AdVM extends BaseVM { return; } - myAdsFilteredList = myAds - .where((element) => - element.statusID! == adPostStatusEnum.getIdFromAdPostStatusEnum()) - .toList(); + myAdsFilteredList = myAds.where((element) => element.statusID! == adPostStatusEnum.getIdFromAdPostStatusEnum()).toList(); notifyListeners(); } Future getMyAds() async { setState(ViewState.busy); myAds = await adsRepo.getAllAds(isMyAds: true); - final myActiveAds = myAds - .where((element) => element.adPostStatus == AdPostStatus.active) - .toList(); - myActiveAdsForHome = - myActiveAds.length >= 3 ? myActiveAds.take(3).toList() : myActiveAds; + final myActiveAds = myAds.where((element) => element.adPostStatus == AdPostStatus.active).toList(); + myActiveAdsForHome = myActiveAds.length >= 3 ? myActiveAds.take(3).toList() : myActiveAds; await getMyReservedAds(); notifyListeners(); setState(ViewState.idle); @@ -285,11 +259,9 @@ class AdVM extends BaseVM { return myReservedAds; } - Future createReserveAd( - {required int adId, required BuildContext context}) async { + Future createReserveAd({required int adId, required BuildContext context}) async { Utils.showLoading(context); - GenericRespModel genericRespModel = - await adsRepo.createReserveAd(adId: adId); + GenericRespModel genericRespModel = await adsRepo.createReserveAd(adId: adId); if (genericRespModel.messageStatus == null) { Utils.hideLoading(context); @@ -319,8 +291,7 @@ class AdVM extends BaseVM { } Future getVehicleAdsSpecialServices() async { - vehicleAdsSpecialServices = - await adsRepo.getSpecialServices(specialServiceId: 1); + vehicleAdsSpecialServices = await adsRepo.getSpecialServices(specialServiceId: 1); notifyListeners(); } @@ -339,8 +310,7 @@ class AdVM extends BaseVM { Future markAdAsSold(BuildContext context, {required int adId}) async { Utils.showLoading(context); - GenericRespModel respModel = await adsRepo.updateAdStatus( - adId: adId, adStatusToUpdate: AdPostStatus.sold); + GenericRespModel respModel = await adsRepo.updateAdStatus(adId: adId, adStatusToUpdate: AdPostStatus.sold); if (respModel.messageStatus != 1) { Utils.hideLoading(context); @@ -350,8 +320,7 @@ class AdVM extends BaseVM { Utils.hideLoading(context); Utils.showToast("A has been marked as sold successfully!"); updateIsExploreAds(false); - applyFilterOnMyAds( - adPostStatusEnum: AdPostStatus.sold); //pending for review + applyFilterOnMyAds(adPostStatusEnum: AdPostStatus.sold); //pending for review navigateReplaceWithName(context, AppRoutes.dashboard); } @@ -367,18 +336,13 @@ class AdVM extends BaseVM { Utils.hideLoading(context); Utils.showToast(LocaleKeys.AdDeletedSuccessfully.tr()); updateIsExploreAds(false); - applyFilterOnMyAds( - adPostStatusEnum: AdPostStatus.active); //pending for review + applyFilterOnMyAds(adPostStatusEnum: AdPostStatus.active); //pending for review navigateReplaceWithName(context, AppRoutes.dashboard); } - Future cancelMyAdReservation(BuildContext context, - {required int adId, required String reason}) async { + Future cancelMyAdReservation(BuildContext context, {required int adId, required String reason}) async { Utils.showLoading(context); - GenericRespModel respModel = await adsRepo.cancelMyAdReservation( - adId: adId, - adsReserveStatus: 11, - reason: reason); // 11 is to Cancel Reservation + GenericRespModel respModel = await adsRepo.cancelMyAdReservation(adId: adId, adsReserveStatus: 11, reason: reason); // 11 is to Cancel Reservation if (respModel.messageStatus != 1) { Utils.hideLoading(context); @@ -388,16 +352,13 @@ class AdVM extends BaseVM { Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourReservationCancelled.tr()); updateIsExploreAds(false); - applyFilterOnMyAds( - adPostStatusEnum: AdPostStatus.active); //pending for review + applyFilterOnMyAds(adPostStatusEnum: AdPostStatus.active); //pending for review navigateReplaceWithName(context, AppRoutes.dashboard); } - Future deactivateTheAd(BuildContext context, - {required int adId}) async { + Future deactivateTheAd(BuildContext context, {required int adId}) async { Utils.showLoading(context); - GenericRespModel respModel = await adsRepo.updateAdStatus( - adId: adId, adStatusToUpdate: AdPostStatus.cancelled); + GenericRespModel respModel = await adsRepo.updateAdStatus(adId: adId, adStatusToUpdate: AdPostStatus.cancelled); if (respModel.messageStatus != 1) { Utils.hideLoading(context); @@ -407,8 +368,7 @@ class AdVM extends BaseVM { Utils.hideLoading(context); Utils.showToast(LocaleKeys.adDeactivatedSuccessfully.tr()); updateIsExploreAds(false); - applyFilterOnMyAds( - adPostStatusEnum: AdPostStatus.cancelled); //pending for review + applyFilterOnMyAds(adPostStatusEnum: AdPostStatus.cancelled); //pending for review navigateReplaceWithName(context, AppRoutes.dashboard); } @@ -433,18 +393,14 @@ class AdVM extends BaseVM { // notifyListeners(); // } - Future getVehicleBrandsByVehicleTypeId( - {int vehicleIdForEditAd = -1}) async { + Future getVehicleBrandsByVehicleTypeId({int vehicleIdForEditAd = -1}) async { // if (vehicleTypeId.selectedId == -1 || vehicleBrands.isNotEmpty) { // return; // } isFetchingLists = true; notifyListeners(); - vehicleBrands = await commonRepo.getVehicleBrands( - vehicleTypeId: vehicleIdForEditAd != -1 - ? vehicleIdForEditAd - : vehicleTypeId.selectedId); + vehicleBrands = await commonRepo.getVehicleBrands(vehicleTypeId: vehicleIdForEditAd != -1 ? vehicleIdForEditAd : vehicleTypeId.selectedId); isFetchingLists = false; notifyListeners(); } @@ -455,9 +411,7 @@ class AdVM extends BaseVM { // } isFetchingLists = true; notifyListeners(); - vehicleDetails = await commonRepo.getVehicleDetails( - vehicleTypeId: vehicleTypeId.selectedId, - vehicleBrandId: vehicleBrandId.selectedId); + vehicleDetails = await commonRepo.getVehicleDetails(vehicleTypeId: vehicleTypeId.selectedId, vehicleBrandId: vehicleBrandId.selectedId); if (vehicleDetails != null) { vehicleModels = vehicleDetails!.vehicleModels!; @@ -515,8 +469,7 @@ class AdVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleTypeId(SelectionModel id) async { vehicleTypeId = id; @@ -524,18 +477,13 @@ class AdVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleBrandId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleBrandId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - Future updateSelectionVehicleBrandId(SelectionModel id, - {bool isForSearch = false}) async { + Future updateSelectionVehicleBrandId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - VehicleBrandsModel brand = - vehicleBrands.firstWhere((element) => element.id == id.selectedId); - DropValue brandValue = - DropValue(brand.id ?? 0, brand.vehicleBrandDescription ?? "", ""); - if (!ifAlreadyExist( - list: vehicleBrandsAdSearchHistory, value: brandValue)) { + VehicleBrandsModel brand = vehicleBrands.firstWhere((element) => element.id == id.selectedId); + DropValue brandValue = DropValue(brand.id ?? 0, brand.vehicleBrandDescription ?? "", ""); + if (!ifAlreadyExist(list: vehicleBrandsAdSearchHistory, value: brandValue)) { addToVehicleBrandsAdSearchHistory(value: brandValue); } notifyListeners(); @@ -548,22 +496,18 @@ class AdVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleModelId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleModelId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleModelId(SelectionModel id) { vehicleModelId = id; notifyListeners(); } - SelectionModel vehicleModelYearId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleModelYearId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateSelectionVehicleModelYearId(SelectionModel id, - {bool isForSearch = false}) { + void updateSelectionVehicleModelYearId(SelectionModel id, {bool isForSearch = false}) { if (isForSearch) { - VehicleYearModel year = vehicleModelYears - .firstWhere((element) => element.id == id.selectedId); + VehicleYearModel year = vehicleModelYears.firstWhere((element) => element.id == id.selectedId); DropValue yearValue = DropValue(year.id ?? 0, year.modelYear ?? "", ""); if (!ifAlreadyExist(list: vehicleYearAdSearchHistory, value: yearValue)) { addToVehicleYearAdSearchHistory(value: yearValue); @@ -575,32 +519,28 @@ class AdVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleColorId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleColorId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleColorId(SelectionModel id) { vehicleColorId = id; notifyListeners(); } - SelectionModel vehicleConditionId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleConditionId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleConditionId(SelectionModel id) { vehicleConditionId = id; notifyListeners(); } - SelectionModel vehicleCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleCategoryId(SelectionModel id) { vehicleCategoryId = id; notifyListeners(); } - SelectionModel vehicleMileageId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleMileageId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleMileageId(SelectionModel id) { vehicleMileageId = id; @@ -653,16 +593,14 @@ class AdVM extends BaseVM { vehicleDescription = desc; } - SelectionModel vehicleTransmissionId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleTransmissionId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleTransmissionId(SelectionModel id) { vehicleTransmissionId = id; notifyListeners(); } - SelectionModel vehicleSellerTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleSellerTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleSellerTypeId(SelectionModel id) { vehicleSellerTypeId = id; @@ -673,38 +611,31 @@ class AdVM extends BaseVM { void updateSelectionVehicleDamagePartId(SelectionModel id, int index) { vehicleDamageCards[index].partSelectedId = id; - int partIndex = vehicleDamageParts - .indexWhere((element) => element.partName == id.selectedOption); + int partIndex = vehicleDamageParts.indexWhere((element) => element.partName == id.selectedOption); if (partIndex != -1) { // vehicleDamageParts[partIndex].isSelected = true; } notifyListeners(); } - SelectionModel vehicleCountryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleCountryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleCountryId(SelectionModel id) async { vehicleCountryId = id; isCountryFetching = true; notifyListeners(); - vehicleCities = await commonRepo.getVehicleCities( - countryId: vehicleCountryId.selectedId); + vehicleCities = await commonRepo.getVehicleCities(countryId: vehicleCountryId.selectedId); isCountryFetching = false; notifyListeners(); } - SelectionModel vehicleCityId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleCityId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateSelectionVehicleCityId(SelectionModel id, - {bool isForSearch = false}) async { + void updateSelectionVehicleCityId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - VehicleCityModel city = - vehicleCities.firstWhere((element) => element.id == id.selectedId); + VehicleCityModel city = vehicleCities.firstWhere((element) => element.id == id.selectedId); DropValue cityValue = DropValue(city.id ?? 0, city.cityName ?? "", ""); - if (!ifAlreadyExist( - list: vehicleLocationAdSearchHistory, value: cityValue)) { + if (!ifAlreadyExist(list: vehicleLocationAdSearchHistory, value: cityValue)) { addToVehicleLocationAdSearchHistory(value: cityValue); } notifyListeners(); @@ -714,32 +645,28 @@ class AdVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleAdDurationId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleAdDurationId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleAdDurationId(SelectionModel id) { vehicleAdDurationId = id; notifyListeners(); } - SelectionModel vehicleExtendAdDurationId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleExtendAdDurationId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleExtendAdDurationId(SelectionModel id) { vehicleAdDurationId = id; notifyListeners(); } - SelectionModel vehicleAdReservableId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleAdReservableId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleAdReservableId(SelectionModel id) { vehicleAdReservableId = id; notifyListeners(); } - SelectionModel vehicleAdsSpecialServicesId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleAdsSpecialServicesId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleAdsSpecialServicesId(SelectionModel id) async { vehicleAdsSpecialServicesId = id; @@ -769,8 +696,7 @@ class AdVM extends BaseVM { adSSTimeSlots[index].isSelected = true; } - SelectionModel vehicleAdsPhotoServiceDate = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleAdsPhotoServiceDate = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleVehicleAdsPhotoServiceDate(SelectionModel id) { vehicleAdsPhotoServiceDate = id; @@ -779,17 +705,14 @@ class AdVM extends BaseVM { slotSelectedIndex = null; for (var value in ssPhotoScheduleModel!.photoOfficeScheduleSlots!) { - if (value.slotDate!.toFormattedDateWithoutTime() == - vehicleAdsPhotoServiceDate.selectedOption) { - adSSTimeSlots.add(TimeSlotModel( - slot: value.startTime!, isSelected: false, slotId: value.id!)); + if (value.slotDate!.toFormattedDateWithoutTime() == vehicleAdsPhotoServiceDate.selectedOption) { + adSSTimeSlots.add(TimeSlotModel(slot: value.startTime!, isSelected: false, slotId: value.id!)); } } notifyListeners(); } - SelectionModel vehicleAdsCarCheckServicesDate = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleAdsCarCheckServicesDate = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateVehicleAdsCarCheckServicesDate(SelectionModel id) { vehicleAdsCarCheckServicesDate = id; @@ -798,10 +721,8 @@ class AdVM extends BaseVM { slotSelectedIndex = null; for (var value in ssCarCheckScheduleModel!.branchScheduleSlots!) { - if (value.slotDate!.toFormattedDateWithoutTime() == - vehicleAdsCarCheckServicesDate.selectedOption) { - adSSTimeSlots.add(TimeSlotModel( - slot: value.startTime!, isSelected: false, slotId: value.id!)); + if (value.slotDate!.toFormattedDateWithoutTime() == vehicleAdsCarCheckServicesDate.selectedOption) { + adSSTimeSlots.add(TimeSlotModel(slot: value.startTime!, isSelected: false, slotId: value.id!)); } } notifyListeners(); @@ -838,8 +759,7 @@ class AdVM extends BaseVM { for (var element in ssPhotoScheduleModel!.photoOfficeScheduleSlots!) { if (!slotDates.contains(element.slotDate!)) { slotDates.add(element.slotDate!); - vehicleAdsSpecialServiceDates.add(DropValue(element.id!.toInt(), - element.slotDate!.toFormattedDateWithoutTime(), "")); + vehicleAdsSpecialServiceDates.add(DropValue(element.id!.toInt(), element.slotDate!.toFormattedDateWithoutTime(), "")); } } @@ -857,8 +777,7 @@ class AdVM extends BaseVM { for (var element in ssCarCheckScheduleModel!.branchScheduleSlots!) { if (!slotDates.contains(element.slotDate!)) { slotDates.add(element.slotDate!); - vehicleAdsSpecialServiceDates.add(DropValue(element.id!.toInt(), - element.slotDate!.toFormattedDateWithoutTime(), "")); + vehicleAdsSpecialServiceDates.add(DropValue(element.id!.toInt(), element.slotDate!.toFormattedDateWithoutTime(), "")); } } @@ -883,8 +802,7 @@ class AdVM extends BaseVM { } if (vehicleModelYearId.selectedId == -1) { - vehicleModelYearId.errorValue = - LocaleKeys.vehicle_selectVehicleModelYear.tr(); + vehicleModelYearId.errorValue = LocaleKeys.vehicle_selectVehicleModelYear.tr(); isValidated = false; } else { vehicleModelYearId.errorValue = ""; @@ -919,16 +837,14 @@ class AdVM extends BaseVM { } if (vehicleTransmissionId.selectedId == -1) { - vehicleTransmissionId.errorValue = - LocaleKeys.vehicle_vehicleTransmission.tr(); + vehicleTransmissionId.errorValue = LocaleKeys.vehicle_vehicleTransmission.tr(); isValidated = false; } else { vehicleTransmissionId.errorValue = ""; } if (vehicleSellerTypeId.selectedId == -1) { - vehicleSellerTypeId.errorValue = - LocaleKeys.vehicle_vehicleSellerType.tr(); + vehicleSellerTypeId.errorValue = LocaleKeys.vehicle_vehicleSellerType.tr(); isValidated = false; } else { vehicleSellerTypeId.errorValue = ""; @@ -978,8 +894,7 @@ class AdVM extends BaseVM { } else { vehicleDescError = ""; } - if ((pickedPostingImages.isEmpty || pickedPostingImages.length < 3) && - !isAdEditEnabled) { + if ((pickedPostingImages.isEmpty || pickedPostingImages.length < 3) && !isAdEditEnabled) { vehicleImageError = GlobalConsts.attachImageError; isValidated = false; } else { @@ -1006,8 +921,7 @@ class AdVM extends BaseVM { for (var element in vehicleDamageCards) { if (element.partSelectedId!.selectedId == -1) { - element.partSelectedId!.errorValue = - LocaleKeys.vehicle_vehiclePart.tr(); + element.partSelectedId!.errorValue = LocaleKeys.vehicle_vehiclePart.tr(); isValidated = false; } else { element.partSelectedId!.errorValue = ""; @@ -1139,9 +1053,7 @@ class AdVM extends BaseVM { currentProgressStep = AdCreationSteps.vehicleDetails; resetValues(); updateIsExploreAds(false); - applyFilterOnMyAds( - adPostStatusEnum: - AdPostStatus.pendingForReview); //pending for review + applyFilterOnMyAds(adPostStatusEnum: AdPostStatus.pendingForReview); //pending for review navigateReplaceWithName(context, AppRoutes.dashboard); } catch (e) { Utils.hideLoading(context); @@ -1176,8 +1088,7 @@ class AdVM extends BaseVM { List pickedPostingImages = []; void removeImageFromList(String filePath) { - int index = pickedPostingImages - .indexWhere((element) => element.filePath == filePath); + int index = pickedPostingImages.indexWhere((element) => element.filePath == filePath); if (index == -1) { return; } @@ -1202,8 +1113,7 @@ class AdVM extends BaseVM { String receiptPdfFileError = ""; void removePdfFileFromList(String filePath) { - int index = pickedReceiptPdfFiles - .indexWhere((element) => element.filePath == filePath); + int index = pickedReceiptPdfFiles.indexWhere((element) => element.filePath == filePath); if (index == -1) { return; } @@ -1245,8 +1155,7 @@ class AdVM extends BaseVM { List pickedDamageImages = []; void removeDamageImageFromList(String filePath) { - int index = - pickedDamageImages.indexWhere((element) => element.path == filePath); + int index = pickedDamageImages.indexWhere((element) => element.path == filePath); if (index == -1) { return; } @@ -1255,8 +1164,7 @@ class AdVM extends BaseVM { } void removeDamagePartCard(int index) { - String option = - vehicleDamageCards.elementAt(index).partSelectedId!.selectedOption; + String option = vehicleDamageCards.elementAt(index).partSelectedId!.selectedOption; for (var value in vehicleDamageParts) { if (value.partName == option) { @@ -1269,12 +1177,10 @@ class AdVM extends BaseVM { notifyListeners(); } - void removeDamageImageFromCard( - int imageIndex, String filePath, int cardIndex) { + void removeDamageImageFromCard(int imageIndex, String filePath, int cardIndex) { VehicleDamageCard card = vehicleDamageCards.elementAt(cardIndex); if (card.partImages == null) return; - int index = - card.partImages!.indexWhere((element) => element.filePath == filePath); + int index = card.partImages!.indexWhere((element) => element.filePath == filePath); if (index == -1) { return; } @@ -1296,32 +1202,19 @@ class AdVM extends BaseVM { specialServiceCards.clear(); vehicleAdsSpecialServices.clear(); currentProgressStep = AdCreationSteps.vehicleDetails; - vehicleTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleBrandId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleModelYearId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleColorId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleConditionId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleMileageId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleTransmissionId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleSellerTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleCountryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleCityId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleAdDurationId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleBrandId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleModelYearId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleColorId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleConditionId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleMileageId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleTransmissionId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleSellerTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleCountryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleCityId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleAdDurationId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); vehicleDemandAmount = ""; vehicleVin = ""; vehicleTitle = ""; @@ -1340,83 +1233,63 @@ class AdVM extends BaseVM { } resetSpecialServiceBottomSheet() { - photoOfficeSelectedId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + photoOfficeSelectedId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); selectedPhotoSSSchedulesByOffice = SSPhotoOfficeScheduleModel(); selectedPhotoOfficeSlotDateTime = null; photoSSSchedulesByOffices = []; } - SelectionModel photoOfficeSelectedId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel photoOfficeSelectedId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updatePhotoOfficeSelectedId(SelectionModel id) { photoOfficeSelectedId = id; - selectedPhotoSSSchedulesByOffice = - photoSSSchedulesByOffices.elementAt(int.parse(id.itemPrice)); + selectedPhotoSSSchedulesByOffice = photoSSSchedulesByOffices.elementAt(int.parse(id.itemPrice)); notifyListeners(); } updateSelectedPhotoOfficeAppointmentDate({required int dateIndex}) { - for (var element - in selectedPhotoSSSchedulesByOffice.customTimeDateSlotList!) { + for (var element in selectedPhotoSSSchedulesByOffice.customTimeDateSlotList!) { element.date!.isSelected = false; for (var element in element.availableSlots!) { element.isSelected = false; } } - selectedPhotoSSSchedulesByOffice - .customTimeDateSlotList![dateIndex].date!.isSelected = true; + selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![dateIndex].date!.isSelected = true; selectedPhotoSSSchedulesByOffice.selectedDateIndex = dateIndex; final date = TimeSlotModel( - date: selectedPhotoSSSchedulesByOffice - .customTimeDateSlotList![dateIndex].date!.date, - slotId: selectedPhotoSSSchedulesByOffice - .customTimeDateSlotList![dateIndex].date!.slotId, + date: selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![dateIndex].date!.date, + slotId: selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![dateIndex].date!.slotId, isSelected: true, slot: "", ); - selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel = - CustomTimeDateSlotModel(date: date); + selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel = CustomTimeDateSlotModel(date: date); notifyListeners(); } int? selectedPhotoOfficeSlotDateTime; updateSelectedAppointmentSlotByDate({required int slotIndex}) { - for (var element - in selectedPhotoSSSchedulesByOffice.customTimeDateSlotList!) { + for (var element in selectedPhotoSSSchedulesByOffice.customTimeDateSlotList!) { for (var element in element.availableSlots!) { element.isSelected = false; } } int index = selectedPhotoSSSchedulesByOffice.selectedDateIndex!; - selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![index] - .availableSlots![slotIndex].isSelected = true; - selectedPhotoOfficeSlotDateTime = selectedPhotoSSSchedulesByOffice - .customTimeDateSlotList![index].availableSlots![slotIndex].slotId; - selectedPhotoSSSchedulesByOffice - .selectedCustomTimeDateSlotModel!.availableSlots = - selectedPhotoSSSchedulesByOffice - .customTimeDateSlotList![index].availableSlots!; + selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![index].availableSlots![slotIndex].isSelected = true; + selectedPhotoOfficeSlotDateTime = selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![index].availableSlots![slotIndex].slotId; + selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel!.availableSlots = selectedPhotoSSSchedulesByOffice.customTimeDateSlotList![index].availableSlots!; notifyListeners(); } List photoSSSchedulesByOffices = []; - SSPhotoOfficeScheduleModel selectedPhotoSSSchedulesByOffice = - SSPhotoOfficeScheduleModel(); + SSPhotoOfficeScheduleModel selectedPhotoSSSchedulesByOffice = SSPhotoOfficeScheduleModel(); - Future getPhotographyServiceScheduleListByOffices( - {required double latitude, - required double longitude, - bool isNeedToRebuild = false}) async { + Future getPhotographyServiceScheduleListByOffices({required double latitude, required double longitude, bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); try { - photoSSSchedulesByOffices = - await commonRepo.getPhotographyServiceScheduleListByOffices( - lat: latitude, long: longitude); + photoSSSchedulesByOffices = await commonRepo.getPhotographyServiceScheduleListByOffices(lat: latitude, long: longitude); if (isNeedToRebuild) setState(ViewState.idle); } catch (e) { if (isNeedToRebuild) setState(ViewState.idle); @@ -1436,28 +1309,18 @@ class AdVM extends BaseVM { // } // } - Future onAdSSBookAppointmentPressed(BuildContext context, - {required AdDetailsModel adDetailsModel, - required int adsSpecialServiceID}) async { + Future onAdSSBookAppointmentPressed(BuildContext context, {required AdDetailsModel adDetailsModel, required int adsSpecialServiceID}) async { bool isValidated = false; if (selectedPhotoSSSchedulesByOffice.photoOfficeID == null) { isValidated = false; - } else if (selectedPhotoSSSchedulesByOffice - .selectedCustomTimeDateSlotModel == - null || - !selectedPhotoSSSchedulesByOffice - .selectedCustomTimeDateSlotModel!.date!.isSelected) { + } else if (selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel == null || !selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel!.date!.isSelected) { isValidated = false; } else { - if (selectedPhotoSSSchedulesByOffice - .selectedCustomTimeDateSlotModel!.availableSlots == - null) { + if (selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel!.availableSlots == null) { isValidated = false; } else { - TimeSlotModel slot = selectedPhotoSSSchedulesByOffice - .selectedCustomTimeDateSlotModel!.availableSlots! - .firstWhere((element) => element.isSelected); + TimeSlotModel slot = selectedPhotoSSSchedulesByOffice.selectedCustomTimeDateSlotModel!.availableSlots!.firstWhere((element) => element.isSelected); if (slot.date.isNotEmpty) { isValidated = true; } @@ -1469,8 +1332,7 @@ class AdVM extends BaseVM { } Utils.showLoading(context); try { - GenericRespModel genericRespModel = - await adsRepo.createAppointmentForAdSpecialService( + GenericRespModel genericRespModel = await adsRepo.createAppointmentForAdSpecialService( adId: adDetailsModel.id ?? 0, photoOfficeID: photoOfficeSelectedId.selectedId, photoOfficeSlotID: selectedPhotoOfficeSlotDateTime ?? 0, @@ -1479,12 +1341,10 @@ class AdVM extends BaseVM { Utils.hideLoading(context); if (genericRespModel.messageStatus != 1) { - Utils.showToast( - LocaleKeys.error.tr() + ": ${genericRespModel.message}"); + Utils.showToast(LocaleKeys.error.tr() + ": ${genericRespModel.message}"); } else { resetSpecialServiceBottomSheet(); - navigateWithName(context, AppRoutes.paymentMethodsView, - arguments: PaymentTypes.ads); + navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.ads); } } catch (e) { Utils.hideLoading(context); @@ -1509,8 +1369,7 @@ class AdVM extends BaseVM { List vehicleImages = []; for (var image in pickedPostingImages) { - vehicleImages - .add(await convertFileToVehiclePostingImages(imageModel: image)); + vehicleImages.add(await convertFileToVehiclePostingImages(imageModel: image)); } List vehicleDamageImages = []; @@ -1518,8 +1377,7 @@ class AdVM extends BaseVM { for (var card in vehicleDamageCards) { if (card.partImages != null && card.partImages!.isNotEmpty) { for (var image in card.partImages!) { - VehiclePostingDamageParts stringImage = - await convertFileToVehiclePostingDamageParts( + VehiclePostingDamageParts stringImage = await convertFileToVehiclePostingDamageParts( imageModel: image, damagePartId: card.partSelectedId!.selectedId, ); @@ -1551,26 +1409,19 @@ class AdVM extends BaseVM { demandAmount: int.parse(vehicleDemandAmount), vehiclePostingImages: vehicleImages, vehiclePostingDamageParts: vehicleDamageImages, - phoneNo: - isPhoneNumberShown ? adPhoneNumberDialCode + adPhoneNumber : null, - whatsAppNo: (isPhoneNumberShown && isNumberOnWhatsApp) - ? adPhoneNumberDialCode + adPhoneNumber - : null, + phoneNo: isPhoneNumberShown ? adPhoneNumberDialCode + adPhoneNumber : null, + whatsAppNo: (isPhoneNumberShown && isNumberOnWhatsApp) ? adPhoneNumberDialCode + adPhoneNumber : null, ); - AdsCreationPayloadModel adsCreationPayloadModel = - AdsCreationPayloadModel(ads: ads, vehiclePosting: vehiclePosting); - GenericRespModel respModel = await adsRepo.createOrUpdateAd( - adsCreationPayloadModel: adsCreationPayloadModel, - isCreateNew: !isAdEditEnabled); + AdsCreationPayloadModel adsCreationPayloadModel = AdsCreationPayloadModel(ads: ads, vehiclePosting: vehiclePosting); + GenericRespModel respModel = await adsRepo.createOrUpdateAd(adsCreationPayloadModel: adsCreationPayloadModel, isCreateNew: !isAdEditEnabled); Utils.showToast(respModel.message.toString()); return Future.value(respModel.messageStatus); } - Future convertFileToVehiclePostingImages( - {required ImageModel imageModel}) async { + Future convertFileToVehiclePostingImages({required ImageModel imageModel}) async { VehiclePostingImages vehiclePostingImages; if (imageModel.isFromNetwork ?? false) { vehiclePostingImages = VehiclePostingImages( @@ -1586,16 +1437,14 @@ class AdVM extends BaseVM { imageName: fileName, imageStr: image, imageUrl: file.path, - vehiclePostingID: - isAdEditEnabled ? previousAdDetails!.vehiclePostingID : null, + vehiclePostingID: isAdEditEnabled ? previousAdDetails!.vehiclePostingID : null, ); } return vehiclePostingImages; } - Future convertFileToVehiclePostingDamageParts( - {required ImageModel imageModel, required int damagePartId}) async { + Future convertFileToVehiclePostingDamageParts({required ImageModel imageModel, required int damagePartId}) async { VehiclePostingDamageParts vehiclePostingDamageParts; if (imageModel.isFromNetwork ?? false) { @@ -1603,8 +1452,7 @@ class AdVM extends BaseVM { id: imageModel.id, vehicleDamagePartID: damagePartId, imageUrl: imageModel.filePath, - vehiclePostingID: - isAdEditEnabled ? previousAdDetails!.vehiclePostingID : null, + vehiclePostingID: isAdEditEnabled ? previousAdDetails!.vehiclePostingID : null, ); } else { File file = File(imageModel.filePath!); @@ -1627,11 +1475,9 @@ class AdVM extends BaseVM { vehicleBrands = await commonRepo.getVehicleBrands(vehicleTypeId: -1); } if (vehicleModelYears.isEmpty) { - vehicleModelYears = - await commonRepo.getVehicleModelYears(vehicleTypeId: -1); + vehicleModelYears = await commonRepo.getVehicleModelYears(vehicleTypeId: -1); } - vehicleCities = await commonRepo.getVehicleCities( - countryId: -1); // fetch all the cities + vehicleCities = await commonRepo.getVehicleCities(countryId: -1); // fetch all the cities } ifAlreadyExist({required List list, required DropValue value}) { @@ -1649,8 +1495,7 @@ class AdVM extends BaseVM { //BRANDS List vehicleBrandsAdSearchHistory = []; - void removeVehicleBrandsAdSearchHistory( - {bool isClear = false, required int index}) { + void removeVehicleBrandsAdSearchHistory({bool isClear = false, required int index}) { if (isClear) { vehicleBrandsAdSearchHistory.clear(); notifyListeners(); @@ -1674,8 +1519,7 @@ class AdVM extends BaseVM { // LOCATION List vehicleLocationAdSearchHistory = []; - void removeVehicleLocationAdSearchHistory( - {bool isClear = false, required int index}) { + void removeVehicleLocationAdSearchHistory({bool isClear = false, required int index}) { if (isClear) { vehicleLocationAdSearchHistory.clear(); notifyListeners(); @@ -1698,18 +1542,13 @@ class AdVM extends BaseVM { // OWNER - SelectionModel vehicleOwnerId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleOwnerId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateSelectionVehicleAdOwnerId(SelectionModel id, - {bool isForSearch = false}) { + void updateSelectionVehicleAdOwnerId(SelectionModel id, {bool isForSearch = false}) { if (isForSearch) { - EnumsModel owner = - exploreAdsEnums.firstWhere((element) => element.id == id.selectedId); - DropValue ownerValue = - DropValue(owner.id, "${owner.enumValueStr} Ads", ""); - if (!ifAlreadyExist( - list: vehicleYearAdSearchHistory, value: ownerValue)) { + EnumsModel owner = exploreAdsEnums.firstWhere((element) => element.id == id.selectedId); + DropValue ownerValue = DropValue(owner.id, "${owner.enumValueStr} Ads", ""); + if (!ifAlreadyExist(list: vehicleYearAdSearchHistory, value: ownerValue)) { addToVehicleAdOwnerSearchHistory(value: ownerValue); } notifyListeners(); @@ -1721,8 +1560,7 @@ class AdVM extends BaseVM { List vehicleAdOwnerSearchHistory = []; - void removeVehicleAdOwnerSearchHistory( - {bool isClear = false, required int index}) { + void removeVehicleAdOwnerSearchHistory({bool isClear = false, required int index}) { if (isClear) { vehicleAdOwnerSearchHistory.clear(); notifyListeners(); @@ -1746,8 +1584,7 @@ class AdVM extends BaseVM { // YEAR List vehicleYearAdSearchHistory = []; - void removeVehicleYearAdSearchHistory( - {bool isClear = false, required int index}) { + void removeVehicleYearAdSearchHistory({bool isClear = false, required int index}) { if (isClear) { vehicleYearAdSearchHistory.clear(); notifyListeners(); @@ -1823,14 +1660,11 @@ class AdVM extends BaseVM { ///// Edit Work Amir - void onEditUpdateAdPressed( - BuildContext context, AdDetailsModel previousDetails) { + void onEditUpdateAdPressed(BuildContext context, AdDetailsModel previousDetails) { isAdEditEnabled = true; previousAdDetails = previousDetails; autoFillSelectedVehicleType(); - navigateWithName(context, AppRoutes.selectAdTypeView, - arguments: - AppState().currentAppType == AppType.provider ? true : false); + navigateWithName(context, AppRoutes.selectAdTypeView, arguments: AppState().currentAppType == AppType.provider ? true : false); } autoFillSelectedVehicleType() async { @@ -1854,8 +1688,7 @@ class AdVM extends BaseVM { await getVehicleAdsDuration(); } if (vehicleAdsDurations.isNotEmpty) { - int index = vehicleAdsDurations.indexWhere( - (element) => element.price == previousAdDetails!.adsDurationPrice!); + int index = vehicleAdsDurations.indexWhere((element) => element.price == previousAdDetails!.adsDurationPrice!); if (index != -1) { updateVehicleAdDurationId( SelectionModel( @@ -1872,8 +1705,7 @@ class AdVM extends BaseVM { List vehicleOldDamageImagesList = []; void removeVehicleOldDamageImagesList(String imageUrl) { - int index = vehicleOldDamageImagesList - .indexWhere((element) => element.imageUrl == imageUrl); + int index = vehicleOldDamageImagesList.indexWhere((element) => element.imageUrl == imageUrl); if (index == -1) { return; } @@ -1882,86 +1714,50 @@ class AdVM extends BaseVM { } autoFillSelectedVehicleAdsDetails() async { - int index = vehicleBrands.indexWhere((element) => - element.id == previousAdDetails!.vehicle!.model!.vehicleBrandID); + int index = vehicleBrands.indexWhere((element) => element.id == previousAdDetails!.vehicle!.model!.vehicleBrandID); if (index != -1) { - await updateSelectionVehicleBrandId(SelectionModel( - selectedId: vehicleBrands[index].id!, - selectedOption: vehicleBrands[index].vehicleBrandDescription ?? "")); - } - - updateSelectionVehicleModelId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.model!.id!, - selectedOption: previousAdDetails!.vehicle!.model!.label ?? "")); - updateSelectionVehicleModelYearId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.modelyear!.id!, - selectedOption: previousAdDetails!.vehicle!.modelyear!.label ?? "")); - updateSelectionVehicleColorId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.color!.id!, - selectedOption: previousAdDetails!.vehicle!.color!.label ?? "")); - updateSelectionVehicleConditionId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.condition!.id!, - selectedOption: previousAdDetails!.vehicle!.condition!.label ?? "")); - updateSelectionVehicleCategoryId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.category!.id!, - selectedOption: previousAdDetails!.vehicle!.category!.label ?? "")); + await updateSelectionVehicleBrandId(SelectionModel(selectedId: vehicleBrands[index].id!, selectedOption: vehicleBrands[index].vehicleBrandDescription ?? "")); + } + + updateSelectionVehicleModelId(SelectionModel(selectedId: previousAdDetails!.vehicle!.model!.id!, selectedOption: previousAdDetails!.vehicle!.model!.label ?? "")); + updateSelectionVehicleModelYearId(SelectionModel(selectedId: previousAdDetails!.vehicle!.modelyear!.id!, selectedOption: previousAdDetails!.vehicle!.modelyear!.label ?? "")); + updateSelectionVehicleColorId(SelectionModel(selectedId: previousAdDetails!.vehicle!.color!.id!, selectedOption: previousAdDetails!.vehicle!.color!.label ?? "")); + updateSelectionVehicleConditionId(SelectionModel(selectedId: previousAdDetails!.vehicle!.condition!.id!, selectedOption: previousAdDetails!.vehicle!.condition!.label ?? "")); + updateSelectionVehicleCategoryId(SelectionModel(selectedId: previousAdDetails!.vehicle!.category!.id!, selectedOption: previousAdDetails!.vehicle!.category!.label ?? "")); updateSelectionVehicleMileageId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.mileage!.id!, - selectedOption: - "${previousAdDetails!.vehicle!.mileage!.mileageStart} - ${previousAdDetails!.vehicle!.mileage!.mileageEnd}")); - updateSelectionVehicleTransmissionId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.transmission!.id!, - selectedOption: previousAdDetails!.vehicle!.transmission!.label ?? "")); - updateSelectionVehicleSellerTypeId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.sellertype!.id!, - selectedOption: previousAdDetails!.vehicle!.sellertype!.label ?? "")); - int indexCountry = vehicleCountries.indexWhere( - (element) => element.id == previousAdDetails!.vehicle!.countryID); + selectedId: previousAdDetails!.vehicle!.mileage!.id!, selectedOption: "${previousAdDetails!.vehicle!.mileage!.mileageStart} - ${previousAdDetails!.vehicle!.mileage!.mileageEnd}")); + updateSelectionVehicleTransmissionId(SelectionModel(selectedId: previousAdDetails!.vehicle!.transmission!.id!, selectedOption: previousAdDetails!.vehicle!.transmission!.label ?? "")); + updateSelectionVehicleSellerTypeId(SelectionModel(selectedId: previousAdDetails!.vehicle!.sellertype!.id!, selectedOption: previousAdDetails!.vehicle!.sellertype!.label ?? "")); + int indexCountry = vehicleCountries.indexWhere((element) => element.id == previousAdDetails!.vehicle!.countryID); if (indexCountry != -1) { - updateSelectionVehicleCountryId(SelectionModel( - selectedId: vehicleCountries[index].id!, - selectedOption: vehicleCountries[index].countryName ?? "")); + updateSelectionVehicleCountryId(SelectionModel(selectedId: vehicleCountries[index].id!, selectedOption: vehicleCountries[index].countryName ?? "")); } - updateSelectionVehicleCityId(SelectionModel( - selectedId: previousAdDetails!.vehicle!.cityID!, - selectedOption: previousAdDetails!.vehicle!.cityName ?? "")); - vehicleDemandAmount = - previousAdDetails!.vehicle!.demandAmount!.toInt().toString(); + updateSelectionVehicleCityId(SelectionModel(selectedId: previousAdDetails!.vehicle!.cityID!, selectedOption: previousAdDetails!.vehicle!.cityName ?? "")); + vehicleDemandAmount = previousAdDetails!.vehicle!.demandAmount!.toInt().toString(); vehicleVin = previousAdDetails!.vehicle!.vehicleVIN.toString(); vehicleTitle = previousAdDetails!.vehicle!.vehicleTitle.toString(); - vehicleDescription = - previousAdDetails!.vehicle!.vehicleDescription.toString(); - financeAvailableStatus = - previousAdDetails!.vehicle!.isFinanceAvailable ?? false; + vehicleDescription = previousAdDetails!.vehicle!.vehicleDescription.toString(); + financeAvailableStatus = previousAdDetails!.vehicle!.isFinanceAvailable ?? false; - if (previousAdDetails!.vehicle!.image != null && - previousAdDetails!.vehicle!.image!.isNotEmpty) { + if (previousAdDetails!.vehicle!.image != null && previousAdDetails!.vehicle!.image!.isNotEmpty) { for (var element in previousAdDetails!.vehicle!.image!) { if (element.imageUrl != null) { - ImageModel imageModel = ImageModel( - id: element.id, filePath: element.imageUrl, isFromNetwork: true); + ImageModel imageModel = ImageModel(id: element.id, filePath: element.imageUrl, isFromNetwork: true); pickedPostingImages.add(imageModel); } } } - if (previousAdDetails!.vehicle!.damagereport != null && - previousAdDetails!.vehicle!.damagereport!.isNotEmpty) { + if (previousAdDetails!.vehicle!.damagereport != null && previousAdDetails!.vehicle!.damagereport!.isNotEmpty) { for (var element in previousAdDetails!.vehicle!.damagereport!) { int index = -1; if (vehicleDamageCards.isNotEmpty) { index = ifDamagePartAlreadyThere(element.vehicleDamagePartID!); - ImageModel imageModel = ImageModel( - id: element.id!, - filePath: element.imageUrl!, - isFromNetwork: true); + ImageModel imageModel = ImageModel(id: element.id!, filePath: element.imageUrl!, isFromNetwork: true); vehicleDamageCards[index].partImages!.add(imageModel); } else { - ImageModel imageModel = ImageModel( - id: element.id!, - filePath: element.imageUrl!, - isFromNetwork: true); + ImageModel imageModel = ImageModel(id: element.id!, filePath: element.imageUrl!, isFromNetwork: true); VehicleDamageCard vehicleDamageCard = VehicleDamageCard( partSelectedId: SelectionModel( @@ -1975,13 +1771,9 @@ class AdVM extends BaseVM { } } - if (previousAdDetails!.specialservice != null && - previousAdDetails!.specialservice!.isNotEmpty) { + if (previousAdDetails!.specialservice != null && previousAdDetails!.specialservice!.isNotEmpty) { for (var element in previousAdDetails!.specialservice!) { - SelectionModel vehicleAdsSpecialServicesId = SelectionModel( - selectedId: element.specialServiceID!, - selectedOption: element.name ?? "", - itemPrice: element.price.toString()); + SelectionModel vehicleAdsSpecialServicesId = SelectionModel(selectedId: element.specialServiceID!, selectedOption: element.name ?? "", itemPrice: element.price.toString()); SpecialServiceCard specialServiceCard = SpecialServiceCard( serviceSelectedId: vehicleAdsSpecialServicesId, description: element.description ?? "", @@ -1996,8 +1788,7 @@ class AdVM extends BaseVM { } } - selectionDurationStartDate = - DateHelper.formatDateT(previousAdDetails!.startdate ?? ""); + selectionDurationStartDate = DateHelper.formatDateT(previousAdDetails!.startdate ?? ""); isPhoneNumberShown = previousAdDetails!.phoneNo != null; if (isPhoneNumberShown) { adPhoneNumber = previousAdDetails!.phoneNo ?? ""; @@ -2011,13 +1802,11 @@ class AdVM extends BaseVM { } int ifDamagePartAlreadyThere(int partId) { - return vehicleDamageCards - .indexWhere((element) => element.partSelectedId!.selectedId == partId); + return vehicleDamageCards.indexWhere((element) => element.partSelectedId!.selectedId == partId); } int ifSpecialServiceAlreadyThere(int id) { - return specialServiceCards - .indexWhere((element) => element.serviceSelectedId!.selectedId == id); + return specialServiceCards.indexWhere((element) => element.serviceSelectedId!.selectedId == id); } } diff --git a/lib/view_models/appointments_view_model.dart b/lib/view_models/appointments_view_model.dart index 33496d8..9158fb0 100644 --- a/lib/view_models/appointments_view_model.dart +++ b/lib/view_models/appointments_view_model.dart @@ -6,6 +6,7 @@ import 'package:mc_common_app/config/routes.dart'; import 'package:mc_common_app/extensions/int_extensions.dart'; import 'package:mc_common_app/extensions/string_extensions.dart'; import 'package:mc_common_app/generated/locale_keys.g.dart'; +import 'package:mc_common_app/main.dart'; import 'package:mc_common_app/models/appointments_models/appointment_list_model.dart'; import 'package:mc_common_app/models/appointments_models/appointment_slots.dart'; import 'package:mc_common_app/models/appointments_models/service_schedule_model.dart'; @@ -45,11 +46,7 @@ class AppointmentsVM extends BaseVM { final BranchRepo branchRepo; final AppointmentRepo appointmentRepo; - AppointmentsVM( - {required this.commonServices, - required this.appointmentRepo, - required this.commonRepo, - required this.branchRepo}); + AppointmentsVM({required this.commonServices, required this.appointmentRepo, required this.commonRepo, required this.branchRepo}); bool isUpcommingEnabled = true; bool isFetchingLists = false; @@ -76,8 +73,7 @@ class AppointmentsVM extends BaseVM { List serviceAppointmentScheduleList = []; bool ifItemAlreadySelected(int id) { - int indexFound = allSelectedItemsInAppointments - .indexWhere((element) => element.id == id); + int indexFound = allSelectedItemsInAppointments.indexWhere((element) => element.id == id); if (indexFound != -1) { return true; } @@ -98,8 +94,7 @@ class AppointmentsVM extends BaseVM { Future onItemsSelectedInService() async { if (currentServiceSelection != null) { - int index = servicesInCurrentAppointment.indexWhere((element) => - element.serviceId == currentServiceSelection!.serviceId!); + int index = servicesInCurrentAppointment.indexWhere((element) => element.serviceId == currentServiceSelection!.serviceId!); if (index == -1) { double totalPrice = 0.0; @@ -115,13 +110,9 @@ class AppointmentsVM extends BaseVM { } } - Future onPayNowPressedForAppointment( - {required BuildContext context, required int appointmentID}) async { - context - .read() - .updateAppointmentIdsForPayment(ids: [appointmentID]); - navigateWithName(context, AppRoutes.paymentMethodsView, - arguments: PaymentTypes.partialAppointment); + Future onPayNowPressedForAppointment({required BuildContext context, required int appointmentID}) async { + context.read().updateAppointmentIdsForPayment(ids: [appointmentID]); + navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.partialAppointment); } Future onBookAppointmentPressed(BuildContext context) async { @@ -129,8 +120,7 @@ class AppointmentsVM extends BaseVM { bool isSuccess = false; List appointmentIdsList = []; try { - GenericRespModel genericRespModel = - await appointmentRepo.createServiceAppointment( + GenericRespModel genericRespModel = await appointmentRepo.createServiceAppointment( schedules: serviceAppointmentScheduleList, serviceProviderID: selectedBranchModel!.serviceProviderId ?? 0, ); @@ -156,17 +146,13 @@ class AppointmentsVM extends BaseVM { } context.read().onNavbarTapped(1); - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.booked); + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.booked); Utils.hideLoading(context); resetAfterBookingAppointment(); if (isSuccess) { if (amountToPayForAppointment > 0) { - context - .read() - .updateAppointmentIdsForPayment(ids: appointmentIdsList); - navigateWithName(context, AppRoutes.paymentMethodsView, - arguments: PaymentTypes.appointment); + context.read().updateAppointmentIdsForPayment(ids: appointmentIdsList); + navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.appointment); } else { Utils.showToast(LocaleKeys.appointmentBookedSuccessfully.tr()); getMyAppointments(); @@ -178,37 +164,28 @@ class AppointmentsVM extends BaseVM { } } - Future onConfirmAppointmentPressed( - {required BuildContext context, required appointmentId}) async { - context - .read() - .updateAppointmentIdsForPayment(ids: [appointmentId]); - navigateWithName(context, AppRoutes.paymentMethodsView, - arguments: PaymentTypes.appointment); + Future onConfirmAppointmentPressed({required BuildContext context, required appointmentId}) async { + context.read().updateAppointmentIdsForPayment(ids: [appointmentId]); + navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.appointment); } - Future onCancelAppointmentPressed( - {required BuildContext context, - required AppointmentListModel appointmentListModel}) async { + Future onCancelAppointmentPressed({required BuildContext context, required AppointmentListModel appointmentListModel}) async { Utils.showLoading(context); try { - GenericRespModel genericRespModel = - await appointmentRepo.cancelOrRescheduleServiceAppointment( + GenericRespModel genericRespModel = await appointmentRepo.cancelOrRescheduleServiceAppointment( serviceAppointmentID: appointmentListModel.id ?? 0, serviceSlotID: appointmentListModel.serviceSlotID ?? 0, appointmentScheduleAction: 2, // 1 for Reschedule and 2 for Cancel ); - if (genericRespModel.messageStatus == 2 || - genericRespModel.data == null) { + if (genericRespModel.messageStatus == 2 || genericRespModel.data == null) { Utils.hideLoading(context); Utils.showToast("${genericRespModel.message.toString()}"); return; } if (genericRespModel.messageStatus == 1) { context.read().onNavbarTapped(1); - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.cancelled); + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.cancelled); Utils.showToast("${genericRespModel.message.toString()}"); await getMyAppointments(); Utils.hideLoading(context); @@ -239,8 +216,7 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel branchSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel branchSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateProviderCategoryId(SelectionModel id) { branchSelectedCategoryId = id; @@ -255,30 +231,25 @@ class AppointmentsVM extends BaseVM { void updateBranchServiceId(SelectionModel id) async { branchSelectedServiceId = id; - currentServiceSelection = branchServices.firstWhere( - (element) => element.serviceProviderServiceId == id.selectedId); + currentServiceSelection = branchServices.firstWhere((element) => element.serviceProviderServiceId == id.selectedId); notifyListeners(); } void removeServiceInCurrentAppointment(int index) { int serviceId = servicesInCurrentAppointment - .elementAt(index) - .serviceProviderServiceId ?? - -1; - allSelectedItemsInAppointments.removeWhere( - (element) => element.serviceProviderServiceId == serviceId); + .elementAt(index) + .serviceProviderServiceId ?? -1; + allSelectedItemsInAppointments.removeWhere((element) => element.serviceProviderServiceId == serviceId); servicesInCurrentAppointment.removeAt(index); notifyListeners(); } resetCategorySelectionBottomSheet() { selectedSubServicesCounter = 0; - branchSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); isHomeTapped = false; - branchSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); currentServiceSelection = null; } @@ -293,30 +264,22 @@ class AppointmentsVM extends BaseVM { Future populateAppointmentsFilterList() async { if (appointmentsFilterOptions.isNotEmpty) return; - myAppointmentsEnum = await commonRepo.getEnumTypeValues( - enumTypeID: 13); // 13 is to get Appointments Filter Enums + myAppointmentsEnum = await commonRepo.getEnumTypeValues(enumTypeID: 13); // 13 is to get Appointments Filter Enums for (int i = 0; i < myAppointmentsEnum.length; i++) { - appointmentsFilterOptions.add(FilterListModel( - title: myAppointmentsEnum[i].enumValueStr, - isSelected: false, - id: myAppointmentsEnum[i].enumValue)); + appointmentsFilterOptions.add(FilterListModel(title: myAppointmentsEnum[i].enumValueStr, isSelected: false, id: myAppointmentsEnum[i].enumValue)); } - appointmentsFilterOptions.insert( - 0, FilterListModel(title: "All Appointments", isSelected: true, id: 0)); + appointmentsFilterOptions.insert(0, FilterListModel(title: "All Appointments", isSelected: true, id: 0)); // TODO: THIS SHOULD REMOVED AND ADDED IN THE ENUMS API - appointmentsFilterOptions.add( - FilterListModel(title: "Work In Progress", isSelected: false, id: 7)); - appointmentsFilterOptions.add( - FilterListModel(title: "Visit Completed", isSelected: false, id: 8)); + appointmentsFilterOptions.add(FilterListModel(title: "Work In Progress", isSelected: false, id: 7)); + appointmentsFilterOptions.add(FilterListModel(title: "Visit Completed", isSelected: false, id: 8)); + logger.i("appointmentsFilterOptions: ${appointmentsFilterOptions.length}"); notifyListeners(); } - applyFilterOnAppointmentsVM( - {required AppointmentStatusEnum appointmentStatusEnum, - bool isNeedCustomerFilter = false}) { + applyFilterOnAppointmentsVM({required AppointmentStatusEnum appointmentStatusEnum, bool isNeedCustomerFilter = false}) { // isNeedCustomerFilter IS ONLY FOR THE PROVIDER APP if (appointmentsFilterOptions.isEmpty) return; for (var value in appointmentsFilterOptions) { @@ -324,8 +287,7 @@ class AppointmentsVM extends BaseVM { } for (var element in appointmentsFilterOptions) { - if (element.id == - appointmentStatusEnum.getIdFromAppointmentStatusEnum()) { + if (element.id == appointmentStatusEnum.getIdFromAppointmentStatusEnum()) { element.isSelected = true; } } @@ -340,11 +302,7 @@ class AppointmentsVM extends BaseVM { return; } - myFilteredAppointments = myAppointments - .where((element) => - element.appointmentStatusID! == - appointmentStatusEnum.getIdFromAppointmentStatusEnum()) - .toList(); + myFilteredAppointments = myAppointments.where((element) => element.appointmentStatusID! == appointmentStatusEnum.getIdFromAppointmentStatusEnum()).toList(); if (isNeedCustomerFilter) findAppointmentsBasedOnCustomers(); notifyListeners(); } @@ -360,9 +318,7 @@ class AppointmentsVM extends BaseVM { // Create a list of CustomerData instances myFilteredAppointments2 = uniqueCustomerIDs.map((id) { - List list = myFilteredAppointments - .where((item) => item.customerID == id) - .toList(); + List list = myFilteredAppointments.where((item) => item.customerID == id).toList(); AppointmentListModel model = list.first; model.customerAppointmentList = list; return model; @@ -385,29 +341,20 @@ class AppointmentsVM extends BaseVM { Future getMyAppointments({bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); - myAppointments = - await appointmentRepo.getMyAppointmentsForCustomersByFilters(); + myAppointments = await appointmentRepo.getMyAppointmentsForCustomersByFilters(); // myFilteredAppointments = myAppointments; - myUpComingAppointments = myAppointments - .where((element) => - element.appointmentStatusEnum == AppointmentStatusEnum.confirmed) - .toList(); + myUpComingAppointments = myAppointments.where((element) => element.appointmentStatusEnum == AppointmentStatusEnum.confirmed).toList(); setState(ViewState.idle); - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.allAppointments); + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.allAppointments); notifyListeners(); } AppointmentSlots? appointmentSlots; - Future getAppointmentSlotsInfo( - {required Map map, - required BuildContext context, - bool isNeedToRebuild = false}) async { + Future getAppointmentSlotsInfo({required Map map, required BuildContext context, bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); try { - MResponse genericRespModel = - await appointmentRepo.getAppointmentSlots(map); + MResponse genericRespModel = await appointmentRepo.getAppointmentSlots(map); if (genericRespModel.messageStatus == 1) { appointmentSlots = AppointmentSlots.fromJson(genericRespModel.data); } else { @@ -418,29 +365,21 @@ class AppointmentsVM extends BaseVM { } } - Future getMyAppointmentsForProvider(Map map, - {bool isNeedToRebuild = false}) async { + Future getMyAppointmentsForProvider(Map map, {bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); myAppointments = await appointmentRepo.getMyAppointmentsForProvider(map); myFilteredAppointments = myAppointments; - myUpComingAppointments = myAppointments - .where((element) => - element.appointmentStatusEnum == AppointmentStatusEnum.booked) - .toList(); - - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.allAppointments, - isNeedCustomerFilter: true); + myUpComingAppointments = myAppointments.where((element) => element.appointmentStatusEnum == AppointmentStatusEnum.booked).toList(); + + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.allAppointments, isNeedCustomerFilter: true); setState(ViewState.idle); } - updateAppointmentStatus(Map map, - {bool isNeedToRebuild = false}) async { + updateAppointmentStatus(Map map, {bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); try { - MResponse genericRespModel = - await appointmentRepo.updateAppointmentStatus(map); + MResponse genericRespModel = await appointmentRepo.updateAppointmentStatus(map); if (genericRespModel.messageStatus == 1) { Utils.showToast(LocaleKeys.appointmentStatusUpdated.tr()); @@ -452,12 +391,10 @@ class AppointmentsVM extends BaseVM { } } - updateAppointmentPaymentStatus(Map map, - {bool isNeedToRebuild = false}) async { + updateAppointmentPaymentStatus(Map map, {bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); try { - MResponse genericRespModel = - await appointmentRepo.updateAppointmentPaymentStatus(map); + MResponse genericRespModel = await appointmentRepo.updateAppointmentPaymentStatus(map); if (genericRespModel.messageStatus == 1) { Utils.showToast(LocaleKeys.paymentStatusUpdated.tr()); @@ -469,11 +406,9 @@ class AppointmentsVM extends BaseVM { } } - Future createMergeAppointment(Map map, - {bool isNeedToRebuild = false}) async { + Future createMergeAppointment(Map map, {bool isNeedToRebuild = false}) async { if (isNeedToRebuild) setState(ViewState.busy); - MResponse genericRespModel = - await appointmentRepo.createMergeAppointment(map); + MResponse genericRespModel = await appointmentRepo.createMergeAppointment(map); return genericRespModel; } @@ -481,16 +416,10 @@ class AppointmentsVM extends BaseVM { bool inNeedToEnableMergeButton = false; updateCheckBoxInMergeRequest(int currentIndex) { - myFilteredAppointments2[selectedAppointmentIndex] - .customerAppointmentList![currentIndex] - .isSelected = !(myFilteredAppointments2[selectedAppointmentIndex] - .customerAppointmentList?[currentIndex] - .isSelected ?? - false); - - int count = countSelected(myFilteredAppointments2[selectedAppointmentIndex] - .customerAppointmentList ?? - []); + myFilteredAppointments2[selectedAppointmentIndex].customerAppointmentList![currentIndex].isSelected = + !(myFilteredAppointments2[selectedAppointmentIndex].customerAppointmentList?[currentIndex].isSelected ?? false); + + int count = countSelected(myFilteredAppointments2[selectedAppointmentIndex].customerAppointmentList ?? []); if (count > 1) inNeedToEnableMergeButton = true; else @@ -505,55 +434,32 @@ class AppointmentsVM extends BaseVM { .length; } - updateSelectedAppointmentDate( - {required int dateIndex, required int scheduleIndex}) { - for (var element in serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList!) { + updateSelectedAppointmentDate({required int dateIndex, required int scheduleIndex}) { + for (var element in serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList!) { element.date!.isSelected = false; } - serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList![dateIndex] - .date! - .isSelected = true; + serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList![dateIndex].date!.isSelected = true; serviceAppointmentScheduleList[scheduleIndex].selectedDateIndex = dateIndex; final date = TimeSlotModel( - date: serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList![dateIndex] - .date! - .date, - slotId: serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList![dateIndex] - .date! - .slotId, + date: serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList![dateIndex].date!.date, + slotId: serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList![dateIndex].date!.slotId, isSelected: true, slot: "", ); - serviceAppointmentScheduleList[scheduleIndex] - .selectedCustomTimeDateSlotModel = CustomTimeDateSlotModel(date: date); + serviceAppointmentScheduleList[scheduleIndex].selectedCustomTimeDateSlotModel = CustomTimeDateSlotModel(date: date); notifyListeners(); } - updateSelectedAppointmentSlotByDate( - {required int scheduleIndex, required int slotIndex}) { - for (var element in serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList!) { + updateSelectedAppointmentSlotByDate({required int scheduleIndex, required int slotIndex}) { + for (var element in serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList!) { for (var element in element.availableSlots!) { element.isSelected = false; } } - int index = - serviceAppointmentScheduleList[scheduleIndex].selectedDateIndex!; - serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList![index] - .availableSlots![slotIndex] - .isSelected = true; - serviceAppointmentScheduleList[scheduleIndex] - .selectedCustomTimeDateSlotModel! - .availableSlots = - serviceAppointmentScheduleList[scheduleIndex] - .customTimeDateSlotList![index] - .availableSlots!; + int index = serviceAppointmentScheduleList[scheduleIndex].selectedDateIndex!; + serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList![index].availableSlots![slotIndex].isSelected = true; + serviceAppointmentScheduleList[scheduleIndex].selectedCustomTimeDateSlotModel!.availableSlots = serviceAppointmentScheduleList[scheduleIndex].customTimeDateSlotList![index].availableSlots!; notifyListeners(); } @@ -567,8 +473,7 @@ class AppointmentsVM extends BaseVM { int selectedSubServicesCounter = 0; onItemUpdateOrSelected(int index, bool selected, int itemId) { - int serviceIndex = servicesInCurrentAppointment.indexWhere( - (element) => element.serviceId == currentServiceSelection!.serviceId!); + int serviceIndex = servicesInCurrentAppointment.indexWhere((element) => element.serviceId == currentServiceSelection!.serviceId!); // print("servicesInCurrentAppointment: ${servicesInCurrentAppointment.length}"); // if (serviceIndex == -1) { // return; @@ -583,28 +488,19 @@ class AppointmentsVM extends BaseVM { allSelectedItemsInAppointments.add(serviceItemsFromApi[index]); for (var element in allSelectedItemsInAppointments) { if (!ifItemAlreadySelected(element.id!)) { - servicesInCurrentAppointment[serviceIndex] - .serviceItems! - .add(serviceItemsFromApi[index]); + servicesInCurrentAppointment[serviceIndex].serviceItems!.add(serviceItemsFromApi[index]); servicesInCurrentAppointment[serviceIndex].currentTotalServicePrice = - servicesInCurrentAppointment[serviceIndex] - .currentTotalServicePrice + - double.parse((serviceItemsFromApi[index].price) ?? "0.0"); + servicesInCurrentAppointment[serviceIndex].currentTotalServicePrice + double.parse((serviceItemsFromApi[index].price) ?? "0.0"); } } } if (!selected) { selectedSubServicesCounter = selectedSubServicesCounter - 1; - currentServiceSelection!.serviceItems! - .removeWhere((element) => element.id == itemId); - allSelectedItemsInAppointments - .removeWhere((element) => element.id == itemId); + currentServiceSelection!.serviceItems!.removeWhere((element) => element.id == itemId); + allSelectedItemsInAppointments.removeWhere((element) => element.id == itemId); servicesInCurrentAppointment[serviceIndex].currentTotalServicePrice = - servicesInCurrentAppointment[serviceIndex].currentTotalServicePrice - - double.parse((serviceItemsFromApi[index].price) ?? "0.0"); - servicesInCurrentAppointment[serviceIndex] - .serviceItems! - .removeWhere((element) => element.id == itemId); + servicesInCurrentAppointment[serviceIndex].currentTotalServicePrice - double.parse((serviceItemsFromApi[index].price) ?? "0.0"); + servicesInCurrentAppointment[serviceIndex].serviceItems!.removeWhere((element) => element.id == itemId); } notifyListeners(); } @@ -616,8 +512,7 @@ class AppointmentsVM extends BaseVM { } branchesFilterOptions[index].isSelected = true; - await getBranchesBasedOnCategoryFilters( - categoryId: branchesFilterOptions[index].id); + await getBranchesBasedOnCategoryFilters(categoryId: branchesFilterOptions[index].id); notifyListeners(); } @@ -636,8 +531,7 @@ class AppointmentsVM extends BaseVM { String pickHomeLocationError = ""; String selectSubServicesError = ""; - SelectionModel branchSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel branchSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updatePickHomeLocationError(String value) { pickHomeLocationError = value; @@ -677,8 +571,7 @@ class AppointmentsVM extends BaseVM { return totalPrice.toString(); } - void openTheAddServiceBottomSheet( - BuildContext context, AppointmentsVM appointmentsVM) { + void openTheAddServiceBottomSheet(BuildContext context, AppointmentsVM appointmentsVM) { showModalBottomSheet( context: context, isScrollControlled: true, @@ -689,8 +582,7 @@ class AppointmentsVM extends BaseVM { ); } - void priceBreakDownClicked( - BuildContext context, ServiceModel selectedService) { + void priceBreakDownClicked(BuildContext context, ServiceModel selectedService) { showModalBottomSheet( context: context, isScrollControlled: true, @@ -698,9 +590,7 @@ class AppointmentsVM extends BaseVM { builder: (BuildContext context) { double totalKms = 15.3; return InfoBottomSheet( - title: LocaleKeys.chargesBreakdown - .tr() - .toText(fontSize: 24, isBold: true), + title: LocaleKeys.chargesBreakdown.tr().toText(fontSize: 24, isBold: true), description: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -708,48 +598,37 @@ class AppointmentsVM extends BaseVM { Column( children: List.generate( selectedService.serviceItems!.length, - (index) => Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "${selectedService.serviceItems![index].name}".toText( - fontSize: 12, - color: MyColors.lightTextColor, - isBold: true), - "${selectedService.serviceItems![index].price} SAR" - .toText(fontSize: 12, isBold: true), - ], - ), + (index) => + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "${selectedService.serviceItems![index].name}".toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true), + "${selectedService.serviceItems![index].price} SAR".toText(fontSize: 12, isBold: true), + ], + ), ), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - "${selectedService.currentTotalServicePrice} SAR" - .toText(fontSize: 16, isBold: true), + "${selectedService.currentTotalServicePrice} SAR".toText(fontSize: 16, isBold: true), ], ), if (selectedService.isHomeSelected) ...[ 20.height, - LocaleKeys.homeLocation - .tr() - .toText(fontSize: 16, isBold: true), + LocaleKeys.homeLocation.tr().toText(fontSize: 16, isBold: true), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "${totalKms}km ".toText( - fontSize: 12, - color: MyColors.lightTextColor, - isBold: true), - "${selectedService.rangePricePerKm} x $totalKms" - .toText(fontSize: 12, isBold: true), + "${totalKms}km ".toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true), + "${selectedService.rangePricePerKm} x $totalKms".toText(fontSize: 12, isBold: true), ], ), 8.height, Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - "${selectedService.rangePricePerKm ?? 0 * totalKms} SAR" - .toText(fontSize: 16, isBold: true), + "${selectedService.rangePricePerKm ?? 0 * totalKms} SAR".toText(fontSize: 16, isBold: true), ], ), ], @@ -757,24 +636,16 @@ class AppointmentsVM extends BaseVM { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - LocaleKeys.totalAmount - .tr() - .toText(fontSize: 16, isBold: true), + LocaleKeys.totalAmount.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ (selectedService.isHomeSelected - ? "${(selectedService.currentTotalServicePrice) + (double.parse((selectedService.rangePricePerKm ?? "0.0")) * totalKms)}" - : "${selectedService.currentTotalServicePrice}") + ? "${(selectedService.currentTotalServicePrice) + (double.parse((selectedService.rangePricePerKm ?? "0.0")) * totalKms)}" + : "${selectedService.currentTotalServicePrice}") .toText(fontSize: 29, isBold: true), 2.width, - LocaleKeys.sar - .tr() - .toText( - color: MyColors.lightTextColor, - fontSize: 16, - isBold: true) - .paddingOnly(bottom: 5), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 16, isBold: true).paddingOnly(bottom: 5), ], ) ], @@ -794,8 +665,7 @@ class AppointmentsVM extends BaseVM { isValidated = false; break; } - if (schedule.selectedCustomTimeDateSlotModel!.date == null || - !schedule.selectedCustomTimeDateSlotModel!.date!.isSelected) { + if (schedule.selectedCustomTimeDateSlotModel!.date == null || !schedule.selectedCustomTimeDateSlotModel!.date!.isSelected) { isValidated = false; break; } else { @@ -803,9 +673,7 @@ class AppointmentsVM extends BaseVM { isValidated = false; break; } else { - TimeSlotModel slot = schedule - .selectedCustomTimeDateSlotModel!.availableSlots! - .firstWhere((element) => element.isSelected); + TimeSlotModel slot = schedule.selectedCustomTimeDateSlotModel!.availableSlots!.firstWhere((element) => element.isSelected); if (slot.date.isNotEmpty) { isValidated = true; break; @@ -833,8 +701,7 @@ class AppointmentsVM extends BaseVM { } } - serviceAppointmentScheduleList = - await appointmentRepo.mergeServiceIntoAvailableSchedules( + serviceAppointmentScheduleList = await appointmentRepo.mergeServiceIntoAvailableSchedules( serviceItemIdsForHome: serviceItemIdsForHome, serviceItemIdsForWorkshop: serviceItemIdsForWorkshop, ); @@ -847,22 +714,17 @@ class AppointmentsVM extends BaseVM { totalAmount = 0.0; amountToPayForAppointment = 0.0; for (var schedule in serviceAppointmentScheduleList) { - amountToPayForAppointment = - amountToPayForAppointment + (schedule.amountToPay ?? 0.0); + amountToPayForAppointment = amountToPayForAppointment + (schedule.amountToPay ?? 0.0); totalAmount = totalAmount + (schedule.amountTotal ?? 0.0); } Utils.hideLoading(context); - navigateWithName(context, AppRoutes.bookAppointmenSchedulesView, - arguments: ScreenArgumentsForAppointmentDetailPage( - routeFlag: 1, appointmentId: 0)); // 1 For Creating an Appointment + navigateWithName(context, AppRoutes.bookAppointmenSchedulesView, arguments: ScreenArgumentsForAppointmentDetailPage(routeFlag: 1, appointmentId: 0)); // 1 For Creating an Appointment notifyListeners(); } - Future onRescheduleAppointmentPressed( - {required BuildContext context, - required AppointmentListModel appointmentListModel}) async { + Future onRescheduleAppointmentPressed({required BuildContext context, required AppointmentListModel appointmentListModel}) async { Utils.showLoading(context); List serviceItemIdsForHome = []; @@ -879,8 +741,7 @@ class AppointmentsVM extends BaseVM { } } - serviceAppointmentScheduleList = - await appointmentRepo.mergeServiceIntoAvailableSchedules( + serviceAppointmentScheduleList = await appointmentRepo.mergeServiceIntoAvailableSchedules( serviceItemIdsForHome: serviceItemIdsForHome, serviceItemIdsForWorkshop: serviceItemIdsForWorkshop, ); @@ -895,36 +756,29 @@ class AppointmentsVM extends BaseVM { navigateWithName( context, AppRoutes.bookAppointmenSchedulesView, - arguments: ScreenArgumentsForAppointmentDetailPage( - routeFlag: 2, appointmentId: appointmentListModel.id ?? 0), + arguments: ScreenArgumentsForAppointmentDetailPage(routeFlag: 2, appointmentId: appointmentListModel.id ?? 0), ); // 2 For Rescheduling an Appointment notifyListeners(); } - Future onRescheduleAppointmentConfirmPressed( - {required BuildContext context, - required int appointmentId, - required int selectedSlotId}) async { + Future onRescheduleAppointmentConfirmPressed({required BuildContext context, required int appointmentId, required int selectedSlotId}) async { Utils.showLoading(context); try { - GenericRespModel genericRespModel = - await appointmentRepo.cancelOrRescheduleServiceAppointment( + GenericRespModel genericRespModel = await appointmentRepo.cancelOrRescheduleServiceAppointment( serviceAppointmentID: appointmentId, serviceSlotID: selectedSlotId, appointmentScheduleAction: 1, // 1 for Reschedule and 2 for Cancel ); - if (genericRespModel.messageStatus == 2 || - genericRespModel.data == null) { + if (genericRespModel.messageStatus == 2 || genericRespModel.data == null) { Utils.hideLoading(context); Utils.showToast("${genericRespModel.message.toString()}"); return; } if (genericRespModel.messageStatus == 1) { context.read().onNavbarTapped(1); - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.cancelled); + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.cancelled); Utils.showToast("${genericRespModel.message.toString()}"); getMyAppointments(); Utils.hideLoading(context); @@ -961,27 +815,20 @@ class AppointmentsVM extends BaseVM { setOnlyState(ViewState.busy); Category category = await branchRepo.fetchBranchCategory(); category.data?.forEach((element) { - branchesFilterOptions.add(FilterListModel( - id: element.id ?? 0, - isSelected: false, - title: element.categoryName ?? "N/A")); + branchesFilterOptions.add(FilterListModel(id: element.id ?? 0, isSelected: false, title: element.categoryName ?? "N/A")); }); - branchesFilterOptions.insert( - 0, FilterListModel(id: 0, isSelected: true, title: "All Branches")); + branchesFilterOptions.insert(0, FilterListModel(id: 0, isSelected: true, title: "All Branches")); notifyListeners(); setState(ViewState.idle); } - Future getAllNearBranches( - {bool isNeedToRebuild = false, bool isFromRefresh = false}) async { + Future getAllNearBranches({bool isNeedToRebuild = false, bool isFromRefresh = false}) async { nearbyBranches.clear(); if (isNeedToRebuild) setState(ViewState.busy); if (isFromRefresh) { - var selectedBranch = - branchesFilterOptions.firstWhere((element) => element.isSelected); - nearbyBranches = await branchRepo - .getBranchesByFilters(categoryIdsList: [selectedBranch.id]); + var selectedBranch = branchesFilterOptions.firstWhere((element) => element.isSelected); + nearbyBranches = await branchRepo.getBranchesByFilters(categoryIdsList: [selectedBranch.id]); setState(ViewState.idle); return; } @@ -992,16 +839,14 @@ class AppointmentsVM extends BaseVM { void getBranchCategories() async { for (var value in selectedBranchModel!.branchServices!) { if (!isCategoryAlreadyPresent(value.categoryId!)) { - branchCategories - .add(DropValue(value.categoryId!, value.categoryName!, "")); + branchCategories.add(DropValue(value.categoryId!, value.categoryName!, "")); } } notifyListeners(); } getBranchServices({required int categoryId}) async { - branchSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); isHomeTapped = false; pickedHomeLocation = ""; pickHomeLocationError = ""; @@ -1014,16 +859,13 @@ class AppointmentsVM extends BaseVM { } List getFilteredBranchServices({required int categoryId}) { - List filteredServices = selectedBranchModel!.branchServices! - .where((element) => element.categoryId == categoryId) - .toList(); + List filteredServices = selectedBranchModel!.branchServices!.where((element) => element.categoryId == categoryId).toList(); return filteredServices; } getBranchAndServices(int providerId) async { providerProfileModel = null; - providerProfileModel = - await branchRepo.getBranchAndServicesByProviderId(providerId); + providerProfileModel = await branchRepo.getBranchAndServicesByProviderId(providerId); setState(ViewState.idle); } @@ -1058,8 +900,7 @@ class AppointmentsVM extends BaseVM { // Provider Filter List branchFilterProviderSearchHistory = []; - void removeBranchFilterProviderSearchHistory( - {bool isClear = false, required int index}) { + void removeBranchFilterProviderSearchHistory({bool isClear = false, required int index}) { if (isClear) { branchFilterProviderSearchHistory.clear(); notifyListeners(); @@ -1081,16 +922,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel branchFilterSelectedProviderId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel branchFilterSelectedProviderId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateBranchFilterSelectedProviderId(SelectionModel id, - {bool isForSearch = false}) async { + void updateBranchFilterSelectedProviderId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue providerDrop = providersDropList - .firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: branchFilterProviderSearchHistory, value: providerDrop)) { + DropValue providerDrop = providersDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: branchFilterProviderSearchHistory, value: providerDrop)) { addBranchFilterProviderSearchHistory(value: providerDrop); } } @@ -1102,8 +939,7 @@ class AppointmentsVM extends BaseVM { // Category Filter List branchFilterCategorySearchHistory = []; - void removeBranchFilterCategorySearchHistory( - {bool isClear = false, required int index}) { + void removeBranchFilterCategorySearchHistory({bool isClear = false, required int index}) { if (isClear) { branchFilterCategorySearchHistory.clear(); notifyListeners(); @@ -1125,16 +961,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel branchFilterSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel branchFilterSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateBranchFilterSelectedCategoryId(SelectionModel id, - {bool isForSearch = false}) async { + void updateBranchFilterSelectedCategoryId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue categoryDrop = - categoryDropList.firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: branchFilterCategorySearchHistory, value: categoryDrop)) { + DropValue categoryDrop = categoryDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: branchFilterCategorySearchHistory, value: categoryDrop)) { addBranchFilterCategorySearchHistory(value: categoryDrop); } } @@ -1146,8 +978,7 @@ class AppointmentsVM extends BaseVM { // Services Filter List branchFilterServicesSearchHistory = []; - void removeBranchFilterServicesSearchHistory( - {bool isClear = false, required int index}) { + void removeBranchFilterServicesSearchHistory({bool isClear = false, required int index}) { if (isClear) { branchFilterServicesSearchHistory.clear(); notifyListeners(); @@ -1169,16 +1000,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel branchFilterSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel branchFilterSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateBranchFilterSelectedServiceId(SelectionModel id, - {bool isForSearch = false}) async { + void updateBranchFilterSelectedServiceId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue serviceDrop = - servicesDropList.firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: branchFilterServicesSearchHistory, value: serviceDrop)) { + DropValue serviceDrop = servicesDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: branchFilterServicesSearchHistory, value: serviceDrop)) { addBranchFilterServicesSearchHistory(value: serviceDrop); } notifyListeners(); @@ -1219,8 +1046,7 @@ class AppointmentsVM extends BaseVM { providersDropList.clear(); setOnlyState(ViewState.busy); - List providers = - await branchRepo.getAllProvidersWitheBasicData(); + List providers = await branchRepo.getAllProvidersWitheBasicData(); for (var element in providers) { providersDropList.add( DropValue(element.id ?? 0, element.providerName ?? "N/A", ""), @@ -1239,10 +1065,10 @@ class AppointmentsVM extends BaseVM { DropValue( element.id ?? 0, ((element.categoryName!.isEmpty - ? "N/A" - : countryCode == "SA" - ? element.categoryNameN - : element.categoryName) ?? + ? "N/A" + : countryCode == "SA" + ? element.categoryNameN + : element.categoryName) ?? "N/A"), ""), ); @@ -1254,8 +1080,7 @@ class AppointmentsVM extends BaseVM { if (servicesDropList.isNotEmpty) return; servicesDropList.clear(); setState(ViewState.busy); - Services services = await branchRepo.fetchServicesByCategoryId( - serviceCategoryId: -1); // to get all services + Services services = await branchRepo.fetchServicesByCategoryId(serviceCategoryId: -1); // to get all services for (var element in services.data!) { servicesDropList.add( @@ -1288,12 +1113,9 @@ class AppointmentsVM extends BaseVM { } void clearBranchFilterSelections() { - branchFilterSelectedProviderId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - branchFilterSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - branchFilterSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchFilterSelectedProviderId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchFilterSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + branchFilterSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); } Future getBranchesBasedOnFilters() async { @@ -1330,16 +1152,14 @@ class AppointmentsVM extends BaseVM { setState(ViewState.idle); } - Future getBranchesBasedOnCategoryFilters( - {required int categoryId}) async { + Future getBranchesBasedOnCategoryFilters({required int categoryId}) async { if (categoryId == 0) { await getAllNearBranches(); return; } setState(ViewState.busy); nearbyBranches.clear(); - nearbyBranches = - await branchRepo.getBranchesByFilters(categoryIdsList: [categoryId]); + nearbyBranches = await branchRepo.getBranchesByFilters(categoryIdsList: [categoryId]); setState(ViewState.idle); } @@ -1347,15 +1167,12 @@ class AppointmentsVM extends BaseVM { List branchesDropList = []; - Future fetchAllBranchesBySelectedProviderId( - {required List providersIdsList}) async { + Future fetchAllBranchesBySelectedProviderId({required List providersIdsList}) async { branchesDropList.clear(); setOnlyState(ViewState.busy); - List providers = await branchRepo.getBranchesByFilters( - providerIdsList: providersIdsList); + List providers = await branchRepo.getBranchesByFilters(providerIdsList: providersIdsList); for (var element in providers) { - branchesDropList - .add(DropValue(element.id ?? 0, element.branchName ?? "N/A", "")); + branchesDropList.add(DropValue(element.id ?? 0, element.branchName ?? "N/A", "")); } setState(ViewState.idle); @@ -1378,8 +1195,7 @@ class AppointmentsVM extends BaseVM { // Provider Filter For Appointments List appointmentFilterProviderSearchHistory = []; - void removeAppointmentFilterProviderSearchHistory( - {bool isClear = false, required int index}) { + void removeAppointmentFilterProviderSearchHistory({bool isClear = false, required int index}) { if (isClear) { appointmentFilterProviderSearchHistory.clear(); notifyListeners(); @@ -1391,8 +1207,7 @@ class AppointmentsVM extends BaseVM { for (var element in appointmentFilterProviderSearchHistory) { providerIdsSelected.add(element.id); } - fetchAllBranchesBySelectedProviderId( - providersIdsList: providerIdsSelected); + fetchAllBranchesBySelectedProviderId(providersIdsList: providerIdsSelected); } if (appointmentFilterProviderSearchHistory.isEmpty) { @@ -1415,16 +1230,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel appointmentFilterSelectedProviderId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel appointmentFilterSelectedProviderId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateAppointmentFilterSelectedProviderId(SelectionModel id, - {bool isForSearch = false}) async { + void updateAppointmentFilterSelectedProviderId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue providerDrop = providersDropList - .firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: appointmentFilterProviderSearchHistory, value: providerDrop)) { + DropValue providerDrop = providersDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: appointmentFilterProviderSearchHistory, value: providerDrop)) { addAppointmentFilterProviderSearchHistory(value: providerDrop); } } @@ -1436,8 +1247,7 @@ class AppointmentsVM extends BaseVM { List appointmentFilterBranchSearchHistory = []; - void removeAppointmentFilterBranchSearchHistory( - {bool isClear = false, required int index}) { + void removeAppointmentFilterBranchSearchHistory({bool isClear = false, required int index}) { if (isClear) { appointmentFilterBranchSearchHistory.clear(); notifyListeners(); @@ -1459,16 +1269,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel appointmentFilterSelectedBranchId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel appointmentFilterSelectedBranchId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateAppointmentFilterSelectedBranchId(SelectionModel id, - {bool isForSearch = false}) async { + void updateAppointmentFilterSelectedBranchId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue branchesDrop = - branchesDropList.firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: appointmentFilterBranchSearchHistory, value: branchesDrop)) { + DropValue branchesDrop = branchesDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: appointmentFilterBranchSearchHistory, value: branchesDrop)) { addAppointmentFilterBranchSearchHistory(value: branchesDrop); } } @@ -1480,8 +1286,7 @@ class AppointmentsVM extends BaseVM { List appointmentFilterCategorySearchHistory = []; - void removeAppointmentFilterCategorySearchHistory( - {bool isClear = false, required int index}) { + void removeAppointmentFilterCategorySearchHistory({bool isClear = false, required int index}) { if (isClear) { appointmentFilterCategorySearchHistory.clear(); notifyListeners(); @@ -1503,16 +1308,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel appointmentFilterSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel appointmentFilterSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateAppointmentFilterSelectedCategoryId(SelectionModel id, - {bool isForSearch = false}) async { + void updateAppointmentFilterSelectedCategoryId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue categoryDrop = - categoryDropList.firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: appointmentFilterCategorySearchHistory, value: categoryDrop)) { + DropValue categoryDrop = categoryDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: appointmentFilterCategorySearchHistory, value: categoryDrop)) { addAppointmentFilterCategorySearchHistory(value: categoryDrop); } } @@ -1522,8 +1323,7 @@ class AppointmentsVM extends BaseVM { List appointmentFilterServicesSearchHistory = []; - void removeAppointmentFilterServicesSearchHistory( - {bool isClear = false, required int index}) { + void removeAppointmentFilterServicesSearchHistory({bool isClear = false, required int index}) { if (isClear) { appointmentFilterServicesSearchHistory.clear(); notifyListeners(); @@ -1545,16 +1345,12 @@ class AppointmentsVM extends BaseVM { notifyListeners(); } - SelectionModel appointmentFilterSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel appointmentFilterSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - void updateAppointmentFilterSelectedServiceId(SelectionModel id, - {bool isForSearch = false}) async { + void updateAppointmentFilterSelectedServiceId(SelectionModel id, {bool isForSearch = false}) async { if (isForSearch) { - DropValue servicesDrop = - servicesDropList.firstWhere((element) => element.id == id.selectedId); - if (!ifAlreadyExist( - list: appointmentFilterServicesSearchHistory, value: servicesDrop)) { + DropValue servicesDrop = servicesDropList.firstWhere((element) => element.id == id.selectedId); + if (!ifAlreadyExist(list: appointmentFilterServicesSearchHistory, value: servicesDrop)) { addAppointmentFilterServicesSearchHistory(value: servicesDrop); } } @@ -1563,14 +1359,10 @@ class AppointmentsVM extends BaseVM { } void clearAppointmentFilterSelections() { - appointmentFilterSelectedProviderId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - appointmentFilterSelectedCategoryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - appointmentFilterSelectedServiceId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - appointmentFilterSelectedBranchId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + appointmentFilterSelectedProviderId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + appointmentFilterSelectedCategoryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + appointmentFilterSelectedServiceId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + appointmentFilterSelectedBranchId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); } void clearAppointmentFilters() { @@ -1611,15 +1403,13 @@ class AppointmentsVM extends BaseVM { } } - myAppointments = - await appointmentRepo.getMyAppointmentsForCustomersByFilters( + myAppointments = await appointmentRepo.getMyAppointmentsForCustomersByFilters( providerIdsList: providersIdsList.isNotEmpty ? providersIdsList : null, categoryIdsList: categoryIdsList.isNotEmpty ? categoryIdsList : null, serviceIdsList: servicesIdsList.isNotEmpty ? servicesIdsList : null, branchIdsList: branchesIdsList.isNotEmpty ? branchesIdsList : null, ); - applyFilterOnAppointmentsVM( - appointmentStatusEnum: AppointmentStatusEnum.allAppointments); + applyFilterOnAppointmentsVM(appointmentStatusEnum: AppointmentStatusEnum.allAppointments); setState(ViewState.idle); } } diff --git a/lib/view_models/chat_view_model.dart b/lib/view_models/chat_view_model.dart index c53bcde..212d4d3 100644 --- a/lib/view_models/chat_view_model.dart +++ b/lib/view_models/chat_view_model.dart @@ -102,41 +102,31 @@ class ChatVM extends ChangeNotifier { return isValidated; } - Future onNewMessageReceived( - {required List messages, - required BuildContext context, - bool isMyOwnOffer = false}) async { - // log("message I received in onNewMessageReceived ${messages.first.toString()}"); + Future onNewMessageReceived({required List messages, required BuildContext context, bool isMyOwnOffer = false}) async { if (AppState().currentAppType == AppType.customer) { for (var msg in messages) { - int providerIndex = serviceProviderOffersList.indexWhere( - (element) => element.providerUserId == msg.senderUserID); + int providerIndex = serviceProviderOffersList.indexWhere((element) => element.providerUserId == msg.senderUserID); // TODO : NEED TO BE CHECKED if (providerIndex != -1) { serviceProviderOffersList[providerIndex].chatMessages!.add(msg); } } + + //providerUserId } else { for (var msg in messages) { // Where we need to call this function for saving a message in chat we will use receiverUserID and in those cases where received ID is null , it means it is a signal R call int providerIndex = -1; if (isMyOwnOffer) { - providerIndex = - context.read().myFilteredRequests.indexWhere( - (element) => element.customerUserID == msg.receiverUserID, - ); + providerIndex = context.read().myFilteredRequests.indexWhere( + (element) => element.customerUserID == msg.receiverUserID, + ); } else { - providerIndex = - context.read().myFilteredRequests.indexWhere( - (element) => element.customerUserID == msg.senderUserID, - ); + providerIndex = context.read().myFilteredRequests.indexWhere( + (element) => element.customerUserID == msg.senderUserID, + ); } - // log("here is it: $providerIndex"); - // log("here is it: ${msg.senderUserID}"); - // log("here is it: ${context.read().myFilteredRequests.first.customerUserID.toString()}"); if (providerIndex != -1) { - context - .read() - .addChatMessagesInRequestsModel(msg: msg, index: providerIndex); + context.read().addChatMessagesInRequestsModel(msg: msg, index: providerIndex); } } } @@ -145,18 +135,15 @@ class ChatVM extends ChangeNotifier { } Future buildHubConnection(BuildContext context) async { - if (hubConnection == null || - hubConnection!.state != HubConnectionState.connected) { + if (hubConnection == null || hubConnection!.state != HubConnectionState.connected) { try { hubConnection = await chatRepo.getHubConnection(); await hubConnection!.start(); - hubConnection!.on("ReceiveMessageRequestOffer", - (List? arguments) { + hubConnection!.on("ReceiveMessageRequestOffer", (List? arguments) { if (arguments == null || arguments.isEmpty) return; List chat = []; for (var message in arguments) { - final chatMessage = - ChatMessageModel.fromJson(message as Map); + final chatMessage = ChatMessageModel.fromJson(message as Map); chat.add(chatMessage); } onNewMessageReceived(messages: chat, context: context); @@ -178,8 +165,7 @@ class ChatVM extends ChangeNotifier { required String offerPrice, required BuildContext context, }) async { - if (hubConnection == null || - hubConnection!.state != HubConnectionState.connected) { + if (hubConnection == null || hubConnection!.state != HubConnectionState.connected) { await buildHubConnection(context); } if (hubConnection!.state == HubConnectionState.connected) { @@ -197,8 +183,7 @@ class ChatVM extends ChangeNotifier { "RequestID": requestId, "Price": double.parse(offerPrice), "ServiceProviderID": providerId, - "OfferStatus": RequestOfferStatusEnum.offer - .getIdFromRequestOfferStatusEnum(), + "OfferStatus": RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), "Comment": message, }, } @@ -209,6 +194,21 @@ class ChatVM extends ChangeNotifier { return false; }); } + + logger.i({ + "ReceiverUserID": receiverId, + "MessageType": chatMessageType.getIdFromChatMessageTypeEnum(), + "ChatText": message, + "RequestID": requestId, + "ReqOfferID": 0, + "ReqOffer": { + "RequestID": requestId, + "Price": double.parse(offerPrice), + "ServiceProviderID": AppState().getUser.data!.userInfo!.providerId, + "OfferStatus": RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), + "Comment": message, + }, + }); return true; } @@ -222,22 +222,22 @@ class ChatVM extends ChangeNotifier { }) async { if (message.isEmpty) return false; - if (hubConnection == null || - hubConnection!.state != HubConnectionState.connected) { + if (hubConnection == null || hubConnection!.state != HubConnectionState.connected) { await buildHubConnection(context); } if (hubConnection!.state == HubConnectionState.connected) { final userId = AppState().getUser.data!.userInfo!.userId.toString(); final name = AppState().getUser.data!.userInfo!.firstName.toString(); - log("I have saved this: ${({ + logger.i(({ "ReceiverUserID": receiverId, "SenderUserID": userId, "MessageType": chatMessageType.getIdFromChatMessageTypeEnum(), "ChatText": message, "RequestID": requestId, "ReqOfferID": latestOfferId, - }).toString()}"); + })); + hubConnection!.invoke( "SendMessageRequestOffer", args: [ @@ -251,10 +251,11 @@ class ChatVM extends ChangeNotifier { } ], ).catchError((e) { - logger.i("error in invoking SendMessageRequestOffer: ${e.toString()}"); + logger.i("error in invoking SendMessage: ${e.toString()}"); Utils.showToast(e.toString()); return false; }); + ChatMessageModel chatMessageModel = ChatMessageModel( messageType: chatMessageType.getIdFromChatMessageTypeEnum(), chatText: message, @@ -267,21 +268,14 @@ class ChatVM extends ChangeNotifier { ); if (AppState().currentAppType == AppType.customer) { - int providerIndex = serviceProviderOffersList - .indexWhere((element) => element.providerUserId == receiverId); + int providerIndex = serviceProviderOffersList.indexWhere((element) => element.providerUserId == receiverId); if (providerIndex != -1) { - serviceProviderOffersList[providerIndex] - .chatMessages! - .add(chatMessageModel); + serviceProviderOffersList[providerIndex].chatMessages!.add(chatMessageModel); } } else { - int providerIndex = context - .read() - .myFilteredRequests - .indexWhere((element) => element.customerUserID == receiverId); + int providerIndex = context.read().myFilteredRequests.indexWhere((element) => element.customerUserID == receiverId); if (providerIndex != -1) { - context.read().addChatMessagesInRequestsModel( - msg: chatMessageModel, index: providerIndex); + context.read().addChatMessagesInRequestsModel(msg: chatMessageModel, index: providerIndex); } } return true; @@ -291,12 +285,10 @@ class ChatVM extends ChangeNotifier { List serviceProviderOffersList = []; - Future getOffersFromProvidersByRequest( - {required int requestId, required BuildContext context}) async { + Future getOffersFromProvidersByRequest({required int requestId, required BuildContext context}) async { try { Utils.showLoading(context); - ProviderOffersModel providerOffersModel = await requestRepo - .getOffersFromProvidersByRequest(requestId: requestId); + ProviderOffersModel providerOffersModel = await requestRepo.getOffersFromProvidersByRequest(requestId: requestId); Utils.hideLoading(context); serviceProviderOffersList.clear(); serviceProviderOffersList = providerOffersModel.serviceProviders ?? []; @@ -318,15 +310,10 @@ class ChatVM extends ChangeNotifier { try { int customerId = AppState().getUser.data!.userInfo!.customerId!; Utils.showLoading(context); - List chatMessages = await chatRepo.getUsersChatMessages( - providerId: providerId, - customerId: customerId, - requestOfferId: requestOfferId, - requestId: requestId); + List chatMessages = await chatRepo.getUsersChatMessages(providerId: providerId, customerId: customerId, requestOfferId: requestOfferId, requestId: requestId); serviceProviderOffersList[providerOfferIndex].chatMessages = chatMessages; if (serviceProviderOffersList[providerOfferIndex].chatMessages != null) { - for (var message - in serviceProviderOffersList[providerOfferIndex].chatMessages!) { + for (var message in serviceProviderOffersList[providerOfferIndex].chatMessages!) { if (message.chatMessageTypeEnum == ChatMessageTypeEnum.offer) { updateLatestOfferId(message.reqOfferID ?? 0); log("latestOfferId: $latestOfferId"); @@ -352,13 +339,8 @@ class ChatVM extends ChangeNotifier { try { int providerId = AppState().getUser.data!.userInfo!.providerId!; Utils.showLoading(context); - List chatMessages = await chatRepo.getUsersChatMessages( - providerId: providerId, - customerId: customerId, - requestOfferId: requestOfferId, - requestId: requestId); - context.read().overwriteChatMessagesInRequestsModel( - messages: chatMessages, index: customerRequestIndex); + List chatMessages = await chatRepo.getUsersChatMessages(providerId: providerId, customerId: customerId, requestOfferId: requestOfferId, requestId: requestId); + context.read().overwriteChatMessagesInRequestsModel(messages: chatMessages, index: customerRequestIndex); Utils.hideLoading(context); } catch (e) { logger.i(e.toString()); @@ -367,16 +349,10 @@ class ChatVM extends ChangeNotifier { } } - Future onActionOfferTapped( - {required BuildContext context, - required RequestOfferStatusEnum requestOfferStatusEnum, - required int reqOfferId}) async { + Future onActionOfferTapped({required BuildContext context, required RequestOfferStatusEnum requestOfferStatusEnum, required int reqOfferId}) async { try { Utils.showLoading(context); - GenericRespModel genericRespModel = - await requestRepo.updateOfferRequestStatus( - requestOfferStatusEnum: requestOfferStatusEnum, - requestOfferId: reqOfferId); + GenericRespModel genericRespModel = await requestRepo.updateOfferRequestStatus(requestOfferStatusEnum: requestOfferStatusEnum, requestOfferId: reqOfferId); Utils.hideLoading(context); return genericRespModel.messageStatus == 1 ? reqOfferId : -1; } catch (e) { diff --git a/lib/view_models/requests_view_model.dart b/lib/view_models/requests_view_model.dart index a6fb875..757ab73 100644 --- a/lib/view_models/requests_view_model.dart +++ b/lib/view_models/requests_view_model.dart @@ -33,10 +33,7 @@ class RequestsVM extends BaseVM { final CommonRepo commonRepo; final RequestRepo requestRepo; - RequestsVM( - {required this.commonServices, - required this.commonRepo, - required this.requestRepo}); + RequestsVM({required this.commonServices, required this.commonRepo, required this.requestRepo}); List myRequests = []; List myFilteredRequests = []; @@ -45,27 +42,26 @@ class RequestsVM extends BaseVM { List myRequestsTypeEnum = []; + RequestModel? currentSelectedRequest; + + void updateCurrentSelectedRequest(RequestModel value) { + currentSelectedRequest = value; + } + populateRequestsFilterList() async { if (requestsTypeFilterOptions.isNotEmpty) return; if (myRequestsTypeEnum.isEmpty) { - myRequestsTypeEnum = await commonRepo.getEnumTypeValues( - enumTypeID: 16); //TODO: 16 is to get Requests Filter Enums + myRequestsTypeEnum = await commonRepo.getEnumTypeValues(enumTypeID: AppEnums.requestFilterEnumId); } for (int i = 0; i < myRequestsTypeEnum.length; i++) { - requestsTypeFilterOptions.add(FilterListModel( - title: myRequestsTypeEnum[i].enumValueStr, - isSelected: false, - id: myRequestsTypeEnum[i].enumValue)); + requestsTypeFilterOptions.add(FilterListModel(title: myRequestsTypeEnum[i].enumValueStr, isSelected: false, id: myRequestsTypeEnum[i].enumValue)); } - log("requestsTypeFilterOptions: ${requestsTypeFilterOptions.toString()}"); - notifyListeners(); } - Future getRequests( - {bool isNeedToRebuild = false, required AppType appType}) async { + Future getRequests({bool isNeedToRebuild = false, required AppType appType}) async { if (isNeedToRebuild) setState(ViewState.busy); var paramsForGetRequests = {}; @@ -76,29 +72,22 @@ class RequestsVM extends BaseVM { "requestType": 0, }; if (appType == AppType.provider) { - paramsForGetRequests.addEntries([ - MapEntry("providerID", AppState().getUser.data!.userInfo!.providerId) - ]); + paramsForGetRequests.addEntries([MapEntry("providerID", AppState().getUser.data!.userInfo!.providerId)]); } else { - paramsForGetRequests.addEntries([ - MapEntry("customerID", AppState().getUser.data!.userInfo!.customerId) - ]); + paramsForGetRequests.addEntries([MapEntry("customerID", AppState().getUser.data!.userInfo!.customerId)]); } myRequests = await requestRepo.getRequests(paramsForGetRequests); - applyFilterOnRequestsVM( - requestsTypeEnum: RequestsTypeEnum.specialCarRequest); + applyFilterOnRequestsVM(requestsTypeEnum: RequestsTypeEnum.specialCarRequest); setState(ViewState.idle); notifyListeners(); } - addChatMessagesInRequestsModel( - {required ChatMessageModel msg, required int index}) { + addChatMessagesInRequestsModel({required ChatMessageModel msg, required int index}) { myFilteredRequests[index].chatMessages.add(msg); notifyListeners(); } - overwriteChatMessagesInRequestsModel( - {required List messages, required int index}) { + overwriteChatMessagesInRequestsModel({required List messages, required int index}) { myFilteredRequests[index].chatMessages.clear(); myFilteredRequests[index].chatMessages = messages; notifyListeners(); @@ -109,14 +98,8 @@ class RequestsVM extends BaseVM { for (var value in requestsTypeFilterOptions) { value.isSelected = false; } - requestsTypeFilterOptions[ - requestsTypeEnum.getIdFromRequestTypeStatusEnum() - 1] - .isSelected = true; // -1 to match with the index - myFilteredRequests = myRequests - .where((element) => - element.requestType == - requestsTypeEnum.getIdFromRequestTypeStatusEnum()) - .toList(); + requestsTypeFilterOptions[requestsTypeEnum.getIdFromRequestTypeStatusEnum() - 1].isSelected = true; // -1 to match with the index + myFilteredRequests = myRequests.where((element) => element.requestType == requestsTypeEnum.getIdFromRequestTypeStatusEnum()).toList(); notifyListeners(); } @@ -125,8 +108,7 @@ class RequestsVM extends BaseVM { String vehicleImageError = ""; void removeImageFromList(String filePath) { - int index = pickedVehicleImages - .indexWhere((element) => element.filePath == filePath); + int index = pickedVehicleImages.indexWhere((element) => element.filePath == filePath); if (index == -1) { return; } @@ -156,8 +138,7 @@ class RequestsVM extends BaseVM { List vehicleCountries = []; List vehicleCities = []; - SelectionModel requestTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel requestTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionRequestTypeId(SelectionModel id) async { requestTypeId = id; @@ -165,8 +146,7 @@ class RequestsVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleTypeId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); Future getVehicleTypes() async { resetRequestCreationForm(); @@ -197,8 +177,7 @@ class RequestsVM extends BaseVM { // } isFetchingVehicleDetail = true; notifyListeners(); - vehicleDetails = await commonRepo.getVehicleDetails( - vehicleTypeId: vehicleTypeId.selectedId); + vehicleDetails = await commonRepo.getVehicleDetails(vehicleTypeId: vehicleTypeId.selectedId); if (vehicleDetails != null) { vehicleBrands = vehicleDetails!.vehicleBrands!; @@ -210,30 +189,24 @@ class RequestsVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleBrandId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleBrandId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleBrandId(SelectionModel id) { vehicleBrandId = id; - vehicleModelId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); - vehicleModelYearId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleModelId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleModelYearId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); notifyListeners(); } - SelectionModel vehicleModelId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleModelId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleModelId(SelectionModel id) { vehicleModelId = id; - vehicleModelYearId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + vehicleModelYearId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); notifyListeners(); } - SelectionModel vehicleModelYearId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleModelYearId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleModelYearId(SelectionModel id) { vehicleModelYearId = id; @@ -248,21 +221,18 @@ class RequestsVM extends BaseVM { } bool isCountryFetching = false; - SelectionModel vehicleCountryId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleCountryId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleCountryId(SelectionModel id) async { vehicleCountryId = id; isCountryFetching = true; notifyListeners(); - vehicleCities = await commonRepo.getVehicleCities( - countryId: vehicleCountryId.selectedId); + vehicleCities = await commonRepo.getVehicleCities(countryId: vehicleCountryId.selectedId); isCountryFetching = false; notifyListeners(); } - SelectionModel vehicleCityId = - SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleCityId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); void updateSelectionVehicleCityId(SelectionModel id) { vehicleCityId = id; @@ -280,12 +250,10 @@ class RequestsVM extends BaseVM { description = v; } - Future convertFileToRequestPostingImages( - {required File file}) async { + Future convertFileToRequestPostingImages({required File file}) async { List imageBytes = await file.readAsBytes(); String image = base64Encode(imageBytes); - RequestPostingImages vehiclePostingImages = - RequestPostingImages(requestImage: image); + RequestPostingImages vehiclePostingImages = RequestPostingImages(requestImage: image); return vehiclePostingImages; } @@ -294,8 +262,7 @@ class RequestsVM extends BaseVM { log("requestImages: ${pickedVehicleImages.length}"); for (var image in pickedVehicleImages) { - var value = - await convertFileToRequestPostingImages(file: File(image.filePath!)); + var value = await convertFileToRequestPostingImages(file: File(image.filePath!)); requestImages.add(value); } @@ -306,8 +273,7 @@ class RequestsVM extends BaseVM { if (validateCreateRequestForm()) { Utils.showLoading(context); - List vehicleImages = - await getVehiclePostingImageList(); + List vehicleImages = await getVehiclePostingImageList(); List requestImages = []; vehicleImages.forEach((element) { requestImages.add(element.toJson()); @@ -377,12 +343,10 @@ class RequestsVM extends BaseVM { return isValid; } - Future> getOffersByRequest( - {required int requestId, required BuildContext context}) async { + Future> getOffersByRequest({required int requestId, required BuildContext context}) async { try { Utils.showLoading(context); - List respModel = - await requestRepo.getOffersByRequest(requestId: requestId); + List respModel = await requestRepo.getOffersByRequest(requestId: requestId); Utils.hideLoading(context); return respModel; } catch (e) { @@ -473,26 +437,22 @@ class RequestsVM extends BaseVM { ChatMessageModel chatMessageModel = ChatMessageModel( isMyMessage: true, chatText: message, - messageType: - ChatMessageTypeEnum.offer.getIdFromChatMessageTypeEnum(), + messageType: ChatMessageTypeEnum.offer.getIdFromChatMessageTypeEnum(), senderName: senderName, senderUserID: senderId, receiverUserID: receiverId, chatMessageTypeEnum: ChatMessageTypeEnum.offer, requestID: requestModel.id, - offerStatus: - RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), + offerStatus: RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), reqOffer: ReqOffer( - offerStatus: RequestOfferStatusEnum.offer - .getIdFromRequestOfferStatusEnum(), + offerStatus: RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), requestID: requestModel.id, price: double.parse(offerPrice), requestOfferStatusEnum: RequestOfferStatusEnum.offer, comment: message, offerStatusText: "", )); - context.read().onNewMessageReceived( - messages: [chatMessageModel], context: context, isMyOwnOffer: true); + context.read().onNewMessageReceived(messages: [chatMessageModel], context: context, isMyOwnOffer: true); if (!isFromChatScreen) { ChatViewArguments chatViewArguments = ChatViewArguments( chatTypeEnum: ChatTypeEnum.requestOffer, @@ -502,8 +462,7 @@ class RequestsVM extends BaseVM { requestIndex: requestIndex, providerIndex: -1, ); - navigateWithName(context, AppRoutes.chatView, - arguments: chatViewArguments); + navigateWithName(context, AppRoutes.chatView, arguments: chatViewArguments); } } } diff --git a/lib/views/advertisement/ads_list.dart b/lib/views/advertisement/ads_list.dart index 80ec639..0dd45c1 100644 --- a/lib/views/advertisement/ads_list.dart +++ b/lib/views/advertisement/ads_list.dart @@ -104,7 +104,7 @@ class AdCard extends StatelessWidget { (adDetails.vehicle!.vehicleTitle ?? "").toText(fontSize: 16, isBold: true), Row( children: [ - (LocaleKeys.model.tr() + ":").toText( + ("${LocaleKeys.model.tr()}:").toText( color: MyColors.lightTextColor, ), 2.width, @@ -113,7 +113,7 @@ class AdCard extends StatelessWidget { ), Row( children: [ - (LocaleKeys.mileage.tr() + ":").toText( + ("${LocaleKeys.mileage.tr()}:").toText( color: MyColors.lightTextColor, ), 2.width, diff --git a/lib/views/appointments/appointment_detail_view.dart b/lib/views/appointments/appointment_detail_view.dart index 2729d56..cd86fea 100644 --- a/lib/views/appointments/appointment_detail_view.dart +++ b/lib/views/appointments/appointment_detail_view.dart @@ -16,7 +16,6 @@ import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; import 'package:provider/provider.dart'; import 'package:easy_localization/easy_localization.dart'; - class AppointmentDetailView extends StatelessWidget { final AppointmentListModel appointmentListModel; @@ -267,7 +266,7 @@ class AppointmentDetailView extends StatelessWidget { ), ], 15.height, - if (appointmentListModel.appointmentStatusEnum != AppointmentStatusEnum.workStarted && appointmentListModel.appointmentStatusEnum != AppointmentStatusEnum.visitCompleted) ...[ + if (appointmentListModel.appointmentStatusEnum == AppointmentStatusEnum.booked || appointmentListModel.appointmentStatusEnum == AppointmentStatusEnum.confirmed) ...[ Row( children: [ CardButtonWithIcon( diff --git a/lib/views/chat/chat_view.dart b/lib/views/chat/chat_view.dart index 044daa9..ff754b1 100644 --- a/lib/views/chat/chat_view.dart +++ b/lib/views/chat/chat_view.dart @@ -34,15 +34,11 @@ class ChatView extends StatelessWidget { isScrollControlled: true, enableDrag: true, builder: (BuildContext context) { - return Consumer(builder: - (BuildContext context, RequestsVM requestsVM, Widget? child) { + return Consumer(builder: (BuildContext context, RequestsVM requestsVM, Widget? child) { return InfoBottomSheet( - title: LocaleKeys.makeAnOffer - .tr() - .toText(fontSize: 28, isBold: true, letterSpacing: -1.44), + title: LocaleKeys.makeAnOffer.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44), description: Padding( - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom), + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -64,8 +60,7 @@ class ChatView extends StatelessWidget { errorValue: requestsVM.offerDescriptionError, keyboardType: TextInputType.text, hint: LocaleKeys.description.tr(), - onChanged: (v) => - requestsVM.updateOfferDescription(v), + onChanged: (v) => requestsVM.updateOfferDescription(v), ), ], ), @@ -99,29 +94,21 @@ class ChatView extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar(title: LocaleKeys.chat.tr()), - body: Consumer2(builder: (BuildContext context, - ChatVM chatVM, RequestsVM requestVM, Widget? child) { + body: Consumer2(builder: (BuildContext context, ChatVM chatVM, RequestsVM requestVM, Widget? child) { final chatMessages = AppState().currentAppType == AppType.customer - ? chatVM.serviceProviderOffersList[chatViewArguments.providerIndex] - .chatMessages - : requestVM.myFilteredRequests[chatViewArguments.requestIndex] - .chatMessages; + ? chatVM.serviceProviderOffersList[chatViewArguments.providerIndex].chatMessages + : requestVM.myFilteredRequests[chatViewArguments.requestIndex].chatMessages; return chatMessages == null - ? Center( - child: LocaleKeys.noRequestsShow - .tr() - .toText(fontSize: 16, color: MyColors.lightTextColor)) + ? Center(child: LocaleKeys.noRequestsShow.tr().toText(fontSize: 16, color: MyColors.lightTextColor)) : Column( children: [ Expanded( child: ListView.separated( itemCount: chatMessages.length, - separatorBuilder: (BuildContext context, int index) => - 20.height, + separatorBuilder: (BuildContext context, int index) => 20.height, itemBuilder: (BuildContext context, int index) { ChatMessageModel chatMessageModel = chatMessages[index]; - return ChatMessageCustomWidget( - chatMessageModel: chatMessageModel); + return ChatMessageCustomWidget(chatMessageModel: chatMessageModel); }, ).horPaddingMain(), ), @@ -129,54 +116,64 @@ class ChatView extends StatelessWidget { Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - if (AppState().currentAppType == AppType.provider) ...[ + if (requestVM.currentSelectedRequest!.requestStatus == RequestStatus.inProgress) ...[ + Center( + child: LocaleKeys.requestAlreadyInProgress.tr().toText( + textAlign: TextAlign.center, + color: MyColors.lightTextColor, + fontSize: 14, + ), + ).paddingAll(15) + ] else ...[ + if (AppState().currentAppType == AppType.provider) ...[ + Expanded( + flex: 1, + child: const Icon( + Icons.local_offer_rounded, + color: MyColors.darkPrimaryColor, + size: 30, + ).onPress( + () async { + buildSendOfferBottomSheet(context); + }, + ), + ), + ], + Expanded( + flex: 8, + child: TxtField( + value: chatVM.chatMessageText, + hint: LocaleKeys.typeMessageHere.tr(), + keyboardType: TextInputType.text, + isNeedBorder: false, + onChanged: (v) => chatVM.updateChatMessageText(v), + ), + ), Expanded( flex: 1, child: const Icon( - Icons.local_offer_rounded, + Icons.send_rounded, color: MyColors.darkPrimaryColor, size: 30, ).onPress( () async { - buildSendOfferBottomSheet(context); + log("chatViewArguments.requestId:${chatViewArguments.requestId}"); + final status = await chatVM.onTextMessageSend( + context: context, + receiverId: chatViewArguments.receiverId, + message: chatVM.chatMessageText, + requestId: chatViewArguments.requestId ?? 0, + offerPrice: "0.0", + chatMessageType: ChatMessageTypeEnum.freeText, + ); + + if (status) { + chatVM.clearChatMessageText(); + } }, ), ), ], - Expanded( - flex: 8, - child: TxtField( - value: chatVM.chatMessageText, - hint: LocaleKeys.typeMessageHere.tr(), - keyboardType: TextInputType.text, - isNeedBorder: false, - onChanged: (v) => chatVM.updateChatMessageText(v), - ), - ), - Expanded( - flex: 1, - child: const Icon( - Icons.send_rounded, - color: MyColors.darkPrimaryColor, - size: 30, - ).onPress( - () async { - log("chatViewArguments.requestId:${chatViewArguments.requestId}"); - final status = await chatVM.onTextMessageSend( - context: context, - receiverId: chatViewArguments.receiverId, - message: chatVM.chatMessageText, - requestId: chatViewArguments.requestId ?? 0, - offerPrice: "0.0", - chatMessageType: ChatMessageTypeEnum.freeText, - ); - - if (status) { - chatVM.clearChatMessageText(); - } - }, - ), - ) ], ).toContainer(isShadowEnabled: true), ], @@ -193,8 +190,7 @@ class ChatMessageCustomWidget extends StatefulWidget { const ChatMessageCustomWidget({super.key, required this.chatMessageModel}); @override - State createState() => - _ChatMessageCustomWidgetState(); + State createState() => _ChatMessageCustomWidgetState(); } class _ChatMessageCustomWidgetState extends State { @@ -204,15 +200,11 @@ class _ChatMessageCustomWidgetState extends State { isScrollControlled: true, enableDrag: true, builder: (BuildContext context) { - return Consumer( - builder: (BuildContext context, ChatVM chatVM, Widget? child) { + return Consumer(builder: (BuildContext context, ChatVM chatVM, Widget? child) { return InfoBottomSheet( - title: LocaleKeys.makeAnOffer - .tr() - .toText(fontSize: 28, isBold: true, letterSpacing: -1.44), + title: LocaleKeys.makeAnOffer.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44), description: Padding( - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom), + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -223,18 +215,14 @@ class _ChatMessageCustomWidgetState extends State { ListView.separated( shrinkWrap: true, itemCount: chatVM.offerRejectModelList.length, - separatorBuilder: (BuildContext context, int index) => - const Divider(thickness: 0.5), + separatorBuilder: (BuildContext context, int index) => const Divider(thickness: 0.5), itemBuilder: (BuildContext context, int index) { - OfferRequestCommentModel offerRequestCommentModel = - chatVM.offerRejectModelList[index]; + OfferRequestCommentModel offerRequestCommentModel = chatVM.offerRejectModelList[index]; return CircleCheckBoxWithTitle( - isChecked: - offerRequestCommentModel.isSelected ?? false, + isChecked: offerRequestCommentModel.isSelected ?? false, title: '${offerRequestCommentModel.title}', onSelected: () { - chatVM.updateSelectionInOfferRejectModelList( - index); + chatVM.updateSelectionInOfferRejectModelList(index); }, selectedColor: MyColors.darkPrimaryColor, ); @@ -247,8 +235,7 @@ class _ChatMessageCustomWidgetState extends State { errorValue: chatVM.rejectOfferDescriptionError, keyboardType: TextInputType.text, hint: LocaleKeys.description.tr(), - onChanged: (v) => - chatVM.updateRejectOfferDescription(v), + onChanged: (v) => chatVM.updateRejectOfferDescription(v), ), ], ), @@ -267,12 +254,8 @@ class _ChatMessageCustomWidgetState extends State { ); } - Widget buildOfferDetailsInChatMessage( - {required ChatMessageModel chatMessageModel, - required BuildContext context}) { - final requestOfferStatusEnum = - chatMessageModel.reqOffer!.requestOfferStatusEnum ?? - RequestOfferStatusEnum.offer; + Widget buildOfferDetailsInChatMessage({required ChatMessageModel chatMessageModel, required BuildContext context}) { + final requestOfferStatusEnum = chatMessageModel.reqOffer!.requestOfferStatusEnum ?? RequestOfferStatusEnum.offer; switch (requestOfferStatusEnum) { case RequestOfferStatusEnum.offer: @@ -282,18 +265,9 @@ class _ChatMessageCustomWidgetState extends State { Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ - "${chatMessageModel.reqOffer!.price}".toText( - fontSize: 19, - isBold: true, - color: AppState().currentAppType == AppType.provider - ? MyColors.white - : MyColors.darkTextColor), + "${chatMessageModel.reqOffer!.price}".toText(fontSize: 19, isBold: true, color: AppState().currentAppType == AppType.provider ? MyColors.white : MyColors.darkTextColor), 5.width, - LocaleKeys.sar.tr().toText( - color: MyColors.lightTextColor, - height: 2.2, - fontSize: 10, - isBold: true), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, height: 2.2, fontSize: 10, isBold: true), ], ), if (widget.chatMessageModel.isMyMessage == false) ...[ @@ -308,19 +282,15 @@ class _ChatMessageCustomWidgetState extends State { borderColor: MyColors.greenColor, isFilled: false, onPressed: () async { - int status = - await context.read().onActionOfferTapped( - context: context, - requestOfferStatusEnum: - RequestOfferStatusEnum.accepted, - reqOfferId: chatMessageModel.reqOfferID ?? -1, - ); + int status = await context.read().onActionOfferTapped( + context: context, + requestOfferStatusEnum: RequestOfferStatusEnum.accepted, + reqOfferId: chatMessageModel.reqOfferID ?? -1, + ); if (status != -1) { - log("accepted: $status"); if (chatMessageModel.reqOfferID == status) { - chatMessageModel.reqOffer!.requestOfferStatusEnum = - RequestOfferStatusEnum.accepted; + chatMessageModel.reqOffer!.requestOfferStatusEnum = RequestOfferStatusEnum.accepted; setState(() {}); } } @@ -358,11 +328,7 @@ class _ChatMessageCustomWidgetState extends State { fontSize: 12, isItalic: true, ), - ).toContainer( - borderRadius: 40, - width: double.infinity, - backgroundColor: - MyColors.adPendingStatusColor.withOpacity(0.16)), + ).toContainer(borderRadius: 40, width: double.infinity, backgroundColor: MyColors.adPendingStatusColor.withOpacity(0.16)), ], ); case RequestOfferStatusEnum.accepted: @@ -374,11 +340,7 @@ class _ChatMessageCustomWidgetState extends State { fontSize: 12, isItalic: true, ), - ).toContainer( - borderRadius: 40, - width: double.infinity, - backgroundColor: - MyColors.adPendingStatusColor.withOpacity(0.16)), + ).toContainer(borderRadius: 40, width: double.infinity, backgroundColor: MyColors.adPendingStatusColor.withOpacity(0.16)), ], ); case RequestOfferStatusEnum.rejected: @@ -390,11 +352,7 @@ class _ChatMessageCustomWidgetState extends State { fontSize: 12, isItalic: true, ), - ).toContainer( - borderRadius: 40, - width: double.infinity, - backgroundColor: - MyColors.adPendingStatusColor.withOpacity(0.16)), + ).toContainer(borderRadius: 40, width: double.infinity, backgroundColor: MyColors.adPendingStatusColor.withOpacity(0.16)), ], ); case RequestOfferStatusEnum.cancel: @@ -406,11 +364,7 @@ class _ChatMessageCustomWidgetState extends State { fontSize: 12, isItalic: true, ), - ).toContainer( - borderRadius: 40, - width: double.infinity, - backgroundColor: - MyColors.adPendingStatusColor.withOpacity(0.16)), + ).toContainer(borderRadius: 40, width: double.infinity, backgroundColor: MyColors.adPendingStatusColor.withOpacity(0.16)), ], ); } @@ -419,9 +373,7 @@ class _ChatMessageCustomWidgetState extends State { @override Widget build(BuildContext context) { return Directionality( - textDirection: (widget.chatMessageModel.isMyMessage ?? false) - ? TextDirection.rtl - : TextDirection.ltr, + textDirection: (widget.chatMessageModel.isMyMessage ?? false) ? TextDirection.rtl : TextDirection.ltr, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -443,10 +395,7 @@ class _ChatMessageCustomWidgetState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ - ((widget.chatMessageModel.isMyMessage ?? false) - ? "You" - : widget.chatMessageModel.senderName ?? "") - .toText(fontSize: 16, isBold: true), + ((widget.chatMessageModel.isMyMessage ?? false) ? "You" : widget.chatMessageModel.senderName ?? "").toText(fontSize: 16, isBold: true), ], ), 5.height, @@ -458,13 +407,8 @@ class _ChatMessageCustomWidgetState extends State { Expanded( child: Directionality( textDirection: TextDirection.ltr, - child: - (widget.chatMessageModel.chatText ?? "").toText( - color: - (widget.chatMessageModel.isMyMessage ?? false) - ? MyColors.white - : MyColors.lightTextColor, - + child: (widget.chatMessageModel.chatText ?? "").toText( + color: (widget.chatMessageModel.isMyMessage ?? false) ? MyColors.white : MyColors.lightTextColor, fontSize: 12, // isBold: true, ), @@ -472,26 +416,15 @@ class _ChatMessageCustomWidgetState extends State { ), ], ), - if (widget.chatMessageModel.chatMessageTypeEnum == - ChatMessageTypeEnum.offer) ...[ - buildOfferDetailsInChatMessage( - chatMessageModel: widget.chatMessageModel, - context: context), + if (widget.chatMessageModel.chatMessageTypeEnum == ChatMessageTypeEnum.offer) ...[ + buildOfferDetailsInChatMessage(chatMessageModel: widget.chatMessageModel, context: context), ], ], ).toContainer( - isShadowEnabled: - !(widget.chatMessageModel.isMyMessage ?? false), - backgroundColor: - (widget.chatMessageModel.isMyMessage ?? false) - ? MyColors.darkIconColor - : MyColors.white, + isShadowEnabled: !(widget.chatMessageModel.isMyMessage ?? false), + backgroundColor: (widget.chatMessageModel.isMyMessage ?? false) ? MyColors.darkIconColor : MyColors.white, borderRadius: 0, - margin: EdgeInsets.fromLTRB( - (widget.chatMessageModel.isMyMessage ?? false) ? 25 : 0, - 0, - !(widget.chatMessageModel.isMyMessage ?? false) ? 25 : 0, - 0), + margin: EdgeInsets.fromLTRB((widget.chatMessageModel.isMyMessage ?? false) ? 25 : 0, 0, !(widget.chatMessageModel.isMyMessage ?? false) ? 25 : 0, 0), ), ], ), diff --git a/lib/views/profile/profile_view.dart b/lib/views/profile/profile_view.dart index 5de4917..80ab4c2 100644 --- a/lib/views/profile/profile_view.dart +++ b/lib/views/profile/profile_view.dart @@ -1,9 +1,6 @@ -import 'dart:io'; import 'dart:ui'; import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_svg/flutter_svg.dart'; import 'package:mc_common_app/classes/app_state.dart'; import 'package:mc_common_app/classes/consts.dart'; import 'package:mc_common_app/config/routes.dart'; @@ -11,14 +8,9 @@ import 'package:mc_common_app/extensions/int_extensions.dart'; import 'package:mc_common_app/extensions/string_extensions.dart'; import 'package:mc_common_app/generated/locale_keys.g.dart'; import 'package:mc_common_app/theme/colors.dart'; -import 'package:mc_common_app/utils/app_permission_handler.dart'; -import 'package:mc_common_app/view_models/service_view_model.dart'; import 'package:mc_common_app/view_models/user_view_model.dart'; import 'package:mc_common_app/views/setting_options/widgets/custom_setting_options_tile.dart'; -import 'package:mc_common_app/views/user/change_password_page.dart'; -import 'package:mc_common_app/views/user/change_password_page.dart'; import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; -import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import 'package:easy_localization/easy_localization.dart'; @@ -46,7 +38,6 @@ class _ProfileScreenState extends State { backgroundColor: const Color(0xffefefef), body: Consumer(builder: (_, model, __) { return Stack( - // fit: StackFit.loose, children: [ Column( children: [ @@ -54,29 +45,15 @@ class _ProfileScreenState extends State { flex: 3, child: Container( decoration: BoxDecoration( - image: AppState() - .getUser - .data! - .userInfo! - .userLocalImage != - null + image: AppState().getUser.data!.userInfo!.userLocalImage != null ? DecorationImage( - image: FileImage(AppState() - .getUser - .data! - .userInfo! - .userLocalImage!), + image: FileImage(AppState().getUser.data!.userInfo!.userLocalImage!), fit: BoxFit.cover, ) - : AppState().getUser.data!.userInfo!.userImageUrl != - null + : AppState().getUser.data!.userInfo!.userImageUrl != null ? DecorationImage( image: CachedNetworkImageProvider( - AppState() - .getUser - .data! - .userInfo! - .userImageUrl, + AppState().getUser.data!.userInfo!.userImageUrl, ), fit: BoxFit.cover, ) @@ -103,9 +80,7 @@ class _ProfileScreenState extends State { child: ListView( children: [ 20.height, - "${AppState().getUser.data!.userInfo!.firstName} ${AppState().getUser.data!.userInfo!.lastName ?? ""}" - .toText(fontSize: 20) - .paddingOnly(left: 25), + "${AppState().getUser.data!.userInfo!.firstName} ${AppState().getUser.data!.userInfo!.lastName ?? ""}".toText(fontSize: 20).paddingOnly(left: 25), Column( children: [ CustomProfileOptionsTile( @@ -116,39 +91,29 @@ class _ProfileScreenState extends State { ), CustomProfileOptionsTile( titleText: LocaleKeys.email.tr(), - subtitleText: - "${AppState().getUser.data!.userInfo!.email}", + subtitleText: "${AppState().getUser.data!.userInfo!.email}", needBorderBelow: true, onTap: () { - Navigator.pushNamed( - context, AppRoutes.changeEmailPage); + Navigator.pushNamed(context, AppRoutes.changeEmailPage); }, ), CustomProfileOptionsTile( titleText: LocaleKeys.phoneNumber.tr(), - subtitleText: - "${AppState().getUser.data!.userInfo!.email}", + subtitleText: "${AppState().getUser.data!.userInfo!.email}", needBorderBelow: true, onTap: () { - Navigator.pushNamed( - context, AppRoutes.changeMobilePage); + Navigator.pushNamed(context, AppRoutes.changeMobilePage); }, ), CustomProfileOptionsTile( titleText: LocaleKeys.password.tr(), subtitleText: "************", onTap: () { - Navigator.pushNamed( - context, AppRoutes.changePassword); + Navigator.pushNamed(context, AppRoutes.changePassword); }, ), ], - ).toContainer( - width: double.infinity, - isShadowEnabled: true, - paddingAll: 10, - margin: const EdgeInsets.fromLTRB(24, 20, 24, 0), - borderRadius: 0), + ).toContainer(width: double.infinity, isShadowEnabled: true, paddingAll: 10, margin: const EdgeInsets.fromLTRB(24, 20, 24, 0), borderRadius: 0), ], ), ), @@ -161,8 +126,7 @@ class _ProfileScreenState extends State { height: 90, alignment: Alignment.centerLeft, child: ClipOval( - child: AppState().getUser.data!.userInfo!.userLocalImage != - null + child: AppState().getUser.data!.userInfo!.userLocalImage != null ? Image.file( AppState().getUser.data!.userInfo!.userLocalImage!, width: 90, @@ -170,8 +134,7 @@ class _ProfileScreenState extends State { fit: BoxFit.fill, ) : CachedNetworkImage( - imageUrl: - "${AppState().getUser.data!.userInfo!.userImageUrl}", + imageUrl: "${AppState().getUser.data!.userInfo!.userImageUrl}", imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( image: DecorationImage( @@ -180,10 +143,8 @@ class _ProfileScreenState extends State { ), ), ), - placeholder: (context, url) => - const Center(child: CircularProgressIndicator()), - errorWidget: (context, url, error) => - const Icon(Icons.error), + placeholder: (context, url) => const Center(child: CircularProgressIndicator()), + errorWidget: (context, url, error) => const Icon(Icons.error), width: 90, height: 90, fit: BoxFit.fill, @@ -200,14 +161,8 @@ class _ProfileScreenState extends State { child: Container( height: 35, width: 35, - decoration: BoxDecoration( - color: MyColors.white, - shape: BoxShape.circle, - border: - Border.all(color: MyColors.darkTextColor, width: 0.1)), - child: const Icon(Icons.edit_note, - color: MyColors.darkIconColor, size: 27) - .paddingOnly(left: 5), + decoration: BoxDecoration(color: MyColors.white, shape: BoxShape.circle, border: Border.all(color: MyColors.darkTextColor, width: 0.1)), + child: const Icon(Icons.edit_note, color: MyColors.darkIconColor, size: 27).paddingOnly(left: 5), ).onPress( () async { model.updateUserImage(context); diff --git a/lib/views/requests/offer_list_page.dart b/lib/views/requests/offer_list_page.dart index 803511d..72a8a2f 100644 --- a/lib/views/requests/offer_list_page.dart +++ b/lib/views/requests/offer_list_page.dart @@ -23,29 +23,23 @@ class OfferListPage extends StatelessWidget { @override Widget build(BuildContext context) { - final List serviceProviderOffers = - offerListPageArguments.serviceProviderOffers; + final List serviceProviderOffers = offerListPageArguments.serviceProviderOffers; return Scaffold( appBar: CustomAppBar(title: LocaleKeys.offers.tr()), body: serviceProviderOffers.isEmpty - ? Center( - child: LocaleKeys.noOffersShow - .tr() - .toText(fontSize: 16, color: MyColors.lightTextColor)) + ? Center(child: LocaleKeys.noOffersShow.tr().toText(fontSize: 16, color: MyColors.lightTextColor)) : ListView.separated( itemCount: serviceProviderOffers.length, padding: const EdgeInsets.all(16), itemBuilder: (context, index) { - ServiceProvidersOffers offersModel = - serviceProviderOffers[index]; + ServiceProvidersOffers offersModel = serviceProviderOffers[index]; return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ - (offersModel.name ?? "") - .toText(fontSize: 16, isBold: true), + (offersModel.name ?? "").toText(fontSize: 16, isBold: true), Center( child: "${offersModel.offerCount}".toText( color: Colors.white, @@ -56,8 +50,8 @@ class OfferListPage extends StatelessWidget { backgroundColor: MyColors.redColor, borderRadius: 100, paddingAll: 1, - width: 20, - height: 20, + width: 22, + height: 22, ), ], ), @@ -72,6 +66,13 @@ class OfferListPage extends StatelessWidget { color: MyColors.lightTextColor, fontSize: 12, ), + + //TODO: createdOn parameter need to be added in the backend + // if (offersModel.createdOn != null) ...[ + // DateTime.parse(offersModel.createdOn!).getTimeAgo().toText( + // color: MyColors.lightTextColor, + // ), + // ], " | 1 hour ago".toText( color: MyColors.lightTextColor, fontSize: 12, @@ -90,12 +91,10 @@ class OfferListPage extends StatelessWidget { ChatViewArguments chatViewArguments = ChatViewArguments( chatTypeEnum: ChatTypeEnum.requestOffer, receiverId: "${offersModel.providerUserId}", - senderId: - AppState().getUser.data!.userInfo!.userId.toString(), + senderId: AppState().getUser.data!.userInfo!.userId.toString(), requestId: offerListPageArguments.requestId, providerIndex: index, - requestIndex: - -1, // This will be only send in case of provider + requestIndex: -1, // This will be only send in case of provider ); final chatVM = context.read(); @@ -109,8 +108,7 @@ class OfferListPage extends StatelessWidget { providerOfferIndex: index, ) .whenComplete( - () => navigateWithName(context, AppRoutes.chatView, - arguments: chatViewArguments), + () => navigateWithName(context, AppRoutes.chatView, arguments: chatViewArguments), ); }).toContainer(isShadowEnabled: true); }, diff --git a/lib/views/requests/widget/request_item.dart b/lib/views/requests/widget/request_item.dart index e46f050..a863b3f 100644 --- a/lib/views/requests/widget/request_item.dart +++ b/lib/views/requests/widget/request_item.dart @@ -13,6 +13,7 @@ import 'package:mc_common_app/models/requests_models/request_model.dart'; import 'package:mc_common_app/theme/colors.dart'; import 'package:mc_common_app/utils/navigator.dart'; import 'package:mc_common_app/utils/utils.dart'; +import 'package:mc_common_app/view_models/requests_view_model.dart'; import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; import 'package:provider/provider.dart'; import 'package:easy_localization/easy_localization.dart'; @@ -22,11 +23,7 @@ class RequestItem extends StatelessWidget { final AppType appType; final int requestIndex; - const RequestItem( - {super.key, - required this.request, - required this.appType, - required this.requestIndex}); + const RequestItem({super.key, required this.request, required this.appType, required this.requestIndex}); @override Widget build(BuildContext context) { @@ -40,16 +37,11 @@ class RequestItem extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Utils.statusContainerChip( - text: request.requestStatusName, - chipColor: Utils.getChipColorByRequestStatus( - request.requestStatus)), + Utils.statusContainerChip(text: request.requestStatusName, chipColor: Utils.getChipColorByRequestStatus(request.requestStatus)), 6.height, - "${request.brand} ${request.model}" - .toText(fontSize: 16, isBold: true), - showItem((LocaleKeys.model.tr()), "${request.year}"), - showItem( - (LocaleKeys.customerName.tr()), request.customerName), + "${request.brand} ${request.model}".toText(fontSize: 16, isBold: true), + showItem("${LocaleKeys.model.tr()}:", "${request.year}"), + showItem("${LocaleKeys.customerName.tr()}:", request.customerName), ], ), ), @@ -62,28 +54,30 @@ class RequestItem extends StatelessWidget { child: "${request.offerCount}".toText( color: Colors.white, isBold: true, - fontSize: 10, + fontSize: 12, ), ).toContainer( backgroundColor: MyColors.redColor, borderRadius: 100, paddingAll: 1, - width: 20, - height: 20, + width: 25, + height: 25, ), ], 2.height, request.cityName.toText( color: MyColors.lightTextColor, ), - "9 Hours Ago".toText( - color: MyColors.lightTextColor, - ) + if (request.createdOn != null) ...[ + DateTime.parse(request.createdOn!).getTimeAgo().toText( + color: MyColors.lightTextColor, + ), + ], ], ) ], ), - showItem((LocaleKeys.description.tr()), request.description), + showItem("${LocaleKeys.description.tr()}:", request.description), showItem("Price Range: ", ""), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -109,33 +103,31 @@ class RequestItem extends StatelessWidget { ), ], ), - const Icon( - Icons.arrow_forward, - color: MyColors.darkIconColor, - size: 18, - ), + request.requestStatus == RequestStatus.submitted + ? const Icon( + Icons.arrow_forward, + color: MyColors.darkIconColor, + size: 18, + ) + : const SizedBox() ], ), ], ).toContainer(isShadowEnabled: true).onPress(() async { + RequestsVM requestsVM = context.read(); + requestsVM.updateCurrentSelectedRequest(request); if (request.requestStatus == RequestStatus.pending) { return; } if (appType == AppType.provider) { - RequestDetailPageArguments requestDetailPageArguments = - RequestDetailPageArguments( - requestIndex: requestIndex, requestModel: request); - navigateWithName(context, AppRoutes.requestsDetailPage, - arguments: requestDetailPageArguments); + RequestDetailPageArguments requestDetailPageArguments = RequestDetailPageArguments(requestIndex: requestIndex, requestModel: request); + navigateWithName(context, AppRoutes.requestsDetailPage, arguments: requestDetailPageArguments); } else { ChatVM chatVM = context.read(); - await chatVM.getOffersFromProvidersByRequest( - requestId: request.id, context: context); - OfferListPageArguments offerListPageArguments = OfferListPageArguments( - serviceProviderOffers: chatVM.serviceProviderOffersList, - requestId: request.id); - navigateWithName(context, AppRoutes.offersListPage, - arguments: offerListPageArguments); + + await chatVM.getOffersFromProvidersByRequest(requestId: request.id, context: context); + OfferListPageArguments offerListPageArguments = OfferListPageArguments(serviceProviderOffers: chatVM.serviceProviderOffersList, requestId: request.id); + navigateWithName(context, AppRoutes.offersListPage, arguments: offerListPageArguments); } }); }