diff --git a/assets/images/svg/ai_overview.svg b/assets/images/svg/ai_overview.svg new file mode 100644 index 0000000..95c29aa --- /dev/null +++ b/assets/images/svg/ai_overview.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/svg/calculator_icon.svg b/assets/images/svg/calculator_icon.svg new file mode 100644 index 0000000..989a4db --- /dev/null +++ b/assets/images/svg/calculator_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/guard_icon.svg b/assets/images/svg/guard_icon.svg new file mode 100644 index 0000000..e3a68d9 --- /dev/null +++ b/assets/images/svg/guard_icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/high_caution.svg b/assets/images/svg/high_caution.svg new file mode 100644 index 0000000..d268468 --- /dev/null +++ b/assets/images/svg/high_caution.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/information-circle.svg b/assets/images/svg/information-circle.svg new file mode 100644 index 0000000..f1a850e --- /dev/null +++ b/assets/images/svg/information-circle.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index 178b4c0..3df6041 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -1526,8 +1526,48 @@ "trackerAndOthers": "المتتبع وأخرى", "bmi": "مؤشر كتلة الجسم", "yesPleaseINeedHelp": "نعم، من فضلك أريد المساعدة", - "noThanksIKnowTheClinic": "لا شكراً، أعرف العيادة" - "unableToSendOTP": "تعذر إرسال رمز التحقق لمرة واحدة" + "noThanksIKnowTheClinic": "لا شكراً، أعرف العيادة", + "unableToSendOTP": "تعذر إرسال رمز التحقق لمرة واحدة", + "aiOverView": "AI ملخص", + "generateAiAnalysis": "قم بإجراء تحليل لهذا الطلب AI", + "aiAnalysis": "AI تحليل", + "prediction": "تنبؤ", + "prevention": "وقاية", + "disclaimer": "تنصل", + "thisAboveInfo": "المعلومات المذكورة أعلاه تم إنشاؤها بواسطة AI", + "aiDisclaimer": "سيتم مشاركة بيانات نتائج تحاليلك المخبرية بشكل آمن مع خدمة الذكاء الاصطناعي لدينا لتحليلها. يساعد هذا في تقديم رؤى صحية مُخصصة. هل ترغب في المتابعة؟", + "consent": "موافقة", + "bmiNormalDescription": "مؤشر كتلة جسمك ضمن المعدل الصحي. استمر في اتباع نظام غذائي متوازن، وممارسة النشاط البدني بانتظام، وإجراء الفحوصات الدورية للحفاظ على صحة جيدة. راقب أي تغييرات ملحوظة مع مرور الوقت.", + "bmiUnderweightDescription": "يشير مؤشر كتلة الجسم إلى أنك تعاني من نقص الوزن. لذا، يُنصح بزيادة السعرات الحرارية المتناولة من خلال تناول الأطعمة الغنية بالعناصر الغذائية، وممارسة تمارين المقاومة لبناء العضلات، واستشارة أخصائي رعاية صحية للتحقق من وجود أسباب كامنة.", + "bmiOverweightDescription": "يشير مؤشر كتلة الجسم إلى زيادة الوزن. لذا، يُنصح بالسعي إلى إنقاص الوزن تدريجياً وبشكل مستدام من خلال تقليل السعرات الحرارية بشكل معتدل، وممارسة النشاط البدني بانتظام، واختيار الأطعمة الصحية. استشر طبيبك قبل إجراء أي تغييرات جذرية في نمط حياتك.", + "caloriesMaintenanceDescription": "السعرات الحرارية اليومية المُقدَّرة للحفاظ على وزنك الحالي بناءً على مستوى نشاطك ومعدل الأيض لديك. استخدم هذه الكمية كخط أساس: زدها قليلاً لزيادة الكتلة العضلية، أو قللها قليلاً لإنقاص الوزن تدريجياً. تابع تقدمك وعدّل الخطة كل أسبوعين إلى أربعة أسابيع.", + "caloriesModerateDeficitDescription": "نظام غذائي معتدل لتقليل السعرات الحرارية مصمم لإنقاص الوزن بشكل ثابت ومستدام (عادةً من 0.25 إلى 0.5 كيلوغرام أسبوعيًا). يُنصح بدمجه مع تمارين المقاومة وتناول كمية كافية من البروتين للحفاظ على الكتلة العضلية. تجنب التخفيضات الحادة في السعرات الحرارية واستشر طبيبًا مختصًا إذا كنت تعاني من أي حالة صحية.", + "caloriesAggressiveDeficitDescription": "يؤدي خفض السعرات الحرارية بشكل كبير إلى فقدان الوزن بشكل أسرع، ولكنه قد يصعب الاستمرار عليه ويزيد من خطر نقص العناصر الغذائية والإرهاق وفقدان الكتلة العضلية. لا يُنصح باتباعه على المدى الطويل؛ استشر طبيبًا أو أخصائي تغذية قبل الاستمرار.", + "bodyFatEssentialDescription": "نسبة الدهون في جسمك ضمن النطاق الأساسي/الرياضي. هذا المستوى شائع لدى الرياضيين ويشير إلى انخفاض نسبة الدهون في الجسم. مع أن هذا قد يكون مثاليًا للأداء، تأكد من الحفاظ على تغذية سليمة ووظائف هرمونية متوازنة. استشر طبيبًا إذا شعرت بالتعب، أو واجهت مشاكل هرمونية، أو أي مخاوف صحية أخرى.", + "bodyFatFitnessDescription": "نسبة الدهون في جسمك ضمن النطاق الصحي. وهذا يدل على مستوى صحي من الدهون في الجسم يرتبط بلياقة بدنية جيدة. حافظ على نمط حياتك الحالي، بما في ذلك ممارسة الرياضة بانتظام واتباع نظام غذائي متوازن، للحفاظ على هذا المستوى الصحي.", + "bodyFatAverageDescription": "نسبة الدهون في جسمك ضمن المعدل الطبيعي/المقبول، وهي نسبة تُعتبر صحية لعموم الناس. لتحسين تكوين جسمك، يُنصح بممارسة تمارين القوة، وتمارين القلب والأوعية الدموية، واتباع نظام غذائي متوازن. ركّز على التغييرات التدريجية والمستدامة للحفاظ على صحتك على المدى الطويل.", + "bodyFatObeseDescription": "نسبة الدهون في جسمك أعلى من المعدل الصحي الموصى به. قد يزيد هذا من المخاطر الصحية، بما في ذلك أمراض القلب والأوعية الدموية، والسكري، ومشاكل المفاصل. يُنصح باستشارة طبيب أو أخصائي تغذية معتمد لوضع خطة علاجية شخصية تشمل التغذية المتوازنة، والنشاط البدني المنتظم، وتعديلات نمط الحياة لتحقيق إدارة مستدامة للوزن.", + "bmrNormalDescription": "معدل الأيض الأساسي لديك ضمن النطاق المتوقع لحالتك. معدل الأيض الأساسي هو الطاقة التي يحتاجها جسمك في حالة الراحة للحفاظ على وظائفه الحيوية (التنفس، الدورة الدموية، درجة الحرارة). استخدم هذه القيمة كأساس لتقدير إجمالي احتياجاتك اليومية من الطاقة من خلال تطبيق مُعامل النشاط. حافظ على نظام غذائي متوازن وممارسة النشاط البدني بانتظام لدعم صحة التمثيل الغذائي.", + "bmrLowDescription": "معدل الأيض الأساسي لديك أقل من المعدل الطبيعي لحالتك. تشمل الأسباب المحتملة انخفاض كتلة العضلات، أو تراجع التمثيل الغذائي المرتبط بالتقدم في السن، أو التكيف الأيضي الناتج عن تقييد السعرات الحرارية لفترة طويلة. يُنصح بالتركيز على تمارين المقاومة لبناء العضلات والحفاظ عليها، والتأكد من تناول كميات كافية من البروتين والمغذيات الدقيقة، واستشارة أخصائي رعاية صحية إذا كان هذا الأمر غير متوقع.", + "bmrHighDescription": "معدل الأيض الأساسي لديك أعلى من المتوسط \u200B\u200Bبالنسبة لحالتك. قد يعكس هذا زيادة في كتلة العضلات، أو صغر السن، أو ارتفاع معدل الأيض لديك بشكل طبيعي، مما يعني أنك تحرق طاقة أكبر أثناء الراحة. استخدم هذه المعلومات لتحديد احتياجاتك من السعرات الحرارية: احتياجات أعلى للحفاظ على الوزن أو بناء العضلات، ونقص معتدل في السعرات الحرارية لإنقاص الوزن. استشر طبيبك إذا لاحظت أي تغيرات سريعة غير مبررة.", + "ibwAtTargetDescription": "Your weight is at the ideal target. Maintain your current habits — balanced diet and regular activity — to keep this.", + "ibwBelowTargetDescription": "You are below the ideal weight by {kg} kg. Aim to gradually increase weight with a modest calorie surplus, nutrient-dense foods, and resistance training.", + "ibwAboveTargetDescription": "You are above the ideal weight by {kg} kg. Aim for a gradual, sustainable weight reduction through a moderate calorie deficit, increased activity, and balanced nutrition.", + "ibwCloseToRangeDescription": "Your weight is close to the ideal range. Maintain a balanced diet and regular activity; follow personalized advice from a healthcare professional if needed.", + "ibwUnderweightDescription": "You are below the ideal weight by {kg} kg. Focus on increasing calorie intake with nutrient-dense foods, prioritize protein and resistance training to build healthy mass, and consider consulting a healthcare professional.", + "ibwUnderweightGenericDescription": "You appear underweight compared to the ideal. Consider increasing calorie intake with nutrient-dense foods and resistance training; seek professional guidance if needed.", + "ibwOverweightDescription": "You are above the ideal weight by {kg} kg. Aim for a gradual, sustainable weight loss strategy — moderate calorie deficit, regular physical activity, and balanced nutrition. Consult a professional before major changes.", + "ibwOverweightGenericDescription": "You appear above the ideal weight. Consider a gradual, sustainable calorie deficit combined with activity and balanced nutrition; consult a professional if needed.", + "dietVeryLowCarbsDescription": "Very low‑carb (ketogenic) approach: minimal carbohydrates, higher fat and moderate protein. May support rapid weight loss and improved blood sugar control for some, but can be hard to sustain and may cause nutrient gaps. Monitor hydration/electrolytes and consult a professional for long‑term use.", + "dietLowCarbsDescription": "Low‑carb, higher‑protein plan: reduced carbohydrates with increased protein to support satiety and muscle maintenance. Helpful for weight management and glycemic control when balanced with vegetables and healthy fats. Ensure adequate fiber and micronutrients.", + "dietModerateCarbsDescription": "Moderate carbohydrate intake with balanced protein and fats: provides steady energy for daily activity and exercise while allowing flexibility. Suitable for many people aiming for sustainable weight management and performance.", + "dietUSDAGuidelinesDescription": "USDA‑based balanced pattern: emphasizes fruits, vegetables, whole grains, lean proteins, and limited added sugars and saturated fats. Evidence‑based framework for general health, nutrient adequacy, and chronic disease prevention.", + "dietZoneDietDescription": "Zone Diet (~40% carbs / 30% protein / 30% fat): emphasizes hormonal balance and portion control. May improve body composition and energy for some, but requires planning; personalize with a nutrition professional.", + "contextDependent": "يعتمد السياق", + "calculatedValue": "القيمة المحسوبة", + "calculationFormula": "صيغة الحساب" + + } diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index d6f5228..7799807 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -1517,8 +1517,46 @@ "trackerAndOthers": "Tracker & Others", "bmi": "BMI", "yesPleaseINeedHelp": "Yes, Please I need help", - "noThanksIKnowTheClinic": "No, Thanks. I Know the clinic" - "unableToSendOTP": "Unable to send Verification OTP" + "noThanksIKnowTheClinic": "No, Thanks. I Know the clinic", + "unableToSendOTP": "Unable to send Verification OTP", + "aiOverView": "AI Overview", + "generateAiAnalysis": "Generate AI analysis for this order", + "aiAnalysis": "AI Analysis", + "prediction": "Prediction", + "prevention": "Prevention", + "disclaimer": "Disclaimer", + "thisAboveInfo": "The above information is generated by", + "aiDisclaimer": "Your lab result data will be securely shared with our AI service for analysis. This helps provide personalized health insights. Do you want to proceed?", + "consent": "Consent", + "bmiNormalDescription": "Your BMI is within the healthy range. Continue a balanced diet, regular physical activity, and routine checkups to maintain good health. Monitor any significant changes over time.", + "bmiUnderweightDescription": "BMI suggests you are underweight. Consider increasing calorie intake with nutrient-dense foods, include resistance training to build muscle, and consult a healthcare professional to check for underlying causes.", + "bmiOverweightDescription": "BMI indicates overweight. Aim for gradual, sustainable weight loss through a modest calorie deficit, regular physical activity, and healthier food choices. Seek medical advice before major lifestyle changes.", + "caloriesMaintenanceDescription": "Estimated daily calories to maintain your current weight given your activity level and metabolism. Use this as a baseline: increase slightly for muscle gain, or create a small deficit for gradual weight loss. Track progress and adjust every 2–4 weeks.", + "caloriesModerateDeficitDescription": "A moderate calorie reduction designed for steady, sustainable weight loss (typically 0.25–0.5 kg per week). Combine with resistance training and adequate protein to preserve muscle. Avoid extreme cuts and consult a professional if you have medical conditions.", + "caloriesAggressiveDeficitDescription": "A large calorie reduction that may produce faster weight loss but can be hard to sustain and increase risk of nutrient deficiencies, fatigue, or muscle loss. Not recommended long-term; seek guidance from a healthcare or nutrition professional before continuing.", + "bodyFatEssentialDescription": "Your body fat percentage is in the essential/athletic range. This level is typical for athletes and indicates very low body fat. While this may be optimal for performance, ensure you maintain adequate nutrition and hormone function. Consult a healthcare professional if you experience fatigue, hormonal issues, or other health concerns.", + "bodyFatFitnessDescription": "Your body fat percentage is in the fitness range. This indicates a healthy level of body fat associated with good physical conditioning. Maintain your current lifestyle habits including regular exercise and balanced nutrition to sustain this healthy range.", + "bodyFatAverageDescription": "Your body fat percentage is in the average/acceptable range. This is considered a healthy range for general population. To improve body composition, consider incorporating strength training, cardiovascular exercise, and a balanced diet. Focus on gradual, sustainable changes for long-term health.", + "bodyFatObeseDescription": "Your body fat percentage is above the recommended healthy range. This may increase health risks including cardiovascular disease, diabetes, and joint problems. Consider consulting a healthcare provider or registered dietitian to develop a personalized plan that includes balanced nutrition, regular physical activity, and lifestyle modifications for sustainable weight management.", + "bmrNormalDescription": "Your Basal Metabolic Rate (BMR) is within the expected range for your profile. BMR is the energy your body needs at rest to maintain vital functions (breathing, circulation, temperature). Use this value as the baseline for estimating total daily energy needs by applying an activity multiplier. Maintain a balanced diet and regular physical activity to support metabolic health.", + "bmrLowDescription": "Your BMR is lower than typical for your profile. Possible causes include lower lean muscle mass, age-related metabolic decline, or metabolic adaptation from prolonged calorie restriction. Consider focusing on resistance training to build/maintain muscle, ensure adequate protein and micronutrient intake, and consult a healthcare professional if this is unexpected.", + "bmrHighDescription": "Your BMR is higher than average for your profile. This can reflect greater lean mass, younger age, or a naturally higher metabolic rate, meaning you burn more energy at rest. Use this information to tailor calorie targets: higher needs for maintenance or muscle gain, moderate deficit for weight loss. Seek medical advice if you notice rapid unexplained changes.", + "ibwAtTargetDescription": "Your weight is at the ideal target. Maintain your current habits — balanced diet and regular activity — to keep this.", + "ibwBelowTargetDescription": "You are below the ideal weight by {kg} kg. Aim to gradually increase weight with a modest calorie surplus, nutrient-dense foods, and resistance training.", + "ibwAboveTargetDescription": "You are above the ideal weight by {kg} kg. Aim for a gradual, sustainable weight reduction through a moderate calorie deficit, increased activity, and balanced nutrition.", + "ibwCloseToRangeDescription": "Your weight is close to the ideal range. Maintain a balanced diet and regular activity; follow personalized advice from a healthcare professional if needed.", + "ibwUnderweightDescription": "You are below the ideal weight by {kg} kg. Focus on increasing calorie intake with nutrient-dense foods, prioritize protein and resistance training to build healthy mass, and consider consulting a healthcare professional.", + "ibwUnderweightGenericDescription": "You appear underweight compared to the ideal. Consider increasing calorie intake with nutrient-dense foods and resistance training; seek professional guidance if needed.", + "ibwOverweightDescription": "You are above the ideal weight by {kg} kg. Aim for a gradual, sustainable weight loss strategy — moderate calorie deficit, regular physical activity, and balanced nutrition. Consult a professional before major changes.", + "ibwOverweightGenericDescription": "You appear above the ideal weight. Consider a gradual, sustainable calorie deficit combined with activity and balanced nutrition; consult a professional if needed.", + "dietVeryLowCarbsDescription": "Very low‑carb (ketogenic) approach: minimal carbohydrates, higher fat and moderate protein. May support rapid weight loss and improved blood sugar control for some, but can be hard to sustain and may cause nutrient gaps. Monitor hydration/electrolytes and consult a professional for long‑term use.", + "dietLowCarbsDescription": "Low‑carb, higher‑protein plan: reduced carbohydrates with increased protein to support satiety and muscle maintenance. Helpful for weight management and glycemic control when balanced with vegetables and healthy fats. Ensure adequate fiber and micronutrients.", + "dietModerateCarbsDescription": "Moderate carbohydrate intake with balanced protein and fats: provides steady energy for daily activity and exercise while allowing flexibility. Suitable for many people aiming for sustainable weight management and performance.", + "dietUSDAGuidelinesDescription": "USDA‑based balanced pattern: emphasizes fruits, vegetables, whole grains, lean proteins, and limited added sugars and saturated fats. Evidence‑based framework for general health, nutrient adequacy, and chronic disease prevention.", + "dietZoneDietDescription": "Zone Diet (~40% carbs / 30% protein / 30% fat): emphasizes hormonal balance and portion control. May improve body composition and energy for some, but requires planning; personalize with a nutrition professional.", + "contextDependent": "Context Dependent", + "calculatedValue": "Calculated Value", + "calculationFormula": "Calculation Formula" diff --git a/lib/core/api_consts.dart b/lib/core/api_consts.dart index 8319c9d..e71629d 100644 --- a/lib/core/api_consts.dart +++ b/lib/core/api_consts.dart @@ -901,6 +901,8 @@ class ApiConsts { static String getPatientBloodGroup = "services/PatientVarification.svc/REST/BloodDonation_GetBloodGroupDetails"; static String getPatientBloodAgreement = "Services/PatientVarification.svc/REST/CheckUserAgreementForBloodDonation"; + static String getAiOverViewLabOrders = "Services/Patients.svc/REST/HMGAI_Lab_Analyze_Orders_API"; + static String getAiOverViewLabOrder = "Services/Patients.svc/REST/HMGAI_Lab_Analyzer_API"; // ************ static values for Api **************** static final double appVersionID = 50.3; diff --git a/lib/core/app_assets.dart b/lib/core/app_assets.dart index 5b8d2ed..d9d7120 100644 --- a/lib/core/app_assets.dart +++ b/lib/core/app_assets.dart @@ -251,6 +251,10 @@ class AppAssets { static const String alertSquare = '$svgBasePath/alert-square.svg'; static const String arrowRight = '$svgBasePath/arrow-right.svg'; static const String tickIcon = '$svgBasePath/tick.svg'; + static const String guradIcon = '$svgBasePath/guard_icon.svg'; + static const String calculatorIcon = '$svgBasePath/calculator_icon.svg'; + static const String informationIcon = '$svgBasePath/information-circle.svg'; + static const String highCautionIcon = '$svgBasePath/high_caution.svg'; // Symptoms Checker static const String calendarGrey = '$svgBasePath/calendar-grey.svg'; @@ -322,6 +326,7 @@ class AppAssets { static const String doctorResponseIcon = '$svgBasePath/doctor_response_icon.svg'; static const String changeLanguageHomePageIcon = '$svgBasePath/change_language_home_page.svg'; + static const String aiOverView = '$svgBasePath/ai_overview.svg'; // PNGS // static const String hmgLogo = '$pngBasePath/hmg_logo.png'; diff --git a/lib/features/authentication/authentication_view_model.dart b/lib/features/authentication/authentication_view_model.dart index 8206160..e93c246 100644 --- a/lib/features/authentication/authentication_view_model.dart +++ b/lib/features/authentication/authentication_view_model.dart @@ -279,9 +279,10 @@ class AuthenticationViewModel extends ChangeNotifier { loginTypeEnum = otpTypeEnum == OTPTypeEnum.sms ? LoginTypeEnum.sms : LoginTypeEnum.whatsapp; - if (phoneNumberController.text.isEmpty) { - phoneNumberController.text = "504278212"; - } + // if (phoneNumberController.text.isEmpty) { + // phoneNumberController.text = "504278212"; + // } + bool isValidated = ValidationUtils.isValidatePhoneAndId(phoneNumber: phoneNumberController.text, nationalId: nationalIdController.text); if (!isValidated) { @@ -404,7 +405,6 @@ class AuthenticationViewModel extends ChangeNotifier { return; } patientShareRequestID = apiResponse.data['PatientShareRequestID']; - print("PatientShareRequestID ==============: $patientShareRequestID"); _appState.setFamilyFileTokenID = apiResponse.data['LogInTokenID']; } if (apiResponse.messageStatus == 2) { @@ -581,7 +581,8 @@ class AuthenticationViewModel extends ChangeNotifier { if (!_appState.getIsChildLoggedIn) { await medicalVm.getFamilyFiles(status: 0); // await medicalVm.getAllPendingRecordsByResponseId(); - _navigationService.replaceAllRoutesAndNavigateToLanding(); + _navigationService.popUntilNamed(AppRoutes.landingScreen); + // _navigationService.replaceAllRoutesAndNavigateToLanding(); } } else { if (activation.list != null && activation.list!.isNotEmpty) { diff --git a/lib/features/lab/lab_repo.dart b/lib/features/lab/lab_repo.dart index e661157..a4cdcf1 100644 --- a/lib/features/lab/lab_repo.dart +++ b/lib/features/lab/lab_repo.dart @@ -5,6 +5,8 @@ import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; import 'package:dartz/dartz.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_special_result.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; @@ -13,6 +15,7 @@ import 'models/resp_models/lab_result.dart' show LabResult; abstract class LabRepo { Future>>> getPatientLabOrders(); + Future>>> getPatientLabResults(PatientLabOrdersResponseModel laborder, bool isVidaPlus, String procedureName); Future>>> getPatientLabResultsByHospitals(PatientLabOrdersResponseModel laborder, bool isVidaPlus); @@ -22,6 +25,10 @@ abstract class LabRepo { Future>> getLabResultReportPDF({required PatientLabOrdersResponseModel labOrder}); Future>> getLabResultsByAppointmentNo({required num appointmentNo, required num projectID, required num clinicID}); + + Future>> getPatientAiOverViewLabOrders(var payload); + + Future>> getPatientAiOverViewLabOrder(var payload); } class LabRepoImp implements LabRepo { @@ -71,10 +78,7 @@ class LabRepoImp implements LabRepo { } @override - Future>>> getPatientLabResults( - PatientLabOrdersResponseModel laborder, bool isVidaPlus, String procedureName - ) async { - + Future>>> getPatientLabResults(PatientLabOrdersResponseModel laborder, bool isVidaPlus, String procedureName) async { Map request = Map(); request['InvoiceNo_VP'] = isVidaPlus ? laborder!.invoiceNo : "0"; request['InvoiceNo'] = isVidaPlus ? "0" : laborder!.invoiceNo; @@ -100,10 +104,7 @@ class LabRepoImp implements LabRepo { throw Exception("lab list is empty"); } - final labOrders = list - .map((item) => LabResult.fromJson(item as Map)) - .toList() - .cast(); + final labOrders = list.map((item) => LabResult.fromJson(item as Map)).toList().cast(); apiResponse = GenericApiModel>( messageStatus: messageStatus, @@ -125,9 +126,7 @@ class LabRepoImp implements LabRepo { } @override - Future>>> - getPatientLabResultsByHospitals( - PatientLabOrdersResponseModel laborder, bool isVidaPlus) async { + Future>>> getPatientLabResultsByHospitals(PatientLabOrdersResponseModel laborder, bool isVidaPlus) async { Map request = Map(); request['InvoiceNo_VP'] = isVidaPlus ? laborder!.invoiceNo : "0"; request['InvoiceNo'] = isVidaPlus ? "0" : laborder!.invoiceNo; @@ -175,9 +174,7 @@ class LabRepoImp implements LabRepo { } @override - Future>>> - getSpecialLabResult( - PatientLabOrdersResponseModel laborder, bool isVidaPlus) async { + Future>>> getSpecialLabResult(PatientLabOrdersResponseModel laborder, bool isVidaPlus) async { Map request = Map(); request['InvoiceNo_VP'] = isVidaPlus ? laborder!.invoiceNo : "0"; request['InvoiceNo'] = isVidaPlus ? "0" : laborder!.invoiceNo; @@ -203,11 +200,7 @@ class LabRepoImp implements LabRepo { throw Exception("lab list is empty"); } - final labOrders = list - .map((item) => PatientLabSpecialResult.fromJson( - item as Map)) - .toList() - .cast(); + final labOrders = list.map((item) => PatientLabSpecialResult.fromJson(item as Map)).toList().cast(); apiResponse = GenericApiModel>( messageStatus: messageStatus, @@ -318,4 +311,76 @@ class LabRepoImp implements LabRepo { return Left(UnknownFailure(e.toString())); } } + + @override + Future>> getPatientAiOverViewLabOrder(var labOrder) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getAiOverViewLabOrder, + body: labOrder, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + var res; + if (response["analysis_result"] != null) { + res = response["analysis_result"]; + } + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: LabOrderResponseByAi.fromJson(res), + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getPatientAiOverViewLabOrders(var labOrder) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getAiOverViewLabOrders, + body: {"lab_results": labOrder}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + var res; + if (response["lab_analysis_result"] != null) { + res = response["lab_analysis_result"]; + } + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: LabOrdersResponseByAi.fromJson(res), + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } } diff --git a/lib/features/lab/lab_view_model.dart b/lib/features/lab/lab_view_model.dart index 118c54a0..9b4e941 100644 --- a/lib/features/lab/lab_view_model.dart +++ b/lib/features/lab/lab_view_model.dart @@ -1,16 +1,24 @@ import 'dart:collection'; +import 'dart:convert'; import 'dart:core'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/common_models/data_points.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/loading_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart' show Utils; import 'package:hmg_patient_app_new/features/lab/lab_repo.dart'; +import 'package:hmg_patient_app_new/features/lab/models/ai_overview_labresult_model_payload.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/lab_result.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_results/lab_result_details.dart'; +import 'package:hmg_patient_app_new/presentation/labAiAnalysis/lab_ai_analysis_detailed_page.dart'; +import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -53,20 +61,7 @@ class LabViewModel extends ChangeNotifier { List mainLabResults = []; List mainGraphPoints = []; List filteredGraphValues = []; - List months = [ - 'Jan', - 'Feb', - 'Mar', - 'April', - 'May', - 'Jun', - 'July', - 'Aug', - 'Sep', - 'Oct', - 'Nov', - 'Dec' - ]; + List months = ['Jan', 'Feb', 'Mar', 'April', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; late List _labSuggestionsList = []; @@ -86,22 +81,22 @@ class LabViewModel extends ChangeNotifier { List> patientLabOrdersByHospital = []; List> patientLabOrdersViewList = []; - LabViewModel( - {required this.labRepo, - required this.errorHandlerService, - required this.navigationService}); + LabOrderResponseByAi? labOrderResponseByAi; + LabOrdersResponseByAi? labOrdersResponseByAi; + + LabViewModel({required this.labRepo, required this.errorHandlerService, required this.navigationService}); initLabProvider() { // if (isLabNeedToLoad) { - patientLabOrders.clear(); - filteredLabOrders.clear(); - labOrderTests.clear(); - isLabOrdersLoading = true; - isLabResultsLoading = true; - patientLabOrdersByClinic.clear(); - patientLabOrdersByHospital.clear(); - patientLabOrdersViewList.clear(); - getPatientLabOrders(); + patientLabOrders.clear(); + filteredLabOrders.clear(); + labOrderTests.clear(); + isLabOrdersLoading = true; + isLabResultsLoading = true; + patientLabOrdersByClinic.clear(); + patientLabOrdersByHospital.clear(); + patientLabOrdersViewList.clear(); + getPatientLabOrders(); // } notifyListeners(); } @@ -133,13 +128,13 @@ class LabViewModel extends ChangeNotifier { final result = await labRepo.getPatientLabOrders(); result.fold( - (failure) async { - isLabOrdersLoading = false; - isLabResultsLoading = false; - notifyListeners(); - }, - // => await errorHandler_service.handleError(failure: failure), - (apiResponse) { + (failure) async { + isLabOrdersLoading = false; + isLabResultsLoading = false; + notifyListeners(); + }, + // => await errorHandler_service.handleError(failure: failure), + (apiResponse) { if (apiResponse.messageStatus == 2) { // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); } else if (apiResponse.messageStatus == 1) { @@ -203,11 +198,7 @@ class LabViewModel extends ChangeNotifier { } filterSuggestions() { - final List labels = patientLabOrders - .expand((order) => order.testDetails ?? []) - .map((detail) => detail.description) - .whereType() - .toList(); + final List labels = patientLabOrders.expand((order) => order.testDetails ?? []).map((detail) => detail.description).whereType().toList(); _labSuggestionsList = labels.toSet().toList(); notifyListeners(); @@ -319,14 +310,12 @@ class LabViewModel extends ChangeNotifier { ); } - Future getPatientLabResultByHospital( - PatientLabOrdersResponseModel laborder) async { + Future getPatientLabResultByHospital(PatientLabOrdersResponseModel laborder) async { isLabResultByHospitalLoading = true; notifyListeners(); mainLabResultsByHospitals.clear(); - final result = await labRepo.getPatientLabResultsByHospitals(laborder, - Utils.isVidaPlusProject(int.parse(laborder.projectID ?? "0"))); + final result = await labRepo.getPatientLabResultsByHospitals(laborder, Utils.isVidaPlusProject(int.parse(laborder.projectID ?? "0"))); result.fold( (failure) async { @@ -350,12 +339,9 @@ class LabViewModel extends ChangeNotifier { mainLabResults.clear(); filteredGraphValues.clear(); maxY = double.negativeInfinity; - minY = double.infinity; - maxX = double.infinity; - final result = await labRepo.getPatientLabResults( - laborder, - Utils.isVidaPlusProject(int.parse(laborder.projectID ?? "0")), - procedureName); + minY = double.infinity; + maxX = double.infinity; + final result = await labRepo.getPatientLabResults(laborder, Utils.isVidaPlusProject(int.parse(laborder.projectID ?? "0")), procedureName); result.fold( (failure) async { @@ -369,7 +355,6 @@ class LabViewModel extends ChangeNotifier { var recentThree = sort(apiResponse.data!); mainLabResults = recentThree; - double highRefrenceValue = double.negativeInfinity; String? flagForHighReferenceRange; double lowRefenceValue = double.infinity; @@ -377,11 +362,10 @@ class LabViewModel extends ChangeNotifier { recentThree.reversed.forEach((element) { try { - var dateTime = - DateUtil.convertStringToDate(element.verifiedOnDateTime!); + var dateTime = DateUtil.convertStringToDate(element.verifiedOnDateTime!); var resultValue = double.parse(element.resultValue!); - var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag??""); - if (resultValue>maxY) { + var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag ?? ""); + if (resultValue > maxY) { maxY = resultValue; maxX = maxY; } @@ -398,14 +382,13 @@ class LabViewModel extends ChangeNotifier { } filteredGraphValues.add(DataPoint( - value: transformedValue, - actualValue:element.resultValue!, - label: formatDateAsMMYY(dateTime), - unitOfMeasurement: element.uOM, - displayTime: resultDate(dateTime), - time: DateUtil.convertStringToDate(element.verifiedOnDateTime), - referenceValue: element.calculatedResultFlag ?? "", - + value: transformedValue, + actualValue: element.resultValue!, + label: formatDateAsMMYY(dateTime), + unitOfMeasurement: element.uOM, + displayTime: resultDate(dateTime), + time: DateUtil.convertStringToDate(element.verifiedOnDateTime), + referenceValue: element.calculatedResultFlag ?? "", )); } catch (e) {} }); @@ -421,7 +404,7 @@ class LabViewModel extends ChangeNotifier { this.highRefrenceValue = double.parse(highRefrenceValue.toStringAsFixed(1)); this.lowRefenceValue = double.parse(lowRefenceValue.toStringAsFixed(1)); - if(maxY< highRefrenceValue) { + if (maxY < highRefrenceValue) { maxY = highRefrenceValue; } maxY += 25; @@ -431,7 +414,9 @@ class LabViewModel extends ChangeNotifier { checkIfGraphShouldBeDisplayed(recentResult); recentResult.verifiedOn = resultDate(DateUtil.convertStringToDate(recentResult.verifiedOnDateTime!)); // filteredGraphValues = [filteredGraphValues.first]; - navigationService.push(MaterialPageRoute( + labOrderResponseByAi = null; + navigationService.push( + MaterialPageRoute( builder: (_) => LabResultDetails(recentLabResult: recentResult, testDescription: testDescription), ), ); @@ -441,14 +426,13 @@ class LabViewModel extends ChangeNotifier { ); } - void checkIfGraphShouldBeDisplayed(LabResult recentResult){ + void checkIfGraphShouldBeDisplayed(LabResult recentResult) { shouldShowGraph = recentResult.checkIfGraphShouldBeDisplayed(); isGraphVisible = shouldShowGraph; notifyListeners(); } - Future getPatientSpecialResult( - PatientLabOrdersResponseModel laborder) async { + Future getPatientSpecialResult(PatientLabOrdersResponseModel laborder) async { isSpecialResultsLoading = true; labSpecialResult = ""; notifyListeners(); @@ -470,8 +454,7 @@ class LabViewModel extends ChangeNotifier { StringBuffer htmlbuffer = StringBuffer(""); apiResponse.data?.forEach((element) { - if(element.resultDataHTML != null && element.resultDataHTML?.isNotEmpty == true) - htmlbuffer.write("${element.resultDataHTML}

"); + if (element.resultDataHTML != null && element.resultDataHTML?.isNotEmpty == true) htmlbuffer.write("${element.resultDataHTML}

"); }); labSpecialResult = htmlbuffer.toString(); @@ -483,10 +466,8 @@ class LabViewModel extends ChangeNotifier { ); } - String resultDate(DateTime date){ - - - return '${date.day} ${months[date.month-1]},${date.year}'; + String resultDate(DateTime date) { + return '${date.day} ${months[date.month - 1]},${date.year}'; } double transformValueInRange(double inputValue, String flag) { @@ -494,7 +475,7 @@ class LabViewModel extends ChangeNotifier { double rangeStart, rangeEnd; switch (flag) { - case'LCL': + case 'LCL': case 'CL': rangeStart = 0.0; rangeEnd = 19.0; @@ -531,16 +512,17 @@ class LabViewModel extends ChangeNotifier { debugPrint("the transformed value is $transformedValue"); return transformedValue; } + void getSelectedDateRange(DateTime? start, DateTime? end) { maxY = double.negativeInfinity; - if(start == null && end == null) { + if (start == null && end == null) { mainLabResults.forEach((element) { final time = DateUtil.convertStringToDate(element.verifiedOnDateTime!); - try{ + try { var resultValue = double.parse(element.resultValue!); - var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag??""); + var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag ?? ""); if (resultValue > maxY) { maxY = resultValue; } @@ -549,54 +531,43 @@ class LabViewModel extends ChangeNotifier { actualValue: element.resultValue!, label: formatDateAsMMYY(time), unitOfMeasurement: element.uOM, - displayTime: resultDate(time), time: DateUtil.convertStringToDate(element.verifiedOnDateTime), referenceValue: element.calculatedResultFlag ?? "", )); - }catch(e){ - - } + } catch (e) {} }); - - }else { + } else { filteredGraphValues.clear(); mainLabResults.forEach((element) { try { - var dateTime = - DateUtil.convertStringToDate(element.verifiedOnDateTime!); + var dateTime = DateUtil.convertStringToDate(element.verifiedOnDateTime!); var resultValue = double.parse(element.resultValue!); - var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag??""); + var transformedValue = transformValueInRange(double.parse(element.resultValue!), element.calculatedResultFlag ?? ""); if (resultValue > maxY) { maxY = resultValue; } if (start != null && end == null) { if (dateTime.isAtSameMomentAs(start)) { - filteredGraphValues.add(DataPoint( value: transformedValue, actualValue: element.resultValue!, unitOfMeasurement: element.uOM, - label: formatDateAsMMYY(dateTime), displayTime: resultDate(dateTime), - time: - DateUtil.convertStringToDate(element.verifiedOnDateTime), + time: DateUtil.convertStringToDate(element.verifiedOnDateTime), referenceValue: element.calculatedResultFlag ?? "")); } } else if (start != null && end != null) { if ((dateTime.isAfter(start)) && (dateTime.isBefore(end))) { - filteredGraphValues.add(DataPoint( value: transformedValue, actualValue: element.resultValue!, label: formatDateAsMMYY(dateTime), unitOfMeasurement: element.uOM, - displayTime: resultDate(dateTime), - time: - DateUtil.convertStringToDate(element.verifiedOnDateTime), + time: DateUtil.convertStringToDate(element.verifiedOnDateTime), referenceValue: element.calculatedResultFlag ?? "")); } } @@ -605,16 +576,13 @@ class LabViewModel extends ChangeNotifier { } filteredGraphValues = sortFilteredList(filteredGraphValues).reversed.toList(); - notifyListeners(); } String formatDateAsMMYY(DateTime date) { - - return '${months[date.month-1]}, ${date.year}'; + return '${months[date.month - 1]}, ${date.year}'; } - List sortByFlagAndValue(List original) { const priorityOrder = ['LCL', 'CL', 'L', 'N', 'H', 'CH', 'HCH']; @@ -648,7 +616,6 @@ class LabViewModel extends ChangeNotifier { } List sort(List original) { - final copy = List.from(original); copy.sort((a, b) { final aDate = DateUtil.convertStringToDate(a.verifiedOnDateTime); @@ -663,8 +630,6 @@ class LabViewModel extends ChangeNotifier { } List sortFilteredList(List original) { - - final copy = List.from(original); copy.sort((a, b) { final aDate = a.time; @@ -699,7 +664,7 @@ class LabViewModel extends ChangeNotifier { } } - String getFormattedDate(DateTime date){ + String getFormattedDate(DateTime date) { return DateFormat('EEEE, dd MMMM. yyyy').format(date); } @@ -713,7 +678,7 @@ class LabViewModel extends ChangeNotifier { case 'N': return AppAssets.ic_normal_result; case 'H': - return AppAssets.ic_low_result; + return AppAssets.ic_low_result; case 'CH': case 'HCH': return AppAssets.ic_critical_low_result; @@ -755,8 +720,80 @@ class LabViewModel extends ChangeNotifier { } } - alterGraphVisibility(){ + alterGraphVisibility() { isGraphVisible = !isGraphVisible; notifyListeners(); } + + Future getAiOverviewLabOrders({required PatientLabOrdersResponseModel labOrder}) async { + LoadingUtils.showFullScreenLoader(loadingText: "Loading and analysing your data,\nPlease be patient and let the AI do the magic"); + List> results = []; + Map orderData = {"order_date": labOrder.orderDate ?? "", "clinic": labOrder.clinicDescription ?? "", "doctor": labOrder.doctorName ?? "", "results": []}; + List> testResults = []; + if (labOrder.testDetails != null && labOrder.testDetails!.isNotEmpty) { + for (var testDetail in labOrder.testDetails!) { + LabResult? matchingResult = + mainLabResultsByHospitals.firstWhere((labResult) => labResult.testCode == testDetail.testCode || labResult.description == testDetail.description, orElse: () => LabResult()); + testResults.add({ + "test_name": testDetail.description ?? "", + "result_value": matchingResult.resultValue ?? "", + "reference_range": matchingResult.referanceRange ?? "", + "unit": matchingResult.uOM ?? "", + "flag": matchingResult.calculatedResultFlag ?? "N" + }); + } + } + orderData["results"] = testResults; + results.add(orderData); + final result = await labRepo.getPatientAiOverViewLabOrders(results); + result.fold( + (failure) async { + LoadingUtils.hideFullScreenLoader(); + await errorHandlerService.handleError(failure: failure); + }, + (apiResponse) { + LoadingUtils.hideFullScreenLoader(); + if (apiResponse.messageStatus == 2) { + } else if (apiResponse.messageStatus == 1) { + labOrdersResponseByAi = apiResponse.data; + navigationService.push( + MaterialPageRoute(builder: (_) => LabAiAnalysisDetailedPage()), + ); + } + }, + ); + + LoadingUtils.hideFullScreenLoader(); + } + + Future getAiOverviewSingleLabResult({required String langId, required LabResult recentLabResult}) async { + LoaderBottomSheet.showLoader(); + List> results = []; + results.add({ + "Description": recentLabResult.description ?? '', + "ResultValue": recentLabResult.resultValue ?? '', + "CalculatedResultFlag": recentLabResult.calculatedResultFlag ?? '', + "UOM": recentLabResult.uOM ?? '', + "ReferanceRange": recentLabResult.referanceRange ?? '', + }); + + var payload = {"patient_id": currentlySelectedPatientOrder!.patientID, "language_id": langId, "lab_results": results}; + final result = await labRepo.getPatientAiOverViewLabOrder(payload); + result.fold( + (failure) async { + LoaderBottomSheet.hideLoader(); + await errorHandlerService.handleError(failure: failure); + }, + (apiResponse) { + LoaderBottomSheet.hideLoader(); + if (apiResponse.messageStatus == 2) { + } else if (apiResponse.messageStatus == 1) { + labOrderResponseByAi = apiResponse.data; + notifyListeners(); + } + }, + ); + + LoaderBottomSheet.hideLoader(); + } } diff --git a/lib/features/lab/models/ai_overview_labresult_model_payload.dart b/lib/features/lab/models/ai_overview_labresult_model_payload.dart new file mode 100644 index 0000000..c876592 --- /dev/null +++ b/lib/features/lab/models/ai_overview_labresult_model_payload.dart @@ -0,0 +1,69 @@ +import 'dart:convert'; + +class AiLabOrdersOverView { + String? orderDate; + String? clinic; + String? doctor; + List? results; + + AiLabOrdersOverView({ + this.orderDate, + this.clinic, + this.doctor, + this.results, + }); + + factory AiLabOrdersOverView.fromRawJson(String str) => AiLabOrdersOverView.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory AiLabOrdersOverView.fromJson(Map json) => AiLabOrdersOverView( + orderDate: json["order_date"] == null ? null : json["order_date"], + clinic: json["clinic"], + doctor: json["doctor"], + results: json["results"] == null ? [] : List.from(json["results"]!.map((x) => Result.fromJson(x))), + ); + + Map toJson() => { + "order_date": orderDate, + "clinic": clinic, + "doctor": doctor, + "results": results == null ? [] : List.from(results!.map((x) => x.toJson())), + }; +} + +class Result { + String? testName; + String? resultValue; + String? referenceRange; + String? unit; + String? flag; + + Result({ + this.testName, + this.resultValue, + this.referenceRange, + this.unit, + this.flag, + }); + + factory Result.fromRawJson(String str) => Result.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory Result.fromJson(Map json) => Result( + testName: json["test_name"], + resultValue: json["result_value"], + referenceRange: json["reference_range"], + unit: json["unit"], + flag: json["flag"], + ); + + Map toJson() => { + "test_name": testName, + "result_value": resultValue, + "reference_range": referenceRange, + "unit": unit, + "flag": flag, + }; +} diff --git a/lib/features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart b/lib/features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart new file mode 100644 index 0000000..2353cf8 --- /dev/null +++ b/lib/features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart @@ -0,0 +1,177 @@ +import 'dart:convert'; + +class LabOrdersResponseByAi { + Analysis? analysis; + String? patientId; + int? totalOrders; + int? totalResults; + + LabOrdersResponseByAi({ + this.analysis, + this.patientId, + this.totalOrders, + this.totalResults, + }); + + factory LabOrdersResponseByAi.fromRawJson(String str) => LabOrdersResponseByAi.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory LabOrdersResponseByAi.fromJson(Map json) => LabOrdersResponseByAi( + analysis: json["analysis"] == null ? null : Analysis.fromJson(json["analysis"]), + patientId: json["patient_id"], + totalOrders: json["total_orders"], + totalResults: json["total_results"], + ); + + Map toJson() => { + "analysis": analysis?.toJson(), + "patient_id": patientId, + "total_orders": totalOrders, + "total_results": totalResults, + }; +} + +class Analysis { + List? aiGeneratedAttributes; + List? aiPredictions; + List? aiRecommendations; + List? prevention; + String? rawMessage; + List? riskFactors; + List? suggestedDoctors; + String? summary; + + Analysis({ + this.aiGeneratedAttributes, + this.aiPredictions, + this.aiRecommendations, + this.prevention, + this.rawMessage, + this.riskFactors, + this.suggestedDoctors, + this.summary, + }); + + factory Analysis.fromRawJson(String str) => Analysis.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory Analysis.fromJson(Map json) => Analysis( + aiGeneratedAttributes: json["ai_generated_attributes"] == null ? [] : List.from(json["ai_generated_attributes"]!.map((x) => AiGeneratedAttribute.fromJson(x))), + aiPredictions: json["ai_predictions"] == null ? [] : List.from(json["ai_predictions"]!.map((x) => x)), + aiRecommendations: json["ai_recommendations"] == null ? [] : List.from(json["ai_recommendations"]!.map((x) => AiRecommendation.fromJson(x))), + prevention: json["prevention"] == null ? [] : List.from(json["prevention"]!.map((x) => x)), + rawMessage: json["raw_message"], + riskFactors: json["riskFactors"] == null ? [] : List.from(json["riskFactors"]!.map((x) => RiskFactor.fromJson(x))), + suggestedDoctors: json["suggested_doctors"] == null ? [] : List.from(json["suggested_doctors"]!.map((x) => x)), + summary: json["summary"], + ); + + Map toJson() => { + "ai_generated_attributes": aiGeneratedAttributes == null ? [] : List.from(aiGeneratedAttributes!.map((x) => x.toJson())), + "ai_predictions": aiPredictions == null ? [] : List.from(aiPredictions!.map((x) => x)), + "ai_recommendations": aiRecommendations == null ? [] : List.from(aiRecommendations!.map((x) => x.toJson())), + "prevention": prevention == null ? [] : List.from(prevention!.map((x) => x)), + "raw_message": rawMessage, + "riskFactors": riskFactors == null ? [] : List.from(riskFactors!.map((x) => x.toJson())), + "suggested_doctors": suggestedDoctors == null ? [] : List.from(suggestedDoctors!.map((x) => x)), + "summary": summary, + }; +} + +class AiGeneratedAttribute { + String? calculatedResultFlag; + String? description; + String? referanceRange; + String? resultValue; + String? testShortDescription; + String? uom; + String? calculationFormula; + + AiGeneratedAttribute({ + this.calculatedResultFlag, + this.description, + this.referanceRange, + this.resultValue, + this.testShortDescription, + this.uom, + this.calculationFormula, + }); + + factory AiGeneratedAttribute.fromRawJson(String str) => AiGeneratedAttribute.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory AiGeneratedAttribute.fromJson(Map json) => AiGeneratedAttribute( + calculatedResultFlag: json["CalculatedResultFlag"], + description: json["Description"], + referanceRange: json["ReferanceRange"], + resultValue: json["ResultValue"], + testShortDescription: json["TestShortDescription"], + uom: json["UOM"], + calculationFormula: json["calculationFormula"], + ); + + Map toJson() => { + "CalculatedResultFlag": calculatedResultFlag, + "Description": description, + "ReferanceRange": referanceRange, + "ResultValue": resultValue, + "TestShortDescription": testShortDescription, + "UOM": uom, + "calculationFormula": calculationFormula, + }; +} + +class AiRecommendation { + String? priority; + String? recommendation; + + AiRecommendation({ + this.priority, + this.recommendation, + }); + + factory AiRecommendation.fromRawJson(String str) => AiRecommendation.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory AiRecommendation.fromJson(Map json) => AiRecommendation( + priority: json["priority"], + recommendation: json["recommendation"], + ); + + Map toJson() => { + "priority": priority, + "recommendation": recommendation, + }; +} + +class RiskFactor { + String? description; + String? factor; + String? risk; + + RiskFactor({ + this.description, + this.factor, + this.risk, + }); + + factory RiskFactor.fromRawJson(String str) => RiskFactor.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory RiskFactor.fromJson(Map json) => RiskFactor( + description: json["description"], + factor: json["factor"], + risk: json["risk"], + ); + + Map toJson() => { + "description": description, + "factor": factor, + "risk": risk, + }; +} diff --git a/lib/features/lab/models/resp_models/lab_result.dart b/lib/features/lab/models/resp_models/lab_result.dart index a075be3..2314684 100644 --- a/lib/features/lab/models/resp_models/lab_result.dart +++ b/lib/features/lab/models/resp_models/lab_result.dart @@ -26,6 +26,7 @@ class LabResult { String? referenceLow; num? resultTypeID; String? packageShortDescription; + int? testId; LabResult( {this.description, @@ -52,6 +53,7 @@ class LabResult { this.referenceHigh, this.criticalLow, this.referenceLow, + this.testId, }); LabResult.fromJson(Map json) { @@ -82,6 +84,7 @@ class LabResult { referenceLow = json['ReferenceLow']; packageShortDescription = json['PackageShortDescription']; resultTypeID = json['ResultTypeID']; + testId = json['TestID']; } Map toJson() { @@ -110,6 +113,7 @@ class LabResult { data['ReferenceHigh'] = this.referenceHigh; data['CriticalLow'] = this.criticalLow; data['ReferenceLow'] = this.referenceLow; + data['TestID'] = this.testId; return data; } diff --git a/lib/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart b/lib/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart new file mode 100644 index 0000000..7ad3d54 --- /dev/null +++ b/lib/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart @@ -0,0 +1,145 @@ +import 'dart:convert'; + +class LabOrderResponseByAi { + String? summary; + List? aiGeneratedAttributes; + List? aiPredictions; + List? aiRecommendations; + List? riskFactors; + List? prevention; + List? suggestedDoctors; + String? rawMessage; + + LabOrderResponseByAi({ + this.summary, + this.aiGeneratedAttributes, + this.aiPredictions, + this.aiRecommendations, + this.riskFactors, + this.prevention, + this.suggestedDoctors, + this.rawMessage, + }); + + factory LabOrderResponseByAi.fromRawJson(String str) => LabOrderResponseByAi.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory LabOrderResponseByAi.fromJson(Map json) => LabOrderResponseByAi( + summary: json["summary"], + aiGeneratedAttributes: json["ai_generated_attributes"] == null ? [] : List.from(json["ai_generated_attributes"]!.map((x) => AiGeneratedAttribute.fromJson(x))), + aiPredictions: json["ai_predictions"] == null ? [] : List.from(json["ai_predictions"]!.map((x) => x)), + aiRecommendations: json["ai_recommendations"] == null ? [] : List.from(json["ai_recommendations"]!.map((x) => AiRecommendation.fromJson(x))), + riskFactors: json["riskFactors"] == null ? [] : List.from(json["riskFactors"]!.map((x) => RiskFactor.fromJson(x))), + prevention: json["prevention"] == null ? [] : List.from(json["prevention"]!.map((x) => x)), + suggestedDoctors: json["suggested_doctors"] == null ? [] : List.from(json["suggested_doctors"]!.map((x) => x)), + rawMessage: json["raw_message"], + ); + + Map toJson() => { + "summary": summary, + "ai_generated_attributes": aiGeneratedAttributes == null ? [] : List.from(aiGeneratedAttributes!.map((x) => x.toJson())), + "ai_predictions": aiPredictions == null ? [] : List.from(aiPredictions!.map((x) => x)), + "ai_recommendations": aiRecommendations == null ? [] : List.from(aiRecommendations!.map((x) => x.toJson())), + "riskFactors": riskFactors == null ? [] : List.from(riskFactors!.map((x) => x.toJson())), + "prevention": prevention == null ? [] : List.from(prevention!.map((x) => x)), + "suggested_doctors": suggestedDoctors == null ? [] : List.from(suggestedDoctors!.map((x) => x)), + "raw_message": rawMessage, + }; +} + +class AiGeneratedAttribute { + String? description; + String? resultValue; + String? referanceRange; + String? calculatedResultFlag; + String? uom; + String? calculationFormula; + String? testShortDescription; + + AiGeneratedAttribute({ + this.description, + this.resultValue, + this.referanceRange, + this.calculatedResultFlag, + this.uom, + this.calculationFormula, + this.testShortDescription, + }); + + factory AiGeneratedAttribute.fromRawJson(String str) => AiGeneratedAttribute.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory AiGeneratedAttribute.fromJson(Map json) => AiGeneratedAttribute( + description: json["Description"], + resultValue: json["ResultValue"], + referanceRange: json["ReferanceRange"], + calculatedResultFlag: json["CalculatedResultFlag"], + uom: json["UOM"], + calculationFormula: json["calculationFormula"], + testShortDescription: json["TestShortDescription"], + ); + + Map toJson() => { + "Description": description, + "ResultValue": resultValue, + "ReferanceRange": referanceRange, + "CalculatedResultFlag": calculatedResultFlag, + "UOM": uom, + "calculationFormula": calculationFormula, + "TestShortDescription": testShortDescription, + }; +} + +class AiRecommendation { + String? recommendation; + String? priority; + + AiRecommendation({ + this.recommendation, + this.priority, + }); + + factory AiRecommendation.fromRawJson(String str) => AiRecommendation.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory AiRecommendation.fromJson(Map json) => AiRecommendation( + recommendation: json["recommendation"], + priority: json["priority"], + ); + + Map toJson() => { + "recommendation": recommendation, + "priority": priority, + }; +} + +class RiskFactor { + String? factor; + String? risk; + String? description; + + RiskFactor({ + this.factor, + this.risk, + this.description, + }); + + factory RiskFactor.fromRawJson(String str) => RiskFactor.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory RiskFactor.fromJson(Map json) => RiskFactor( + factor: json["factor"], + risk: json["risk"], + description: json["description"], + ); + + Map toJson() => { + "factor": factor, + "risk": risk, + "description": description, + }; +} diff --git a/lib/generated/locale_keys.g.dart b/lib/generated/locale_keys.g.dart index 416d2a4..05563f7 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -1515,5 +1515,43 @@ abstract class LocaleKeys { static const yesPleaseINeedHelp = 'yesPleaseINeedHelp'; static const noThanksIKnowTheClinic = 'noThanksIKnowTheClinic'; static const unableToSendOTP = 'unableToSendOTP'; + static const aiOverView = 'aiOverView'; + static const generateAiAnalysis = 'generateAiAnalysis'; + static const aiAnalysis = 'aiAnalysis'; + static const prediction = 'prediction'; + static const prevention = 'prevention'; + static const disclaimer = 'disclaimer'; + static const thisAboveInfo = 'thisAboveInfo'; + static const aiDisclaimer = 'aiDisclaimer'; + static const consent = 'consent'; + static const bmiNormalDescription = 'bmiNormalDescription'; + static const bmiUnderweightDescription = 'bmiUnderweightDescription'; + static const bmiOverweightDescription = 'bmiOverweightDescription'; + static const caloriesMaintenanceDescription = 'caloriesMaintenanceDescription'; + static const caloriesModerateDeficitDescription = 'caloriesModerateDeficitDescription'; + static const caloriesAggressiveDeficitDescription = 'caloriesAggressiveDeficitDescription'; + static const bodyFatEssentialDescription = 'bodyFatEssentialDescription'; + static const bodyFatFitnessDescription = 'bodyFatFitnessDescription'; + static const bodyFatAverageDescription = 'bodyFatAverageDescription'; + static const bodyFatObeseDescription = 'bodyFatObeseDescription'; + static const bmrNormalDescription = 'bmrNormalDescription'; + static const bmrLowDescription = 'bmrLowDescription'; + static const bmrHighDescription = 'bmrHighDescription'; + static const ibwAtTargetDescription = 'ibwAtTargetDescription'; + static const ibwBelowTargetDescription = 'ibwBelowTargetDescription'; + static const ibwAboveTargetDescription = 'ibwAboveTargetDescription'; + static const ibwCloseToRangeDescription = 'ibwCloseToRangeDescription'; + static const ibwUnderweightDescription = 'ibwUnderweightDescription'; + static const ibwUnderweightGenericDescription = 'ibwUnderweightGenericDescription'; + static const ibwOverweightDescription = 'ibwOverweightDescription'; + static const ibwOverweightGenericDescription = 'ibwOverweightGenericDescription'; + static const dietVeryLowCarbsDescription = 'dietVeryLowCarbsDescription'; + static const dietLowCarbsDescription = 'dietLowCarbsDescription'; + static const dietModerateCarbsDescription = 'dietModerateCarbsDescription'; + static const dietUSDAGuidelinesDescription = 'dietUSDAGuidelinesDescription'; + static const dietZoneDietDescription = 'dietZoneDietDescription'; + static const contextDependent = 'contextDependent'; + static const calculatedValue = 'calculatedValue'; + static const calculationFormula = 'calculationFormula'; } diff --git a/lib/presentation/authentication/saved_login_screen.dart b/lib/presentation/authentication/saved_login_screen.dart index f0fd8cb..22fc467 100644 --- a/lib/presentation/authentication/saved_login_screen.dart +++ b/lib/presentation/authentication/saved_login_screen.dart @@ -115,6 +115,7 @@ class _SavedLogin extends State { CustomButton( text: "${LocaleKeys.loginBy.tr()} ${loginType.displayName}", onPressed: () { + if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) { authVm.loginWithFingerPrintFace(() {}); } else { diff --git a/lib/presentation/book_appointment/select_clinic_page.dart b/lib/presentation/book_appointment/select_clinic_page.dart index d96c9da..9d2c292 100644 --- a/lib/presentation/book_appointment/select_clinic_page.dart +++ b/lib/presentation/book_appointment/select_clinic_page.dart @@ -261,8 +261,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["bmiCategory"], calories: calculatedResult["bmiResult"], - description: - 'Your BMI is within the healthy range. Continue a balanced diet, regular physical activity, and routine checkups to maintain good health. Monitor any significant changes over time.', + description: LocaleKeys.bmiNormalDescription.tr(), color: Colors.green, icon: Icons.scale, hide: true, @@ -272,8 +271,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["bmiCategory"], calories: calculatedResult["bmiResult"], - description: - 'BMI suggests you are underweight. Consider increasing calorie intake with nutrient-dense foods, include resistance training to build muscle, and consult a healthcare professional to check for underlying causes.', + description: LocaleKeys.bmiUnderweightDescription.tr(), color: Colors.orange, hide: true, icon: Icons.trending_down, @@ -283,8 +281,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["bmiCategory"], calories: calculatedResult["bmiResult"], - description: - 'BMI indicates overweight. Aim for gradual, sustainable weight loss through a modest calorie deficit, regular physical activity, and healthier food choices. Seek medical advice before major lifestyle changes.', + description: LocaleKeys.bmiOverweightDescription.tr(), color: Colors.red, hide: true, icon: Icons.warning_rounded, @@ -295,8 +292,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["calorieRange"], calories: calculatedResult["calories"], - description: - 'Estimated daily calories to maintain your current weight given your activity level and metabolism. Use this as a baseline: increase slightly for muscle gain, or create a small deficit for gradual weight loss. Track progress and adjust every 2–4 weeks.', + description: LocaleKeys.caloriesMaintenanceDescription.tr(), color: Colors.green, icon: Icons.scale, ), @@ -305,8 +301,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["calorieRange"], calories: calculatedResult["calories"], - description: - 'A moderate calorie reduction designed for steady, sustainable weight loss (typically 0.25–0.5 kg per week). Combine with resistance training and adequate protein to preserve muscle. Avoid extreme cuts and consult a professional if you have medical conditions.', + description: LocaleKeys.caloriesModerateDeficitDescription.tr(), color: Colors.orange, icon: Icons.trending_down, ), @@ -315,19 +310,59 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["calorieRange"], calories: calculatedResult["calories"], - description: - 'A large calorie reduction that may produce faster weight loss but can be hard to sustain and increase risk of nutrient deficiencies, fatigue, or muscle loss. Not recommended long-term; seek guidance from a healthcare or nutrition professional before continuing.', + description: LocaleKeys.caloriesAggressiveDeficitDescription.tr(), color: Colors.red, icon: Icons.warning_rounded, ), ] + ] else if (type == HealthCalculatorsTypeEnum.bodyFat) ...[ + if (calculatedResult["fatCategory"] == "Essential Fat" || calculatedResult["fatCategory"] == "Athletes") ...[ + calorieWidget( + title: calculatedResult["fatCategory"], + calories: calculatedResult["fatPercentage"], + description: LocaleKeys.bodyFatEssentialDescription.tr(), + color: Colors.green, + hide: true, + icon: Icons.fitness_center, + ), + SizedBox(height: 16.h), + ] else if (calculatedResult["fatCategory"] == "Fitness") ...[ + calorieWidget( + title: calculatedResult["fatCategory"], + calories: calculatedResult["fatPercentage"], + description: LocaleKeys.bodyFatFitnessDescription.tr(), + color: Colors.green, + hide: true, + icon: Icons.fitness_center, + ), + SizedBox(height: 16.h), + ] else if (calculatedResult["fatCategory"] == "Average" || calculatedResult["fatCategory"] == "Acceptable") ...[ + calorieWidget( + title: calculatedResult["fatCategory"], + calories: calculatedResult["fatPercentage"], + description: LocaleKeys.bodyFatAverageDescription.tr(), + color: Colors.orange, + hide: true, + icon: Icons.accessibility_new, + ), + SizedBox(height: 16.h), + ] else if (calculatedResult["fatCategory"] == "Obese" || calculatedResult["fatCategory"] == "Overweight") ...[ + calorieWidget( + title: calculatedResult["fatCategory"], + calories: calculatedResult["fatPercentage"], + description: LocaleKeys.bodyFatObeseDescription.tr(), + color: Colors.red, + hide: true, + icon: Icons.warning_rounded, + ), + SizedBox(height: 16.h), + ] ] else if (type == HealthCalculatorsTypeEnum.bmr) ...[ if (calculatedResult["bmrRange"] == "Normal") ...[ calorieWidget( title: calculatedResult["bmrRange"], calories: calculatedResult["bmr"], - description: - 'Your Basal Metabolic Rate (BMR) is within the expected range for your profile. BMR is the energy your body needs at rest to maintain vital functions (breathing, circulation, temperature). Use this value as the baseline for estimating total daily energy needs by applying an activity multiplier. Maintain a balanced diet and regular physical activity to support metabolic health.', + description: LocaleKeys.bmrNormalDescription.tr(), color: Colors.green, hide: true, icon: Icons.scale, @@ -337,8 +372,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["bmrRange"], calories: calculatedResult["bmr"], - description: - 'Your BMR is lower than typical for your profile. Possible causes include lower lean muscle mass, age-related metabolic decline, or metabolic adaptation from prolonged calorie restriction. Consider focusing on resistance training to build/maintain muscle, ensure adequate protein and micronutrient intake, and consult a healthcare professional if this is unexpected.', + description: LocaleKeys.low.tr(), color: Colors.orange, hide: true, icon: Icons.trending_down, @@ -348,8 +382,7 @@ class _SelectClinicPageState extends State { calorieWidget( title: calculatedResult["bmrRange"], calories: calculatedResult["bmr"], - description: - 'Your BMR is higher than average for your profile. This can reflect greater lean mass, younger age, or a naturally higher metabolic rate, meaning you burn more energy at rest. Use this information to tailor calorie targets: higher needs for maintenance or muscle gain, moderate deficit for weight loss. Seek medical advice if you notice rapid unexplained changes.', + description: LocaleKeys.bmrHighDescription.tr(), color: Colors.red, hide: true, icon: Icons.warning_rounded, @@ -915,9 +948,16 @@ class _SelectClinicPageState extends State { Widget _buildStatusIcon(String title) { final key = title.trim(); - if (key == 'Maintenance Calories' || key == 'Normal' || key == 'Ideal Weight' || key == 'Moderate Crabs' || key == 'USDA Guidelines') { + if (key == 'Maintenance Calories' || + key == 'Normal' || + key == 'Ideal Weight' || + key == 'Moderate Crabs' || + key == 'USDA Guidelines' || + key == 'Essential Fat' || + key == 'Athletes' || + key == 'Fitness') { return Utils.buildSvgWithAssets(icon: AppAssets.checkmark_icon, width: 24.w, height: 24.h); - } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet') { + } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet' || key == 'Average' || key == 'Acceptable') { return Utils.buildSvgWithAssets(icon: AppAssets.trade_down_yellow, width: 24.w, height: 24.h); } else if (key == 'Aggressive Deficit' || key == 'High' || key == 'Overweight' || key == "Obese") { return Utils.buildSvgWithAssets(icon: AppAssets.trade_down_red, width: 24.w, height: 24.h); @@ -928,9 +968,16 @@ class _SelectClinicPageState extends State { Color getTextColor(String title) { final key = title.trim(); - if (key == 'Maintenance Calories' || key == 'Normal' || key == 'Ideal Weight' || key == 'Moderate Crabs' || key == 'USDA Guidelines') { + if (key == 'Maintenance Calories' || + key == 'Normal' || + key == 'Ideal Weight' || + key == 'Moderate Crabs' || + key == 'USDA Guidelines' || + key == 'Essential Fat' || + key == 'Athletes' || + key == 'Fitness') { return AppColors.successColor; - } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet') { + } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet' || key == 'Average' || key == 'Acceptable') { return AppColors.warningColor; } else if (key == 'Aggressive Deficit' || key == 'High' || key == 'Overweight' || key == "Obese") { return AppColors.errorColor; @@ -1156,7 +1203,8 @@ class _SelectClinicPageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ bookAppointmentsViewModel.patientDentalPlanEstimationList[index].procedureName!.toText12(isBold: true), - AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} ${LocaleKeys.mins.tr(context: context)}"), + AppCustomChipWidget( + icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} ${LocaleKeys.mins.tr(context: context)}"), ], ); }, diff --git a/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart b/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart index 4a83f51..8cccf03 100644 --- a/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart +++ b/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart @@ -52,8 +52,8 @@ class _HealthCalculatorDetailedPageState extends State(); Navigator.of(context).push(CustomPageRoute( page: SelectClinicPage(calculatorType: widget.calculatorType, calculatedResult: calculatedResult), )); @@ -174,69 +172,58 @@ class _HealthCalculatorDetailedPageState extends State { children: [ Radio( value: unit, - groupValue: selectedHeightUnit, + groupValue: selectedHipUnit, activeColor: AppColors.errorColor, onChanged: (String? value) { if (value == null) return; diff --git a/lib/presentation/lab/lab_orders_page.dart b/lib/presentation/lab/lab_orders_page.dart index 006280f..a6ee154 100644 --- a/lib/presentation/lab/lab_orders_page.dart +++ b/lib/presentation/lab/lab_orders_page.dart @@ -1 +1 @@ -import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart'; import 'package:hmg_patient_app_new/presentation/lab/search_lab_report.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_toolbar.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/chip/custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; import 'alphabeticScroll.dart'; class LabOrdersPage extends StatefulWidget { const LabOrdersPage({super.key}); @override State createState() => _LabOrdersPageState(); } class _LabOrdersPageState extends State { late LabViewModel labProvider; late DateRangeSelectorRangeViewModel rangeViewModel; late AppState _appState; List?> labSuggestions = []; int? expandedIndex; String? selectedFilterText = ''; int activeIndex = 0; @override void initState() { scheduleMicrotask(() { labProvider.initLabProvider(); }); super.initState(); } @override Widget build(BuildContext context) { labProvider = Provider.of(context, listen: false); rangeViewModel = Provider.of(context); _appState = getIt(); return CollapsingListView( title: LocaleKeys.labResults.tr(context: context), search: () async { final lavVM = Provider.of(context, listen: false); if (lavVM.isLabOrdersLoading) { return; } else { String? value = await Navigator.of(context).push( CustomPageRoute( page: SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions), fullScreenDialog: true, direction: AxisDirection.down, ), ); if (value != null) { selectedFilterText = value; lavVM.filterLabReports(value); } } }, child: Consumer( builder: (context, model, child) { return SingleChildScrollView( physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.all(24.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: CustomTabBar( activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ CustomTabBarModel(null, LocaleKeys.byVisit.tr()), CustomTabBarModel(null, LocaleKeys.byTest.tr()), // CustomTabBarModel(null, "Completed".needTranslation), ], onTabChange: (index) { activeIndex = index; setState(() {}); }, ), ), ], ), if (activeIndex == 0) Padding( padding: EdgeInsets.symmetric(vertical: 10.h), child: Row( children: [ CustomButton( text: LocaleKeys.byClinic.tr(context: context), onPressed: () { model.setIsSortByClinic(true); }, backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), SizedBox(width: 8.h), CustomButton( text: LocaleKeys.byHospital.tr(context: context), onPressed: () { model.setIsSortByClinic(false); }, backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ], ), ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? // By Visit - show grouped view when available model.isLabOrdersLoading ? ListView.builder( shrinkWrap: true, physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: 5, itemBuilder: (context, index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ), ) : (model.patientLabOrdersViewList.isNotEmpty ? ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.patientLabOrdersViewList.length, itemBuilder: (context, index) { final group = model.patientLabOrdersViewList[index]; final isExpanded = expandedIndex == index; return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: AnimatedContainer( duration: Duration(milliseconds: 300), curve: Curves.easeInOut, margin: EdgeInsets.symmetric(vertical: 8.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), child: InkWell( onTap: () { setState(() { expandedIndex = isExpanded ? null : index; }); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget(labelText: "${group.length} ${LocaleKeys.results.tr(context: context)}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), SizedBox(height: 8.h), Text( model.isSortByClinic ? (group.first.clinicDescription ?? 'Unknown') : (group.first.projectName ?? 'Unknown'), style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis, ), ], ), ), AnimatedSwitcher( duration: Duration(milliseconds: 500), switchInCurve: Curves.easeIn, switchOutCurve: Curves.easeOut, transitionBuilder: (Widget child, Animation animation) { return FadeTransition( opacity: animation, child: SizeTransition( sizeFactor: animation, axisAlignment: 0.0, child: child, ), ); }, child: isExpanded ? Container( key: ValueKey(index), padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h), child: ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemBuilder: (cxt, index) { PatientLabOrdersResponseModel order = group[index]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Image.network( order.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png", width: 24.w, height: 24.h, fit: BoxFit.cover, ).circle(100), SizedBox(width: 8.h), Expanded(child: (order.doctorName ?? order.doctorNameEnglish ?? "").toString().toText14(weight: FontWeight.w500)), ], ), SizedBox(height: 8.h), Wrap( direction: Axis.horizontal, spacing: 4.h, runSpacing: 4.h, children: [ AppCustomChipWidget( labelText: ("${LocaleKeys.orderNo.tr(context: context)}: ${order.orderNo!}"), ), AppCustomChipWidget( labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), ), AppCustomChipWidget( labelText: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), ), ], ), // Row( // children: [ // CustomButton( // text: ("Order No: ".needTranslation + order.orderNo!), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // SizedBox(width: 8.h), // CustomButton( // text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), // SizedBox(height: 8.h), // Row( // children: [ // CustomButton( // text: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), SizedBox(height: 12.h), Row( children: [ Expanded(flex: 2, child: SizedBox()), // Expanded( // flex: 1, // child: Container( // height: 40.h, // width: 40.w, // decoration: RoundedRectangleBorder().toSmoothCornerDecoration( // color: AppColors.textColor, // borderRadius: 12, // ), // child: Padding( // padding: EdgeInsets.all(12.h), // child: Transform.flip( // flipX: _appState.isArabic(), // child: Utils.buildSvgWithAssets( // icon: AppAssets.forward_arrow_icon_small, // iconColor: AppColors.whiteColor, // fit: BoxFit.contain, // ), // ), // ), // ).onPress(() { // model.currentlySelectedPatientOrder = order; // labProvider.getPatientLabResultByHospital(order); // labProvider.getPatientSpecialResult(order); // Navigator.of(context).push( // CustomPageRoute(page: LabResultByClinic(labOrder: order)), // ); // }), // ) Expanded( flex: 2, child: CustomButton( icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, text: LocaleKeys.viewResults.tr(context: context), onPressed: () { model.currentlySelectedPatientOrder = order; labProvider.getPatientLabResultByHospital(order); labProvider.getPatientSpecialResult(order); Navigator.of(context).push( CustomPageRoute(page: LabResultByClinic(labOrder: order)), ); }, backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, fontSize: 14, fontWeight: FontWeight.w500, borderRadius: 12, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ) ], ), // SizedBox(height: 12.h), // Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), // SizedBox(height: 12.h), ], ).paddingOnly(top: 16, bottom: 16); }, separatorBuilder: (cxt, index) => Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), itemCount: group.length)) : SizedBox.shrink(), ), ], ), ), ), ), )); }, ) : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noLabResults.tr(context: context))) : // By Test or other tabs keep existing behavior (model.isLabOrdersLoading) ? Column( children: List.generate( 5, (index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, )), ) : AlphabeticScroll( alpahbetsAvailable: model.indexedCharacterForUniqueTest, details: model.uniqueTestsList, labViewModel: model, rangeViewModel: rangeViewModel, appState: _appState, ) ], ) ); }, ), ); } Color getLabOrderStatusColor(num status) { switch (status) { case 44: return AppColors.warningColorYellow; case 45: return AppColors.warningColorYellow; case 16: return AppColors.successColor; case 17: return AppColors.successColor; default: return AppColors.greyColor; } } String getLabOrderStatusText(num status) { switch (status) { case 44: return LocaleKeys.resultsPending.tr(context: context); case 45: return LocaleKeys.resultsPending.tr(context: context); case 16: return LocaleKeys.resultsAvailable.tr(context: context); case 17: return LocaleKeys.resultsAvailable.tr(context: context); default: return ""; } } getLabSuggestions(LabViewModel model) { if (model.patientLabOrders.isEmpty) { return []; } return model.patientLabOrders.map((m) => m.testDetails).toList(); } } \ No newline at end of file +import 'dart:async'; import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart'; import 'package:hmg_patient_app_new/presentation/lab/search_lab_report.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_toolbar.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/chip/custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; import 'alphabeticScroll.dart'; class LabOrdersPage extends StatefulWidget { const LabOrdersPage({super.key}); @override State createState() => _LabOrdersPageState(); } class _LabOrdersPageState extends State { late LabViewModel labProvider; late DateRangeSelectorRangeViewModel rangeViewModel; late AppState _appState; List?> labSuggestions = []; int? expandedIndex; String? selectedFilterText = ''; int activeIndex = 0; @override void initState() { scheduleMicrotask(() { labProvider.initLabProvider(); }); super.initState(); } @override Widget build(BuildContext context) { labProvider = Provider.of(context, listen: false); rangeViewModel = Provider.of(context); _appState = getIt(); return CollapsingListView( title: LocaleKeys.labResults.tr(context: context), search: () async { final lavVM = Provider.of(context, listen: false); if (lavVM.isLabOrdersLoading) { return; } else { String? value = await Navigator.of(context).push( CustomPageRoute( page: SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions), fullScreenDialog: true, direction: AxisDirection.down, ), ); if (value != null) { selectedFilterText = value; lavVM.filterLabReports(value); } } }, child: Consumer( builder: (context, model, child) { return SingleChildScrollView( physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.all(24.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: CustomTabBar( activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ CustomTabBarModel(null, LocaleKeys.byVisit.tr()), CustomTabBarModel(null, LocaleKeys.byTest.tr()), // CustomTabBarModel(null, "Completed".needTranslation), ], onTabChange: (index) { activeIndex = index; setState(() {}); }, ), ), ], ), if (activeIndex == 0) Padding( padding: EdgeInsets.symmetric(vertical: 10.h), child: Row( children: [ CustomButton( text: LocaleKeys.byClinic.tr(context: context), onPressed: () { model.setIsSortByClinic(true); }, backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), SizedBox(width: 8.h), CustomButton( text: LocaleKeys.byHospital.tr(context: context), onPressed: () { model.setIsSortByClinic(false); }, backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ], ), ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? // By Visit - show grouped view when available model.isLabOrdersLoading ? ListView.builder( shrinkWrap: true, physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: 5, itemBuilder: (context, index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ), ) : (model.patientLabOrdersViewList.isNotEmpty ? ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.patientLabOrdersViewList.length, itemBuilder: (context, index) { final group = model.patientLabOrdersViewList[index]; final isExpanded = expandedIndex == index; return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: AnimatedContainer( duration: Duration(milliseconds: 300), curve: Curves.easeInOut, margin: EdgeInsets.symmetric(vertical: 8.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), child: InkWell( onTap: () { setState(() { expandedIndex = isExpanded ? null : index; }); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget(labelText: "${group.length} ${LocaleKeys.results.tr(context: context)}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), SizedBox(height: 8.h), Text( model.isSortByClinic ? (group.first.clinicDescription ?? 'Unknown') : (group.first.projectName ?? 'Unknown'), style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis, ), ], ), ), AnimatedSwitcher( duration: Duration(milliseconds: 500), switchInCurve: Curves.easeIn, switchOutCurve: Curves.easeOut, transitionBuilder: (Widget child, Animation animation) { return FadeTransition( opacity: animation, child: SizeTransition( sizeFactor: animation, axisAlignment: 0.0, child: child, ), ); }, child: isExpanded ? Container( key: ValueKey(index), padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h), child: ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemBuilder: (cxt, index) { PatientLabOrdersResponseModel order = group[index]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Image.network( order.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png", width: 24.w, height: 24.h, fit: BoxFit.cover, ).circle(100), SizedBox(width: 8.h), Expanded(child: (order.doctorName ?? order.doctorNameEnglish ?? "").toString().toText14(weight: FontWeight.w500)), ], ), SizedBox(height: 8.h), Wrap( direction: Axis.horizontal, spacing: 4.h, runSpacing: 4.h, children: [ AppCustomChipWidget( labelText: ("${LocaleKeys.orderNo.tr(context: context)}: ${order.orderNo!}"), ), AppCustomChipWidget( labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), ), AppCustomChipWidget( labelText: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), ), ], ), // Row( // children: [ // CustomButton( // text: ("Order No: ".needTranslation + order.orderNo!), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // SizedBox(width: 8.h), // CustomButton( // text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), // SizedBox(height: 8.h), // Row( // children: [ // CustomButton( // text: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), SizedBox(height: 12.h), Row( children: [ Expanded(flex: 2, child: SizedBox()), // Expanded( // flex: 1, // child: Container( // height: 40.h, // width: 40.w, // decoration: RoundedRectangleBorder().toSmoothCornerDecoration( // color: AppColors.textColor, // borderRadius: 12, // ), // child: Padding( // padding: EdgeInsets.all(12.h), // child: Transform.flip( // flipX: _appState.isArabic(), // child: Utils.buildSvgWithAssets( // icon: AppAssets.forward_arrow_icon_small, // iconColor: AppColors.whiteColor, // fit: BoxFit.contain, // ), // ), // ), // ).onPress(() { // model.currentlySelectedPatientOrder = order; // labProvider.getPatientLabResultByHospital(order); // labProvider.getPatientSpecialResult(order); // Navigator.of(context).push( // CustomPageRoute(page: LabResultByClinic(labOrder: order)), // ); // }), // ) Expanded( flex: 2, child: CustomButton( icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, text: LocaleKeys.viewResults.tr(context: context), onPressed: () { model.currentlySelectedPatientOrder = order; labProvider.getPatientLabResultByHospital(order); labProvider.getPatientSpecialResult(order); Navigator.of(context).push( CustomPageRoute(page: LabResultByClinic(labOrder: order)), ); }, backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, fontSize: 14, fontWeight: FontWeight.w500, borderRadius: 12, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ) ], ), // SizedBox(height: 12.h), // Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), // SizedBox(height: 12.h), ], ).paddingOnly(top: 16, bottom: 16); }, separatorBuilder: (cxt, index) => Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), itemCount: group.length)) : SizedBox.shrink(), ), ], ), ), ), ), )); }, ) : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noLabResults.tr(context: context))) : // By Test or other tabs keep existing behavior (model.isLabOrdersLoading) ? Column( children: List.generate( 5, (index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, )), ) : AlphabeticScroll( alpahbetsAvailable: model.indexedCharacterForUniqueTest, details: model.uniqueTestsList, labViewModel: model, rangeViewModel: rangeViewModel, appState: _appState, ) ], )); }, ), ); } Color getLabOrderStatusColor(num status) { switch (status) { case 44: return AppColors.warningColorYellow; case 45: return AppColors.warningColorYellow; case 16: return AppColors.successColor; case 17: return AppColors.successColor; default: return AppColors.greyColor; } } String getLabOrderStatusText(num status) { switch (status) { case 44: return LocaleKeys.resultsPending.tr(context: context); case 45: return LocaleKeys.resultsPending.tr(context: context); case 16: return LocaleKeys.resultsAvailable.tr(context: context); case 17: return LocaleKeys.resultsAvailable.tr(context: context); default: return ""; } } getLabSuggestions(LabViewModel model) { if (model.patientLabOrders.isEmpty) { return []; } return model.patientLabOrders.map((m) => m.testDetails).toList(); } } \ No newline at end of file diff --git a/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart b/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart index 50fd1f1..954c09b 100644 --- a/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart +++ b/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart @@ -1,17 +1,22 @@ -import 'package:easy_localization/easy_localization.dart' - show tr, StringTranslateExtension; +import 'package:easy_localization/easy_localization.dart' show tr, StringTranslateExtension; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultList.dart'; +import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/lab_order_specialResult.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -25,6 +30,7 @@ class LabResultByClinic extends StatelessWidget { late LabViewModel labViewModel; PatientLabOrdersResponseModel labOrder; + @override Widget build(BuildContext context) { labViewModel = Provider.of(context, listen: false); @@ -35,6 +41,21 @@ class LabResultByClinic extends StatelessWidget { Expanded( child: CollapsingListView( title: LocaleKeys.labResults.tr(), + aiOverview: () async { + final _dialogService = getIt.get(); + await _dialogService.showCommonBottomSheetWithoutH( + message: LocaleKeys.aiDisclaimer.tr(), + label: LocaleKeys.consent.tr(), + okLabel: LocaleKeys.acceptLbl.tr(), + cancelLabel: LocaleKeys.rejectView.tr(), + onOkPressed: () { + context.pop(); + labViewModel.getAiOverviewLabOrders(labOrder: labOrder); + }, + onCancelPressed: () { + context.pop(); + }); + }, child: SingleChildScrollView( child: Column( spacing: 8.h, @@ -77,7 +98,7 @@ class LabResultByClinic extends StatelessWidget { } }, ), - LabOrderSpecialResult() + LabOrderSpecialResult(), ], ).paddingAll(24.h), )), diff --git a/lib/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart b/lib/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart new file mode 100644 index 0000000..a2d0ff6 --- /dev/null +++ b/lib/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart @@ -0,0 +1,100 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; + +class AiAnalysisWidget extends StatelessWidget { + final LabOrderResponseByAi data; + + const AiAnalysisWidget({super.key, required this.data}); + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration(borderRadius: BorderRadius.circular(24.r), gradient: AppColors.aiLinearGradient), + padding: EdgeInsets.all(1.5.r), // Border thickness + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(22.r), + ), + padding: EdgeInsets.all(20.r), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + LocaleKeys.aiAnalysis.tr().toText18(weight: FontWeight.w700, color: AppColors.blackColor), + Container( + padding: EdgeInsets.all(8.r), + decoration: BoxDecoration(gradient: AppColors.aiLinearGradient, borderRadius: BorderRadius.circular(8.r)), + child: SvgPicture.asset(AppAssets.aiOverView, colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn), height: 18.r, width: 18.r), + ), + ], + ), + SizedBox(height: 16.h), + if (data.summary != null && data.summary!.isNotEmpty) ...[ + LocaleKeys.suggestion.tr().toText16(weight: FontWeight.w700, color: AppColors.blackColor), + SizedBox(height: 8.h), + data.summary!.toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400), + SizedBox(height: 16.h), + const Divider(color: AppColors.dividerColor, thickness: 1), + SizedBox(height: 16.h), + ], + if (data.aiPredictions != null && data.aiPredictions!.isNotEmpty) ...[ + LocaleKeys.prediction.tr().toText16(weight: FontWeight.w700, color: AppColors.blackColor), + SizedBox(height: 12.h), + ...data.aiPredictions!.map((item) => _buildBulletItem(item)), + SizedBox(height: 16.h), + const Divider(color: AppColors.dividerColor, thickness: 1), + SizedBox(height: 16.h), + ], + if (data.prevention != null && data.prevention!.isNotEmpty) ...[ + LocaleKeys.prevention.tr().toText16(weight: FontWeight.w700, color: AppColors.blackColor), + SizedBox(height: 12.h), + ...data.prevention!.map((item) => _buildBulletItem(item)), + SizedBox(height: 20.h), + ], + Row( + children: [ + Icon(Icons.info_outline, color: AppColors.greyTextColor, size: 20.r), + SizedBox(width: 8.w), + Expanded( + child: ("${LocaleKeys.disclaimer.tr()}:${LocaleKeys.thisAboveInfo.tr()}").toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w400), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildBulletItem(String text) { + return Padding( + padding: EdgeInsets.only(bottom: 12.h), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.only(top: 8.h, right: 12.w, left: 4.w), + child: Container( + width: 5.r, + height: 5.r, + decoration: const BoxDecoration(color: AppColors.blackColor, shape: BoxShape.circle), + ), + ), + Expanded( + child: text.toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/lab/lab_results/lab_result_details.dart b/lib/presentation/lab/lab_results/lab_result_details.dart index 29e15ee..c67c39d 100644 --- a/lib/presentation/lab/lab_results/lab_result_details.dart +++ b/lib/presentation/lab/lab_results/lab_result_details.dart @@ -1,45 +1,72 @@ - import 'package:easy_localization/easy_localization.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/lab_result.dart'; +import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/date_range_calender.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_results/lab_result_list_item.dart'; import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart'; -import 'package:provider/provider.dart' show Consumer, Provider, ReadContext; +import 'package:provider/provider.dart' show Consumer, Provider, ReadContext, Selector; -import '../../../widgets/common_bottom_sheet.dart' - show showCommonBottomSheetWithoutHeight; +import '../../../widgets/common_bottom_sheet.dart' show showCommonBottomSheetWithoutHeight; class LabResultDetails extends StatelessWidget { final LabResult recentLabResult; final String? testDescription; - const LabResultDetails( - {super.key, - required this.recentLabResult, - required this.testDescription}); + const LabResultDetails({super.key, required this.recentLabResult, required this.testDescription}); @override Widget build(BuildContext context) { + LabViewModel labViewModel = Provider.of(context, listen: false); + final appState = getIt.get(); return CollapsingListView( title: LocaleKeys.labResultDetails.tr(context: context), + aiOverview: () async { + final _dialogService = getIt.get(); + await _dialogService.showCommonBottomSheetWithoutH( + message: LocaleKeys.aiDisclaimer.tr(), + label: LocaleKeys.consent.tr(), + okLabel: LocaleKeys.acceptLbl.tr(), + cancelLabel: LocaleKeys.rejectView.tr(), + onOkPressed: () { + context.pop(); + labViewModel.getAiOverviewSingleLabResult(langId: appState.getLanguageID().toString(), recentLabResult: recentLabResult); + }, + onCancelPressed: () { + context.pop(); + }); + }, child: SingleChildScrollView( child: Column( spacing: 16.h, children: [ LabNameAndStatus(context), getLabDescription(context), - LabGraph(context) + LabGraph(context), + Selector( + selector: (_, model) => model.labOrderResponseByAi, + builder: (_, aiData, __) { + if (aiData != null) { + return AiAnalysisWidget(data: aiData).paddingOnly(bottom: 16.h); + } + return const SizedBox.shrink(); + }, + ), ], ).paddingAll(24.h), ), @@ -47,11 +74,7 @@ class LabResultDetails extends StatelessWidget { } Widget LabNameAndStatus(BuildContext context) => Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.h, - hasShadow: true, - ), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -107,7 +130,9 @@ class LabResultDetails extends StatelessWidget { ), letterSpacing: -2), ), - SizedBox(width: 4.h,), + SizedBox( + width: 4.h, + ), ], ), ), @@ -150,9 +175,7 @@ class LabResultDetails extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - labmodel.isGraphVisible - ? LocaleKeys.historyFlowchart.tr(context: context) - : LocaleKeys.history.tr(context: context), + labmodel.isGraphVisible ? LocaleKeys.historyFlowchart.tr(context: context) : LocaleKeys.history.tr(context: context), style: TextStyle( fontSize: 16, fontFamily: 'Poppins', @@ -164,22 +187,12 @@ class LabResultDetails extends StatelessWidget { spacing: 16.h, children: [ //todo handle when the graph icon is being displayed - Utils.buildSvgWithAssets( - icon: labmodel.isGraphVisible - ? AppAssets.ic_list - : AppAssets.ic_graph, - width: 24.h, - height: 24.h) - .onPress(() { + Utils.buildSvgWithAssets(icon: labmodel.isGraphVisible ? AppAssets.ic_list : AppAssets.ic_graph, width: 24.h, height: 24.h).onPress(() { if (labmodel.shouldShowGraph) { labmodel.alterGraphVisibility(); } }), - Utils.buildSvgWithAssets( - icon: AppAssets.ic_date_filter, - width: 24, - height: 24) - .onPress(() { + Utils.buildSvgWithAssets(icon: AppAssets.ic_date_filter, width: 24, height: 24).onPress(() { showCommonBottomSheetWithoutHeight( title: LocaleKeys.setTheDateRange.tr(context: context), context, @@ -218,21 +231,17 @@ class LabResultDetails extends StatelessWidget { Widget buildBottomLabel(String label) { return Padding( - padding: const EdgeInsets.only(top:8.0), + padding: const EdgeInsets.only(top: 8.0), child: Text( label, - style: TextStyle( - fontSize: 8.f, - fontFamily: 'Poppins', - fontWeight: FontWeight.w600, - color: AppColors.labelTextColor), + style: TextStyle(fontSize: 8.f, fontFamily: 'Poppins', fontWeight: FontWeight.w600, color: AppColors.labelTextColor), ), ); } Widget historyBody(LabViewModel labmodel) { if (labmodel.isGraphVisible && labmodel.shouldShowGraph) { - var graphColor = labmodel.getColor(recentLabResult.calculatedResultFlag??"N"); + var graphColor = labmodel.getColor(recentLabResult.calculatedResultFlag ?? "N"); return CustomGraph( dataPoints: labmodel.filteredGraphValues, makeGraphBasedOnActualValue: true, @@ -242,11 +251,11 @@ class LabResultDetails extends StatelessWidget { // maxY: (labmodel.maxY)+(getInterval(labmodel)??0)/2, maxY: (labmodel.maxY), minY: labmodel.minY, - maxX: labmodel.filteredGraphValues.length.toDouble()-.75, + maxX: labmodel.filteredGraphValues.length.toDouble() - .75, horizontalInterval: .1, - getDrawingHorizontalLine: (value){ + getDrawingHorizontalLine: (value) { value = double.parse(value.toStringAsFixed(1)); - if(value == labmodel.highRefrenceValue ||value== labmodel.lowRefenceValue) { + if (value == labmodel.highRefrenceValue || value == labmodel.lowRefenceValue) { return FlLine( color: AppColors.bgGreenColor.withOpacity(0.6), strokeWidth: 1, @@ -256,7 +265,8 @@ class LabResultDetails extends StatelessWidget { return FlLine( color: Colors.transparent, strokeWidth: 1, - );; + ); + ; }, leftLabelFormatter: (value) { value = double.parse(value.toStringAsFixed(1)); @@ -272,11 +282,11 @@ class LabResultDetails extends StatelessWidget { return SizedBox.shrink(); // } }, - graphColor:AppColors.blackColor, + graphColor: AppColors.blackColor, graphShadowColor: Colors.transparent, graphGridColor: graphColor.withOpacity(.4), bottomLabelFormatter: (value, data) { - if(data.isEmpty) return SizedBox.shrink(); + if (data.isEmpty) return SizedBox.shrink(); if (value == 0) { return buildBottomLabel(data[value.toInt()].label); } @@ -288,34 +298,34 @@ class LabResultDetails extends StatelessWidget { } return SizedBox.shrink(); }, - rangeAnnotations: RangeAnnotations( - horizontalRangeAnnotations: _buildRangeShades(labmodel) - ), - minX:(labmodel.filteredGraphValues.length == 1)?null : -.2, + rangeAnnotations: RangeAnnotations(horizontalRangeAnnotations: _buildRangeShades(labmodel)), + minX: (labmodel.filteredGraphValues.length == 1) ? null : -.2, scrollDirection: Axis.horizontal, height: 180.h); - }else { + } else { return labHistoryList(labmodel); } } - List _buildRangeShades( LabViewModel model,) { + List _buildRangeShades( + LabViewModel model, + ) { List ranges = []; - ranges.add(HorizontalRangeAnnotation( - y1:model.minY, - y2: model.lowRefenceValue, - color: AppColors.highAndLow.withOpacity(0.05), - )); + ranges.add(HorizontalRangeAnnotation( + y1: model.minY, + y2: model.lowRefenceValue, + color: AppColors.highAndLow.withOpacity(0.05), + )); ranges.add(HorizontalRangeAnnotation( - y1:model.lowRefenceValue, + y1: model.lowRefenceValue, y2: model.highRefrenceValue, color: AppColors.bgGreenColor.withOpacity(0.05), )); ranges.add(HorizontalRangeAnnotation( - y1:model.highRefrenceValue, + y1: model.highRefrenceValue, y2: model.maxY, color: AppColors.criticalLowAndHigh.withOpacity(0.05), )); @@ -324,11 +334,12 @@ class LabResultDetails extends StatelessWidget { Widget labHistoryList(LabViewModel labmodel) { return SizedBox( - height: labmodel.filteredGraphValues.length<3?labmodel.filteredGraphValues.length*64:180.h, + height: labmodel.filteredGraphValues.length < 3 ? labmodel.filteredGraphValues.length * 64 : 180.h, child: ListView.separated( padding: EdgeInsets.zero, - itemCount: labmodel.filteredGraphValues.length,itemBuilder: (context, index){ - var data = labmodel.filteredGraphValues.reversed.toList()[index]; + itemCount: labmodel.filteredGraphValues.length, + itemBuilder: (context, index) { + var data = labmodel.filteredGraphValues.reversed.toList()[index]; return LabHistoryItem( dayNameAndDate: labmodel.getFormattedDate(data.time), result: data.actualValue, @@ -368,11 +379,8 @@ class LabResultDetails extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, spacing: 8.h, children: [ - LocaleKeys.whatIsThisResult.tr(context: context) - .toText16(weight: FontWeight.w600, color: AppColors.textColor), - testDescription?.toText12( - fontWeight: FontWeight.w500, color: AppColors.textColorLight) ?? - SizedBox.shrink() + LocaleKeys.whatIsThisResult.tr(context: context).toText16(weight: FontWeight.w600, color: AppColors.textColor), + testDescription?.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight) ?? SizedBox.shrink() ], )); } diff --git a/lib/presentation/labAiAnalysis/lab_ai_analysis_detailed_page.dart b/lib/presentation/labAiAnalysis/lab_ai_analysis_detailed_page.dart new file mode 100644 index 0000000..5a5aed7 --- /dev/null +++ b/lib/presentation/labAiAnalysis/lab_ai_analysis_detailed_page.dart @@ -0,0 +1,538 @@ +import 'dart:convert'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/expandable_list_widget.dart'; +import 'package:provider/provider.dart'; + +import '../../features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart'; + +class LabAiAnalysisDetailedPage extends StatefulWidget { + const LabAiAnalysisDetailedPage({super.key}); + + @override + State createState() => _LabAiAnalysisDetailedPageState(); +} + +class _LabAiAnalysisDetailedPageState extends State { + late LabViewModel labProvider; + + @override + Widget build(BuildContext context) { + labProvider = Provider.of(context, listen: false); + return CollapsingListView( + title: LocaleKeys.aiAnalysis.tr(context: context), + child: Consumer( + builder: (context, model, child) { + if (model.labOrdersResponseByAi == null || model.labOrdersResponseByAi?.analysis == null) { + return Utils.getNoDataWidget(context); + } + + final analysis = model.labOrdersResponseByAi!.analysis!; + List expandableItems = []; + + // Summary Section + if (analysis.summary != null && analysis.summary!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.summary.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + initiallyExpanded: true, + children: [ + SizedBox(height: 10.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFF0B85F7))), + padding: EdgeInsets.all(16.r), + child: (analysis.summary ?? "").toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400), + ), + SizedBox(height: 8.h), + ], + ), + ); + } + + // AI Generated Attributes Section (Lab Test Results) + if (analysis.aiGeneratedAttributes != null && analysis.aiGeneratedAttributes!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.labResults.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + children: [ + SizedBox(height: 10.h), + ...analysis.aiGeneratedAttributes!.map((attr) { + return Column( + children: [ + _buildCombinedLabCard(attr), + SizedBox(height: 16.h), + ], + ); + }).toList(), + ], + ), + ); + } + + // AI Predictions Section + if (analysis.aiPredictions != null && analysis.aiPredictions!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.prediction.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + children: [ + SizedBox(height: 10.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFFFFAF15))), + padding: EdgeInsets.all(16.r), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: analysis.aiPredictions!.map((prediction) => _buildBulletItem(prediction)).toList(), + ), + ), + SizedBox(height: 8.h), + ], + ), + ); + } + + // AI Recommendations Section + if (analysis.aiRecommendations != null && analysis.aiRecommendations!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.suggestions.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + children: [ + SizedBox(height: 10.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r), + padding: EdgeInsets.all(16.r), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: analysis.aiRecommendations!.asMap().entries.map((entry) { + final rec = entry.value; + final isLast = entry.key == analysis.aiRecommendations!.length - 1; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (rec.priority != null) ...[ + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: _getPriorityColor(rec.priority), borderRadius: BorderRadius.circular(4.r)), + child: rec.priority!.toText12(fontWeight: FontWeight.w600, color: _getPriorityTextColor(rec.priority)), + ), + SizedBox(height: 8.h), + ], + (rec.recommendation ?? "").toText14( + color: AppColors.textColorLight, + height: 1.5, + weight: FontWeight.w400, + ), + if (!isLast) ...[ + SizedBox(height: 12.h), + const Divider(color: AppColors.dividerColor, thickness: 1), + SizedBox(height: 12.h), + ], + ], + ); + }).toList(), + ), + ), + SizedBox(height: 8.h), + ], + ), + ); + } + + // Risk Factors Section + if (analysis.riskFactors != null && analysis.riskFactors!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.riskFactors.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + children: [ + SizedBox(height: 10.h), + ...analysis.riskFactors!.asMap().entries.map((entry) { + final risk = entry.value; + return Column( + children: [ + Container( + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration(color: Color(0xFFFBCB6E).withOpacity(0.10), borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFFFBCB6E).withOpacity(0.10))), + padding: EdgeInsets.all(16.r), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Container( + decoration: BoxDecoration(color: Color(0xFFFBCB6E).withAlpha(38), borderRadius: BorderRadius.circular(8)), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: (risk.risk ?? "").toText10(weight: FontWeight.w500, color: AppColors.blackColor), + ), + ), + ), + ], + ), + if (risk.risk != null && risk.risk!.isNotEmpty) ...[ + SizedBox(height: 4.h), + Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.guradIcon), + Padding( + padding: const EdgeInsets.all(8.0), + child: (risk.factor ?? "").toText16(weight: FontWeight.w700, color: AppColors.blackColor), + ), + ], + ), + SizedBox(height: 4.h), + (risk.description ?? "").toText14( + color: AppColors.textColorLight, + height: 1.5, + weight: FontWeight.w400, + ), + ], + if (risk.description != null && risk.description!.isNotEmpty) ...[ + SizedBox(height: 8.h), + (risk.description ?? "").toText14( + color: AppColors.textColorLight, + height: 1.5, + weight: FontWeight.w400, + ), + ], + ], + ), + ), + SizedBox(height: 16.h), + ], + ); + }).toList(), + ], + ), + ); + } + + // Prevention Section + if (analysis.prevention != null && analysis.prevention!.isNotEmpty) { + expandableItems.add( + ExpandableListItem( + title: LocaleKeys.prevention.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor), + children: [ + SizedBox(height: 10.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFF18C273))), + padding: EdgeInsets.all(16.r), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: analysis.prevention!.map((prevention) => _buildBulletItem(prevention)).toList(), + ), + ), + SizedBox(height: 8.h), + ], + ), + ); + } + + // // Suggested Doctors Section + // if (analysis.suggestedDoctors != null && analysis.suggestedDoctors!.isNotEmpty) { + // expandableItems.add( + // ExpandableListItem( + // title: "Suggested Doctors".toText18(weight: FontWeight.w700, color: AppColors.blackColor), + // children: [ + // SizedBox(height: 10.h), + // Container( + // decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + // color: AppColors.whiteColor, + // borderRadius: 12.r, + // side: BorderSide(width: 1, color: Color(0xFF3498DB)), + // ), + // padding: EdgeInsets.all(16.r), + // child: Column( + // crossAxisAlignment: CrossAxisAlignment.start, + // children: analysis.suggestedDoctors!.asMap().entries.map((entry) { + // final doctor = entry.value; + // final isLast = entry.key == analysis.suggestedDoctors!.length - 1; + // return Column( + // crossAxisAlignment: CrossAxisAlignment.start, + // children: [ + // Row( + // children: [ + // Container( + // width: 40.r, + // height: 40.r, + // decoration: BoxDecoration( + // gradient: AppColors.aiLinearGradient, + // shape: BoxShape.circle, + // ), + // child: Icon( + // Icons.person, + // color: Colors.white, + // size: 24.r, + // ), + // ), + // SizedBox(width: 12.w), + // Expanded( + // child: doctor.toString().toText14( + // color: AppColors.textColorLight, + // height: 1.5, + // weight: FontWeight.w600, + // ), + // ), + // ], + // ), + // if (!isLast) ...[ + // SizedBox(height: 12.h), + // const Divider(color: AppColors.dividerColor, thickness: 1), + // SizedBox(height: 12.h), + // ], + // ], + // ); + // }).toList(), + // ), + // ), + // SizedBox(height: 8.h), + // ], + // ), + // ); + // } + + return Column( + children: [ + if (expandableItems.isEmpty) + Utils.getNoDataWidget(context) + else + CustomExpandableList( + expansionMode: ExpansionMode.exactlyOne, + dividerColor: Color(0xff2b353e1a), + itemPadding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 14.h), + items: expandableItems, + theme: ExpandableListTheme.custom( + defaultTrailingIcon: Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 22.h, width: 22.w, iconColor: AppColors.textColor), + ), + ).paddingSymmetrical(16.w, 0.0), + ], + ); + }, + ), + ); + } + + Color _getPriorityColor(String? priority) { + if (priority == null) return AppColors.primaryRedColor; + switch (priority.toLowerCase()) { + case 'high': + return Color(0xFFED1C2B).withOpacity(.10); + case 'medium' || 'moderate': + return AppColors.lightGreenButtonColor; + case 'low': + return AppColors.warningColorYellow.withOpacity(.3); + default: + return AppColors.primaryRedColor; + } + } + + Color _getPriorityTextColor(String? priority) { + if (priority == null) return AppColors.whiteColor; + switch (priority.toLowerCase()) { + case 'high': + return AppColors.primaryRedColor; + case 'medium' || 'moderate': + return AppColors.lightGreenColor; + case 'low': + return AppColors.alertColor; + default: + return AppColors.primaryRedColor; + } + } + + + + Color _getResultFlagColor(String? flag) { + if (flag == null || flag.isEmpty) return Colors.grey; + switch (flag.toUpperCase()) { + case 'H': // High + case 'HH': // Very High + case 'CRITICAL HIGH': + return AppColors.lightRedButtonColor; + case 'L': // Low + case 'LL': // Very Low + case 'CRITICAL LOW': + return AppColors.chipColorSeekMedicalAdvice; + case 'N': // Normal + return AppColors.lightGreenButtonColor; + case 'A': // Abnormal + return Colors.deepOrange; + default: + return AppColors.greyLightColor; + } + } + + Color _getResultTextColor(String? priority) { + if (priority == null) return AppColors.whiteColor; + switch (priority.toUpperCase()) { + case 'H': // High + case 'HH': // Very High + case 'CRITICAL HIGH': + return AppColors.primaryRedColor; + case 'N': + return AppColors.lightGreenColor; + case 'L': // Low + case 'LL': // Very Low + case 'CRITICAL LOW': + return AppColors.chipTextColorSeekMedicalAdvice; + default: + return AppColors.textColor; + } + } + + Widget _buildBulletItem(String text) { + return Padding( + padding: EdgeInsets.only(bottom: 12.h), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: text.toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400), + ), + ], + ), + ); + } + + Widget _buildCombinedLabCard(AiGeneratedAttribute attr) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 2.h, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty && attr.calculatedResultFlag == "-") ...[ + Row( + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)), + child: Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.informationIcon, width: 14.w, height: 14.h), + SizedBox(width: 4.w), + LocaleKeys.contextDependent.tr().toText12(fontWeight: FontWeight.w600, color: AppColors.textColor), + ], + ), + ), + ], + ), + ] else ...[ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: _getResultFlagColor(attr.calculatedResultFlag), borderRadius: BorderRadius.circular(4.r)), + child: Row( + children: [ + (attr.calculatedResultFlag ?? "").toText12(fontWeight: FontWeight.w600, color: _getResultTextColor(attr.calculatedResultFlag)), + ], + ), + ), + if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty && attr.calculatedResultFlag == "H") + Utils.buildSvgWithAssets(icon: AppAssets.highCautionIcon, iconColor: AppColors.primaryRedColor, width: 24.w, height: 24.h), + ], + ), + ], + SizedBox(height: 4.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded(child: (attr.description ?? "").toText16(isBold: true, color: _getResultTextColor(attr.calculatedResultFlag))), + + // if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty) + // Column( + // spacing: 2.h, + // children: [ + // Consumer( + // builder: (context, labViewModel, child) { + // return labViewModel.getSeverityText(attr.calculatedResultFlag ?? "").tr(context: context).toText10(weight: FontWeight.w500, color: AppColors.greyTextColor); + // }, + // ), + // Consumer( + // builder: (context, labViewModel, child) { + // return Utils.buildSvgWithAssets( + // icon: AppAssets.lab_result_indicator, + // width: 21, + // height: 23, + // iconColor: labViewModel.getColor(attr.calculatedResultFlag ?? ""), + // ); + // }, + // ), + // ], + // ), + ], + ), + SizedBox(height: 4.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded(child: (attr.testShortDescription ?? "").toText12(color: AppColors.textColor)), + ], + ), + SizedBox(height: 4.h) + ], + ), + Row( + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: _getResultFlagColor(attr.calculatedResultFlag), borderRadius: BorderRadius.circular(4.r)), + child: ("${LocaleKeys.calculatedValue.tr()}: ${attr.resultValue!}").toText12(fontWeight: FontWeight.w600, color: _getResultTextColor(attr.calculatedResultFlag)), + ), + SizedBox(width: 8.h), + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)), + child: ("${LocaleKeys.unit.tr()}: ${attr.uom!}").toText12(fontWeight: FontWeight.w600, color: AppColors.textColor), + ), + ], + ), + SizedBox( + height: 4.h, + ), + if (attr.referanceRange != null && attr.referanceRange!.isNotEmpty) + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)), + child: ("${LocaleKeys.referenceRange.tr(context: context)}: ${attr.referanceRange!.trim()}").toText12(fontWeight: FontWeight.w600, color: AppColors.textColor), + ), + if (attr.calculationFormula != null && attr.calculationFormula!.isNotEmpty) ...[ + SizedBox(height: 8.h), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.calendar, iconColor: Colors.grey), + SizedBox(width: 8.w), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + LocaleKeys.calculationFormula.tr().toText16(weight: FontWeight.w600), + (attr.calculationFormula ?? "").toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + ], + ), + ), + ], + ), + ], + ], + ), + ); + } +} diff --git a/lib/services/dialog_service.dart b/lib/services/dialog_service.dart index b185d89..502afac 100644 --- a/lib/services/dialog_service.dart +++ b/lib/services/dialog_service.dart @@ -23,7 +23,7 @@ abstract class DialogService { Future showExceptionBottomSheet({required String message, required Function() onOkPressed, Function()? onCancelPressed}); - Future showCommonBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}); + Future showCommonBottomSheetWithoutH({String? label, required String message, String? okLabel, String? cancelLabel, required Function() onOkPressed, Function()? onCancelPressed}); Future showSuccessBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}); @@ -114,13 +114,20 @@ class DialogServiceImp implements DialogService { } @override - Future showCommonBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}) async { + Future showCommonBottomSheetWithoutH({String? label, required String message, String? okLabel, String? cancelLabel, required Function() onOkPressed, Function()? onCancelPressed}) async { final context = navigationService.navigatorKey.currentContext; if (context == null) return; showCommonBottomSheetWithoutHeight( context, title: label ?? "", - child: exceptionBottomSheetWidget(context: context, message: message, onOkPressed: onOkPressed, onCancelPressed: onCancelPressed), + child: exceptionBottomSheetWidget( + context: context, + message: message, + okLabel: okLabel, + cancelLabel: cancelLabel, + onOkPressed: onOkPressed, + onCancelPressed: onCancelPressed, + ), callBackFunc: () {}, ); } @@ -228,7 +235,7 @@ class DialogServiceImp implements DialogService { } } -Widget exceptionBottomSheetWidget({required BuildContext context, required String message, required Function() onOkPressed, Function()? onCancelPressed}) { +Widget exceptionBottomSheetWidget({required BuildContext context, required String message, String? okLabel, String? cancelLabel, required Function() onOkPressed, Function()? onCancelPressed}) { return Column( children: [ (message).toText16(isBold: false, color: AppColors.textColor), @@ -239,7 +246,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(context: context), + text: cancelLabel ?? LocaleKeys.cancel.tr(context: context), onPressed: () { Navigator.of(context).pop(); }, @@ -253,7 +260,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin SizedBox(width: 10.h), Expanded( child: CustomButton( - text: LocaleKeys.confirm.tr(context: context), + text: okLabel ?? LocaleKeys.confirm.tr(context: context), onPressed: onOkPressed, backgroundColor: AppColors.bgGreenColor, borderColor: AppColors.bgGreenColor, @@ -267,7 +274,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin Padding( padding: EdgeInsets.only(bottom: 10.h), child: CustomButton( - text: LocaleKeys.cancel.tr(context: context), + text: cancelLabel ?? LocaleKeys.cancel.tr(context: context), onPressed: (onCancelPressed == null) ? () { context.pop(); diff --git a/lib/theme/colors.dart b/lib/theme/colors.dart index d56178b..f80085a 100644 --- a/lib/theme/colors.dart +++ b/lib/theme/colors.dart @@ -113,4 +113,6 @@ class AppColors { static const Color covid29Color = Color(0xff2563EB); // #2563EB static const Color lightGreyTextColor = Color(0xFF959595); static const Color labelColorYellow = Color(0xFFFBCB6E); + + static const LinearGradient aiLinearGradient = LinearGradient(colors: [Color(0xFF8A38F5), Color(0xFFE20BBB)], begin: Alignment.topLeft, end: Alignment.bottomRight); } diff --git a/lib/widgets/appbar/collapsing_list_view.dart b/lib/widgets/appbar/collapsing_list_view.dart index 575de03..aaaaa51 100644 --- a/lib/widgets/appbar/collapsing_list_view.dart +++ b/lib/widgets/appbar/collapsing_list_view.dart @@ -19,6 +19,7 @@ class CollapsingListView extends StatelessWidget { VoidCallback? search; VoidCallback? report; VoidCallback? logout; + VoidCallback? aiOverview; VoidCallback? history; VoidCallback? instructions; VoidCallback? requests; @@ -40,6 +41,7 @@ class CollapsingListView extends StatelessWidget { this.bottomChild, this.report, this.logout, + this.aiOverview, this.history, this.instructions, this.requests, @@ -85,9 +87,11 @@ class CollapsingListView extends StatelessWidget { history: history, instructions: instructions, requests: requests, - sendEmail: sendEmail, doctorResponse: doctorResponse, + sendEmail: sendEmail, + doctorResponse: doctorResponse, bottomChild: bottomChild, trailing: trailing, + aiOverview: aiOverview, ), // : null, leading: Visibility( @@ -190,6 +194,7 @@ class ScrollAnimatedTitle extends StatefulWidget implements PreferredSizeWidget VoidCallback? search; VoidCallback? report; VoidCallback? logout; + VoidCallback? aiOverview; VoidCallback? history; VoidCallback? instructions; VoidCallback? requests; @@ -206,6 +211,7 @@ class ScrollAnimatedTitle extends StatefulWidget implements PreferredSizeWidget this.search, this.report, this.logout, + this.aiOverview, this.history, this.instructions, this.requests, @@ -288,6 +294,7 @@ class _ScrollAnimatedTitleState extends State { if (widget.sendEmail != null) actionButton(context, t, title: LocaleKeys.sendEmail.tr(context: context), icon: AppAssets.email).onPress(widget.sendEmail!), if (widget.doctorResponse != null) actionButton(context, t, title: LocaleKeys.doctorResponses.tr(context: context), icon: AppAssets.doctorResponseIcon).onPress(widget.doctorResponse!), if (widget.search != null) Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(widget.search!), + if (widget.aiOverview != null) actionButton(context, t, title: LocaleKeys.aiOverView.tr(context: context), icon: AppAssets.aiOverView, isAiButton: true).onPress(widget.aiOverview!), if (widget.trailing != null) widget.trailing!, ] ], @@ -295,40 +302,77 @@ class _ScrollAnimatedTitleState extends State { ); } - Widget actionButton(BuildContext context, double t, {required String title, required String icon}) { - return AnimatedSize( - duration: Duration(milliseconds: 150), - child: Container( - height: 40.h, - padding: EdgeInsets.all(8.w), - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.secondaryLightRedColor, - borderRadius: 10.r, - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - spacing: 8.h, - children: [ - Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w), - if (t >= .5) - Text( - title, - style: context.dynamicTextStyle( - color: AppColors.primaryRedColor, - letterSpacing: -0.4, - fontSize: (12 - (2 * (1 - t))).f, - fontWeight: FontWeight.lerp( - FontWeight.w400, - FontWeight.w500, - t, - )!, + Widget actionButton(BuildContext context, double t, {required String title, required String icon, bool isAiButton = false}) { + return isAiButton + ? AnimatedSize( + duration: Duration(milliseconds: 150), + child: Center( + child: Container( + height: 40.h, + padding: EdgeInsets.all(8.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.transparent, borderRadius: 10.r, side: BorderSide(width: 1, color: AppColors.borderGrayColor)), + child: ShaderMask( + blendMode: BlendMode.srcIn, + shaderCallback: (bounds) => AppColors.aiLinearGradient.createShader(bounds), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + spacing: 8.h, + children: [ + Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w), + Text( + title, + style: context.dynamicTextStyle( + color: AppColors.primaryRedColor, + letterSpacing: -0.4, + fontSize: (12 - (2 * (1 - t))).f, + fontWeight: FontWeight.lerp( + FontWeight.w400, + FontWeight.w500, + t, + )!, + ), + ), + ], + ), ), ), - ], - ), - ), - ); + ), + ) + : AnimatedSize( + duration: Duration(milliseconds: 150), + child: Container( + height: 40.h, + padding: EdgeInsets.all(8.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.secondaryLightRedColor, + borderRadius: 10.r, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + spacing: 8.h, + children: [ + Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w), + if (t >= .5) + Text( + title, + style: context.dynamicTextStyle( + color: AppColors.primaryRedColor, + letterSpacing: -0.4, + fontSize: (12 - (2 * (1 - t))).f, + fontWeight: FontWeight.lerp( + FontWeight.w400, + FontWeight.w500, + t, + )!, + ), + ), + ], + ), + ), + ); } }