diff --git a/assets/images/svg/add_icon_dark.svg b/assets/images/svg/add_icon_dark.svg new file mode 100644 index 0000000..399df3c --- /dev/null +++ b/assets/images/svg/add_icon_dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/confirm.svg b/assets/images/svg/confirm.svg index 62cfa01..5ed3693 100755 --- a/assets/images/svg/confirm.svg +++ b/assets/images/svg/confirm.svg @@ -1,3 +1,3 @@ - +add_ diff --git a/assets/images/svg/cup_add.svg b/assets/images/svg/cup_add.svg new file mode 100644 index 0000000..ebe186a --- /dev/null +++ b/assets/images/svg/cup_add.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/cup_empty.svg b/assets/images/svg/cup_empty.svg new file mode 100644 index 0000000..fae08fe --- /dev/null +++ b/assets/images/svg/cup_empty.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/cup_filled.svg b/assets/images/svg/cup_filled.svg new file mode 100644 index 0000000..6a085bb --- /dev/null +++ b/assets/images/svg/cup_filled.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/dumbell_icon.svg b/assets/images/svg/dumbell_icon.svg new file mode 100644 index 0000000..1d6db5f --- /dev/null +++ b/assets/images/svg/dumbell_icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/glass_icon.svg b/assets/images/svg/glass_icon.svg new file mode 100644 index 0000000..1df8eec --- /dev/null +++ b/assets/images/svg/glass_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/graph_icon.svg b/assets/images/svg/graph_icon.svg new file mode 100644 index 0000000..7bb6fbb --- /dev/null +++ b/assets/images/svg/graph_icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/green_tick_icon.svg b/assets/images/svg/green_tick_icon.svg new file mode 100644 index 0000000..e041191 --- /dev/null +++ b/assets/images/svg/green_tick_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/height_icon.svg b/assets/images/svg/height_icon.svg new file mode 100644 index 0000000..78cefdc --- /dev/null +++ b/assets/images/svg/height_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/list_icon.svg b/assets/images/svg/list_icon.svg new file mode 100644 index 0000000..e68f20b --- /dev/null +++ b/assets/images/svg/list_icon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/images/svg/minimize_icon.svg b/assets/images/svg/minimize_icon.svg new file mode 100644 index 0000000..b60a041 --- /dev/null +++ b/assets/images/svg/minimize_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/notification_icon_grey.svg b/assets/images/svg/notification_icon_grey.svg new file mode 100644 index 0000000..9e5e8d5 --- /dev/null +++ b/assets/images/svg/notification_icon_grey.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/outer_bubbles.svg b/assets/images/svg/outer_bubbles.svg new file mode 100644 index 0000000..cfe860d --- /dev/null +++ b/assets/images/svg/outer_bubbles.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/images/svg/profile_icon.svg b/assets/images/svg/profile_icon.svg new file mode 100644 index 0000000..20dfb2b --- /dev/null +++ b/assets/images/svg/profile_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/water_bottle.svg b/assets/images/svg/water_bottle.svg new file mode 100644 index 0000000..4763d7e --- /dev/null +++ b/assets/images/svg/water_bottle.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/svg/weight_scale_icon.svg b/assets/images/svg/weight_scale_icon.svg new file mode 100644 index 0000000..c3329ff --- /dev/null +++ b/assets/images/svg/weight_scale_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/yellow_arrow_down_icon.svg b/assets/images/svg/yellow_arrow_down_icon.svg new file mode 100644 index 0000000..f2ca09f --- /dev/null +++ b/assets/images/svg/yellow_arrow_down_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/lib/core/api/api_client.dart b/lib/core/api/api_client.dart index 888f704..039787b 100644 --- a/lib/core/api/api_client.dart +++ b/lib/core/api/api_client.dart @@ -19,7 +19,7 @@ abstract class ApiClient { Future post( String endPoint, { - required Map body, + required dynamic body, required Function(dynamic response, int statusCode, {int? messageStatus, String? errorMessage}) onSuccess, required Function(String error, int statusCode, {int? messageStatus, Failure? failureType}) onFailure, bool isAllowAny, @@ -27,6 +27,8 @@ abstract class ApiClient { bool isRCService, bool isPaymentServices, bool bypassConnectionCheck, + Map apiHeaders, + bool isBodyPlainText, }); Future get( @@ -89,7 +91,7 @@ class ApiClientImp implements ApiClient { @override post( String endPoint, { - required Map body, + required dynamic body, required Function(dynamic response, int statusCode, {int? messageStatus, String? errorMessage}) onSuccess, required Function(String error, int statusCode, {int? messageStatus, Failure? failureType}) onFailure, bool isAllowAny = false, @@ -97,6 +99,8 @@ class ApiClientImp implements ApiClient { bool isRCService = false, bool isPaymentServices = false, bool bypassConnectionCheck = true, + Map? apiHeaders, + bool isBodyPlainText = false, }) async { String url; if (isExternal) { @@ -110,80 +114,84 @@ class ApiClientImp implements ApiClient { } // try { var user = _appState.getAuthenticatedUser(); - Map headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}; - if (!isExternal) { - String? token = _appState.appAuthToken; + Map headers = apiHeaders ?? {'Content-Type': 'application/json', 'Accept': 'application/json'}; - if (body.containsKey('SetupID')) { - body['SetupID'] = body.containsKey('SetupID') ? body['SetupID'] ?? body[''] : SETUP_ID; - } else {} + // When isBodyPlainText is true, skip all body manipulation and use body as-is + if (!isBodyPlainText) { + if (!isExternal) { + String? token = _appState.appAuthToken; - if (body.containsKey('isDentalAllowedBackend')) { - body['isDentalAllowedBackend'] = - body.containsKey('isDentalAllowedBackend') ? body['isDentalAllowedBackend'] ?? IS_DENTAL_ALLOWED_BACKEND : IS_DENTAL_ALLOWED_BACKEND; - } + if (body.containsKey('SetupID')) { + body['SetupID'] = body.containsKey('SetupID') ? body['SetupID'] ?? body[''] : SETUP_ID; + } else {} - if (!body.containsKey('IsPublicRequest')) { - // if (!body.containsKey('PatientType')) { - if (user != null && user.patientType != null) { - body['PatientType'] = user.patientType; - } else { - body['PatientType'] = PATIENT_TYPE.toString(); + if (body.containsKey('isDentalAllowedBackend')) { + body['isDentalAllowedBackend'] = + body.containsKey('isDentalAllowedBackend') ? body['isDentalAllowedBackend'] ?? IS_DENTAL_ALLOWED_BACKEND : IS_DENTAL_ALLOWED_BACKEND; } - if (user != null && user.patientType != null) { - body['PatientTypeID'] = user.patientType; - } else { - body['PatientType'] = PATIENT_TYPE_ID.toString(); - } + if (!body.containsKey('IsPublicRequest')) { + // if (!body.containsKey('PatientType')) { + if (user != null && user.patientType != null) { + body['PatientType'] = user.patientType; + } else { + body['PatientType'] = PATIENT_TYPE.toString(); + } + + if (user != null && user.patientType != null) { + body['PatientTypeID'] = user.patientType; + } else { + body['PatientType'] = PATIENT_TYPE_ID.toString(); + } - if (user != null) { - body['TokenID'] = body['TokenID'] ?? token; + if (user != null) { + body['TokenID'] = body['TokenID'] ?? token; - body['PatientID'] = body['PatientID'] ?? user.patientId; + body['PatientID'] = body['PatientID'] ?? user.patientId; - body['PatientOutSA'] = body.containsKey('PatientOutSA') ? body['PatientOutSA'] ?? user.outSa : user.outSa; - body['SessionID'] = body['TokenID'] == null ? ApiConsts.sessionID : getSessionId(body['TokenID'] ?? ""); //getSe + body['PatientOutSA'] = body.containsKey('PatientOutSA') ? body['PatientOutSA'] ?? user.outSa : user.outSa; + body['SessionID'] = body['TokenID'] == null ? ApiConsts.sessionID : getSessionId(body['TokenID'] ?? ""); //getSe + } + // else { + // body['SessionID'] = body['TokenID'] == null ? ApiConsts.sessionID : getSessionId(body['TokenID'] ?? ""); //getSe + // + // } } - // else { - // body['SessionID'] = body['TokenID'] == null ? ApiConsts.sessionID : getSessionId(body['TokenID'] ?? ""); //getSe - // - // } } - } - // request.versionID = VERSION_ID; - // request.channel = CHANNEL; - // request.iPAdress = IP_ADDRESS; - // request.generalid = GENERAL_ID; - // request.languageID = (languageID == 'ar' ? 1 : 2); - // request.patientOutSA = (request.zipCode == '966' || request.zipCode == '+966') ? 0 : 1; - - // body['VersionID'] = ApiConsts.appVersionID.toString(); - if (!isExternal) { - body['VersionID'] = ApiConsts.appVersionID.toString(); - body['Channel'] = ApiConsts.appChannelId.toString(); - body['IPAdress'] = ApiConsts.appIpAddress; - body['generalid'] = ApiConsts.appGeneralId; - - body['LanguageID'] = _appState.getLanguageID().toString(); - body['Latitude'] = _appState.userLat.toString(); - body['Longitude'] = _appState.userLong.toString(); - body['DeviceTypeID'] = _appState.deviceTypeID; - if (_appState.appAuthToken.isNotEmpty) { - body[_appState.isAuthenticated ? 'TokenID' : 'LogInTokenID'] = _appState.appAuthToken; + // request.versionID = VERSION_ID; + // request.channel = CHANNEL; + // request.iPAdress = IP_ADDRESS; + // request.generalid = GENERAL_ID; + // request.languageID = (languageID == 'ar' ? 1 : 2); + // request.patientOutSA = (request.zipCode == '966' || request.zipCode == '+966') ? 0 : 1; + + // body['VersionID'] = ApiConsts.appVersionID.toString(); + if (!isExternal) { + body['VersionID'] = ApiConsts.appVersionID.toString(); + body['Channel'] = ApiConsts.appChannelId.toString(); + body['IPAdress'] = ApiConsts.appIpAddress; + body['generalid'] = ApiConsts.appGeneralId; + + body['LanguageID'] = _appState.getLanguageID().toString(); + body['Latitude'] = _appState.userLat.toString(); + body['Longitude'] = _appState.userLong.toString(); + body['DeviceTypeID'] = _appState.deviceTypeID; + if (_appState.appAuthToken.isNotEmpty) { + body[_appState.isAuthenticated ? 'TokenID' : 'LogInTokenID'] = _appState.appAuthToken; + } + + // body['TokenID'] = "@dm!n"; + // body['PatientID'] = 1018977; + // body['PatientTypeID'] = 1; + // + // body['PatientOutSA'] = 0; + // body['SessionID'] = "45786230487560q"; } - // body['TokenID'] = "@dm!n"; - // body['PatientID'] = 1018977; - // body['PatientTypeID'] = 1; - // - // body['PatientOutSA'] = 0; - // body['SessionID'] = "45786230487560q"; + body.removeWhere((key, value) => value == null); } - body.removeWhere((key, value) => value == null); - final bool networkStatus = await Utils.checkConnection(bypassConnectionCheck: bypassConnectionCheck); if (!networkStatus) { @@ -196,12 +204,13 @@ class ApiClientImp implements ApiClient { return; } - final response = await http.post(Uri.parse(url.trim()), body: json.encode(body), headers: headers); + // Handle body encoding based on isBodyPlainText flag + final dynamic requestBody = isBodyPlainText ? body : json.encode(body); + final response = await http.post(Uri.parse(url.trim()), body: requestBody, headers: headers); final int statusCode = response.statusCode; log("uri: ${Uri.parse(url.trim())}"); log("body: ${json.encode(body)}"); - // log("response.body: ${response.body}"); - // log("response.body: ${response.body}"); + log("response.body: ${response.body}"); if (statusCode < 200 || statusCode >= 400) { onFailure('Error While Fetching data', statusCode, failureType: StatusCodeFailure("Error While Fetching data")); logApiEndpointError(endPoint, 'Error While Fetching data', statusCode); diff --git a/lib/core/api_consts.dart b/lib/core/api_consts.dart index 309e9df..0febdbe 100644 --- a/lib/core/api_consts.dart +++ b/lib/core/api_consts.dart @@ -439,14 +439,6 @@ var RATE_DOCTOR_RESPONSE = 'Services/OUTPs.svc/REST/insertAppointmentQuestionRat var GET_PATIENT_ALLERGIES = 'Services/Patients.svc/REST/GetPatientAllergies'; -// H2O -var H2O_GET_USER_PROGRESS = "Services/H2ORemainder.svc/REST/H2O_GetUserProgress"; -var H2O_INSERT_USER_ACTIVITY = "Services/H2ORemainder.svc/REST/H2O_InsertUserActivity"; -var H2O_GET_USER_DETAIL = "Services/H2ORemainder.svc/REST/H2O_GetUserDetails_New"; -var H2O_UPDATE_USER_DETAIL = "Services/H2ORemainder.svc/REST/H2O_UpdateUserDetails_New"; -var H2O_UNDO_USER_ACTIVITY = "Services/H2ORemainder.svc/REST/H2o_UndoUserActivity"; -//E_Referral Services - // Encillary Orders var GET_ANCILLARY_ORDERS = 'Services/Doctors.svc/REST/GetOnlineAncillaryOrderList'; @@ -672,25 +664,6 @@ var addPayFortApplePayResponse = "Services/PayFort_Serv.svc/REST/AddResponse"; // Auth Provider Consts -const String INSERT_DEVICE_IMEI = 'Services/Patients.svc/REST/Patient_INSERTDeviceIMEI'; -const String SELECT_DEVICE_IMEI = 'Services/Patients.svc/REST/Patient_SELECTDeviceIMEIbyIMEI'; -const String CHECK_PATIENT_AUTH = 'Services/Authentication.svc/REST/CheckPatientAuthentication'; -const GET_MOBILE_INFO = 'Services/Authentication.svc/REST/GetMobileLoginInfo'; - -const FORGOT_PASSWORD = 'Services/Authentication.svc/REST/CheckActivationCodeForSendFileNo'; -const CHECK_PATIENT_FOR_REGISTRATION = "Services/Authentication.svc/REST/CheckPatientForRegisteration"; - -const CHECK_USER_STATUS = "Services/NHIC.svc/REST/GetPatientInfo"; -const REGISTER_USER = 'Services/Authentication.svc/REST/PatientRegistration'; -const LOGGED_IN_USER_URL = 'Services/MobileNotifications.svc/REST/Insert_PatientMobileDeviceInfo'; - -const FORGOT_PATIENT_ID = 'Services/Authentication.svc/REST/SendPatientIDSMSByMobileNumber'; -const DASHBOARD = 'Services/Patients.svc/REST/PatientDashboard'; -const PROFILE_SETTING = 'Services/Patients.svc/REST/GetPateintInfoForUpdate'; -const SAVE_SETTING = 'Services/Patients.svc/REST/UpdatePateintInfo'; - -const DEACTIVATE_ACCOUNT = 'Services/Patients.svc/REST/PatientAppleActivation_InsertUpdate'; - var ER_CREATE_ADVANCE_PAYMENT = "services/Doctors.svc/REST/ER_CreateAdvancePaymentForClinic"; //family Files @@ -855,12 +828,11 @@ class ApiConsts { // SYMPTOMS CHECKER static final String getBodySymptomsByName = '$symptomsCheckerApi/GetBodySymptomsByName'; static final String getRiskFactors = '$symptomsCheckerApi/GetRiskFactors'; - static final String getGeneralSuggestion = '$symptomsCheckerApi/GetGeneralSggestion'; + static final String getSuggestions = '$symptomsCheckerApi/GetSuggestion'; static final String diagnosis = '$symptomsCheckerApi/diagnosis'; static final String explain = '$symptomsCheckerApi/explain'; //E-REFERRAL SERVICES - static final getAllRelationshipTypes = "Services/Patients.svc/REST/GetAllRelationshipTypes"; static final sendActivationCodeForEReferral = 'Services/Authentication.svc/REST/SendActivationCodeForEReferral'; static final checkActivationCodeForEReferral = 'Services/Authentication.svc/REST/CheckActivationCodeForEReferral'; @@ -868,6 +840,14 @@ class ApiConsts { static final createEReferral = "Services/Patients.svc/REST/CreateEReferral"; static final getEReferrals = "Services/Patients.svc/REST/GetEReferrals"; + //WATER CONSUMPTION + static String h2oGetUserProgress = "Services/H2ORemainder.svc/REST/H2O_GetUserProgress"; + static String h2oInsertUserActivity = "Services/H2ORemainder.svc/REST/H2O_InsertUserActivity"; + static String h2oInsertUserDetailsNew = "Services/H2ORemainder.svc/REST/H2O_InsertUserDetails_New"; + static String h2oGetUserDetail = "Services/H2ORemainder.svc/REST/H2O_GetUserDetails_New"; + static String h2oUpdateUserDetail = "Services/H2ORemainder.svc/REST/H2O_UpdateUserDetails_New"; + static String h2oUndoUserActivity = "Services/H2ORemainder.svc/REST/H2o_UndoUserActivity"; + // ************ static values for Api **************** static final double appVersionID = 50.3; static final int appChannelId = 3; @@ -879,3 +859,34 @@ class ApiConsts { class ApiKeyConstants { static final String googleMapsApiKey = 'AIzaSyB6TERnxIr0yJ3qG4ULBZbu0sAD4tGqtng'; } + +//flutter: URL : https://hmgwebservices.com/Services/H2ORemainder.svc/REST/H2O_InsertUserActivity +// flutter: {"IdentificationNo":"2530976584","MobileNumber":"504278212","QuantityIntake":200,"VersionID":20.0,"Channel":3,"LanguageID":2,"IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","isDentalAllowedBackend":false,"DeviceTypeID":1,"PatientID":4515697,"TokenID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","PatientTypeID":1,"PatientType":1,"Latitude":37.785834,"Longitude":-122.406417} +// flutter: response.body: +// flutter: {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":null,"ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":true,"MealOrderStatus":0,"MealType":0,"MessageStatus":1,"NumberOfResultRecords":0,"PatientBlodType":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"IsHMGPatient":false,"LogInTokenID":null,"PhysicalActivityData":null,"RowExists":0,"UserDetailData":null,"UserDetailData_New":null,"UserProgressForMonthData":null,"UserProgressForTodayData":[{"QuantityConsumed":200.00,"PercentageConsumed":9.41,"PercentageLeft":90.59,"QuantityLimit":2125.00}],"UserProgressForWeekData":null,"UserProgressHistoryData":[{"Quantity":200.000,"CreatedDate":"\/Date(1766911222217+0300)\/"}],"VerificationCode":null,"isSMSSent":false} + +// URL : https://hmgwebservices.com/Services/H2ORemainder.svc/REST/H2o_UndoUserActivity +// flutter: {"Progress":1,"MobileNumber":"504278212","IdentificationNo":"2530976584","VersionID":20.0,"Channel":3,"LanguageID":2,"IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","isDentalAllowedBackend":false,"DeviceTypeID":1,"PatientID":4515697,"TokenID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","PatientTypeID":1,"PatientType":1,"Latitude":37.785834,"Longitude":-122.406417} +// flutter: response.body: +// flutter: {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":null,"ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":false,"MealOrderStatus":0,"MealType":0,"MessageStatus":1,"NumberOfResultRecords":0,"PatientBlodType":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"IsHMGPatient":false,"LogInTokenID":null,"PhysicalActivityData":null,"RowExists":0,"UserDetailData":null,"UserDetailData_New":null,"UserProgressForMonthData":null,"UserProgressForTodayData":[{"QuantityConsumed":0.00,"PercentageConsumed":0.00,"PercentageLeft":100.00,"QuantityLimit":2125.00}],"UserProgressForWeekData":null,"UserProgressHistoryData":[],"VerificationCode":null,"isSMSSent":false} + +// Progress":2 means weekly data + +// flutter: URL : https://hmgwebservices.com/Services/H2ORemainder.svc/REST/H2O_GetUserProgress +// flutter: {"Progress":2,"MobileNumber":"504278212","IdentificationNo":"2530976584","VersionID":20.0,"Channel":3,"LanguageID":2,"IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","isDentalAllowedBackend":false,"DeviceTypeID":1,"PatientID":4515697,"TokenID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","PatientTypeID":1,"PatientType":1,"Latitude":37.785834,"Longitude":-122.406417} +// flutter: response.body: +// [log] {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":null,"ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":false,"MealOrderStatus":0,"MealType":0,"MessageStatus":1,"NumberOfResultRecords":0,"PatientBlodType":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"IsHMGPatient":false,"LogInTokenID":null,"PhysicalActivityData":null,"RowExists":0,"UserDetailData":null,"UserDetailData_New":null,"UserProgressForMonthData":null,"UserProgressForTodayData":null,"UserProgressForWeekData":[{"DayNumber":1,"DayDate":null,"DayName":"Sunday","PercentageConsumed":0},{"DayNumber":7,"DayDate":null,"DayName":"Saturday","PercentageConsumed":0},{"DayNumber":6,"DayDate":null,"DayName":"Friday","PercentageConsumed":0},{"DayNumber":5,"DayDate":null,"DayName":"Thursday","PercentageConsumed":0},{"DayNumber":4,"DayDate":null,"DayName":"Wednesday","PercentageConsumed":0},{"DayNumber":3,"DayDate":null,"DayName":"Tuesday","PercentageConsumed":0},{"DayNumber":2,"DayDate":null,"DayName":"Monday","PercentageConsumed":0}],"UserProgressHistoryData":[],"VerificationCode":null,"isSMSSent":false} + +// Progress":1 means daily data + +//URL : https://hmgwebservices.com/Services/H2ORemainder.svc/REST/H2O_GetUserProgress +// flutter: {"Progress":1,"MobileNumber":"504278212","IdentificationNo":"2530976584","VersionID":20.0,"Channel":3,"LanguageID":2,"IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","isDentalAllowedBackend":false,"DeviceTypeID":1,"PatientID":4515697,"TokenID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","PatientTypeID":1,"PatientType":1,"Latitude":37.785834,"Longitude":-122.406417} +// flutter: response.body: +// flutter: {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":null,"ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":false,"MealOrderStatus":0,"MealType":0,"MessageStatus":1,"NumberOfResultRecords":0,"PatientBlodType":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"IsHMGPatient":false,"LogInTokenID":null,"PhysicalActivityData":null,"RowExists":0,"UserDetailData":null,"UserDetailData_New":null,"UserProgressForMonthData":null,"UserProgressForTodayData":[{"QuantityConsumed":0.00,"PercentageConsumed":0.00,"PercentageLeft":100.00,"QuantityLimit":2125.00}],"UserProgressForWeekData":null,"UserProgressHistoryData":[],"VerificationCode":null,"isSMSSent":false} + +// Progress":1 means monthly data + +// flutter: URL : https://hmgwebservices.com/Services/H2ORemainder.svc/REST/H2O_GetUserProgress +// flutter: {"Progress":3,"MobileNumber":"504278212","IdentificationNo":"2530976584","VersionID":20.0,"Channel":3,"LanguageID":2,"IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","isDentalAllowedBackend":false,"DeviceTypeID":1,"PatientID":4515697,"TokenID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNS0xMi0yOFQwODozNjo0My45MTY0MzRaIiwiUGF0aWVudElEIjoiNDUxNTY5NyIsIlBhdGllbnRNZXJnZWRJRHMiOiI0NTE1Njk3IiwiUGF0aWVudE91dFNBIjpmYWxzZX0sImV4cCI6MTc2Njk2NjQwMH0.l1rCcs2OAU5u2J-iZMiO7NX6shGzLJV0hlYtVh2JeqY","PatientTypeID":1,"PatientType":1,"Latitude":37.785834,"Longitude":-122.406417} +// flutter: response.body: +// [log] {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":null,"ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":false,"MealOrderStatus":0,"MealType":0,"MessageStatus":1,"NumberOfResultRecords":0,"PatientBlodType":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"IsHMGPatient":false,"LogInTokenID":null,"PhysicalActivityData":null,"RowExists":0,"UserDetailData":null,"UserDetailData_New":null,"UserProgressForMonthData":[{"MonthNumber":1,"MonthName":"January","PercentageConsumed":0},{"MonthNumber":2,"MonthName":"February","PercentageConsumed":0},{"MonthNumber":3,"MonthName":"March","PercentageConsumed":0},{"MonthNumber":4,"MonthName":"April","PercentageConsumed":0},{"MonthNumber":5,"MonthName":"May","PercentageConsumed":0},{"MonthNumber":6,"MonthName":"June","PercentageConsumed":0},{"MonthNumber":7,"MonthName":"July","PercentageConsumed":0},{"MonthNumber":8,"MonthName":"August","PercentageConsumed":0},{"MonthNumber":9,"MonthName":"September","PercentageConsumed":0},{"MonthNumber":10,"MonthName":"October","PercentageConsumed":0},{"MonthNumber":11,"MonthName":"November","PercentageConsumed":0},{"MonthNumber":12,"MonthName":"December","PercentageConsumed":0}],"UserProgressForTodayData":null,"UserProgressForWeekData":null,"UserProgressHistoryData":[],"VerificationCode":null,"isSMSSent":false} diff --git a/lib/core/app_assets.dart b/lib/core/app_assets.dart index dde6484..4d5535f 100644 --- a/lib/core/app_assets.dart +++ b/lib/core/app_assets.dart @@ -247,6 +247,26 @@ class AppAssets { static const String refreshIcon = '$svgBasePath/refresh.svg'; static const String homeBorderedIcon = '$svgBasePath/home_bordered.svg'; + // Water Monitor + static const String waterBottle = '$svgBasePath/water_bottle.svg'; + static const String cupAdd = '$svgBasePath/cup_add.svg'; + static const String cupFilled = '$svgBasePath/cup_filled.svg'; + static const String waterBottleOuterBubbles = '$svgBasePath/outer_bubbles.svg'; + static const String cupEmpty = '$svgBasePath/cup_empty.svg'; + static const String dumbellIcon = '$svgBasePath/dumbell_icon.svg'; + static const String weightScaleIcon = '$svgBasePath/weight_scale_icon.svg'; + static const String heightIcon = '$svgBasePath/height_icon.svg'; + static const String profileIcon = '$svgBasePath/profile_icon.svg'; + static const String notificationIconGrey = '$svgBasePath/notification_icon_grey.svg'; + static const String minimizeIcon = '$svgBasePath/minimize_icon.svg'; + static const String addIconDark = '$svgBasePath/add_icon_dark.svg'; + static const String glassIcon = '$svgBasePath/glass_icon.svg'; + static const String graphIcon = '$svgBasePath/graph_icon.svg'; + static const String listIcon = '$svgBasePath/list_icon.svg'; + static const String yellowArrowDownIcon = '$svgBasePath/yellow_arrow_down_icon.svg'; + static const String greenTickIcon = '$svgBasePath/green_tick_icon.svg'; + + // PNGS static const String bloodSugar = '$svgBasePath/bloodsugar.svg'; diff --git a/lib/core/cache_consts.dart b/lib/core/cache_consts.dart index bcbb185..8deb8bd 100644 --- a/lib/core/cache_consts.dart +++ b/lib/core/cache_consts.dart @@ -63,6 +63,7 @@ class CacheConst { static const String pharmacyAutorzieToken = 'PHARMACY_AUTORZIE_TOKEN'; static const String h2oUnit = 'H2O_UNIT'; static const String h2oReminder = 'H2O_REMINDER'; + static const String waterReminderEnabled = 'WATER_REMINDER_ENABLED'; static const String livecareClinicData = 'LIVECARE_CLINIC_DATA'; static const String doctorScheduleDateSel = 'DOCTOR_SCHEDULE_DATE_SEL'; static const String appointmentHistoryMedical = 'APPOINTMENT_HISTORY_MEDICAL'; diff --git a/lib/core/common_models/data_points.dart b/lib/core/common_models/data_points.dart index 3f5065c..f156ecb 100644 --- a/lib/core/common_models/data_points.dart +++ b/lib/core/common_models/data_points.dart @@ -1,26 +1,26 @@ - - ///class used to provide value for the [DynamicResultChart] to plot the values class DataPoint { ///values that is displayed on the graph and dot is plotted on this final double value; + ///label shown on the bottom of the graph String label; String referenceValue; String actualValue; - String? unitOfMeasurement ; + String? unitOfMeasurement; + DateTime time; String displayTime; - DataPoint( - {required this.value, - required this.label, - required this.referenceValue, - required this.actualValue, - required this.time, - required this.displayTime, - this.unitOfMeasurement - }); + DataPoint({ + required this.value, + required this.label, + required this.actualValue, + required this.time, + required this.displayTime, + this.unitOfMeasurement, + this.referenceValue = '', + }); @override String toString() { diff --git a/lib/core/dependencies.dart b/lib/core/dependencies.dart index 5d98a78..489af59 100644 --- a/lib/core/dependencies.dart +++ b/lib/core/dependencies.dart @@ -1,4 +1,5 @@ import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/api/api_client.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -45,6 +46,8 @@ import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_r import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; import 'package:hmg_patient_app_new/features/todo_section/todo_section_repo.dart'; import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_repo.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; import 'package:hmg_patient_app_new/services/analytics/analytics_service.dart'; import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; @@ -53,6 +56,7 @@ import 'package:hmg_patient_app_new/services/firebase_service.dart'; import 'package:hmg_patient_app_new/services/localauth_service.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; +import 'package:hmg_patient_app_new/services/notification_service.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart'; import 'package:local_auth/local_auth.dart'; import 'package:logger/web.dart'; @@ -101,6 +105,13 @@ class AppDependencies { final sharedPreferences = await SharedPreferences.getInstance(); getIt.registerLazySingleton(() => CacheServiceImp(sharedPreferences: sharedPreferences, loggerService: getIt())); + + final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); + getIt.registerLazySingleton(() => NotificationServiceImp( + flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin, + loggerService: getIt(), + )); + getIt.registerLazySingleton(() => ApiClientImp(appState: getIt())); getIt.registerLazySingleton( () => LocalAuthService(loggerService: getIt(), localAuth: getIt()), @@ -126,6 +137,7 @@ class AppDependencies { getIt.registerLazySingleton(() => HmgServicesRepoImp(loggerService: getIt(), apiClient: getIt())); getIt.registerLazySingleton(() => SymptomsCheckerRepoImp(loggerService: getIt(), apiClient: getIt())); getIt.registerLazySingleton(() => BloodDonationRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => WaterMonitorRepoImp(loggerService: getIt(), apiClient: getIt())); // ViewModels // Global/shared VMs → LazySingleton @@ -136,25 +148,25 @@ class AppDependencies { () => RadiologyViewModel(radiologyRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt()), ); - getIt.registerLazySingleton(() => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); + getIt.registerLazySingleton( + () => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); getIt.registerLazySingleton(() => InsuranceViewModel(insuranceRepo: getIt(), errorHandlerService: getIt())); - getIt.registerLazySingleton(() => MyAppointmentsViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); + getIt.registerLazySingleton( + () => MyAppointmentsViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); - getIt.registerLazySingleton(() => AppointmentRatingViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); + getIt.registerLazySingleton( + () => AppointmentRatingViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); getIt.registerLazySingleton( - () => PayfortViewModel( - payfortRepo: getIt(), - errorHandlerService: getIt(), - ), + () => PayfortViewModel(payfortRepo: getIt(), errorHandlerService: getIt()), ); getIt.registerLazySingleton( () => HabibWalletViewModel( habibWalletRepo: getIt(), - errorHandlerService: getIt(), + errorHandlerService: getIt() ), ); @@ -167,7 +179,12 @@ class AppDependencies { getIt.registerLazySingleton( () => BookAppointmentsViewModel( - bookAppointmentsRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt(), myAppointmentsViewModel: getIt(), locationUtils: getIt(), dialogService: getIt()), + bookAppointmentsRepo: getIt(), + errorHandlerService: getIt(), + navigationService: getIt(), + myAppointmentsViewModel: getIt(), + locationUtils: getIt(), + dialogService: getIt()), ); getIt.registerLazySingleton( @@ -181,8 +198,15 @@ class AppDependencies { getIt.registerLazySingleton( () => AuthenticationViewModel( - authenticationRepo: getIt(), cacheService: getIt(), navigationService: getIt(), dialogService: getIt(), appState: getIt(), errorHandlerService: getIt(), localAuthService: getIt()), + authenticationRepo: getIt(), + cacheService: getIt(), + navigationService: getIt(), + dialogService: getIt(), + appState: getIt(), + errorHandlerService: getIt(), + localAuthService: getIt()), ); + getIt.registerLazySingleton(() => ProfileSettingsViewModel()); getIt.registerLazySingleton(() => DateRangeSelectorRangeViewModel()); @@ -195,7 +219,14 @@ class AppDependencies { getIt.registerLazySingleton( () => EmergencyServicesViewModel( - locationUtils: getIt(), navServices: getIt(), emergencyServicesRepo: getIt(), appState: getIt(), errorHandlerService: getIt(), appointmentRepo: getIt(), dialogService: getIt()), + locationUtils: getIt(), + navServices: getIt(), + emergencyServicesRepo: getIt(), + appState: getIt(), + errorHandlerService: getIt(), + appointmentRepo: getIt(), + dialogService: getIt(), + ), ); getIt.registerLazySingleton( @@ -208,30 +239,37 @@ class AppDependencies { getIt.registerLazySingleton(() => HealthCalcualtorViewModel()); - getIt.registerLazySingleton( - () => TodoSectionViewModel(todoSectionRepo: getIt(), errorHandlerService: getIt()), + getIt.registerLazySingleton(() => TodoSectionViewModel(todoSectionRepo: getIt(), errorHandlerService: getIt())); + + getIt.registerLazySingleton( + () => SymptomsCheckerViewModel( + errorHandlerService: getIt(), + symptomsCheckerRepo: getIt(), + appState: getIt(), + ), ); - getIt.registerLazySingleton(() => SymptomsCheckerViewModel(errorHandlerService: getIt(), symptomsCheckerRepo: getIt())); getIt.registerLazySingleton( - () => HmgServicesViewModel(bookAppointmentsRepo: getIt(), hmgServicesRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt()), + () => HmgServicesViewModel( + bookAppointmentsRepo: getIt(), + hmgServicesRepo: getIt(), + errorHandlerService: getIt(), + navigationService: getIt(), + ), ); getIt.registerLazySingleton( - () => BloodDonationViewModel(bloodDonationRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt(), dialogService: getIt(), appState: getIt()), + () => BloodDonationViewModel( + bloodDonationRepo: getIt(), + errorHandlerService: getIt(), + navigationService: getIt(), + dialogService: getIt(), + appState: getIt(), + ), ); - getIt.registerLazySingleton( - () => HealthProvider(), - ); + getIt.registerLazySingleton(() => HealthProvider()); - // Screen-specific VMs → Factory - // getIt.registerFactory( - // () => BookAppointmentsViewModel( - // bookAppointmentsRepo: getIt(), - // dialogService: getIt(), - // errorHandlerService: getIt(), - // ), - // ); + getIt.registerLazySingleton(() => WaterMonitorViewModel(waterMonitorRepo: getIt())); } } diff --git a/lib/core/location_util.dart b/lib/core/location_util.dart index 487b228..9dcdbb5 100644 --- a/lib/core/location_util.dart +++ b/lib/core/location_util.dart @@ -12,8 +12,9 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; -import 'package:huawei_location/huawei_location.dart' as HmsLocation show FusedLocationProviderClient, Location, LocationSettingsRequest, LocationRequest; -import 'package:location/location.dart' show Location, PermissionStatus, LocationData; +import 'package:huawei_location/huawei_location.dart' as HmsLocation + show FusedLocationProviderClient, Location, LocationSettingsRequest, LocationRequest; +import 'package:location/location.dart' show Location; import 'package:permission_handler/permission_handler.dart' show Permission, PermissionListActions, PermissionStatusGetters, openAppSettings; class LocationUtils { @@ -59,37 +60,22 @@ class LocationUtils { // } void getLocation( - {Function(LatLng)? onSuccess, - VoidCallback? onFailure, - bool isShowConfirmDialog = false, - VoidCallback? onLocationDeniedForever}) async { + {Function(LatLng)? onSuccess, VoidCallback? onFailure, bool isShowConfirmDialog = false, VoidCallback? onLocationDeniedForever}) async { this.isShowConfirmDialog = isShowConfirmDialog; if (Platform.isIOS) { - getCurrentLocation( - onFailure: onFailure, - onSuccess: onSuccess, - onLocationDeniedForever: onLocationDeniedForever); + getCurrentLocation(onFailure: onFailure, onSuccess: onSuccess, onLocationDeniedForever: onLocationDeniedForever); return; } if (await isGMSDevice ?? true) { - getCurrentLocation( - onFailure: onFailure, - onSuccess: onSuccess, - onLocationDeniedForever: onLocationDeniedForever); + getCurrentLocation(onFailure: onFailure, onSuccess: onSuccess, onLocationDeniedForever: onLocationDeniedForever); return; } - getHMSLocation( - onFailure: onFailure, - onSuccess: onSuccess, - onLocationDeniedForever: onLocationDeniedForever); + getHMSLocation(onFailure: onFailure, onSuccess: onSuccess, onLocationDeniedForever: onLocationDeniedForever); } - void getCurrentLocation( - {Function(LatLng)? onSuccess, - VoidCallback? onFailure, - VoidCallback? onLocationDeniedForever}) async { + void getCurrentLocation({Function(LatLng)? onSuccess, VoidCallback? onFailure, VoidCallback? onLocationDeniedForever}) async { var location = Location(); bool isLocationEnabled = await location.serviceEnabled(); @@ -113,14 +99,12 @@ class LocationUtils { } } else if (permissionGranted == LocationPermission.deniedForever) { appState.resetLocation(); - if(onLocationDeniedForever == null && isShowConfirmDialog){ + if (onLocationDeniedForever == null && isShowConfirmDialog) { showCommonBottomSheetWithoutHeight( title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!), navigationService.navigatorKey.currentContext!, child: Utils.getWarningWidget( - loadingText: - "Please grant location permission from app settings to see better results" - .needTranslation, + loadingText: "Please grant location permission from app settings to see better results".needTranslation, isShowActionButtons: true, onCancelTap: () { navigationService.pop(); @@ -253,10 +237,7 @@ class LocationUtils { appState.userLong = locationData.longitude; } - void getHMSLocation( - {VoidCallback? onFailure, - Function(LatLng p1)? onSuccess, - VoidCallback? onLocationDeniedForever}) async { + void getHMSLocation({VoidCallback? onFailure, Function(LatLng p1)? onSuccess, VoidCallback? onLocationDeniedForever}) async { try { var location = Location(); HmsLocation.FusedLocationProviderClient locationService = HmsLocation.FusedLocationProviderClient()..initFusedLocationService(); @@ -279,14 +260,12 @@ class LocationUtils { permissionGranted = await Geolocator.requestPermission(); if (permissionGranted == LocationPermission.deniedForever) { appState.resetLocation(); - if(onLocationDeniedForever == null && isShowConfirmDialog){ + if (onLocationDeniedForever == null && isShowConfirmDialog) { showCommonBottomSheetWithoutHeight( title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!), navigationService.navigatorKey.currentContext!, child: Utils.getWarningWidget( - loadingText: - "Please grant location permission from app settings to see better results" - .needTranslation, + loadingText: "Please grant location permission from app settings to see better results".needTranslation, isShowActionButtons: true, onCancelTap: () { navigationService.pop(); @@ -311,7 +290,7 @@ class LocationUtils { HmsLocation.Location data = await locationService.getLastLocation(); if (data.latitude == null || data.longitude == null) { - appState.resetLocation(); + appState.resetLocation(); HmsLocation.LocationRequest request = HmsLocation.LocationRequest() ..priority = HmsLocation.LocationRequest.PRIORITY_HIGH_ACCURACY ..interval = 1000 // 1 second diff --git a/lib/core/post_params_model.dart b/lib/core/post_params_model.dart index cf52306..e13eb5c 100644 --- a/lib/core/post_params_model.dart +++ b/lib/core/post_params_model.dart @@ -14,19 +14,20 @@ class PostParamsModel { String? sessionID; String? setupID; - PostParamsModel( - {this.versionID, - this.channel, - this.languageID, - this.logInTokenID, - this.tokenID, - this.language, - this.ipAddress, - this.generalId, - this.latitude, - this.longitude, - this.deviceTypeID, - this.sessionID}); + PostParamsModel({ + this.versionID, + this.channel, + this.languageID, + this.logInTokenID, + this.tokenID, + this.language, + this.ipAddress, + this.generalId, + this.latitude, + this.longitude, + this.deviceTypeID, + this.sessionID, + }); PostParamsModel.fromJson(Map json) { versionID = json['VersionID']; diff --git a/lib/core/utils/date_util.dart b/lib/core/utils/date_util.dart index a42a44d..746d2a7 100644 --- a/lib/core/utils/date_util.dart +++ b/lib/core/utils/date_util.dart @@ -6,8 +6,6 @@ class DateUtil { /// convert String To Date function /// [date] String we want to convert static DateTime convertStringToDate(String? date) { - - if (date == null) return DateTime.now(); if (date.isEmpty) return DateTime.now(); @@ -522,6 +520,64 @@ class DateUtil { } return ""; } + + /// Get short month name from full month name + /// [monthName] Full month name like "January" + /// Returns short form like "Jan" + static String getShortMonthName(String monthName) { + switch (monthName.toLowerCase()) { + case 'january': + return 'Jan'; + case 'february': + return 'Feb'; + case 'march': + return 'Mar'; + case 'april': + return 'Apr'; + case 'may': + return 'May'; + case 'june': + return 'Jun'; + case 'july': + return 'Jul'; + case 'august': + return 'Aug'; + case 'september': + return 'Sep'; + case 'october': + return 'Oct'; + case 'november': + return 'Nov'; + case 'december': + return 'Dec'; + default: + return monthName; // Return as-is if not recognized + } + } + + /// Get short weekday name from full weekday name + /// [weekDayName] Full weekday name like "Monday" + /// Returns short form like "Mon" + static String getShortWeekDayName(String weekDayName) { + switch (weekDayName.toLowerCase().trim()) { + case 'monday': + return 'Mon'; + case 'tuesday': + return 'Tue'; + case 'wednesday': + return 'Wed'; + case 'thursday': + return 'Thu'; + case 'friday': + return 'Fri'; + case 'saturday': + return 'Sat'; + case 'sunday': + return 'Sun'; + default: + return weekDayName; // Return as-is if not recognized + } + } } extension OnlyDate on DateTime { diff --git a/lib/core/utils/local_notifications.dart b/lib/core/utils/local_notifications.dart deleted file mode 100644 index aba01f8..0000000 --- a/lib/core/utils/local_notifications.dart +++ /dev/null @@ -1,191 +0,0 @@ -import 'dart:math'; -import 'dart:typed_data'; - -import 'package:flutter_local_notifications/flutter_local_notifications.dart'; - -final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); - -class LocalNotification { - Function(String payload)? _onNotificationClick; - static LocalNotification? _instance; - - static LocalNotification? getInstance() { - return _instance; - } - - static init({required Function(String payload) onNotificationClick}) { - if (_instance == null) { - _instance = LocalNotification(); - _instance?._onNotificationClick = onNotificationClick; - _instance?._initialize(); - } else { - // assert(false,(){ - // //TODO fix it - // "LocalNotification Already Initialized"; - // }); - } - } - - _initialize() async { - try { - var initializationSettingsAndroid = new AndroidInitializationSettings('app_icon'); - var initializationSettingsIOS = DarwinInitializationSettings(); - var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS); - await flutterLocalNotificationsPlugin.initialize( - initializationSettings, - onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) { - switch (notificationResponse.notificationResponseType) { - case NotificationResponseType.selectedNotification: - // selectNotificationStream.add(notificationResponse.payload); - break; - case NotificationResponseType.selectedNotificationAction: - // if (notificationResponse.actionId == navigationActionId) { - // selectNotificationStream.add(notificationResponse.payload); - // } - break; - } - }, - // onDidReceiveBackgroundNotificationResponse: notificationTapBackground, - ); - } catch (ex) { - print(ex.toString()); - } - // flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) - // { - // switch (notificationResponse.notificationResponseType) { - // case NotificationResponseType.selectedNotification: - // // selectNotificationStream.add(notificationResponse.payload); - // break; - // case NotificationResponseType.selectedNotificationAction: - // // if (notificationResponse.actionId == navigationActionId) { - // // selectNotificationStream.add(notificationResponse.payload); - // } - // // break; - // },} - // - // , - // - // ); - } - - // void notificationTapBackground(NotificationResponse notificationResponse) { - // // ignore: avoid_print - // print('notification(${notificationResponse.id}) action tapped: ' - // '${notificationResponse.actionId} with' - // ' payload: ${notificationResponse.payload}'); - // if (notificationResponse.input?.isNotEmpty ?? false) { - // // ignore: avoid_print - // print('notification action tapped with input: ${notificationResponse.input}'); - // } - // } - - var _random = new Random(); - - _randomNumber({int from = 100000}) { - return _random.nextInt(from); - } - - _vibrationPattern() { - var vibrationPattern = Int64List(4); - vibrationPattern[0] = 0; - vibrationPattern[1] = 1000; - vibrationPattern[2] = 5000; - vibrationPattern[3] = 2000; - - return vibrationPattern; - } - - Future? showNow({required String title, required String subtitle, required String payload}) { - Future.delayed(Duration(seconds: 1)).then((result) async { - var androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'com.hmg.local_notification', - 'HMG', - channelDescription: 'HMG', - importance: Importance.max, - priority: Priority.high, - ticker: 'ticker', - vibrationPattern: _vibrationPattern(), - ongoing: true, - autoCancel: false, - usesChronometer: true, - when: DateTime.now().millisecondsSinceEpoch - 120 * 1000, - ); - var iOSPlatformChannelSpecifics = DarwinNotificationDetails(); - var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics); - await flutterLocalNotificationsPlugin.show(25613, title, subtitle, platformChannelSpecifics, payload: payload).catchError((err) { - print(err); - }); - }); - } - - Future scheduleNotification({required DateTime scheduledNotificationDateTime, required String title, required String description}) async { - ///vibrationPattern - var vibrationPattern = Int64List(4); - vibrationPattern[0] = 0; - vibrationPattern[1] = 1000; - vibrationPattern[2] = 5000; - vibrationPattern[3] = 2000; - - // var androidPlatformChannelSpecifics = AndroidNotificationDetails('active-prescriptions', 'ActivePrescriptions', - // channelDescription: 'ActivePrescriptionsDescription', - // // icon: 'secondary_icon', - // sound: RawResourceAndroidNotificationSound('slow_spring_board'), - // - // ///change it to be as ionic - // // largeIcon: DrawableResourceAndroidBitmap('sample_large_icon'),///change it to be as ionic - // vibrationPattern: vibrationPattern, - // enableLights: true, - // color: const Color.fromARGB(255, 255, 0, 0), - // ledColor: const Color.fromARGB(255, 255, 0, 0), - // ledOnMs: 1000, - // ledOffMs: 500); - // var iOSPlatformChannelSpecifics = DarwinNotificationDetails(sound: 'slow_spring_board.aiff'); - - // /change it to be as ionic - // var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics); - // await flutterLocalNotificationsPlugin.schedule(0, title, description, scheduledNotificationDateTime, platformChannelSpecifics); - } - - ///Repeat notification every day at approximately 10:00:00 am - Future showDailyAtTime() async { - // var time = Time(10, 0, 0); - // var androidPlatformChannelSpecifics = AndroidNotificationDetails('repeatDailyAtTime channel id', 'repeatDailyAtTime channel name', channelDescription: 'repeatDailyAtTime description'); - // var iOSPlatformChannelSpecifics = DarwinNotificationDetails(); - // var platformChannelSpecifics = NotificationDetails( - // androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics); - // await flutterLocalNotificationsPlugin.showDailyAtTime( - // 0, - // 'show daily title', - // 'Daily notification shown at approximately ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}:${_toTwoDigitString(time.second)}', - // time, - // platformChannelSpecifics); - } - - ///Repeat notification weekly on Monday at approximately 10:00:00 am - Future showWeeklyAtDayAndTime() async { - // var time = Time(10, 0, 0); - // var androidPlatformChannelSpecifics = AndroidNotificationDetails('show weekly channel id', 'show weekly channel name', channelDescription: 'show weekly description'); - // var iOSPlatformChannelSpecifics = DarwinNotificationDetails(); - // var platformChannelSpecifics = NotificationDetails( - // androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics); - // await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime( - // 0, - // 'show weekly title', - // 'Weekly notification shown on Monday at approximately ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}:${_toTwoDigitString(time.second)}', - // Day.Monday, - // time, - // platformChannelSpecifics); - } - - String _toTwoDigitString(int value) { - return value.toString().padLeft(2, '0'); - } - - Future cancelNotification() async { - await flutterLocalNotificationsPlugin.cancel(0); - } - - Future cancelAllNotifications() async { - await flutterLocalNotificationsPlugin.cancelAll(); - } -} diff --git a/lib/core/utils/push_notification_handler.dart b/lib/core/utils/push_notification_handler.dart index a96b805..88e8cc8 100644 --- a/lib/core/utils/push_notification_handler.dart +++ b/lib/core/utils/push_notification_handler.dart @@ -15,16 +15,11 @@ import 'package:flutter_callkit_incoming/entities/notification_params.dart'; import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_ios_voip_kit_karmm/call_state_type.dart'; import 'package:flutter_ios_voip_kit_karmm/flutter_ios_voip_kit.dart'; -// import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; - -import 'package:flutter_local_notifications/flutter_local_notifications.dart'; -import 'package:hmg_patient_app_new/core/utils/local_notifications.dart'; +import 'package:hmg_patient_app_new/core/cache_consts.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:uuid/uuid.dart'; -import '../cache_consts.dart'; - // |--> Push Notification Background @pragma('vm:entry-point') Future backgroundMessageHandler(dynamic message) async { @@ -36,7 +31,7 @@ Future backgroundMessageHandler(dynamic message) async { // showCallkitIncoming(message); _incomingCall(message.data); return; - } else {} + } } callPage(String sessionID, String token) async {} @@ -323,7 +318,7 @@ class PushNotificationHandler { if (fcmToken != null) onToken(fcmToken); // } } catch (ex) { - print("Notification Exception: " + ex.toString()); + print("Notification Exception: $ex"); } FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler); } @@ -331,7 +326,7 @@ class PushNotificationHandler { if (Platform.isIOS) { final permission = await FirebaseMessaging.instance.requestPermission(); await FirebaseMessaging.instance.getAPNSToken().then((value) async { - log("APNS token: " + value.toString()); + log("APNS token: $value"); await Utils.saveStringFromPrefs(CacheConst.apnsToken, value.toString()); }); await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( @@ -378,14 +373,14 @@ class PushNotificationHandler { }); FirebaseMessaging.instance.getToken().then((String? token) { - print("Push Notification getToken: " + token!); + print("Push Notification getToken: ${token!}"); onToken(token!); }).catchError((err) { print(err); }); FirebaseMessaging.instance.onTokenRefresh.listen((fcm_token) { - print("Push Notification onTokenRefresh: " + fcm_token); + print("Push Notification onTokenRefresh: $fcm_token"); onToken(fcm_token); }); @@ -401,7 +396,7 @@ class PushNotificationHandler { } newMessage(RemoteMessage remoteMessage) async { - print("Remote Message: " + remoteMessage.data.toString()); + print("Remote Message: ${remoteMessage.data}"); if (remoteMessage.data.isEmpty) { return; } @@ -427,7 +422,7 @@ class PushNotificationHandler { } onToken(String token) async { - print("Push Notification Token: " + token); + print("Push Notification Token: $token"); await Utils.saveStringFromPrefs(CacheConst.pushToken, token); } @@ -441,9 +436,7 @@ class PushNotificationHandler { Future requestPermissions() async { try { if (Platform.isIOS) { - await flutterLocalNotificationsPlugin - .resolvePlatformSpecificImplementation() - ?.requestPermissions(alert: true, badge: true, sound: true); + await FirebaseMessaging.instance.requestPermission(alert: true, badge: true, sound: true); } else if (Platform.isAndroid) { Map statuses = await [ Permission.notification, diff --git a/lib/core/utils/size_utils.dart b/lib/core/utils/size_utils.dart index 8a0703e..4fdc09c 100644 --- a/lib/core/utils/size_utils.dart +++ b/lib/core/utils/size_utils.dart @@ -1,4 +1,5 @@ import 'dart:developer'; +import 'dart:math' as math; import 'package:flutter/material.dart'; // These are the Viewport values of your Figma Design. @@ -6,6 +7,16 @@ import 'package:flutter/material.dart'; // These are the Viewport values of your const num figmaDesignWidth = 375; // iPhone X / 12 base width const num figmaDesignHeight = 812; // iPhone X / 12 base height + +extension ConstrainedResponsive on num { + /// Width with max cap for tablets + double get wCapped => isTablet ? math.min( w, this * 1.3) : w; + + /// Height with max cap for tablets + double get hCapped => isTablet ? math.min(h, this * 1.3) : h; +} + + extension ResponsiveExtension on num { double get _screenWidth => SizeUtils.width; diff --git a/lib/core/utils/utils.dart b/lib/core/utils/utils.dart index 38d04b9..5a99cda 100644 --- a/lib/core/utils/utils.dart +++ b/lib/core/utils/utils.dart @@ -351,10 +351,10 @@ class Utils { ).center; } - static Widget getSuccessWidget({String? loadingText}) { + static Widget getSuccessWidget({String? loadingText, CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center}) { return Column( mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, + crossAxisAlignment: crossAxisAlignment, children: [ Lottie.asset(AppAnimations.checkmark, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), SizedBox(height: 8.h), @@ -876,7 +876,6 @@ class Utils { launchUrl(uri, mode: LaunchMode.inAppBrowserView); } - static Color getCardBorderColor(int currentQueueStatus) { switch (currentQueueStatus) { case 0: diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 2039fb8..75c57a7 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -23,14 +23,15 @@ extension CapExtension on String { extension EmailValidator on String { Widget get toWidget => Text(this); - Widget toText8({Color? color, bool isBold = false, int? maxlines, FontStyle? fontStyle, TextOverflow? textOverflow}) => Text( + Widget toText8({Color? color, FontWeight? fontWeight, bool isBold = false, int? maxlines, FontStyle? fontStyle, TextOverflow? textOverflow}) => + Text( this, maxLines: maxlines, overflow: textOverflow, style: TextStyle( fontSize: 8.f, fontStyle: fontStyle ?? FontStyle.normal, - fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + fontWeight: fontWeight ?? (isBold ? FontWeight.bold : FontWeight.normal), color: color ?? AppColors.blackColor, letterSpacing: 0, ), @@ -41,7 +42,7 @@ extension EmailValidator on String { FontWeight? weight, bool isBold = false, bool isUnderLine = false, - bool isCenter = false, + bool isCenter = false, int? maxlines, FontStyle? fontStyle, TextOverflow? textOverflow, @@ -214,39 +215,38 @@ extension EmailValidator on String { decoration: isUnderLine ? TextDecoration.underline : null), ); - Widget toText16({ - Color? color, - bool isUnderLine = false, - bool isBold = false, - bool isCenter = false, - int? maxlines, - double? height, - TextAlign? textAlign, - FontWeight? weight, - TextOverflow? textOverflow, - double? letterSpacing = -0.4, - Color decorationColor =AppColors.errorColor - }) => + Widget toText16( + {Color? color, + bool isUnderLine = false, + bool isBold = false, + bool isCenter = false, + int? maxlines, + double? height, + TextAlign? textAlign, + FontWeight? weight, + TextOverflow? textOverflow, + double? letterSpacing = -0.4, + Color decorationColor = AppColors.errorColor}) => Text( this, maxLines: maxlines, textAlign: isCenter ? TextAlign.center : null, style: TextStyle( - color: color ?? AppColors.blackColor, - fontSize: 16.f, - letterSpacing: letterSpacing, - height: height, - overflow: textOverflow, - fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), - decoration: isUnderLine ? TextDecoration.underline : null, - decorationColor: decorationColor - ), + color: color ?? AppColors.blackColor, + fontSize: 16.f, + letterSpacing: letterSpacing, + height: height, + overflow: textOverflow, + fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), + decoration: isUnderLine ? TextDecoration.underline : null, + decorationColor: decorationColor), ); Widget toText17({Color? color, bool isBold = false, bool isCenter = false}) => Text( this, textAlign: isCenter ? TextAlign.center : null, - style: TextStyle(color: color ?? AppColors.blackColor, fontSize: 17.f, letterSpacing: -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), + style: TextStyle( + color: color ?? AppColors.blackColor, fontSize: 17.f, letterSpacing: -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), ); Widget toText18({Color? color, FontWeight? weight, bool isBold = false, bool isCenter = false, int? maxlines, TextOverflow? textOverflow}) => Text( @@ -255,39 +255,62 @@ extension EmailValidator on String { this, overflow: textOverflow, style: TextStyle( - fontSize: 18.f, fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), color: color ?? AppColors.blackColor, letterSpacing: -0.4), + fontSize: 18.f, + fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), + color: color ?? AppColors.blackColor, + letterSpacing: -0.4), ); Widget toText19({Color? color, bool isBold = false}) => Text( this, - style: TextStyle(fontSize: 19.f, fontWeight: isBold ? FontWeight.bold : FontWeight.normal, color: color ?? AppColors.blackColor, letterSpacing: -0.4), + style: TextStyle( + fontSize: 19.f, fontWeight: isBold ? FontWeight.bold : FontWeight.normal, color: color ?? AppColors.blackColor, letterSpacing: -0.4), ); - Widget toText20({Color? color, FontWeight? weight, bool isBold = false, }) => Text( + Widget toText20({ + Color? color, + FontWeight? weight, + bool isBold = false, + }) => + Text( this, style: TextStyle( - fontSize: 20.f, fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), color: color ?? AppColors.blackColor, letterSpacing: -0.4), + fontSize: 20.f, + fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), + color: color ?? AppColors.blackColor, + letterSpacing: -0.4), ); Widget toText21({Color? color, bool isBold = false, FontWeight? weight, int? maxlines}) => Text( this, maxLines: maxlines, style: TextStyle( - color: color ?? AppColors.blackColor, fontSize: 21.f, letterSpacing: -1, fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal)), + color: color ?? AppColors.blackColor, + fontSize: 21.f, + letterSpacing: -1, + fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal)), ); Widget toText22({Color? color, bool isBold = false, bool isCenter = false}) => Text( this, textAlign: isCenter ? TextAlign.center : null, style: TextStyle( - height: 1, color: color ?? AppColors.blackColor, fontSize: 22.f, letterSpacing: -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), + height: 1, + color: color ?? AppColors.blackColor, + fontSize: 22.f, + letterSpacing: -1, + fontWeight: isBold ? FontWeight.bold : FontWeight.normal), ); Widget toText24({Color? color, bool isBold = false, bool isCenter = false, FontWeight? fontWeight, double? letterSpacing}) => Text( this, textAlign: isCenter ? TextAlign.center : null, style: TextStyle( - height: 23 / 24, color: color ?? AppColors.blackColor, fontSize: 24.f, letterSpacing: letterSpacing??-1, fontWeight: isBold ? FontWeight.bold : fontWeight??FontWeight.normal), + height: 23 / 24, + color: color ?? AppColors.blackColor, + fontSize: 24.f, + letterSpacing: letterSpacing ?? -1, + fontWeight: isBold ? FontWeight.bold : fontWeight ?? FontWeight.normal), ); Widget toText26({Color? color, bool isBold = false, double? height, bool isCenter = false, FontWeight? weight, double? letterSpacing}) => Text( @@ -312,17 +335,25 @@ extension EmailValidator on String { fontWeight: isBold ? FontWeight.bold : FontWeight.normal), ); - Widget toText32({Color? color, bool isBold = false, bool isCenter = false}) => Text( + Widget toText32({FontWeight? weight, Color? color, bool isBold = false, bool isCenter = false}) => Text( this, textAlign: isCenter ? TextAlign.center : null, style: TextStyle( - height: 32 / 32, color: color ?? AppColors.blackColor, fontSize: 32.f, letterSpacing: -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), + height: 32 / 32, + color: color ?? AppColors.blackColor, + fontSize: 32.f, + letterSpacing: -1, + fontWeight: isBold ? FontWeight.bold : weight ?? FontWeight.normal), ); Widget toText44({Color? color, bool isBold = false}) => Text( this, style: TextStyle( - height: 32 / 32, color: color ?? AppColors.blackColor, fontSize: 44.f, letterSpacing: -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), + height: 32 / 32, + color: color ?? AppColors.blackColor, + fontSize: 44.f, + letterSpacing: -1, + fontWeight: isBold ? FontWeight.bold : FontWeight.normal), ); Widget toSectionHeading({String upperHeading = "", String lowerHeading = ""}) { diff --git a/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart b/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart new file mode 100644 index 0000000..b2be4a2 --- /dev/null +++ b/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart @@ -0,0 +1,59 @@ +class RiskAndSuggestionsResponseModel { + final List? dataDetails; + + RiskAndSuggestionsResponseModel({this.dataDetails}); + + factory RiskAndSuggestionsResponseModel.fromJson(Map json) { + return RiskAndSuggestionsResponseModel( + dataDetails: + json['dataDetails'] != null ? (json['dataDetails'] as List).map((item) => RiskAndSuggestionsItemModel.fromJson(item)).toList() : null, + ); + } + + Map toJson() { + return { + 'dataDetails': dataDetails?.map((item) => item.toJson()).toList(), + }; + } +} + +class RiskAndSuggestionsItemModel { + final String? id; + final String? type; + final String? name; + final String? commonName; + final String? language; + + RiskAndSuggestionsItemModel({ + this.id, + this.type, + this.name, + this.commonName, + this.language, + }); + + factory RiskAndSuggestionsItemModel.fromJson(Map json) { + return RiskAndSuggestionsItemModel( + id: json['id'], + type: json['type'], + name: json['name'], + commonName: json['common_name'], + language: json['language'], + ); + } + + Map toJson() { + return { + 'id': id, + 'type': type, + 'name': name, + 'common_name': commonName, + 'language': language, + }; + } + + // Helper method to get display name + String getDisplayName() { + return commonName ?? name ?? ''; + } +} diff --git a/lib/features/symptoms_checker/symptoms_checker_repo.dart b/lib/features/symptoms_checker/symptoms_checker_repo.dart index 5379207..954d414 100644 --- a/lib/features/symptoms_checker/symptoms_checker_repo.dart +++ b/lib/features/symptoms_checker/symptoms_checker_repo.dart @@ -7,77 +7,214 @@ import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; -import 'package:http/http.dart' as http; abstract class SymptomsCheckerRepo { Future>> getBodySymptomsByName({ required List organNames, }); + + Future>> getRiskFactors({ + required int age, + required String sex, + required List evidenceIds, + required String language, + }); + + Future>> getSuggestions({ + required int age, + required String sex, + required List evidenceIds, + required String language, + }); } class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { final ApiClient apiClient; final LoggerService loggerService; - SymptomsCheckerRepoImp({ - required this.apiClient, - required this.loggerService, - }); + SymptomsCheckerRepoImp({required this.apiClient, required this.loggerService}); @override - Future>> getBodySymptomsByName({ - required List organNames, + Future>> getBodySymptomsByName({required List organNames}) async { + log("GetBodySymptomsByName Request URL: ${ApiConsts.getBodySymptomsByName}"); + log("GetBodySymptomsByName Request Body: ${jsonEncode(organNames)}"); + + Map headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}; + + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getBodySymptomsByName, + apiHeaders: headers, + body: jsonEncode(organNames), + isExternal: true, + isAllowAny: true, + isBodyPlainText: true, + onFailure: (error, statusCode, {messageStatus, failureType}) { + loggerService.logError("GetBodySymptomsByName API Failed: $error"); + log("GetBodySymptomsByName Failed: $error, Status: $statusCode"); + failure = failureType ?? ServerFailure(error); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + log("GetBodySymptomsByName Response Status: $statusCode"); + loggerService.logInfo("GetBodySymptomsByName API Success: $response"); + log("GetBodySymptomsByName Response: $response"); + + BodySymptomResponseModel bodySymptomResponse = BodySymptomResponseModel.fromJson(response); + + apiResponse = GenericApiModel( + messageStatus: messageStatus ?? 1, + statusCode: statusCode, + errorMessage: errorMessage, + data: bodySymptomResponse, + ); + } catch (e, stackTrace) { + loggerService.logError("Error parsing GetBodySymptomsByName response: $e"); + loggerService.logError("StackTrace: $stackTrace"); + log("Parse Error: $e"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e, stackTrace) { + loggerService.logError("Exception in getBodySymptomsByName: $e"); + loggerService.logError("StackTrace: $stackTrace"); + log("Exception: $e"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getRiskFactors({ + required int age, + required String sex, + required List evidenceIds, + required String language, }) async { + final Map body = { + "age": { + "value": age, + }, + "sex": sex, + "evidence": evidenceIds.map((id) => {"id": id}).toList(), + "language": language, + }; + try { - // API expects a direct JSON array: ["mid_abdomen", "chest"] - // Not an object like: {"organNames": [...]} - // Since ApiClient.post expects Map and encodes it as object, - // we make direct HTTP call here to send array body - - final String requestBody = jsonEncode(organNames); - - loggerService.logInfo("GetBodySymptomsByName Request: $requestBody"); - log("GetBodySymptomsByName Request URL: ${ApiConsts.getBodySymptomsByName}"); - log("GetBodySymptomsByName Request Body: $requestBody"); - - // Make direct HTTP POST request with JSON array body - final response = await http.post( - Uri.parse(ApiConsts.getBodySymptomsByName), - headers: {'Content-Type': 'application/json', 'Accept': 'text/plain'}, - body: requestBody, + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getRiskFactors, + body: body, + isExternal: true, + isAllowAny: true, + onFailure: (error, statusCode, {messageStatus, failureType}) { + log("GetRiskFactors Failed: $error, Status: $statusCode"); + failure = failureType ?? ServerFailure(error); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + log("GetRiskFactors Response: $response"); + + // Parse response if it's a string + final Map responseData = response is String ? jsonDecode(response) : response; + + RiskAndSuggestionsResponseModel riskFactorsResponse = RiskAndSuggestionsResponseModel.fromJson(responseData); + + apiResponse = GenericApiModel( + messageStatus: messageStatus ?? 1, + statusCode: statusCode, + errorMessage: errorMessage, + data: riskFactorsResponse, + ); + } catch (e, stackTrace) { + loggerService.logError("Error parsing GetRiskFactors response: $e"); + loggerService.logError("StackTrace: $stackTrace"); + log("Parse Error: $e"); + failure = DataParsingFailure(e.toString()); + } + }, ); - final int statusCode = response.statusCode; + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e, stackTrace) { + loggerService.logError("Exception in getRiskFactors: $e"); + loggerService.logError("StackTrace: $stackTrace"); + log("Exception: $e"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getSuggestions({ + required int age, + required String sex, + required List evidenceIds, + required String language, + }) async { + final Map body = { + "age": { + "value": age, + }, + "sex": sex, + "evidence": evidenceIds.map((id) => {"id": id}).toList(), + "language": language, + }; - log("GetBodySymptomsByName Response Status: $statusCode"); - loggerService.logInfo("GetBodySymptomsByName Response Status: $statusCode"); + try { + GenericApiModel? apiResponse; + Failure? failure; - try { - // Parse the response - final responseBody = jsonDecode(response.body); + await apiClient.post( + ApiConsts.getSuggestions, + body: body, + isExternal: true, + isAllowAny: true, + onFailure: (error, statusCode, {messageStatus, failureType}) { + log("getSuggestions Failed: $error, Status: $statusCode"); + failure = failureType ?? ServerFailure(error); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + log("getSuggestions Response: $response"); - loggerService.logInfo("GetBodySymptomsByName API Success: $responseBody"); - log("GetBodySymptomsByName Response: $responseBody"); + // Parse response if it's a string + final Map responseData = response is String ? jsonDecode(response) : response; - BodySymptomResponseModel bodySymptomResponse = BodySymptomResponseModel.fromJson(responseBody); + RiskAndSuggestionsResponseModel riskFactorsResponse = RiskAndSuggestionsResponseModel.fromJson(responseData); - GenericApiModel apiResponse = GenericApiModel( - messageStatus: 1, - statusCode: statusCode, - errorMessage: null, - data: bodySymptomResponse, - ); + apiResponse = GenericApiModel( + messageStatus: messageStatus ?? 1, + statusCode: statusCode, + errorMessage: errorMessage, + data: riskFactorsResponse, + ); + } catch (e, stackTrace) { + loggerService.logError("Error parsing getSuggestions response: $e"); + loggerService.logError("StackTrace: $stackTrace"); + log("Parse Error: $e"); + failure = DataParsingFailure(e.toString()); + } + }, + ); - return Right(apiResponse); - } catch (e, stackTrace) { - loggerService.logError("Error parsing GetBodySymptomsByName response: $e"); - loggerService.logError("StackTrace: $stackTrace"); - log("Parse Error: $e"); - return Left(DataParsingFailure(e.toString())); - } + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); } catch (e, stackTrace) { - loggerService.logError("Exception in getBodySymptomsByName: $e"); + loggerService.logError("Exception in getSuggestions: $e"); loggerService.logError("StackTrace: $stackTrace"); log("Exception: $e"); return Left(UnknownFailure(e.toString())); diff --git a/lib/features/symptoms_checker/symptoms_checker_view_model.dart b/lib/features/symptoms_checker/symptoms_checker_view_model.dart index fe66cf7..da439c6 100644 --- a/lib/features/symptoms_checker/symptoms_checker_view_model.dart +++ b/lib/features/symptoms_checker/symptoms_checker_view_model.dart @@ -1,20 +1,24 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/data/organ_mapping_data.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/organ_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_repo.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; class SymptomsCheckerViewModel extends ChangeNotifier { final SymptomsCheckerRepo symptomsCheckerRepo; final ErrorHandlerService errorHandlerService; + final AppState appState; SymptomsCheckerViewModel({ required this.symptomsCheckerRepo, required this.errorHandlerService, + required this.appState, }); // State variables @@ -29,9 +33,19 @@ class SymptomsCheckerViewModel extends ChangeNotifier { // API loading states bool isBodySymptomsLoading = false; + bool isRiskFactorsLoading = false; + bool isSuggestionsLoading = false; // API data storage - using API models directly BodySymptomResponseModel? bodySymptomResponse; + RiskAndSuggestionsResponseModel? riskFactorsResponse; + RiskAndSuggestionsResponseModel? suggestionsResponse; + + // Selected risk factors tracking + final Set _selectedRiskFactorIds = {}; + + // Selected Suggestions tracking + final Set _selectedSuggestionsIds = {}; // Selected symptoms tracking (organId -> Set of symptom IDs) final Map> _selectedSymptomsByOrgan = {}; @@ -111,6 +125,28 @@ class SymptomsCheckerViewModel extends ChangeNotifier { return _selectedSymptomsByOrgan.values.any((symptomIds) => symptomIds.isNotEmpty); } + /// Get risk factors list + List get riskFactorsList { + return riskFactorsResponse?.dataDetails ?? []; + } + + /// Check if any risk factors are selected + bool get hasSelectedRiskFactors => _selectedRiskFactorIds.isNotEmpty; + + /// Get selected risk factors count + int get selectedRiskFactorsCount => _selectedRiskFactorIds.length; + + /// Check if any risk factors are selected + bool get hasSelectedSuggestions => _selectedSuggestionsIds.isNotEmpty; + + /// Get selected risk factors count + int get selectedSuggestionsCount => _selectedSuggestionsIds.length; + + /// Get risk factors list + List get suggestionsList { + return suggestionsResponse?.dataDetails ?? []; + } + void toggleView() { _currentView = _currentView == BodyView.front ? BodyView.back : BodyView.front; notifyListeners(); @@ -122,6 +158,10 @@ class SymptomsCheckerViewModel extends ChangeNotifier { } void toggleOrganSelection(String organId) { + if (selectedOrganIds.isEmpty && _isBottomSheetExpanded == false) { + toggleBottomSheet(); + } + if (_selectedOrganIds.contains(organId)) { _selectedOrganIds.remove(organId); } else { @@ -131,6 +171,11 @@ class SymptomsCheckerViewModel extends ChangeNotifier { // Show tooltip _showTooltip(organId); + if (_selectedOrganIds.isEmpty) { + _isBottomSheetExpanded = false; + notifyListeners(); + } + notifyListeners(); } @@ -157,6 +202,10 @@ class SymptomsCheckerViewModel extends ChangeNotifier { void removeOrgan(String organId) { _selectedOrganIds.remove(organId); notifyListeners(); + if (_selectedOrganIds.isEmpty) { + _isBottomSheetExpanded = false; + notifyListeners(); + } } void clearAllSelections() { @@ -164,7 +213,12 @@ class SymptomsCheckerViewModel extends ChangeNotifier { notifyListeners(); } - void toggleBottomSheet() { + void toggleBottomSheet({bool? value}) { + if (value != null) { + _isBottomSheetExpanded = value; + notifyListeners(); + return; + } _isBottomSheetExpanded = !_isBottomSheetExpanded; notifyListeners(); } @@ -268,11 +322,305 @@ class SymptomsCheckerViewModel extends ChangeNotifier { notifyListeners(); } + // Risk Factors Methods + + /// Toggle risk factor selection + void toggleRiskFactorSelection(String riskFactorId) { + if (riskFactorId == "not_applicable") { + // "Not applicable" is mutually exclusive: if selected, clear all others + if (_selectedRiskFactorIds.contains(riskFactorId)) { + _selectedRiskFactorIds.remove(riskFactorId); + } else { + _selectedRiskFactorIds + ..clear() + ..add(riskFactorId); + } + } else { + _selectedRiskFactorIds.remove("not_applicable"); + if (!_selectedRiskFactorIds.add(riskFactorId)) { + _selectedRiskFactorIds.remove(riskFactorId); + } + } + + notifyListeners(); + } + + /// Check if risk factor is selected + bool isRiskFactorSelected(String riskFactorId) { + return _selectedRiskFactorIds.contains(riskFactorId); + } + + /// Get all selected risk factors + List getAllSelectedRiskFactors() { + return riskFactorsList.where((factor) => factor.id != null && _selectedRiskFactorIds.contains(factor.id)).toList(); + } + + /// Clear all risk factor selections + void clearAllRiskFactorSelections() { + _selectedRiskFactorIds.clear(); + notifyListeners(); + } + + /// Fetch risk factors based on selected symptoms + Future fetchRiskFactors({ + Function()? onSuccess, + Function(String)? onError, + }) async { + // Get all selected symptoms + final selectedSymptoms = getAllSelectedSymptoms(); + + if (selectedSymptoms.isEmpty) { + if (onError != null) { + onError('No symptoms selected'); + } + return; + } + + // Validate user info + if (_selectedAge == null || _selectedGender == null) { + if (onError != null) { + onError('User information is incomplete'); + } + return; + } + + // Extract symptom IDs + List evidenceIds = selectedSymptoms.where((s) => s.id != null).map((s) => s.id!).toList(); + + await getRiskFactors( + age: _selectedAge!, + sex: _selectedGender!.toLowerCase(), + evidenceIds: evidenceIds, + language: appState.isArabic() ? 'ar' : 'en', + onSuccess: (response) { + if (onSuccess != null) { + onSuccess(); + } + }, + onError: (error) { + if (onError != null) { + onError(error); + } + }, + ); + } + + /// Call Risk Factors API + Future getRiskFactors({ + required int age, + required String sex, + required List evidenceIds, + required String language, + Function(RiskAndSuggestionsResponseModel)? onSuccess, + Function(String)? onError, + }) async { + isRiskFactorsLoading = true; + notifyListeners(); + + final result = await symptomsCheckerRepo.getRiskFactors( + age: age, + sex: sex, + evidenceIds: evidenceIds, + language: language, + ); + + result.fold( + (failure) async { + isRiskFactorsLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isRiskFactorsLoading = false; + if (apiResponse.messageStatus == 1 && apiResponse.data != null) { + riskFactorsResponse = apiResponse.data; + + if (riskFactorsResponse != null && riskFactorsResponse!.dataDetails != null) { + RiskAndSuggestionsItemModel riskFactorItem = RiskAndSuggestionsItemModel( + id: "not_applicable", + commonName: "Not Applicable", + name: "Not Applicable", + language: appState.isArabic() ? 'ar' : 'en', + type: null, + ); + riskFactorsResponse!.dataDetails!.add(riskFactorItem); + } + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse.data!); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Failed to fetch risk factors'); + } + } + }, + ); + } + + // Suggestions Methods + + /// Toggle suggestions selection + void toggleSuggestionsSelection(String suggestionsId) { + if (suggestionsId == "not_applicable") { + // "Not applicable" is mutually exclusive: if selected, clear all others + if (_selectedSuggestionsIds.contains(suggestionsId)) { + _selectedSuggestionsIds.remove(suggestionsId); + } else { + _selectedSuggestionsIds + ..clear() + ..add(suggestionsId); + } + } else { + _selectedSuggestionsIds.remove("not_applicable"); + if (!_selectedSuggestionsIds.add(suggestionsId)) { + _selectedSuggestionsIds.remove(suggestionsId); + } + } + + notifyListeners(); + } + + /// Check if risk factor is selected + bool isSuggestionsSelected(String riskFactorId) { + return _selectedSuggestionsIds.contains(riskFactorId); + } + + /// Get all selected risk factors + List getAllSelectedSuggestions() { + return suggestionsList.where((factor) => factor.id != null && _selectedSuggestionsIds.contains(factor.id)).toList(); + } + + /// Clear all risk factor selections + void clearAllSuggestionsSelections() { + _selectedSuggestionsIds.clear(); + notifyListeners(); + } + + /// Fetch risk factors based on selected symptoms + Future fetchSuggestions({ + Function()? onSuccess, + Function(String)? onError, + }) async { + // Get all selected symptoms + final selectedSymptoms = getAllSelectedSymptoms(); + + if (selectedSymptoms.isEmpty) { + if (onError != null) { + onError('No symptoms selected'); + } + return; + } + + // Validate user info + if (_selectedAge == null || _selectedGender == null) { + if (onError != null) { + onError('User information is incomplete'); + } + return; + } + + // Extract symptom IDs + List evidenceIds = selectedSymptoms.where((s) => s.id != null).map((s) => s.id!).toList(); + + // Get all selected symptoms + final selectedRisks = getAllSelectedRiskFactors(); + + if (selectedRisks.isNotEmpty) { + List evidenceRisksIds = selectedRisks.where((s) => s.id != null && s.id != "not_applicable").map((s) => s.id!).toList(); + evidenceIds.addAll(evidenceRisksIds); + } + + await getSuggestions( + age: _selectedAge!, + sex: _selectedGender!.toLowerCase(), + evidenceIds: evidenceIds, + language: appState.isArabic() ? 'ar' : 'en', + onSuccess: (response) { + if (onSuccess != null) { + onSuccess(); + } + }, + onError: (error) { + if (onError != null) { + onError(error); + } + }, + ); + } + + /// Call Suggestions API + Future getSuggestions({ + required int age, + required String sex, + required List evidenceIds, + required String language, + Function(RiskAndSuggestionsResponseModel)? onSuccess, + Function(String)? onError, + }) async { + isSuggestionsLoading = true; + notifyListeners(); + + final result = await symptomsCheckerRepo.getSuggestions( + age: age, + sex: sex, + evidenceIds: evidenceIds, + language: language, + ); + + result.fold( + (failure) async { + isSuggestionsLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isSuggestionsLoading = false; + if (apiResponse.messageStatus == 1 && apiResponse.data != null) { + suggestionsResponse = apiResponse.data; + + if (suggestionsResponse != null && suggestionsResponse!.dataDetails != null) { + RiskAndSuggestionsItemModel riskFactorItem = RiskAndSuggestionsItemModel( + id: "not_applicable", + commonName: "Not Applicable", + name: "Not Applicable", + language: appState.isArabic() ? 'ar' : 'en', + type: null, + ); + suggestionsResponse!.dataDetails!.add(riskFactorItem); + } + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse.data!); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Failed to fetch risk factors'); + } + } + }, + ); + } + void reset() { _currentView = BodyView.front; _selectedOrganIds.clear(); _selectedSymptomsByOrgan.clear(); + _selectedRiskFactorIds.clear(); + _selectedSuggestionsIds.clear(); bodySymptomResponse = null; + riskFactorsResponse = null; + suggestionsResponse = null; _isBottomSheetExpanded = false; _tooltipTimer?.cancel(); _tooltipOrganId = null; diff --git a/lib/features/water_monitor/models/insert_user_activity_request_model.dart b/lib/features/water_monitor/models/insert_user_activity_request_model.dart new file mode 100644 index 0000000..a0af649 --- /dev/null +++ b/lib/features/water_monitor/models/insert_user_activity_request_model.dart @@ -0,0 +1,26 @@ +class InsertUserActivityRequestModel { + String? identificationNo; + String? mobileNumber; + num? quantityIntake; + + InsertUserActivityRequestModel({ + this.identificationNo, + this.mobileNumber, + this.quantityIntake, + }); + + Map toJson() { + final map = {}; + if (identificationNo != null) map['IdentificationNo'] = identificationNo; + if (mobileNumber != null) map['MobileNumber'] = mobileNumber; + if (quantityIntake != null) map['QuantityIntake'] = quantityIntake; + return map; + } + + factory InsertUserActivityRequestModel.fromJson(Map json) => InsertUserActivityRequestModel( + identificationNo: json['IdentificationNo']?.toString(), + mobileNumber: json['MobileNumber']?.toString(), + quantityIntake: json['QuantityIntake'], + ); +} + diff --git a/lib/features/water_monitor/models/undo_user_activity_request_model.dart b/lib/features/water_monitor/models/undo_user_activity_request_model.dart new file mode 100644 index 0000000..01dbd92 --- /dev/null +++ b/lib/features/water_monitor/models/undo_user_activity_request_model.dart @@ -0,0 +1,26 @@ +class UndoUserActivityRequestModel { + num? progress; + String? mobileNumber; + String? identificationNo; + + UndoUserActivityRequestModel({ + this.progress, + this.mobileNumber, + this.identificationNo, + }); + + Map toJson() { + final map = {}; + if (progress != null) map['Progress'] = progress; + if (mobileNumber != null) map['MobileNumber'] = mobileNumber; + if (identificationNo != null) map['IdentificationNo'] = identificationNo; + return map; + } + + factory UndoUserActivityRequestModel.fromJson(Map json) => UndoUserActivityRequestModel( + progress: json['Progress'], + mobileNumber: json['MobileNumber']?.toString(), + identificationNo: json['IdentificationNo']?.toString(), + ); +} + diff --git a/lib/features/water_monitor/models/update_user_detail_request_model.dart b/lib/features/water_monitor/models/update_user_detail_request_model.dart new file mode 100644 index 0000000..33dbbb2 --- /dev/null +++ b/lib/features/water_monitor/models/update_user_detail_request_model.dart @@ -0,0 +1,88 @@ +class UpdateUserDetailRequestModel { + // User detail fields + String? activityID; + String? dOB; + String? email; + String? firstName; + String? lastName; + String? firstNameN; + String? middleName; + String? middleNameN; + String? lastNameN; + String? gender; + num? height; + bool? isHeightInCM; + bool? isWeightInKG; + String? zipCode; + num? weight; + bool? isNotificationOn; + String? mobileNumber; + String? identificationNo; + + UpdateUserDetailRequestModel({ + this.activityID, + this.dOB, + this.email, + this.firstName, + this.lastName, + this.firstNameN, + this.middleName, + this.middleNameN, + this.lastNameN, + this.gender, + this.height, + this.isHeightInCM, + this.isWeightInKG, + this.zipCode, + this.weight, + this.isNotificationOn, + this.mobileNumber, + this.identificationNo, + }); + + Map toJson() { + final map = {}; + + // User detail fields + if (activityID != null) map['ActivityID'] = activityID; + if (dOB != null) map['DOB'] = dOB; + if (email != null) map['Email'] = email; + if (firstName != null) map['FirstName'] = firstName; + if (lastName != null) map['LastName'] = lastName; + if (firstNameN != null) map['FirstNameN'] = firstNameN; + if (middleName != null) map['MiddleName'] = middleName; + if (middleNameN != null) map['MiddleNameN'] = middleNameN; + if (lastNameN != null) map['LastNameN'] = lastNameN; + if (gender != null) map['Gender'] = gender; + if (height != null) map['Height'] = height; + if (isHeightInCM != null) map['IsHeightInCM'] = isHeightInCM; + if (isWeightInKG != null) map['IsWeightInKG'] = isWeightInKG; + if (zipCode != null) map['ZipCode'] = zipCode; + if (weight != null) map['Weight'] = weight; + if (isNotificationOn != null) map['IsNotificationOn'] = isNotificationOn; + if (mobileNumber != null) map['MobileNumber'] = mobileNumber; + if (identificationNo != null) map['IdentificationNo'] = identificationNo; + return map; + } + + factory UpdateUserDetailRequestModel.fromJson(Map json) => UpdateUserDetailRequestModel( + activityID: json['ActivityID']?.toString(), + dOB: json['DOB']?.toString(), + email: json['Email']?.toString(), + firstName: json['FirstName']?.toString(), + lastName: json['LastName']?.toString(), + firstNameN: json['FirstNameN']?.toString(), + middleName: json['MiddleName']?.toString(), + middleNameN: json['MiddleNameN']?.toString(), + lastNameN: json['LastNameN']?.toString(), + gender: json['Gender']?.toString(), + height: json['Height'], + isHeightInCM: json['IsHeightInCM'] as bool?, + isWeightInKG: json['IsWeightInKG'] as bool?, + zipCode: json['ZipCode']?.toString(), + weight: json['Weight'], + isNotificationOn: json['IsNotificationOn'] as bool?, + mobileNumber: json['MobileNumber']?.toString(), + identificationNo: json['IdentificationNo']?.toString(), + ); +} diff --git a/lib/features/water_monitor/models/user_progress_models.dart b/lib/features/water_monitor/models/user_progress_models.dart new file mode 100644 index 0000000..667653e --- /dev/null +++ b/lib/features/water_monitor/models/user_progress_models.dart @@ -0,0 +1,111 @@ +/// Model for today's water progress data +class UserProgressForTodayModel { + num? quantityConsumed; + num? percentageConsumed; + num? percentageLeft; + num? quantityLimit; + + UserProgressForTodayModel({ + this.quantityConsumed, + this.percentageConsumed, + this.percentageLeft, + this.quantityLimit, + }); + + factory UserProgressForTodayModel.fromJson(Map json) => UserProgressForTodayModel( + quantityConsumed: json['QuantityConsumed'], + percentageConsumed: json['PercentageConsumed'], + percentageLeft: json['PercentageLeft'], + quantityLimit: json['QuantityLimit'], + ); + + Map toJson() { + return { + 'QuantityConsumed': quantityConsumed, + 'PercentageConsumed': percentageConsumed, + 'PercentageLeft': percentageLeft, + 'QuantityLimit': quantityLimit, + }; + } +} + +/// Model for weekly water progress data +class UserProgressForWeekModel { + int? dayNumber; + String? dayDate; + String? dayName; + num? percentageConsumed; + + UserProgressForWeekModel({ + this.dayNumber, + this.dayDate, + this.dayName, + this.percentageConsumed, + }); + + factory UserProgressForWeekModel.fromJson(Map json) => UserProgressForWeekModel( + dayNumber: json['DayNumber'] as int?, + dayDate: json['DayDate']?.toString(), + dayName: json['DayName']?.toString(), + percentageConsumed: json['PercentageConsumed'], + ); + + Map toJson() { + return { + 'DayNumber': dayNumber, + 'DayDate': dayDate, + 'DayName': dayName, + 'PercentageConsumed': percentageConsumed, + }; + } +} + +/// Model for monthly water progress data +class UserProgressForMonthModel { + int? monthNumber; + String? monthName; + num? percentageConsumed; + + UserProgressForMonthModel({ + this.monthNumber, + this.monthName, + this.percentageConsumed, + }); + + factory UserProgressForMonthModel.fromJson(Map json) => UserProgressForMonthModel( + monthNumber: json['MonthNumber'] as int?, + monthName: json['MonthName']?.toString(), + percentageConsumed: json['PercentageConsumed'], + ); + + Map toJson() { + return { + 'MonthNumber': monthNumber, + 'MonthName': monthName, + 'PercentageConsumed': percentageConsumed, + }; + } +} + +/// Model for user progress history data +class UserProgressHistoryModel { + num? quantity; + String? createdDate; + + UserProgressHistoryModel({ + this.quantity, + this.createdDate, + }); + + factory UserProgressHistoryModel.fromJson(Map json) => UserProgressHistoryModel( + quantity: json['Quantity'], + createdDate: json['CreatedDate']?.toString(), + ); + + Map toJson() { + return { + 'Quantity': quantity, + 'CreatedDate': createdDate, + }; + } +} diff --git a/lib/features/water_monitor/models/water_cup_model.dart b/lib/features/water_monitor/models/water_cup_model.dart new file mode 100644 index 0000000..b86fae4 --- /dev/null +++ b/lib/features/water_monitor/models/water_cup_model.dart @@ -0,0 +1,47 @@ +class WaterCupModel { + final String id; + final String name; + final int capacityMl; + final String iconPath; // or use IconData if you prefer + final bool isDefault; + + WaterCupModel({ + required this.id, + required this.name, + required this.capacityMl, + required this.iconPath, + this.isDefault = false, + }); + + WaterCupModel copyWith({ + String? id, + String? name, + int? capacityMl, + String? iconPath, + bool? isDefault, + }) { + return WaterCupModel( + id: id ?? this.id, + name: name ?? this.name, + capacityMl: capacityMl ?? this.capacityMl, + iconPath: iconPath ?? this.iconPath, + isDefault: isDefault ?? this.isDefault, + ); + } + + Map toJson() => { + 'id': id, + 'name': name, + 'capacityMl': capacityMl, + 'iconPath': iconPath, + 'isDefault': isDefault, + }; + + factory WaterCupModel.fromJson(Map json) => WaterCupModel( + id: json['id'], + name: json['name'], + capacityMl: json['capacityMl'], + iconPath: json['iconPath'], + isDefault: json['isDefault'] ?? false, + ); +} diff --git a/lib/features/water_monitor/water_monitor_repo.dart b/lib/features/water_monitor/water_monitor_repo.dart new file mode 100644 index 0000000..14a74a7 --- /dev/null +++ b/lib/features/water_monitor/water_monitor_repo.dart @@ -0,0 +1,333 @@ +import 'dart:developer'; + +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/core/api/api_client.dart'; +import 'package:hmg_patient_app_new/core/api_consts.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; +import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/insert_user_activity_request_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/undo_user_activity_request_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/update_user_detail_request_model.dart'; +import 'package:hmg_patient_app_new/services/logger_service.dart'; + +/// Progress types to request different ranges from the progress API. +enum ProgressType { today, week, month } + +abstract class WaterMonitorRepo { + /// Fetch user details for water monitoring. + /// The request will include the standard payload injected by ApiClient and + /// additionally these three parameters: Progress, MobileNumber, IdentificationNo. + Future>> getUserDetailsForWaterMonitoring({ + required num progress, + required String mobileNumber, + required String identificationNo, + }); + + /// Fetch user progress for water monitoring (H2O_GetUserProgress). + Future>> getUserProgressForWaterMonitoring({ + required ProgressType progressType, + required String mobileNumber, + required String identificationNo, + }); + + /// Update user details for water monitoring. + Future>> updateOrInsertUserDetailForWaterMonitoring( + {required UpdateUserDetailRequestModel requestModel, bool isUpdate = false}); + + /// Insert user activity (water intake). + Future>> insertUserActivity({ + required InsertUserActivityRequestModel requestModel, + }); + + /// Undo last user activity. + Future>> undoUserActivity({ + required UndoUserActivityRequestModel requestModel, + }); +} + +class WaterMonitorRepoImp implements WaterMonitorRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + WaterMonitorRepoImp({required this.loggerService, required this.apiClient}); + + @override + Future>> getUserDetailsForWaterMonitoring({ + required num progress, + required String mobileNumber, + required String identificationNo, + }) async { + Map request = { + "Progress": progress, + "MobileNumber": mobileNumber, + "IdentificationNo": identificationNo, + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.h2oGetUserDetail, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // Extract only the specific key from the API response as requested + dynamic extracted; + if (response is Map && response.containsKey('UserDetailData_New')) { + extracted = response['UserDetailData_New']; + } else { + extracted = null; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } 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>> getUserProgressForWaterMonitoring({ + required ProgressType progressType, + required String mobileNumber, + required String identificationNo, + }) async { + final progressValue = progressType == ProgressType.today ? 1 : (progressType == ProgressType.week ? 2 : 3); + + Map request = { + "Progress": progressValue, + "MobileNumber": mobileNumber, + "IdentificationNo": identificationNo, + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.h2oGetUserProgress, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // Extract progress data and history data + dynamic extracted; + dynamic historyData; + + if (response is Map) { + // Extract history data (available for all progress types) + if (response.containsKey('UserProgressHistoryData')) { + historyData = response['UserProgressHistoryData']; + } + + // Extract progress data based on type + switch (progressType) { + case ProgressType.today: + if (response.containsKey('UserProgressForTodayData')) { + extracted = response['UserProgressForTodayData']; + } + break; + case ProgressType.week: + if (response.containsKey('UserProgressForWeekData')) { + extracted = response['UserProgressForWeekData']; + } + break; + case ProgressType.month: + if (response.containsKey('UserProgressForMonthData')) { + extracted = response['UserProgressForMonthData']; + } + break; + } + + // fallbacks + if (extracted == null) { + if (response.containsKey('UserProgress')) { + extracted = response['UserProgress']; + } else if (response.containsKey('UserProgressData_New')) { + extracted = response['UserProgressData_New']; + } else { + extracted = response; + } + } + } else { + extracted = response; + } + + // Package both progress data and history data + final combinedData = { + 'progressData': extracted, + 'historyData': historyData, + }; + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: combinedData, + ); + } 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>> updateOrInsertUserDetailForWaterMonitoring({ + required UpdateUserDetailRequestModel requestModel, + bool isUpdate = false, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + // Use different endpoint based on isUpdate flag + final endpoint = isUpdate ? ApiConsts.h2oUpdateUserDetail : ApiConsts.h2oInsertUserDetailsNew; + await apiClient.post( + endpoint, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map && response.containsKey('UserDetailData_New')) { + extracted = response['UserDetailData_New']; + } else { + extracted = null; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } 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>> insertUserActivity({ + required InsertUserActivityRequestModel requestModel, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.h2oInsertUserActivity, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // Extract UserProgressForTodayData from the response + dynamic extracted; + if (response is Map && response.containsKey('UserProgressForTodayData')) { + extracted = response['UserProgressForTodayData']; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } 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>> undoUserActivity({ + required UndoUserActivityRequestModel requestModel, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.h2oUndoUserActivity, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + log("response h2oUndoUserActivity: ${response.toString()}"); + // Extract UserProgressForTodayData from the response + dynamic extracted; + if (response is Map && response.containsKey('UserProgressForTodayData')) { + extracted = response['UserProgressForTodayData']; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } 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/water_monitor/water_monitor_view_model.dart b/lib/features/water_monitor/water_monitor_view_model.dart new file mode 100644 index 0000000..2e3dbc3 --- /dev/null +++ b/lib/features/water_monitor/water_monitor_view_model.dart @@ -0,0 +1,1288 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.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/cache_consts.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/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/insert_user_activity_request_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/undo_user_activity_request_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/update_user_detail_request_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/user_progress_models.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/models/water_cup_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_repo.dart'; +import 'package:hmg_patient_app_new/routes/app_routes.dart'; +import 'package:hmg_patient_app_new/services/cache_service.dart'; +import 'package:hmg_patient_app_new/services/navigation_service.dart'; +import 'package:hmg_patient_app_new/services/notification_service.dart'; + +class WaterMonitorViewModel extends ChangeNotifier { + WaterMonitorRepo waterMonitorRepo; + + WaterMonitorViewModel({required this.waterMonitorRepo}); + + // Controllers + final TextEditingController nameController = TextEditingController(); + final TextEditingController heightController = TextEditingController(); + final TextEditingController weightController = TextEditingController(); + final TextEditingController ageController = TextEditingController(); + + // Units + final List heightUnits = ['cm', 'm', 'ft', 'in']; + final List weightUnits = ['kg', 'lb']; + + // Selected values + String _selectedHeightUnit = 'cm'; + String _selectedWeightUnit = 'kg'; + String _selectedActivityLevel = 'Lightly active'; + String _selectedNumberOfReminders = '3 Time'; + String _selectedGender = "Male"; + + // ConsumptionScreen + + String _selectedDuration = "Daily"; + bool _isGraphView = true; + + // Validation error message + String? _validationError; + + // Getters + String? get validationError => _validationError; + + String get selectedHeightUnit => _selectedHeightUnit; + + String get selectedWeightUnit => _selectedWeightUnit; + + String get selectedActivityLevel => _selectedActivityLevel; + + String get selectedNumberOfReminders => _selectedNumberOfReminders; + + String get selectedGender => _selectedGender; + + String get selectedDurationFilter => _selectedDuration; + + bool get isGraphView => _isGraphView; + + // Activity level options + List get activityLevels => + ["Almost Inactive (no exercise)", "Lightly active", "Lightly active (1-3) days per week", "Super active (very hard exercise)"]; + + // Reminder options + List get reminderOptions => ["1 Time", "2 Time", "3 Time", "4 Time", "5 Time", "6 Time"]; + + // Gender options + List get genderOptions => ["Male", "Female"]; + +//Duration Options + List get durationFilters => ["Daily", "Weekly", "Monthly"]; + + // Network/data + final AppState _appState = GetIt.instance(); + final NavigationService _navigationService = GetIt.instance(); + final CacheService _cacheService = GetIt.instance(); + + bool _isLoading = false; + dynamic _userDetailData; + bool _isWaterReminderEnabled = false; + + // Progress data lists + List _todayProgressList = []; + List _weekProgressList = []; + List _monthProgressList = []; + List _historyList = []; + + bool get isLoading => _isLoading; + + dynamic get userDetailData => _userDetailData; + + bool get isWaterReminderEnabled => _isWaterReminderEnabled; + + // Getters for progress data + List get todayProgressList => _todayProgressList; + + List get weekProgressList => _weekProgressList; + + List get monthProgressList => _monthProgressList; + + List get historyList => _historyList; + + // Get current progress list based on selected duration + dynamic get currentProgressData { + switch (_selectedDuration) { + case 'Daily': + return _todayProgressList; + case 'Weekly': + return _weekProgressList; + case 'Monthly': + return _monthProgressList; + default: + return _todayProgressList; + } + } + + // Initialize method to be called when needed + Future initialize() async { + _initializeDefaultCups(); + _loadReminderEnabledState(); + await fetchUserDetailsForMonitoring(); + // Fetch daily progress to get consumed amount and daily goal + await fetchUserProgressForMonitoring(); + } + + /// Load reminder enabled state from cache + void _loadReminderEnabledState() { + _isWaterReminderEnabled = _cacheService.getBool(key: CacheConst.waterReminderEnabled) ?? false; + log('Water reminder enabled state loaded: $_isWaterReminderEnabled'); + } + + /// Map selected duration to ProgressType enum + ProgressType _getProgressTypeFromDuration() { + switch (_selectedDuration) { + case 'Daily': + return ProgressType.today; + case 'Weekly': + return ProgressType.week; + case 'Monthly': + return ProgressType.month; + default: + return ProgressType.today; + } + } + + /// Map selected duration to ProgressType enum + int _getProgressIdFromDuration() { + switch (_selectedDuration) { + case 'Daily': + return 1; + case 'Weekly': + return 2; + case 'Monthly': + return 3; + default: + return 1; + } + } + + /// Fetch user progress data based on selected duration + Future fetchUserProgressForMonitoring() async { + try { + _isLoading = true; + notifyListeners(); + + final authenticated = _appState.getAuthenticatedUser(); + if (authenticated == null) { + _isLoading = false; + notifyListeners(); + return; + } + + final mobile = (authenticated.mobileNumber ?? '').replaceAll('+', '').replaceFirst(RegExp(r'^0'), ''); + final identification = authenticated.patientIdentificationNo ?? ''; + final progressType = _getProgressTypeFromDuration(); + + final result = await waterMonitorRepo.getUserProgressForWaterMonitoring( + progressType: progressType, + mobileNumber: mobile, + identificationNo: identification, + ); + + result.fold((failure) { + log('Error fetching user progress: ${failure.message}'); + }, (apiModel) { + log("User Progress Data ($_selectedDuration): ${apiModel.data.toString()}"); + + // Parse the response based on progress type + try { + // Extract progressData and historyData from combined response + dynamic progressData; + dynamic historyData; + + if (apiModel.data is Map && apiModel.data.containsKey('progressData')) { + progressData = apiModel.data['progressData']; + historyData = apiModel.data['historyData']; + } else { + // Fallback to old structure + progressData = apiModel.data; + } + + // Parse history data (available for all progress types, especially for daily) + if (historyData != null && historyData is List) { + _historyList.clear(); + for (var item in historyData) { + if (item is Map) { + _historyList.add(UserProgressHistoryModel.fromJson(item as Map)); + } + } + log('History data parsed: ${_historyList.length} items'); + } + + if (progressData != null && progressData is List) { + switch (progressType) { + case ProgressType.today: + _todayProgressList.clear(); + for (var item in progressData) { + if (item is Map) { + _todayProgressList.add(UserProgressForTodayModel.fromJson(item as Map)); + } + } + + // Update consumed amount and daily goal from API response + if (_todayProgressList.isNotEmpty) { + final todayData = _todayProgressList.first; + if (todayData.quantityConsumed != null) { + _totalConsumedMl = todayData.quantityConsumed!.toInt(); + log('Updated consumed from API: $_totalConsumedMl ml'); + } + if (todayData.quantityLimit != null) { + _dailyGoalMl = todayData.quantityLimit!.toInt(); + log('Updated daily goal from API: $_dailyGoalMl ml'); + } + } + + break; + + case ProgressType.week: + _weekProgressList.clear(); + for (var item in progressData) { + if (item is Map) { + _weekProgressList.add(UserProgressForWeekModel.fromJson(item as Map)); + } + } + log('Week Progress: ${_weekProgressList.length} items'); + break; + + case ProgressType.month: + _monthProgressList.clear(); + for (var item in progressData) { + if (item is Map) { + _monthProgressList.add(UserProgressForMonthModel.fromJson(item as Map)); + } + } + log('Month Progress: ${_monthProgressList.length} items'); + break; + } + } + } catch (e) { + log('Error parsing progress data: $e'); + } + }); + } catch (e) { + log('Exception in fetchUserProgressForMonitoring: $e'); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + Future fetchUserDetailsForMonitoring() async { + try { + _isLoading = true; + + notifyListeners(); + + final authenticated = _appState.getAuthenticatedUser(); + if (authenticated == null) { + _isLoading = false; + notifyListeners(); + return; + } + final mobile = (authenticated.mobileNumber ?? '').replaceAll('+', ''); + final identification = authenticated.patientIdentificationNo ?? ''; + + final result = await waterMonitorRepo.getUserDetailsForWaterMonitoring(progress: 1, mobileNumber: mobile, identificationNo: identification); + result.fold((failure) { + _userDetailData = null; + }, (apiModel) { + _userDetailData = apiModel.data; + + // Populate form fields from the fetched data + if (_userDetailData != null) { + _populateFormFields(_userDetailData); + } + }); + } catch (e) { + _userDetailData = null; + } finally { + _isLoading = false; + notifyListeners(); + + if (_userDetailData == null) { + try { + _navigationService.pushAndReplace(AppRoutes.waterMonitorSettingsScreen); + } catch (navErr) { + log('Navigation to water monitor settings failed: $navErr'); + } + } + } + } + + /// Populates form fields from the API response data + void _populateFormFields(dynamic data) { + if (data == null) return; + + try { + // Parse the response and populate fields + if (data is Map) { + // Name + if (data['FirstName'] != null) { + nameController.text = data['FirstName'].toString(); + } + + // Gender + if (data['Gender'] != null) { + final gender = data['Gender'].toString(); + if (gender == 'M' || gender == 'Male') { + _selectedGender = 'Male'; + } else if (gender == 'F' || gender == 'Female') { + _selectedGender = 'Female'; + } + } + + // Age - calculate from DOB if available + if (data['DOB'] != null) { + final dob = data['DOB'].toString(); + final age = _calculateAgeFromDOB(dob); + if (age > 0) { + ageController.text = age.toString(); + } + } + + // Height + if (data['Height'] != null) { + heightController.text = data['Height'].toString(); + // Set height unit + if (data['IsHeightInCM'] != null) { + _selectedHeightUnit = data['IsHeightInCM'] == true ? 'cm' : 'in'; + } + } + + // Weight + if (data['Weight'] != null) { + weightController.text = data['Weight'].toString(); + // Set weight unit + if (data['IsWeightInKG'] != null) { + _selectedWeightUnit = data['IsWeightInKG'] == true ? 'kg' : 'lb'; + } + } + + // Activity Level - map ActivityID to activity level + if (data['ActivityID'] != null) { + final activityId = data['ActivityID'].toString(); + _selectedActivityLevel = _getActivityLevelFromID(activityId); + } + + // Number of reminders (if available in response) + // Note: This may not be in the response, keeping default if not present + + notifyListeners(); + } + } catch (e) { + log('Error populating form fields: $e'); + } + } + + /// Calculate age from DOB string in format /Date(milliseconds+0300)/ + int _calculateAgeFromDOB(String dobString) { + try { + // Parse the /Date(milliseconds+0300)/ format + final regex = RegExp(r'\/Date\((\d+)'); + final match = regex.firstMatch(dobString); + if (match != null) { + final milliseconds = int.tryParse(match.group(1)!); + if (milliseconds != null) { + final dob = DateTime.fromMillisecondsSinceEpoch(milliseconds); + final now = DateTime.now(); + int age = now.year - dob.year; + if (now.month < dob.month || (now.month == dob.month && now.day < dob.day)) { + age--; + } + return age; + } + } + } catch (e) { + log('Error calculating age from DOB: $e'); + } + return 0; + } + + /// Map activity ID to activity level string + String _getActivityLevelFromID(String activityId) { + switch (activityId) { + case '1': + return "Almost Inactive (no exercise)"; + case '2': + return "Lightly active"; + case '3': + return "Lightly active (1-3) days per week"; + case '4': + return "Super active (very hard exercise)"; + default: + return "Lightly active"; + } + } + + // Reset all fields to default + void resetFields() { + nameController.clear(); + heightController.clear(); + weightController.clear(); + ageController.clear(); + _selectedHeightUnit = 'cm'; + _selectedWeightUnit = 'kg'; + _selectedActivityLevel = 'Lightly active'; + _selectedNumberOfReminders = '3 Time'; + _selectedGender = "Male"; + notifyListeners(); + } + + // Setters with notification + void setFilterDuration(String duration) async { + _selectedDuration = duration; + notifyListeners(); + // Fetch new progress data when duration filter changes + await fetchUserProgressForMonitoring(); + } + + // Setters with notification + void setGraphView(bool value) { + _isGraphView = value; + notifyListeners(); + } + + // Setters with notification + void setGender(String gender) { + _selectedGender = gender; + notifyListeners(); + } + + void setHeightUnit(String unit) { + _selectedHeightUnit = unit; + notifyListeners(); + } + + void setWeightUnit(String unit) { + _selectedWeightUnit = unit; + notifyListeners(); + } + + void setActivityLevel(String level) { + _selectedActivityLevel = level; + notifyListeners(); + } + + void setNumberOfReminders(String number) { + _selectedNumberOfReminders = number; + notifyListeners(); + } + + // Validation methods + bool get isValid { + _validationError = null; // Clear previous error + + if (nameController.text.trim().isEmpty) { + _validationError = 'Name is required'; + return false; + } + + if (ageController.text.trim().isEmpty) { + _validationError = 'Age is required'; + return false; + } + + if (!_isAgeValid()) { + _validationError = validateAge(); + return false; + } + + if (heightController.text.trim().isEmpty) { + _validationError = 'Height is required'; + return false; + } + + if (!_isHeightValid()) { + _validationError = validateHeight(); + return false; + } + + if (weightController.text.trim().isEmpty) { + _validationError = 'Weight is required'; + return false; + } + + if (!_isWeightValid()) { + _validationError = validateWeight(); + return false; + } + + return true; + } + + bool _isAgeValid() { + final age = int.tryParse(ageController.text.trim()); + return age != null && age >= 11 && age <= 120; + } + + bool _isHeightValid() { + final height = double.tryParse(heightController.text.trim()); + return height != null && height > 0; + } + + bool _isWeightValid() { + final weight = double.tryParse(weightController.text.trim()); + return weight != null && weight > 0; + } + + String? validateAge() { + if (ageController.text.trim().isEmpty) { + return 'Age is required'.needTranslation; + } + final age = int.tryParse(ageController.text.trim()); + if (age == null) { + return 'Invalid age'.needTranslation; + } + if (age < 11 || age > 120) { + return 'Age must be between 11 and 120'.needTranslation; + } + return null; + } + + String? validateHeight() { + if (heightController.text.trim().isEmpty) { + return 'Height is required'.needTranslation; + } + final height = double.tryParse(heightController.text.trim()); + if (height == null || height <= 0) { + return 'Invalid height'.needTranslation; + } + return null; + } + + String? validateWeight() { + if (weightController.text.trim().isEmpty) { + return 'Weight is required'.needTranslation; + } + final weight = double.tryParse(weightController.text.trim()); + if (weight == null || weight <= 0) { + return 'Invalid weight'.needTranslation; + } + return null; + } + + String _getApiCompatibleGender() { + if (_selectedGender == "Female") { + return "F"; + } + return "M"; + } + + // Save settings + Future saveSettings() async { + if (!isValid) { + notifyListeners(); // Notify so error can be read + return false; + } + + try { + _isLoading = true; + _validationError = null; + notifyListeners(); + + // Determine if this is an update or insert + final isUpdate = _userDetailData != null; + + // Get authenticated user for mobile number and identification number + final authenticated = _appState.getAuthenticatedUser(); + final mobile = (authenticated?.mobileNumber?.replaceAll('+', '') ?? '').replaceFirst("0", ""); + final identification = authenticated?.patientIdentificationNo ?? ''; + final zipCode = authenticated?.zipCode ?? '966'; + final email = authenticated?.emailAddress ?? ''; + + // Get activity ID based on selected activity level + String activityID = _getActivityID(); + + // Create request model with user detail fields only + final requestModel = UpdateUserDetailRequestModel( + firstName: nameController.text.trim(), + lastName: nameController.text.trim(), + firstNameN: nameController.text.trim(), + middleName: '', + middleNameN: '', + lastNameN: nameController.text.trim(), + gender: _getApiCompatibleGender(), + dOB: _calculateDOBFromAge(), + height: double.tryParse(heightController.text.trim()), + isHeightInCM: _selectedHeightUnit == 'cm', + weight: double.tryParse(weightController.text.trim()), + isWeightInKG: _selectedWeightUnit == 'kg', + activityID: activityID, + isNotificationOn: true, + mobileNumber: mobile, + identificationNo: identification, + email: email, + zipCode: zipCode, + ); + + // Call the API + final result = await waterMonitorRepo.updateOrInsertUserDetailForWaterMonitoring( + requestModel: requestModel, + isUpdate: isUpdate, + ); + + return result.fold( + (failure) { + _validationError = failure.message; + _isLoading = false; + notifyListeners(); + return false; + }, + (apiModel) async { + // Update local data with response + _userDetailData = apiModel.data; + + // Fetch daily progress to get the updated goal and consumed data from API + await fetchUserProgressForMonitoring(); + + _isLoading = false; + notifyListeners(); + return true; + }, + ); + } catch (e) { + _validationError = e.toString(); + _isLoading = false; + notifyListeners(); + return false; + } + } + + // Helper method to get activity ID based on activity level + String _getActivityID() { + switch (_selectedActivityLevel) { + case "Almost Inactive (no exercise)": + return "1"; + case "Lightly active": + return "2"; + case "Lightly active (1-3) days per week": + return "3"; + case "Super active (very hard exercise)": + return "4"; + default: + return "2"; + } + } + + // Helper method to calculate DOB from age + String _calculateDOBFromAge() { + final age = int.tryParse(ageController.text.trim()) ?? 0; + if (age > 0) { + final currentYear = DateTime.now().year; + final birthYear = currentYear - age; + // Create a DateTime for January 1st of the birth year + final birthDate = DateTime(birthYear, 1, 1); + // Convert to API format: /Date(milliseconds+0300)/ using DateUtil + return DateUtil.convertDateToString(birthDate); + } + return ""; + } + + @override + void dispose() { + nameController.dispose(); + heightController.dispose(); + weightController.dispose(); + ageController.dispose(); + super.dispose(); + } + + List _cups = []; + String? _selectedCupId; + int _totalConsumedMl = 0; // Loaded from API + int _dailyGoalMl = 0; // Loaded from API + + // Calibration: portion of the bottle SVG height that is fillable (0.0 - 1.0) + double _fillableHeightPercent = 0.7; + + List get cups => _cups; + + WaterCupModel? get selectedCup { + if (_cups.isEmpty) return null; + return _cups.firstWhere((c) => c.id == _selectedCupId, orElse: () => _cups.first); + } + + int get totalConsumedMl => _totalConsumedMl; + + int get dailyGoalMl => _dailyGoalMl; + + // Portion of bottle drawable height that is fillable. + double get fillableHeightPercent => _fillableHeightPercent; + + void setFillableHeightPercent(double v) { + _fillableHeightPercent = v.clamp(0.0, 1.0); + notifyListeners(); + } + + // Normalized progress in 0.0 - 1.0 (ensure double) + double get progress { + if (_dailyGoalMl == 0) return 0.0; + final p = _totalConsumedMl / _dailyGoalMl; + return p.clamp(0.0, 1.0).toDouble(); + } + + // Convenience percent (0 - 100) + double get progressPercent => (progress * 100.0).clamp(0.0, 100.0).toDouble(); + + // Calculate hydration status based on progress + String get hydrationStatus { + final percent = progressPercent; + + if (percent >= 90) { + return "Well Hydrated"; + } else if (percent >= 70) { + return "Hydrated"; + } else if (percent >= 50) { + return "Moderately Hydrated"; + } else if (percent >= 30) { + return "Slightly Dehydrated"; + } else { + return "Dehydrated"; + } + } + + // Get hydration status color + Color get hydrationStatusColor { + final percent = progressPercent; + + if (percent >= 90) { + return const Color(0xFF00C853); // Dark Green + } else if (percent >= 70) { + return const Color(0xFF4CAF50); // Green + } else if (percent >= 50) { + return const Color(0xFFFFC107); // Amber + } else if (percent >= 30) { + return const Color(0xFFFF9800); // Orange + } else { + return const Color(0xFFF44336); // Red + } + } + + String get nextDrinkTime { + if (progressPercent >= 100) { + return "Goal Achieved!"; + } + + // Get number of reminders from selected string (e.g., "3 Time" -> 3) + final remindersPerDay = int.tryParse(_selectedNumberOfReminders.replaceAll(' Time', '').trim()) ?? 3; + + // Define waking hours (e.g., 6 AM to 10 PM = 16 hours) + const wakingHoursStart = 6; // 6 AM + const wakingHoursEnd = 22; // 10 PM + const totalWakingHours = wakingHoursEnd - wakingHoursStart; + + // Calculate interval between drinks in hours + final intervalHours = totalWakingHours / remindersPerDay; + + // Get current time + final now = DateTime.now(); + final currentHour = now.hour + (now.minute / 60.0); + + // If before waking hours, next drink is at start time + if (currentHour < wakingHoursStart) { + return "${wakingHoursStart.toString().padLeft(2, '0')}:00 AM"; + } + + if (currentHour >= wakingHoursEnd) { + return "Tomorrow ${wakingHoursStart.toString().padLeft(2, '0')}:00 AM"; + } + + // Calculate which interval we're in + final hoursSinceWakeup = currentHour - wakingHoursStart; + final currentInterval = (hoursSinceWakeup / intervalHours).floor(); + + // Calculate next drink time + final nextDrinkHour = wakingHoursStart + ((currentInterval + 1) * intervalHours); + + // If next drink time is past bedtime, show tomorrow + if (nextDrinkHour >= wakingHoursEnd) { + return "Tomorrow ${wakingHoursStart.toString().padLeft(2, '0')}:00 AM"; + } + + // Format the time + final hour = nextDrinkHour.floor(); + final minute = ((nextDrinkHour - hour) * 60).round(); + + // Convert to 12-hour format + final hour12 = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour); + final period = hour >= 12 ? 'PM' : 'AM'; + + return "${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period"; + } + + /// Get time until next drink in minutes + int get minutesUntilNextDrink { + if (progressPercent >= 100) return 0; + + final remindersPerDay = int.tryParse(_selectedNumberOfReminders.replaceAll(' Time', '').trim()) ?? 3; + const wakingHoursStart = 6; + const wakingHoursEnd = 22; + const totalWakingHours = wakingHoursEnd - wakingHoursStart; + final intervalHours = totalWakingHours / remindersPerDay; + + final now = DateTime.now(); + final currentHour = now.hour + (now.minute / 60.0); + + if (currentHour < wakingHoursStart) { + final minutesUntil = ((wakingHoursStart - currentHour) * 60).round(); + return minutesUntil; + } + + if (currentHour >= wakingHoursEnd) { + final hoursUntilTomorrow = 24 - currentHour + wakingHoursStart; + return (hoursUntilTomorrow * 60).round(); + } + + final hoursSinceWakeup = currentHour - wakingHoursStart; + final currentInterval = (hoursSinceWakeup / intervalHours).floor(); + final nextDrinkHour = wakingHoursStart + ((currentInterval + 1) * intervalHours); + + if (nextDrinkHour >= wakingHoursEnd) { + final hoursUntilTomorrow = 24 - currentHour + wakingHoursStart; + return (hoursUntilTomorrow * 60).round(); + } + + final minutesUntil = ((nextDrinkHour - currentHour) * 60).round(); + return minutesUntil.clamp(0, 1440); + } + + // Allow updating consumed and goal through the vm so UI doesn't manipulate internal fields directly + void setTotalConsumedMl(int ml) { + _totalConsumedMl = ml; + notifyListeners(); + } + + void addConsumedMl(int ml) { + _totalConsumedMl = (_totalConsumedMl + ml).clamp(0, 1000000); + notifyListeners(); + } + + void subtractConsumedMl(int ml) { + _totalConsumedMl = (_totalConsumedMl - ml).clamp(0, 1000000); + notifyListeners(); + } + + void setDailyGoal(int ml) { + _dailyGoalMl = ml; + notifyListeners(); + } + + void _initializeDefaultCups() { + _cups = [ + WaterCupModel( + id: 'default_125', + name: '125ml', + capacityMl: 125, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + WaterCupModel( + id: 'default_150', + name: '150ml', + capacityMl: 150, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + WaterCupModel( + id: 'default_175', + name: '175ml', + capacityMl: 175, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + WaterCupModel( + id: 'default_200', + name: '200ml', + capacityMl: 200, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + WaterCupModel( + id: 'default_250', + name: '250ml', + capacityMl: 250, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + WaterCupModel( + id: 'default_300', + name: '300ml', + capacityMl: 300, + iconPath: AppAssets.cupEmpty, + isDefault: true, + ), + ]; + _selectedCupId = _cups.first.id; + notifyListeners(); + } + + void selectCup(String cupId) { + _selectedCupId = cupId; + notifyListeners(); + } + + void addCup(WaterCupModel cup) { + _cups.add(cup); + notifyListeners(); + } + + void updateCup(WaterCupModel updatedCup) { + final index = _cups.indexWhere((c) => c.id == updatedCup.id); + if (index != -1) { + _cups[index] = updatedCup; + notifyListeners(); + } + } + + // Public alias for deleting/removing a cup. Keeps API intention clear in UI code. + void removeCup(String cupId) { + deleteCup(cupId); + } + + void deleteCup(String cupId) { + final cup = _cups.firstWhere((c) => c.id == cupId); + if (cup.isDefault) return; // can't delete default cups + + _cups.removeWhere((c) => c.id == cupId); + if (_selectedCupId == cupId) { + _selectedCupId = _cups.first.id; + } + notifyListeners(); + } + + // Returns the currently selected cup capacity in ml (0 if none) + int get selectedCupCapacityMl => selectedCup?.capacityMl ?? 0; + + /// Increment the consumed amount by the currently selected cup capacity. + /// This centralizes business logic here so UI just calls this method. + void incrementBySelectedCup() { + if (selectedCup != null) { + addConsumedMl(selectedCup!.capacityMl); + } + } + + /// Decrement the consumed amount by the currently selected cup capacity. + /// Ensures value is clamped inside the VM (subtractConsumedMl already clamps). + void decrementBySelectedCup() { + if (selectedCup != null) { + subtractConsumedMl(selectedCup!.capacityMl); + } + } + + /// Insert user activity (record water intake) + Future insertUserActivity({required int quantityIntake}) async { + try { + _isLoading = true; + notifyListeners(); + + // Get authenticated user info + final authenticated = _appState.getAuthenticatedUser(); + if (authenticated == null) { + _isLoading = false; + notifyListeners(); + return false; + } + + final mobile = (authenticated.mobileNumber ?? '').replaceAll('+', '').replaceFirst("0", ""); + final identification = authenticated.patientIdentificationNo ?? ''; + + // Create request model + final requestModel = InsertUserActivityRequestModel( + identificationNo: identification, + mobileNumber: mobile, + quantityIntake: quantityIntake, + ); + + // Call the API + final result = await waterMonitorRepo.insertUserActivity(requestModel: requestModel); + + return result.fold( + (failure) { + log('Error inserting user activity: ${failure.message}'); + _isLoading = false; + notifyListeners(); + return false; + }, + (apiModel) { + log("Insert user activity success: ${apiModel.data.toString()}"); + // Update consumed amount and goal from the response + if (apiModel.data != null && apiModel.data is List && (apiModel.data as List).isNotEmpty) { + final progressData = (apiModel.data as List).first; + if (progressData is Map) { + // Update consumed amount + if (progressData.containsKey('QuantityConsumed')) { + final consumed = progressData['QuantityConsumed']; + if (consumed != null) { + _totalConsumedMl = (consumed is num) ? consumed.toInt() : int.tryParse(consumed.toString()) ?? _totalConsumedMl; + log('Updated consumed after insert: $_totalConsumedMl ml'); + } + } + // Update daily goal + if (progressData.containsKey('QuantityLimit')) { + final limit = progressData['QuantityLimit']; + if (limit != null) { + _dailyGoalMl = (limit is num) ? limit.toInt() : int.tryParse(limit.toString()) ?? _dailyGoalMl; + log('Updated daily goal after insert: $_dailyGoalMl ml'); + } + } + } + + // Refresh progress data to ensure consistency + fetchUserProgressForMonitoring(); + } + + _isLoading = false; + notifyListeners(); + return true; + }, + ); + } catch (e) { + log('Exception in insertUserActivity: $e'); + _isLoading = false; + notifyListeners(); + return false; + } + } + + /// Undo last user activity + Future undoUserActivity() async { + try { + _isLoading = true; + notifyListeners(); + + // Get authenticated user info + final authenticated = _appState.getAuthenticatedUser(); + if (authenticated == null) { + _isLoading = false; + notifyListeners(); + return false; + } + + final mobile = (authenticated.mobileNumber ?? '').replaceAll('+', '').replaceFirst("0", ""); + final identification = authenticated.patientIdentificationNo ?? ''; + + // Create request model + final requestModel = UndoUserActivityRequestModel( + progress: _getProgressIdFromDuration(), + mobileNumber: mobile, + identificationNo: identification, + ); + + // Call the API + final result = await waterMonitorRepo.undoUserActivity(requestModel: requestModel); + + return result.fold( + (failure) { + log('Error undoing user activity: ${failure.message}'); + _isLoading = false; + notifyListeners(); + return false; + }, + (apiModel) { + log("Undo user activity success: ${apiModel.data.toString()}"); + + // Update consumed amount and goal from the response + if (apiModel.data != null && apiModel.data is List && (apiModel.data as List).isNotEmpty) { + final progressData = (apiModel.data as List).first; + if (progressData is Map) { + // Update consumed amount + if (progressData.containsKey('QuantityConsumed')) { + final consumed = progressData['QuantityConsumed']; + if (consumed != null) { + _totalConsumedMl = (consumed is num) ? consumed.toInt() : int.tryParse(consumed.toString()) ?? _totalConsumedMl; + log('Updated consumed after undo: $_totalConsumedMl ml'); + } + } + // Update daily goal + if (progressData.containsKey('QuantityLimit')) { + final limit = progressData['QuantityLimit']; + if (limit != null) { + _dailyGoalMl = (limit is num) ? limit.toInt() : int.tryParse(limit.toString()) ?? _dailyGoalMl; + log('Updated daily goal after undo: $_dailyGoalMl ml'); + } + } + } + } + fetchUserProgressForMonitoring(); + _isLoading = false; + notifyListeners(); + return true; + }, + ); + } catch (e) { + log('Exception in undoUserActivity: $e'); + _isLoading = false; + notifyListeners(); + return false; + } + } + + /// Schedule water reminders based on user's reminder settings + Future scheduleWaterReminders() async { + try { + final notificationService = getIt.get(); + + // Request permission first + final hasPermission = await notificationService.requestPermissions(); + if (!hasPermission) { + log('Notification permission denied'); + return false; + } + + // Calculate reminder times based on _selectedNumberOfReminders + final reminderTimes = _calculateReminderTimes(); + + if (reminderTimes.isEmpty) { + log('No reminder times calculated'); + return false; + } + + // Schedule water reminders + await notificationService.scheduleWaterReminders( + reminderTimes: reminderTimes, + title: 'Time to Drink Water! 💧'.needTranslation, + body: 'Stay hydrated! Drink ${selectedCupCapacityMl}ml of water.'.needTranslation, + ); + + // Save reminder enabled state to cache + _isWaterReminderEnabled = true; + await _cacheService.saveBool(key: CacheConst.waterReminderEnabled, value: true); + + log('Scheduled ${reminderTimes.length} water reminders successfully'); + notifyListeners(); + return true; + } catch (e) { + log('Exception in scheduleWaterReminders: $e'); + return false; + } + } + + /// Calculate reminder times based on selected number of reminders + List _calculateReminderTimes() { + try { + final remindersPerDay = int.tryParse(_selectedNumberOfReminders.replaceAll(' Time', '').trim()) ?? 3; + + const wakingHoursStart = 6; // 6 AM + const wakingHoursEnd = 22; // 10 PM + const totalWakingHours = wakingHoursEnd - wakingHoursStart; + + final intervalHours = totalWakingHours / remindersPerDay; + + List times = []; + final now = DateTime.now(); + + for (int i = 0; i < remindersPerDay; i++) { + final hourDecimal = wakingHoursStart + (i * intervalHours); + final hour = hourDecimal.floor(); + final minute = ((hourDecimal - hour) * 60).round(); + + final reminderTime = DateTime( + now.year, + now.month, + now.day, + hour, + minute, + ); + + times.add(reminderTime); + } + + return times; + } catch (e) { + log('Error calculating reminder times: $e'); + return []; + } + } + + /// Cancel all water reminders + Future cancelWaterReminders() async { + try { + final notificationService = GetIt.instance(); + + // Get pending notifications and cancel water reminders (IDs 5000-5999) + final pendingNotifications = await notificationService.getPendingNotifications(); + for (final notification in pendingNotifications) { + if (notification.id >= 5000 && notification.id < 6000) { + await notificationService.cancelNotification(notification.id); + } + } + + // Save reminder disabled state to cache + _isWaterReminderEnabled = false; + await _cacheService.saveBool(key: CacheConst.waterReminderEnabled, value: false); + + log('Cancelled all water reminders'); + notifyListeners(); + return true; + } catch (e) { + log('Exception in cancelWaterReminders: $e'); + return false; + } + } + + /// Get list of scheduled water reminder times + Future> getScheduledReminderTimes() async { + try { + final notificationService = GetIt.instance(); + final pendingNotifications = await notificationService.getPendingNotifications(); + + List times = []; + for (final notification in pendingNotifications) { + if (notification.id >= 5000 && notification.id < 6000) { + // Note: PendingNotificationRequest doesn't contain scheduled time + // We can only return the calculated times based on current settings + times = _calculateReminderTimes(); + break; + } + } + + return times; + } catch (e) { + log('Exception in getScheduledReminderTimes: $e'); + return []; + } + } + + /// Schedule a test notification after 5 seconds + /// Useful for testing notification functionality + Future scheduleTestNotification() async { + try { + final notificationService = GetIt.instance(); + + // Request permission first + final hasPermission = await notificationService.requestPermissions(); + if (!hasPermission) { + log('Notification permission denied for test notification'); + return false; + } + + // Schedule notification 5 seconds from now + final scheduledTime = DateTime.now().add(const Duration(seconds: 5)); + + await notificationService.scheduleNotification( + id: 9999, + // Use a unique ID for test notifications + title: 'Time to Drink Water! 💧'.needTranslation, + body: 'Stay hydrated! Drink ${selectedCupCapacityMl}ml of water.'.needTranslation, + scheduledDate: scheduledTime, + payload: 'test_notification', + ); + + log('Test notification scheduled for 5 seconds from now'); + return true; + } catch (e) { + log('Exception in scheduleTestNotification: $e'); + return false; + } + } +} diff --git a/lib/main.dart b/lib/main.dart index fd7654f..9600d5e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -30,8 +30,9 @@ import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_mo import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart'; import 'package:hmg_patient_app_new/features/smartwatch_health_data/health_provider.dart'; -import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; @@ -71,7 +72,7 @@ Future callInitializations() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); - AppDependencies.addDependencies(); + await AppDependencies.addDependencies(); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); HttpOverrides.global = MyHttpOverrides(); await callAppStateInitializations(); @@ -165,6 +166,9 @@ void main() async { ), ChangeNotifierProvider( create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), ) ], child: MyApp()), ), @@ -187,11 +191,7 @@ class MyApp extends StatelessWidget { return MaterialApp( title: 'Dr. AlHabib', builder: (context, mchild) { - return MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaler: TextScaler.linear(1.0), - ), - child: mchild!); + return MediaQuery(data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(1.0)), child: mchild!); }, showSemanticsDebugger: false, debugShowCheckedModeBanner: false, diff --git a/lib/presentation/appointments/appointment_queue_page.dart b/lib/presentation/appointments/appointment_queue_page.dart index 4554873..124bf25 100644 --- a/lib/presentation/appointments/appointment_queue_page.dart +++ b/lib/presentation/appointments/appointment_queue_page.dart @@ -42,8 +42,11 @@ class AppointmentQueuePage extends StatelessWidget { color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: false, - side: - BorderSide(color: myAppointmentsVM.isAppointmentQueueDetailsLoading ? AppColors.whiteColor : Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus), width: 2.w), + side: BorderSide( + color: myAppointmentsVM.isAppointmentQueueDetailsLoading + ? AppColors.whiteColor + : Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus), + width: 2.w), ), child: Padding( padding: EdgeInsets.all(16.h), @@ -62,17 +65,23 @@ class AppointmentQueuePage extends StatelessWidget { ], ).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 10.h), - "Hala ${appState!.getAuthenticatedUser()!.firstName}!!!".needTranslation.toText16(isBold: true).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), + "Hala ${appState!.getAuthenticatedUser()!.firstName}!!!" + .needTranslation + .toText16(isBold: true) + .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 8.h), "Thank you for your patience, here is your queue number." .needTranslation .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight) .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 8.h), - myAppointmentsVM.currentPatientQueueDetails.queueNo!.toText32(isBold: true).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), + myAppointmentsVM.currentPatientQueueDetails.queueNo! + .toText32(isBold: true) + .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 8.h), CustomButton( - text: Utils.getCardButtonText(myAppointmentsVM.currentQueueStatus, myAppointmentsVM.currentPatientQueueDetails.roomNo ?? ""), + text: Utils.getCardButtonText( + myAppointmentsVM.currentQueueStatus, myAppointmentsVM.currentPatientQueueDetails.roomNo ?? ""), onPressed: () {}, backgroundColor: Utils.getCardButtonColor(myAppointmentsVM.currentQueueStatus), borderColor: Utils.getCardButtonColor(myAppointmentsVM.currentQueueStatus).withValues(alpha: 0.01), @@ -94,61 +103,72 @@ class AppointmentQueuePage extends StatelessWidget { ? Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, - borderRadius: 20.h, - hasShadow: true, - ), - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Serving Now".needTranslation.toText16(isBold: true).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), + borderRadius: 20.h, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "Serving Now" + .needTranslation + .toText16(isBold: true) + .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 18.h), ListView.separated( - padding: EdgeInsets.zero, - shrinkWrap: true, + padding: EdgeInsets.zero, + shrinkWrap: true, itemCount: myAppointmentsVM.patientQueueDetailsList.length, physics: NeverScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - myAppointmentsVM.patientQueueDetailsList[index].queueNo!.toText17(isBold: true), - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - "Room: ${myAppointmentsVM.patientQueueDetailsList[index].roomNo}".toText12(fontWeight: FontWeight.w500), + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + myAppointmentsVM.patientQueueDetailsList[index].queueNo!.toText17(isBold: true), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + "Room: ${myAppointmentsVM.patientQueueDetailsList[index].roomNo}" + .toText12(fontWeight: FontWeight.w500), SizedBox(width: 8.w), AppCustomChipWidget( - deleteIcon: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? AppAssets.call_for_vitals : AppAssets.call_for_doctor, - labelText: - myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? "Call for vital signs".needTranslation : "Call for Doctor".needTranslation, - iconColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? AppColors.primaryRedColor : AppColors.successColor, - textColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? AppColors.primaryRedColor : AppColors.successColor, + deleteIcon: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 + ? AppAssets.call_for_vitals + : AppAssets.call_for_doctor, + labelText: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 + ? "Call for vital signs".needTranslation + : "Call for Doctor".needTranslation, + iconColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 + ? AppColors.primaryRedColor + : AppColors.successColor, + textColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 + ? AppColors.primaryRedColor + : AppColors.successColor, iconSize: 14.w, backgroundColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? AppColors.primaryRedColor.withValues(alpha: 0.1) : AppColors.successColor.withValues(alpha: 0.1), labelPadding: EdgeInsetsDirectional.only(start: 8.h, end: -2.h), ), - ], - ), - ], - ); - }, - separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 8.h), + ], + ), + ], + ); + }, + separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 8.h), ).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), ], ), - ), + ), ) : SizedBox.shrink(), SizedBox(height: 16.h), Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, - borderRadius: 20.h, + borderRadius: 24.4, hasShadow: true, ), child: Padding( @@ -171,15 +191,25 @@ class AppointmentQueuePage extends StatelessWidget { // Are there any side effects I should know about? // When should I come back for a follow-up? - "• ${"What can I do to improve my overall health?"}".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + "• ${"What can I do to improve my overall health?"}" + .needTranslation + .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"Are there any routine screenings I should get?"}".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + "• ${"Are there any routine screenings I should get?"}" + .needTranslation + .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"What is this medication for?"}".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + "• ${"What is this medication for?"}" + .needTranslation + .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"Are there any side effects I should know about?"}".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + "• ${"Are there any side effects I should know about?"}" + .needTranslation + .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"When should I come back for a follow-up?"}".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + "• ${"When should I come back for a follow-up?"}" + .needTranslation + .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 16.h), ], diff --git a/lib/presentation/e_referral/new_e_referral.dart b/lib/presentation/e_referral/new_e_referral.dart index b28b8df..3083de1 100644 --- a/lib/presentation/e_referral/new_e_referral.dart +++ b/lib/presentation/e_referral/new_e_referral.dart @@ -24,6 +24,7 @@ import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:hmg_patient_app_new/widgets/stepper/stepper_widget.dart'; import 'package:provider/provider.dart'; + import 'e-referral_validator.dart'; import 'e_referral_form_manager.dart'; @@ -43,7 +44,6 @@ class _NewReferralPageState extends State { double widthOfOneState = ((ResponsiveExtension.screenWidth) / 3) - (20.h); - @override void initState() { super.initState(); @@ -116,7 +116,7 @@ class _NewReferralPageState extends State { cityCode: _formManager.formData.patientCity!.iD!.toString(), cityName: _formManager.formData.patientCity!.description, requesterName: _formManager.formData.requesterName, - requesterContactNo: _formManager.formData.countryEnum.countryCode + _formManager.formData.requesterPhone, + requesterContactNo: _formManager.formData.countryEnum.countryCode + _formManager.formData.requesterPhone, requesterRelationship: _formManager.formData.relationship?.iD, otherRelationship: _formManager.formData.relationship!.iD.toString(), fullName: _formManager.formData.patientName, @@ -133,10 +133,8 @@ class _NewReferralPageState extends State { hmgServicesVM.createEReferral( requestModel: createReferralRequestModel, onSuccess: (GenericApiModel response) { - showSuccessBottomSheet(int.parse(response.data), hmgServicesVM); LoaderBottomSheet.hideLoader(); - }, onError: (errorMessage) { // Handle error (e.g., show error message) @@ -146,9 +144,6 @@ class _NewReferralPageState extends State { } void _loadData() { - - - final authVM = context.read(); final habibWalletVM = context.read(); final hmgServicesVM = context.read(); @@ -179,7 +174,7 @@ class _NewReferralPageState extends State { color: Colors.white, padding: EdgeInsets.all(ResponsiveExtension(20).h), child: CustomButton( - text: _currentStep <=1 ? LocaleKeys.next.tr() : LocaleKeys.submit.tr(), + text: _currentStep <= 1 ? LocaleKeys.next.tr() : LocaleKeys.submit.tr(), // icon: AppAssets.search_icon, iconColor: Colors.white, onPressed: () => {_handleNextStep()}, @@ -188,7 +183,7 @@ class _NewReferralPageState extends State { child: ChangeNotifierProvider.value( value: _formManager, child: SizedBox( - height: ResponsiveExtension.screenHeight * 0.65, + height: ResponsiveExtension.screenHeight * 0.65, child: Column( children: [ const SizedBox(height: 8), @@ -220,7 +215,6 @@ class _NewReferralPageState extends State { // ); } - showSuccessBottomSheet(int requestId, HmgServicesViewModel hmgServicesViewModel) { return showCommonBottomSheetWithoutHeight( context, @@ -232,9 +226,9 @@ class _NewReferralPageState extends State { Row( children: [ "Here is your Referral #: ".needTranslation.toText14( - color: AppColors.textColorLight, - weight: FontWeight.w500, - ), + color: AppColors.textColorLight, + weight: FontWeight.w500, + ), SizedBox(width: 4.w), ("$requestId").toText16(isBold: true), ], @@ -249,7 +243,7 @@ class _NewReferralPageState extends State { onPressed: () { context.pop(); context.pop(); - _currentStep =0; + _currentStep = 0; }, textColor: AppColors.whiteColor, ), diff --git a/lib/presentation/hmg_services/services_page.dart b/lib/presentation/hmg_services/services_page.dart index 118bc35..bf0b7f5 100644 --- a/lib/presentation/hmg_services/services_page.dart +++ b/lib/presentation/hmg_services/services_page.dart @@ -143,7 +143,7 @@ class ServicesPage extends StatelessWidget { AppAssets.daily_water_monitor_icon, bgColor: AppColors.whiteColor, true, - route: AppRoutes.eReferralPage, + route: AppRoutes.waterConsumptionScreen, ), HmgServicesComponentModel( 11, @@ -386,7 +386,7 @@ class ServicesPage extends StatelessWidget { SizedBox(height: 16.h), GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount:(isFoldable || isTablet) ? 6 : 4, // 4 icons per row + crossAxisCount: (isFoldable || isTablet) ? 6 : 4, // 4 icons per row crossAxisSpacing: 12.w, mainAxisSpacing: 18.h, childAspectRatio: 0.8, diff --git a/lib/presentation/home_health_care/hhc_procedures_page.dart b/lib/presentation/home_health_care/hhc_procedures_page.dart index 41d8a2f..be97a88 100644 --- a/lib/presentation/home_health_care/hhc_procedures_page.dart +++ b/lib/presentation/home_health_care/hhc_procedures_page.dart @@ -446,68 +446,62 @@ class _HhcProceduresPageState extends State { Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, - body: Column( - children: [ - Expanded( - child: CollapsingListView( - title: "Home Health Care".needTranslation, - history: () => Navigator.of(context).push(CustomPageRoute(page: HhcOrderDetailPage(), direction: AxisDirection.up)), - child: Consumer( - builder: (context, hmgServicesViewModel, child) { - if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) { - return _buildLoadingShimmer(); - } - final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList); - if (pendingOrder != null) { - return _buildPendingOrderCard(pendingOrder); - } else { - return Column( - children: [ - Center( - child: Utils.getNoDataWidget( - context, - noDataText: "You have no pending requests.".needTranslation, - ), - ), - ], - ); - } - }, - ), - ), - ), - Consumer( - builder: (BuildContext context, HmgServicesViewModel hmgServicesViewModel, Widget? child) { - if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) { - return SizedBox.shrink(); - } - final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList); - if (pendingOrder == null) { - return Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, + body: CollapsingListView( + title: "Home Health Care".needTranslation, + history: () => Navigator.of(context).push(CustomPageRoute(page: HhcOrderDetailPage(), direction: AxisDirection.up)), + bottomChild: Consumer( + builder: (BuildContext context, HmgServicesViewModel hmgServicesViewModel, Widget? child) { + if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) { + return SizedBox.shrink(); + } + final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList); + if (pendingOrder == null) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.w), + child: CustomButton( + borderWidth: 0, + text: "Create new request".needTranslation, + onPressed: () => _buildServicesListBottomsSheet(hmgServicesViewModel.hhcServicesList), + textColor: AppColors.whiteColor, + borderRadius: 12.r, + borderColor: Colors.transparent, + padding: EdgeInsets.symmetric(vertical: 14.h), ), - child: Padding( - padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 24.h, top: 24.h), - child: CustomButton( - borderWidth: 0, - text: "Create new request".needTranslation, - onPressed: () => _buildServicesListBottomsSheet(hmgServicesViewModel.hhcServicesList), - textColor: AppColors.whiteColor, - borderRadius: 12.r, - borderColor: Colors.transparent, - padding: EdgeInsets.symmetric(vertical: 14.h), + ), + ); + } + + return SizedBox.shrink(); + }, + ), + child: Consumer( + builder: (context, hmgServicesViewModel, child) { + if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) { + return _buildLoadingShimmer(); + } + final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList); + if (pendingOrder != null) { + return _buildPendingOrderCard(pendingOrder); + } else { + return Column( + children: [ + Center( + child: Utils.getNoDataWidget( + context, + noDataText: "You have no pending requests.".needTranslation, ), ), - ); - } - - return SizedBox.shrink(); - }, - ), - ], + ], + ); + } + }, + ), ), ); } diff --git a/lib/presentation/symptoms_checker/organ_selector_screen.dart b/lib/presentation/symptoms_checker/organ_selector_screen.dart index d5dc32c..c23b956 100644 --- a/lib/presentation/symptoms_checker/organ_selector_screen.dart +++ b/lib/presentation/symptoms_checker/organ_selector_screen.dart @@ -267,14 +267,15 @@ class _OrganSelectorPageState extends State { runSpacing: 8.h, children: viewModel.selectedOrgans.map((organ) { return AppCustomChipWidget( - labelText: organ.description, - backgroundColor: AppColors.secondaryLightRedColor, - textColor: AppColors.primaryRedColor, - deleteIcon: AppAssets.cancel, - deleteIconColor: AppColors.primaryRedColor, - deleteIconHasColor: false, - onDeleteTap: () => viewModel.removeOrgan(organ.id), - ); + labelText: organ.description, + backgroundColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + deleteIcon: AppAssets.cancel, + deleteIconColor: AppColors.primaryRedColor, + deleteIconHasColor: false, + onDeleteTap: () { + viewModel.removeOrgan(organ.id); + }); }).toList(), ), ), diff --git a/lib/presentation/symptoms_checker/risk_factors_screen.dart b/lib/presentation/symptoms_checker/risk_factors_screen.dart index 2992593..d4ff2cb 100644 --- a/lib/presentation/symptoms_checker/risk_factors_screen.dart +++ b/lib/presentation/symptoms_checker/risk_factors_screen.dart @@ -1,16 +1,15 @@ -import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.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/symptoms_checker/symptoms_checker_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/buttons/custom_button.dart'; -import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:provider/provider.dart'; class RiskFactorsScreen extends StatefulWidget { @@ -24,23 +23,24 @@ class _RiskFactorsScreenState extends State { @override void initState() { super.initState(); - // Initialize symptom groups based on selected organs + // Fetch risk factors based on selected symptoms WidgetsBinding.instance.addPostFrameCallback((_) { final viewModel = context.read(); - viewModel.initializeSymptomGroups(); + viewModel.fetchRiskFactors(); }); } - void _onOptionSelected(int optionIndex) {} + void _onRiskFactorSelected(SymptomsCheckerViewModel viewModel, String riskFactorId) { + viewModel.toggleRiskFactorSelection(riskFactorId); + } void _onNextPressed(SymptomsCheckerViewModel viewModel) { - if (viewModel.hasSelectedSymptoms) { - // Navigate to triage screen + if (viewModel.hasSelectedRiskFactors) { context.navigateWithName(AppRoutes.suggestionsScreen); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text('Please select at least one option before proceeding'.needTranslation), + content: Text('Please select at least one risk before proceeding'.needTranslation), backgroundColor: AppColors.errorColor, ), ); @@ -51,27 +51,13 @@ class _RiskFactorsScreenState extends State { context.pop(); } - _buildConfirmationBottomSheet({required BuildContext context, required VoidCallback onConfirm}) { - return showCommonBottomSheetWithoutHeight( - title: LocaleKeys.notice.tr(context: context), - context, - child: Utils.getWarningWidget( - loadingText: "Are you sure you want to restart the organ selection?".needTranslation, - isShowActionButtons: true, - onCancelTap: () => Navigator.pop(context), - onConfirmTap: () => onConfirm(), - ), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - } + Widget _buildRiskFactorItem(SymptomsCheckerViewModel viewModel, String riskFactorId, String optionText) { + final bool selected = viewModel.isRiskFactorSelected(riskFactorId); - Widget _buildOptionItem(int index, bool selected, String optionText) { return GestureDetector( - onTap: () => _onOptionSelected(index), + onTap: () => _onRiskFactorSelected(viewModel, riskFactorId), child: Container( - margin: EdgeInsets.only(bottom: 12.h), + margin: EdgeInsets.only(bottom: 16.h), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -83,56 +69,137 @@ class _RiskFactorsScreenState extends State { decoration: BoxDecoration( color: selected ? AppColors.primaryRedColor : Colors.transparent, borderRadius: BorderRadius.circular(5.r), - border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.borderGrayColor, width: 1.w), + border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.checkBoxBorderColor, width: 1.w), ), child: selected ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null, ), SizedBox(width: 12.w), Expanded( - child: Text( - optionText, - style: TextStyle(fontSize: 14.f, color: AppColors.textColor, fontWeight: FontWeight.w500), - ), - ), + child: optionText.toText14( + color: riskFactorId == "not_applicable" ? AppColors.errorColor : AppColors.textColor, + weight: FontWeight.w500, + )), ], ), ), ); } - Widget buildFactorsList() { - return AnimatedSwitcher( - duration: const Duration(milliseconds: 400), - transitionBuilder: (Widget child, Animation animation) { - final offsetAnimation = Tween( - begin: const Offset(1.0, 0.0), - end: Offset.zero, - ).animate(CurvedAnimation( - parent: animation, - curve: Curves.easeInOut, - )); - - return SlideTransition( - position: offsetAnimation, - child: FadeTransition( - opacity: animation, - child: child, + Widget _buildRiskFactorsList(SymptomsCheckerViewModel viewModel) { + return Container( + key: ValueKey(viewModel.riskFactorsList.length), + width: double.infinity, + margin: EdgeInsets.symmetric(horizontal: 24.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), + padding: EdgeInsets.only(top: 24.h, left: 16.w, right: 16.w, bottom: 8.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ...viewModel.riskFactorsList.map((factor) { + return _buildRiskFactorItem(viewModel, factor.id ?? '', factor.getDisplayName()); + }), + SizedBox(height: 12.w), + Row( + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.alertSquare, + height: 24.h, + width: 24.h, + iconColor: AppColors.textColor, + ), + SizedBox(width: 12.w), + Expanded( + child: RichText( + text: TextSpan( + style: TextStyle( + height: 1.3, + fontSize: 13.f, + fontWeight: FontWeight.w500, + color: AppColors.greyInfoTextColor, + ), + children: [ + TextSpan( + text: "Above you see the most common risk factors. Although /diagnosis may return questions about risk factors, " + .needTranslation, + ), + TextSpan( + text: "read more".needTranslation, + style: TextStyle( + color: AppColors.primaryRedColor, + fontWeight: FontWeight.w500, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + // handle tap - navigate or show bottom sheet + debugPrint('Read more tapped'); + // Example: Navigator.push(context, MaterialPageRoute(builder: (_) => RiskFactorsDetailScreen())); + }, + ), + ], + ), + ), + ) + ], ), - ); - }, - child: Container( - width: double.infinity, - margin: EdgeInsets.symmetric(horizontal: 24.w), - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), - padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 20.w), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ...List.generate(4, (index) { - return _buildOptionItem(index, false, "currentQuestion.options[index].text"); + ], + ), + ); + } + + Widget _buildLoadingShimmer() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + // Create 2-3 shimmer cards + ...List.generate(3, (index) { + return Padding( + padding: EdgeInsets.only(bottom: 16.h), + child: _buildShimmerCard(), + ); + }), + ], + ); + } + + Widget _buildShimmerCard() { + return Container( + width: double.infinity, + margin: EdgeInsets.symmetric(horizontal: 24.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), + padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Shimmer title + Container( + height: 40.h, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(24.r), + ), + ).toShimmer2(isShow: true, radius: 24.r), + SizedBox(height: 16.h), + // Shimmer chips + Wrap( + runSpacing: 12.h, + spacing: 8.w, + children: List.generate(4, (index) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h), + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(24.r), + border: Border.all(color: AppColors.bottomNAVBorder, width: 1), + ), + child: Text( + 'Not Applicable Risk Factor', + style: TextStyle(fontSize: 14.f, color: AppColors.textColor), + ), + ).toShimmer2(isShow: true, radius: 24.r); }), - ], - ), + ), + ], ), ); } @@ -147,68 +214,19 @@ class _RiskFactorsScreenState extends State { children: [ Expanded( child: CollapsingListView( - title: "Risks".needTranslation, - leadingCallback: () => _buildConfirmationBottomSheet( - context: context, - onConfirm: () => { - context.pop(), - context.pop(), - }), - child: _buildEmptyState(), - // child: viewModel.organSymptomsGroups.isEmpty - // ? _buildEmptyState() - // : Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // SizedBox(height: 16.h), - // ...viewModel.organSymptomsGroups.map((group) { - // return Padding( - // padding: EdgeInsets.only(bottom: 16.h), - // child: Container( - // width: double.infinity, - // margin: EdgeInsets.symmetric(horizontal: 24.w), - // decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), - // padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), - // child: Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // Row( - // mainAxisAlignment: MainAxisAlignment.spaceBetween, - // children: [ - // Expanded( - // child: Text( - // 'Possible symptoms related to "${group.organName}"', - // style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), - // ), - // ), - // ], - // ), - // SizedBox(height: 24.h), - // Wrap( - // runSpacing: 12.h, - // spacing: 8.w, - // children: group.symptoms.map((symptom) { - // bool isSelected = viewModel.isSymptomSelected(group.organId, symptom.id); - // return GestureDetector( - // onTap: () => viewModel.toggleSymptomSelection(group.organId, symptom.id), - // child: CustomSelectableChip( - // label: symptom.name, - // selected: isSelected, - // activeColor: AppColors.primaryRedBorderColor, - // activeTextColor: AppColors.primaryRedBorderColor, - // inactiveBorderColor: AppColors.bottomNAVBorder, - // inactiveTextColor: AppColors.textColor, - // ), - // ); - // }).toList(), - // ), - // ], - // ), - // ), - // ); - // }), - // ], - // ), + title: "Risk Factors".needTranslation, + leadingCallback: () => context.pop(), + child: viewModel.isRiskFactorsLoading + ? _buildLoadingShimmer() + : viewModel.riskFactorsList.isEmpty + ? _buildEmptyState() + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + _buildRiskFactorsList(viewModel), + ], + ), ), ), _buildStickyBottomCard(context, viewModel), @@ -229,7 +247,7 @@ class _RiskFactorsScreenState extends State { Icon(Icons.info_outline, size: 64.h, color: AppColors.greyTextColor), SizedBox(height: 16.h), Text( - 'No organs selected'.needTranslation, + 'No risk factors found'.needTranslation, style: TextStyle( fontSize: 18.f, fontWeight: FontWeight.w600, @@ -238,7 +256,7 @@ class _RiskFactorsScreenState extends State { ), SizedBox(height: 8.h), Text( - 'Please go back and select organs first'.needTranslation, + 'Based on your selected symptoms, no additional risk factors were identified.'.needTranslation, textAlign: TextAlign.center, style: TextStyle( fontSize: 14.f, diff --git a/lib/presentation/symptoms_checker/suggestions_screen.dart b/lib/presentation/symptoms_checker/suggestions_screen.dart index 2832515..f2aa71e 100644 --- a/lib/presentation/symptoms_checker/suggestions_screen.dart +++ b/lib/presentation/symptoms_checker/suggestions_screen.dart @@ -1,16 +1,14 @@ -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/app_export.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/symptoms_checker/symptoms_checker_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/buttons/custom_button.dart'; -import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:provider/provider.dart'; class SuggestionsScreen extends StatefulWidget { @@ -27,14 +25,18 @@ class _SuggestionsScreenState extends State { // Initialize symptom groups based on selected organs WidgetsBinding.instance.addPostFrameCallback((_) { final viewModel = context.read(); - viewModel.initializeSymptomGroups(); + viewModel.fetchSuggestions(); }); } void _onOptionSelected(int optionIndex) {} + void _onSuggestionSelected(SymptomsCheckerViewModel viewModel, String suggestionId) { + viewModel.toggleSuggestionsSelection(suggestionId); + } + void _onNextPressed(SymptomsCheckerViewModel viewModel) { - if (viewModel.hasSelectedSymptoms) { + if (viewModel.hasSelectedSuggestions) { // Navigate to triage screen context.navigateWithName(AppRoutes.triageScreen); } else { @@ -51,27 +53,13 @@ class _SuggestionsScreenState extends State { context.pop(); } - _buildConfirmationBottomSheet({required BuildContext context, required VoidCallback onConfirm}) { - return showCommonBottomSheetWithoutHeight( - title: LocaleKeys.notice.tr(context: context), - context, - child: Utils.getWarningWidget( - loadingText: "Are you sure you want to restart the organ selection?".needTranslation, - isShowActionButtons: true, - onCancelTap: () => Navigator.pop(context), - onConfirmTap: () => onConfirm(), - ), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - } + Widget _buildSuggestionItem(SymptomsCheckerViewModel viewModel, String suggestionId, String optionText) { + final bool selected = viewModel.isSuggestionsSelected(suggestionId); - Widget _buildOptionItem(int index, bool selected, String optionText) { return GestureDetector( - onTap: () => _onOptionSelected(index), + onTap: () => _onSuggestionSelected(viewModel, suggestionId), child: Container( - margin: EdgeInsets.only(bottom: 12.h), + margin: EdgeInsets.only(bottom: 16.h), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -83,56 +71,111 @@ class _SuggestionsScreenState extends State { decoration: BoxDecoration( color: selected ? AppColors.primaryRedColor : Colors.transparent, borderRadius: BorderRadius.circular(5.r), - border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.borderGrayColor, width: 1.w), + border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.checkBoxBorderColor, width: 1.w), ), child: selected ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null, ), SizedBox(width: 12.w), Expanded( - child: Text( - optionText, - style: TextStyle(fontSize: 14.f, color: AppColors.textColor, fontWeight: FontWeight.w500), - ), - ), + child: optionText.toText14( + color: suggestionId == "not_applicable" ? AppColors.errorColor : AppColors.textColor, + weight: FontWeight.w500, + )), ], ), ), ); } - Widget buildFactorsList() { - return AnimatedSwitcher( - duration: const Duration(milliseconds: 400), - transitionBuilder: (Widget child, Animation animation) { - final offsetAnimation = Tween( - begin: const Offset(1.0, 0.0), - end: Offset.zero, - ).animate(CurvedAnimation( - parent: animation, - curve: Curves.easeInOut, - )); - - return SlideTransition( - position: offsetAnimation, - child: FadeTransition( - opacity: animation, - child: child, + Widget _buildSuggestionsList(SymptomsCheckerViewModel viewModel) { + return Container( + key: ValueKey(viewModel.suggestionsList.length), + width: double.infinity, + margin: EdgeInsets.symmetric(horizontal: 24.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), + padding: EdgeInsets.only(top: 24.h, left: 16.w, right: 16.w, bottom: 8.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ...viewModel.suggestionsList.map((factor) { + return _buildSuggestionItem(viewModel, factor.id ?? '', factor.getDisplayName()); + }), + SizedBox(height: 12.w), + Row( + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.alertSquare, + height: 24.h, + width: 24.h, + iconColor: AppColors.textColor, + ), + SizedBox(width: 12.w), + Expanded( + child: "This is a list of symptoms suggested by our AI, based on the information gathered so far during the interview".toText12( + color: AppColors.greyInfoTextColor, + ), + ) + ], ), - ); - }, - child: Container( - width: double.infinity, - margin: EdgeInsets.symmetric(horizontal: 24.w), - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), - padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 20.w), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ...List.generate(4, (index) { - return _buildOptionItem(index, false, "currentQuestion.options[index].text"); + ], + ), + ); + } + + Widget _buildLoadingShimmer() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + // Create 2-3 shimmer cards + ...List.generate(3, (index) { + return Padding( + padding: EdgeInsets.only(bottom: 16.h), + child: _buildShimmerCard(), + ); + }), + ], + ); + } + + Widget _buildShimmerCard() { + return Container( + width: double.infinity, + margin: EdgeInsets.symmetric(horizontal: 24.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), + padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Shimmer title + Container( + height: 40.h, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(24.r), + ), + ).toShimmer2(isShow: true, radius: 24.r), + SizedBox(height: 16.h), + // Shimmer chips + Wrap( + runSpacing: 12.h, + spacing: 8.w, + children: List.generate(4, (index) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h), + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(24.r), + border: Border.all(color: AppColors.bottomNAVBorder, width: 1), + ), + child: Text( + 'Not Applicable Suggestion', + style: TextStyle(fontSize: 14.f, color: AppColors.textColor), + ), + ).toShimmer2(isShow: true, radius: 24.r); }), - ], - ), + ), + ], ), ); } @@ -148,68 +191,18 @@ class _SuggestionsScreenState extends State { Expanded( child: CollapsingListView( title: "Suggestions".needTranslation, - leadingCallback: () => _buildConfirmationBottomSheet( - context: context, - onConfirm: () => { - context.pop(), - context.pop(), - }), - child: _buildEmptyState(), - - // child: viewModel.organSymptomsGroups.isEmpty - // ? _buildEmptyState() - // : Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // SizedBox(height: 16.h), - // ...viewModel.organSymptomsGroups.map((group) { - // return Padding( - // padding: EdgeInsets.only(bottom: 16.h), - // child: Container( - // width: double.infinity, - // margin: EdgeInsets.symmetric(horizontal: 24.w), - // decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), - // padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), - // child: Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // Row( - // mainAxisAlignment: MainAxisAlignment.spaceBetween, - // children: [ - // Expanded( - // child: Text( - // 'Possible symptoms related to "${group.organName}"', - // style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), - // ), - // ), - // ], - // ), - // SizedBox(height: 24.h), - // Wrap( - // runSpacing: 12.h, - // spacing: 8.w, - // children: group.symptoms.map((symptom) { - // bool isSelected = viewModel.isSymptomSelected(group.organId, symptom.id); - // return GestureDetector( - // onTap: () => viewModel.toggleSymptomSelection(group.organId, symptom.id), - // child: CustomSelectableChip( - // label: symptom.name, - // selected: isSelected, - // activeColor: AppColors.primaryRedBorderColor, - // activeTextColor: AppColors.primaryRedBorderColor, - // inactiveBorderColor: AppColors.bottomNAVBorder, - // inactiveTextColor: AppColors.textColor, - // ), - // ); - // }).toList(), - // ), - // ], - // ), - // ), - // ); - // }), - // ], - // ), + leadingCallback: () => context.pop(), + child: viewModel.isSuggestionsLoading + ? _buildLoadingShimmer() + : viewModel.suggestionsList.isEmpty + ? _buildEmptyState() + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + _buildSuggestionsList(viewModel), + ], + ), ), ), _buildStickyBottomCard(context, viewModel), diff --git a/lib/presentation/symptoms_checker/triage_screen.dart b/lib/presentation/symptoms_checker/triage_screen.dart index aa0cd72..ff0482e 100644 --- a/lib/presentation/symptoms_checker/triage_screen.dart +++ b/lib/presentation/symptoms_checker/triage_screen.dart @@ -148,10 +148,7 @@ class _TriageScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - currentQuestion.question, - style: TextStyle(fontSize: 16.f, fontWeight: FontWeight.w500, color: AppColors.textColor), - ), + currentQuestion.question.toText16(weight: FontWeight.w500), SizedBox(height: 24.h), ...List.generate(currentQuestion.options.length, (index) { bool selected = currentQuestion.selectedOptionIndex == index; @@ -179,17 +176,12 @@ class _TriageScreenState extends State { decoration: BoxDecoration( color: selected ? AppColors.primaryRedColor : Colors.transparent, borderRadius: BorderRadius.circular(5.r), - border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.borderGrayColor, width: 1.w), + border: Border.all(color: selected ? AppColors.primaryRedColor : AppColors.checkBoxBorderColor, width: 1.w), ), child: selected ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null, ), SizedBox(width: 12.w), - Expanded( - child: Text( - optionText, - style: TextStyle(fontSize: 14.f, color: AppColors.textColor, fontWeight: FontWeight.w500), - ), - ), + Expanded(child: optionText.toText14(weight: FontWeight.w500)), ], ), ), diff --git a/lib/presentation/water_monitor/water_consumption_screen.dart b/lib/presentation/water_monitor/water_consumption_screen.dart new file mode 100644 index 0000000..e91abf6 --- /dev/null +++ b/lib/presentation/water_monitor/water_consumption_screen.dart @@ -0,0 +1,829 @@ +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_export.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/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/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/hydration_tips_widget.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_intake_summary_widget.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'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart'; +import 'package:provider/provider.dart'; +import 'package:shimmer/shimmer.dart'; + +class WaterConsumptionScreen extends StatefulWidget { + const WaterConsumptionScreen({super.key}); + + @override + State createState() => _WaterConsumptionScreenState(); +} + +class _WaterConsumptionScreenState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) async { + await _refreshData(); + }); + } + + /// Refresh data by calling initialize on the view model + Future _refreshData() async { + final vm = context.read(); + await vm.initialize(); + } + + Widget _buildLoadingShimmer({bool isForHistory = true}) { + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.all(0.w), + itemCount: 4, + separatorBuilder: (_, __) => SizedBox(height: 12.h), + itemBuilder: (context, index) { + return Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Container( + height: isForHistory ? 60.h : 40.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(10.r), + ), + ), + ); + }, + ); + } + + Widget buildHistoryListTile({required String title, required String subTitle}) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title.toText14(weight: FontWeight.w500, color: AppColors.labelTextColor), + subTitle.toText18(weight: FontWeight.w600), + ], + ), + Utils.buildSvgWithAssets(icon: AppAssets.greenTickIcon) + ], + ).paddingSymmetrical(0, 8.h); + } + + Widget _buildHistoryGraphOrList() { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Consumer(builder: (BuildContext context, WaterMonitorViewModel viewModel, Widget? child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "History".needTranslation.toText16(isBold: true), + Row( + children: [ + InkWell( + onTap: () => viewModel.setGraphView(!viewModel.isGraphView), + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + transitionBuilder: (Widget child, Animation animation) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + child: child, + ), + ); + }, + child: Container( + key: ValueKey(viewModel.isGraphView), + child: Utils.buildSvgWithAssets( + icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon, + height: 24.h, + width: 24.h, + ), + ), + ), + ), + SizedBox(width: 8.w), + InkWell( + onTap: () => _showHistoryDurationBottomsheet(context, viewModel), + child: Utils.buildSvgWithAssets(icon: AppAssets.doctor_calendar_icon, height: 24.h, width: 24.h)) + ], + ), + ], + ), + SizedBox(height: 12.h), + if (!viewModel.isGraphView) _buildHistoryListView(viewModel) else _buildHistoryGraph() + ], + ); + }), + ); + } + + Widget _buildHistoryListView(WaterMonitorViewModel viewModel) { + final selectedDuration = viewModel.selectedDurationFilter; + + // Build list items based on duration + List listItems = []; + + if (selectedDuration == 'Daily') { + if (viewModel.todayProgressList.isNotEmpty) { + final todayData = viewModel.todayProgressList.first; + listItems.add( + buildHistoryListTile( + title: "Today's Progress", + subTitle: "${todayData.quantityConsumed?.toStringAsFixed(0) ?? '0'} ml / ${todayData.quantityLimit?.toStringAsFixed(0) ?? '0'} ml", + ), + ); + listItems.add(Divider(height: 1, color: AppColors.dividerColor)); + listItems.add( + buildHistoryListTile( + title: "Percentage Completed", + subTitle: "${todayData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%", + ), + ); + + // Add history data if available (show ALL entries) + if (viewModel.historyList.isNotEmpty) { + listItems.add(Divider(height: 1, color: AppColors.dividerColor)); + listItems.add( + Padding( + padding: EdgeInsets.symmetric(vertical: 8.h), + child: "Water Intake History".toText14( + weight: FontWeight.w600, + color: AppColors.textColor, + ), + ), + ); + + // Show all history entries + for (var history in viewModel.historyList) { + final quantity = "${history.quantity?.toStringAsFixed(0) ?? '0'} ml"; + final time = _formatHistoryDate(history.createdDate ?? ''); + + listItems.add( + buildHistoryListTile( + title: quantity, + subTitle: time, + ), + ); + + if (history != viewModel.historyList.last) { + listItems.add(Divider(height: 1, color: AppColors.dividerColor)); + } + } + } + } else { + listItems.add( + Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 16.h), + child: "No data available for today".toText14(color: AppColors.greyTextColor), + ), + ), + ); + } + } else if (selectedDuration == 'Weekly') { + if (viewModel.weekProgressList.isNotEmpty) { + // Show previous 6 days + today (total 7 days) + // API returns data in reverse order (today first), so we reverse it to show oldest to newest (top to bottom) + // This ensures today appears at the end (bottom) + final totalDays = viewModel.weekProgressList.length; + final startIndex = totalDays > 7 ? totalDays - 7 : 0; + final weekDataToShow = viewModel.weekProgressList.skip(startIndex).toList().reversed.toList(); + + for (var dayData in weekDataToShow) { + listItems.add( + buildHistoryListTile( + title: dayData.dayName ?? 'Unknown', + subTitle: "${dayData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%", + ), + ); + if (dayData != weekDataToShow.last) { + listItems.add(Divider(height: 1, color: AppColors.dividerColor)); + } + } + } else { + listItems.add( + Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 16.h), + child: "No data available for this week".toText14(color: AppColors.greyTextColor), + ), + ), + ); + } + } else if (selectedDuration == 'Monthly') { + if (viewModel.monthProgressList.isNotEmpty) { + // Show last 6 months + current month (total 7 months) + // Show in chronological order: oldest to newest (top to bottom) + final totalMonths = viewModel.monthProgressList.length; + final startIndex = totalMonths > 7 ? totalMonths - 7 : 0; + final monthDataToShow = viewModel.monthProgressList.skip(startIndex).toList(); + + for (var monthData in monthDataToShow) { + listItems.add( + buildHistoryListTile( + title: monthData.monthName ?? 'Unknown', + subTitle: "${monthData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%", + ), + ); + if (monthData != monthDataToShow.last) { + listItems.add(Divider(height: 1, color: AppColors.dividerColor)); + } + } + } else { + listItems.add( + Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 16.h), + child: "No data available for this year".toText14(color: AppColors.greyTextColor), + ), + ), + ); + } + } + + // Return scrollable list with min and max height constraints + return ConstrainedBox( + constraints: BoxConstraints(minHeight: 80.h, maxHeight: 270.h), + child: viewModel.isLoading + ? _buildLoadingShimmer().paddingOnly(top: 16.h) + : listItems.isEmpty + ? Center( + child: "No history data available".toText14(color: AppColors.greyTextColor), + ) + : ListView.separated( + padding: EdgeInsets.only(top: 16.h), + shrinkWrap: true, + itemCount: listItems.length, + separatorBuilder: (context, index) => SizedBox.shrink(), + itemBuilder: (context, index) => listItems[index], + ), + ); + } + + Widget _buildHistoryGraph() { + return Consumer( + builder: (context, viewModel, _) { + final selectedDuration = viewModel.selectedDurationFilter; + + // Build dynamic data points based on selected duration + List dataPoints = []; + + if (selectedDuration == 'Daily') { + // For daily, show last 7 history entries with at least 5 minutes difference + if (viewModel.historyList.isNotEmpty) { + // Filter entries with at least 5 minutes difference + List filteredPoints = []; + DateTime? lastTime; + + for (var historyItem in viewModel.historyList) { + final currentTime = _parseHistoryDate(historyItem.createdDate ?? ''); + + // Add if first entry OR if more than 5 minutes difference from last added entry + if (lastTime == null || currentTime.difference(lastTime).inMinutes.abs() >= 5) { + final quantity = historyItem.quantity?.toDouble() ?? 0.0; + final time = _formatHistoryDate(historyItem.createdDate ?? ''); + + filteredPoints.add( + DataPoint( + value: quantity, + actualValue: quantity.toStringAsFixed(0), + label: time, + displayTime: time, + unitOfMeasurement: 'ml', + time: currentTime, + ), + ); + lastTime = currentTime; + } + } + + // Take only last 7 filtered entries + final totalFiltered = filteredPoints.length; + final startIndex = totalFiltered > 7 ? totalFiltered - 7 : 0; + dataPoints = filteredPoints.skip(startIndex).toList(); + } else if (viewModel.todayProgressList.isNotEmpty) { + // Fallback: show today's percentage if no history + final todayData = viewModel.todayProgressList.first; + final percentage = todayData.percentageConsumed?.toDouble() ?? 0.0; + dataPoints.add( + DataPoint( + value: percentage, + actualValue: percentage.toStringAsFixed(1), + label: 'Today', + displayTime: 'Today', + unitOfMeasurement: '%', + time: DateTime.now(), + ), + ); + } + } else if (selectedDuration == 'Weekly') { + // For weekly, show previous 6 days + today (total 7 days) + // API returns data in reverse order (today first), so we reverse it to show oldest to newest (left to right) + // This ensures today appears at the end (right side) + if (viewModel.weekProgressList.isNotEmpty) { + final totalDays = viewModel.weekProgressList.length; + final startIndex = totalDays > 7 ? totalDays - 7 : 0; + final weekDataToShow = viewModel.weekProgressList.skip(startIndex).toList().reversed.toList(); + + for (var dayData in weekDataToShow) { + final percentage = dayData.percentageConsumed?.toDouble() ?? 0.0; + final dayName = dayData.dayName ?? 'Day ${dayData.dayNumber}'; + dataPoints.add( + DataPoint( + value: percentage, + actualValue: percentage.toStringAsFixed(1), + label: DateUtil.getShortWeekDayName(dayName), + displayTime: dayName, + unitOfMeasurement: '%', + time: DateTime.now(), + ), + ); + } + } + } else if (selectedDuration == 'Monthly') { + // For monthly, show last 6 months + current month (total 7 months) + // Show in chronological order: oldest to newest (left to right) + if (viewModel.monthProgressList.isNotEmpty) { + final totalMonths = viewModel.monthProgressList.length; + final startIndex = totalMonths > 7 ? totalMonths - 7 : 0; + final monthDataToShow = viewModel.monthProgressList.skip(startIndex).toList(); + + for (var monthData in monthDataToShow) { + final percentage = monthData.percentageConsumed?.toDouble() ?? 0.0; + final monthName = monthData.monthName ?? 'Month ${monthData.monthNumber}'; + dataPoints.add( + DataPoint( + value: percentage, + actualValue: percentage.toStringAsFixed(1), + label: DateUtil.getShortMonthName(monthName), + displayTime: monthName, + unitOfMeasurement: '%', + time: DateTime.now(), + ), + ); + } + } + } + + // If no data, show empty state + if (dataPoints.isEmpty) { + return Container( + padding: EdgeInsets.symmetric(vertical: 80.h), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.graphIcon, + iconColor: AppColors.greyTextColor.withValues(alpha: 0.5), + height: 32.w, + width: 32.w, + ), + SizedBox(height: 12.h), + "No graph data available".toText14(color: AppColors.greyTextColor), + ], + ), + ), + ); + } + + // Show loading shimmer while fetching data + if (viewModel.isLoading) { + return Container( + padding: EdgeInsets.symmetric(vertical: 40.h), + child: _buildLoadingShimmer(), + ); + } + + // Configure graph based on selected duration + double maxY; + double minY; + double horizontalInterval; + double leftLabelInterval; + + if (selectedDuration == 'Daily') { + // For daily (quantity in ml), use max available cup size + // Get the biggest cup from available cups + final maxCupSize = viewModel.cups.isEmpty ? 500.0 : viewModel.cups.map((cup) => cup.capacityMl.toDouble()).reduce((a, b) => a > b ? a : b); + + maxY = maxCupSize; + minY = 0; + // Divide into 4 intervals (5 labels: 0, 1/4, 1/2, 3/4, max) + horizontalInterval = maxY / 4; + leftLabelInterval = maxY / 4; + } else { + // For weekly/monthly (percentage), use 0-100% + maxY = 100.0; + minY = 0; + horizontalInterval = 25; + leftLabelInterval = 25; + } + + return CustomGraph( + bottomLabelReservedSize: 30, + dataPoints: dataPoints, + makeGraphBasedOnActualValue: true, + leftLabelReservedSize: 50.h, + showGridLines: true, + maxY: maxY, + minY: minY, + maxX: dataPoints.length > 1 ? dataPoints.length.toDouble() - 0.75 : 1.0, + horizontalInterval: horizontalInterval, + leftLabelInterval: leftLabelInterval, + showShadow: true, + getDrawingHorizontalLine: (value) { + // Draw dashed lines at intervals + if (selectedDuration == 'Daily') { + // For daily, draw lines every 50 or 100 ml + if (value % horizontalInterval == 0 && value > 0) { + return FlLine( + color: AppColors.greyTextColor.withValues(alpha: 0.3), + strokeWidth: 1.5, + dashArray: [8, 4], + ); + } + } else { + // For weekly/monthly, draw lines at 25%, 50%, 75% + if (value == 25 || value == 50 || value == 75) { + return FlLine( + color: AppColors.successColor.withValues(alpha: 0.3), + strokeWidth: 1.5, + dashArray: [8, 4], + ); + } + } + return FlLine(color: AppColors.transparent, strokeWidth: 0); + }, + leftLabelFormatter: (value) { + if (selectedDuration == 'Daily') { + // Show exactly 5 labels: 0, 1/4, 1/2, 3/4, max + // Check if value matches one of the 5 positions + final interval = maxY / 4; + final positions = [0.0, interval, interval * 2, interval * 3, maxY]; + + for (var position in positions) { + if ((value - position).abs() < 1) { + return '${value.toInt()}ml'.toText10(weight: FontWeight.w600); + } + } + } else { + // Show percentage labels + if (value == 0) return '0%'.toText10(weight: FontWeight.w600); + if (value == 25) return '25%'.toText10(weight: FontWeight.w600); + if (value == 50) return '50%'.toText10(weight: FontWeight.w600); + if (value == 75) return '75%'.toText10(weight: FontWeight.w600); + if (value == 100) return '100%'.toText10(weight: FontWeight.w600); + } + return SizedBox.shrink(); + }, + graphColor: AppColors.successColor, + graphShadowColor: AppColors.successColor.withValues(alpha: 0.15), + bottomLabelFormatter: (value, data) { + if (data.isEmpty) return SizedBox.shrink(); + + // Only show labels for whole number positions (not fractional) + if ((value - value.round()).abs() > 0.01) { + return SizedBox.shrink(); + } + + int index = value.round(); + if (index < 0 || index >= data.length) return SizedBox.shrink(); + + // For daily, show all 7 time labels (last 7 entries) + if (selectedDuration == 'Daily' && index < 7) { + return Padding( + padding: EdgeInsets.only(top: 5.h), + child: data[index].label.toText8( + fontWeight: FontWeight.w600, + color: AppColors.labelTextColor, + ), + ); + } + + // For weekly, show all 7 days (today + last 6 days) + if (selectedDuration == 'Weekly' && index < 7) { + return Padding( + padding: EdgeInsets.only(top: 5.h), + child: data[index].label.toText10( + weight: FontWeight.w600, + color: AppColors.labelTextColor, + ), + ); + } + + // For monthly, show all 7 months (current month + last 6 months) + if (selectedDuration == 'Monthly' && index < 7) { + return Padding( + padding: EdgeInsets.only(top: 5.h), + child: data[index].label.toText10( + weight: FontWeight.w600, + color: AppColors.labelTextColor, + ), + ); + } + + return SizedBox.shrink(); + }, + scrollDirection: selectedDuration == 'Monthly' ? Axis.horizontal : Axis.vertical, + height: 250.h, + spotColor: AppColors.successColor, + ); + }, + ); + } + + // Reusable method to build selection row widget + Widget _buildSelectionRow({ + required String value, + required String groupValue, + required VoidCallback onTap, + bool useUpperCase = false, + }) { + return SizedBox( + height: 70.h, + child: Row( + spacing: 8.h, + children: [ + Radio( + value: value, + groupValue: groupValue, + activeColor: AppColors.errorColor, + onChanged: (_) => onTap(), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + (useUpperCase ? value.toUpperCase() : value.toCamelCase) + .toText16(weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1) + .expanded, + ], + ).onPress(onTap), + ); + } + + void _showSelectionBottomSheet({ + required BuildContext context, + required String title, + required List items, + required String selectedValue, + required Function(String) onSelected, + bool useUpperCase = false, + }) { + final dialogService = getIt.get(); + + dialogService.showFamilyBottomSheetWithoutHWithChild( + label: title.needTranslation, + message: "", + child: Container( + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: BoxDecoration(color: AppColors.whiteColor, borderRadius: BorderRadius.circular(20.r)), + child: ListView.separated( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return _buildSelectionRow( + value: item, + groupValue: selectedValue, + useUpperCase: useUpperCase, + onTap: () { + onSelected(item); + Navigator.pop(context); + }, + ); + }, + separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor), + ), + ), + onOkPressed: () {}, + ); + } + + void _showHistoryDurationBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Duration".needTranslation, + items: viewModel.durationFilters, + selectedValue: viewModel.selectedDurationFilter, + onSelected: viewModel.setFilterDuration, + ); + } + + /// Handle reminder button tap (Set or Cancel) + Future _handleReminderButtonTap(WaterMonitorViewModel viewModel) async { + if (viewModel.isWaterReminderEnabled) { + // Cancel reminders + _showCancelReminderConfirmation(viewModel); + } else { + // Set reminders + await _setReminders(viewModel); + } + } + + /// Show confirmation bottom sheet before cancelling reminders + void _showCancelReminderConfirmation(WaterMonitorViewModel viewModel) { + showCommonBottomSheetWithoutHeight( + title: 'Notice'.needTranslation, + context, + child: Utils.getWarningWidget( + loadingText: "Are you sure you want to cancel all water reminders?".needTranslation, + isShowActionButtons: true, + onCancelTap: () { + Navigator.pop(context); + }, + onConfirmTap: () async { + Navigator.pop(context); + await _cancelReminders(viewModel); + }, + ), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + isDismissible: true, + ); + } + + /// Set water reminders + Future _setReminders(WaterMonitorViewModel viewModel) async { + // Schedule reminders + final success = await viewModel.scheduleWaterReminders(); + + if (success) { + final times = await viewModel.getScheduledReminderTimes(); + _showReminderScheduledDialog(times); + } + } + + /// Cancel water reminders + Future _cancelReminders(WaterMonitorViewModel viewModel) async { + final success = await viewModel.cancelWaterReminders(); + } + + /// Show bottom sheet with scheduled reminder times + void _showReminderScheduledDialog(List times) { + showCommonBottomSheetWithoutHeight( + title: 'Reminders Set!'.needTranslation, + context, + isCloseButtonVisible: false, + isDismissible: false, + child: Padding( + padding: EdgeInsets.only(top: 16.w, left: 16.w, right: 16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Utils.getSuccessWidget(loadingText: 'Daily water reminders scheduled at:'.needTranslation), + SizedBox(height: 16.h), + Wrap( + spacing: 8.w, + runSpacing: 8.h, + children: times + .map( + (time) => AppCustomChipWidget( + icon: AppAssets.bell, + iconColor: AppColors.quickLoginColor, + richText: _formatTime(time).toText14(), + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h), + ), + ) + .toList(), + ), + + SizedBox(height: 24.h), + + // OK button + Row( + children: [ + Expanded( + child: CustomButton( + height: 56.h, + text: 'OK'.needTranslation, + onPressed: () => Navigator.of(context).pop(), + textColor: AppColors.whiteColor, + ), + ), + ], + ), + ], + ), + ), + callBackFunc: () {}, + ); + } + + /// Format DateTime to readable time string + String _formatTime(DateTime time) { + final hour = time.hour; + final minute = time.minute; + final hour12 = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour); + final period = hour >= 12 ? 'PM' : 'AM'; + return '${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period'; + } + + /// Format history date from /Date(milliseconds+0300)/ format + String _formatHistoryDate(String dateString) { + try { + // Parse the /Date(milliseconds+0300)/ format + final regex = RegExp(r'\/Date\((\d+)'); + final match = regex.firstMatch(dateString); + if (match != null) { + final milliseconds = int.tryParse(match.group(1)!); + if (milliseconds != null) { + final dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds); + return _formatTime(dateTime); + } + } + } catch (e) { + return dateString; + } + return dateString; + } + + /// Parse history date from /Date(milliseconds+0300)/ format to DateTime + DateTime _parseHistoryDate(String dateString) { + try { + final regex = RegExp(r'\/Date\((\d+)'); + final match = regex.firstMatch(dateString); + if (match != null) { + final milliseconds = int.tryParse(match.group(1)!); + if (milliseconds != null) { + return DateTime.fromMillisecondsSinceEpoch(milliseconds); + } + } + } catch (e) { + // Return current time as fallback + } + return DateTime.now(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: "Water Consumption".needTranslation, + bottomChild: Consumer( + builder: (context, viewModel, child) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.w), + child: CustomButton( + text: viewModel.isWaterReminderEnabled ? "Cancel Reminders".needTranslation : "Set Reminder".needTranslation, + textColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor : AppColors.successColor, + backgroundColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor.withValues(alpha: 0.1) : AppColors.successLightBgColor, + onPressed: () => _handleReminderButtonTap(viewModel), + icon: viewModel.isWaterReminderEnabled ? null : AppAssets.bell, + iconColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor : AppColors.successColor, + borderRadius: 12.r, + borderColor: AppColors.transparent, + padding: EdgeInsets.symmetric(vertical: 14.h), + ), + ), + ); + }, + ), + child: RefreshIndicator( + onRefresh: _refreshData, + color: AppColors.blueColor, + backgroundColor: AppColors.whiteColor, + child: Column( + children: [ + SizedBox(height: 16.h), + const WaterIntakeSummaryWidget(), + SizedBox(height: 16.h), + _buildHistoryGraphOrList(), + SizedBox(height: 16.h), + const HydrationTipsWidget(), + SizedBox(height: 16.h), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/water_monitor/water_monitor_settings_screen.dart b/lib/presentation/water_monitor/water_monitor_settings_screen.dart new file mode 100644 index 0000000..45a39e6 --- /dev/null +++ b/lib/presentation/water_monitor/water_monitor_settings_screen.dart @@ -0,0 +1,359 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/dependencies.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/water_monitor/water_monitor_view_model.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'; +import 'package:provider/provider.dart'; + +class WaterMonitorSettingsScreen extends StatefulWidget { + const WaterMonitorSettingsScreen({super.key}); + + @override + State createState() => _WaterMonitorSettingsScreenState(); +} + +class _WaterMonitorSettingsScreenState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().initialize(); + }); + } + + void _showSnackbar(String text) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(text), + backgroundColor: AppColors.errorColor, + ), + ); + } + + // Reusable method to build selection row widget + Widget _buildSelectionRow({ + required String value, + required String groupValue, + required VoidCallback onTap, + bool useUpperCase = false, + }) { + return SizedBox( + height: 70.h, + child: Row( + spacing: 8.h, + children: [ + Radio( + value: value, + groupValue: groupValue, + activeColor: AppColors.errorColor, + onChanged: (_) => onTap(), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + (useUpperCase ? value.toUpperCase() : value.toCamelCase) + .toText16(weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1) + .expanded, + ], + ).onPress(onTap), + ); + } + + // Reusable method to show selection bottom sheet + void _showSelectionBottomSheet({ + required BuildContext context, + required String title, + required List items, + required String selectedValue, + required Function(String) onSelected, + bool useUpperCase = false, + }) { + final dialogService = getIt.get(); + + dialogService.showFamilyBottomSheetWithoutHWithChild( + label: title.needTranslation, + message: "", + child: Container( + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20.r)), + child: ListView.separated( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return _buildSelectionRow( + value: item, + groupValue: selectedValue, + useUpperCase: useUpperCase, + onTap: () { + onSelected(item); + Navigator.pop(context); + }, + ); + }, + separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor), + ), + ), + onOkPressed: () {}, + ); + } + + void _showGenderSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Gender".needTranslation, + items: viewModel.genderOptions, + selectedValue: viewModel.selectedGender, + onSelected: viewModel.setGender, + ); + } + + void _showHeightUnitSelectionBottomSheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Unit".needTranslation, + items: viewModel.heightUnits, + selectedValue: viewModel.selectedHeightUnit, + onSelected: viewModel.setHeightUnit, + useUpperCase: true, + ); + } + + void _showWeightUnitSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Unit".needTranslation, + items: viewModel.weightUnits, + selectedValue: viewModel.selectedWeightUnit, + onSelected: viewModel.setWeightUnit, + useUpperCase: true, + ); + } + + void _showActivityLevelSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Activity Level".needTranslation, + items: viewModel.activityLevels, + selectedValue: viewModel.selectedActivityLevel, + onSelected: viewModel.setActivityLevel, + ); + } + + void _showNumberOfRemindersSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: "Select Number of Reminders".needTranslation, + items: viewModel.reminderOptions, + selectedValue: viewModel.selectedNumberOfReminders, + onSelected: viewModel.setNumberOfReminders, + ); + } + + // Reusable method to build text field + Widget _buildTextField(TextEditingController controller, String hintText) { + return TextField( + controller: controller, + keyboardType: TextInputType.number, + maxLines: 1, + cursorHeight: 14.h, + textAlignVertical: TextAlignVertical.center, + decoration: InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + isCollapsed: true, + hintText: hintText, + hintStyle: const TextStyle(color: Colors.grey), + ), + style: TextStyle( + fontSize: 14.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ); + } + + // Reusable method to build settings row + Widget _buildSettingsRow({ + required String icon, + required String label, + String? value, + Widget? inputField, + String? unit, + VoidCallback? onUnitTap, + VoidCallback? onRowTap, + bool showDivider = true, + }) { + return Column( + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + height: 40.w, + width: 40.w, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.greyColor, + borderRadius: 10.r, + hasShadow: false, + ), + child: Center(child: Utils.buildSvgWithAssets(icon: icon, height: 22.w, width: 22.w)), + ), + SizedBox(width: 12.w), + Expanded( + flex: unit != null ? 3 : 1, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + label.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + if (inputField != null) + Container( + height: 20.w, + alignment: Alignment.centerLeft, + child: inputField, + ) + else if (value != null) + value.toCamelCase.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ), + ), + if (unit != null) ...[ + Container( + width: 1.w, + height: 30.w, + color: AppColors.dividerColor, + ).paddingOnly(right: 10.w), + Expanded( + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + unit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ), + SizedBox(width: 12.w), + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down) + ], + ).onPress(onUnitTap ?? () {}), + ), + ] else if (onRowTap != null) ...[ + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down), + SizedBox(width: 4.w), + ], + ], + ).paddingSymmetrical(0.w, 16.w).onPress(onRowTap ?? () {}), + if (showDivider) Divider(height: 1, color: AppColors.dividerColor), + ], + ); + } + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: "H20 Settings".needTranslation, + bottomChild: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.w), + child: CustomButton( + text: "Save".needTranslation, + onPressed: () async { + final success = await viewModel.saveSettings(); + if (!success && viewModel.validationError != null) { + _showSnackBar(context, viewModel.validationError!); + } else if (success) { + _showSnackBar(context, "Settings saved successfully"); + } + }, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(vertical: 14.h), + ), + ), + ), + child: Container( + margin: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h), + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), + child: Column( + children: [ + _buildSettingsRow( + icon: AppAssets.profileIcon, + label: "Your Name".needTranslation, + inputField: _buildTextField(viewModel.nameController, 'Guest'), + ), + _buildSettingsRow( + icon: AppAssets.genderIcon, + label: "Select Gender".needTranslation, + value: viewModel.selectedGender, + onRowTap: () => _showGenderSelectionBottomsheet(context, viewModel), + ), + _buildSettingsRow( + icon: AppAssets.calendarGrey, + label: "Age (11-120) yrs".needTranslation, + inputField: _buildTextField(viewModel.ageController, '20'), + ), + _buildSettingsRow( + icon: AppAssets.heightIcon, + label: "Height".needTranslation, + inputField: _buildTextField(viewModel.heightController, '175'), + unit: viewModel.selectedHeightUnit, + onUnitTap: () => _showHeightUnitSelectionBottomSheet(context, viewModel), + ), + _buildSettingsRow( + icon: AppAssets.weightScaleIcon, + label: "Weight".needTranslation, + inputField: _buildTextField(viewModel.weightController, '75'), + unit: viewModel.selectedWeightUnit, + onUnitTap: () => _showWeightUnitSelectionBottomsheet(context, viewModel), + ), + _buildSettingsRow( + icon: AppAssets.dumbellIcon, + label: "Activity Level".needTranslation, + value: viewModel.selectedActivityLevel, + onRowTap: () => _showActivityLevelSelectionBottomsheet(context, viewModel), + ), + _buildSettingsRow( + icon: AppAssets.notificationIconGrey, + label: "Number of reminders in a day".needTranslation, + value: viewModel.selectedNumberOfReminders, + onRowTap: () => _showNumberOfRemindersSelectionBottomsheet(context, viewModel), + showDivider: false, + ), + ], + ), + ), + ), + ); + } + + // Show snackbar for validation errors and success messages + void _showSnackBar(BuildContext context, String message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(message), + duration: const Duration(seconds: 3), + behavior: SnackBarBehavior.floating, + backgroundColor: message.contains('successfully') + ? Colors.green + : AppColors.errorColor, + ), + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/bottle_shape_clipper.dart b/lib/presentation/water_monitor/widgets/bottle_shape_clipper.dart new file mode 100644 index 0000000..b4b7ba0 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/bottle_shape_clipper.dart @@ -0,0 +1,25 @@ +// Add this class at the bottom of your file (outside the main class) +import 'package:flutter/material.dart'; + +class BottleShapeClipper extends CustomClipper { + @override + Path getClip(Size size) { + final path = Path(); + + // Create rounded rectangle matching the bottle body shape + // The bottle has rounded corners with radius ~30-40 based on SVG + final borderRadius = size.width * 0.25; // 25% of width for rounded corners + + path.addRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(0, 0, size.width, size.height), + Radius.circular(borderRadius), + ), + ); + + return path; + } + + @override + bool shouldReclip(covariant CustomClipper oldClipper) => false; +} diff --git a/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart b/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart new file mode 100644 index 0000000..013ac7b --- /dev/null +++ b/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart @@ -0,0 +1,324 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.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/water_monitor/models/water_cup_model.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:provider/provider.dart'; +import 'package:uuid/uuid.dart'; + +/// Bottom sheet to switch between existing cups or add new custom cup +void showSwitchCupBottomSheet(BuildContext context) { + return showCommonBottomSheetWithoutHeight( + context, + titleWidget: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "Switch Cups".toText20(weight: FontWeight.w600), + "Select your preferred cup size".toText16(weight: FontWeight.w500, color: AppColors.greyTextColor), + ], + ), + child: SwitchCupBottomSheet(), + callBackFunc: () {}, + ); +} + +class SwitchCupBottomSheet extends StatelessWidget { + const SwitchCupBottomSheet({super.key}); + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + final selectedId = viewModel.selectedCup?.id; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + crossAxisSpacing: 16.w, + childAspectRatio: 0.85, + ), + itemCount: viewModel.cups.length + 1, + itemBuilder: (context, index) { + if (index == viewModel.cups.length) { + return _buildAddCupItem(context); + } + + final cup = viewModel.cups[index]; + final isSelected = selectedId == cup.id; + + return _buildCupItem( + cup: cup, + isSelected: isSelected, + onTap: () { + viewModel.selectCup(cup.id); + context.pop(); + }, + ); + }, + ), + ], + ); + } + + Widget _buildCupItem({required WaterCupModel cup, required bool isSelected, required VoidCallback onTap}) { + return GestureDetector( + onTap: onTap, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Stack( + clipBehavior: Clip.none, + children: [ + Container( + width: 60.w, + height: 60.w, + decoration: BoxDecoration( + color: isSelected ? AppColors.primaryRedColor.withOpacity(0.08) : Colors.transparent, + borderRadius: BorderRadius.circular(12.r), + border: Border.all( + color: isSelected ? AppColors.primaryRedColor : AppColors.bgScaffoldColor, + width: 1, + ), + ), + child: Center( + child: Utils.buildSvgWithAssets( + icon: cup.iconPath, + height: 30.h, + width: 42.w, + iconColor: isSelected ? AppColors.primaryRedColor : null, + ), + ), + ), + // Red badge for custom cups (delete) + if (!cup.isDefault) + Positioned( + top: -6.h, + right: -6.w, + child: Builder(builder: (ctx) { + return InkWell( + onTap: () { + // call viewmodel remove + final vm = ctx.read(); + vm.removeCup(cup.id); + }, + child: Container( + color: AppColors.whiteColor, + child: Utils.buildSvgWithAssets(icon: AppAssets.minimizeIcon, height: 20.w, width: 20.w), + ), + ); + }), + ), + ], + ), + SizedBox(height: 2.h), + '${cup.capacityMl}ml'.toText10(weight: FontWeight.w500), + ], + ), + ); + } + + Widget _buildAddCupItem(BuildContext context) { + return GestureDetector( + onTap: () { + showCustomizeCupBottomSheet(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 60.w, + height: 60.w, + child: Center(child: Utils.buildSvgWithAssets(icon: AppAssets.cupAdd, height: 30.h, width: 42.w)), + ), + SizedBox(height: 4.h), + 'Add'.needTranslation.toText10(weight: FontWeight.w500), + ], + ), + ); + } +} + +/// Bottom sheet to customize cup capacity with slider +void showCustomizeCupBottomSheet(BuildContext context, {WaterCupModel? cupToEdit}) { + return showCommonBottomSheetWithoutHeight( + context, + titleWidget: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "Customize your drink cup".needTranslation.toText20(weight: FontWeight.w600), + ], + ), + child: CustomizeCupBottomSheet(cupToEdit: cupToEdit), + callBackFunc: () {}, + ); +} + +class CustomizeCupBottomSheet extends StatefulWidget { + final WaterCupModel? cupToEdit; + + const CustomizeCupBottomSheet({super.key, this.cupToEdit}); + + @override + State createState() => _CustomizeCupBottomSheetState(); +} + +class _CustomizeCupBottomSheetState extends State { + static const int minCapacity = 50; + static const int maxCapacity = 500; + + late double _currentCapacity; + + @override + void initState() { + super.initState(); + _currentCapacity = (widget.cupToEdit?.capacityMl ?? 150).toDouble(); + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Cup icon with fill level visualization + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: 60.w, + height: 80.h, + child: Stack( + alignment: Alignment.bottomCenter, + children: [ + // Cup image with dynamic fill + SizedBox( + width: 60.w, + height: 80.h, + child: Center( + child: Utils.buildSvgWithAssets( + icon: AppAssets.cupEmpty, + width: 60.w, + height: 80.h, + fit: BoxFit.contain, + ), + ), + ), + ClipRect( + child: Align( + alignment: Alignment.bottomCenter, + heightFactor: (_currentCapacity / maxCapacity).clamp(0.0, 1.0), + child: Utils.buildSvgWithAssets( + icon: AppAssets.cupFilled, + width: 60.w, + height: 80.h, + fit: BoxFit.contain, + )), + ), + ], + ), + ), + + SizedBox(width: 12.w), + + // Slider and labels + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Current value + Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + '${_currentCapacity.round()}'.toText32(isBold: true), + SizedBox(width: 4.w), + Padding( + padding: EdgeInsets.only(bottom: 4.h), + child: Text( + 'ml', + style: TextStyle( + fontSize: 16.f, + fontWeight: FontWeight.w500, + color: AppColors.greyTextColor, + height: 1.0, + ), + ), + ), + ], + ).paddingOnly(left: 12.w), + + SizedBox(height: 16.h), + + // Slider + SliderTheme( + data: SliderTheme.of(context).copyWith( + activeTrackColor: AppColors.primaryRedColor, + inactiveTrackColor: AppColors.primaryRedColor.withOpacity(0.2), + thumbColor: AppColors.primaryRedColor, + overlayColor: AppColors.primaryRedColor.withOpacity(0.2), + trackHeight: 4.h, + thumbShape: RoundSliderThumbShape(enabledThumbRadius: 10.w), + ), + child: Slider( + value: _currentCapacity, + min: minCapacity.toDouble(), + max: maxCapacity.toDouble(), + divisions: (maxCapacity - minCapacity) ~/ 10, + onChanged: (value) => setState(() => _currentCapacity = value), + ), + ), + + Align( + alignment: Alignment.centerRight, + child: 'Max: $maxCapacity ml'.toText14( + color: AppColors.greyTextColor, + ), + ), + ], + ), + ), + ], + ), + + SizedBox(height: 24.h), + CustomButton( + text: 'Select'.needTranslation, + onPressed: () { + final newCup = WaterCupModel( + id: widget.cupToEdit?.id ?? Uuid().v4(), + name: '${_currentCapacity.round()}ml', + capacityMl: _currentCapacity.round(), + iconPath: AppAssets.cupEmpty, + isDefault: false, + ); + + final viewModel = context.read(); + if (widget.cupToEdit != null) { + viewModel.updateCup(newCup); + } else { + viewModel.addCup(newCup); + } + viewModel.selectCup(newCup.id); + + Navigator.pop(context); + }, + backgroundColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 16.f, + ), + ], + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart b/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart new file mode 100644 index 0000000..df55886 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.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/theme/colors.dart'; + +class HydrationTipsWidget extends StatelessWidget { + const HydrationTipsWidget({super.key}); + + @override + Widget build(BuildContext context) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.bulb_icon, + width: 24.w, + height: 24.h, + ), + SizedBox(width: 8.w), + "Tips to stay hydrated".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(height: 8.h), + " • ${"Drink before you feel thirsty"}".needTranslation.toText12( + fontWeight: FontWeight.w500, + color: AppColors.textColorLight, + ), + SizedBox(height: 4.h), + " • ${"Keep a refillable bottle next to you"}".needTranslation.toText12( + fontWeight: FontWeight.w500, + color: AppColors.textColorLight, + ), + SizedBox(height: 4.h), + " • ${"Track your daily intake to stay motivated"}".needTranslation.toText12( + fontWeight: FontWeight.w500, + color: AppColors.textColorLight, + ), + SizedBox(height: 4.h), + " • ${"Choose sparkling water instead of soda"}".needTranslation.toText12( + fontWeight: FontWeight.w500, + color: AppColors.textColorLight, + ), + SizedBox(height: 8.h), + ], + ), + ); + } +} + diff --git a/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart b/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart new file mode 100644 index 0000000..31f8fdb --- /dev/null +++ b/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.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/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:provider/provider.dart'; + +class WaterActionButtonsWidget extends StatelessWidget { + const WaterActionButtonsWidget({super.key}); + + @override + Widget build(BuildContext context) { + return Consumer(builder: (context, vm, _) { + final cupAmount = vm.selectedCupCapacityMl; + return Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + InkWell( + onTap: () async { + if (cupAmount > 0) { + await vm.undoUserActivity(); + } + }, + child: Utils.buildSvgWithAssets( + icon: AppAssets.minimizeIcon, + height: 20.h, + width: 20.h, + iconColor: AppColors.textColor, + ), + ), + Container( + margin: EdgeInsets.symmetric(horizontal: 4.w), + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.blueColor, + borderRadius: 99.r, + hasShadow: true, + ), + child: (cupAmount > 0 ? "+ $cupAmount ml" : "+ 0ml").toText12( + fontWeight: FontWeight.w600, + color: AppColors.whiteColor, + ), + ), + InkWell( + onTap: () async { + if (cupAmount > 0) { + await vm.insertUserActivity(quantityIntake: cupAmount); + } + }, + child: Utils.buildSvgWithAssets( + icon: AppAssets.addIconDark, + height: 20.h, + width: 20.h, + ), + ), + ], + ), + SizedBox(height: 8.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _buildActionButton( + context: context, + onTap: () => showSwitchCupBottomSheet(context), + overlayWidget: AppAssets.refreshIcon, + title: "Switch Cup".needTranslation, + icon: Utils.buildSvgWithAssets(icon: AppAssets.glassIcon, height: 24.w, width: 24.w), + ), + _buildActionButton( + context: context, + onTap: () async { + final success = await vm.scheduleTestNotification(); + if (success) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Test notification will appear in 5 seconds!'.needTranslation), + backgroundColor: AppColors.blueColor, + behavior: SnackBarBehavior.floating, + margin: EdgeInsets.all(16.w), + duration: const Duration(seconds: 2), + ), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to schedule test notification'.needTranslation), + backgroundColor: AppColors.errorColor, + behavior: SnackBarBehavior.floating, + margin: EdgeInsets.all(16.w), + ), + ); + } + }, + title: "Plain Water".needTranslation, + icon: Utils.buildSvgWithAssets(icon: AppAssets.glassIcon, height: 24.w, width: 24.w), + ), + _buildActionButton( + context: context, + onTap: () => context.navigateWithName(AppRoutes.waterMonitorSettingsScreen), + title: "Settings".needTranslation, + icon: Icon( + Icons.settings, + color: AppColors.blueColor, + size: 24.w, + ), + ), + ], + ), + ], + ); + }); + } + + Widget _buildActionButton({ + required BuildContext context, + String? overlayWidget, + required String title, + required Widget icon, + required VoidCallback onTap, + }) { + return InkWell( + onTap: onTap, + child: Column( + children: [ + Stack( + children: [ + Container( + height: 46.w, + width: 46.w, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.blueColor.withValues(alpha: 0.14), + borderRadius: 12.r, + hasShadow: true, + ), + child: Center(child: icon), + ), + if (overlayWidget != null) ...[ + Positioned( + top: 0, + right: 0, + child: Container( + padding: EdgeInsets.all(2.w), + height: 16.w, + width: 16.w, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.blueColor, + borderRadius: 100.r, + hasShadow: true, + ), + child: Center( + child: Utils.buildSvgWithAssets( + icon: AppAssets.refreshIcon, + iconColor: AppColors.whiteColor, + ), + ), + ), + ), + ] + ], + ), + SizedBox(height: 4.h), + title.toText10(), + ], + ), + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/water_bottle_widget.dart b/lib/presentation/water_monitor/widgets/water_bottle_widget.dart new file mode 100644 index 0000000..b681e32 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/water_bottle_widget.dart @@ -0,0 +1,112 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/bottle_shape_clipper.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_consumption_progress_widget.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:provider/provider.dart'; + +class WaterBottleWidget extends StatelessWidget { + const WaterBottleWidget({super.key}); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, vm, _) { + final progressPercent = (vm.progress * 100).clamp(0.0, 100.0); + + // SVG aspect ratio + const svgAspectRatio = 315.0 / 143.0; // ~2.2 + + // Responsive bottle sizing with device-specific constraints + double bottleWidth; + if (isTablet) { + bottleWidth = math.min(SizeUtils.width * 0.15, 180.0); + } else if (isFoldable) { + bottleWidth = math.min(100.w, 160.0); + } else { + bottleWidth = math.min(120.w, 140.0); + } + + final bottleHeight = bottleWidth * svgAspectRatio; + + // Fillable area percentages + final fillableHeightPercent = 0.7; + const fillableWidthPercent = 0.8; + + final fillableHeight = bottleHeight * fillableHeightPercent; + final fillableWidth = bottleWidth * fillableWidthPercent; + + // Device-specific positioning offsets + final double leftOffset = isTablet ? 4.w : 8.w; + final double bottomOffset = isTablet ? -65.h : -78.h; + + return SizedBox( + height: bottleHeight, + width: bottleWidth, + child: Stack( + fit: StackFit.expand, + alignment: Alignment.center, + children: [ + // Bottle SVG outline + Center( + child: Utils.buildSvgWithAssets( + icon: AppAssets.waterBottle, + height: bottleHeight, + width: bottleWidth, + fit: BoxFit.contain, + ), + ), + + // Wave and bubbles clipped to bottle shape + Positioned.fill( + left: leftOffset, + bottom: bottomOffset, + child: Center( + child: SizedBox( + width: fillableWidth, + height: fillableHeight, + child: ClipPath( + clipper: BottleShapeClipper(), + child: Stack( + alignment: Alignment.bottomCenter, + children: [ + // Animated wave + Positioned( + child: WaterConsumptionProgressWidget( + progress: progressPercent, + size: math.min(fillableWidth, fillableHeight), + containerWidth: fillableWidth, + containerHeight: fillableHeight, + waveDuration: const Duration(milliseconds: 3000), + waveColor: AppColors.blueColor, + ), + ), + + // Bubbles (only show if progress > 10%) + if (progressPercent > 10) + Positioned( + bottom: fillableHeight * 0.12, + child: Utils.buildSvgWithAssets( + icon: AppAssets.waterBottleOuterBubbles, + height: isTablet ? math.min(45.0, fillableHeight * 0.2) : math.min(55.0, fillableHeight * 0.22), + width: fillableWidth * 0.65, + ), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/water_consumption_progress_widget.dart b/lib/presentation/water_monitor/widgets/water_consumption_progress_widget.dart new file mode 100644 index 0000000..08350a1 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/water_consumption_progress_widget.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_splash_progress_widget.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; + +class WaterConsumptionProgressWidget extends StatefulWidget { + /// progress: 0.0 - 100.0 + final double progress; + final double size; + final Color? waveColor; + final double? containerWidth; + final double? containerHeight; + final Duration? waveDuration; + + const WaterConsumptionProgressWidget({super.key, required this.progress, this.size = 100, this.waveColor, this.containerWidth, this.containerHeight, this.waveDuration}); + + @override + State createState() => _WaterConsumptionProgressWidgetState(); +} + +class _WaterConsumptionProgressWidgetState extends State with SingleTickerProviderStateMixin { + late AnimationController _progressController; + late Animation _progressAnimation; + double _lastTarget = 0.0; + + @override + void initState() { + super.initState(); + _lastTarget = widget.progress; + _progressController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1200)); + _progressAnimation = Tween(begin: 0, end: widget.progress).animate(CurvedAnimation(parent: _progressController, curve: Curves.easeInOut)); + _progressController.forward(); + } + + @override + void didUpdateWidget(covariant WaterConsumptionProgressWidget oldWidget) { + super.didUpdateWidget(oldWidget); + if ((widget.progress - _lastTarget).abs() > 0.01) { + // animate from current value to new target + final begin = _progressAnimation.value; + _progressAnimation = + Tween(begin: begin, end: widget.progress).animate(CurvedAnimation(parent: _progressController, curve: Curves.easeInOut)); + _progressController + ..reset() + ..forward(); + _lastTarget = widget.progress; + } + } + + @override + void dispose() { + _progressController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + // default to app blue color if none provided + final blue = widget.waveColor ?? AppColors.blueColor; + return AnimatedBuilder( + animation: _progressAnimation, + builder: (context, child) { + return WaterWaveProgress( + progress: _progressAnimation.value, + size: widget.size, + showPercentage: false, + useCircleClip: false, + waveColor: blue, + containerWidth: widget.containerWidth, + containerHeight: widget.containerHeight, + waveDuration: widget.waveDuration, + backgroundColor: Colors.transparent, + progressColor: Colors.transparent, + textColor: Colors.transparent, + ); + }, + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart b/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart new file mode 100644 index 0000000..094cc38 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_action_buttons_widget.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_bottle_widget.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:provider/provider.dart'; +import 'package:shimmer/shimmer.dart'; + +class WaterIntakeSummaryWidget extends StatelessWidget { + const WaterIntakeSummaryWidget({super.key}); + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: EdgeInsets.all(24.w), + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + AppColors.blueGradientColorOne, + AppColors.blueGradientColorTwo, + ], + ), + ), + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + flex: isTablet ? 2 : 3, + child: Consumer(builder: (context, vm, _) { + if (vm.isLoading) { + return _buildLoadingShimmer(); + } + + final goalMl = vm.dailyGoalMl; + final consumed = vm.totalConsumedMl; + final remaining = (goalMl - consumed) > 0 ? (goalMl - consumed) : 0; + final completedPercent = "${(vm.progress * 100).clamp(0.0, 100.0).toStringAsFixed(0)}%"; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "Next Drink Time".needTranslation.toText18(weight: FontWeight.w600, color: AppColors.textColor), + vm.nextDrinkTime.toText32(weight: FontWeight.w600, color: AppColors.blueColor), + SizedBox(height: 12.h), + _buildStatusColumn(title: "Your Goal".needTranslation, subTitle: "${goalMl}ml"), + SizedBox(height: 8.h), + _buildStatusColumn(title: "Remaining".needTranslation, subTitle: "${remaining}ml"), + SizedBox(height: 8.h), + _buildStatusColumn(title: "Completed".needTranslation, subTitle: completedPercent, subTitleColor: AppColors.successColor), + SizedBox(height: 8.h), + _buildStatusColumn( + title: "Hydration Status".needTranslation, + subTitle: vm.hydrationStatus, + subTitleColor: vm.hydrationStatusColor, + ), + ], + ); + }), + ), + SizedBox(width: isTablet ? 32 : 16.w), + Expanded( + flex: isTablet ? 1 : 2, + child: const WaterBottleWidget(), + ), + ], + ), + const WaterActionButtonsWidget(), + ], + ), + ); + } + + Widget _buildStatusColumn({required String title, required String subTitle, Color? subTitleColor}) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "$title: ".toText16(weight: FontWeight.w500, color: AppColors.textColor), + subTitle.toText12( + fontWeight: FontWeight.w600, + color: subTitleColor ?? AppColors.greyTextColor, + ), + ], + ); + } + + Widget _buildLoadingShimmer() { + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.all(0.w), + itemCount: 4, + separatorBuilder: (_, __) => SizedBox(height: 12.h), + itemBuilder: (context, index) { + return Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Container( + height: 40.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(10.r), + ), + ), + ); + }, + ); + } +} diff --git a/lib/presentation/water_monitor/widgets/water_splash_progress_widget.dart b/lib/presentation/water_monitor/widgets/water_splash_progress_widget.dart new file mode 100644 index 0000000..da5eb06 --- /dev/null +++ b/lib/presentation/water_monitor/widgets/water_splash_progress_widget.dart @@ -0,0 +1,351 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; + +/// Spherical water wave progress bar with animated ripple effect +/// Based on https://github.com/meeziest/spherical_water_wavy_progress_bar +/// +/// Usage: +/// WaterWaveProgress( +/// progress: 75.0, +/// size: 200.w, +/// showPercentage: true, +/// ) +class WaterWaveProgress extends StatefulWidget { + final double progress; // 0.0 to 100.0 + final double size; + final bool showPercentage; + final bool useCircleClip; + final Color? waveColor; + final Color? backgroundColor; + final Color? progressColor; + final Color? textColor; + final Duration? waveDuration; + + // When drawing inside a non-square clip (like bottle area), provide the actual available + // width and height so the painter can compute vertical fill correctly. + final double? containerWidth; + final double? containerHeight; + + const WaterWaveProgress({ + super.key, + required this.progress, + this.size = 200, + this.showPercentage = true, + this.useCircleClip = true, + this.waveColor, + this.backgroundColor, + this.progressColor, + this.textColor, + this.waveDuration, + this.containerWidth, + this.containerHeight, + }); + + @override + State createState() => _WaterWaveProgressState(); +} + +class _WaterWaveProgressState extends State with SingleTickerProviderStateMixin { + late AnimationController _waveController; + + @override + void initState() { + super.initState(); + _waveController = AnimationController( + vsync: this, + duration: widget.waveDuration ?? const Duration(milliseconds: 2000), + )..repeat(); + } + + @override + void dispose() { + _waveController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final radius = widget.size / 2; + + // When container dimensions are provided (non-square bottle area), use them so + // the CustomPaint canvas matches the available clip rect. Otherwise fall back + // to the square size value. + final paintWidth = widget.containerWidth ?? widget.size; + final paintHeight = widget.containerHeight ?? widget.size; + + return SizedBox( + width: paintWidth, + height: paintHeight, + child: CustomPaint( + painter: _WavePainter( + progress: widget.progress, + waveAnimation: _waveController, + // For circle-based painters we still provide circleRadius; when using + // rectangular painting the circleRadius is unused. + circleRadius: radius, + waveColor: widget.waveColor ?? AppColors.primaryRedColor, + backgroundColor: widget.backgroundColor ?? AppColors.bgScaffoldColor, + useCircleClip: widget.useCircleClip, + containerWidth: widget.containerWidth, + containerHeight: widget.containerHeight, + ), + // Only draw the circular progress/percentage when explicitly requested. + foregroundPainter: widget.showPercentage + ? _ProgressPainter( + progress: widget.progress, + circleRadius: radius, + progressColor: widget.progressColor ?? AppColors.primaryRedColor, + textColor: widget.textColor ?? AppColors.textColor, + showPercentage: widget.showPercentage, + ) + : null, + ), + ); + } +} + +/// Paints the animated water waves inside a circular clip +class _WavePainter extends CustomPainter { + final double progress; + final Animation waveAnimation; + final double circleRadius; + final Color waveColor; + final Color backgroundColor; + final bool useCircleClip; + final double? containerWidth; + final double? containerHeight; + + _WavePainter({ + required this.progress, + required this.waveAnimation, + required this.circleRadius, + required this.waveColor, + required this.backgroundColor, + this.useCircleClip = true, + this.containerWidth, + this.containerHeight, + }) : super(repaint: waveAnimation); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + canvas.translate(center.dx, center.dy); + + if (useCircleClip) { + // Clip to circle + canvas.clipPath( + Path() + ..addOval( + Rect.fromCircle( + center: Offset.zero, + radius: circleRadius, + ), + ), + ); + + // Fill background circle if specified + if (backgroundColor != Colors.transparent) { + canvas.drawCircle( + Offset.zero, + circleRadius, + Paint()..color = backgroundColor, + ); + } + + // Draw two sine waves clipped to circle for spherical style + _drawSineWave(canvas, waveColor.withAlpha((0.5 * 255).round()), shift: 0); + _drawSineWave(canvas, waveColor, shift: circleRadius / 2, mirror: true); + } else { + // No circular clipping: draw waves over the full rectangular area. Use provided container + // dimensions if available; otherwise fall back to square bounds derived from circleRadius. + final w = containerWidth ?? (circleRadius * 2); + final h = containerHeight ?? (circleRadius * 2); + + // use local transforms to center at origin and compute waves relative to the provided rect + canvas.save(); + canvas.translate(-w / 2, -h / 2); // move origin to top-left of the rect + + _drawSineWaveRect(canvas, waveColor.withAlpha((0.5 * 255).round()), width: w, height: h, shift: 0); + _drawSineWaveRect(canvas, waveColor, width: w, height: h, shift: w / 4, mirror: true); + + canvas.restore(); + } + } + + void _drawSineWaveRect(Canvas canvas, Color color, {required double width, required double height, double shift = 0.0, bool mirror = false}) { + if (mirror) { + canvas.save(); + canvas.translate(width, 0); + canvas.scale(-1, 1); + } + + final amplitude = height * 0.04; // smaller amplitude for rectangular waves + final angularVelocity = pi / (width / 2); + final delta = Curves.easeInOut.transform(progress / 100); + + final offsetX = 2 * width * waveAnimation.value + shift; + final offsetY = height * (1.0 - delta); + + final path = Path(); + for (double x = 0; x <= width; x += 1) { + final y = amplitude * sin(angularVelocity * (x + offsetX)); + if (x == 0) { + path.moveTo(x, y + offsetY); + } else { + path.lineTo(x, y + offsetY); + } + } + + path.lineTo(width, height); + path.lineTo(0, height); + path.close(); + + final wavePaint = Paint() + ..color = color + ..style = PaintingStyle.fill + ..isAntiAlias = true; + + canvas.drawPath(path, wavePaint); + + if (mirror) canvas.restore(); + } + + void _drawSineWave(Canvas canvas, Color color, {double shift = 0.0, bool mirror = false}) { + if (mirror) { + canvas.save(); + canvas.transform(Matrix4.rotationY(pi).storage); + } + + // original circular/spherical style: compute bounds based on circleRadius + final startX = -circleRadius; + final endX = circleRadius; + final startY = circleRadius; + final endY = -circleRadius; + + final amplitude = circleRadius * 0.15; + final angularVelocity = pi / circleRadius; + final delta = Curves.easeInOut.transform(progress / 100); + + final offsetX = 2 * circleRadius * waveAnimation.value + shift; + final offsetY = startY + (endY - startY - amplitude) * delta; + + final wavePaint = Paint() + ..color = color + ..style = PaintingStyle.fill + ..isAntiAlias = true; + + final path = Path(); + + for (double x = startX; x <= endX; x++) { + // Sine wave function: y = A * sin(ωx + φ) + final y = amplitude * sin(angularVelocity * (x + offsetX)); + if (x == startX) { + path.moveTo(x, y + offsetY); + } else { + path.lineTo(x, y + offsetY); + } + } + + path.lineTo(endX, startY); + path.lineTo(startX, startY); + path.close(); + + canvas.drawPath(path, wavePaint); + + if (mirror) canvas.restore(); + } + + @override + bool shouldRepaint(covariant _WavePainter oldDelegate) => oldDelegate.progress != progress; +} + +/// Paints the circular progress arc and percentage text +class _ProgressPainter extends CustomPainter { + final double progress; + final double circleRadius; + final Color progressColor; + final Color textColor; + final bool showPercentage; + + _ProgressPainter({ + required this.progress, + required this.circleRadius, + required this.progressColor, + required this.textColor, + required this.showPercentage, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + canvas.translate(center.dx, center.dy); + + _drawCircleProgress(canvas); + if (showPercentage) { + _drawProgressText(canvas); + } + } + + void _drawCircleProgress(Canvas canvas) { + final strokeWidth = circleRadius * 0.077; + + // Background circle with shadow + final bgPaint = Paint() + ..color = progressColor.withAlpha((0.2 * 255).round()) + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..isAntiAlias = true; + + final shadowPaint = Paint() + ..color = Colors.black.withAlpha((0.1 * 255).round()) + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..maskFilter = const MaskFilter.blur(BlurStyle.outer, 10); + + canvas.drawCircle(Offset.zero, circleRadius, bgPaint); + canvas.drawCircle(Offset.zero, circleRadius, shadowPaint); + + // Progress arc + final progressPaint = Paint() + ..color = progressColor + ..strokeWidth = strokeWidth + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke + ..isAntiAlias = true; + + canvas.drawArc( + Rect.fromCircle(center: Offset.zero, radius: circleRadius), + -0.5 * pi, + 2 * pi * (progress / 100), + false, + progressPaint, + ); + } + + void _drawProgressText(Canvas canvas) { + final textSpan = TextSpan( + text: "${progress.toInt()}%", + style: TextStyle( + color: textColor, + fontSize: circleRadius * 0.35, + fontWeight: FontWeight.w700, + height: 1.0, + ), + ); + + final textPainter = TextPainter( + text: textSpan, + textDirection: TextDirection.ltr, + )..layout(); + + textPainter.paint( + canvas, + Offset(-textPainter.width / 2, -textPainter.height / 2), + ); + } + + @override + bool shouldRepaint(covariant _ProgressPainter oldDelegate) => oldDelegate.progress != progress; +} diff --git a/lib/routes/app_routes.dart b/lib/routes/app_routes.dart index 2718741..f0acd5b 100644 --- a/lib/routes/app_routes.dart +++ b/lib/routes/app_routes.dart @@ -22,6 +22,8 @@ import 'package:hmg_patient_app_new/presentation/symptoms_checker/triage_screen. import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart'; import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/water_consumption_screen.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/water_monitor_settings_screen.dart'; import 'package:hmg_patient_app_new/splashPage.dart'; import '../presentation/covid19test/covid19_landing_page.dart'; @@ -46,6 +48,10 @@ class AppRoutes { //appointments static const String bookAppointmentPage = '/bookAppointmentPage'; + // Water Monitor + static const String waterConsumptionScreen = '/waterConsumptionScreen'; + static const String waterMonitorSettingsScreen = '/waterMonitorSettingsScreen'; + // Symptoms Checker static const String organSelectorPage = '/organSelectorPage'; static const String symptomsSelectorScreen = '/symptomsCheckerScreen'; @@ -83,6 +89,8 @@ class AppRoutes { huaweiHealthExample: (context) => HuaweiHealthExample(), covid19Test: (context) => Covid19LandingPage(), // + waterConsumptionScreen: (context) => WaterConsumptionScreen(), + waterMonitorSettingsScreen: (context) => WaterMonitorSettingsScreen(), healthCalculatorsPage: (context) => HealthCalculatorsPage(type: HealthCalConEnum.calculator), healthConvertersPage: (context) => HealthCalculatorsPage(type: HealthCalConEnum.converter) }; diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart new file mode 100644 index 0000000..fd154c6 --- /dev/null +++ b/lib/services/notification_service.dart @@ -0,0 +1,373 @@ +import 'dart:typed_data'; + +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:hmg_patient_app_new/services/logger_service.dart'; +import 'package:timezone/data/latest_all.dart' as tz; +import 'package:timezone/timezone.dart' as tz show TZDateTime, local, setLocalLocation, getLocation; + +/// Abstract class defining the notification service interface +abstract class NotificationService { + /// Initialize the notification service + Future initialize({Function(String payload)? onNotificationClick}); + + /// Request notification permissions (mainly for iOS) + Future requestPermissions(); + + /// Show an immediate notification + Future showNotification({ + required String title, + required String body, + String? payload, + }); + + /// Schedule a notification at a specific date and time + Future scheduleNotification({ + required int id, + required String title, + required String body, + required DateTime scheduledDate, + String? payload, + }); + + /// Schedule daily notifications at specific times + Future scheduleDailyNotifications({ + required List times, + required String title, + required String body, + String? payload, + }); + + /// Schedule water reminder notifications + Future scheduleWaterReminders({ + required List reminderTimes, + required String title, + required String body, + }); + + /// Cancel a specific notification by id + Future cancelNotification(int id); + + /// Cancel all scheduled notifications + Future cancelAllNotifications(); + + /// Get list of pending notifications + Future> getPendingNotifications(); +} + +/// Implementation of NotificationService following the project architecture +class NotificationServiceImp implements NotificationService { + final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; + final LoggerService loggerService; + + NotificationServiceImp({required this.flutterLocalNotificationsPlugin, required this.loggerService}); + + // Channel IDs for different notification types + static const String _waterReminderChannelId = 'water_reminder_channel'; + static const String _waterReminderChannelName = 'Water Reminders'; + static const String _waterReminderChannelDescription = 'Daily water intake reminders'; + + static const String _generalChannelId = 'hmg_general_channel'; + static const String _generalChannelName = 'HMG Notifications'; + static const String _generalChannelDescription = 'General notifications from HMG'; + + Function(String payload)? _onNotificationClick; + + @override + Future initialize({Function(String payload)? onNotificationClick}) async { + try { + // Initialize timezone database + tz.initializeTimeZones(); + + // Set local timezone (you can also use a specific timezone if needed) + // For example: tz.setLocalLocation(tz.getLocation('Asia/Riyadh')); + final locationName = DateTime.now().timeZoneName; + try { + tz.setLocalLocation(tz.getLocation(locationName)); + } catch (e) { + // Fallback to UTC if specific timezone not found + loggerService.logInfo('Could not set timezone $locationName, using UTC'); + tz.setLocalLocation(tz.getLocation('UTC')); + } + + _onNotificationClick = onNotificationClick; + + const androidSettings = AndroidInitializationSettings('app_icon'); + const iosSettings = DarwinInitializationSettings( + requestAlertPermission: true, + requestBadgePermission: true, + requestSoundPermission: true, + ); + + const initializationSettings = InitializationSettings( + android: androidSettings, + iOS: iosSettings, + ); + + await flutterLocalNotificationsPlugin.initialize( + initializationSettings, + onDidReceiveNotificationResponse: _handleNotificationResponse, + ); + + loggerService.logInfo('NotificationService initialized successfully'); + } catch (ex) { + loggerService.logError('Failed to initialize NotificationService: $ex'); + } + } + + /// Handle notification tap + void _handleNotificationResponse(NotificationResponse response) { + try { + if (response.payload != null && _onNotificationClick != null) { + _onNotificationClick!(response.payload!); + } + loggerService.logInfo('Notification tapped: ${response.payload}'); + } catch (ex) { + loggerService.logError('Error handling notification response: $ex'); + } + } + + @override + Future requestPermissions() async { + try { + // Request permissions for iOS + final result = + await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation()?.requestPermissions( + alert: true, + badge: true, + sound: true, + ); + + // For Android 13+, permissions are requested at runtime + final androidResult = await flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation() + ?.requestNotificationsPermission(); + + loggerService.logInfo('Notification permissions: iOS=${result ?? true}, Android=${androidResult ?? true}'); + return result ?? androidResult ?? true; + } catch (ex) { + loggerService.logError('Error requesting notification permissions: $ex'); + return false; + } + } + + @override + Future showNotification({ + required String title, + required String body, + String? payload, + }) async { + try { + final androidDetails = AndroidNotificationDetails( + _generalChannelId, + _generalChannelName, + channelDescription: _generalChannelDescription, + importance: Importance.high, + priority: Priority.high, + vibrationPattern: _getVibrationPattern(), + ); + + const iosDetails = DarwinNotificationDetails(); + + final notificationDetails = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await flutterLocalNotificationsPlugin.show( + DateTime.now().millisecondsSinceEpoch ~/ 1000, + title, + body, + notificationDetails, + payload: payload, + ); + + loggerService.logInfo('Notification shown: $title'); + } catch (ex) { + loggerService.logError('Error showing notification: $ex'); + } + } + + @override + Future scheduleNotification({ + required int id, + required String title, + required String body, + required DateTime scheduledDate, + String? payload, + }) async { + try { + final androidDetails = AndroidNotificationDetails( + _generalChannelId, + _generalChannelName, + channelDescription: _generalChannelDescription, + importance: Importance.high, + priority: Priority.high, + vibrationPattern: _getVibrationPattern(), + ); + + const iosDetails = DarwinNotificationDetails(); + + final notificationDetails = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await flutterLocalNotificationsPlugin.zonedSchedule( + id, + title, + body, + tz.TZDateTime.from(scheduledDate, tz.local), + notificationDetails, + androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle, + payload: payload, + ); + + loggerService.logInfo('Notification scheduled for: $scheduledDate'); + } catch (ex) { + loggerService.logError('Error scheduling notification: $ex'); + } + } + + @override + Future scheduleDailyNotifications({ + required List times, + required String title, + required String body, + String? payload, + }) async { + try { + for (int i = 0; i < times.length; i++) { + final time = times[i]; + await scheduleNotification( + id: i + 1000, + // Offset ID to avoid conflicts + title: title, + body: body, + scheduledDate: time, + payload: payload, + ); + } + + loggerService.logInfo('Scheduled ${times.length} daily notifications'); + } catch (ex) { + loggerService.logError('Error scheduling daily notifications: $ex'); + } + } + + @override + Future scheduleWaterReminders({ + required List reminderTimes, + required String title, + required String body, + }) async { + try { + // Cancel existing water reminders first + await _cancelWaterReminders(); + + final androidDetails = AndroidNotificationDetails( + _waterReminderChannelId, + _waterReminderChannelName, + channelDescription: _waterReminderChannelDescription, + importance: Importance.high, + priority: Priority.high, + vibrationPattern: _getVibrationPattern(), + icon: 'app_icon', + styleInformation: const BigTextStyleInformation(''), + ); + + const iosDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ); + + final notificationDetails = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + for (int i = 0; i < reminderTimes.length; i++) { + final reminderTime = reminderTimes[i]; + final notificationId = 5000 + i; // Use 5000+ range for water reminders + + // Schedule for today if time hasn't passed, otherwise schedule for tomorrow + DateTime scheduledDate = reminderTime; + if (scheduledDate.isBefore(DateTime.now())) { + scheduledDate = scheduledDate.add(const Duration(days: 1)); + } + + await flutterLocalNotificationsPlugin.zonedSchedule( + notificationId, + title, + body, + tz.TZDateTime.from(scheduledDate, tz.local), + notificationDetails, + androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle, + matchDateTimeComponents: DateTimeComponents.time, // Repeat daily at the same time + payload: 'water_reminder_$i', + ); + } + + loggerService.logInfo('Scheduled ${reminderTimes.length} water reminders'); + } catch (ex) { + loggerService.logError('Error scheduling water reminders: $ex'); + } + } + + /// Cancel all water reminders (IDs 5000-5999) + Future _cancelWaterReminders() async { + try { + final pendingNotifications = await getPendingNotifications(); + for (final notification in pendingNotifications) { + if (notification.id >= 5000 && notification.id < 6000) { + await cancelNotification(notification.id); + } + } + loggerService.logInfo('Cancelled all water reminders'); + } catch (ex) { + loggerService.logError('Error cancelling water reminders: $ex'); + } + } + + @override + Future cancelNotification(int id) async { + try { + await flutterLocalNotificationsPlugin.cancel(id); + loggerService.logInfo('Cancelled notification with ID: $id'); + } catch (ex) { + loggerService.logError('Error cancelling notification: $ex'); + } + } + + @override + Future cancelAllNotifications() async { + try { + await flutterLocalNotificationsPlugin.cancelAll(); + loggerService.logInfo('Cancelled all notifications'); + } catch (ex) { + loggerService.logError('Error cancelling all notifications: $ex'); + } + } + + @override + Future> getPendingNotifications() async { + try { + final pending = await flutterLocalNotificationsPlugin.pendingNotificationRequests(); + loggerService.logInfo('Found ${pending.length} pending notifications'); + return pending; + } catch (ex) { + loggerService.logError('Error getting pending notifications: $ex'); + return []; + } + } + + /// Get vibration pattern for notifications + Int64List _getVibrationPattern() { + final vibrationPattern = Int64List(4); + vibrationPattern[0] = 0; + vibrationPattern[1] = 500; + vibrationPattern[2] = 500; + vibrationPattern[3] = 500; + return vibrationPattern; + } +} diff --git a/lib/splashPage.dart b/lib/splashPage.dart index bd7afa5..043eefd 100644 --- a/lib/splashPage.dart +++ b/lib/splashPage.dart @@ -5,30 +5,30 @@ import 'package:flutter_callkit_incoming/entities/call_event.dart'; import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; import 'package:get_it/get_it.dart'; -import 'package:hmg_patient_app_new/presentation/onboarding/onboarding_screen.dart'; -import 'package:hmg_patient_app_new/presentation/onboarding/splash_animation_screen.dart'; import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; - -// import 'package:hmg_patient_app_new/presentation/authantication/login.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; +import 'package:hmg_patient_app_new/presentation/onboarding/onboarding_screen.dart'; +import 'package:hmg_patient_app_new/presentation/onboarding/splash_animation_screen.dart'; import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.dart'; import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; +import 'package:hmg_patient_app_new/services/notification_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart'; import 'package:lottie/lottie.dart'; -import 'package:provider/provider.dart'; import 'core/cache_consts.dart'; -import 'core/utils/local_notifications.dart'; import 'core/utils/push_notification_handler.dart'; class SplashPage extends StatefulWidget { + const SplashPage({super.key}); + @override _SplashScreenState createState() => _SplashScreenState(); } @@ -47,9 +47,13 @@ class _SplashScreenState extends State { ); await authVm.getServicePrivilege(); Timer(Duration(seconds: 2, milliseconds: 500), () async { - bool isAppOpenedFromCall = await GetIt.instance().getBool(key: CacheConst.isAppOpenedFromCall) ?? false; + bool isAppOpenedFromCall = getIt.get().getBool(key: CacheConst.isAppOpenedFromCall) ?? false; - LocalNotification.init(onNotificationClick: (payload) {}); + // Initialize NotificationService using dependency injection + final notificationService = getIt.get(); + await notificationService.initialize(onNotificationClick: (payload) { + // Handle notification click here + }); if (isAppOpenedFromCall) { navigateToTeleConsult(); @@ -78,7 +82,8 @@ class _SplashScreenState extends State { // GetIt.instance().remove(key: CacheConst.isAppOpenedFromCall); Utils.removeFromPrefs(CacheConst.isAppOpenedFromCall); - Navigator.of(GetIt.instance().navigatorKey.currentContext!).pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: LandingNavigation()))); + Navigator.of(GetIt.instance().navigatorKey.currentContext!) + .pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: LandingNavigation()))); Navigator.pushReplacementNamed( // context, GetIt.instance().navigatorKey.currentContext!, @@ -216,7 +221,7 @@ class _SplashScreenState extends State { @override void initState() { - authVm = context.read(); + authVm = getIt(); super.initState(); initializeStuff(); } @@ -225,6 +230,8 @@ class _SplashScreenState extends State { Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.whiteColor, - body: Lottie.asset(AppAnimations.loadingAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 80.h, height: 80.h, fit: BoxFit.fill).center); + body: Lottie.asset(AppAnimations.loadingAnimation, + repeat: true, reverse: false, frameRate: FrameRate(60), width: 80.h, height: 80.h, fit: BoxFit.fill) + .center); } } diff --git a/lib/theme/colors.dart b/lib/theme/colors.dart index e658b29..c631f5b 100644 --- a/lib/theme/colors.dart +++ b/lib/theme/colors.dart @@ -8,6 +8,7 @@ class AppColors { static const bottomSheetBgColor = Color(0xFFF8F8FA); static const lightGreyEFColor = Color(0xffeaeaff); static const greyF7Color = Color(0xffF7F7F7); + static const greyInfoTextColor = Color(0xff777777); static const lightGrayColor = Color(0xff808080); static const greyTextColorLight = Color(0xFFA2A2A2); @@ -32,6 +33,7 @@ class AppColors { static const Color inputLabelTextColor = Color(0xff898A8D); static const Color greyTextColor = Color(0xFF8F9AA3); static const Color lightGrayBGColor = Color(0x142E3039); + static const Color checkBoxBorderColor = Color(0xffD2D2D2); static const Color pharmacyBGColor = Color(0xFF359846); @@ -42,6 +44,7 @@ class AppColors { //Chips static const Color successColor = Color(0xff18C273); + static const Color successLightBgColor = Color(0xffDDF6EA); static const Color errorColor = Color(0xFFED1C2B); static const Color alertColor = Color(0xFFD48D05); static const Color infoColor = Color(0xFF0B85F7); @@ -96,5 +99,14 @@ class AppColors { static const Color eReferralCardColor = Color(0xFFFF8012); static const Color bloodDonationCardColor = Color(0xFFFF5662); static const Color bookAppointment = Color(0xFF415364); + + // Water Monitor + static const Color blueColor = Color(0xFF4EB5FF); + static const Color blueGradientColorOne = Color(0xFFF1F7FD); + static const Color blueGradientColorTwo = Color(0xFFD9EFFF); + + // Shimmer + static const Color shimmerBaseColor = Color(0xFFE0E0E0); + static const Color shimmerHighlightColor = Color(0xFFF5F5F5); static const Color covid29Color = Color(0xff2563EB); } diff --git a/lib/widgets/buttons/custom_button.dart b/lib/widgets/buttons/custom_button.dart index 676f0bc..08d281f 100644 --- a/lib/widgets/buttons/custom_button.dart +++ b/lib/widgets/buttons/custom_button.dart @@ -75,7 +75,7 @@ class CustomButton extends StatelessWidget { children: [ if (icon != null) Padding( - padding: text.isNotEmpty ? EdgeInsets.only(right: 6.w, left: 6.w) : EdgeInsets.zero, + padding: text.isNotEmpty ? EdgeInsets.only(right: 8.w, left: 8.w) : EdgeInsets.zero, child: Utils.buildSvgWithAssets(icon: icon!, iconColor: iconColor, isDisabled: isDisabled, width: iconS, height: iconS), ), Visibility( diff --git a/lib/widgets/chip/app_custom_chip_widget.dart b/lib/widgets/chip/app_custom_chip_widget.dart index 8be16b7..69d82b7 100644 --- a/lib/widgets/chip/app_custom_chip_widget.dart +++ b/lib/widgets/chip/app_custom_chip_widget.dart @@ -72,11 +72,11 @@ class AppCustomChipWidget extends StatelessWidget { ? Image.asset(icon, width: iconS, height: iconS) : Utils.buildSvgWithAssets( icon: icon, - width: iconS, - height: iconS, - iconColor: iconHasColor ? iconColor : null, - fit: BoxFit.contain, - ) + width: iconS, + height: iconS, + iconColor: iconHasColor ? iconColor : null, + fit: BoxFit.contain, + ) : SizedBox.shrink(), label: richText ?? labelText!.toText10(weight: FontWeight.w500, letterSpacing: 0, color: textColor), padding: padding, diff --git a/lib/widgets/graph/custom_graph.dart b/lib/widgets/graph/custom_graph.dart index b955b32..e04d978 100644 --- a/lib/widgets/graph/custom_graph.dart +++ b/lib/widgets/graph/custom_graph.dart @@ -1,8 +1,9 @@ -import 'package:flutter/material.dart'; import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/common_models/data_points.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; + /// A customizable line graph widget using `fl_chart`. /// /// Displays a line chart with configurable axis labels, colors, and data points. @@ -56,67 +57,69 @@ class CustomGraph extends StatelessWidget { final FontWeight? bottomLabelFontWeight; final double? leftLabelInterval; final double? leftLabelReservedSize; + final double? bottomLabelReservedSize; final bool? showGridLines; final GetDrawingGridLine? getDrawingHorizontalLine; final double? horizontalInterval; final double? minY; final bool showShadow; + final double? cutOffY; final RangeAnnotations? rangeAnnotations; ///creates the left label and provide it to the chart as it will be used by other part of the application so the label will be different for every chart final Widget Function(double) leftLabelFormatter; - final Widget Function(double , List) bottomLabelFormatter; - + final Widget Function(double, List) bottomLabelFormatter; final Axis scrollDirection; final bool showBottomTitleDates; final bool isFullScreeGraph; final bool makeGraphBasedOnActualValue; - const CustomGraph({ - super.key, - required this.dataPoints, - required this.leftLabelFormatter, - this.width, - required this.scrollDirection, - required this.height, - this.maxY, - this.maxX, - this.showBottomTitleDates = true, - this.isFullScreeGraph = false, - this.spotColor = AppColors.bgGreenColor, - this.graphColor = AppColors.bgGreenColor, - this.graphShadowColor = AppColors.graphGridColor, - this.graphGridColor = AppColors.graphGridColor, - this.bottomLabelColor = AppColors.textColor, - this.bottomLabelFontWeight = FontWeight.w500, - this.bottomLabelSize, - this.leftLabelInterval, - this.leftLabelReservedSize, - this.makeGraphBasedOnActualValue = false, - required this.bottomLabelFormatter, - this.minX, - this.showGridLines = false, - this.getDrawingHorizontalLine, - this.horizontalInterval, - this.minY, - this.showShadow = false, - this.rangeAnnotations - }); + const CustomGraph( + {super.key, + required this.dataPoints, + required this.leftLabelFormatter, + this.width, + required this.scrollDirection, + required this.height, + this.maxY, + this.maxX, + this.showBottomTitleDates = true, + this.isFullScreeGraph = false, + this.spotColor = AppColors.bgGreenColor, + this.graphColor = AppColors.bgGreenColor, + this.graphShadowColor = AppColors.graphGridColor, + this.graphGridColor = AppColors.graphGridColor, + this.bottomLabelColor = AppColors.textColor, + this.bottomLabelFontWeight = FontWeight.w500, + this.bottomLabelSize, + this.leftLabelInterval, + this.leftLabelReservedSize, + this.bottomLabelReservedSize, + this.makeGraphBasedOnActualValue = false, + required this.bottomLabelFormatter, + this.minX, + this.showGridLines = false, + this.getDrawingHorizontalLine, + this.horizontalInterval, + this.minY, + this.showShadow = false, + this.cutOffY = 0, + this.rangeAnnotations}); @override Widget build(BuildContext context) { return Material( - color: Colors.white, - child: SizedBox( - width: width, - height: height, - child: LineChart( - LineChartData( - minY: minY??0, + color: Colors.white, + child: SizedBox( + width: width, + height: height, + child: LineChart( + LineChartData( + minY: minY ?? 0, maxY: maxY, maxX: maxX, - minX: minX , + minX: minX, lineTouchData: LineTouchData( getTouchLineEnd: (_, __) => 0, getTouchedSpotIndicator: (barData, indicators) { @@ -149,11 +152,8 @@ class CustomGraph extends StatelessWidget { final dataPoint = dataPoints[spot.x.toInt()]; return LineTooltipItem( - '${dataPoint.actualValue} ${dataPoint.unitOfMeasurement??""} - ${dataPoint.displayTime}', - TextStyle( - color: Colors.black, - fontSize: 12.f, - fontWeight: FontWeight.w500), + '${dataPoint.actualValue} ${dataPoint.unitOfMeasurement ?? ""} - ${dataPoint.displayTime}', + TextStyle(color: Colors.black, fontSize: 12.f, fontWeight: FontWeight.w500), ); } return null; // hides the rest @@ -165,7 +165,7 @@ class CustomGraph extends StatelessWidget { leftTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, - reservedSize: leftLabelReservedSize??80, + reservedSize: leftLabelReservedSize ?? 80, interval: leftLabelInterval ?? .1, // Let fl_chart handle it getTitlesWidget: (value, _) { return leftLabelFormatter(value); @@ -176,9 +176,9 @@ class CustomGraph extends StatelessWidget { axisNameSize: 20, sideTitles: SideTitles( showTitles: showBottomTitleDates, - reservedSize: 20, + reservedSize: bottomLabelReservedSize ?? 20, getTitlesWidget: (value, _) { - return bottomLabelFormatter(value, dataPoints, ); + return bottomLabelFormatter(value, dataPoints); }, interval: 1, // ensures 1:1 mapping with spots ), @@ -197,30 +197,29 @@ class CustomGraph extends StatelessWidget { ), lineBarsData: _buildColoredLineSegments(dataPoints), gridData: FlGridData( - show: showGridLines??true, + show: showGridLines ?? true, drawVerticalLine: false, - horizontalInterval:horizontalInterval, + horizontalInterval: horizontalInterval, // checkToShowHorizontalLine: (value) => // value >= 0 && value <= 100, - getDrawingHorizontalLine: getDrawingHorizontalLine??(value) { - return FlLine( - color: graphGridColor, - strokeWidth: 1, - dashArray: [5, 5], - ); - }, + getDrawingHorizontalLine: getDrawingHorizontalLine ?? + (value) { + return FlLine( + color: graphGridColor, + strokeWidth: 1, + dashArray: [5, 5], + ); + }, ), - rangeAnnotations: rangeAnnotations - ), - ), + rangeAnnotations: rangeAnnotations), ), + ), ); } - List _buildColoredLineSegments(List dataPoints) { final List allSpots = dataPoints.asMap().entries.map((entry) { - double value = (makeGraphBasedOnActualValue)?double.tryParse(entry.value.actualValue)??0.0:entry.value.value; + double value = (makeGraphBasedOnActualValue) ? double.tryParse(entry.value.actualValue) ?? 0.0 : entry.value.value; return FlSpot(entry.key.toDouble(), value); }).toList(); @@ -241,6 +240,8 @@ class CustomGraph extends StatelessWidget { ), belowBarData: BarAreaData( show: showShadow, + applyCutOffY: cutOffY != null, + cutOffY: cutOffY ?? 0, gradient: LinearGradient( colors: [ graphShadowColor, @@ -255,4 +256,4 @@ class CustomGraph extends StatelessWidget { return data; } -} \ No newline at end of file +} diff --git a/lib/widgets/shimmer/common_shimmer_widget.dart b/lib/widgets/shimmer/common_shimmer_widget.dart index d6a2906..3d935cb 100644 --- a/lib/widgets/shimmer/common_shimmer_widget.dart +++ b/lib/widgets/shimmer/common_shimmer_widget.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/int_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -11,9 +12,7 @@ class CommonShimmerWidget extends StatelessWidget { return SizedBox( child: Container( decoration: BoxDecoration( - borderRadius: const BorderRadius.all( - Radius.circular(10), - ), + borderRadius: BorderRadius.all(Radius.circular(10.r)), border: Border.all(color: AppColors.lightGreyEFColor, width: 1), boxShadow: [ BoxShadow( @@ -27,7 +26,11 @@ class CommonShimmerWidget extends StatelessWidget { padding: const EdgeInsets.all(12.0), child: Column( children: [ - Container(height: 100).toShimmer(), + Container( + height: 100, + decoration: BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(24.r)), + )).toShimmer(), 16.height, Container(height: 24).toShimmer(), 16.height, diff --git a/pubspec.yaml b/pubspec.yaml index 5590c9e..461d3ab 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -30,6 +30,7 @@ dependencies: # firebase_core: ^3.13.1 permission_handler: ^12.0.1 flutter_local_notifications: ^19.4.1 + timezone: ^0.10.0 provider: ^6.1.5+1 get_it: ^8.2.0 just_audio: ^0.10.4