From 4abcd4efe3624a3673c8f8ac6af05ec66ea8df2e Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" <> Date: Mon, 15 Jul 2024 17:21:51 +0300 Subject: [PATCH] Localization --- assets/langs/ar-SA.json | 91 ++- assets/langs/en-US.json | 92 ++- lib/generated/codegen_loader.g.dart | 179 +++++- lib/generated/locale_keys.g.dart | 86 +++ lib/services/common_auth_service.dart | 22 +- lib/view_models/ad_view_model.dart | 583 ++++++++++++------ lib/view_models/appointments_view_model.dart | 550 ++++++++++++----- lib/view_models/chat_view_model.dart | 103 +++- lib/view_models/payment_view_model.dart | 68 +- lib/view_models/requests_view_model.dart | 137 ++-- lib/view_models/service_view_model.dart | 50 +- lib/view_models/subscriptions_view_model.dart | 5 +- lib/view_models/user_view_model.dart | 217 ++++--- .../ad_duration_selection_sheet_content.dart | 67 +- lib/views/advertisement/ads_detail_view.dart | 278 ++++----- 15 files changed, 1810 insertions(+), 718 deletions(-) diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index a40d024..976aab4 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -351,5 +351,94 @@ "demandAmount": "المبلغ المطلوب", "warrantyAvailableYears": "الضمان متاح (عدد السنوات)", "vehicleDescription": "وصف المركبة", - "attachImage": "إرفاق صورة" + "attachImage": "إرفاق صورة", + "useFingerPrintFaceID": "يرجى استخدام بصمة الإصبع أو معرف الوجه", + "setupTouchID": "يرجى إعداد معرف اللمس", + "reenableTouchID": "يرجى إعادة تمكين معرف اللمس", + "scanFaceIDAuthenticate": "امسح بصمة الإصبع أو معرف الوجه للتحقق", + "AdDeletedSuccessfully": "تم حذف الإعلان بنجاح!", + "yourReservationCancelled": "تم إلغاء حجزك.", + "adDeactivatedSuccessfully": "تم إلغاء تفعيل الإعلان بنجاح!", + "vehicle": { + "selectVehicleType": "يرجى اختيار نوع السيارة", + "selectVehicleModel": "يرجى اختيار طراز السيارة", + "selectVehicleModelYear": "يرجى اختيار سنة طراز السيارة", + "selectVehicleColor": "يرجى اختيار لون السيارة", + "vehicleCondition": "يرجى اختيار حالة السيارة", + "vehicleCategory": "يرجى اختيار فئة السيارة", + "vehicleMileage": "يرجى اختيار عدد أميال السيارة", + "vehicleTransmission": "يرجى اختيار نوع ناقل الحركة", + "vehicleSellerType": "يرجى اختيار نوع بائع السيارة", + "selectAny": "يرجى اختيار أي خيار", + "vehicleCity": "يرجى اختيار مدينة السيارة", + "vehiclePart": "يرجى اختيار جزء السيارة", + "selectValidVehicleType": "يرجى اختيار نوع سيارة صالح" + }, + "selectAppointmentTimeService": "يجب عليك اختيار وقت الموعد للخدمة.", + "error": "خطأ", + "appointmentBookedSuccessfully": "تم حجز موعدك بنجاح", + "appointmentStatusUpdated": "تم تحديث حالة الموعد", + "paymentStatusUpdated": "تم تحديث حالة الدفع", + "selectOneSubService": "يرجى اختيار خدمة فرعية واحدة على الأقل", + "chargesBreakdown": "تفاصيل الرسوم", + "services": "الخدمات", + "homeLocation": "الموقع المنزلي", + "selectAppointmentTime": "يجب عليك اختيار وقت الموعد لكل موعد في الجدول", + "noAppointmentAvailable": "لا توجد مواعيد متاحة للعناصر المحددة", + "changedMind": "لقد غيرت رأيي", + "veryHighPrice": "السعر مرتفع جداً", + "alreadySold": "تم البيع بالفعل", + "otherVar": "أخرى", + "paymentSuccessful": "تم الدفع بنجاح", + "paymentFailed": "فشل الدفع!", + "requestSuccessfullyCreated": "تم إنشاء الطلب بنجاح", + "selectValidRequestType": "يرجى اختيار نوع طلب صالح", + "selectValidBrand": "يرجى اختيار علامة تجارية صالحة", + "selectValidModel": "يرجى اختيار طراز صالح", + "selectValidYear": "يرجى اختيار سنة صالحة", + "selectValidCountry": "يرجى اختيار بلد صالح", + "selectValidCity": "يرجى اختيار مدينة صالحة", + "addValidPrice": "يرجى إضافة سعر صالح", + "addValidDescription": "يرجى إضافة وصف صالح", + "passwordTooShort": "كلمة المرور الخاصة بك قصيرة جدًا", + "passwordAcceptableStrong": "كلمة المرور الخاصة بك مقبولة ولكنها ليست قوية", + "passwordIsStrong": "كلمة المرور الخاصة بك قوية", + "passwordVeryStrong": "كلمة المرور الخاصة بك قوية جدًا", + "selectDuration": "اختر المدة", + "daysVar": "الأيام", + "adCharges": "رسوم الإعلان", + "select": "اختر", + "deleteAdConfirmation": "هل تريد حذف الإعلان؟", + "deleteAdConfirmationMessage": "سيتم حذف إعلانك نهائيًا ولا يمكنك التراجع عن هذا الإجراء", + "mileage": "المسافة المقطوعة", + "transmission": "ناقل الحركة", + "demand": "الطلب", + "adDurationExpired": "انتهت مدة عرض الإعلان الخاص بك", + "bankDetails": "تفاصيل البنك", + "bankName": "اسم البنك", + "iban": "الرقم الدولي للحساب المصرفي (IBAN)", + "rejectionComments": "تعليقات الرفض", + "editAd": "تعديل الإعلان", + "reserveAd": "حجز الإعلان", + "reservationAmount": "مبلغ الحجز", + "belowAmountPayLater": "المبلغ الذي ستدفعه لاحقًا", + "carPrice": "سعر السيارة", + "vatExcluded": "القيمة المضافة غير مشمولة", + "carInsuranceService": "خدمة التأمين على السيارة", + "toBeDecided": "لم يتم اتخاذ القرار بعد", + "registrationCarPlates": "تسجيل ولوحات السيارة", + "homeDeliveryService": "خدمة التوصيل إلى المنزل", + "specialServicechargesInsuranceDeliveryLocation": "سيتم إضافة رسوم خدمة خاصة بناءً على التأمين المطلوب وموقع التسليم", + "estimated": "مقدر", + "servicesReservingAd": "بعض الخدمات إلزامية أثناء حجز الإعلان", + "completeReservation": "إتمام الحجز", + "contact": "اتصال", + "setDateandTime": "تحديد التاريخ والوقت", + "selectOffice": "اختيار المكتب", + "availableSlots": "المواعيد المتاحة", + "bookAndPay": "الحجز والدفع", + "reservationAmounts": "مبالغ الحجز", + "tax": "الضريبة" + + } \ No newline at end of file diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index 464157e..412b467 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -351,6 +351,96 @@ "demandAmount": "Demand Amount", "warrantyAvailableYears": "Warranty Available (No. of Years)", "vehicleDescription": "Vehicle Description", - "attachImage": "Attach Image" + "attachImage": "Attach Image", + "useFingerPrintFaceID": "Please use your fingerprint or face ID", + "setupTouchID": "Please set up your Touch ID", + "reenableTouchID": "Please reenable your Touch ID", + "scanFaceIDAuthenticate": "Scan your fingerprint or face ID to authenticate", + "adDeletedSuccessfully": "Ad has been deleted successfully!", + "yourReservationCancelled": "Your reservation has been cancelled.", + "adDeactivatedSuccessfully": "Ad has been deactivated successfully!", + "vehicle": { + "selectVehicleType": "Please select vehicle type", + "selectVehicleModel": "Please select vehicle model", + "selectVehicleModelYear": "Please select vehicle model year", + "selectVehicleColor": "Please select vehicle color", + "vehicleCondition": "Please select vehicle condition", + "vehicleCategory": "Please select vehicle category", + "vehicleMileage": "Please select vehicle Mileage", + "vehicleTransmission": "Please select vehicle transmission", + "vehicleSellerType": "Please select vehicle seller type", + "selectAny": "Please select any", + "vehicleCity": "Please select vehicle city", + "vehiclePart": "Please select vehicle part", + "selectValidVehicleType": "Please select valid Vehicle Type" + }, + "selectAppointmentTimeService": "You must select appointment time the service.", + "error": "Error", + "appointmentBookedSuccessfully": "Your appointment has been booked successfully", + "appointmentStatusUpdated": "Appointment Status Updated", + "paymentStatusUpdated": "Payment Status Updated", + "selectOneSubService": "Please select at least one sub service", + "chargesBreakdown": "Charges Breakdown", + "services": "Services", + "homeLocation": "Home Location", + "selectAppointmentTime": "You must select appointment time for each schedule's appointment", + "noAppointmentAvailable": "There are no available appointments for selected Items", + "changedMind": "I have changed my mind", + "veryHighPrice": "Very High Price", + "alreadySold": "Already Sold", + "otherVar": "Other", + "paymentSuccessful": "Payment Successful", + "paymentFailed": "Payment Failed!", + "requestSuccessfullyCreated": "Request Successfully Created", + "selectValidRequestType": "Please select valid Request Type", + "selectValidBrand": "Please select valid Brand", + "selectValidModel": "Please select valid Model", + "selectValidYear": "Please select valid Year", + "selectValidCountry": "Please select valid Country", + "selectValidCity": "Please select valid City", + "addValidPrice": "Please add valid Price", + "addValidDescription": "Please add valid Description", + "passwordTooShort": "Your password is too short", + "passwordAcceptableStrong": "Your password is acceptable but not strong", + "passwordIsStrong": "Your password is strong", + "passwordVeryStrong": "Your password is very strong", + "onlyProviderApp": "Sorry, Only Customer's can log in this app", + "selectDuration": "Select Duration", + "daysVar": "Days", + "adCharges": "Ad Charges", + "select": "Select", + "deleteAdConfirmation": "Do you want to delete the ad?", + "deleteAdConfirmationMessage": "Your ad will be permanently deleted and you cannot undo this action", + "mileage": "mileage", + "transmission": "Transmission", + "demand": "Demand", + "adDurationExpired": "Your Ad Duration time is over", + "bankDetails": "Bank Details", + "bankName": "Bank Name", + "iban": "IBAN", + "rejectionComments": "Rejection Comments", + "editAd": "Edit Ad", + "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" + + } \ No newline at end of file diff --git a/lib/generated/codegen_loader.g.dart b/lib/generated/codegen_loader.g.dart index 24a2a1b..81ffbf5 100644 --- a/lib/generated/codegen_loader.g.dart +++ b/lib/generated/codegen_loader.g.dart @@ -367,7 +367,94 @@ class CodegenLoader extends AssetLoader{ "demandAmount": "المبلغ المطلوب", "warrantyAvailableYears": "الضمان متاح (عدد السنوات)", "vehicleDescription": "وصف المركبة", - "attachImage": "إرفاق صورة" + "attachImage": "إرفاق صورة", + "useFingerPrintFaceID": "يرجى استخدام بصمة الإصبع أو معرف الوجه", + "setupTouchID": "يرجى إعداد معرف اللمس", + "reenableTouchID": "يرجى إعادة تمكين معرف اللمس", + "scanFaceIDAuthenticate": "امسح بصمة الإصبع أو معرف الوجه للتحقق", + "AdDeletedSuccessfully": "تم حذف الإعلان بنجاح!", + "yourReservationCancelled": "تم إلغاء حجزك.", + "adDeactivatedSuccessfully": "تم إلغاء تفعيل الإعلان بنجاح!", + "vehicle": { + "selectVehicleType": "يرجى اختيار نوع السيارة", + "selectVehicleModel": "يرجى اختيار طراز السيارة", + "selectVehicleModelYear": "يرجى اختيار سنة طراز السيارة", + "selectVehicleColor": "يرجى اختيار لون السيارة", + "vehicleCondition": "يرجى اختيار حالة السيارة", + "vehicleCategory": "يرجى اختيار فئة السيارة", + "vehicleMileage": "يرجى اختيار عدد أميال السيارة", + "vehicleTransmission": "يرجى اختيار نوع ناقل الحركة", + "vehicleSellerType": "يرجى اختيار نوع بائع السيارة", + "selectAny": "يرجى اختيار أي خيار", + "vehicleCity": "يرجى اختيار مدينة السيارة", + "vehiclePart": "يرجى اختيار جزء السيارة", + "selectValidVehicleType": "يرجى اختيار نوع سيارة صالح" + }, + "selectAppointmentTimeService": "يجب عليك اختيار وقت الموعد للخدمة.", + "error": "خطأ", + "appointmentBookedSuccessfully": "تم حجز موعدك بنجاح", + "appointmentStatusUpdated": "تم تحديث حالة الموعد", + "paymentStatusUpdated": "تم تحديث حالة الدفع", + "selectOneSubService": "يرجى اختيار خدمة فرعية واحدة على الأقل", + "chargesBreakdown": "تفاصيل الرسوم", + "services": "الخدمات", + "homeLocation": "الموقع المنزلي", + "selectAppointmentTime": "يجب عليك اختيار وقت الموعد لكل موعد في الجدول", + "noAppointmentAvailable": "لا توجد مواعيد متاحة للعناصر المحددة", + "changedMind": "لقد غيرت رأيي", + "veryHighPrice": "السعر مرتفع جداً", + "alreadySold": "تم البيع بالفعل", + "otherVar": "أخرى", + "paymentSuccessful": "تم الدفع بنجاح", + "paymentFailed": "فشل الدفع!", + "requestSuccessfullyCreated": "تم إنشاء الطلب بنجاح", + "selectValidRequestType": "يرجى اختيار نوع طلب صالح", + "selectValidBrand": "يرجى اختيار علامة تجارية صالحة", + "selectValidModel": "يرجى اختيار طراز صالح", + "selectValidYear": "يرجى اختيار سنة صالحة", + "selectValidCountry": "يرجى اختيار بلد صالح", + "selectValidCity": "يرجى اختيار مدينة صالحة", + "addValidPrice": "يرجى إضافة سعر صالح", + "addValidDescription": "يرجى إضافة وصف صالح", + "passwordTooShort": "كلمة المرور الخاصة بك قصيرة جدًا", + "passwordAcceptableStrong": "كلمة المرور الخاصة بك مقبولة ولكنها ليست قوية", + "passwordIsStrong": "كلمة المرور الخاصة بك قوية", + "passwordVeryStrong": "كلمة المرور الخاصة بك قوية جدًا", + "selectDuration": "اختر المدة", + "daysVar": "الأيام", + "adCharges": "رسوم الإعلان", + "select": "اختر", + "deleteAdConfirmation": "هل تريد حذف الإعلان؟", + "deleteAdConfirmationMessage": "سيتم حذف إعلانك نهائيًا ولا يمكنك التراجع عن هذا الإجراء", + "mileage": "المسافة المقطوعة", + "transmission": "ناقل الحركة", + "demand": "الطلب", + "adDurationExpired": "انتهت مدة عرض الإعلان الخاص بك", + "bankDetails": "تفاصيل البنك", + "bankName": "اسم البنك", + "iban": "الرقم الدولي للحساب المصرفي (IBAN)", + "rejectionComments": "تعليقات الرفض", + "editAd": "تعديل الإعلان", + "reserveAd": "حجز الإعلان", + "reservationAmount": "مبلغ الحجز", + "belowAmountPayLater": "المبلغ الذي ستدفعه لاحقًا", + "carPrice": "سعر السيارة", + "vatExcluded": "القيمة المضافة غير مشمولة", + "carInsuranceService": "خدمة التأمين على السيارة", + "toBeDecided": "لم يتم اتخاذ القرار بعد", + "registrationCarPlates": "تسجيل ولوحات السيارة", + "homeDeliveryService": "خدمة التوصيل إلى المنزل", + "specialServicechargesInsuranceDeliveryLocation": "سيتم إضافة رسوم خدمة خاصة بناءً على التأمين المطلوب وموقع التسليم", + "estimated": "مقدر", + "servicesReservingAd": "بعض الخدمات إلزامية أثناء حجز الإعلان", + "completeReservation": "إتمام الحجز", + "contact": "اتصال", + "setDateandTime": "تحديد التاريخ والوقت", + "selectOffice": "اختيار المكتب", + "availableSlots": "المواعيد المتاحة", + "bookAndPay": "الحجز والدفع", + "reservationAmounts": "مبالغ الحجز", + "tax": "الضريبة" }; static const Map en_US = { "firstTimeLogIn": "First Time Log In", @@ -722,7 +809,95 @@ static const Map en_US = { "demandAmount": "Demand Amount", "warrantyAvailableYears": "Warranty Available (No. of Years)", "vehicleDescription": "Vehicle Description", - "attachImage": "Attach Image" + "attachImage": "Attach Image", + "useFingerPrintFaceID": "Please use your fingerprint or face ID", + "setupTouchID": "Please set up your Touch ID", + "reenableTouchID": "Please reenable your Touch ID", + "scanFaceIDAuthenticate": "Scan your fingerprint or face ID to authenticate", + "adDeletedSuccessfully": "Ad has been deleted successfully!", + "yourReservationCancelled": "Your reservation has been cancelled.", + "adDeactivatedSuccessfully": "Ad has been deactivated successfully!", + "vehicle": { + "selectVehicleType": "Please select vehicle type", + "selectVehicleModel": "Please select vehicle model", + "selectVehicleModelYear": "Please select vehicle model year", + "selectVehicleColor": "Please select vehicle color", + "vehicleCondition": "Please select vehicle condition", + "vehicleCategory": "Please select vehicle category", + "vehicleMileage": "Please select vehicle Mileage", + "vehicleTransmission": "Please select vehicle transmission", + "vehicleSellerType": "Please select vehicle seller type", + "selectAny": "Please select any", + "vehicleCity": "Please select vehicle city", + "vehiclePart": "Please select vehicle part", + "selectValidVehicleType": "Please select valid Vehicle Type" + }, + "selectAppointmentTimeService": "You must select appointment time the service.", + "error": "Error", + "appointmentBookedSuccessfully": "Your appointment has been booked successfully", + "appointmentStatusUpdated": "Appointment Status Updated", + "paymentStatusUpdated": "Payment Status Updated", + "selectOneSubService": "Please select at least one sub service", + "chargesBreakdown": "Charges Breakdown", + "services": "Services", + "homeLocation": "Home Location", + "selectAppointmentTime": "You must select appointment time for each schedule's appointment", + "noAppointmentAvailable": "There are no available appointments for selected Items", + "changedMind": "I have changed my mind", + "veryHighPrice": "Very High Price", + "alreadySold": "Already Sold", + "otherVar": "Other", + "paymentSuccessful": "Payment Successful", + "paymentFailed": "Payment Failed!", + "requestSuccessfullyCreated": "Request Successfully Created", + "selectValidRequestType": "Please select valid Request Type", + "selectValidBrand": "Please select valid Brand", + "selectValidModel": "Please select valid Model", + "selectValidYear": "Please select valid Year", + "selectValidCountry": "Please select valid Country", + "selectValidCity": "Please select valid City", + "addValidPrice": "Please add valid Price", + "addValidDescription": "Please add valid Description", + "passwordTooShort": "Your password is too short", + "passwordAcceptableStrong": "Your password is acceptable but not strong", + "passwordIsStrong": "Your password is strong", + "passwordVeryStrong": "Your password is very strong", + "onlyProviderApp": "Sorry, Only Customer's can log in this app", + "selectDuration": "Select Duration", + "daysVar": "Days", + "adCharges": "Ad Charges", + "select": "Select", + "deleteAdConfirmation": "Do you want to delete the ad?", + "deleteAdConfirmationMessage": "Your ad will be permanently deleted and you cannot undo this action", + "mileage": "mileage", + "transmission": "Transmission", + "demand": "Demand", + "adDurationExpired": "Your Ad Duration time is over", + "bankDetails": "Bank Details", + "bankName": "Bank Name", + "iban": "IBAN", + "rejectionComments": "Rejection Comments", + "editAd": "Edit Ad", + "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" }; 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 915960d..8ecc7ca 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -332,5 +332,91 @@ abstract class LocaleKeys { static const warrantyAvailableYears = 'warrantyAvailableYears'; static const vehicleDescription = 'vehicleDescription'; static const attachImage = 'attachImage'; + static const useFingerPrintFaceID = 'useFingerPrintFaceID'; + static const setupTouchID = 'setupTouchID'; + static const reenableTouchID = 'reenableTouchID'; + static const scanFaceIDAuthenticate = 'scanFaceIDAuthenticate'; + static const AdDeletedSuccessfully = 'AdDeletedSuccessfully'; + static const yourReservationCancelled = 'yourReservationCancelled'; + static const adDeactivatedSuccessfully = 'adDeactivatedSuccessfully'; + static const vehicle_selectVehicleType = 'vehicle.selectVehicleType'; + static const vehicle_selectVehicleModel = 'vehicle.selectVehicleModel'; + static const vehicle_selectVehicleModelYear = 'vehicle.selectVehicleModelYear'; + static const vehicle_selectVehicleColor = 'vehicle.selectVehicleColor'; + static const vehicle_vehicleCondition = 'vehicle.vehicleCondition'; + static const vehicle_vehicleCategory = 'vehicle.vehicleCategory'; + static const vehicle_vehicleMileage = 'vehicle.vehicleMileage'; + static const vehicle_vehicleTransmission = 'vehicle.vehicleTransmission'; + static const vehicle_vehicleSellerType = 'vehicle.vehicleSellerType'; + static const vehicle_selectAny = 'vehicle.selectAny'; + static const vehicle_vehicleCity = 'vehicle.vehicleCity'; + static const vehicle_vehiclePart = 'vehicle.vehiclePart'; + static const vehicle_selectValidVehicleType = 'vehicle.selectValidVehicleType'; + static const vehicle = 'vehicle'; + static const selectAppointmentTimeService = 'selectAppointmentTimeService'; + static const error = 'error'; + static const appointmentBookedSuccessfully = 'appointmentBookedSuccessfully'; + static const appointmentStatusUpdated = 'appointmentStatusUpdated'; + static const paymentStatusUpdated = 'paymentStatusUpdated'; + static const selectOneSubService = 'selectOneSubService'; + static const chargesBreakdown = 'chargesBreakdown'; + static const services = 'services'; + static const homeLocation = 'homeLocation'; + static const selectAppointmentTime = 'selectAppointmentTime'; + static const noAppointmentAvailable = 'noAppointmentAvailable'; + static const changedMind = 'changedMind'; + static const veryHighPrice = 'veryHighPrice'; + static const alreadySold = 'alreadySold'; + static const otherVar = 'otherVar'; + static const paymentSuccessful = 'paymentSuccessful'; + static const paymentFailed = 'paymentFailed'; + static const requestSuccessfullyCreated = 'requestSuccessfullyCreated'; + static const selectValidRequestType = 'selectValidRequestType'; + static const selectValidBrand = 'selectValidBrand'; + static const selectValidModel = 'selectValidModel'; + static const selectValidYear = 'selectValidYear'; + static const selectValidCountry = 'selectValidCountry'; + static const selectValidCity = 'selectValidCity'; + static const addValidPrice = 'addValidPrice'; + static const addValidDescription = 'addValidDescription'; + static const passwordTooShort = 'passwordTooShort'; + static const passwordAcceptableStrong = 'passwordAcceptableStrong'; + static const passwordIsStrong = 'passwordIsStrong'; + static const passwordVeryStrong = 'passwordVeryStrong'; + static const selectDuration = 'selectDuration'; + static const daysVar = 'daysVar'; + static const adCharges = 'adCharges'; + static const select = 'select'; + static const deleteAdConfirmation = 'deleteAdConfirmation'; + static const deleteAdConfirmationMessage = 'deleteAdConfirmationMessage'; + static const mileage = 'mileage'; + static const transmission = 'transmission'; + static const demand = 'demand'; + static const adDurationExpired = 'adDurationExpired'; + static const bankDetails = 'bankDetails'; + static const bankName = 'bankName'; + static const iban = 'iban'; + static const rejectionComments = 'rejectionComments'; + static const editAd = 'editAd'; + static const reserveAd = 'reserveAd'; + static const reservationAmount = 'reservationAmount'; + static const belowAmountPayLater = 'belowAmountPayLater'; + static const carPrice = 'carPrice'; + static const vatExcluded = 'vatExcluded'; + static const carInsuranceService = 'carInsuranceService'; + static const toBeDecided = 'toBeDecided'; + static const registrationCarPlates = 'registrationCarPlates'; + static const homeDeliveryService = 'homeDeliveryService'; + static const specialServicechargesInsuranceDeliveryLocation = 'specialServicechargesInsuranceDeliveryLocation'; + static const estimated = 'estimated'; + static const servicesReservingAd = 'servicesReservingAd'; + static const completeReservation = 'completeReservation'; + static const contact = 'contact'; + static const setDateandTime = 'setDateandTime'; + static const selectOffice = 'selectOffice'; + static const availableSlots = 'availableSlots'; + static const bookAndPay = 'bookAndPay'; + static const reservationAmounts = 'reservationAmounts'; + static const tax = 'tax'; } diff --git a/lib/services/common_auth_service.dart b/lib/services/common_auth_service.dart index 1daeec0..1f52e02 100644 --- a/lib/services/common_auth_service.dart +++ b/lib/services/common_auth_service.dart @@ -6,7 +6,9 @@ import 'package:huawei_fido/huawei_fido.dart'; import 'package:local_auth/local_auth.dart'; import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_darwin/types/auth_messages_ios.dart'; +import 'package:mc_common_app/generated/locale_keys.g.dart'; import 'package:mc_common_app/main.dart'; +import 'package:easy_localization/easy_localization.dart'; abstract class CommonAuthServices { Future authenticate(); @@ -33,17 +35,17 @@ class CommonAuthImp implements CommonAuthServices { useErrorDialogs: true, ), authMessages: [ - const AndroidAuthMessages( - cancelButton: 'Cancel', - biometricHint: 'Please use your fingerprint or face ID', - goToSettingsButton: 'Settings', - goToSettingsDescription: 'Please set up your Touch ID.', + AndroidAuthMessages( + cancelButton: LocaleKeys.cancel.tr(), + biometricHint: LocaleKeys.useFingerPrintFaceID.tr(), + goToSettingsButton: LocaleKeys.settings.tr(), + goToSettingsDescription: LocaleKeys.setupTouchID.tr(), ), - const IOSAuthMessages( - cancelButton: 'Cancel', - goToSettingsButton: 'Settings', - goToSettingsDescription: 'Please set up your Touch ID.', - lockOut: 'Please reenable your Touch ID', + IOSAuthMessages( + cancelButton: LocaleKeys.cancel.tr(), + goToSettingsButton: LocaleKeys.settings.tr(), + goToSettingsDescription: LocaleKeys.setupTouchID.tr(), + lockOut: LocaleKeys.reenableTouchID.tr(), ), ], ); diff --git a/lib/view_models/ad_view_model.dart b/lib/view_models/ad_view_model.dart index af8f5ee..ff636b1 100644 --- a/lib/view_models/ad_view_model.dart +++ b/lib/view_models/ad_view_model.dart @@ -6,6 +6,7 @@ import 'package:mc_common_app/classes/consts.dart'; import 'package:mc_common_app/config/dependencies.dart'; import 'package:mc_common_app/config/routes.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/advertisment_models/ad_details_model.dart'; import 'package:mc_common_app/models/advertisment_models/ads_bank_details_model.dart'; @@ -27,6 +28,7 @@ import 'package:mc_common_app/utils/navigator.dart'; import 'package:mc_common_app/utils/utils.dart'; import 'package:mc_common_app/view_models/base_view_model.dart'; import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; +import 'package:easy_localization/easy_localization.dart'; class AdVM extends BaseVM { final CommonRepo commonRepo; @@ -34,7 +36,10 @@ 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; @@ -95,19 +100,23 @@ 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) { @@ -135,7 +144,9 @@ 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(); @@ -165,32 +176,44 @@ class AdVM extends BaseVM { List myAdsFilterOptions = []; populateAdsFilterList() async { - if (myAdsFilterOptions.isNotEmpty && exploreAdsFilterOptions.isNotEmpty) return; + 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: 18); //18 is to get My Ad Filter Enums } if (exploreAdsEnums.isEmpty) { - exploreAdsEnums = await commonRepo.getEnumTypeValues(enumTypeID: 23); // 23 is to get Explore Ad Filter Enums + exploreAdsEnums = await commonRepo.getEnumTypeValues( + enumTypeID: 23); // 23 is to get Explore Ad Filter Enums } 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)); 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; @@ -202,14 +225,17 @@ 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; @@ -231,15 +257,21 @@ 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); @@ -253,9 +285,11 @@ 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); @@ -285,7 +319,8 @@ class AdVM extends BaseVM { } Future getVehicleAdsSpecialServices() async { - vehicleAdsSpecialServices = await adsRepo.getSpecialServices(specialServiceId: 1); + vehicleAdsSpecialServices = + await adsRepo.getSpecialServices(specialServiceId: 1); notifyListeners(); } @@ -304,7 +339,8 @@ 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); @@ -314,7 +350,8 @@ 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); } @@ -328,15 +365,20 @@ class AdVM extends BaseVM { return; } Utils.hideLoading(context); - Utils.showToast("Ad has been deleted successfully!"); + 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); @@ -344,15 +386,18 @@ class AdVM extends BaseVM { return; } Utils.hideLoading(context); - Utils.showToast("Your reservation has been cancelled."); + 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); @@ -360,9 +405,10 @@ class AdVM extends BaseVM { return; } Utils.hideLoading(context); - Utils.showToast("Ad has been deactivated successfully!"); + 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); } @@ -387,14 +433,18 @@ 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(); } @@ -405,7 +455,9 @@ 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!; @@ -463,7 +515,8 @@ 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; @@ -471,13 +524,18 @@ 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(); @@ -490,18 +548,22 @@ 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); @@ -513,28 +575,32 @@ 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; @@ -587,14 +653,16 @@ 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; @@ -605,31 +673,38 @@ 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(); @@ -639,28 +714,32 @@ 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; @@ -690,7 +769,8 @@ 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; @@ -699,14 +779,17 @@ 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; @@ -715,8 +798,10 @@ 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(); @@ -753,7 +838,8 @@ 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(), "")); } } @@ -771,7 +857,8 @@ 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(), "")); } } @@ -781,7 +868,7 @@ class AdVM extends BaseVM { bool isVehicleDetailsValidated() { bool isValidated = true; if (vehicleTypeId.selectedId == -1) { - vehicleTypeId.errorValue = "Please select vehicle type"; + vehicleTypeId.errorValue = LocaleKeys.vehicle_selectVehicleType.tr(); isValidated = false; notifyListeners(); return isValidated; @@ -789,70 +876,73 @@ class AdVM extends BaseVM { vehicleTypeId.errorValue = ""; } if (vehicleModelId.selectedId == -1) { - vehicleModelId.errorValue = "Please select vehicle model"; + vehicleModelId.errorValue = LocaleKeys.vehicle_selectVehicleModel.tr(); isValidated = false; } else { vehicleModelId.errorValue = ""; } if (vehicleModelYearId.selectedId == -1) { - vehicleModelYearId.errorValue = "Please select vehicle model year"; + vehicleModelYearId.errorValue = + LocaleKeys.vehicle_selectVehicleModelYear.tr(); isValidated = false; } else { vehicleModelYearId.errorValue = ""; } if (vehicleColorId.selectedId == -1) { - vehicleColorId.errorValue = "Please select vehicle color"; + vehicleColorId.errorValue = LocaleKeys.vehicle_selectVehicleColor.tr(); isValidated = false; } else { vehicleColorId.errorValue = ""; } if (vehicleConditionId.selectedId == -1) { - vehicleConditionId.errorValue = "Please select vehicle condition"; + vehicleConditionId.errorValue = LocaleKeys.vehicle_vehicleCondition.tr(); isValidated = false; } else { vehicleConditionId.errorValue = ""; } if (vehicleCategoryId.selectedId == -1) { - vehicleCategoryId.errorValue = "Please select vehicle category"; + vehicleCategoryId.errorValue = LocaleKeys.vehicle_vehicleCategory.tr(); isValidated = false; } else { vehicleCategoryId.errorValue = ""; } if (vehicleMileageId.selectedId == -1) { - vehicleMileageId.errorValue = "Please select vehicle Mileage"; + vehicleMileageId.errorValue = LocaleKeys.vehicle_vehicleMileage.tr(); isValidated = false; } else { vehicleMileageId.errorValue = ""; } if (vehicleTransmissionId.selectedId == -1) { - vehicleTransmissionId.errorValue = "Please select vehicle transmission"; + vehicleTransmissionId.errorValue = + LocaleKeys.vehicle_vehicleTransmission.tr(); isValidated = false; } else { vehicleTransmissionId.errorValue = ""; } if (vehicleSellerTypeId.selectedId == -1) { - vehicleSellerTypeId.errorValue = "Please select vehicle seller type"; + vehicleSellerTypeId.errorValue = + LocaleKeys.vehicle_vehicleSellerType.tr(); isValidated = false; } else { vehicleSellerTypeId.errorValue = ""; } if (vehicleCountryId.selectedId == -1) { - vehicleCountryId.errorValue = "Please select any"; + vehicleCountryId.errorValue = LocaleKeys.vehicle_selectAny.tr(); isValidated = false; } else { vehicleCountryId.errorValue = ""; } if (vehicleCityId.selectedId != -1 && vehicleCityId.selectedId == -1) { - vehicleCityId.errorValue = "Please select vehicle city"; + vehicleCityId.errorValue = LocaleKeys.vehicle_vehicleCity.tr(); isValidated = false; } else { vehicleCityId.errorValue = ""; @@ -888,7 +978,8 @@ 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 { @@ -915,7 +1006,8 @@ class AdVM extends BaseVM { for (var element in vehicleDamageCards) { if (element.partSelectedId!.selectedId == -1) { - element.partSelectedId!.errorValue = "Please select vehicle part"; + element.partSelectedId!.errorValue = + LocaleKeys.vehicle_vehiclePart.tr(); isValidated = false; } else { element.partSelectedId!.errorValue = ""; @@ -946,7 +1038,7 @@ class AdVM extends BaseVM { bool isAdDurationValidated() { bool isValidated = true; if (vehicleAdDurationId.selectedId == -1) { - vehicleAdDurationId.errorValue = "Please select vehicle part"; + vehicleAdDurationId.errorValue = LocaleKeys.vehicle_vehiclePart.tr(); isValidated = false; } else { vehicleAdDurationId.errorValue = ""; @@ -1047,7 +1139,9 @@ 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); @@ -1082,7 +1176,8 @@ 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; } @@ -1107,7 +1202,8 @@ 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; } @@ -1149,7 +1245,8 @@ 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; } @@ -1158,7 +1255,8 @@ 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) { @@ -1171,10 +1269,12 @@ 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; } @@ -1196,19 +1296,32 @@ 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 = ""; @@ -1227,63 +1340,83 @@ 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); @@ -1303,30 +1436,41 @@ 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; } } } if (!isValidated) { - Utils.showToast("You must select appointment time the service."); + Utils.showToast(LocaleKeys.selectAppointmentTimeService.tr()); return; } Utils.showLoading(context); try { - GenericRespModel genericRespModel = await adsRepo.createAppointmentForAdSpecialService( + GenericRespModel genericRespModel = + await adsRepo.createAppointmentForAdSpecialService( adId: adDetailsModel.id ?? 0, photoOfficeID: photoOfficeSelectedId.selectedId, photoOfficeSlotID: selectedPhotoOfficeSlotDateTime ?? 0, @@ -1335,14 +1479,16 @@ class AdVM extends BaseVM { Utils.hideLoading(context); if (genericRespModel.messageStatus != 1) { - Utils.showToast("Error: ${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); - Utils.showToast("Error: ${e.toString()}"); + Utils.showToast(LocaleKeys.error.tr() + ": ${e.toString()}"); } } @@ -1363,7 +1509,8 @@ 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 = []; @@ -1371,7 +1518,8 @@ 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, ); @@ -1403,19 +1551,26 @@ 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( @@ -1431,14 +1586,16 @@ 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) { @@ -1446,7 +1603,8 @@ 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!); @@ -1469,9 +1627,11 @@ 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}) { @@ -1489,7 +1649,8 @@ 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(); @@ -1513,7 +1674,8 @@ 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(); @@ -1536,13 +1698,18 @@ 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(); @@ -1554,7 +1721,8 @@ 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(); @@ -1578,7 +1746,8 @@ 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(); @@ -1654,11 +1823,14 @@ 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 { @@ -1682,7 +1854,8 @@ 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( @@ -1699,7 +1872,8 @@ 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; } @@ -1708,50 +1882,86 @@ 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( @@ -1765,9 +1975,13 @@ 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 ?? "", @@ -1782,7 +1996,8 @@ class AdVM extends BaseVM { } } - selectionDurationStartDate = DateHelper.formatDateT(previousAdDetails!.startdate ?? ""); + selectionDurationStartDate = + DateHelper.formatDateT(previousAdDetails!.startdate ?? ""); isPhoneNumberShown = previousAdDetails!.phoneNo != null; if (isPhoneNumberShown) { adPhoneNumber = previousAdDetails!.phoneNo ?? ""; @@ -1796,11 +2011,13 @@ 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 e685c9d..33496d8 100644 --- a/lib/view_models/appointments_view_model.dart +++ b/lib/view_models/appointments_view_model.dart @@ -5,6 +5,7 @@ import 'package:mc_common_app/classes/consts.dart'; 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/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'; @@ -36,6 +37,7 @@ import 'package:mc_common_app/widgets/common_widgets/info_bottom_sheet.dart'; import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; import 'package:provider/provider.dart'; +import 'package:easy_localization/easy_localization.dart'; class AppointmentsVM extends BaseVM { final CommonRepo commonRepo; @@ -43,7 +45,11 @@ 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; @@ -70,7 +76,8 @@ 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; } @@ -91,7 +98,8 @@ 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; @@ -107,9 +115,13 @@ 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 { @@ -117,7 +129,8 @@ 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, ); @@ -143,15 +156,19 @@ 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("Your appointment has been booked successfully!"); + Utils.showToast(LocaleKeys.appointmentBookedSuccessfully.tr()); getMyAppointments(); navigateReplaceWithNameUntilRoute(context, AppRoutes.dashboard); } @@ -161,28 +178,37 @@ 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); @@ -213,7 +239,8 @@ 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; @@ -228,23 +255,30 @@ 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); + int serviceId = servicesInCurrentAppointment + .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; } @@ -259,21 +293,30 @@ 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)); 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) { @@ -281,7 +324,8 @@ class AppointmentsVM extends BaseVM { } for (var element in appointmentsFilterOptions) { - if (element.id == appointmentStatusEnum.getIdFromAppointmentStatusEnum()) { + if (element.id == + appointmentStatusEnum.getIdFromAppointmentStatusEnum()) { element.isSelected = true; } } @@ -296,7 +340,11 @@ 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(); } @@ -312,7 +360,9 @@ 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; @@ -335,20 +385,29 @@ 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 { @@ -359,24 +418,32 @@ 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("appointment status updated"); + Utils.showToast(LocaleKeys.appointmentStatusUpdated.tr()); } else { Utils.showToast(genericRespModel.message.toString()); } @@ -385,13 +452,15 @@ 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("payment status updated"); + Utils.showToast(LocaleKeys.paymentStatusUpdated.tr()); } else { Utils.showToast(genericRespModel.message.toString()); } @@ -400,9 +469,11 @@ 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; } @@ -410,10 +481,16 @@ 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 @@ -422,35 +499,61 @@ class AppointmentsVM extends BaseVM { } int countSelected(List appointments) { - return appointments.where((appointment) => appointment.isSelected == true).toList().length; + return appointments + .where((appointment) => appointment.isSelected == true) + .toList() + .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(); } @@ -464,7 +567,8 @@ 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; @@ -479,19 +583,28 @@ 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(); } @@ -503,7 +616,8 @@ class AppointmentsVM extends BaseVM { } branchesFilterOptions[index].isSelected = true; - await getBranchesBasedOnCategoryFilters(categoryId: branchesFilterOptions[index].id); + await getBranchesBasedOnCategoryFilters( + categoryId: branchesFilterOptions[index].id); notifyListeners(); } @@ -522,7 +636,8 @@ 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; @@ -549,7 +664,7 @@ class AppointmentsVM extends BaseVM { return true; } } - selectSubServicesError = "Please select at least one sub service"; + selectSubServicesError = LocaleKeys.selectOneSubService.tr(); notifyListeners(); return false; } @@ -562,7 +677,8 @@ class AppointmentsVM extends BaseVM { return totalPrice.toString(); } - void openTheAddServiceBottomSheet(BuildContext context, AppointmentsVM appointmentsVM) { + void openTheAddServiceBottomSheet( + BuildContext context, AppointmentsVM appointmentsVM) { showModalBottomSheet( context: context, isScrollControlled: true, @@ -573,7 +689,8 @@ class AppointmentsVM extends BaseVM { ); } - void priceBreakDownClicked(BuildContext context, ServiceModel selectedService) { + void priceBreakDownClicked( + BuildContext context, ServiceModel selectedService) { showModalBottomSheet( context: context, isScrollControlled: true, @@ -581,19 +698,25 @@ class AppointmentsVM extends BaseVM { builder: (BuildContext context) { double totalKms = 15.3; return InfoBottomSheet( - title: "Charges Breakdown".toText(fontSize: 24, isBold: true), + title: LocaleKeys.chargesBreakdown + .tr() + .toText(fontSize: 24, isBold: true), description: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Services".toText(fontSize: 16, isBold: true), + LocaleKeys.services.tr().toText(fontSize: 16, isBold: true), 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), + "${selectedService.serviceItems![index].name}".toText( + fontSize: 12, + color: MyColors.lightTextColor, + isBold: true), + "${selectedService.serviceItems![index].price} SAR" + .toText(fontSize: 12, isBold: true), ], ), ), @@ -601,24 +724,32 @@ class AppointmentsVM extends BaseVM { 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, - "Home Location".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), ], ), ], @@ -626,7 +757,9 @@ class AppointmentsVM extends BaseVM { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Total Amount ".toText(fontSize: 16, isBold: true), + LocaleKeys.totalAmount + .tr() + .toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ @@ -635,7 +768,13 @@ class AppointmentsVM extends BaseVM { : "${selectedService.currentTotalServicePrice}") .toText(fontSize: 29, isBold: true), 2.width, - "SAR".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), ], ) ], @@ -655,7 +794,8 @@ 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 { @@ -663,7 +803,9 @@ 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; @@ -672,7 +814,7 @@ class AppointmentsVM extends BaseVM { } } if (!isValidated) { - Utils.showToast("You must select appointment time for each schedule's appointment."); + Utils.showToast(LocaleKeys.selectAppointmentTime.tr()); return; } navigateWithName(context, AppRoutes.reviewAppointmentView); @@ -691,30 +833,36 @@ class AppointmentsVM extends BaseVM { } } - serviceAppointmentScheduleList = await appointmentRepo.mergeServiceIntoAvailableSchedules( + serviceAppointmentScheduleList = + await appointmentRepo.mergeServiceIntoAvailableSchedules( serviceItemIdsForHome: serviceItemIdsForHome, serviceItemIdsForWorkshop: serviceItemIdsForWorkshop, ); if (serviceAppointmentScheduleList.isEmpty) { Utils.hideLoading(context); - Utils.showToast("There are no available appointments for selected Items."); + Utils.showToast(LocaleKeys.noAppointmentAvailable.tr()); return; } 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 = []; @@ -731,14 +879,15 @@ class AppointmentsVM extends BaseVM { } } - serviceAppointmentScheduleList = await appointmentRepo.mergeServiceIntoAvailableSchedules( + serviceAppointmentScheduleList = + await appointmentRepo.mergeServiceIntoAvailableSchedules( serviceItemIdsForHome: serviceItemIdsForHome, serviceItemIdsForWorkshop: serviceItemIdsForWorkshop, ); if (serviceAppointmentScheduleList.isEmpty) { Utils.hideLoading(context); - Utils.showToast("There are no available appointments for selected Items."); + Utils.showToast(LocaleKeys.noAppointmentAvailable.tr()); return; } Utils.hideLoading(context); @@ -746,29 +895,36 @@ 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); @@ -805,20 +961,27 @@ 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; } @@ -829,14 +992,16 @@ 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 = ""; @@ -849,13 +1014,16 @@ 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); } @@ -890,7 +1058,8 @@ 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(); @@ -912,12 +1081,16 @@ 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); } } @@ -929,7 +1102,8 @@ 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(); @@ -951,12 +1125,16 @@ 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); } } @@ -968,7 +1146,8 @@ 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(); @@ -990,12 +1169,16 @@ 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(); @@ -1036,7 +1219,8 @@ 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", ""), @@ -1070,7 +1254,8 @@ 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( @@ -1103,9 +1288,12 @@ 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 { @@ -1142,14 +1330,16 @@ 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); } @@ -1157,12 +1347,15 @@ 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); @@ -1185,7 +1378,8 @@ 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(); @@ -1197,7 +1391,8 @@ class AppointmentsVM extends BaseVM { for (var element in appointmentFilterProviderSearchHistory) { providerIdsSelected.add(element.id); } - fetchAllBranchesBySelectedProviderId(providersIdsList: providerIdsSelected); + fetchAllBranchesBySelectedProviderId( + providersIdsList: providerIdsSelected); } if (appointmentFilterProviderSearchHistory.isEmpty) { @@ -1220,12 +1415,16 @@ 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); } } @@ -1237,7 +1436,8 @@ 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(); @@ -1259,12 +1459,16 @@ 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); } } @@ -1276,7 +1480,8 @@ 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(); @@ -1298,12 +1503,16 @@ 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); } } @@ -1313,7 +1522,8 @@ 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(); @@ -1335,12 +1545,16 @@ 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); } } @@ -1349,10 +1563,14 @@ 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() { @@ -1393,13 +1611,15 @@ 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 cdd4859..c53bcde 100644 --- a/lib/view_models/chat_view_model.dart +++ b/lib/view_models/chat_view_model.dart @@ -6,6 +6,7 @@ import 'package:flutter/cupertino.dart'; import 'package:mc_common_app/classes/app_state.dart'; import 'package:mc_common_app/classes/consts.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/chat_models/chat_message_model.dart'; import 'package:mc_common_app/models/general_models/generic_resp_model.dart'; @@ -17,6 +18,7 @@ import 'package:mc_common_app/utils/utils.dart'; import 'package:mc_common_app/view_models/requests_view_model.dart'; import 'package:provider/provider.dart'; import 'package:signalr_core/signalr_core.dart'; +import 'package:easy_localization/easy_localization.dart'; class ChatVM extends ChangeNotifier { final ChatRepo chatRepo; @@ -48,22 +50,22 @@ class ChatVM extends ChangeNotifier { OfferRequestCommentModel( index: 0, isSelected: false, - title: "I have changed my mind.", + title: LocaleKeys.changedMind.tr(), ), OfferRequestCommentModel( index: 1, isSelected: false, - title: "Very High Price.", + title: LocaleKeys.veryHighPrice.tr(), ), OfferRequestCommentModel( index: 2, isSelected: false, - title: "Already Sold", + title: LocaleKeys.alreadySold.tr(), ), OfferRequestCommentModel( index: 3, isSelected: true, - title: "Other", + title: LocaleKeys.otherVar.tr(), ), ]; @@ -100,11 +102,15 @@ class ChatVM extends ChangeNotifier { return isValidated; } - Future onNewMessageReceived({required List messages, required BuildContext context, bool isMyOwnOffer = false}) async { + Future onNewMessageReceived( + {required List messages, + required BuildContext context, + bool isMyOwnOffer = false}) async { // log("message I received in onNewMessageReceived ${messages.first.toString()}"); 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); if (providerIndex != -1) { serviceProviderOffersList[providerIndex].chatMessages!.add(msg); } @@ -114,19 +120,23 @@ class ChatVM extends ChangeNotifier { // 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); } } } @@ -135,15 +145,18 @@ 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); @@ -165,7 +178,8 @@ 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) { @@ -183,7 +197,8 @@ class ChatVM extends ChangeNotifier { "RequestID": requestId, "Price": double.parse(offerPrice), "ServiceProviderID": providerId, - "OfferStatus": RequestOfferStatusEnum.offer.getIdFromRequestOfferStatusEnum(), + "OfferStatus": RequestOfferStatusEnum.offer + .getIdFromRequestOfferStatusEnum(), "Comment": message, }, } @@ -207,7 +222,8 @@ 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) { @@ -251,14 +267,21 @@ 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; @@ -268,10 +291,12 @@ 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 ?? []; @@ -293,10 +318,15 @@ 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"); @@ -322,8 +352,13 @@ 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()); @@ -332,10 +367,16 @@ 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/payment_view_model.dart b/lib/view_models/payment_view_model.dart index 75aff78..44049d3 100644 --- a/lib/view_models/payment_view_model.dart +++ b/lib/view_models/payment_view_model.dart @@ -3,6 +3,7 @@ import 'dart:developer'; import 'package:flutter/cupertino.dart'; import 'package:mc_common_app/config/routes.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/models/payment_models/pay_order_detail_resp_model.dart'; import 'package:mc_common_app/repositories/payments_repo.dart'; import 'package:mc_common_app/services/payments_service.dart'; @@ -11,7 +12,7 @@ import 'package:mc_common_app/utils/navigator.dart'; import 'package:mc_common_app/utils/utils.dart'; import 'package:mc_common_app/view_models/subscriptions_view_model.dart'; import 'package:provider/provider.dart'; - +import 'package:easy_localization/easy_localization.dart'; import '../classes/app_state.dart'; class PaymentVM extends ChangeNotifier { @@ -52,9 +53,8 @@ class PaymentVM extends ChangeNotifier { notifyListeners(); } - Future onContinuePressed(BuildContext context, {required PaymentTypes paymentType}) async { - - + Future onContinuePressed(BuildContext context, + {required PaymentTypes paymentType}) async { switch (selectedPaymentMethod) { case PaymentMethods.mada: // TODO: Handle this case. @@ -76,41 +76,53 @@ class PaymentVM extends ChangeNotifier { return; } - Future onAdsPaymentSuccess({required BuildContext context, required int currentAdId, required int paymentTypeId}) async { + Future onAdsPaymentSuccess( + {required BuildContext context, + required int currentAdId, + required int paymentTypeId}) async { Utils.showLoading(context); - PayOrderDetailRespModel payOrderDetailRespModel = await paymentRepo.getPayOrderDetails(paymentId: paymentTypeId, adId: currentAdId); + PayOrderDetailRespModel payOrderDetailRespModel = await paymentRepo + .getPayOrderDetails(paymentId: paymentTypeId, adId: currentAdId); await Future.delayed(const Duration(seconds: 2)); Utils.hideLoading(context); log("payOrderDetailRespModel: ${payOrderDetailRespModel.toString()}"); - if (payOrderDetailRespModel.isPaid == null || !payOrderDetailRespModel.isPaid!) { - Utils.showToast("Payment Failed!"); + if (payOrderDetailRespModel.isPaid == null || + !payOrderDetailRespModel.isPaid!) { + Utils.showToast(LocaleKeys.paymentFailed.tr()); return; } - if (payOrderDetailRespModel.isPaid != null && payOrderDetailRespModel.isPaid!) { - Utils.showToast("Payment Successful"); + if (payOrderDetailRespModel.isPaid != null && + payOrderDetailRespModel.isPaid!) { + Utils.showToast(LocaleKeys.paymentSuccessful.tr()); navigateReplaceWithNameUntilRoute(context, AppRoutes.dashboard); } } - Future onAppointmentPaymentSuccess({required BuildContext context, required int currentAdId, required int paymentTypeId}) async { + Future onAppointmentPaymentSuccess( + {required BuildContext context, + required int currentAdId, + required int paymentTypeId}) async { Utils.showLoading(context); //TODO: CONFIRM FROM ZAHOOR THAT WILL THIS METHOD WORK FOR APPOINTMENT - PayOrderDetailRespModel payOrderDetailRespModel = await paymentRepo.getPayOrderDetails(paymentId: paymentTypeId, adId: currentAdId); + PayOrderDetailRespModel payOrderDetailRespModel = await paymentRepo + .getPayOrderDetails(paymentId: paymentTypeId, adId: currentAdId); await Future.delayed(const Duration(seconds: 2)); Utils.hideLoading(context); log("payOrderDetailRespModel: ${payOrderDetailRespModel.toString()}"); - if (payOrderDetailRespModel.isPaid == null || !payOrderDetailRespModel.isPaid!) { - Utils.showToast("Payment Failed!"); + if (payOrderDetailRespModel.isPaid == null || + !payOrderDetailRespModel.isPaid!) { + Utils.showToast(LocaleKeys.paymentFailed.tr()); return; } - if (payOrderDetailRespModel.isPaid != null && payOrderDetailRespModel.isPaid!) { - Utils.showToast("Payment Successful"); + if (payOrderDetailRespModel.isPaid != null && + payOrderDetailRespModel.isPaid!) { + Utils.showToast(LocaleKeys.paymentSuccessful.tr()); navigateReplaceWithNameUntilRoute(context, AppRoutes.dashboard); } } @@ -131,14 +143,16 @@ class PaymentVM extends ChangeNotifier { } } - Future placeThePayment({required PaymentTypes paymentTypeEnum, required BuildContext context}) async { + Future placeThePayment( + {required PaymentTypes paymentTypeEnum, + required BuildContext context}) async { await paymentService.placePayment( // This will be request ID for request payment || ad ID for Ad Related Payment || OrderProviderSubscriptionID for SubscriptionPayment id: getIdTypeByPaymentType(paymentTypeEnum), appointmentIds: appointmentIdsForPayment, paymentType: paymentTypeEnum, onFailure: () { - Utils.showToast("Payment Failed!"); + Utils.showToast(LocaleKeys.paymentFailed.tr()); switch (paymentTypeEnum) { case PaymentTypes.subscription: // TODO: Handle this case. @@ -179,7 +193,10 @@ class PaymentVM extends ChangeNotifier { case PaymentTypes.adReserve: case PaymentTypes.ads: case PaymentTypes.extendAds: - await onAdsPaymentSuccess(context: context, paymentTypeId: paymentTypeEnum.getIdFromPaymentTypesEnum(), currentAdId: currentAdId); + await onAdsPaymentSuccess( + context: context, + paymentTypeId: paymentTypeEnum.getIdFromPaymentTypesEnum(), + currentAdId: currentAdId); break; case PaymentTypes.partialAppointment: log("Partial Appointment Payment has been Succeeded"); @@ -189,21 +206,16 @@ class PaymentVM extends ChangeNotifier { ); } - onSubscriptionSuccess(BuildContext context){ + onSubscriptionSuccess(BuildContext context) { pop(context); pop(context); pop(context); context.read().getMySubscriptions( - AppState() - .getUser - .data - ?.userInfo - ?.providerId - .toString() ?? - ""); + AppState().getUser.data?.userInfo?.providerId.toString() ?? ""); } - Future onVisaCardSelected(BuildContext context, PaymentTypes paymentType) async { + Future onVisaCardSelected( + BuildContext context, PaymentTypes paymentType) async { currentPaymentType = paymentType; switch (currentPaymentType) { case PaymentTypes.appointment: diff --git a/lib/view_models/requests_view_model.dart b/lib/view_models/requests_view_model.dart index 2077713..a6fb875 100644 --- a/lib/view_models/requests_view_model.dart +++ b/lib/view_models/requests_view_model.dart @@ -8,6 +8,7 @@ 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'; import 'package:mc_common_app/extensions/string_extensions.dart'; +import 'package:mc_common_app/generated/locale_keys.g.dart'; import 'package:mc_common_app/models/advertisment_models/vehicle_details_models.dart'; import 'package:mc_common_app/models/chat_models/chat_message_model.dart'; import 'package:mc_common_app/models/general_models/enums_model.dart'; @@ -25,13 +26,17 @@ import 'package:mc_common_app/view_models/ad_view_model.dart'; import 'package:mc_common_app/view_models/base_view_model.dart'; import 'package:mc_common_app/view_models/chat_view_model.dart'; import 'package:provider/provider.dart'; +import 'package:easy_localization/easy_localization.dart'; class RequestsVM extends BaseVM { final CommonAppServices commonServices; 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 = []; @@ -44,10 +49,14 @@ class RequestsVM extends BaseVM { 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: 16); //TODO: 16 is to get Requests Filter Enums } 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()}"); @@ -55,7 +64,8 @@ class RequestsVM extends BaseVM { 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 = {}; @@ -66,22 +76,29 @@ 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(); @@ -92,8 +109,14 @@ 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(); } @@ -102,7 +125,8 @@ 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; } @@ -132,7 +156,8 @@ 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; @@ -140,7 +165,8 @@ class RequestsVM extends BaseVM { notifyListeners(); } - SelectionModel vehicleTypeId = SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); + SelectionModel vehicleTypeId = + SelectionModel(selectedOption: "", selectedId: -1, errorValue: ""); Future getVehicleTypes() async { resetRequestCreationForm(); @@ -171,7 +197,8 @@ 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!; @@ -183,24 +210,30 @@ 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; @@ -215,18 +248,21 @@ 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; @@ -244,10 +280,12 @@ 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; } @@ -256,7 +294,8 @@ 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); } @@ -267,7 +306,8 @@ 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()); @@ -291,7 +331,7 @@ class RequestsVM extends BaseVM { GenericRespModel respModel = await requestRepo.createRequest(body); Utils.hideLoading(context); if (respModel.messageStatus == 1) { - Utils.showToast("Request Successfully Created"); + Utils.showToast(LocaleKeys.requestSuccessfullyCreated.tr()); Navigator.pop(context); await getRequests(appType: AppType.customer); } else { @@ -307,40 +347,42 @@ class RequestsVM extends BaseVM { bool validateCreateRequestForm() { bool isValid = true; if (requestTypeId.selectedId == -1) { - Utils.showToast("Please select valid Request Type"); + Utils.showToast(LocaleKeys.selectValidRequestType.tr()); isValid = false; } else if (vehicleTypeId.selectedId == -1) { - Utils.showToast("Please select valid Vehicle Type"); + Utils.showToast(LocaleKeys.vehicle_selectValidVehicleType.tr()); isValid = false; } else if (vehicleBrandId.selectedId == -1) { - Utils.showToast("Please select valid Brand"); + Utils.showToast(LocaleKeys.selectValidBrand.tr()); isValid = false; } else if (vehicleModelId.selectedId == -1) { - Utils.showToast("Please select valid Model"); + Utils.showToast(LocaleKeys.selectValidModel.tr()); isValid = false; } else if (vehicleModelYearId.selectedId == -1) { - Utils.showToast("Please select valid Year"); + Utils.showToast(LocaleKeys.selectValidYear.tr()); isValid = false; } else if (vehicleCountryId.selectedId == -1) { - Utils.showToast("Please select valid Country"); + Utils.showToast(LocaleKeys.selectValidCountry.tr()); isValid = false; } else if (vehicleCityId.selectedId == -1) { - Utils.showToast("Please select valid City"); + Utils.showToast(LocaleKeys.selectValidCity.tr()); isValid = false; } else if (price.isEmpty) { - Utils.showToast("Please add valid Price"); + Utils.showToast(LocaleKeys.addValidPrice.tr()); isValid = false; } else if (description.isEmpty) { - Utils.showToast("Please add valid Description"); + Utils.showToast(LocaleKeys.addValidDescription.tr()); isValid = false; } 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) { @@ -431,22 +473,26 @@ 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, @@ -456,7 +502,8 @@ class RequestsVM extends BaseVM { requestIndex: requestIndex, providerIndex: -1, ); - navigateWithName(context, AppRoutes.chatView, arguments: chatViewArguments); + navigateWithName(context, AppRoutes.chatView, + arguments: chatViewArguments); } } } diff --git a/lib/view_models/service_view_model.dart b/lib/view_models/service_view_model.dart index 44fe97b..f348195 100644 --- a/lib/view_models/service_view_model.dart +++ b/lib/view_models/service_view_model.dart @@ -236,6 +236,7 @@ // } import 'dart:io'; +import 'package:mc_common_app/generated/locale_keys.g.dart'; import 'package:mc_common_app/repositories/branch_repo.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/cupertino.dart'; @@ -257,6 +258,7 @@ import 'package:mc_common_app/utils/enums.dart'; import 'package:mc_common_app/utils/utils.dart'; import 'package:mc_common_app/view_models/base_view_model.dart'; import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; +import 'package:easy_localization/easy_localization.dart'; class ServiceVM extends BaseVM { final BranchRepo branchRepo; @@ -324,7 +326,7 @@ class ServiceVM extends BaseVM { int sizeInBytes = file.lengthSync(); // double sizeInMb = sizeInBytes / (1024 * 1024); if (sizeInBytes > 1000000) { - Utils.showToast("File is larger then 1KB"); + Utils.showToast(LocaleKeys.fileLarger.tr()); } else { document!.data![index].document = Utils.convertFileToBase64(file); document!.data![index].fileExt = Utils.checkFileExt(file.path); @@ -348,7 +350,8 @@ class ServiceVM extends BaseVM { setState(ViewState.idle); } - Future getAllCountriesList(BranchDetailModel? branchData, String countryCode) async { + Future getAllCountriesList( + BranchDetailModel? branchData, String countryCode) async { cities = null; country = null; setState(ViewState.busy); @@ -360,7 +363,9 @@ class ServiceVM extends BaseVM { countryId = element.id ?? -1; countryValue = DropValue( element.id ?? 0, - countryCode == "SA" ? (element.countryNameN ?? "") : (element.countryName ?? ""), + countryCode == "SA" + ? (element.countryNameN ?? "") + : (element.countryName ?? ""), element.countryCode ?? "", ); } @@ -368,7 +373,9 @@ class ServiceVM extends BaseVM { countryDropList.add( DropValue( element.id ?? 0, - countryCode == "SA" ? (element.countryNameN ?? "") : (element.countryName ?? ""), + countryCode == "SA" + ? (element.countryNameN ?? "") + : (element.countryName ?? ""), element.countryCode ?? "", ), ); @@ -379,7 +386,8 @@ class ServiceVM extends BaseVM { setState(ViewState.idle); } - Future getAllCities(BranchDetailModel? branchData, String countryCode) async { + Future getAllCities( + BranchDetailModel? branchData, String countryCode) async { setState(ViewState.busy); citiesDropList = []; cities = null; @@ -398,7 +406,9 @@ class ServiceVM extends BaseVM { cityId = branchData.cityId!; cityValue = DropValue( element.id ?? 0, - countryCode == "SA" ? (element.cityNameN ?? "") : (element.cityName ?? ""), + countryCode == "SA" + ? (element.cityNameN ?? "") + : (element.cityName ?? ""), element.id.toString() ?? "", ); } @@ -406,7 +416,9 @@ class ServiceVM extends BaseVM { citiesDropList.add( DropValue( element.id ?? 0, - countryCode == "SA" ? (element.cityNameN ?? "") : (element.cityName ?? ""), + countryCode == "SA" + ? (element.cityNameN ?? "") + : (element.cityName ?? ""), element.id.toString() ?? "", ), ); @@ -414,8 +426,10 @@ class ServiceVM extends BaseVM { setState(ViewState.idle); } - Future createBranch(String branchName, String branchDescription, String cityId, String address, String latitude, String longitude) async { - return await branchRepo.createBranch(branchName, branchDescription, cityId.toString(), address, latitude.toString(), longitude.toString()); + Future createBranch(String branchName, String branchDescription, + String cityId, String address, String latitude, String longitude) async { + return await branchRepo.createBranch(branchName, branchDescription, + cityId.toString(), address, latitude.toString(), longitude.toString()); } Future updateBranch( @@ -489,7 +503,8 @@ class ServiceVM extends BaseVM { Future fetchServicesByCategoryId(int categoryId) async { servicesDropList = []; setState(ViewState.busy); - services = await branchRepo.fetchServicesByCategoryId(serviceCategoryId: categoryId); // to get all the services + services = await branchRepo.fetchServicesByCategoryId( + serviceCategoryId: categoryId); // to get all the services for (var element in services!.data!) { servicesDropList.add( DropValue( @@ -536,13 +551,16 @@ class ServiceVM extends BaseVM { List? matchedServices; bool isAllSelected = false; - Future getAllMatchedServices(int oldBranchId, int newBranchId, int categoryId) async { + Future getAllMatchedServices( + int oldBranchId, int newBranchId, int categoryId) async { matchedServices = null; - final MResponse response = await branchRepo.getMatchedServices(oldBranchId, newBranchId, categoryId); + final MResponse response = await branchRepo.getMatchedServices( + oldBranchId, newBranchId, categoryId); matchedServices = []; if (response.messageStatus == 1) { - matchedServices = List.from(response.data.map((x) => ServiceModel.fromJson(x))); + matchedServices = List.from( + response.data.map((x) => ServiceModel.fromJson(x))); } notifyListeners(); } @@ -583,7 +601,8 @@ class ServiceVM extends BaseVM { MResponse response = await branchRepo.getAllProviderDealers(map); if (response.messageStatus == 1) { allProviderDealersList = []; - allProviderDealersList = List.from(response.data.map((x) => BranchUser.fromJson(x))); + allProviderDealersList = List.from( + response.data.map((x) => BranchUser.fromJson(x))); } setState(ViewState.idle); } @@ -593,7 +612,8 @@ class ServiceVM extends BaseVM { MResponse response = await branchRepo.getBranchUsers(map); if (response.messageStatus == 1) { branchUserList = []; - branchUserList = List.from(response.data.map((x) => BranchUser.fromJson(x))); + branchUserList = List.from( + response.data.map((x) => BranchUser.fromJson(x))); } setState(ViewState.idle); } diff --git a/lib/view_models/subscriptions_view_model.dart b/lib/view_models/subscriptions_view_model.dart index d89c5a9..d6a31a5 100644 --- a/lib/view_models/subscriptions_view_model.dart +++ b/lib/view_models/subscriptions_view_model.dart @@ -1,6 +1,5 @@ import 'dart:convert'; - import 'package:mc_common_app/classes/app_state.dart'; import 'package:mc_common_app/models/general_models/m_response.dart'; import 'package:mc_common_app/models/subscriptions_models/branch_user_selection_model.dart'; @@ -8,7 +7,6 @@ import 'package:mc_common_app/models/subscriptions_models/subscription_model.dar import 'package:mc_common_app/utils/enums.dart'; import 'package:mc_common_app/view_models/base_view_model.dart'; import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; - import '../repositories/subscription_repo.dart'; class SubscriptionsVM extends BaseVM { @@ -171,7 +169,8 @@ class SubscriptionsVM extends BaseVM { selectedIndex = 0; setState(ViewState.busy); // allSubscriptions = await subscriptionRepo.getAllSubscriptions(serviceProviderID); - allSubscriptions = await subscriptionRepo.getMySubscriptions(serviceProviderID); + allSubscriptions = + await subscriptionRepo.getMySubscriptions(serviceProviderID); if (allSubscriptions.messageStatus == 1) { // allSubscriptions.data!.sort((a, b) => a.value.compareTo(b.value)); setState(ViewState.idle); diff --git a/lib/view_models/user_view_model.dart b/lib/view_models/user_view_model.dart index ef18a5d..078d3cc 100644 --- a/lib/view_models/user_view_model.dart +++ b/lib/view_models/user_view_model.dart @@ -70,16 +70,19 @@ class UserVM extends BaseVM { notifyListeners(); } - Future changeUserEmail(BuildContext context, String email, String password) async { + Future changeUserEmail( + BuildContext context, String email, String password) async { Utils.showLoading(context); - ChanEmailRespModel otpRequest = await userRepo.changeEmailOTPRequest(email, password); + ChanEmailRespModel otpRequest = + await userRepo.changeEmailOTPRequest(email, password); Utils.hideLoading(context); if (otpRequest.messageStatus == 1) { showMDialog(context, child: OtpDialog( onClick: (String code) async { pop(context); Utils.showLoading(context); - ConfirmEmailRespModel otpCompare = await userRepo.changeEmail(otpRequest.data!.userToken ?? "", code); + ConfirmEmailRespModel otpCompare = await userRepo.changeEmail( + otpRequest.data!.userToken ?? "", code); Utils.hideLoading(context); if (otpCompare.messageStatus == 1) { showMDialog( @@ -88,7 +91,9 @@ class UserVM extends BaseVM { title: LocaleKeys.emailChangedSuccessfully.tr(), //"Email is Changed Successfully", onClick: () { - Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route route) => true); + Navigator.of(context).pushNamedAndRemoveUntil( + AppRoutes.loginWithPassword, + (Route route) => true); }, ), ); @@ -102,16 +107,19 @@ class UserVM extends BaseVM { } } - Future changeUserMobile(BuildContext context, int countryId, String mobileNo, String password) async { + Future changeUserMobile(BuildContext context, int countryId, + String mobileNo, String password) async { Utils.showLoading(context); - ChangeMobileRespModel otpRequest = await userRepo.changeMobileNoOTPRequest(countryId, mobileNo, password); + ChangeMobileRespModel otpRequest = + await userRepo.changeMobileNoOTPRequest(countryId, mobileNo, password); Utils.hideLoading(context); if (otpRequest.messageStatus == 1) { showMDialog(context, child: OtpDialog( onClick: (String code) async { pop(context); Utils.showLoading(context); - ConfirmMobileRespModel otpCompare = await userRepo.changeMobileNo(otpRequest.data!.userToken ?? "", code); + ConfirmMobileRespModel otpCompare = await userRepo.changeMobileNo( + otpRequest.data!.userToken ?? "", code); Utils.hideLoading(context); if (otpCompare.messageStatus == 1) { showMDialog( @@ -120,7 +128,9 @@ class UserVM extends BaseVM { title: LocaleKeys.phoneNumberVerified.tr(), //"Phone Number Verified", onClick: () { - Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route route) => true); + Navigator.of(context).pushNamedAndRemoveUntil( + AppRoutes.loginWithPassword, + (Route route) => true); }, ), ); @@ -134,16 +144,19 @@ class UserVM extends BaseVM { } } - Future changeUserPassword(BuildContext context, String newPassword, String currentPassword) async { + Future changeUserPassword( + BuildContext context, String newPassword, String currentPassword) async { if (Utils.passwordValidateStructure(newPassword)) { Utils.showLoading(context); - MResponse res = await userRepo.changePassword(currentPassword, newPassword); + MResponse res = + await userRepo.changePassword(currentPassword, newPassword); Utils.hideLoading(context); if (res.messageStatus == 1) { Utils.showToast(LocaleKeys.passwordIsUpdated.tr()); //("Password is Updated"); // navigateWithName(context, AppRoutes.loginWithPassword); - Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route route) => true); + Navigator.of(context).pushNamedAndRemoveUntil( + AppRoutes.loginWithPassword, (Route route) => true); } else { Utils.showToast(res.message ?? ""); } @@ -226,26 +239,28 @@ class UserVM extends BaseVM { void checkPassword(String password) { if (password.length <= 6) { updateStrengthThreshold(1 / 4); - updateStrengthText('Your password is too short'); + updateStrengthText(LocaleKeys.passwordTooShort.tr()); } else if (password.length < 8) { updateStrengthThreshold(2 / 4); - updateStrengthText('Your password is acceptable but not strong'); + updateStrengthText(LocaleKeys.passwordAcceptableStrong.tr()); } else { if (!letterReg.hasMatch(password) || !numReg.hasMatch(password)) { updateStrengthThreshold(3 / 4); - updateStrengthText('Your password is strong'); + updateStrengthText(LocaleKeys.passwordIsStrong.tr()); } else { updateStrengthThreshold(1); - updateStrengthText('Your password is very strong'); + updateStrengthText(LocaleKeys.passwordVeryStrong.tr()); } } notifyListeners(); } - Future confirmPasswordOTP(BuildContext context, {required String userToken, required String newPassword}) async { + Future confirmPasswordOTP(BuildContext context, + {required String userToken, required String newPassword}) async { if (Utils.passwordValidateStructure(newPassword)) { Utils.showLoading(context); - ConfirmPasswordRespModel data = await userRepo.forgetPassword(userToken, newPassword); + ConfirmPasswordRespModel data = + await userRepo.forgetPassword(userToken, newPassword); Utils.hideLoading(context); if (data.messageStatus == 1) { Utils.showToast(LocaleKeys.passwordIsUpdated.tr()); @@ -258,7 +273,8 @@ class UserVM extends BaseVM { } } - Future verifyEmail(BuildContext context, {required String email, required String userID}) async { + Future verifyEmail(BuildContext context, + {required String email, required String userID}) async { Utils.showLoading(context); VerifyEmailRespModel otpRequest = await userRepo.emailVerify(email, userID); Utils.hideLoading(context); @@ -267,7 +283,8 @@ class UserVM extends BaseVM { onClick: (String code) async { pop(context); Utils.showLoading(context); - MResponse otpCompare = await userRepo.emailVerifyOTPVerify(otpRequest.data!.userToken ?? "", code); + MResponse otpCompare = await userRepo.emailVerifyOTPVerify( + otpRequest.data!.userToken ?? "", code); Utils.hideLoading(context); if (otpCompare.messageStatus == 1) { AppState().getUser.data!.userInfo!.isEmailVerified = true; @@ -283,16 +300,19 @@ class UserVM extends BaseVM { notifyListeners(); } - Future forgetPasswordOTPMethod(BuildContext context, {required String userToken}) async { + Future forgetPasswordOTPMethod(BuildContext context, + {required String userToken}) async { showMDialog(context, child: OtpDialog( onClick: (String code) async { pop(context); Utils.showLoading(context); - PasswordOTPCompareResModel otpCompare = await userRepo.forgetPasswordOTPCompare(userToken, code); + PasswordOTPCompareResModel otpCompare = + await userRepo.forgetPasswordOTPCompare(userToken, code); Utils.hideLoading(context); if (otpCompare.messageStatus == 1) { var userToken = otpCompare.data!.userToken; - navigateWithName(context, AppRoutes.confirmNewPasswordPage, arguments: userToken); + navigateWithName(context, AppRoutes.confirmNewPasswordPage, + arguments: userToken); } else { Utils.showToast(otpCompare.message ?? ""); } @@ -300,35 +320,48 @@ class UserVM extends BaseVM { )); } - Future forgetPasswordPhoneOTP(BuildContext context, {required String countryCode, required String userName, required int otpType}) async { + Future forgetPasswordPhoneOTP(BuildContext context, + {required String countryCode, + required String userName, + required int otpType}) async { Utils.showLoading(context); - Response response = await userRepo.forgetPasswordOTPRequest(countryCode + userName, otpType); + Response response = await userRepo.forgetPasswordOTPRequest( + countryCode + userName, otpType); Utils.hideLoading(context); - PasswordOTPRequestRespModel otpRequest = PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body)); + PasswordOTPRequestRespModel otpRequest = + PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body)); if (otpRequest.messageStatus == 1) { var userToken = otpRequest.data!.userToken; - navigateReplaceWithName(context, AppRoutes.forgetPasswordMethodPage, arguments: userToken); + navigateReplaceWithName(context, AppRoutes.forgetPasswordMethodPage, + arguments: userToken); } else { Utils.showToast(otpRequest.message ?? ""); } } - Future forgetPasswordEmailOTP(BuildContext context, {required String countryCode, required String userName, required int otpType}) async { + Future forgetPasswordEmailOTP(BuildContext context, + {required String countryCode, + required String userName, + required int otpType}) async { Utils.showLoading(context); - Response response = await userRepo.forgetPasswordOTPRequest(userName, otpType); + Response response = + await userRepo.forgetPasswordOTPRequest(userName, otpType); Utils.hideLoading(context); - PasswordOTPRequestRespModel otpRequest = PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body)); + PasswordOTPRequestRespModel otpRequest = + PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body)); if (otpRequest.messageStatus == 1) { Utils.showToast(LocaleKeys.codeSentToEmail.tr()); showMDialog(context, child: OtpDialog( onClick: (String code) async { pop(context); Utils.showLoading(context); - PasswordOTPCompareResModel otpCompare = await userRepo.forgetPasswordOTPCompare(otpRequest.data!.userToken ?? "", code); + PasswordOTPCompareResModel otpCompare = await userRepo + .forgetPasswordOTPCompare(otpRequest.data!.userToken ?? "", code); Utils.hideLoading(context); if (otpCompare.messageStatus == 1) { var userToken = otpCompare.data!.userToken; - navigateWithName(context, AppRoutes.confirmNewPasswordPage, arguments: userToken); + navigateWithName(context, AppRoutes.confirmNewPasswordPage, + arguments: userToken); } else { Utils.showToast(otpCompare.message ?? ""); } @@ -339,28 +372,36 @@ class UserVM extends BaseVM { } } - Future performBasicOtpLoginSelectionPage(BuildContext context, {required String userToken, required AppType appType, String? loginType}) async { + Future performBasicOtpLoginSelectionPage(BuildContext context, + {required String userToken, + required AppType appType, + String? loginType}) async { if (loginType == "3" || loginType == "4") { Utils.showLoading(context); - LoginPasswordRespModel user = await userRepo.loginV2OTP(userToken, loginType!); + LoginPasswordRespModel user = + await userRepo.loginV2OTP(userToken, loginType!); Utils.hideLoading(context); if (user.messageStatus == 1) { Utils.showLoading(context); - Response response2 = await userRepo.loginV2OTPVerify(user.data!.userToken ?? "", "9999"); + Response response2 = + await userRepo.loginV2OTPVerify(user.data!.userToken ?? "", "9999"); Utils.hideLoading(context); - RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body)); + RegisterUserRespModel verifiedUser = + RegisterUserRespModel.fromJson(jsonDecode(response2.body)); if (verifiedUser.messageStatus == 1) { User user = User.fromJson(jsonDecode(response2.body)); if (appType == AppType.provider) { - if (user.data!.userInfo!.roleId == 5 || user.data!.userInfo!.roleId == 6) { + if (user.data!.userInfo!.roleId == 5 || + user.data!.userInfo!.roleId == 6) { AppState().setUser = user; SharedPrefManager.setUserToken(user.data!.accessToken ?? ""); SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? ""); SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? ""); - SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson())); + SharedPrefManager.setData( + jsonEncode(user.data!.userInfo!.toJson())); navigateReplaceWithName(context, AppRoutes.dashboard); } else { - Utils.showToast("LocaleKeys.onlyProviderApp.tr()"); + Utils.showToast(LocaleKeys.onlyProviderApp.tr()); //("Sorry, Only Customer's can log in this app"); } } else if (user.data!.userInfo!.roleId == 4) { @@ -369,10 +410,11 @@ class UserVM extends BaseVM { SharedPrefManager.setUserToken(user.data!.accessToken ?? ""); SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? ""); SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? ""); - SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson())); + SharedPrefManager.setData( + jsonEncode(user.data!.userInfo!.toJson())); navigateReplaceWithName(context, AppRoutes.dashboard); } else { - Utils.showToast("Sorry, Only Customer's can log in this app"); + Utils.showToast(LocaleKeys.onlyCustomerApp.tr()); } } } else { @@ -388,33 +430,42 @@ class UserVM extends BaseVM { onClick: (String code) async { pop(context); Utils.showLoading(context); - Response response2 = await userRepo.loginV2OTPVerify(user.data!.userToken ?? "", code); + Response response2 = await userRepo.loginV2OTPVerify( + user.data!.userToken ?? "", code); Utils.hideLoading(context); - RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body)); + RegisterUserRespModel verifiedUser = + RegisterUserRespModel.fromJson(jsonDecode(response2.body)); if (verifiedUser.messageStatus == 1) { User user = User.fromJson(jsonDecode(response2.body)); if (appType == AppType.provider) { - if (user.data!.userInfo!.roleId == 5 || user.data!.userInfo!.roleId == 6) { + if (user.data!.userInfo!.roleId == 5 || + user.data!.userInfo!.roleId == 6) { AppState().setUser = user; SharedPrefManager.setUserToken(user.data!.accessToken ?? ""); - SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? ""); - SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? ""); - SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson())); + SharedPrefManager.setUserId( + user.data!.userInfo!.userId ?? ""); + SharedPrefManager.setRefreshToken( + user.data!.refreshToken ?? ""); + SharedPrefManager.setData( + jsonEncode(user.data!.userInfo!.toJson())); navigateReplaceWithName(context, AppRoutes.dashboard); } else { - Utils.showToast("LocaleKeys.onlyProviderApp.tr()"); + Utils.showToast(LocaleKeys.onlyProviderApp.tr()); //("Sorry, Only Customer's can log in this app"); } } else if (user.data!.userInfo!.roleId == 4) { if (user.data!.userInfo!.roleId == 4) { AppState().setUser = user; SharedPrefManager.setUserToken(user.data!.accessToken ?? ""); - SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? ""); - SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? ""); - SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson())); + SharedPrefManager.setUserId( + user.data!.userInfo!.userId ?? ""); + SharedPrefManager.setRefreshToken( + user.data!.refreshToken ?? ""); + SharedPrefManager.setData( + jsonEncode(user.data!.userInfo!.toJson())); navigateReplaceWithName(context, AppRoutes.dashboard); } else { - Utils.showToast("Sorry, Only Customer's can log in this app"); + Utils.showToast(LocaleKeys.onlyCustomerApp.tr()); } } } else { @@ -428,7 +479,8 @@ class UserVM extends BaseVM { } } - Future performApiCallLoginVerificationPage(BuildContext context) async { + Future performApiCallLoginVerificationPage( + BuildContext context) async { String userToken = ""; String userName = await SharedPrefManager.getPhoneOrEmail(); String password = await SharedPrefManager.getUserPassword(); @@ -436,7 +488,8 @@ class UserVM extends BaseVM { Utils.showLoading(context); Response response = await userRepo.loginV1(userName, password); Utils.hideLoading(context); - LoginPasswordRespModel user = LoginPasswordRespModel.fromJson(jsonDecode(response.body)); + LoginPasswordRespModel user = + LoginPasswordRespModel.fromJson(jsonDecode(response.body)); if (user.messageStatus == 1) { userToken = user.data!.userToken ?? ""; // navigateWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken); @@ -447,7 +500,8 @@ class UserVM extends BaseVM { return userToken; } - Future performBasicOtpLoginVerificationPage(BuildContext context, {required String userToken}) async { + Future performBasicOtpLoginVerificationPage(BuildContext context, + {required String userToken}) async { Utils.showLoading(context); LoginPasswordRespModel user = await userRepo.loginV2OTP(userToken, "1"); Utils.hideLoading(context); @@ -456,9 +510,11 @@ class UserVM extends BaseVM { onClick: (String code) async { pop(context); Utils.showLoading(context); - Response response2 = await userRepo.loginV2OTPVerify(user.data!.userToken ?? "", code); + Response response2 = + await userRepo.loginV2OTPVerify(user.data!.userToken ?? "", code); Utils.hideLoading(context); - RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body)); + RegisterUserRespModel verifiedUser = + RegisterUserRespModel.fromJson(jsonDecode(response2.body)); if (verifiedUser.messageStatus == 1) { User user = User.fromJson(jsonDecode(response2.body)); AppState().setUser = user; @@ -473,16 +529,19 @@ class UserVM extends BaseVM { } } - Future performBasicOtpLoginVerifyAccountPage(BuildContext context, {required String phoneNum, required int otpType}) async { + Future performBasicOtpLoginVerifyAccountPage(BuildContext context, + {required String phoneNum, required int otpType}) async { Utils.showLoading(context); - BasicOtpRespModel basicOtp = await userRepo.basicOtp(phoneNum, otpType: otpType); + BasicOtpRespModel basicOtp = + await userRepo.basicOtp(phoneNum, otpType: otpType); Utils.hideLoading(context); if (basicOtp.messageStatus == 1) { showMDialog(context, child: OtpDialog( onClick: (String code) async { pop(context); Utils.showLoading(context); - RegisterUserRespModel user = await userRepo.basicVerify(phoneNum, code, basicOtp.data!.userToken ?? ""); + RegisterUserRespModel user = await userRepo.basicVerify( + phoneNum, code, basicOtp.data!.userToken ?? ""); Utils.hideLoading(context); if (user.messageStatus == 1) { Utils.showToast(user.message ?? ""); @@ -493,7 +552,8 @@ class UserVM extends BaseVM { //"Phone Number Verified", onClick: () { pop(context); - navigateWithName(context, AppRoutes.profile1, arguments: user); + navigateWithName(context, AppRoutes.profile1, + arguments: user); }, ), ); @@ -507,15 +567,23 @@ class UserVM extends BaseVM { } } - Future performBasicOtpLoginWithPasswordPage(BuildContext context, {required ClassType type, required String countryCode, required String phoneNum, required String password}) async { + Future performBasicOtpLoginWithPasswordPage(BuildContext context, + {required ClassType type, + required String countryCode, + required String phoneNum, + required String password}) async { Utils.showLoading(context); - Response response = await userRepo.loginV1(type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum, password); + Response response = await userRepo.loginV1( + type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum, password); Utils.hideLoading(context); - LoginPasswordRespModel user = LoginPasswordRespModel.fromJson(jsonDecode(response.body)); + LoginPasswordRespModel user = + LoginPasswordRespModel.fromJson(jsonDecode(response.body)); if (user.messageStatus == 1) { - SharedPrefManager.setPhoneOrEmail(type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum); + SharedPrefManager.setPhoneOrEmail( + type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum); SharedPrefManager.setUserPassword(password); - navigateReplaceWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken); + navigateReplaceWithName(context, AppRoutes.loginMethodSelection, + arguments: user.data!.userToken); } else { Utils.showToast(user.message ?? ""); } @@ -526,9 +594,14 @@ class UserVM extends BaseVM { } Future performBasicOtpRegisterPage(BuildContext context, - {required String countryCode, required String phoneNum, required int role, bool isNeedToPassToken = false, VoidCallback? reloadPage}) async { + {required String countryCode, + required String phoneNum, + required int role, + bool isNeedToPassToken = false, + VoidCallback? reloadPage}) async { Utils.showLoading(context); - BasicOtpRespModel basicOtp = await userRepo.basicOtp(countryCode + phoneNum, roleId: role, isNeedToPassToken: isNeedToPassToken); + BasicOtpRespModel basicOtp = await userRepo.basicOtp(countryCode + phoneNum, + roleId: role, isNeedToPassToken: isNeedToPassToken); Utils.hideLoading(context); if (basicOtp.messageStatus == 1) { showMDialog(context, child: OtpDialog( @@ -546,7 +619,9 @@ class UserVM extends BaseVM { Utils.showToast(user.message ?? ""); user.data!.roleId = role; user.data!.isNeedToPassToken = isNeedToPassToken; - navigateReplaceWithName(context, AppRoutes.completeProfile, arguments: user).then((value) { + navigateReplaceWithName(context, AppRoutes.completeProfile, + arguments: user) + .then((value) { if (reloadPage != null) { reloadPage(); } @@ -572,7 +647,8 @@ class UserVM extends BaseVM { }) async { bool auth = await CommonAuthImp().authenticate(); if (auth) { - performBasicOtpLoginSelectionPage(context!, userToken: userToken!, appType: apptype!, loginType: loginType); + performBasicOtpLoginSelectionPage(context!, + userToken: userToken!, appType: apptype!, loginType: loginType); } } @@ -590,7 +666,8 @@ class UserVM extends BaseVM { } Future updateUserImage(BuildContext context) async { - File? myPick = await commanServices.pickFile(context, fileType: FileType.image); + File? myPick = + await commanServices.pickFile(context, fileType: FileType.image); if (myPick != null) { userRepo.updateUserImage(encodeBase64Image(myPick)).whenComplete(() { AppState().getUser.data!.userInfo!.userLocalImage = myPick; diff --git a/lib/views/advertisement/ad_duration_selection_sheet_content.dart b/lib/views/advertisement/ad_duration_selection_sheet_content.dart index 8904245..e5c5106 100644 --- a/lib/views/advertisement/ad_duration_selection_sheet_content.dart +++ b/lib/views/advertisement/ad_duration_selection_sheet_content.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; 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/advertisment_models/ads_duration_model.dart'; import 'package:mc_common_app/models/general_models/widgets_models.dart'; @@ -12,12 +13,16 @@ import 'package:mc_common_app/view_models/ad_view_model.dart'; import 'package:mc_common_app/widgets/button/show_fill_button.dart'; import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; import 'package:provider/provider.dart'; +import 'package:easy_localization/easy_localization.dart'; class AdDurationSelectionSheetContent extends StatelessWidget { final bool isFromExtendAd; final bool isUpdateAdSelected; - const AdDurationSelectionSheetContent({super.key, required this.isFromExtendAd, required this.isUpdateAdSelected}); + const AdDurationSelectionSheetContent( + {super.key, + required this.isFromExtendAd, + required this.isUpdateAdSelected}); @override Widget build(BuildContext context) { @@ -28,7 +33,10 @@ class AdDurationSelectionSheetContent extends StatelessWidget { children: [ Row( children: [ - "Select Duration".toText(fontSize: 22, isBold: true).paddingOnly(top: 10, left: 21, right: 21), + LocaleKeys.selectDuration + .tr() + .toText(fontSize: 22, isBold: true) + .paddingOnly(top: 10, left: 21, right: 21), ], ), Expanded( @@ -48,22 +56,32 @@ class AdDurationSelectionSheetContent extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "${adDuration.days} Days".toString().toText(fontSize: 16, isBold: true), + ("${adDuration.days}" + LocaleKeys.daysVar.tr()) + .toString() + .toText(fontSize: 16, isBold: true), 4.height, - "Your Ad will be active for ${adDuration.days} Days and then you will need to extend it to keep it active. ".toText( + "Your Ad will be active for ${adDuration.days} Days and then you will need to extend it to keep it active. " + .toText( fontSize: 14, color: MyColors.lightTextColor, ), 12.height, - "Ad Charges".toText(fontSize: 14, color: MyColors.lightTextColor, isBold: true), + LocaleKeys.adCharges.tr().toText( + fontSize: 14, + color: MyColors.lightTextColor, + isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ - "${adDuration.price}".toText(fontSize: 22, isBold: true), + "${adDuration.price}" + .toText(fontSize: 22, isBold: true), 2.width, Padding( padding: const EdgeInsets.only(bottom: 4), - child: "SAR".toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true), + child: LocaleKeys.sar.tr().toText( + fontSize: 12, + color: MyColors.lightTextColor, + isBold: true), ), ], ), @@ -74,14 +92,16 @@ class AdDurationSelectionSheetContent extends StatelessWidget { ).toWhiteContainer( width: double.infinity, allPading: 12, - isBorderRequired: adDuration.id == adVM.vehicleAdDurationId.selectedId, + isBorderRequired: + adDuration.id == adVM.vehicleAdDurationId.selectedId, ), ).onPress(() { if (isFromExtendAd) { adVM.updateVehicleExtendAdDurationId( SelectionModel( selectedId: adDuration.id ?? 0, - selectedOption: "${adDuration.days} Days", + selectedOption: + ("${adDuration.days} " + LocaleKeys.daysVar.tr()), itemPrice: adDuration.price!.toInt().toString(), ), ); @@ -90,7 +110,8 @@ class AdDurationSelectionSheetContent extends StatelessWidget { adVM.updateVehicleAdDurationId( SelectionModel( selectedId: adDuration.id ?? 0, - selectedOption: "${adDuration.days} Days", + selectedOption: + ("${adDuration.days} " + LocaleKeys.daysVar.tr()), itemPrice: adDuration.price!.toInt().toString(), ), ); @@ -103,15 +124,17 @@ class AdDurationSelectionSheetContent extends StatelessWidget { ), ), ShowFillButton( - iconWidget: adVM.isFetchingLists ? const Padding( - padding: EdgeInsets.all(8.0), - child: SizedBox( - height: 30, - width: 30, - child: CircularProgressIndicator(color: Colors.white), - ), - ) : null, - title: adVM.isFetchingLists ? "" : "Select", + iconWidget: adVM.isFetchingLists + ? const Padding( + padding: EdgeInsets.all(8.0), + child: SizedBox( + height: 30, + width: 30, + child: CircularProgressIndicator(color: Colors.white), + ), + ) + : null, + title: adVM.isFetchingLists ? "" : LocaleKeys.select.tr(), maxWidth: double.infinity, margin: const EdgeInsets.all(21), onPressed: () { @@ -119,7 +142,8 @@ class AdDurationSelectionSheetContent extends StatelessWidget { return; } else { if (isFromExtendAd && !isUpdateAdSelected) { - navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.extendAds); + navigateWithName(context, AppRoutes.paymentMethodsView, + arguments: PaymentTypes.extendAds); return; } navigateReplaceWithName(context, AppRoutes.createAdView); @@ -131,7 +155,8 @@ class AdDurationSelectionSheetContent extends StatelessWidget { ); } - Widget showItem(String item, String value, {Color valueColor = Colors.black}) { + Widget showItem(String item, String value, + {Color valueColor = Colors.black}) { return Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, diff --git a/lib/views/advertisement/ads_detail_view.dart b/lib/views/advertisement/ads_detail_view.dart index ca6f78b..4d95308 100644 --- a/lib/views/advertisement/ads_detail_view.dart +++ b/lib/views/advertisement/ads_detail_view.dart @@ -1,12 +1,10 @@ import 'dart:async'; -import 'dart:convert'; -import 'dart:developer'; - import 'package:flutter/material.dart'; import 'package:mc_common_app/classes/consts.dart'; 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/advertisment_models/ad_details_model.dart'; import 'package:mc_common_app/models/advertisment_models/ads_bank_details_model.dart'; @@ -32,6 +30,7 @@ import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart'; import 'package:mc_common_app/widgets/extensions/extensions_widget.dart'; import 'package:mc_common_app/widgets/txt_field.dart'; import 'package:provider/provider.dart'; +import 'package:easy_localization/easy_localization.dart'; class AdsDetailView extends StatefulWidget { final AdDetailsModel adDetails; @@ -62,12 +61,12 @@ class _AdsDetailViewState extends State { AdVM adVM = context.read(); return actionConfirmationBottomSheet( context: context, - title: "Do you want to delete the ad?".toText(fontSize: 28, isBold: true, letterSpacing: -1.44), - subtitle: "Your ad will be permanently deleted and you cannot undo this action.", + title: LocaleKeys.deleteAdConfirmation.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44), + subtitle: LocaleKeys.deleteAdConfirmationMessage.tr(), actionButtonYes: Expanded( child: ShowFillButton( maxHeight: 55, - title: "Yes", + title: LocaleKeys.yes.tr(), fontSize: 15, onPressed: () { Navigator.pop(context); @@ -80,7 +79,7 @@ class _AdsDetailViewState extends State { maxHeight: 55, isFilled: false, borderColor: MyColors.darkPrimaryColor, - title: "No", + title: LocaleKeys.no.tr(), txtColor: MyColors.darkPrimaryColor, fontSize: 15, onPressed: () { @@ -95,22 +94,22 @@ class _AdsDetailViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar( - title: "Ads", + title: LocaleKeys.ads.tr(), profileImageUrl: MyAssets.bnCar, isRemoveBackButton: false, isDrawerEnabled: false, actions: [ ((widget.adDetails.isMyAd ?? false) && (widget.adDetails.adPostStatus != AdPostStatus.reserved) - ? IconButton( - icon: const Icon(Icons.delete_outline, color: MyColors.redColor), - onPressed: () { - return deleteAdBottomSheet(context); - }, - ) - : IconButton( - icon: const Icon(Icons.chat_outlined, color: Colors.black), - onPressed: () {}, - )) + ? IconButton( + icon: const Icon(Icons.delete_outline, color: MyColors.redColor), + onPressed: () { + return deleteAdBottomSheet(context); + }, + ) + : IconButton( + icon: const Icon(Icons.chat_outlined, color: Colors.black), + onPressed: () {}, + )) .toContainer( margin: const EdgeInsets.fromLTRB(0, 8, 21, 8), paddingAll: 0, @@ -155,7 +154,7 @@ class _AdsDetailViewState extends State { children: [ Row( children: [ - "Model: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.model.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), "${widget.adDetails.vehicle!.modelyear!.label}".toText( fontSize: 14, isBold: true, @@ -170,7 +169,7 @@ class _AdsDetailViewState extends State { children: [ Row( children: [ - "Mileage: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.mileage.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), "${widget.adDetails.vehicle!.mileage!.mileageEnd}Km".toText( fontSize: 14, isBold: true, @@ -184,7 +183,7 @@ class _AdsDetailViewState extends State { ), Row( children: [ - "Transmission: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.transmission.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), "${widget.adDetails.vehicle!.transmission!.label}".toText( fontSize: 14, isBold: true, @@ -192,30 +191,30 @@ class _AdsDetailViewState extends State { ], ), 8.height, - "Description: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.description.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), "${widget.adDetails.vehicle!.vehicleDescription}".toText( fontSize: 14, isBold: true, ), if (widget.adDetails.isMyAd ?? false) ...[ 8.height, - "Demand: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.demand.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ widget.adDetails.vehicle!.demandAmount!.toInt().toString().toText(fontSize: 30, height: 1.2, isBold: true), - " SAR".toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5), + LocaleKeys.sar.tr().toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5), ], ), if (widget.adDetails.adPostStatus == AdPostStatus.expired) ...[ 8.height, const Divider(thickness: 1, height: 1), 8.height, - "Your Ad Duration time is over.".toText( - color: MyColors.redColor, - fontSize: 12, - isItalic: true, - ), + LocaleKeys.adDurationExpired.tr().toText( + color: MyColors.redColor, + fontSize: 12, + isItalic: true, + ), ], ] ], @@ -227,7 +226,7 @@ class _AdsDetailViewState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Bank Details".toText(fontSize: 18, isBold: true), + LocaleKeys.bankDetails.tr().toText(fontSize: 18, isBold: true), // Row( // children: [ // "Full Name: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), @@ -239,7 +238,7 @@ class _AdsDetailViewState extends State { // ), Row( children: [ - "Bank Name: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.bankName.tr() + ": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), (adVM.adsBankDetailsModel!.bankName ?? "").toText( fontSize: 14, isBold: true, @@ -248,7 +247,7 @@ class _AdsDetailViewState extends State { ), Row( children: [ - "IBAN: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + (LocaleKeys.iban.tr()+": ").toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), (adVM.adsBankDetailsModel!.iban ?? "").toText( fontSize: 14, isBold: true, @@ -270,10 +269,10 @@ class _AdsDetailViewState extends State { crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Rejection Comments".toText(fontSize: 13, isBold: true, color: MyColors.lightTextColor), + LocaleKeys.rejectionComments.tr().toText(fontSize: 13, isBold: true, color: MyColors.lightTextColor), Row( children: [ - "Edit Ad".toText(fontSize: 10, isBold: true), + LocaleKeys.editAd.tr().toText(fontSize: 10, isBold: true), 2.width, const Icon(Icons.edit, size: 15), ], @@ -312,7 +311,7 @@ class _AdsDetailViewState extends State { crossAxisAlignment: CrossAxisAlignment.end, children: [ widget.adDetails.vehicle!.demandAmount!.toInt().toString().toText(fontSize: 30, isBold: true), - " SAR".toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5), + LocaleKeys.sar.tr().toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5), ], ), 14.height, @@ -340,37 +339,37 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { enableDrag: true, builder: (BuildContext context) { return InfoBottomSheet( - title: "Reserve Ad".toText(fontSize: 24, isBold: true), + title: LocaleKeys.reserveAd.tr().toText(fontSize: 24, isBold: true), description: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Reservation Amount".toText(fontSize: 16, isBold: true), + LocaleKeys.reservationAmount.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "${adDetailsModel.reservePrice}".toText(fontSize: 19, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), ], ) ], ), const Divider(), - "Below Amount that you will pay later".toText(fontSize: 12), + LocaleKeys.belowAmountPayLater.tr().toText(fontSize: 12), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ - "Car Price".toText(fontSize: 16, isBold: true), + LocaleKeys.carPrice.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "${adDetailsModel.vehicle!.demandAmount ?? 0.0}".toText(fontSize: 19, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), ], ) ], @@ -379,48 +378,48 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end, children: [ - "VAT Excluded".toText(fontSize: 10, isBold: true), + LocaleKeys.vatExcluded.tr().toText(fontSize: 10, isBold: true), ], ), const Divider(), - "Special Services".toText(fontSize: 16, isBold: true), + LocaleKeys.specialService.toText(fontSize: 16, isBold: true), 5.height, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Car insurance Service".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor, fontWeight: FontWeight.w500), - "To be Decided".toText(fontSize: 12, isBold: true), + LocaleKeys.carInsuranceService.tr().toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor, fontWeight: FontWeight.w500), + LocaleKeys.toBeDecided.tr().toText(fontSize: 12, isBold: true), ], ), 5.height, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Registration & Car Plates".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), - "To be Decided".toText(fontSize: 12, isBold: true), + LocaleKeys.registrationCarPlates.tr().toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + LocaleKeys.toBeDecided.tr().toText(fontSize: 12, isBold: true), ], ), 5.height, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Home Delivery Service".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), - "To be Decided".toText(fontSize: 12, isBold: true), + LocaleKeys.homeDeliveryService.tr().toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + LocaleKeys.toBeDecided.tr().toText(fontSize: 12, isBold: true), ], ), 12.height, - "Special service charges will be added based on desired insurance and delivery Location".toText(fontSize: 12, maxLines: 2), + LocaleKeys.specialServicechargesInsuranceDeliveryLocation.tr().toText(fontSize: 12, maxLines: 2), 30.height, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Total Amount ".toText(fontSize: 16, isBold: true), + LocaleKeys.totalAmount.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "${(adDetailsModel.vehicle!.demandAmount ?? 0.0)}".toText(fontSize: 19, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), ], ) ], @@ -429,7 +428,7 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end, children: [ - "Estimated".toText(fontSize: 10, isBold: true), + LocaleKeys.estimated.tr().toText(fontSize: 10, isBold: true), ], ), 30.height, @@ -442,7 +441,7 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { size: 19, ).paddingOnly(bottom: 2), 3.width, - "Some services are mandatory while reserving Ad.".toText( + LocaleKeys.servicesReservingAd.tr().toText( color: MyColors.adPendingStatusColor, fontSize: 12, isItalic: true, @@ -455,7 +454,7 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { Expanded( child: ShowFillButton( maxHeight: 55, - title: "Complete Reservation", + title: LocaleKeys.completeReservation.tr(), onPressed: () async { // Navigator.pop(context); bool status = await context.read().createReserveAd(adId: adDetailsModel.id!, context: context); @@ -479,7 +478,7 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { Expanded( child: ShowFillButton( maxHeight: 55, - title: "Reserve Ad", + title: LocaleKeys.reserveAd.tr(), onPressed: () { reserveAdPriceBreakDownClicked(context, adDetailsModel); // navigateWithName(context, AppRoutes.paymentMethodsView); @@ -519,36 +518,36 @@ class BuildAdDetailsActionButtonForExploreAds extends StatelessWidget { Widget defaultActionForProviderAndCustomer(BuildContext context, AdDetailsModel adDetailsModel) { return (adDetailsModel.phoneNo == null) ? Row( - children: [ - Expanded( - child: ShowFillButton( - maxHeight: 55, - title: "Contact", - fontSize: 18, - isBold: false, - iconWidget: const Padding( - padding: EdgeInsets.only(right: 10), - child: Icon(Icons.phone, color: MyColors.white, size: 24), - ), - onPressed: () { - Utils.openNumberViaCaller(phoneNumber: adDetailsModel.phoneNo ?? ""); - }, - ), - ), - if (adDetailsModel.whatsAppNo == null) ...[ - 8.width, - Container( - height: 55, - width: 55, - alignment: Alignment.center, - decoration: BoxDecoration(border: Border.all(color: MyColors.black, width: 2)), - child: MyAssets.whatsAppIcon.buildSvg(height: 33, width: 35)) - .onPress(() { - Utils.openNumberViaWhatsApp(phoneNumber: adDetailsModel.whatsAppNo ?? ""); - }), - ], - ], - ) + children: [ + Expanded( + child: ShowFillButton( + maxHeight: 55, + title: LocaleKeys.contact.tr(), + fontSize: 18, + isBold: false, + iconWidget: const Padding( + padding: EdgeInsets.only(right: 10), + child: Icon(Icons.phone, color: MyColors.white, size: 24), + ), + onPressed: () { + Utils.openNumberViaCaller(phoneNumber: adDetailsModel.phoneNo ?? ""); + }, + ), + ), + if (adDetailsModel.whatsAppNo == null) ...[ + 8.width, + Container( + height: 55, + width: 55, + alignment: Alignment.center, + decoration: BoxDecoration(border: Border.all(color: MyColors.black, width: 2)), + child: MyAssets.whatsAppIcon.buildSvg(height: 33, width: 35)) + .onPress(() { + Utils.openNumberViaWhatsApp(phoneNumber: adDetailsModel.whatsAppNo ?? ""); + }), + ], + ], + ) : const SizedBox.shrink(); } @@ -584,7 +583,7 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { builder: (BuildContext context) { return Consumer(builder: (BuildContext context, AdVM adVM, Widget? child) { return InfoBottomSheet( - title: "Set Date and Time".toText(fontSize: 16, isBold: true, letterSpacing: -1.44, height: 1.2), + title: LocaleKeys.setDateandTime.tr().toText(fontSize: 16, isBold: true, letterSpacing: -1.44, height: 1.2), description: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -592,23 +591,23 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { adVM.state == ViewState.busy ? const Center(child: CircularProgressIndicator()) : Builder( - builder: (context) { - List vehicleCitiesDrop = []; - for (int i = 0; i < adVM.photoSSSchedulesByOffices.length; i++) { - var element = adVM.photoSSSchedulesByOffices[i]; - vehicleCitiesDrop.add(DropValue(element.photoOfficeID?.toInt() ?? 0, element.photoOfficeName ?? "", i.toString())); - } + builder: (context) { + List vehicleCitiesDrop = []; + for (int i = 0; i < adVM.photoSSSchedulesByOffices.length; i++) { + var element = adVM.photoSSSchedulesByOffices[i]; + vehicleCitiesDrop.add(DropValue(element.photoOfficeID?.toInt() ?? 0, element.photoOfficeName ?? "", i.toString())); + } - return DropdownField( - (DropValue value) => adVM.updatePhotoOfficeSelectedId(SelectionModel(selectedId: value.id, selectedOption: value.value, itemPrice: value.subValue)), - // here the item price is the index of the selected option - list: vehicleCitiesDrop, - dropdownValue: adVM.photoOfficeSelectedId.selectedId != -1 ? DropValue(adVM.photoOfficeSelectedId.selectedId, adVM.photoOfficeSelectedId.selectedOption, "") : null, - hint: "Select Office", - errorValue: adVM.photoOfficeSelectedId.errorValue, - ); - }, - ), + return DropdownField( + (DropValue value) => adVM.updatePhotoOfficeSelectedId(SelectionModel(selectedId: value.id, selectedOption: value.value, itemPrice: value.subValue)), + // here the item price is the index of the selected option + list: vehicleCitiesDrop, + dropdownValue: adVM.photoOfficeSelectedId.selectedId != -1 ? DropValue(adVM.photoOfficeSelectedId.selectedId, adVM.photoOfficeSelectedId.selectedOption, "") : null, + hint: LocaleKeys.selectOffice.tr(), + errorValue: adVM.photoOfficeSelectedId.errorValue, + ); + }, + ), if (adVM.photoOfficeSelectedId.selectedId != -1) ...[ 9.height, CustomCalenderAppointmentWidget( @@ -621,7 +620,7 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - ("Available Slots").toText(fontSize: 14, isBold: true), + LocaleKeys.availableSlots.tr().toText(fontSize: 14, isBold: true), ], ), 5.height, @@ -640,7 +639,7 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { Expanded( child: ShowFillButton( maxHeight: 55, - title: "Book and Pay", + title: LocaleKeys.bookAndPay.tr(), fontSize: 15, onPressed: () { adVM.onAdSSBookAppointmentPressed(context, adDetailsModel: adDetailsModel, adsSpecialServiceID: 1); //1 for photography Service @@ -665,37 +664,37 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { enableDrag: true, builder: (BuildContext context) { return InfoBottomSheet( - title: "Reserve Ad".toText(fontSize: 24, isBold: true), + title: LocaleKeys.reserveAd.tr().toText(fontSize: 24, isBold: true), description: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Reservation Amounts".toText(fontSize: 16, isBold: true), + LocaleKeys.reservationAmounts.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "500".toText(fontSize: 19, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), ], ) ], ), const Divider(), - "Below Amount that you will pay later".toText(fontSize: 12), + LocaleKeys.belowAmountPayLater.tr().toText(fontSize: 12), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ - "Car Price".toText(fontSize: 16, isBold: true), + LocaleKeys.carPrice.tr().toText(fontSize: 16, isBold: true), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "30,000".toText(fontSize: 19, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 3), ], ) ], @@ -703,13 +702,13 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Tax".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), + LocaleKeys.tax.tr().toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ "4,500".toText(fontSize: 16, isBold: true), 2.width, - "SAR".toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 0), + LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, isBold: true).paddingOnly(bottom: 0), ], ) ], @@ -953,10 +952,7 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { return InfoBottomSheet( title: "Cancel Reservation".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: Consumer( builder: (BuildContext context, AdVM adVM, Widget? child) { return Column( @@ -1072,10 +1068,7 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { return InfoBottomSheet( title: "Upload Bank Receipt".toText(fontSize: 26, 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: Consumer( builder: (BuildContext context, AdVM adVM, Widget? child) { return Column( @@ -1107,28 +1100,27 @@ class BuildAdDetailsActionButtonForMyAds extends StatelessWidget { }, isPdf: true, ), - ] else - ...[ - Row( - children: [ - Container( - height: 90, - width: 90, - decoration: BoxDecoration(color: MyColors.greyButtonColor, border: Border.all(width: 2, color: MyColors.greyAddBorderColor)), - margin: const EdgeInsets.all(8), - alignment: Alignment.center, - child: Container( - height: 24, - width: 24, - decoration: const BoxDecoration(shape: BoxShape.circle, color: MyColors.darkTextColor), - child: const Icon(Icons.add, color: MyColors.white), - ), - ).onPress(() { - context.read().pickPdfReceiptFile(context); - }), - ], - ), - ], + ] else ...[ + Row( + children: [ + Container( + height: 90, + width: 90, + decoration: BoxDecoration(color: MyColors.greyButtonColor, border: Border.all(width: 2, color: MyColors.greyAddBorderColor)), + margin: const EdgeInsets.all(8), + alignment: Alignment.center, + child: Container( + height: 24, + width: 24, + decoration: const BoxDecoration(shape: BoxShape.circle, color: MyColors.darkTextColor), + child: const Icon(Icons.add, color: MyColors.white), + ), + ).onPress(() { + context.read().pickPdfReceiptFile(context); + }), + ], + ), + ], 15.height, ShowFillButton( title: "Submit",