diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 1032b29b..79bc3dc4 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -76,13 +76,21 @@ - - - + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt index 8b73b0c7..e67f646f 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt @@ -2,8 +2,7 @@ package com.cloud.diplomaticquarterapp import android.os.Bundle import android.util.Log import androidx.annotation.NonNull; -import com.cloud.diplomaticquarterapp.utils.FlutterText -import com.cloud.diplomaticquarterapp.utils.PlatformBridge +import com.cloud.diplomaticquarterapp.utils.* import io.flutter.embedding.android.FlutterFragmentActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel @@ -15,6 +14,16 @@ class MainActivity: FlutterFragmentActivity() { // Create Flutter Platform Bridge PlatformBridge(flutterEngine.dartExecutor.binaryMessenger, this).create() + val time = timeToMillis("04:00:00", "HH:mm:ss") + print(time) + +// val d1 = Logs.list(this) +// val d2 = Logs.raw(this) +// val d3 = Logs.RegisterGeofence.list(this) +// val d4 = Logs.RegisterGeofence.raw(this) +// val d5 = Logs.GeofenceEvent.list(this) +// val d6 = Logs.GeofenceEvent.raw(this) + print("") } override fun onResume() { diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeoZoneModel.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeoZoneModel.kt index 7eba1ead..b3fb4f56 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeoZoneModel.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeoZoneModel.kt @@ -37,6 +37,7 @@ class GeoZoneModel { val rad = Radius.toFloat() if(lat != null && long != null){ + val loiteringDelayMinutes:Int = 2 // in Minutes return Geofence.Builder() .setRequestId(identifier()) .setCircularRegion( @@ -45,7 +46,8 @@ class GeoZoneModel { rad ) .setTransitionTypes(GeofenceTransition.ENTER_EXIT.value) -// .setNotificationResponsiveness(0) + .setNotificationResponsiveness(0) + .setLoiteringDelay(loiteringDelayMinutes * 60 * 1000) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build() } diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceBroadcastReceiver.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceBroadcastReceiver.kt deleted file mode 100644 index 8fc1faae..00000000 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceBroadcastReceiver.kt +++ /dev/null @@ -1,13 +0,0 @@ - - -package com.cloud.diplomaticquarterapp.geofence - -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent - -class GeofenceBroadcastReceiver : BroadcastReceiver() { - override fun onReceive(context: Context, intent: Intent) { - GeofenceTransitionsJobIntentService.enqueueWork(context, intent) - } -} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/HMG_Geofence.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/HMG_Geofence.kt index 4d2c48b3..840075eb 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/HMG_Geofence.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/HMG_Geofence.kt @@ -6,7 +6,11 @@ import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager +import android.location.Location import androidx.core.content.ContextCompat +import com.cloud.diplomaticquarterapp.geofence.intent_receivers.GeofenceBroadcastReceiver +import com.cloud.diplomaticquarterapp.geofence.intent_receivers.ReregisterGeofenceJobService +import com.cloud.diplomaticquarterapp.utils.* import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingRequest @@ -17,8 +21,10 @@ import com.google.gson.reflect.TypeToken enum class GeofenceTransition(val value: Int) { ENTER(1), EXIT(2), + DWELL(4), + ENTER_EXIT((ENTER.value or EXIT.value)), - DWELL(4); + DWELL_EXIT((DWELL.value or EXIT.value)); companion object { fun fromInt(value: Int) = GeofenceTransition.values().first { it.value == value } @@ -27,17 +33,13 @@ enum class GeofenceTransition(val value: Int) { fun named():String{ if (value == 1)return "Enter" if (value == 2)return "Exit" - if (value == (ENTER.value or EXIT.value))return "Enter or Exit" if (value == 4)return "dWell" + if (value == (ENTER.value or EXIT.value))return "Enter or Exit" + if (value == (DWELL.value or EXIT.value))return "DWell or Exit" return "unknown" } } -const val PREFS_STORAGE = "FlutterSharedPreferences" -const val PREF_KEY_SUCCESS = "HMG_GEOFENCE_SUCCESS" -const val PREF_KEY_FAILED = "HMG_GEOFENCE_FAILED" -const val PREF_KEY_HMG_ZONES = "flutter.hmg-geo-fences" - class HMG_Geofence { // https://developer.android.com/training/location/geofencing#java @@ -69,13 +71,53 @@ class HMG_Geofence { } } - fun register(geoZones: List){ + fun limitize(zones: List):List{ + var geoZones_ = zones + if(zones.size > 100) + geoZones_ = zones.subList(0, 99) + return geoZones_ + } + + + fun register(completion:((Boolean, java.lang.Exception?)->Unit)){ + unRegisterAll { status, exception -> + val geoZones = getGeoZonesFromPreference(context) + doRegister(geoZones){ status_, error -> + completion.let { it(status_, error) } + } + } + } + + fun unRegisterAll(completion: (status: Boolean, exception: Exception?) -> Unit){ + getActiveGeofences({ success -> + removeActiveGeofences() + if(success.isNotEmpty()) + geofencingClient + .removeGeofences(success) + .addOnSuccessListener { + completion(true, null) + } + .addOnFailureListener { + completion(false, it) + saveLog(context, "error:REMOVE_GEOFENCES", it.localizedMessage) + } + else + completion(true, null) + + }, { failed -> + // Nothing to do with failed geofences. + }) + } + + private fun doRegister(geoZones: List, completion:((Boolean, java.lang.Exception?)->Unit)? = null){ if (geoZones.isEmpty()) return + val geoZones_ = limitize(geoZones) + fun buildGeofencingRequest(geofences: List): GeofencingRequest { return GeofencingRequest.Builder() - .setInitialTrigger(0) + .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL) .addGeofences(geofences) .build() } @@ -83,9 +125,9 @@ class HMG_Geofence { getActiveGeofences({ active -> val geofences = mutableListOf() - geoZones.forEach { - it.toGeofence()?.let { geof -> - if(!active.contains(geof.requestId)){ // if not already registered then register + geoZones_.forEach { + it.toGeofence()?.let { geof -> + if (!active.contains(geof.requestId)) { // if not already registered then register geofences.add(geof) } } @@ -95,31 +137,29 @@ class HMG_Geofence { geofencingClient .addGeofences(buildGeofencingRequest(geofences), geofencePendingIntent) .addOnSuccessListener { + Logs.RegisterGeofence.save(context,"SUCCESS", "Successfuly registered the geofences", Logs.STATUS.SUCCESS) saveActiveGeofence(geofences.map { it.requestId }, listOf()) + completion?.let { it(true,null) } } - .addOnFailureListener { - print(it.localizedMessage) + .addOnFailureListener { exc -> + Logs.RegisterGeofence.save(context,"FAILED_TO_REGISTER", "Failed to register geofence",Logs.STATUS.ERROR) + completion?.let { it(false,exc) } } + + // Schedule the job to register after specified duration (due to: events not calling after long period.. days or days [Needs to register fences again]) + HMGUtils.scheduleJob(context, ReregisterGeofenceJobService::class.java,ReregisterGeofenceJobService.JobID, ReregisterGeofenceJobService.TriggerIntervalDuration) } - },null) + + }, null) + } - fun unRegisterAll(completion: (status: Boolean, exception:Exception?) -> Unit){ - getActiveGeofences({ success -> - val mList = success.toMutableList() - mList.add("12345") - geofencingClient - .removeGeofences(success) - .addOnSuccessListener { - completion(true, null) - } - .addOnFailureListener { - completion(false, it) - } - removeActiveGeofences() - }, { failed -> - // Nothing to do with failed geofences. - }) + fun getGeoZonesFromPreference(context: Context):List{ + val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) + val json = pref.getString(PREF_KEY_HMG_ZONES, "[]") + + val geoZones = GeoZoneModel().listFrom(json!!) + return geoZones } fun saveActiveGeofence(success: List, failed: List){ @@ -130,8 +170,8 @@ class HMG_Geofence { } fun removeActiveGeofences(){ - preferences.edit().putString(PREF_KEY_SUCCESS,"[]").apply() - preferences.edit().putString(PREF_KEY_FAILED,"[]").apply() + preferences.edit().putString(PREF_KEY_SUCCESS, "[]").apply() + preferences.edit().putString(PREF_KEY_FAILED, "[]").apply() } fun getActiveGeofences(success: (success: List) -> Unit, failure: ((failed: List) -> Unit)?){ @@ -154,12 +194,48 @@ class HMG_Geofence { } fun getPatientID():Int?{ - val profileJson = preferences.getString("flutter.imei-user-data", "{}") + var profileJson = preferences.getString("flutter.imei-user-data", null) + if (profileJson == null) + profileJson = preferences.getString("flutter.user-profile", null) + val type = object : TypeToken?>() {}.type - return gson.fromJson?>(profileJson,type) + return gson.fromJson?>(profileJson, type) ?.get("PatientID") .toString() .toDoubleOrNull() ?.toInt() } + + + fun handleEvent(triggerGeofences: List, location: Location, transition: GeofenceTransition) { + getPatientID()?.let { patientId -> + getActiveGeofences({ activeGeofences -> + + triggerGeofences.forEach { geofence -> + // Extract PointID from 'geofence.requestId' and find from active geofences + val pointID = activeGeofences.firstOrNull { it == geofence.requestId }?.split('_')?.first() + if (!pointID.isNullOrEmpty() && pointID.toIntOrNull() != null) { + + val body = mutableMapOf( + "PointsID" to pointID.toIntOrNull(), + "GeoType" to transition.value, + "PatientID" to patientId + ) + body.putAll(HMGUtils.defaultHTTPParams(context)) + + httpPost>(API.LOG_GEOFENCE, body, { response -> + saveLog(context, "HMG_GEOFENCE_NOTIFY", "Success: Notified to server\uD83D\uDE0E.") + sendNotification(context, transition.named(), geofence.requestId, "Notified to server.😎") + }, { exception -> + val errorMessage = "${transition.named()}, ${geofence.requestId}" + saveLog(context, "HMG_GEOFENCE_NOTIFY", "failed: $errorMessage | error: ${exception.localizedMessage}") + sendNotification(context, transition.named(), geofence.requestId, "Failed to notify server😔 -> ${exception.localizedMessage}") + }) + + } + } + + }, null) + } + } } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiver.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiver.kt new file mode 100644 index 00000000..77df1572 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiver.kt @@ -0,0 +1,49 @@ + + +package com.cloud.diplomaticquarterapp.geofence.intent_receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Log +import com.cloud.diplomaticquarterapp.geofence.GeofenceTransition +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence +import com.cloud.diplomaticquarterapp.utils.Logs +import com.google.android.gms.location.GeofenceStatusCodes +import com.google.android.gms.location.GeofencingEvent + +class GeofenceBroadcastReceiver : BroadcastReceiver() { + private val LOG_TAG = "GeofenceBroadcastReceiver" + override fun onReceive(context: Context, intent: Intent) { + + val geofencingEvent = GeofencingEvent.fromIntent(intent) + if (geofencingEvent.hasError()) { + val errorMessage = GeofenceErrorMessages.getErrorString(context, geofencingEvent.errorCode) + Log.e(LOG_TAG, errorMessage) + + Logs.GeofenceEvent.save(context,LOG_TAG,"Error while triggering geofence event",Logs.STATUS.ERROR) + doReRegisterIfRequired(context,geofencingEvent.errorCode) + + return + } + + Logs.GeofenceEvent.save(context,LOG_TAG,"Geofence event triggered: ${GeofenceTransition.fromInt(geofencingEvent.geofenceTransition).value} for ${geofencingEvent.triggeringGeofences.map {it.requestId}}",Logs.STATUS.SUCCESS) + HMG_Geofence.shared(context).handleEvent(geofencingEvent.triggeringGeofences,geofencingEvent.triggeringLocation, GeofenceTransition.fromInt(geofencingEvent.geofenceTransition)); + + } + + fun doReRegisterIfRequired(context: Context, errorCode: Int){ + val errorRequiredReregister = listOf( + GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE, + GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES, + GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS, + GeofenceStatusCodes.GEOFENCE_REQUEST_TOO_FREQUENT + ) + + if(errorRequiredReregister.contains(errorCode)) + HMG_Geofence.shared(context).register(){ status, error -> + + } + + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiverWithJobService.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiverWithJobService.kt new file mode 100644 index 00000000..a9924ca1 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceBroadcastReceiverWithJobService.kt @@ -0,0 +1,16 @@ + + +package com.cloud.diplomaticquarterapp.geofence.intent_receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence +import com.google.android.gms.location.GeofenceStatusCodes + +class GeofenceBroadcastReceiverWithJobService : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + GeofenceTransitionsJobIntentService.enqueueWork(context, intent) + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceErrorMessages.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceErrorMessages.kt similarity index 67% rename from android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceErrorMessages.kt rename to android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceErrorMessages.kt index 4890f7cb..01377d49 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceErrorMessages.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceErrorMessages.kt @@ -1,9 +1,10 @@ -package com.cloud.diplomaticquarterapp.geofence +package com.cloud.diplomaticquarterapp.geofence.intent_receivers import android.content.Context import com.cloud.diplomaticquarterapp.R +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence import com.google.android.gms.common.api.ApiException import com.google.android.gms.location.GeofenceStatusCodes @@ -18,7 +19,7 @@ object GeofenceErrorMessages { fun getErrorString(context: Context, errorCode: Int): String { val resources = context.resources - return when (errorCode) { + val errorMessage = when (errorCode) { GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE -> resources.getString(R.string.geofence_not_available) @@ -28,7 +29,15 @@ object GeofenceErrorMessages { GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS -> resources.getString(R.string.geofence_too_many_pending_intents) + GeofenceStatusCodes.GEOFENCE_INSUFFICIENT_LOCATION_PERMISSION -> + resources.getString(R.string.GEOFENCE_INSUFFICIENT_LOCATION_PERMISSION) + + GeofenceStatusCodes.GEOFENCE_REQUEST_TOO_FREQUENT -> + resources.getString(R.string.GEOFENCE_REQUEST_TOO_FREQUENT) + else -> resources.getString(R.string.geofence_unknown_error) } + + return errorMessage } } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceTransitionsJobIntentService.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceTransitionsJobIntentService.kt similarity index 53% rename from android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceTransitionsJobIntentService.kt rename to android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceTransitionsJobIntentService.kt index f28e1720..214957cf 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofenceTransitionsJobIntentService.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofenceTransitionsJobIntentService.kt @@ -29,31 +29,27 @@ */ -package com.cloud.diplomaticquarterapp.geofence +package com.cloud.diplomaticquarterapp.geofence.intent_receivers import android.content.Context import android.content.Intent -import android.location.Location import android.util.Log import androidx.core.app.JobIntentService -import com.cloud.diplomaticquarterapp.utils.API -import com.cloud.diplomaticquarterapp.utils.httpPost -import com.cloud.diplomaticquarterapp.utils.sendNotification -import com.github.kittinunf.fuel.core.extensions.jsonBody -import com.github.kittinunf.fuel.core.isSuccessful -import com.github.kittinunf.fuel.httpPost -import com.google.android.gms.location.Geofence +import com.cloud.diplomaticquarterapp.geofence.GeofenceTransition +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence +import com.cloud.diplomaticquarterapp.utils.saveLog +import com.google.android.gms.location.GeofenceStatusCodes import com.google.android.gms.location.GeofencingEvent -import com.google.gson.Gson class GeofenceTransitionsJobIntentService : JobIntentService() { companion object { private const val LOG_TAG = "GeoTrIntentService" - private const val JOB_ID = 573 - + private const val JOB_ID = 95902 + var context_: Context? = null fun enqueueWork(context: Context, intent: Intent) { + context_ = context enqueueWork( context, GeofenceTransitionsJobIntentService::class.java, JOB_ID, @@ -64,43 +60,31 @@ class GeofenceTransitionsJobIntentService : JobIntentService() { override fun onHandleWork(intent: Intent) { val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent.hasError()) { - val errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.errorCode) + val errorMessage = GeofenceErrorMessages.getErrorString(context_!!, geofencingEvent.errorCode) Log.e(LOG_TAG, errorMessage) - return - } - if (geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { - handleEvent(geofencingEvent.triggeringGeofences,geofencingEvent.triggeringLocation, GeofenceTransition.fromInt(geofencingEvent.geofenceTransition)); - } - } - private fun handleEvent(triggerGeofences: List, location:Location, transition:GeofenceTransition) { - val hmg = HMG_Geofence.shared(this) - hmg.getPatientID()?.let { patientId -> + saveLog(context_!!,LOG_TAG,errorMessage) + doReRegisterIfRequired(context_!!, geofencingEvent.errorCode) - hmg.getActiveGeofences({ activeGeofences -> + return + } - triggerGeofences.forEach { geofence -> - // Extract PointID from 'geofence.requestId' and find from active geofences - val pointID = activeGeofences.firstOrNull {it == geofence.requestId}?.split('_')?.first() - if(!pointID.isNullOrEmpty() && pointID.toIntOrNull() != null){ + HMG_Geofence.shared(context_!!).handleEvent(geofencingEvent.triggeringGeofences,geofencingEvent.triggeringLocation, GeofenceTransition.fromInt(geofencingEvent.geofenceTransition)); - val body = mapOf( - "PointsID" to pointID.toIntOrNull(), - "GeoType" to transition.value, - "PatientID" to patientId - ) + } - httpPost>(API.LOG_GEOFENCE, body, { response -> - sendNotification(this, transition.named(), geofence.requestId, "Notified to server.😎") - },{ exception -> - sendNotification(this, transition.named(), geofence.requestId, "Failed to notify server.😔") - }) - } - } + fun doReRegisterIfRequired(context: Context, errorCode: Int){ + val errorRequiredReregister = listOf( + GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE, + GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES, + GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS, + GeofenceStatusCodes.GEOFENCE_REQUEST_TOO_FREQUENT + ) + + if(errorRequiredReregister.contains(errorCode)) + HMG_Geofence.shared(context).register(){ status, exc -> } - },null) - } } } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofencingRebootBroadcastReceiver.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofencingRebootBroadcastReceiver.kt similarity index 58% rename from android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofencingRebootBroadcastReceiver.kt rename to android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofencingRebootBroadcastReceiver.kt index 08a0c93f..6421b327 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/GeofencingRebootBroadcastReceiver.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/GeofencingRebootBroadcastReceiver.kt @@ -1,26 +1,22 @@ -package com.cloud.diplomaticquarterapp.geofence +package com.cloud.diplomaticquarterapp.geofence.intent_receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent -import android.os.Handler -import android.os.Message import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence -import com.cloud.diplomaticquarterapp.utils.HMGUtils +import com.cloud.diplomaticquarterapp.utils.PREFS_STORAGE class GeofencingRebootBroadcastReceiver : BroadcastReceiver(){ override fun onReceive(context: Context, intent: Intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.action)) { +// if (intent.action.equals("android.intent.action.BOOT_COMPLETE")) { val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) pref.edit().putString("REBOOT_DETECTED","YES").apply() - HMG_Geofence.shared(context).unRegisterAll { status, exception -> - val geoZones = HMGUtils.getGeoZonesFromPreference(context) - HMG_Geofence.shared(context).register(geoZones) - } + HMG_Geofence.shared(context).register(){ status, error -> } } } diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/LocationProviderChangeReceiver.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/LocationProviderChangeReceiver.kt new file mode 100644 index 00000000..273ca8f5 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/LocationProviderChangeReceiver.kt @@ -0,0 +1,25 @@ + + +package com.cloud.diplomaticquarterapp.geofence.intent_receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.location.LocationManager +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence +import com.cloud.diplomaticquarterapp.utils.HMGUtils +import com.cloud.diplomaticquarterapp.utils.PREFS_STORAGE + +class LocationProviderChangeReceiver : BroadcastReceiver() { + private val LOG_TAG = "LocationProviderChangeReceiver" + override fun onReceive(context: Context, intent: Intent) { + + if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.action)) { + val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) + pref.edit().putString("LOCATION_PROVIDER_CHANGE","YES").apply() + + HMG_Geofence.shared(context).register(){ s, e -> } + } + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/ReregisterGeofenceJobService.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/ReregisterGeofenceJobService.kt new file mode 100644 index 00000000..0bc496bc --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/geofence/intent_receivers/ReregisterGeofenceJobService.kt @@ -0,0 +1,24 @@ +package com.cloud.diplomaticquarterapp.geofence.intent_receivers + +import android.app.job.JobParameters +import android.app.job.JobService +import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence +import com.cloud.diplomaticquarterapp.utils.Logs + +class ReregisterGeofenceJobService : JobService(){ + companion object{ + val TriggerIntervalDuration:String = "06:00:00" + val JobID = 918273 + } + override fun onStartJob(params: JobParameters?): Boolean { + Logs.save(applicationContext,"ReregisterGeofenceJobService.onStartJob", "triggered to re-register the geofences after $TriggerIntervalDuration >> [HH:mm:ss]") + HMG_Geofence.shared(applicationContext).register(){ status, error -> + jobFinished(params, true) + } + return true + } + + override fun onStopJob(params: JobParameters?): Boolean { + return true + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/API.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/API.kt index 30f57dde..924bda91 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/API.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/API.kt @@ -2,7 +2,7 @@ package com.cloud.diplomaticquarterapp.utils class API { companion object{ - private val BASE = "https://uat.hmgwebservices.com" + private val BASE = "https://hmgwebservices.com" private val SERVICE = "Services/Patients.svc/REST" val WIFI_CREDENTIALS = "$BASE/$SERVICE/Hmg_SMS_Get_By_ProjectID_And_PatientID" diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Constants.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Constants.kt new file mode 100644 index 00000000..aa0f8ec2 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Constants.kt @@ -0,0 +1,8 @@ +package com.cloud.diplomaticquarterapp.utils + + +const val PREFS_STORAGE = "FlutterSharedPreferences" +const val PREF_KEY_SUCCESS = "HMG_GEOFENCE_SUCCESS" +const val PREF_KEY_FAILED = "HMG_GEOFENCE_FAILED" +const val PREF_KEY_HMG_ZONES = "flutter.hmg-geo-fences" +const val PREF_KEY_LANGUAGE = "flutter.language" \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt index ceecd65b..94bf54e6 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt @@ -3,6 +3,9 @@ package com.cloud.diplomaticquarterapp.utils import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent +import android.app.job.JobInfo +import android.app.job.JobScheduler +import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build @@ -14,17 +17,16 @@ import com.cloud.diplomaticquarterapp.BuildConfig import com.cloud.diplomaticquarterapp.MainActivity import com.cloud.diplomaticquarterapp.R import com.cloud.diplomaticquarterapp.geofence.GeoZoneModel -import com.cloud.diplomaticquarterapp.geofence.PREFS_STORAGE -import com.cloud.diplomaticquarterapp.geofence.PREF_KEY_HMG_ZONES import com.github.kittinunf.fuel.core.extensions.jsonBody import com.github.kittinunf.fuel.httpPost -import com.google.android.gms.location.Geofence import com.google.gson.Gson import com.google.gson.reflect.TypeToken import io.flutter.plugin.common.MethodChannel +import org.jetbrains.anko.doAsyncResult import org.json.JSONArray import org.json.JSONException import org.json.JSONObject +import java.text.SimpleDateFormat import java.util.* import kotlin.concurrent.timerTask @@ -68,24 +70,65 @@ class HMGUtils { } } - fun getGeoZonesFromPreference(context: Context): List { + fun getLanguageCode(context: Context) : Int { val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) - val json = pref.getString(PREF_KEY_HMG_ZONES,"[]") + val lang = pref.getString(PREF_KEY_LANGUAGE, "ar") + return if (lang == "ar") 2 else 1 + } - val geoZones = json?.let { GeoZoneModel().listFrom(it) } - return geoZones!! + fun defaultHTTPParams(context: Context) : Map{ + return mapOf( + "ZipCode" to "966", + "VersionID" to 5.8, + "Channel" to 3, + "LanguageID" to getLanguageCode(context), + "IPAdress" to "10.20.10.20", + "generalid" to "Cs2020@2016$2958", + "PatientOutSA" to 0, + "SessionID" to null, + "isDentalAllowedBackend" to false, + "DeviceTypeID" to 2) + } + + + fun scheduleJob(context: Context, pendingIntentClassType:Class, jobId:Int, intervalDuration:String, deadlineMillis:Long = (30 * 1000)) { // default deadline: 30 Seconds + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { + val jobScheduler: JobScheduler = context.getSystemService(JobScheduler::class.java) + + val serviceComponent = ComponentName(context, pendingIntentClassType) + val builder = JobInfo.Builder(jobId, serviceComponent) + builder.setPersisted(true) + builder.setBackoffCriteria(30000, JobInfo.BACKOFF_POLICY_LINEAR) + + val intervalMillis = timeToMillis(intervalDuration,"HH:mm:ss") + builder.setMinimumLatency(intervalMillis) // wait at least + builder.setOverrideDeadline((intervalMillis + deadlineMillis)) // maximum delay + if (jobScheduler.schedule(builder.build()) == JobScheduler.RESULT_SUCCESS){ + Logs.save(context,"ScheduleJob", "${pendingIntentClassType.simpleName}: Job scheduled to trigger after duration $intervalDuration >> HH:mm:ss --('MinimumLatency:$intervalMillis Deadline:${(intervalMillis + deadlineMillis)}')--",Logs.STATUS.SUCCESS) + }else{ + Logs.save(context,"ScheduleJob", "${pendingIntentClassType.simpleName}: Failed to scheduled Job",Logs.STATUS.ERROR) + } + + } else { + Logs.save(context,"ScheduleJob", "${pendingIntentClassType.simpleName}: Failed to scheduled Job on VERSION.SDK_INT < ${android.os.Build.VERSION_CODES.M}",Logs.STATUS.ERROR) + } } } } -private fun Timer.schedule(timerTask: TimerTask) { -} private const val NOTIFICATION_CHANNEL_ID = BuildConfig.APPLICATION_ID + ".channel" -fun sendNotification(context: Context, title:String, @Nullable subtitle:String?, message:String?) { + +fun timeToMillis(time:String, format:String):Long{ + val sdf = SimpleDateFormat(format, Locale.US) + val millis = sdf.parse(time).time + TimeZone.getDefault().rawOffset + return millis +} + +fun sendNotification(context: Context, title: String, @Nullable subtitle: String?, message: String?) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O @@ -117,8 +160,18 @@ fun sendNotification(context: Context, title:String, @Nullable subtitle:String?, notificationManager.notify(getUniqueId(), notification.build()) } +//------------------------- +// Open Helper Methods +//------------------------- +fun getUniqueId() = ((System.currentTimeMillis() % 10000).toInt()) -private fun getUniqueId() = ((System.currentTimeMillis() % 10000).toInt()) +object DateUtils { + @JvmStatic + fun dateTimeNow() : String { + val format = SimpleDateFormat("dd-MMM-yyy hh:mm:ss") + return format.format(Date()) + } +} fun isJSONValid(jsonString: String?): Boolean { try { JSONObject(jsonString) } catch (ex: JSONException) { @@ -129,31 +182,43 @@ fun isJSONValid(jsonString: String?): Boolean { return true } +fun saveLog(context: Context, tag: String, message: String){ + val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) + var logs = pref.getString("LOGS", "") + logs += "$tag -> $message \n" + pref.edit().putString("LOGS", logs).apply(); +} + +fun getLogs(context: Context) : String?{ + val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) + return pref.getString("LOGS", "") +} + class HTTPResponse(data: T){ final var data:T = data } -fun httpPost(url: String, body: Map, onSuccess: (response: HTTPResponse) -> Unit, onError: (error: Exception) -> Unit){ +fun httpPost(url: String, body: Map, onSuccess: (response: HTTPResponse) -> Unit, onError: (error: Exception) -> Unit){ val gson = Gson() val type = object : TypeToken() {}.type val jsonBody = gson.toJson(body) url.httpPost() .jsonBody(jsonBody, Charsets.UTF_8) .timeout(10000) - .header("Content-Type","application/json") - .header("Allow","*/*") + .header("Content-Type", "application/json") + .header("Allow", "*/*") .response { request, response, result -> + result.doAsyncResult { } result.fold({ data -> val dataString = String(data) - if(isJSONValid(dataString)){ - val responseData = gson.fromJson(dataString,type) + if (isJSONValid(dataString)) { + val responseData = gson.fromJson(dataString, type) onSuccess(HTTPResponse(responseData)) - }else{ + } else { onError(Exception("Invalid response from server (Not a valid JSON)")) } }, { onError(it) - it.localizedMessage }) } diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Logs.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Logs.kt new file mode 100644 index 00000000..e74f463e --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/Logs.kt @@ -0,0 +1,145 @@ +package com.cloud.diplomaticquarterapp.utils + +import android.content.Context +import android.content.SharedPreferences +import android.os.Build +import com.cloud.diplomaticquarterapp.BuildConfig +import com.google.gson.Gson + +class Logs { + + enum class STATUS{ + SUCCESS, + ERROR; + } + class GeofenceEvent{ + companion object{ + fun save(context: Context, tag:String, message:String, status:Logs.STATUS = STATUS.SUCCESS){ + Logs.Common.save(context,"GeofenceEvent", tag, message, status) + } + + fun list(context: Context, tag:String? = null, status:Logs.STATUS? = null):List{ + return Logs.Common.list(context,"GeofenceEvent", tag, status) + } + + fun raw(context: Context):String{ + return Logs.Common.raw(context,"GeofenceEvent") + } + } + } + + class RegisterGeofence{ + companion object{ + fun save(context: Context, tag:String, message:String, status:Logs.STATUS = STATUS.SUCCESS){ + Logs.Common.save(context,"RegisterGeofence", tag, message, status) + } + + fun list(context: Context, tag:String? = null, status:Logs.STATUS? = null):List{ + return Logs.Common.list(context,"RegisterGeofence", tag, status) + } + + fun raw(context: Context):String{ + return Logs.Common.raw(context,"RegisterGeofence"); + } + } + } + + + companion object{ + private var pref:SharedPreferences? = null + fun save(context: Context, tag:String, message:String, status:Logs.STATUS = STATUS.SUCCESS){ + Logs.Common.save(context,"Logs", tag, message, status) + } + + fun list(context: Context, tag:String? = null, status:Logs.STATUS? = null):List{ + return Logs.Common.list(context,"Logs", tag, status) + } + + fun raw(context: Context):String{ + return Logs.Common.raw(context,"Logs"); + } + + private fun storage(context: Context):SharedPreferences{ + if(pref == null) { + pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) + } + return pref!! + } + } + + private class Common{ + companion object{ + private val gson = Gson() + + fun save(context: Context, key:String, tag:String, message:String, status:Logs.STATUS = STATUS.SUCCESS){ + if(!BuildConfig.DEBUG) + return + + val pref = Logs.storage(context) + + val string = pref.getString(key,"{}") + val json = gson.fromJson(string,LogsContainerModel::class.java) + json.add( + LogModel().apply { + this.TAG = tag + this.MESSAGE = message + this.STATUS = status.name + this.DATE = DateUtils.dateTimeNow() + } + ) + + pref.edit().putString(key,gson.toJson(json)).apply() + } + + fun list(context: Context, key:String, tag:String? = null, status:Logs.STATUS? = null):List{ + val pref = Logs.storage(context) + val string = pref.getString(key,"{}") + val json = gson.fromJson(string,LogsContainerModel::class.java) + if(tag == null && status == null) { + return json.LOGS + }else if(tag != null && status != null){ + return json.LOGS.filter { (it.TAG == tag && it.STATUS == status.name) } + }else if(tag != null){ + return json.LOGS.filter { (it.TAG == tag) } + }else if(status != null){ + return json.LOGS.filter { (it.STATUS == status.name) } + } + return listOf() + } + + fun raw(context: Context, key:String):String{ + val pref = Logs.storage(context) + val string = pref.getString(key,"{}") + return string!! + } + + } + } + + class LogModel{ + lateinit var TAG:String + lateinit var MESSAGE:String + lateinit var STATUS:String + lateinit var DATE:String + + companion object{ + fun with(tag:String, message:String, status:String):LogModel{ + return LogModel().apply { + this.TAG = tag + this.MESSAGE = message + this.STATUS = status + this.DATE = DateUtils.dateTimeNow() + } + } + } + } + + class LogsContainerModel{ + var LOGS = mutableListOf() + fun add(log:LogModel){ + LOGS.add(log) + } + } + + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt index ed1a62c8..eb2fff08 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt @@ -105,7 +105,7 @@ class PlatformBridge(binaryMessenger: BinaryMessenger, flutterMainActivity: Main override fun success(result: Any?) { if(result is String) { val geoZones = GeoZoneModel().listFrom(result) - HMG_Geofence.shared(mainActivity).register(geoZones) + HMG_Geofence.shared(mainActivity).register(){ s, e -> } } } diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 8acc0c12..4e107030 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -13,4 +13,10 @@ You have provided too many PendingIntents to the addGeofences() call. + + App do not have permission to access location service. + + + Geofence requests happened too frequently. + diff --git a/assets/images/map_markers/destination_map_marker.png b/assets/images/map_markers/destination_map_marker.png new file mode 100644 index 00000000..4f4eca35 Binary files /dev/null and b/assets/images/map_markers/destination_map_marker.png differ diff --git a/assets/images/map_markers/driver-pin.png b/assets/images/map_markers/driver-pin.png new file mode 100644 index 00000000..9d16ceca Binary files /dev/null and b/assets/images/map_markers/driver-pin.png differ diff --git a/assets/images/map_markers/source_map_marker.png b/assets/images/map_markers/source_map_marker.png new file mode 100644 index 00000000..4b493b09 Binary files /dev/null and b/assets/images/map_markers/source_map_marker.png differ diff --git a/ios/GoogleService-Info.plist b/ios/GoogleService-Info.plist index 0c093a2a..633037cb 100644 --- a/ios/GoogleService-Info.plist +++ b/ios/GoogleService-Info.plist @@ -3,21 +3,23 @@ CLIENT_ID - 864393916058-ekeb4s8tgfo58dutv0l54399t7ivr06r.apps.googleusercontent.com + 815750722565-da8p56le8bd6apsbm9eft0jjl1rtpgkt.apps.googleusercontent.com REVERSED_CLIENT_ID - com.googleusercontent.apps.864393916058-ekeb4s8tgfo58dutv0l54399t7ivr06r + com.googleusercontent.apps.815750722565-da8p56le8bd6apsbm9eft0jjl1rtpgkt + ANDROID_CLIENT_ID + 815750722565-m14h8mkosm7cnq6uh6rhqr54dn02d705.apps.googleusercontent.com API_KEY - AIzaSyA_6ayGCk4fly7o7eTVBrj9kuHBYHMAOfs + AIzaSyDiXnCO00li4V7Ioa2YZ_M4ECxRsu_P9tA GCM_SENDER_ID - 864393916058 + 815750722565 PLIST_VERSION 1 BUNDLE_ID - com.cloud.diplomaticquarterapp + com.HMG.HMG-Smartphone PROJECT_ID - diplomaticquarter-d2385 + api-project-815750722565 STORAGE_BUCKET - diplomaticquarter-d2385.appspot.com + api-project-815750722565.appspot.com IS_ADS_ENABLED IS_ANALYTICS_ENABLED @@ -29,8 +31,8 @@ IS_SIGNIN_ENABLED GOOGLE_APP_ID - 1:864393916058:ios:13f787bbfe6051f8b97923 + 1:815750722565:ios:328ec247a81a2ca23c186c DATABASE_URL - https://diplomaticquarter-d2385.firebaseio.com + https://api-project-815750722565.firebaseio.com \ No newline at end of file diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 77dfa5e1..e16b62e0 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -20,7 +20,7 @@ PODS: - Firebase/Messaging (6.33.0): - Firebase/CoreOnly - FirebaseMessaging (~> 4.7.0) - - firebase_core (0.5.3): + - firebase_core (0.5.2): - Firebase/CoreOnly (~> 6.33.0) - Flutter - firebase_core_web (0.1.0): @@ -70,7 +70,7 @@ PODS: - Flutter - flutter_tts (0.0.1): - Flutter - - geolocator (6.1.9): + - "geolocator (6.0.0+4)": - Flutter - google_maps_flutter (0.0.1): - Flutter @@ -385,7 +385,7 @@ SPEC CHECKSUMS: device_calendar: 23b28a5f1ab3bf77e34542fb1167e1b8b29a98f5 device_info: d7d233b645a32c40dfdc212de5cf646ca482f175 Firebase: 8db6f2d1b2c5e2984efba4949a145875a8f65fe5 - firebase_core: 5d6a02f3d85acd5f8321c2d6d62877626a670659 + firebase_core: 350ba329d1641211bc6183a3236893cafdacfea7 firebase_core_web: d501d8b946b60c8af265428ce483b0fff5ad52d1 firebase_messaging: 0aea2cd5885b65e19ede58ee3507f485c992cc75 FirebaseCore: d889d9e12535b7f36ac8bfbf1713a0836a3012cd @@ -400,7 +400,7 @@ SPEC CHECKSUMS: flutter_local_notifications: 9e4738ce2471c5af910d961a6b7eadcf57c50186 flutter_plugin_android_lifecycle: dc0b544e129eebb77a6bfb1239d4d1c673a60a35 flutter_tts: 0f492aab6accf87059b72354fcb4ba934304771d - geolocator: 057a0c63a43e9c5296d8ad845a3ac8e6df23d899 + geolocator: 1ae40084cc6c1586ce5ad12cfc3fd38c64d05f2f google_maps_flutter: c7f9c73576de1fbe152a227bfd6e6c4ae8088619 GoogleDataTransport: f56af7caa4ed338dc8e138a5d7c5973e66440833 GoogleMaps: 4b5346bddfe6911bb89155d43c903020170523ac diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 0f0f942c..ade2e0aa 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -28,8 +28,10 @@ E923EFD62587443800E3E751 /* HMGPlatformBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = E923EFD52587443800E3E751 /* HMGPlatformBridge.swift */; }; E923EFD82588D17700E3E751 /* gpx.gpx in Resources */ = {isa = PBXBuildFile; fileRef = E923EFD72588D17700E3E751 /* gpx.gpx */; }; E9620805255C2ED100D3A35D /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9620804255C2ED100D3A35D /* NetworkExtension.framework */; }; + E9A35329258B8E8F00CBA688 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = E9A35328258B8E8F00CBA688 /* GoogleService-Info.plist */; }; E9C8C136256BACDA00EFFB62 /* HMG_Guest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9C8C135256BACDA00EFFB62 /* HMG_Guest.swift */; }; E9E27168256E3A4000F49B69 /* LocalizedFromFlutter.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9E27167256E3A4000F49B69 /* LocalizedFromFlutter.swift */; }; + E9F7623B25922BCE00FB5CCF /* FlutterConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F7623A25922BCE00FB5CCF /* FlutterConstants.swift */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -78,8 +80,10 @@ E923EFD72588D17700E3E751 /* gpx.gpx */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = gpx.gpx; sourceTree = ""; }; E9620803255C2ED100D3A35D /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; E9620804255C2ED100D3A35D /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; }; + E9A35328258B8E8F00CBA688 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; E9C8C135256BACDA00EFFB62 /* HMG_Guest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMG_Guest.swift; sourceTree = ""; }; E9E27167256E3A4000F49B69 /* LocalizedFromFlutter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalizedFromFlutter.swift; sourceTree = ""; }; + E9F7623A25922BCE00FB5CCF /* FlutterConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlutterConstants.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -128,6 +132,7 @@ 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( + E9A35328258B8E8F00CBA688 /* GoogleService-Info.plist */, E923EFD72588D17700E3E751 /* gpx.gpx */, 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, @@ -177,6 +182,7 @@ E923EFD125863FDF00E3E751 /* GeoZoneModel.swift */, E923EFD3258645C100E3E751 /* HMG_Geofence.swift */, E923EFD52587443800E3E751 /* HMGPlatformBridge.swift */, + E9F7623A25922BCE00FB5CCF /* FlutterConstants.swift */, ); path = Helper; sourceTree = ""; @@ -265,6 +271,7 @@ files = ( E91B53A0256AAC1400E96549 /* GuestPOC_Certificate.cer in Resources */, 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + E9A35329258B8E8F00CBA688 /* GoogleService-Info.plist in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, E923EFD82588D17700E3E751 /* gpx.gpx in Resources */, E91B539F256AAC1400E96549 /* GuestPOC_Certificate.p12 in Resources */, @@ -374,6 +381,7 @@ E91B5396256AAA6500E96549 /* GlobalHelper.swift in Sources */, E923EFD4258645C100E3E751 /* HMG_Geofence.swift in Sources */, E923EFD62587443800E3E751 /* HMGPlatformBridge.swift in Sources */, + E9F7623B25922BCE00FB5CCF /* FlutterConstants.swift in Sources */, 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, E9E27168256E3A4000F49B69 /* LocalizedFromFlutter.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, @@ -472,7 +480,7 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; + DEVELOPMENT_TEAM = 3A359E86ZF; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -611,7 +619,7 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; + DEVELOPMENT_TEAM = 3A359E86ZF; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -644,7 +652,7 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; + DEVELOPMENT_TEAM = 3A359E86ZF; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index e686619c..2dc828d1 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -2,46 +2,67 @@ import UIKit import Flutter import GoogleMaps +var userNotificationCenterDelegate:UNUserNotificationCenterDelegate? = nil @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { let locationManager = CLLocationManager() + var flutterViewController:MainFlutterVC! override func application( _ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { -// initLocationManager() GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8") GeneratedPluginRegistrant.register(with: self) - if let mainViewController = window.rootViewController as? MainFlutterVC{ - HMGPlatformBridge.initialize(flutterViewController: mainViewController) - } + initializePlatformChannel() if let _ = launchOptions?[.location] { HMG_Geofence.initGeofencing() } + UNUserNotificationCenter.current().delegate = self return super.application(application, didFinishLaunchingWithOptions: launchOptions) } -} - -extension AppDelegate: CLLocationManagerDelegate { - func initLocationManager(){ - locationManager.allowsBackgroundLocationUpdates = true - locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters - locationManager.activityType = .other - locationManager.delegate = self - locationManager.requestAlwaysAuthorization() + + func initializePlatformChannel(){ + if let mainViewController = window.rootViewController as? MainFlutterVC{ // platform initialization suppose to be in foreground + flutterViewController = mainViewController + HMGPlatformBridge.initialize(flutterViewController: flutterViewController) + + }else if let mainViewController = initialViewController(){ // platform initialization suppose to be in background + flutterViewController = mainViewController + HMGPlatformBridge.initialize(flutterViewController: flutterViewController) + } } - - func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { - if region is CLCircularRegion { + + + func initialViewController() -> MainFlutterVC?{ + return nil //UIStoryboard(name: "Main", bundle: .main).instantiateInitialViewController() as? MainFlutterVC } - } - - func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { - if region is CLCircularRegion { +} + +extension AppDelegate{ + override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + if (notification.request.content.categoryIdentifier == HmgLocalNotificationCategoryIdentifier){ + completionHandler([.alert,.sound]) + }else{ + super.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler) + } } - } } + + +/* + let dart = FlutterDartProject(precompiledDartBundle: .main) + let engine = FlutterEngine(name: "com.hmg.cs", project: dart, allowHeadlessExecution: true) + if engine.run(){ + flutterMethodChannel = FlutterMethodChannel(name: "HMG-Platform-Bridge", binaryMessenger: engine.binaryMessenger) + + Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { (timer) in + FlutterText.with(key: "alreadyConnectedHmgNetwork"){ localized in + print(localized) + } + } + } + */ diff --git a/ios/Runner/Helper/API.swift b/ios/Runner/Helper/API.swift index 763147c8..b487f033 100644 --- a/ios/Runner/Helper/API.swift +++ b/ios/Runner/Helper/API.swift @@ -13,5 +13,10 @@ fileprivate let BASE_URL = "\(DOMAIN)/\(SERVICE)" struct API { static let WIFI_CREDENTIALS = "\(BASE_URL)/Hmg_SMS_Get_By_ProjectID_And_PatientID" - } + + +//struct API { +// static let WIFI_CREDENTIALS = FlutterConstants.WIFI_CREDENTIALS_URL +// static let LOG_GEOFENCE = FlutterConstants.LOG_GEOFENCE_URL +//} diff --git a/ios/Runner/Helper/Extensions.swift b/ios/Runner/Helper/Extensions.swift index a8793617..de67f9b9 100644 --- a/ios/Runner/Helper/Extensions.swift +++ b/ios/Runner/Helper/Extensions.swift @@ -18,6 +18,24 @@ extension String{ } } +extension Date{ + func toString(format:String) -> String{ + let df = DateFormatter() + df.dateFormat = format + return df.string(from: self) + } +} + +extension Dictionary{ + func merge(dict:[String:Any?]) -> [String:Any?]{ + var self_ = self as! [String:Any?] + dict.forEach { (kv) in + self_.updateValue(kv.value, forKey: kv.key) + } + return self_ + } +} + extension Bundle { func certificate(named name: String) -> SecCertificate { diff --git a/ios/Runner/Helper/FlutterConstants.swift b/ios/Runner/Helper/FlutterConstants.swift new file mode 100644 index 00000000..f1b3f098 --- /dev/null +++ b/ios/Runner/Helper/FlutterConstants.swift @@ -0,0 +1,36 @@ +// +// FlutterConstants.swift +// Runner +// +// Created by ZiKambrani on 22/12/2020. +// + +import UIKit + +class FlutterConstants{ + static var LOG_GEOFENCE_URL:String? + static var WIFI_CREDENTIALS_URL:String? + static var DEFAULT_HTTP_PARAMS:[String:Any?]? + + class func set(){ + + // (FiX) Take a start with FlutterMethodChannel (kikstart) + /* First call to flutter method is not returning the correct value (Always returning 'NSObject') then after it wroking fine and returning correct value*/ + FlutterText.with(key: "test") { (test) in + + flutterMethodChannel?.invokeMethod("getDefaultHttpParameters", arguments: nil){ (response) in + if let defaultHTTPParams = response as? [String:Any?]{ + DEFAULT_HTTP_PARAMS = defaultHTTPParams + } + + } + + flutterMethodChannel?.invokeMethod("getLogGeofenceFullUrl", arguments:nil){ (response) in + if let url = response as? String{ + LOG_GEOFENCE_URL = url + } + } + + } + } +} diff --git a/ios/Runner/Helper/GlobalHelper.swift b/ios/Runner/Helper/GlobalHelper.swift index c5eb7295..37687806 100644 --- a/ios/Runner/Helper/GlobalHelper.swift +++ b/ios/Runner/Helper/GlobalHelper.swift @@ -31,27 +31,59 @@ func dictionary(from:String) -> [String:Any]?{ } -func showNotification(identifier:String? = nil, title:String?, subtitle:String?, message:String?, sound:UNNotificationSound = UNNotificationSound.default){ - let notificationContent = UNMutableNotificationContent() - - if identifier != nil { notificationContent.categoryIdentifier = identifier! } - if title != nil { notificationContent.title = title! } - if subtitle != nil { notificationContent.body = message! } - if message != nil { notificationContent.subtitle = subtitle! } - - notificationContent.sound = UNNotificationSound.default - let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) - let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSinceNow)", content: notificationContent, trigger: trigger) - UNUserNotificationCenter.current().add(request) { error in - if let error = error { - print("Error: \(error)") +let HmgLocalNotificationCategoryIdentifier = "hmg.local.notification" +func showNotification(identifier:String? = nil, title:String?, subtitle:String?, message:String?, sound:UNNotificationSound = UNNotificationSound.default, categoryIdentifier:String = HmgLocalNotificationCategoryIdentifier){ + DispatchQueue.main.async { + let notificationContent = UNMutableNotificationContent() + notificationContent.categoryIdentifier = categoryIdentifier + + if identifier != nil { notificationContent.categoryIdentifier = identifier! } + if title != nil { notificationContent.title = title! } + if subtitle != nil { notificationContent.body = message! } + if message != nil { notificationContent.subtitle = subtitle! } + + notificationContent.sound = UNNotificationSound.default + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) + let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSinceNow)", content: notificationContent, trigger: trigger) + + + UNUserNotificationCenter.current().add(request) { error in + if let error = error { + print("Error: \(error)") + } } } } +func appLanguageCode() -> Int{ + let lang = UserDefaults.standard.string(forKey: "language") ?? "ar" + return lang == "ar" ? 2 : 1 +} + +func userProfile() -> [String:Any?]?{ + var userProf = UserDefaults.standard.string(forKey: "flutter.imei-user-data") + if(userProf == nil){ + userProf = UserDefaults.standard.string(forKey: "flutter.user-profile") + } + return dictionary(from: userProf ?? "{}") +} + +fileprivate let defaultHTTPParams:[String : Any?] = [ + "ZipCode" : "966", + "VersionID" : 5.8, + "Channel" : 3, + "LanguageID" : appLanguageCode(), + "IPAdress" : "10.20.10.20", + "generalid" : "Cs2020@2016$2958", + "PatientOutSA" : 0, + "SessionID" : nil, + "isDentalAllowedBackend" : false, + "DeviceTypeID" : 2 +] -func httpPostRequest(urlString:String, jsonBody:[String:Any], completion:((Bool,[String:Any]?)->Void)?){ - let json: [String: Any] = jsonBody +func httpPostRequest(urlString:String, jsonBody:[String:Any?], completion:((Bool,[String:Any]?)->Void)?){ + var json: [String: Any?] = jsonBody + json = json.merge(dict: defaultHTTPParams) let jsonData = try? JSONSerialization.data(withJSONObject: json) // create post request @@ -77,6 +109,8 @@ func httpPostRequest(urlString:String, jsonBody:[String:Any], completion:((Bool, completion?(false,responseJSON) } + }else{ + completion?(false,nil) } } diff --git a/ios/Runner/Helper/HMGPlatformBridge.swift b/ios/Runner/Helper/HMGPlatformBridge.swift index f897188c..f94f9b34 100644 --- a/ios/Runner/Helper/HMGPlatformBridge.swift +++ b/ios/Runner/Helper/HMGPlatformBridge.swift @@ -49,6 +49,9 @@ class HMGPlatformBridge{ print("") } + Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (timer) in + FlutterConstants.set() + } } diff --git a/ios/Runner/Helper/HMG_Geofence.swift b/ios/Runner/Helper/HMG_Geofence.swift index fb469165..47454d3e 100644 --- a/ios/Runner/Helper/HMG_Geofence.swift +++ b/ios/Runner/Helper/HMG_Geofence.swift @@ -129,8 +129,10 @@ extension HMG_Geofence : CLLocationManagerDelegate{ extension HMG_Geofence{ func handleEvent(for region: CLRegion!, transition:Transition, location:CLLocation?) { - notifyUser(forRegion: region, transition: transition, location: locationManager.location) - notifyServer(forRegion: region, transition: transition, location: locationManager.location) + if let userProfile = userProfile(){ + notifyUser(forRegion: region, transition: transition, location: locationManager.location, userProfile: userProfile) + notifyServer(forRegion: region, transition: transition, location: locationManager.location, userProfile: userProfile) + } } func geoZone(by id: String) -> GeoZoneModel? { @@ -144,20 +146,14 @@ extension HMG_Geofence{ } - func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?){ - if let zone = geoZone(by: forRegion.identifier){ - if UIApplication.shared.applicationState == .active { - mainViewController.showAlert(withTitle: transition.name(), message: zone.message()) - }else{ - - } + func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){ + if let patientId = userProfile["PatientID"] as? Int{ + } } - func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?){ - df.dateFormat = "MMM/dd/yyyy hh:mm:ss" - if let userProfileJson = UserDefaults.standard.string(forKey: "flutter.user-profile"), - let userProfile = dictionary(from: userProfileJson), let patientId = userProfile["PatientID"] as? Int{ + func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){ + if let patientId = userProfile["PatientID"] as? Int{ if let idString = forRegion.identifier.split(separator: "_").first, let idInt = Int(idString){ let body:[String:Any] = [ @@ -165,22 +161,20 @@ extension HMG_Geofence{ "GeoType":transition.rawValue, "PatientID":patientId ] + + var logs = UserDefaults.init(suiteName: "GeoFenceLog")?.dictionary(forKey: "GEOFENCE_LOGS") ?? [:] + var geo = (logs[forRegion.identifier] as? [String]) ?? [] let url = "https://hmgwebservices.com/Services/Patients.svc/REST/GeoF_InsertPatientFileInfo" httpPostRequest(urlString: url, jsonBody: body){ (status,json) in - let status_ = status ? "Notified" : "Not notified" + let status_ = status ? "Notified successfully:" : "Failed to notify:" showNotification(title: transition.name(), subtitle: forRegion.identifier, message: status_) - var logs = UserDefaults.init(suiteName: "GeoFenceLog")?.dictionary(forKey: "LOGS") ?? [:] - if var geo = logs[forRegion.identifier] as? [String]{ - geo.append("\(status_) at \(df.string(from: Date()))") - }else{ - logs.updateValue(["\(status_) at \(df.string(from: Date()))"], forKey: forRegion.identifier) - } - - UserDefaults.init(suiteName: "GeoFenceLog")?.set(logs, forKey: "LOGS") + geo.append("\(status_) \(transition.name()) at \(Date().toString(format: "dd/MMM/yyy hh:mm:ss"))") + logs.updateValue( geo, forKey: forRegion.identifier) + UserDefaults.init(suiteName: "GeoFenceLog")?.set(logs, forKey: "GEOFENCE_LOGS") } } } diff --git a/ios/gpx.gpx b/ios/gpx.gpx index 9cc26956..ed8e9be6 100644 --- a/ios/gpx.gpx +++ b/ios/gpx.gpx @@ -1 +1 @@ - Sverrir Sigmundarson Office Office Mahmoud Home Mahmoud Home Panorama Mall Panorama Mall Saudi Architects Crossing Saudi Architects Crossing Office Office \ No newline at end of file + Sverrir Sigmundarson 608.26 620.97 617.77 643.86 \ No newline at end of file diff --git a/lib/config/config.dart b/lib/config/config.dart index 3f5f8755..e909dad8 100644 --- a/lib/config/config.dart +++ b/lib/config/config.dart @@ -30,6 +30,10 @@ const WEATHER_INDICATOR = 'Services/Weather.svc/REST/GetCityInfo'; const GET_PRIVILEGE = 'Services/Patients.svc/REST/Service_Privilege'; +// Wifi Credentials +const WIFI_CREDENTIALS = + "Services/Patients.svc/Hmg_SMS_Get_By_ProjectID_And_PatientID"; + ///Doctor const GET_MY_DOCTOR = 'Services/Doctors.svc/REST/GetPatientDoctorAppointmentResult'; @@ -372,6 +376,10 @@ const GET_CALL_INFO_HOURS_RESULT = 'Services/Doctors.svc/REST/GetCallInfoHoursResult'; const GET_CALL_REQUEST_TYPE_LOV = 'Services/Doctors.svc/REST/GetCallRequestType_LOV'; + +const UPDATE_DIABETIC_RESULT = + 'Services/Patients.svc/REST/Patient_UpdateDiabeticResult'; + const GET_DOCTOR_RESPONSE = 'Services/Patients.svc/REST/GetDoctorResponse'; const UPDATE_READ_STATUS = 'Services/Patients.svc/REST/UpdateReadStatus'; const INSERT_CALL_INFO = 'Services/Doctors.svc/REST/InsertCallInfo'; @@ -408,7 +416,7 @@ const GET_PHARMACY_BEST_SELLER_PRODUCT = "epharmacy/api/bestsellerproducts"; const GET_PHARMACY_PRODUCTs_BY_IDS = "epharmacy/api/productsbyids/"; const GET_CUSTOMERS_ADDRESSES = "epharmacy/api/Customers/"; const GET_ORDER = "orders?"; -const GET_ORDER_DETAILS = "epharmacy/api/orders/"; +const GET_ORDER_DETAILS = "orders/"; const ADD_CUSTOMER_ADDRESS = "epharmacy/api/addcustomeraddress"; const EDIT_CUSTOMER_ADDRESS = "epharmacy/api/editcustomeraddress"; const DELETE_CUSTOMER_ADDRESS = "epharmacy/api/deletecustomeraddress"; @@ -435,6 +443,7 @@ const TRANSFER_YAHALA_LOYALITY_POINTS = "Services/Patients.svc/REST/TransferYaHalaLoyaltyPoints"; const LAKUM_GET_USER_TERMS_AND_CONDITIONS = "Services/ERP.svc/REST/GetUserTermsAndConditionsForEPharmcy"; +const PRESCRIPTION = 'Services/Patients.svc/REST/GetPrescriptionApptList'; // Home Health Care const HHC_GET_ALL_SERVICES = @@ -457,6 +466,10 @@ const GET_PATIENT_ALL_PRES_ORD = const PATIENT_ER_INSERT_PRES_ORDER = 'Services/Patients.svc/REST/PatientER_InsertPresOrder'; const PHARMACY_MAKE_REVIEW = 'epharmacy/api/insertreviews'; +const BLOOD_DONATION_REGISTER_BLOOD_TYPE = + 'Services/PatientVarification.svc/REST/BloodDonation_RegisterBloodType'; +const ADD_USER_AGREEMENT_FOR_BLOOD_DONATION = + 'Services/PatientVarification.svc/REST/AddUserAgreementForBloodDonation'; //Pharmacy wishlist const GET_WISHLIST = "shopping_cart_items/"; @@ -510,7 +523,6 @@ class AppGlobal { Request getPublicRequest() { Request request = new Request(); - request.VersionID = 5.6; //3.6; request.Channel = 3; request.IPAdress = "10.20.10.20"; request.generalid = 'Cs2020@2016\$2958'; diff --git a/lib/config/localized_values.dart b/lib/config/localized_values.dart index 8eea6cbb..1761dd99 100644 --- a/lib/config/localized_values.dart +++ b/lib/config/localized_values.dart @@ -231,6 +231,7 @@ const Map localizedValues = { 'ar': 'ابحث عن الدواء هنا' }, 'description': {'en': 'Description', 'ar': 'الوصف'}, + 'howToUse': {'en': 'How to Use', 'ar': 'طريقة الأستخدام'}, 'price': {'en': 'Price', 'ar': 'السعر'}, 'youCanFindItIn': {'en': 'You can find it in', 'ar': 'يمكنكة ان تجده في'}, 'pleaseEnterMedicineName': { @@ -296,6 +297,10 @@ const Map localizedValues = { "en": "Email Sent Successfully", "ar": "تم إرسال البريد الإلكتروني بنجاح" }, + "EmailSentError": { + "en": "Error Sending Email", + "ar": "خطأ في إرسال البريد الإلكتروني" + }, "close": {"en": "Close", "ar": "مغلق"}, "booked": {"en": "Booked", "ar": "محجوز"}, "confirmed": {"en": "Confirmed", "ar": "مؤكد"}, @@ -594,6 +599,7 @@ const Map localizedValues = { "SelectPatientName": {"en": "Select Patient Name", "ar": "اختر اسم المريض"}, "SelectFamilyPatientName": {"en": "Family Members", "ar": "أفراد الأسرة"}, "SelectHospital": {"en": "Select Hospital", "ar": "اختر المستشفى"}, + "selectCity": {"en": "Select City", "ar": "اختر المدينة"}, "MyAccount": {"en": "My Account", "ar": "حسابي"}, "OtherAccount": {"en": "Other Account", "ar": "حساب آخر"}, "SelectBeneficiary": {"en": "Select Beneficiary", "ar": "حدد المستفيد"}, @@ -710,6 +716,7 @@ const Map localizedValues = { "cancelledOrder": {"en": " CANCELLED", "ar": "ملغي"}, "compare": {"en": " Compare", "ar": "مقارنه"}, "medicationsRefill": {"en": " Medication Refill", "ar": "طلب أعادة صرف"}, + "recommended": {"en": " Recommended For You", "ar": "موصى لك"}, "myPrescription": {"en": " My Prescriptions", "ar": "وصفاتي"}, "quantity": {"en": " QTY ", "ar": "الكمية"}, "backMyAccount": { @@ -1352,6 +1359,10 @@ const Map localizedValues = { "en": "Send a copy of this report to the email", "ar": "أرسل نسخة من هذا التقرير إلى البريد الإلكتروني" }, + "update-email-msg": { + "en": "Email updated", + "ar": "تم تحديث البريد الالكتروني" + }, "update-email": {"en": "Update Email", "ar": "تحديث البريد الالكتروني"}, "booked-success": { "en": "The appointment has been successfully booked.", @@ -1554,6 +1565,10 @@ const Map localizedValues = { }, "covidTest": {"en": "COVID-19 TEST", "ar": "فحص كورونا"}, "driveThru": {"en": "Drive-Thru", "ar": "من السيارة"}, + "trackDeliveryDriver": { + "en": "Track Delivery Driver", + "ar": "trackDeliveryDriver" + }, "NearestErDesc": { "en": "\nThis service Displays nearest branch\n among all the branches of All Habib \n medical Group based on your current Location", @@ -1574,4 +1589,54 @@ const Map localizedValues = { "هذا ملخص التقرير الصحي الشهري و الذي يسرد المؤشرات الصحية و نتائج التحاليل لأخر الزيارات. يرجى ملاحظة أن هذا التقرير هو تقرير يتم ارساله بشكل آلي من النظام و لا يعتبر رسمي و لا تؤخذ عليه أي قرارات طبية" }, "reqId": {"en": "Request ID:", "ar": " رقم الطلب"}, + "RRT-orders-log": {"en": "Orders Log", "ar": "سجل الطلبات"}, + "blood-sugar": {"en": "Blood Sugar", "ar": "سكر الدم"}, + + "covid19_driveThrueTest": { + "en": "'Covid-19- Drive-Thru Test'", + "ar": "Covid-19- الفحص من خلال القيادة" + }, + "E-Referral": {"en": "'E-Referral'", "ar": "الإحالة الإلكترونية"}, + "childName": {"en": "'CHILD NAME'", "ar": "إسم الطفل"}, + "recordDeleted": {"en": "'Record Deleted'", "ar": "تم حذف السجل"}, + "msg_email_address_up_to_date": { + "en": + "Please ensure that the email address is up-to-date and process to view the schedule", + "ar": + "يرجى التأكد من أن عنوان البريد الإلكتروني محدث وأن العملية لعرض الجدول الزمني" + }, + "add-new-child": {"en": "ADD NEW CHILD", "ar": "إضافة طفل جديد"}, + "send-child-email-msg": { + "en": "Send the child's schedule to the email", + "ar": "أرسل جدول الطفل إلى البريد الإلكتروني" + }, + "vaccination-add-child-msg": { + "en": + "Add the child's information below to receive the schedule of vaccinations.", + "ar": "أضف معلومات الطفل أدناه للحصول على جدول التطعيمات." + }, + "child_added_successfully": { + "en": "Child added successfully", + "ar": "تمت إضافة الطفل بنجاح" + }, + "my-tracker": {"en": "My Tracker", "ar": "قراءاتي"}, + "weekly": {"en": "Weekly", "ar": "أسبوعي"}, + "monthly": {"en": "Monthly", "ar": "شهري"}, + "yearly": {"en": "Yearly", "ar": "سنوي"}, + "measured": {"en": "Measured", "ar": "قياس"}, + "sugar-add": {"en": "Enter Blood Sugar Value", "ar": "أدخل قيمة قراءة السكر"}, + "other": {"en": "Other", "ar": "آخر"}, + "measure-unit": {"en": "Measure unit", "ar": "وحدة القياس"}, + "measure-time": {"en": "Measure time", "ar": "وقت القياس"}, + "update": {"en": "Update", "ar": "تعديل"}, + "bloodD-enter-desc": { + "en": + "Enter the required information, In order to register for Blood Donation Service", + "ar": "أدخل المعلومات المطلوبة ، للتسجيل في خدمة التبرع بالدم" + }, + "viewTermsConditions": { + "en": "To view the terms and conditions", + "ar": "لعرض الشروط والأحكام" + }, + // "visit": {"en" : "Visit", "ar": "الزيارة"}, }; diff --git a/lib/core/enum/Ambulate.dart b/lib/core/enum/Ambulate.dart index f8b2e8be..e4714cb2 100644 --- a/lib/core/enum/Ambulate.dart +++ b/lib/core/enum/Ambulate.dart @@ -1,3 +1,4 @@ +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:flutter/cupertino.dart'; enum Ambulate { Wheelchair, Walker, Stretcher, None } @@ -6,19 +7,19 @@ extension SelectedAmbulate on Ambulate { String getAmbulateTitle(BuildContext context) { switch (this) { case Ambulate.Wheelchair: - return 'Wheelchair'; + return TranslationBase.of(context).wheelchair; break; case Ambulate.Walker: - return 'Walker'; + return TranslationBase.of(context).walker; break; case Ambulate.Stretcher: - return 'Stretcher'; + return TranslationBase.of(context).stretcher; break; case Ambulate.None: - return 'None'; + return TranslationBase.of(context).none; break; } - return 'None'; + return TranslationBase.of(context).none; } int selectAmbulateNumber() { diff --git a/lib/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart b/lib/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart index 5b95409e..86263155 100644 --- a/lib/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart +++ b/lib/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart @@ -17,7 +17,7 @@ class DiabtecPatientResult { int patientID; var remark; var resultDesc; - int resultValue; + dynamic resultValue; String unit; var weekAverageResult; String weekDesc; diff --git a/lib/core/model/my_trakers/blood_sugar/WeekDiabtectResultAverage.dart b/lib/core/model/my_trakers/blood_sugar/WeekDiabtectResultAverage.dart index c18e5433..3b1a8d9c 100644 --- a/lib/core/model/my_trakers/blood_sugar/WeekDiabtectResultAverage.dart +++ b/lib/core/model/my_trakers/blood_sugar/WeekDiabtectResultAverage.dart @@ -1,7 +1,7 @@ import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; class WeekDiabtectResultAverage { - int dailyAverageResult; + dynamic dailyAverageResult; DateTime dateChart; WeekDiabtectResultAverage({this.dailyAverageResult, this.dateChart}); diff --git a/lib/core/model/pharmacies/Prescriptions.dart b/lib/core/model/pharmacies/Prescriptions.dart new file mode 100644 index 00000000..80caff0a --- /dev/null +++ b/lib/core/model/pharmacies/Prescriptions.dart @@ -0,0 +1,157 @@ + + +import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; + +class Prescriptions { + String setupID; + int projectID; + int patientID; + int appointmentNo; + String appointmentDate; + String doctorName; + String clinicDescription; + String name; + int episodeID; + int actualDoctorRate; + int admission; + int clinicID; + String companyName; + String despensedStatus; + DateTime dischargeDate; + int dischargeNo; + int doctorID; + String doctorImageURL; + int doctorRate; + String doctorTitle; + int gender; + String genderDescription; + bool isActiveDoctorProfile; + bool isDoctorAllowVedioCall; + bool isExecludeDoctor; + bool isInOutPatient; + String isInOutPatientDescription; + String isInOutPatientDescriptionN; + bool isInsurancePatient; + String nationalityFlagURL; + int noOfPatientsRate; + String qR; + List speciality; + + Prescriptions( + {this.setupID, + this.projectID, + this.patientID, + this.appointmentNo, + this.appointmentDate, + this.doctorName, + this.clinicDescription, + this.name, + this.episodeID, + this.actualDoctorRate, + this.admission, + this.clinicID, + this.companyName, + this.despensedStatus, + this.dischargeDate, + this.dischargeNo, + this.doctorID, + this.doctorImageURL, + this.doctorRate, + this.doctorTitle, + this.gender, + this.genderDescription, + this.isActiveDoctorProfile, + this.isDoctorAllowVedioCall, + this.isExecludeDoctor, + this.isInOutPatient, + this.isInOutPatientDescription, + this.isInOutPatientDescriptionN, + this.isInsurancePatient, + this.nationalityFlagURL, + this.noOfPatientsRate, + this.qR, + this.speciality}); + + Prescriptions.fromJson(Map json) { + setupID = json['SetupID']; + projectID = json['ProjectID']; + patientID = json['PatientID']; + appointmentNo = json['AppointmentNo']; + appointmentDate = json['AppointmentDate']; + doctorName = json['DoctorName']; + clinicDescription = json['ClinicDescription']; + name = json['Name']; + episodeID = json['EpisodeID']; + actualDoctorRate = json['ActualDoctorRate']; + admission = json['Admission']; + clinicID = json['ClinicID']; + companyName = json['CompanyName']; + despensedStatus = json['Despensed_Status']; + dischargeDate = DateUtil.convertStringToDate(json['DischargeDate']); + dischargeNo = json['DischargeNo']; + doctorID = json['DoctorID']; + doctorImageURL = json['DoctorImageURL']; + doctorRate = json['DoctorRate']; + doctorTitle = json['DoctorTitle']; + gender = json['Gender']; + genderDescription = json['GenderDescription']; + isActiveDoctorProfile = json['IsActiveDoctorProfile']; + isDoctorAllowVedioCall = json['IsDoctorAllowVedioCall']; + isExecludeDoctor = json['IsExecludeDoctor']; + isInOutPatient = json['IsInOutPatient']; + isInOutPatientDescription = json['IsInOutPatientDescription']; + isInOutPatientDescriptionN = json['IsInOutPatientDescriptionN']; + isInsurancePatient = json['IsInsurancePatient']; + nationalityFlagURL = json['NationalityFlagURL']; + noOfPatientsRate = json['NoOfPatientsRate']; + qR = json['QR']; + // speciality = json['Speciality'].cast(); + } + + Map toJson() { + final Map data = new Map(); + data['SetupID'] = this.setupID; + data['ProjectID'] = this.projectID; + data['PatientID'] = this.patientID; + data['AppointmentNo'] = this.appointmentNo; + data['AppointmentDate'] = this.appointmentDate; + data['DoctorName'] = this.doctorName; + data['ClinicDescription'] = this.clinicDescription; + data['Name'] = this.name; + data['EpisodeID'] = this.episodeID; + data['ActualDoctorRate'] = this.actualDoctorRate; + data['Admission'] = this.admission; + data['ClinicID'] = this.clinicID; + data['CompanyName'] = this.companyName; + data['Despensed_Status'] = this.despensedStatus; + data['DischargeDate'] = this.dischargeDate; + data['DischargeNo'] = this.dischargeNo; + data['DoctorID'] = this.doctorID; + data['DoctorImageURL'] = this.doctorImageURL; + data['DoctorRate'] = this.doctorRate; + data['DoctorTitle'] = this.doctorTitle; + data['Gender'] = this.gender; + data['GenderDescription'] = this.genderDescription; + data['IsActiveDoctorProfile'] = this.isActiveDoctorProfile; + data['IsDoctorAllowVedioCall'] = this.isDoctorAllowVedioCall; + data['IsExecludeDoctor'] = this.isExecludeDoctor; + data['IsInOutPatient'] = this.isInOutPatient; + data['IsInOutPatientDescription'] = this.isInOutPatientDescription; + data['IsInOutPatientDescriptionN'] = this.isInOutPatientDescriptionN; + data['IsInsurancePatient'] = this.isInsurancePatient; + data['NationalityFlagURL'] = this.nationalityFlagURL; + data['NoOfPatientsRate'] = this.noOfPatientsRate; + data['QR'] = this.qR; + data['Speciality'] = this.speciality; + return data; + } +} + +//class PrescriptionsList { +// String filterName = ""; +// List prescriptionsList = List(); +// +// PrescriptionsList({this.filterName, Prescriptions prescriptions}) { +// prescriptionsList.add(prescriptions); +// } +//} diff --git a/lib/core/model/pharmacies/order_model.dart b/lib/core/model/pharmacies/order_model.dart index 027d1f81..8872aaf8 100644 --- a/lib/core/model/pharmacies/order_model.dart +++ b/lib/core/model/pharmacies/order_model.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyImageObject.dart'; +import 'package:google_maps_flutter/google_maps_flutter.dart'; List orderModelFromJson(String str) => List.from(json.decode(str).map((x) => OrderModel.fromJson(x))); @@ -31,6 +32,7 @@ class OrderModel { this.taxRates, this.orderTax, this.orderDiscount, + this.productCount, this.orderTotal, this.refundedAmount, this.rewardPointsWereAdded, @@ -95,6 +97,7 @@ class OrderModel { String taxRates; double orderTax; dynamic orderDiscount; + dynamic productCount; double orderTotal; dynamic refundedAmount; dynamic rewardPointsWereAdded; @@ -159,6 +162,7 @@ class OrderModel { taxRates: json["tax_rates"], orderTax: json["order_tax"].toDouble(), orderDiscount: json["order_discount"], + productCount: json["product_count"], orderTotal: json["order_total"].toDouble(), refundedAmount: json["refunded_amount"], rewardPointsWereAdded: json["reward_points_were_added"], @@ -306,7 +310,22 @@ class IngAddress { String customerAttributes; DateTime createdOnUtc; dynamic province; - LatLong latLong; + String latLong; + + LatLng getLocation(){ + if(latLong.contains(',')){ + var parts = latLong.trim().split(','); + if(parts.length == 2){ + var lat = double.tryParse(parts.first); + var lng = double.tryParse(parts.last); + if(lat != null || lng != null) { + var location = LatLng(lat, lng); + return location; + } + } + } + return null; + } factory IngAddress.fromJson(Map json) => IngAddress( id: json["id"], @@ -326,7 +345,7 @@ class IngAddress { customerAttributes: json["customer_attributes"], createdOnUtc: DateTime.parse(json["created_on_utc"]), province: json["province"], - latLong: latLongValues.map[json["lat_long"]], + latLong: json["lat_long"], ); Map toJson() => { @@ -347,7 +366,7 @@ class IngAddress { "customer_attributes": customerAttributes, "created_on_utc": createdOnUtc.toIso8601String(), "province": province, - "lat_long": latLongValues.reverse[latLong], + "lat_long": latLong, }; } @@ -491,9 +510,9 @@ class OrderModelCustomer { isSystemAccount: json["is_system_account"], systemName: json["system_name"], lastIpAddress: lastIpAddressValues.map[json["last_ip_address"]], - createdOnUtc: DateTime.parse(json["created_on_utc"]), - lastLoginDateUtc: DateTime.parse(json["last_login_date_utc"]), - lastActivityDateUtc: DateTime.parse(json["last_activity_date_utc"]), + createdOnUtc: (json["created_on_utc"] != null) ? DateTime.parse(json["created_on_utc"]) : null, + lastLoginDateUtc: (json["created_on_utc"] != null) ? DateTime.parse(json["last_login_date_utc"]) : null, + lastActivityDateUtc: (json["created_on_utc"] != null) ? DateTime.parse(json["last_activity_date_utc"]) : null, registeredInStoreId: json["registered_in_store_id"], roleIds: List.from(json["role_ids"].map((x) => x)), ); diff --git a/lib/core/model/pharmacies/orders_model.dart b/lib/core/model/pharmacies/orders_model.dart new file mode 100644 index 00000000..a97bda98 --- /dev/null +++ b/lib/core/model/pharmacies/orders_model.dart @@ -0,0 +1,77 @@ +class OrdersModel { + List orders; + + OrdersModel({this.orders}); + + OrdersModel.fromJson(Map json) { + if (json['orders'] != null) { + orders = new List(); + json['orders'].forEach((v) { + orders.add(new Orders.fromJson(v)); + }); + } + } + + Map toJson() { + final Map data = new Map(); + if (this.orders != null) { + data['orders'] = this.orders.map((v) => v.toJson()).toList(); + } + return data; + } +} + +class Orders { + String id; + int productCount; + double orderTotal; + String createdOnUtc; + int orderStatusId; + String orderStatus; + String orderStatusn; + bool canCancel; + bool canRefund; + dynamic customerId; + + Orders( + {this.id, + this.productCount, + this.orderTotal, + this.createdOnUtc, + this.orderStatusId, + this.orderStatus, + this.orderStatusn, + this.canCancel, + this.canRefund, + this.customerId,}); + + Orders.fromJson(Map json) { + try { + id = json['id']; + productCount = json['product_count']; + orderTotal = json['order_total']; + createdOnUtc = json['created_on_utc']; + orderStatusId = json['order_status_id']; + orderStatus = json['order_status']; + orderStatusn = json['order_statusn']; + canCancel = json['can_cancel']; + canRefund = json['can_refund']; + customerId = json['customer_id']; + }catch(e){ + print(e); + } + + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['product_count'] = this.productCount; + data['order_total'] = this.orderTotal; + data['created_on_utc'] = this.createdOnUtc; + data['order_status_id'] = this.orderStatusId; + data['order_status'] = this.orderStatus; + data['order_statusn'] = this.orderStatusn; + return data; + } +} diff --git a/lib/core/service/childvaccines/vaccination_table_service.dart b/lib/core/service/childvaccines/vaccination_table_service.dart index 7f987b76..fc2b40e9 100644 --- a/lib/core/service/childvaccines/vaccination_table_service.dart +++ b/lib/core/service/childvaccines/vaccination_table_service.dart @@ -1,7 +1,9 @@ import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/core/model/childvaccines/List_BabyInformationModel.dart'; import 'package:diplomaticquarterapp/core/model/childvaccines/add_newchild_model.dart'; import 'package:diplomaticquarterapp/core/model/childvaccines/create_vaccination_table.dart'; import 'package:diplomaticquarterapp/core/model/childvaccines/user_information_model.dart'; +import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; import '../base_service.dart'; class VaccinationTableService extends BaseService { @@ -10,19 +12,18 @@ class VaccinationTableService extends BaseService { - Future getCreateVaccinationTableOrders() async { + Future getCreateVaccinationTableOrders(List_BabyInformationModel babyInfo, bool sendEmail) async { + String babyBDFormatted = "${DateUtil.convertDateToString(babyInfo.dOB)}/"; + hasError = false; await getUser(); - body['BabyName']="fffffffffff eeeeeeeeeeeeee"; - body['DOB'] = "/Date(1585774800000+0300)/"; + body['BabyName']= babyInfo.babyName; + body['DOB'] = babyBDFormatted; body['EmailAddress'] = user.emailAddress; body['isDentalAllowedBackend'] = false; - body['SendEmail'] = false; + body['SendEmail'] = sendEmail; body['IsLogin'] =true; - - - await baseAppClient.post(GET_TABLE_REQUEST, onSuccess: (dynamic response, int statusCode) { createVaccinationTableModelList.clear(); diff --git a/lib/core/service/medical/BloodSugarService.dart b/lib/core/service/medical/BloodSugarService.dart index 09fe9fe9..e0c5007c 100644 --- a/lib/core/service/medical/BloodSugarService.dart +++ b/lib/core/service/medical/BloodSugarService.dart @@ -69,25 +69,34 @@ class BloodSugarService extends BaseService { }, body: Map()); } - addDiabtecResult( - {String bloodSugerDateChart, - String bloodSugerResult, - String diabtecUnit, - int measuredTime}) async { + addDiabtecResult({String bloodSugerDateChart, String bloodSugerResult, String diabtecUnit, int measuredTime}) async { hasError = false; super.error = ""; - Map body = Map(); body['BloodSugerDateChart'] = bloodSugerDateChart; body['BloodSugerResult'] = bloodSugerResult; body['DiabtecUnit'] = diabtecUnit; - body['MeasuredTime'] =2;// measuredTime; + body['MeasuredTime'] = measuredTime; body['isDentalAllowedBackend'] = false; - await baseAppClient.post(ADD_BLOOD_PRESSURE_RESULT, - onSuccess: (response, statusCode) async { - var asd =""; - }, + onSuccess: (response, statusCode) async {}, + onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }, body: body); + } + updateDiabtecResult({DateTime month,DateTime hour,String bloodSugerResult,String diabtecUnit, int measuredTime,int lineItemNo}) async { + hasError = false; + super.error = ""; + Map body = Map(); + body['BloodSugerResult'] = bloodSugerResult; + body['DiabtecUnit'] = diabtecUnit; + body['BloodSugerDateChart'] = '${month.year}-${month.month}-${month.day} ${hour.hour}:${hour.minute}:00'; + body['isDentalAllowedBackend'] = false; + body['MeasuredTime'] = measuredTime; + body['LineItemNo'] = lineItemNo; + await baseAppClient.post(UPDATE_DIABETIC_RESULT, + onSuccess: (response, statusCode) async {}, onFailure: (String error, int statusCode) { hasError = true; super.error = error; diff --git a/lib/core/service/medical/my_balance_service.dart b/lib/core/service/medical/my_balance_service.dart index 86e925b8..e2744250 100644 --- a/lib/core/service/medical/my_balance_service.dart +++ b/lib/core/service/medical/my_balance_service.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; +import 'package:diplomaticquarterapp/core/model/blooddonation/blood_groub_details.dart'; import 'package:diplomaticquarterapp/core/model/my_balance/AdvanceModel.dart'; import 'package:diplomaticquarterapp/core/model/my_balance/patient_advance_balance_amount.dart'; import 'package:diplomaticquarterapp/core/model/my_balance/patient_info.dart'; @@ -23,11 +24,11 @@ class MyBalanceService extends BaseService { PatientInfoAndMobileNumber patientInfoAndMobileNumber; String logInTokenID; String verificationCode; - + String updatedRegisterBloodMessage = ""; AuthenticatedUserObject authenticatedUserObject = locator(); - MyBalanceService(){ + MyBalanceService() { getFamilyFiles(); } @@ -156,4 +157,49 @@ class MyBalanceService extends BaseService { return await getSharedRecordByStatus(); } } + + Future updateBloodGroup(List_BloodGroupDetailsModel detailsModel) async { + hasError = false; + await getUser(); + var languageID = + await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar'); + Map body = Map(); + body['City'] = detailsModel.city; + body['cityCode'] = detailsModel.cityCode; + body['Gender'] = detailsModel.gender; + body['BloodGroup'] = detailsModel.bloodGroup; + body['CellNumber'] = user.mobileNumber; + body['LanguageID'] = languageID; + body['NationalID'] = user.nationalityID; + body['ZipCode'] = user.zipCode ?? "+966"; + body['isDentalAllowedBackend'] = false; + + await baseAppClient.post(BLOOD_DONATION_REGISTER_BLOOD_TYPE, + onSuccess: (dynamic response, int statusCode) { + updatedRegisterBloodMessage = response['ErrorEndUserMessage']; + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + if(error == null){ + super.error = "Something went wrong"; + } + }, body: body); + } + + Future addUserAgreementForBloodDonation() async { + hasError = false; + var languageID = + await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar'); + Map body = Map(); + body['IsAgreed'] = true; + body['LanguageID'] = languageID; + body['isDentalAllowedBackend'] = false; + + await baseAppClient.post(ADD_USER_AGREEMENT_FOR_BLOOD_DONATION, + onSuccess: (dynamic response, int statusCode) { + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }, body: body); + } } diff --git a/lib/core/service/parmacyModule/parmacy_module_service.dart b/lib/core/service/parmacyModule/parmacy_module_service.dart index c3bce324..7f0a1050 100644 --- a/lib/core/service/parmacyModule/parmacy_module_service.dart +++ b/lib/core/service/parmacyModule/parmacy_module_service.dart @@ -6,17 +6,21 @@ import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart' import 'package:diplomaticquarterapp/core/service/base_service.dart'; import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; + class PharmacyModuleService extends BaseService { final AppSharedPreferences sharedPref = AppSharedPreferences(); bool isFinished = true; bool hasError = false; String errorMsg = ''; + String url =""; List bannerItems = List(); List manufacturerList = List(); List bestSellerProducts = List(); List lastVisitedProducts = List(); + + Future makeVerifyCustomer(dynamic data) async { Map queryParams = {'FileNumber': data['PatientID'].toString()}; hasError = false; @@ -148,4 +152,5 @@ class PharmacyModuleService extends BaseService { } } } + } diff --git a/lib/core/service/parmacyModule/prescription_service.dart b/lib/core/service/parmacyModule/prescription_service.dart new file mode 100644 index 00000000..7aafc9d3 --- /dev/null +++ b/lib/core/service/parmacyModule/prescription_service.dart @@ -0,0 +1,53 @@ + +import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; +import 'package:diplomaticquarterapp/core/service/base_service.dart'; +import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/Prescriptions.dart'; + + +class PrescriptionService extends BaseService { + final AppSharedPreferences sharedPref = AppSharedPreferences(); + bool isFinished = true; + bool hasError = false; + String errorMsg = ''; + String url = ""; + + List _prescriptionsList = List(); + List get prescriptionsList => _prescriptionsList; + + + Future getPrescription() async { + hasError = false; + url = PRESCRIPTION; + print("Print PRESCRIPTION url" + url); + await baseAppClient.get(url, + onSuccess: (dynamic response, int statusCode) { + _prescriptionsList.clear(); + response['PatientPrescriptionList'].forEach((item) { + _prescriptionsList.add(Prescriptions.fromJson(item)); + }); + print(_prescriptionsList.length); + print(response); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }); + } +// Future getPrescription() async { +// hasError = false; +// Map body = Map(); +// body['isDentalAllowedBackend'] = false; +// await baseAppClient.post(PRESCRIPTION, +// onSuccess: (dynamic response, int statusCode) { +// prescriptionsList.clear(); +// response['PatientPrescriptionList'].forEach((prescriptions) { +// prescriptionsList.add(Prescriptions.fromJson(prescriptions)); +// }); +// }, onFailure: (String error, int statusCode) { +// hasError = true; +// super.error = error; +// }, body: body); +// } + +} \ No newline at end of file diff --git a/lib/core/service/termsConditionsService.dart b/lib/core/service/termsConditionsService.dart new file mode 100644 index 00000000..1f806e22 --- /dev/null +++ b/lib/core/service/termsConditionsService.dart @@ -0,0 +1,18 @@ +import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/core/service/base_service.dart'; + +class TermsConditionsService extends BaseService { + + String userAgreementContent = ""; + + Future getUserTermsAndConditions() async { + hasError = false; + await baseAppClient.post(GET_USER_TERMS, + onSuccess: (dynamic response, int statusCode) { + userAgreementContent = response['UserAgreementContent']; + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }, body: Map()); + } +} \ No newline at end of file diff --git a/lib/core/viewModels/TermsConditionsViewModel.dart b/lib/core/viewModels/TermsConditionsViewModel.dart new file mode 100644 index 00000000..0cd667cf --- /dev/null +++ b/lib/core/viewModels/TermsConditionsViewModel.dart @@ -0,0 +1,29 @@ +import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; +import 'package:diplomaticquarterapp/core/service/termsConditionsService.dart'; +import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart'; + +import '../../locator.dart'; + +class TermsConditionsViewModel extends BaseViewModel{ + + TermsConditionsService _service = locator(); + + String get userAgreementContent => _service.userAgreementContent; + + getUserTermsAndConditions() async { + setState(ViewState.Busy); + await _service.getUserTermsAndConditions(); + if (_service.hasError) { + error = _service.error; + setState(ViewState.Error); + } else { + setState(ViewState.Idle); + } + } + + @override + void dispose() { + super.dispose(); + } + +} \ No newline at end of file diff --git a/lib/core/viewModels/child_vaccines/vaccination_table_view_model.dart b/lib/core/viewModels/child_vaccines/vaccination_table_view_model.dart index 3b72dd50..d0ccb8a1 100644 --- a/lib/core/viewModels/child_vaccines/vaccination_table_view_model.dart +++ b/lib/core/viewModels/child_vaccines/vaccination_table_view_model.dart @@ -1,4 +1,5 @@ import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; +import 'package:diplomaticquarterapp/core/model/childvaccines/List_BabyInformationModel.dart'; import 'package:diplomaticquarterapp/core/model/childvaccines/add_newchild_model.dart'; import 'package:diplomaticquarterapp/core/model/childvaccines/create_vaccination_table.dart'; import 'package:diplomaticquarterapp/core/service/childvaccines/add_new_child_service.dart'; @@ -11,14 +12,12 @@ import '../base_view_model.dart'; class VaccinationTableViewModel extends BaseViewModel{ VaccinationTableService _creteVaccinationTableService = locator(); + List get creteVaccinationTableModelList=> _creteVaccinationTableService.createVaccinationTableModelList; - // String get creteVaccinationTableContent => _creteVaccinationTableService.userAgreementContent; - //String get userAgreementContent => _creteNewBabyService.v//_reportsService.userAgreementContent; - List get creteVaccinationTableModelList=> _creteVaccinationTableService.createVaccinationTableModelList;//.createNewBabyModelList; - getCreateVaccinationTable() async { + getCreateVaccinationTable(List_BabyInformationModel babyInfo, bool sendEmail) async { setState(ViewState.Busy); - await _creteVaccinationTableService.getCreateVaccinationTableOrders();//getCreateNewBabyOrders(); + await _creteVaccinationTableService.getCreateVaccinationTableOrders(babyInfo, sendEmail);//getCreateNewBabyOrders(); if ( _creteVaccinationTableService.hasError) { error = _creteVaccinationTableService.error; diff --git a/lib/core/viewModels/medical/blood_sugar_view_model.dart b/lib/core/viewModels/medical/blood_sugar_view_model.dart index fb00f80e..29cc3249 100644 --- a/lib/core/viewModels/medical/blood_sugar_view_model.dart +++ b/lib/core/viewModels/medical/blood_sugar_view_model.dart @@ -45,7 +45,6 @@ class BloodSugarViewMode extends BaseViewModel { x: index, y: bloodSugarService .monthDiabtectResultAverageList[index].weekAverageResult)); - var asd=""; } bloodSugarService.yearDiabtecResultAverageList.forEach((element) { @@ -94,11 +93,7 @@ class BloodSugarViewMode extends BaseViewModel { ]; } - addDiabtecResult( - {String bloodSugerDateChart, - String bloodSugerResult, - String diabtecUnit, - int measuredTime}) async { + Future addDiabtecResult({String bloodSugerDateChart, String bloodSugerResult, String diabtecUnit, int measuredTime}) async { setState(ViewState.BusyLocal); await bloodSugarService.addDiabtecResult( bloodSugerDateChart: bloodSugerDateChart, @@ -113,7 +108,25 @@ class BloodSugarViewMode extends BaseViewModel { setState(ViewState.Idle); } } - + + Future updateDiabtecResult({DateTime month,DateTime hour,String bloodSugerResult,String diabtecUnit, int measuredTime,int lineItemNo}) async { + setState(ViewState.BusyLocal); + await bloodSugarService.updateDiabtecResult( + bloodSugerResult: bloodSugerResult , + diabtecUnit: diabtecUnit, + hour: hour, + measuredTime: measuredTime, + lineItemNo: lineItemNo, + month: month); + if (bloodSugarService.hasError) { + error = bloodSugarService.error; + setState(ViewState.Error); + } else { + await getBloodSugar(); + setState(ViewState.Idle); + } + } + } diff --git a/lib/core/viewModels/medical/my_balance_view_model.dart b/lib/core/viewModels/medical/my_balance_view_model.dart index e38a8a73..e33bc86c 100644 --- a/lib/core/viewModels/medical/my_balance_view_model.dart +++ b/lib/core/viewModels/medical/my_balance_view_model.dart @@ -41,6 +41,9 @@ class MyBalanceViewModel extends BaseViewModel { double get totalAdvanceBalanceAmount => _myBalanceService.totalAdvanceBalanceAmount; + String get updatedRegisterBloodMessage => + _myBalanceService.updatedRegisterBloodMessage; + GetAllSharedRecordsByStatusResponse get getAllSharedRecordsByStatusResponse => _myBalanceService.getAllSharedRecordsByStatusResponse; @@ -74,7 +77,6 @@ class MyBalanceViewModel extends BaseViewModel { setState(ViewState.Idle); } - Future getCities() async { setState(ViewState.Busy); await _bloodDonationService.getAllCitiesOrders(); @@ -95,7 +97,6 @@ class MyBalanceViewModel extends BaseViewModel { setState(ViewState.Idle); } - Future getPatientInfoByPatientID({String id}) async { setState(ViewState.Busy); await _myBalanceService.getPatientInfoByPatientID(id: id); @@ -108,7 +109,8 @@ class MyBalanceViewModel extends BaseViewModel { } } - Future getPatientInfoByPatientIDAndMobileNumber(AdvanceModel advanceModel) async { + Future getPatientInfoByPatientIDAndMobileNumber( + AdvanceModel advanceModel) async { setState(ViewState.Busy); await _myBalanceService .getPatientInfoByPatientIDAndMobileNumber(advanceModel); @@ -160,4 +162,15 @@ class MyBalanceViewModel extends BaseViewModel { } } + Future updateBloodGroup(List_BloodGroupDetailsModel detailsModel) async { + setState(ViewState.Busy); + await _myBalanceService.updateBloodGroup(detailsModel); + if (_myBalanceService.hasError) { + error = _myBalanceService.error; + setState(ViewState.ErrorLocal); + } else { + await _myBalanceService.addUserAgreementForBloodDonation(); + setState(ViewState.Idle); + } + } } diff --git a/lib/core/viewModels/pharmacyModule/order_model_view_model.dart b/lib/core/viewModels/pharmacyModule/order_model_view_model.dart index b7ddb528..f434db54 100644 --- a/lib/core/viewModels/pharmacyModule/order_model_view_model.dart +++ b/lib/core/viewModels/pharmacyModule/order_model_view_model.dart @@ -10,6 +10,7 @@ import 'package:diplomaticquarterapp/services/pharmacy_services/cancelOrder_serv import 'package:diplomaticquarterapp/services/pharmacy_services/orderDetails_service.dart'; import 'package:diplomaticquarterapp/services/pharmacy_services/order_service.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/order_model.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/orders_model.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:flutter/material.dart'; import '../../../locator.dart'; @@ -17,15 +18,12 @@ import '../base_view_model.dart'; class OrderModelViewModel extends BaseViewModel { OrderService _orderService = locator(); - - List get order => _orderService.orderList; + List get orders => _orderService.orderList; OrderDetailsService _orderDetailsService = locator(); - - List get orderDetails => _orderDetailsService.orderDetails; + List get orderListModel => _orderDetailsService.orderList; CancelOrderService _cancelOrderService = locator(); - List get cancelOrder => _cancelOrderService.cancelOrderList; @@ -52,9 +50,9 @@ class OrderModelViewModel extends BaseViewModel { } } - Future getOrderDetails(orderId) async { + Future getOrderDetails(OrderId) async { setState(ViewState.Busy); - await _orderDetailsService.getOrderDetails(orderId); + await _orderDetailsService.getOrderDetails(OrderId); if (_orderDetailsService.hasError) { error = _orderDetailsService.error; setState(ViewState.Error); diff --git a/lib/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart b/lib/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart index 4dfc6a26..bee7f654 100644 --- a/lib/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart +++ b/lib/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart @@ -3,7 +3,11 @@ import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/Manufacturer.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyImageObject.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/Prescriptions.dart'; +//import 'package:diplomaticquarterapp/core/model/prescriptions/perscription_pharmacy.dart'; +//import 'package:diplomaticquarterapp/core/service/medical/prescriptions_service.dart'; import 'package:diplomaticquarterapp/core/service/parmacyModule/parmacy_module_service.dart'; +import 'package:diplomaticquarterapp/core/service/parmacyModule/prescription_service.dart'; import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart'; import '../../../locator.dart'; @@ -11,6 +15,8 @@ import '../../../locator.dart'; class PharmacyModuleViewModel extends BaseViewModel { PharmacyModuleService _pharmacyService = locator(); + PrescriptionService _prescriptionService = locator(); + List get bannerList => _pharmacyService.bannerItems; List get manufacturerList => _pharmacyService.manufacturerList; @@ -21,6 +27,11 @@ class PharmacyModuleViewModel extends BaseViewModel { List get lastVisitedProducts => _pharmacyService.lastVisitedProducts; + List get prescriptionsList => + _prescriptionService.prescriptionsList; + +// List get pharmacyPrescriptionsList => PharmacyProduct.pharmacyPrescriptionsList ; + Future getPharmacyHomeData() async { setState(ViewState.Busy); var data = await sharedPref.getObject(USER_PROFILE); @@ -92,6 +103,17 @@ class PharmacyModuleViewModel extends BaseViewModel { } } + /////////////RecommendedProducts +// _getRecommendedProducts() async { +// await _pharmacyService.getRecommendedProducts(); +// if (_pharmacyService.hasError) { +// error = _pharmacyService.error; +// setState(ViewState.Error); +// } else { +// setState(ViewState.Idle); +// } +// } + Future checkUserIsActivated() async { if (authenticatedUserObject.isLogin) { var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID); @@ -105,4 +127,17 @@ class PharmacyModuleViewModel extends BaseViewModel { return false; } } + + getPrescription() async { + print("Print PRESCRIPTION url"); + setState(ViewState.Busy); + await _prescriptionService.getPrescription(); + if (_prescriptionService.hasError) { + error = _prescriptionService.error; + setState(ViewState.Error); + } else { + setState(ViewState.Idle); + } + } + } diff --git a/lib/locator.dart b/lib/locator.dart index c871b67e..a89ade41 100644 --- a/lib/locator.dart +++ b/lib/locator.dart @@ -1,4 +1,5 @@ import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/H2O_service.dart'; +import 'package:diplomaticquarterapp/core/service/parmacyModule/prescription_service.dart'; import 'package:diplomaticquarterapp/core/service/qr_service.dart'; import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/H2O_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/child_vaccines/user_information_view_model.dart'; @@ -63,12 +64,14 @@ import 'core/service/parmacyModule/order-preview-service.dart'; import 'core/service/notifications_service.dart'; import 'core/service/parmacyModule/terms-condition-service.dart'; import 'core/service/privilege_service.dart'; +import 'core/service/termsConditionsService.dart'; import 'core/service/weather_service.dart'; import 'core/viewModels/AlHabibMedicalService/cmc_view_model.dart'; import 'core/service/parmacyModule/parmacy_module_service.dart'; import 'core/service/offers_service.dart'; import 'core/service/pharmacy_categorise_service.dart'; +import 'core/viewModels/TermsConditionsViewModel.dart'; import 'core/viewModels/all_habib_medical_services/e_referral_view_model.dart'; import 'core/viewModels/appointment_rate_view_model.dart'; import 'core/viewModels/blooddonation/blood_details_view_model.dart'; @@ -209,8 +212,11 @@ void setupLocator() { // locator.registerLazySingleton(() => TermsConditionService()); locator.registerLazySingleton(() => TermsConditionService()); locator.registerLazySingleton(() => CancelOrderService()); + locator.registerLazySingleton(() => PrescriptionService()); + locator.registerLazySingleton(() => PrivilegeService()); locator.registerLazySingleton(() => WeatherService()); + locator.registerLazySingleton(() => TermsConditionsService()); /// View Model locator.registerFactory(() => HospitalViewModel()); @@ -291,4 +297,5 @@ void setupLocator() { // --------------------- locator.registerLazySingleton( () => GeofencingServices()); // Geofencing Services + locator.registerFactory(() => TermsConditionsViewModel()); } diff --git a/lib/pages/AlHabibMedicalService/all_habib_medical_service_page.dart b/lib/pages/AlHabibMedicalService/all_habib_medical_service_page.dart index e1720258..3c3c18c1 100644 --- a/lib/pages/AlHabibMedicalService/all_habib_medical_service_page.dart +++ b/lib/pages/AlHabibMedicalService/all_habib_medical_service_page.dart @@ -52,14 +52,16 @@ class _AllHabibMedicalServiceState extends State { AuthenticatedUser authUser = new AuthenticatedUser(); LocationUtils locationUtils; var weather = '--'; - + WeatherService _weatherService = WeatherService(); @override void initState() { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { - getAuthUser(); locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context); - locationUtils.getCurrentLocation(); + WidgetsBinding.instance.addPostFrameCallback((_) => { + Geolocator.getLastKnownPosition() + .then((value) => setLocation(value)) + }); }); super.initState(); } @@ -71,7 +73,6 @@ class _AllHabibMedicalServiceState extends State { isShowAppBar: true, appBarTitle: TranslationBase.of(context).alhabiServices, isShowDecPage: false, - isHelp: false, body: Column( children: [ Expanded( @@ -94,26 +95,23 @@ class _AllHabibMedicalServiceState extends State { padding: EdgeInsets.symmetric(horizontal: 10.0), child: Row( children: [ - Expanded( - flex: 3, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts( - TranslationBase.of(context) - .healthWeatherIndicators, - color: Colors.white, - fontWeight: FontWeight.w600, - ), - Texts( - TranslationBase.of(context) - .healthTipsBasedOnCurrentWeather, - color: Colors.white, - fontSize: 14, - ), - ], - )), + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts( + TranslationBase.of(context) + .healthWeatherIndicators, + color: Colors.white, + fontWeight: FontWeight.w600, + ), + Texts( + TranslationBase.of(context).healthTipsBasedOnCurrentWeather, + color: Colors.white, + fontSize: 14, + ), + ], + ), Expanded( flex: 2, child: InkWell( @@ -136,8 +134,11 @@ class _AllHabibMedicalServiceState extends State { width: 60, height: 60, ), - AppText(weather, - fontSize: 22, color: Colors.white) + Directionality( + textDirection: TextDirection.ltr, + child: AppText(weather, + fontSize: 22, + color: Colors.white)) ], ), Texts( @@ -202,7 +203,7 @@ class _AllHabibMedicalServiceState extends State { ), imageLocation: 'assets/images/al-habib_online_payment_service_icon.png', - title: 'Covid-19- Drive-Thru Test', + title: TranslationBase.of(context).covid19_driveThrueTest, ), ServicesContainer( onTap: () { @@ -226,7 +227,7 @@ class _AllHabibMedicalServiceState extends State { ), ), imageLocation: 'assets/images/pharmacy_logo.png', - title: 'Pharmacy'), + title: TranslationBase.of(context).pharmacy), ServicesContainer( onTap: () => Navigator.push( context, @@ -247,7 +248,7 @@ class _AllHabibMedicalServiceState extends State { : EReferralPage()), ), imageLocation: 'assets/images/ereferral_service_icon.png', - title: 'E-Referral', + title: TranslationBase.of(context).ereferral, ), ServicesContainer( onTap: () => Navigator.push( @@ -258,18 +259,18 @@ class _AllHabibMedicalServiceState extends State { ), imageLocation: 'assets/images/new-design/family_menu_icon_red.png', - title: 'My Family', + title: TranslationBase.of(context).myFamily, ), - if (projectViewModel.havePrivilege(35)) - ServicesContainer( - onTap: () => Navigator.push( - context, - FadePage(page: ChildVaccinesPage()), - ), - imageLocation: - 'assets/images/new-design/children_vaccines_icon.png', - title: 'Child Vaccines', + if(projectViewModel.havePrivilege(35)) + ServicesContainer( + onTap: () => Navigator.push( + context, + FadePage(page: ChildVaccinesPage()), ), + imageLocation: + 'assets/images/new-design/children_vaccines_icon.png', + title: TranslationBase.of(context).childVaccine, + ), ServicesContainer( onTap: () => Navigator.push( context, @@ -281,23 +282,23 @@ class _AllHabibMedicalServiceState extends State { 'assets/images/new-design/upcoming_icon_bottom_bar.png', title: TranslationBase.of(context).todoList, ), - if (projectViewModel.havePrivilege(42)) - ServicesContainer( - onTap: () => Navigator.push( - context, - FadePage(page: SymptomInfo()), - ), - imageLocation: 'assets/images/new-design/body_icon.png', - title: 'Symptom Checker'), - if (projectViewModel.havePrivilege(36)) - ServicesContainer( + if(projectViewModel.havePrivilege(42)) + ServicesContainer( onTap: () => Navigator.push( - context, - FadePage(page: BloodDonationPage()), - ), - imageLocation: 'assets/images/new-design/blood_icon.png', - title: 'Blood Donation', + context, + FadePage(page: SymptomInfo()), + ), + imageLocation: 'assets/images/new-design/body_icon.png', + title: TranslationBase.of(context).symptomCheckerTitle), + if(projectViewModel.havePrivilege(36)) + ServicesContainer( + onTap: () => Navigator.push( + context, + FadePage(page: BloodDonationPage()), ), + imageLocation: 'assets/images/new-design/blood_icon.png', + title: TranslationBase.of(context).bloodD, + ), ServicesContainer( onTap: () => Navigator.push( context, @@ -307,7 +308,7 @@ class _AllHabibMedicalServiceState extends State { ), imageLocation: 'assets/images/new-design/health_calculator_icon.png', - title: 'Health Calculators', + title: TranslationBase.of(context).calculators, ), ServicesContainer( onTap: () => Navigator.push( @@ -318,29 +319,28 @@ class _AllHabibMedicalServiceState extends State { ), imageLocation: 'assets/images/new-design/health_convertor_icon.png', - title: 'Health Converter', + title: TranslationBase.of(context).converters, ), - if (projectViewModel.havePrivilege(38)) - ServicesContainer( - onTap: () => Navigator.push( - context, - FadePage( - page: H2OPageIndexPage(), - ), + if(projectViewModel.havePrivilege(38)) + ServicesContainer( + onTap: () => Navigator.push( + context, + FadePage( + page: H2OPageIndexPage(), ), - imageLocation: 'assets/images/new-design/water_icon.png', - title: 'H2O', ), - if (projectViewModel.havePrivilege(41)) - ServicesContainer( - onTap: () => Navigator.push( - context, - FadePage(), - ), - imageLocation: - 'assets/images/new-design/smartwatch_icon.png', - title: TranslationBase.of(context).smartWatches, + imageLocation: 'assets/images/new-design/water_icon.png', + title: 'H2O', + ), + if(projectViewModel.havePrivilege(41)) + ServicesContainer( + onTap: () => Navigator.push( + context, + FadePage(), ), + imageLocation: 'assets/images/new-design/smartwatch_icon.png', + title: TranslationBase.of(context).smartWatches, + ), ServicesContainer( onTap: () => Navigator.push( context, @@ -370,7 +370,7 @@ class _AllHabibMedicalServiceState extends State { }, imageLocation: 'assets/images/new-design/twitter_dashboard_icon.png', - title: 'Latest News', + title: TranslationBase.of(context).latestNews, ), ServicesContainer( onTap: () => Navigator.push( @@ -399,7 +399,23 @@ class _AllHabibMedicalServiceState extends State { }); } var data = await this.sharedPref.getObject(WEATHER); - weather = data != null ? data['Temperature'].toString() + '\u2103' : '--'; - print(data); + if (data == null) { + var d = await _weatherService.getWeatherData(); + print(d); + setState(() { + weather = d != null ? d.temperature.toString() + '\u2103' : '--'; + }); + } else { + setState(() { + weather = + data != null ? data['Temperature'].toString() + '\u2103' : '--'; + }); + } + } + + void setLocation(Position position) { + this.sharedPref.setDouble(USER_LAT, position.latitude ?? 0.0); + this.sharedPref.setDouble(USER_LONG, position.longitude ?? 0.0); + getAuthUser(); } } diff --git a/lib/pages/Blood/blood_donation.dart b/lib/pages/Blood/blood_donation.dart index 1eaa02da..e0fa2aec 100644 --- a/lib/pages/Blood/blood_donation.dart +++ b/lib/pages/Blood/blood_donation.dart @@ -1,16 +1,15 @@ - import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; import 'package:diplomaticquarterapp/core/model/blooddonation/blood_groub_details.dart'; import 'package:diplomaticquarterapp/core/model/blooddonation/get_all_cities.dart'; + //import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart'; import 'package:diplomaticquarterapp/core/model/my_balance/AdvanceModel.dart'; import 'package:diplomaticquarterapp/core/model/my_balance/patient_info.dart'; import 'package:diplomaticquarterapp/core/service/blood/blood_details_servies.dart'; -import 'package:diplomaticquarterapp/core/service/blood/blood_donation_service.dart'; import 'package:diplomaticquarterapp/core/viewModels/blooddonation/blood_details_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/medical/my_balance_view_model.dart'; -import 'package:diplomaticquarterapp/locator.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart'; import 'package:diplomaticquarterapp/pages/Blood/user_agreement_page.dart'; @@ -20,18 +19,16 @@ import 'package:diplomaticquarterapp/pages/medical/balance/dialogs/SelectCiteisD import 'package:diplomaticquarterapp/pages/medical/balance/dialogs/SelectHospitalDialog.dart'; import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; -import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; -import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; -import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:giffy_dialog/giffy_dialog.dart'; +import 'package:provider/provider.dart'; import 'package:smart_progress_bar/smart_progress_bar.dart'; //import '../../../core/model/my_balance/AdvanceModel.dart'; @@ -44,8 +41,8 @@ import 'dialogs/SelectPatientInfoDialog.dart'; import 'new_text_Field.dart'; enum BeneficiaryType { MyAccount, MyFamilyFiles, OtherAccount, NON } -enum Gender{Male,Female,NON} -enum Blood{Oplus,Ominus,Aplus,Aminus,Bplus,Bminus,ABplus,ABminus,NON} +enum Gender { Male, Female, NON } +enum Blood { Oplus, Ominus, Aplus, Aminus, Bplus, Bminus, ABplus, ABminus, NON } class BloodDonationPage extends StatefulWidget { @override @@ -56,34 +53,38 @@ class _BloodDonationPageState extends State { TextEditingController _fileTextController = TextEditingController(); TextEditingController _notesTextController = TextEditingController(); BeneficiaryType beneficiaryType = BeneficiaryType.NON; - Gender gender = Gender.Male;//Gender.NON; - Blood blood = Blood.Aminus;//Blood.NON; + Gender gender = Gender.Male; //Gender.NON; + Blood blood = Blood.Aminus; //Blood.NON; //HospitalsModel _selectedHospital; - var _selectedHospital = new CitiesModel(); + CitiesModel _selectedHospital; + String amount = ""; String email; PatientInfo _selectedPatientInfo; AuthenticatedUser authenticatedUser; GetAllSharedRecordsByStatusList selectedPatientFamily; AdvanceModel advanceModel = AdvanceModel(); - List_BloodGroupDetailsModel bloodDetails=List_BloodGroupDetailsModel(); + List_BloodGroupDetailsModel bloodDetails = List_BloodGroupDetailsModel(bloodGroup: "A-"); AppSharedPreferences sharedPref = AppSharedPreferences(); - BloodDonationService _bloodDonationService = locator(); AuthenticatedUser authUser; - var checkedValue = false; + var checkedValue = false; + @override void initState() { super.initState(); getAuthUser(); - } + @override Widget build(BuildContext context) { + ProjectViewModel projectProvider = Provider.of(context); + return BaseView( - onModelReady: (model) => model.getCities(),//model.getHospitals(), + onModelReady: (model) => model.getCities(), //model.getHospitals(), builder: (_, model, w) => AppScaffold( isShowAppBar: true, - appBarTitle: TranslationBase.of(context).bloodDonation,//TranslationBase.of(context).advancePayment, + baseViewModel: model, + appBarTitle: TranslationBase.of(context).bloodD, body: SingleChildScrollView( physics: ScrollPhysics(), child: Container( @@ -91,15 +92,17 @@ class _BloodDonationPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - AppText( - TranslationBase.of(context).bloodInstruction, + Texts( + TranslationBase.of(context).bloodDEnterDesc, textAlign: TextAlign.center, ), SizedBox( height: 12, ), InkWell( - onTap: () => confirmSelectHospitalDialog(model.CitiesModelList),//model.hospitals + onTap: () => + confirmSelectHospitalDialog(model.CitiesModelList), + //model.hospitals child: Container( padding: EdgeInsets.all(12), width: double.infinity, @@ -110,7 +113,7 @@ class _BloodDonationPageState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Texts(getHospitalName()), + Texts(getHospitalName(projectProvider, context)), Icon(Icons.arrow_drop_down) ], ), @@ -121,7 +124,8 @@ class _BloodDonationPageState extends State { ), InkWell( //======Gender======== - onTap: () => confirmSelectGenderDialog(),//confirmSelectBeneficiaryDialog(model), + onTap: () => confirmSelectGenderDialog(), + //confirmSelectBeneficiaryDialog(model), child: Container( padding: EdgeInsets.all(12), width: double.infinity, @@ -133,19 +137,19 @@ class _BloodDonationPageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ //Texts(getBeneficiaryType()), - Texts(getGender()), + Texts(getGender(context)), Icon(Icons.arrow_drop_down) ], ), ), ), - SizedBox( height: 12, ), InkWell( //======Gender======== - onTap: () => confirmSelectBloodDialog(),//confirmSelectBeneficiaryDialog(model), + onTap: () => confirmSelectBloodDialog(), + //confirmSelectBeneficiaryDialog(model), child: Container( padding: EdgeInsets.all(12), width: double.infinity, @@ -163,24 +167,29 @@ class _BloodDonationPageState extends State { ), ), ), - SizedBox( height: 12, ), Row( children: [ - AppText(TranslationBase.of(context).bloodTermsNcondition), - - // SizedBox( - // width: MediaQuery.of(context).size.height * 0.10, - // ), + Container( + child: Text( + TranslationBase.of(context).viewTermsConditions), + ), + SizedBox( + width: MediaQuery.of(context).size.height * 0.10, + ), InkWell( onTap: () { Navigator.of(context).push(MaterialPageRoute( - builder: (BuildContext context) => UserAgreementPage())); + builder: (BuildContext context) => + UserAgreementPage())); }, child: Container( - child: Texts(" Click here ", color: Colors.blue,), + child: Texts( + TranslationBase.of(context).clickHere, + color: Colors.blue, + ), ), ) ], @@ -191,29 +200,34 @@ class _BloodDonationPageState extends State { Row( children: [ Checkbox( - onChanged: (bool value) { + onChanged: (bool value) { setState(() { checkedValue = value; }); }, - // tristate: checkedValue==true,//i == 1, + // tristate: checkedValue==true,//i == 1, value: checkedValue, - activeColor: Colors.red,//Color(0xFF6200EE), + activeColor: Color(0xFFc5272d), //Color(0xFF6200EE), + ), + SizedBox( + height: 10, + ), + Row( + children: [], ), - SizedBox(height: 10,), - Row(children: [ - - ],), SizedBox( width: 10, ), Text( - TranslationBase.of(context).iAgreeToTheTermsAndConditions, - style: Theme.of(context).textTheme.subtitle1.copyWith(color: checkedValue? Colors.red : Colors.black), + TranslationBase.of(context) + .iAgreeToTheTermsAndConditions, + style: Theme.of(context).textTheme.subtitle1.copyWith( + color: checkedValue + ? Color(0xFFc5272d) + : Colors.black), ), ], ), - SizedBox( height: 10, ), @@ -229,29 +243,25 @@ class _BloodDonationPageState extends State { onTap: () { showDialog( context: context, - builder: (_) => - AssetGiffyDialog( + builder: (_) => AssetGiffyDialog( title: Text( "", style: TextStyle( fontSize: 22.0, - fontWeight: - FontWeight - .w600), + fontWeight: FontWeight.w600), ), image: Image.asset( 'assets/images/BloodChrt_EN.png'), - buttonCancelText: - Text(TranslationBase.of(context).cancel), - buttonCancelColor: - Colors.grey, + buttonCancelText: Text( + TranslationBase.of(context).cancel), + buttonCancelColor: Colors.grey, onlyCancelButton: true, )); }, child: Container( width: 250, height: 200, - child:Image.asset( + child: Image.asset( 'assets/images/BloodChrt_EN.png')), ), ), @@ -267,36 +277,43 @@ class _BloodDonationPageState extends State { ), ), bottomSheet: Container( - height: MediaQuery.of(context).size.height * 0.10, + height: MediaQuery.of(context).size.height * 0.12, width: double.infinity, padding: EdgeInsets.all(12), child: SecondaryButton( textColor: Colors.white, - color: checkedValue== false ?Colors.white24:Color.fromRGBO(63, 72, 74, 1,), - label: TranslationBase.of(context).save, - // - onTap: (){ - Map request = Map(); - request["BloodGroup"] = getBlood();//'O-'; - request['CellNumber'] =authUser.mobileNumber;//m'537503378'; - request['City'] = _selectedHospital.description; //'Riyadh'; - request['CityCode'] =_selectedHospital.iD ; - request['Gender']= gender.index ==0 ? 1 : 2; - request['NationalID'] = authUser.nationalityID; - request['ZipCode'] = authUser.outSA ==1 ? '971' :'966'; - - - saveBloodDonation(request); - bloodDetails.city=_selectedHospital.toString(); - - // bloodDetails. + color: checkedValue == false + ? Color(0xFFa0a4a6) + : Color.fromRGBO( + 63, + 72, + 74, + 1, + ), + label: TranslationBase.of(context).save, + onTap: () async { + if(_selectedHospital == null){ + AppToast.showErrorToast(message: TranslationBase.of(context).selectCity); + return; + } + bloodDetails.city = projectProvider.isArabic + ? _selectedHospital.descriptionN + : _selectedHospital.description; + bloodDetails.cityCode = _selectedHospital.iD.toString(); + bloodDetails.gender = gender == Gender.Male ? 1 : 2; + await model.updateBloodGroup(bloodDetails); + if (model.state == ViewState.Idle) { + AppToast.showSuccessToast( + message: model.updatedRegisterBloodMessage); + } else { + AppToast.showErrorToast(message: model.error); + } }, - - ), )), ); } + //============== void confirmSelectBeneficiaryDialog(MyBalanceViewModel model) { showDialog( @@ -318,94 +335,85 @@ class _BloodDonationPageState extends State { ), ); } - void confirmSelectBloodDialog(){ + + void confirmSelectBloodDialog() { showDialog( context: context, - child: SelectBloodDialog(bloodType: blood, + child: SelectBloodDialog( + bloodType: blood, onValueSelected: (value) { setState(() { if (value == Blood.Oplus) { - bloodDetails.bloodGroup="O+"; + bloodDetails.bloodGroup = "O+"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.Ominus) { + } else if (value == Blood.Ominus) { // _fileTextController.text = model.user.patientID.toString(); - bloodDetails.bloodGroup="O-"; + bloodDetails.bloodGroup = "O-"; // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.ABplus) { - bloodDetails.bloodGroup="AB+"; + } else if (value == Blood.ABplus) { + bloodDetails.bloodGroup = "AB+"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.ABminus) { - bloodDetails.bloodGroup="AB-"; + } else if (value == Blood.ABminus) { + bloodDetails.bloodGroup = "AB-"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.Aplus) { - bloodDetails.bloodGroup="A+"; + } else if (value == Blood.Aplus) { + bloodDetails.bloodGroup = "A+"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.Aminus) { - bloodDetails.bloodGroup="A-"; + } else if (value == Blood.Aminus) { + bloodDetails.bloodGroup = "A-"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.Bplus) { - bloodDetails.bloodGroup="B+"; + } else if (value == Blood.Bplus) { + bloodDetails.bloodGroup = "B+"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - }else - if (value == Blood.Bminus) { - bloodDetails.bloodGroup="B-"; + } else if (value == Blood.Bminus) { + bloodDetails.bloodGroup = "B-"; // _fileTextController.text = model.user.patientID.toString(); // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; - } - - - else + } else _fileTextController.text = ""; // beneficiaryType = value; - blood=value; - } - - - - - ); + blood = value; + }); }, ), ); } - void confirmSelectGenderDialog(){ + + void confirmSelectGenderDialog() { showDialog( context: context, - child: SelectGenderDialog(beneficiaryType: gender, + child: SelectGenderDialog( + beneficiaryType: gender, onValueSelected: (value) { setState(() { if (value == Gender.Male) { // _fileTextController.text = model.user.patientID.toString(); - bloodDetails.patientType=1; + bloodDetails.patientType = 1; // advanceModel.depositorName = // model.user.firstName + " " + model.user.lastName; } else - // _fileTextController.text = ""; - {bloodDetails.gender=2;} + // _fileTextController.text = ""; + { + bloodDetails.gender = 2; + } - // beneficiaryType = value; - gender=value; + // beneficiaryType = value; + gender = value; }); }, ), @@ -474,23 +482,25 @@ class _BloodDonationPageState extends State { return TranslationBase.of(context).otherAccount; break; case BeneficiaryType.NON: - return "Select Gender";//TranslationBase.of(context).selectBeneficiary; + return TranslationBase.of(context).selectBeneficiary; } - return "Select Gender";//TranslationBase.of(context).selectBeneficiary; + return TranslationBase.of(context).selectBeneficiary; } - String getGender() { + + String getGender(BuildContext context) { switch (gender) { case Gender.Male: - return "Male"; + return TranslationBase.of(context).male; case Gender.Female: - return "Female"; + return TranslationBase.of(context).female; break; case Gender.NON: - return "Select Gender";//TranslationBase.of(context).selectBeneficiary; + return TranslationBase.of(context).selectGender; } - return "Select Gender";//TranslationBase.of(context).selectBeneficiary; + return TranslationBase.of(context).selectGender; } + String getBlood() { switch (blood) { case Blood.Oplus: @@ -522,22 +532,19 @@ class _BloodDonationPageState extends State { break; case Blood.NON: - return "Select Blood Type";//TranslationBase.of(context).selectBeneficiary; + return "Select Blood Type"; //TranslationBase.of(context).selectBeneficiary; } - return "Select Blood Type";//TranslationBase.of(context).selectBeneficiary; + return "Select Blood Type"; //TranslationBase.of(context).selectBeneficiary; } - String getHospitalName() { - if (_selectedHospital.description !=null) - return _selectedHospital.description; + String getHospitalName(ProjectViewModel projectProvider, BuildContext context) { + if (_selectedHospital != null) + return projectProvider.isArabic + ? _selectedHospital.descriptionN + : _selectedHospital.description; else - { - _selectedHospital.iD =1; - _selectedHospital.description='Riyadh'; - return _selectedHospital.description; - } - // "Riyadh"; - // return List_BloodGroupDetailsModel.fromJson(0).city.toString();//"Select City";//TranslationBase.of(context).selectHospital; + return TranslationBase.of(context).selectCity; + // return List_BloodGroupDetailsModel.fromJson(0).city.toString();//"Select City";//TranslationBase.of(context).selectHospital; } String getPatientName() { @@ -551,7 +558,6 @@ class _BloodDonationPageState extends State { if (await this.sharedPref.getObject(USER_PROFILE) != null) { var data = AuthenticatedUser.fromJson( await this.sharedPref.getObject(USER_PROFILE)); - getBloodDonationAgreement(); setState(() { authUser = data; }); @@ -565,30 +571,6 @@ class _BloodDonationPageState extends State { return TranslationBase.of(context).selectFamilyPatientName; } +//================ - //================ - saveBloodDonation(request){ - - GifLoaderDialogUtils.showMyDialog(context); - _bloodDonationService.bloodDonationSave(request).then((result)=> - { - GifLoaderDialogUtils.hideDialog(context), - AppToast.showSuccessToast(message: result['ErrorEndUserMessage']), - saveBloodDonationAgreement() - }); - } - - getBloodDonationAgreement(){ - _bloodDonationService.getAgreement().then((result)=> { - checkedValue = result['IsAgreed'] - }); - } - - saveBloodDonationAgreement(){ - Map request = Map(); - request['IsAgreed'] = checkedValue; - _bloodDonationService.saveAgreement(request).then((result)=> { - - }); - } } diff --git a/lib/pages/Blood/dialogs/SelectGenderDialog.dart b/lib/pages/Blood/dialogs/SelectGenderDialog.dart index 295c6dcd..a097ae8e 100644 --- a/lib/pages/Blood/dialogs/SelectGenderDialog.dart +++ b/lib/pages/Blood/dialogs/SelectGenderDialog.dart @@ -38,7 +38,7 @@ class _SelectGenderDialogState extends State { }); }, child: ListTile( - title: Text("Male"), + title: Text(TranslationBase.of(context).male), leading: Radio( value: Gender.Male, groupValue: beneficiaryType, @@ -68,7 +68,7 @@ class _SelectGenderDialogState extends State { }); }, child: ListTile( - title: Text("Female"), + title: Text(TranslationBase.of(context).female), leading: Radio( value: Gender.Female, groupValue: beneficiaryType, diff --git a/lib/pages/Blood/user_agreement_page.dart b/lib/pages/Blood/user_agreement_page.dart index d05725b4..36989ea5 100644 --- a/lib/pages/Blood/user_agreement_page.dart +++ b/lib/pages/Blood/user_agreement_page.dart @@ -1,55 +1,23 @@ +import 'package:diplomaticquarterapp/core/viewModels/TermsConditionsViewModel.dart'; +import 'package:diplomaticquarterapp/pages/base/base_view.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; +import 'package:flutter_html/flutter_html.dart'; class UserAgreementPage extends StatelessWidget { @override Widget build(BuildContext context) { - return AppScaffold( - isShowAppBar: true, - appBarTitle: "User Agreement", - - body: - Container( - child:ListView( - scrollDirection: Axis.vertical, - children: [ - /////////// - Column( - children: [ - SizedBox( - height: 20, - ), - Container( - child:Text("Communication via email, text messages and phone calls",textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)), - ), - SizedBox( - height: 20, - ), - Container( - child: - Text("I understand that the contact number or Email that \n I have provided on registration will be used for communication by HMG.\n I hereby agree to be notified by HMG through SMS, Email or any other method for appointments notifications, current HMG’s medical services, and any services introduced by the HMG in the future or any modifications made to the services offered by the HMG. And these messages may be submitted as evidence where the HMG has the right to use at any time whatsoever and as it sees fit.",textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)), - ), - SizedBox( - height: 20, - ), - Container( - child: - Text("I understand the risks of communicating by email and text messages, in particular the privacy risks. \nI understand that HMG cannot guarantee the security and confidentiality of email or text communication. HMG will not be responsible for messages that are not received or delivered due to technical failure, or for disclosure of confidential information unless caused by intentional misconduct.",textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)), - ), - SizedBox( - height: 20, - ), - Container( - child: - Text("\b I hereby agree to receive emails, text messages, phone calls for appointments notifications, special promotions and new features or products introduced by HMG or any third party.",textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)), - ), - ], - ) - /////////// - ]) - - - - )); + return BaseView( + onModelReady: (model) => model.getUserTermsAndConditions(), + builder: (_, model, w) => AppScaffold( + isShowAppBar: true, + appBarTitle: TranslationBase.of(context).userAgreement, + body: SingleChildScrollView( + child: Html( + data: model.userAgreementContent, + ), + )), + ); } } diff --git a/lib/pages/ChildVaccines/add_newchild_page.dart b/lib/pages/ChildVaccines/add_newchild_page.dart index 51b89f98..3c0d072b 100644 --- a/lib/pages/ChildVaccines/add_newchild_page.dart +++ b/lib/pages/ChildVaccines/add_newchild_page.dart @@ -11,6 +11,7 @@ import 'package:diplomaticquarterapp/pages/ChildVaccines/child_page.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/medical/active_medications/DayCheckBoxDialog.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; @@ -84,10 +85,12 @@ class _AddNewChildPageState extends State { @override Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return BaseView( builder: (_, model, w) => AppScaffold( isShowAppBar: true, - appBarTitle: "Vaccintion", + appBarTitle: TranslationBase.of(context).vaccination, body: SingleChildScrollView( physics: ScrollPhysics(), child: Container( @@ -96,10 +99,10 @@ class _AddNewChildPageState extends State { // crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( - height: 50, + height: 20, ), Texts( - "Add the child's information below to recieve the schedule of vaccinations.", + TranslationBase.of(context).vaccinationAddChildMsg, //+model.user.firstName, textAlign: TextAlign.center, ), @@ -107,14 +110,14 @@ class _AddNewChildPageState extends State { height: 12, ), NewTextFields( - hintText: "First Name", + hintText: TranslationBase.of(context).firstName, controller: _firstTextController, ), SizedBox( height: 12, ), NewTextFields( - hintText: "Second Name", + hintText: TranslationBase.of(context).middleName, controller: _secondTextController, ), SizedBox( @@ -124,62 +127,57 @@ class _AddNewChildPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Gender:", + TranslationBase.of(context).gender, textAlign: TextAlign.end, ), ], ), Container( - height: MediaQuery.of(context).size.height * 0.12, width: double.infinity, + height: size.height * 0.12, padding: EdgeInsets.all(12), - - child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ - Container( - height: MediaQuery.of(context).size.height * 0.12, - width: 175, - color: Colors.white, - child: SecondaryButton( - textColor: - checkedValue == 1 ? Colors.white : Colors.black, - color: checkedValue == 1 ? Colors.red : Colors.white, - - label: "Male", - // - onTap: () { + Expanded( + child: Container( + color: Colors.white, + child: SecondaryButton( + textColor: + checkedValue == 1 ? Colors.white : Colors.black, + color: checkedValue == 1 ? Colors.red : Colors.white, + label: TranslationBase.of(context).male, + onTap: () { + setState(() { + checkedValue = 1; + print("checkedValue=" + checkedValue.toString()); + }); - setState(() { - checkedValue = 1; - print("checkedValue=" + checkedValue.toString()); - }); - - // bloodDetails. - }, + // bloodDetails. + }, + ), ), ), - Container( - height: MediaQuery.of(context).size.height * 0.12, - width: 175, - color: Colors.white, - child: SecondaryButton( - textColor: - checkedValue == 2 ? Colors.white : Colors.black, - color: checkedValue == 2 ? Colors.red : Colors.white, - label: "Female", - // - onTap: () { - setState(() { - checkedValue = 2; - print("checkedValue=" + checkedValue.toString()); - }); - // bloodDetails.city=_selectedHospital.toString(); + Expanded( + child: Container( + color: Colors.white, + child: SecondaryButton( + textColor: + checkedValue == 2 ? Colors.white : Colors.black, + color: checkedValue == 2 ? Colors.red : Colors.white, + label: TranslationBase.of(context).female, + // + onTap: () { + setState(() { + checkedValue = 2; + print("checkedValue=" + checkedValue.toString()); + }); + // bloodDetails.city=_selectedHospital.toString(); - // bloodDetails. - }, + // bloodDetails. + }, + ), ), ) ], @@ -193,7 +191,7 @@ class _AddNewChildPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Date Of Birth::", + TranslationBase.of(context).dob, textAlign: TextAlign.end, ), ], @@ -249,29 +247,29 @@ class _AddNewChildPageState extends State { color: checkedValue == false ? Colors.white24 : Color.fromRGBO( - 63, - 72, - 74, - 1, - ), - label: "Add", + 63, + 72, + 74, + 1, + ), + label: TranslationBase.of(context).add, // - onTap: () async{ - newChild.babyName = _firstTextController.text + " " + _secondTextController.text; + onTap: () async { + newChild.babyName = _firstTextController.text + + " " + + _secondTextController.text; newChild.gender = checkedValue.toString(); newChild.strDOB = getStartDay(); newChild.tempValue = true; newChild.isLogin = true; await model.createNewBabyOrders(newChild: newChild); - if(model.isAdded){ - AppToast.showSuccessToast(message: "Record Added"); - Navigator.pop(context,model.isAdded); - }else{ - + if (model.isAdded) { + AppToast.showSuccessToast(message: TranslationBase.of(context).childAddedSuccessfully); + Navigator.pop(context, model.isAdded); + } else { //TODO handling error } - }, ), ), @@ -280,7 +278,7 @@ class _AddNewChildPageState extends State { ), ), ), - // bottomSheet: + // bottomSheet: ), ); } diff --git a/lib/pages/ChildVaccines/child_page.dart b/lib/pages/ChildVaccines/child_page.dart index 806a5b71..ae33cc03 100644 --- a/lib/pages/ChildVaccines/child_page.dart +++ b/lib/pages/ChildVaccines/child_page.dart @@ -5,6 +5,7 @@ import 'package:diplomaticquarterapp/pages/ChildVaccines/add_newchild_page.dart' import 'package:diplomaticquarterapp/pages/ChildVaccines/vaccinationtable_page.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; @@ -22,30 +23,51 @@ class ChildPage extends StatefulWidget { class _ChildPageState extends State with SingleTickerProviderStateMixin { - DeleteBaby deleteBaby = DeleteBaby(); @override Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + final double height = (size.height - kToolbarHeight - 60); + final double itemWidth = size.width / 2; + final double itemHeight = height / 2 + 40; + var checkedValue = true; return BaseView( onModelReady: (model) => model.getNewUserOrders(), builder: (_, model, widget) => AppScaffold( isShowAppBar: true, - appBarTitle: " Vaccination", + appBarTitle: TranslationBase.of(context).vaccination, baseViewModel: model, - body: SingleChildScrollView( - child: Container( - margin: EdgeInsets.only(left: 15, right: 15, top: 70), - child: Column( - children: [ - ...List.generate( + body: Container( + height: height * 0.85, + child: SingleChildScrollView( + child: Container( + margin: EdgeInsets.only(left: 8, right: 8, top: 16), + child: GridView.count( + crossAxisCount: 2, + childAspectRatio: (itemWidth / (itemHeight + 0)), + crossAxisSpacing: 10, + mainAxisSpacing: 10, + controller: ScrollController(keepScrollOffset: true), + shrinkWrap: true, + padding: const EdgeInsets.all(4.0), + children: [ + ...List.generate( model.babyInformationModelList.length, - (index) => Container( - margin: EdgeInsets.only( - left: 0, right: 0, bottom: 20), - - decoration: BoxDecoration( + (index) => InkWell( + onTap: () { + Navigator.push( + context, + FadePage( + page: VaccinationTablePage(model.babyInformationModelList[index]), + ), + ); + }, + child: Container( + margin: EdgeInsets.only( + left: 0, right: 0, bottom: 20), + decoration: BoxDecoration( shape: BoxShape.rectangle, border: Border.all( color: Colors.white, width: 0.5), @@ -54,11 +76,12 @@ class _ChildPageState extends State color: Colors.white, ), padding: EdgeInsets.all(12), - width: 200,//double.infinity, + //double.infinity, child: Column( children: [ Row(children: [ - Texts("CHILD NAME"), + Texts(TranslationBase.of(context) + .childName), ]), Row(children: [ Texts(model @@ -96,19 +119,14 @@ class _ChildPageState extends State Navigator.push( context, FadePage( - - - page: VaccinationTablePage(), - - + page: VaccinationTablePage(model.babyInformationModelList[index]), ), ); - }, ) ]), Row(children: [ - Texts("Birthday"), + Texts(TranslationBase.of(context).dob), ]), Row(children: [ IconButton( @@ -116,9 +134,7 @@ class _ChildPageState extends State 'assets/images/new-design/calender-secondary.png'), tooltip: '', onPressed: () { - setState(() { - - }); + setState(() {}); }, ), Texts(DateUtil.yearMonthDay(model @@ -130,73 +146,71 @@ class _ChildPageState extends State icon: new Image.asset( 'assets/images/new-design/garbage.png'), tooltip: '', - onPressed: ()async { - + onPressed: () async { //===================== - await model.deleteBabyOrders(newChild:deleteBaby ); - + await model.deleteBabyOrders( + newChild: deleteBaby); - deleteBaby.babyID=model.babyInformationModelList[index] + deleteBaby.babyID = model + .babyInformationModelList[index] .babyID; - await model.deleteBabyOrders(newChild:deleteBaby ); - if(model.isDeleted){ - AppToast.showSuccessToast(message: "Record Deleted"); - Navigator.pop(context,model.isDeleted); - }else{ - - //TODO handling error - } - - - - - + await model.deleteBabyOrders( + newChild: deleteBaby); + if (model.isDeleted) { + AppToast.showSuccessToast( + message: + TranslationBase.of(context) + .recordDeleted); + Navigator.pop( + context, model.isDeleted); + } else { + //TODO handling error + } }, ), - Texts("Delete"), + Texts(TranslationBase.of(context) + .deleteView), ]), SizedBox( height: 12, ), ], ), - + ), ), - - - ) - ], - )) + ) + ], + ))), ), - bottomSheet: Container( - height: MediaQuery.of(context).size.height * 0.12, - width: double.infinity, - padding: EdgeInsets.all(15), - child: SecondaryButton( - textColor: Colors.white, - color: checkedValue == false - ? Colors.white24 - : Color.fromRGBO( - 63, - 72, - 74, - 1, - ), - label: "ADD NEW CHILD ", - // - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AddNewChildPage(), - ), - ).then((value) { - if (value) model.getNewUserOrders(); - }); - }, - ), + bottomSheet: Container( + height: height * 0.15, + width: double.infinity, + padding: EdgeInsets.all(16), + child: SecondaryButton( + textColor: Colors.white, + color: checkedValue == false + ? Colors.white24 + : Color.fromRGBO( + 63, + 72, + 74, + 1, ), + label: TranslationBase.of(context).addNewChild, + // + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => AddNewChildPage(), + ), + ).then((value) { + if (value) model.getNewUserOrders(); + }); + }, + ), + ), )); } } diff --git a/lib/pages/ChildVaccines/child_vaccines_page.dart b/lib/pages/ChildVaccines/child_vaccines_page.dart index 92f3a0be..38c6b5af 100644 --- a/lib/pages/ChildVaccines/child_vaccines_page.dart +++ b/lib/pages/ChildVaccines/child_vaccines_page.dart @@ -1,10 +1,10 @@ - import 'package:diplomaticquarterapp/core/viewModels/child_vaccines/child_vaccines_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/child_vaccines/user_information_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/medical/my_balance_view_model.dart'; import 'package:diplomaticquarterapp/pages/ChildVaccines/child_page.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/input/text_field.dart'; @@ -13,214 +13,218 @@ import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; - - class ChildVaccinesPage extends StatefulWidget { @override _ChildVaccinesPageState createState() => _ChildVaccinesPageState(); } class _ChildVaccinesPageState extends State - with SingleTickerProviderStateMixin{ + with SingleTickerProviderStateMixin { TextEditingController titleController = TextEditingController(); - var checkedValue=false; - String addEmail=""; + var checkedValue = false; + String addEmail = ""; + @override Widget build(BuildContext context) { - return BaseView( onModelReady: (model) => model.getUserInformationRequestOrders(), builder: (_, model, w) => AppScaffold( - isShowAppBar: true, - baseViewModel: model, - appBarTitle: " Vaccination",//TranslationBase.of(context).advancePayment, - body: SingleChildScrollView( - physics: ScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - SizedBox( - height: 20, - ), - - Padding( - padding: const EdgeInsets.all(10.0), - child:Container( - child: Texts("Welcome back",fontSize: 20,), - ) , - ), - Divider(color:Colors.black , indent: 10, - endIndent: 10,), - SizedBox( - height: 20, - ), - Padding( - padding: const EdgeInsets.all(10.0), - child:Container( - child: Texts("Please ensure that the email address is up-to-date and process to view the schedule",fontSize: 20,), - ) , + isShowAppBar: true, + baseViewModel: model, + appBarTitle: TranslationBase.of(context).vaccination, + //TranslationBase.of(context).advancePayment, + body: SingleChildScrollView( + physics: ScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + SizedBox( + height: 20, + ), + Padding( + padding: const EdgeInsets.all(10.0), + child: Container( + child: Texts( + TranslationBase.of(context).welcomeBack, + fontSize: 20, ), - - Divider(color:Colors.black , indent: 10, - endIndent: 10,), - Padding( - padding: const EdgeInsets.all(10.0), - child:Container( - - margin: EdgeInsets.only(left: 10, right: 10, top: 15), - child: TextFields( - fillColor: Colors.red, - - hintText: model.user.emailAddress, - controller: titleController, - fontSize: 20, - hintColor: Colors.black, - fontWeight: FontWeight.w600, - onChanged: (text) { - addEmail=text; - model.user.emailAddress==addEmail?checkedValue=false:checkedValue=true; - - - }, - validator: (value) { - - if (value == null) - { - return model.user.emailAddress; - - } - else - - { - return model.user.emailAddress;} - }, - ), - ), + ), + ), + Divider( + color: Colors.black, + indent: 10, + endIndent: 10, + ), + SizedBox( + height: 20, + ), + Padding( + padding: const EdgeInsets.all(10.0), + child: Container( + child: Texts( + TranslationBase.of(context).msg_email_address_up_to_date, + fontSize: 20, ), - Container( - height: MediaQuery.of(context).size.height * 0.12, - width: double.infinity, - - padding: EdgeInsets.all(15), - child: SecondaryButton( - textColor: Colors.white, - color: checkedValue== false ?Colors.white24:Color.fromRGBO(63, 72, 74, 1,), - label: "UPDATE EMAIL", - // - onTap: (){ - model.user.emailAddress=addEmail.toString(); - AppToast.showSuccessToast( - message: "Email updated"); - // bloodDetails.city=_selectedHospital.toString(); - - // bloodDetails. - }, - + ), + ), - ), + Divider( + color: Colors.black, + indent: 10, + endIndent: 10, + ), + Padding( + padding: const EdgeInsets.all(10.0), + child: Container( + margin: EdgeInsets.only(left: 10, right: 10, top: 15), + child: TextFields( + fillColor: Colors.red, + hintText: model.user.emailAddress, + controller: titleController, + fontSize: 20, + hintColor: Colors.black, + fontWeight: FontWeight.w600, + onChanged: (text) { + addEmail = text; + model.user.emailAddress == addEmail + ? checkedValue = false + : checkedValue = true; + }, + validator: (value) { + if (value == null) { + return model.user.emailAddress; + } else { + return model.user.emailAddress; + } + }, ), - Container( - height: MediaQuery.of(context).size.height * 0.12, - width: double.infinity, - - padding: EdgeInsets.all(15), - child: SecondaryButton( - textColor: Colors.white, - color: Color.fromRGBO(63, 72, 74, 1,), - label: " VIEW LIST OF CHILDREN", - // - onTap: () => Navigator.push( - context, - FadePage( - page: ChildPage(), - - - - ), + ), + ), + Container( + height: MediaQuery.of(context).size.height * 0.12, + width: double.infinity, + padding: EdgeInsets.all(15), + child: SecondaryButton( + textColor: Colors.white, + color: checkedValue == false + ? Colors.white24 + : Color.fromRGBO( + 63, + 72, + 74, + 1, ), - - - ), - ), - - // Texts( - // // TranslationBase.of(context).advancePaymentLabel, - // model.user.emailAddress, - // textAlign: TextAlign.center, - // ), - SizedBox( - height: 12, - ), - SizedBox( - height: 12, - ), - SizedBox( - height: 12, + label: TranslationBase.of(context).updateEmail, + // + onTap: () { + model.user.emailAddress = addEmail.toString(); + AppToast.showSuccessToast( + message: TranslationBase.of(context).updateEmailMsg); + // bloodDetails.city=_selectedHospital.toString(); + + // bloodDetails. + }, + ), + ), + Container( + height: MediaQuery.of(context).size.height * 0.12, + width: double.infinity, + padding: EdgeInsets.all(15), + child: SecondaryButton( + textColor: Colors.white, + color: Color.fromRGBO( + 63, + 72, + 74, + 1, ), - - SizedBox( - height: 12, + label: TranslationBase.of(context).viewListChildren, + // + onTap: () => Navigator.push( + context, + FadePage( + page: ChildPage(), + ), ), + ), + ), - SizedBox( - height: 12, - ), + // Texts( + // // TranslationBase.of(context).advancePaymentLabel, + // model.user.emailAddress, + // textAlign: TextAlign.center, + // ), + SizedBox( + height: 12, + ), + SizedBox( + height: 12, + ), + SizedBox( + height: 12, + ), - SizedBox( - height: 10, - ), - // Row( - // mainAxisAlignment: MainAxisAlignment.center, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // Center( - // child: Container( - // color: Colors.white, - // width: 350, - // child: InkWell( - // onTap: () { - // showDialog( - // context: context, - // builder: (_) => - // AssetGiffyDialog( - // title: Text( - // "", - // style: TextStyle( - // fontSize: 22.0, - // fontWeight: - // FontWeight - // .w600), - // ), - // image: Image.asset( - // 'assets/images/BloodChrt_EN.png'), - // buttonCancelText: - // Text('cancel'), - // buttonCancelColor: - // Colors.grey, - // onlyCancelButton: true, - // )); - // }, - // child: Container( - // width: 250, - // height: 200, - // child:Image.asset( - // 'assets/images/BloodChrt_EN.png')), - // ), - // ), - // ), - // ], - // ), + SizedBox( + height: 12, + ), - SizedBox( - height: MediaQuery.of(context).size.height * 0.15, - ) - ], + SizedBox( + height: 12, ), + SizedBox( + height: 10, + ), + // Row( + // mainAxisAlignment: MainAxisAlignment.center, + // crossAxisAlignment: CrossAxisAlignment.center, + // children: [ + // Center( + // child: Container( + // color: Colors.white, + // width: 350, + // child: InkWell( + // onTap: () { + // showDialog( + // context: context, + // builder: (_) => + // AssetGiffyDialog( + // title: Text( + // "", + // style: TextStyle( + // fontSize: 22.0, + // fontWeight: + // FontWeight + // .w600), + // ), + // image: Image.asset( + // 'assets/images/BloodChrt_EN.png'), + // buttonCancelText: + // Text('cancel'), + // buttonCancelColor: + // Colors.grey, + // onlyCancelButton: true, + // )); + // }, + // child: Container( + // width: 250, + // height: 200, + // child:Image.asset( + // 'assets/images/BloodChrt_EN.png')), + // ), + // ), + // ), + // ], + // ), + + SizedBox( + height: MediaQuery.of(context).size.height * 0.15, + ) + ], ), - ), + ), + ), ); } } - diff --git a/lib/pages/ChildVaccines/dialogs/SelectGenderDialog.dart b/lib/pages/ChildVaccines/dialogs/SelectGenderDialog.dart index 259bbdb7..c08749b8 100644 --- a/lib/pages/ChildVaccines/dialogs/SelectGenderDialog.dart +++ b/lib/pages/ChildVaccines/dialogs/SelectGenderDialog.dart @@ -7,8 +7,11 @@ import 'package:flutter/material.dart'; class SelectGenderDialog extends StatefulWidget { final Email; + final Function okFunction; + + const SelectGenderDialog({Key key, this.Email, this.okFunction}) + : super(key: key); - const SelectGenderDialog({Key key, this.Email}) : super(key: key); @override _SelectGenderDialogState createState() => _SelectGenderDialogState(); } @@ -33,9 +36,8 @@ class _SelectGenderDialogState extends State { }); }, child: ListTile( - title: Text("Send the child's schedule to the email\n Tamer.dasdasdas@gmail.com "), - - + title: Text( + "${TranslationBase.of(context).sendChildEmailMsg}\n Tamer.dasdasdas@gmail.com "), ), ), ) @@ -44,7 +46,6 @@ class _SelectGenderDialogState extends State { SizedBox( height: 5.0, ), - SizedBox( height: 5.0, ), @@ -82,7 +83,7 @@ class _SelectGenderDialogState extends State { flex: 1, child: InkWell( onTap: () { - AppToast.showSuccessToast(message: "Email Sended"); + widget.okFunction(); // widget.onValueSelected(beneficiaryType); Navigator.pop(context); }, @@ -105,7 +106,4 @@ class _SelectGenderDialogState extends State { ], ); } - - - } diff --git a/lib/pages/ChildVaccines/vaccinationtable_page.dart b/lib/pages/ChildVaccines/vaccinationtable_page.dart index c160acfb..7b8499e0 100644 --- a/lib/pages/ChildVaccines/vaccinationtable_page.dart +++ b/lib/pages/ChildVaccines/vaccinationtable_page.dart @@ -1,8 +1,13 @@ +import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; +import 'package:diplomaticquarterapp/core/model/childvaccines/List_BabyInformationModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/child_vaccines/vaccination_table_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/medical/reports_monthly_view_model.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; +import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; +import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -12,91 +17,161 @@ import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'dialogs/SelectGenderDialog.dart'; class VaccinationTablePage extends StatelessWidget { + final List_BabyInformationModel babyInfo; + + VaccinationTablePage(this.babyInfo); + @override Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + final double height = (size.height - kToolbarHeight - 60); + var checkedValue; return BaseView( - onModelReady: (model) => model.getCreateVaccinationTable(),//getUserTermsAndConditions(), + onModelReady: (model) => model.getCreateVaccinationTable(babyInfo, false), builder: (_, model, w) => AppScaffold( isShowAppBar: true, baseViewModel: model, - appBarTitle: "Vaccination", - body: SingleChildScrollView( - child:Container( - margin: EdgeInsets.only(left: 15,right: 15,top: 70), - child: Column( - children: [//babyInformationModelList.length - ...List.generate(model.creteVaccinationTableModelList.length, (index) => - Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - border: Border.all(color: Colors.white, width: 0.5), - borderRadius: BorderRadius.all(Radius.circular(5)), - color: Colors.white, - - ), - padding: EdgeInsets.all(12), - width: double.infinity, - child: Column( - - children: [ - Row(children: [ - Text(model.creteVaccinationTableModelList[index].visit), - SizedBox(width: 10,), - - Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Html( - // data:"
BCG
HEPATITIS B
"//model.creteVaccinationTableModelList[index].vaccinesDescription - data:model.creteVaccinationTableModelList[index].vaccinesDescription, - - ), - ],), - ), - Text(model.creteVaccinationTableModelList[index].givenAt), - - - ],), - Divider(color:Colors.black ,), - - ], - ) - - - ) - - ) - ], + appBarTitle: TranslationBase.of(context).vaccination, + body: Container( + height: height * 0.85, + child: SingleChildScrollView( + child: Container( + margin: EdgeInsets.only(left: 16, right: 16, top: 16), + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Texts(TranslationBase.of(context).childName), + ), + Expanded( + child: Texts(TranslationBase.of(context).dob), + ), + ], + ), + SizedBox( + height: 10, + ), + Row( + children: [ + Expanded( + child: Texts(babyInfo.babyName), + ), + Expanded( + child: Texts(DateUtil.getFormattedDate( + babyInfo.dOB, "MMM dd,yyyy")), + ), + ], + ), + SizedBox( + height: 10, + ), + Divider( + color: Colors.black, + ), + Row( + children: [ + Text(TranslationBase.of(context).visit), + SizedBox( + width: 25, + ), + Expanded( + child: Text(TranslationBase.of(context).description)), + Text(TranslationBase.of(context).dueDate), + ], + ), + ...List.generate( + model.creteVaccinationTableModelList.length, + (index) => Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + // border: Border.all(color: Colors.white, width: 0.5), + borderRadius: BorderRadius.all(Radius.circular(5)), + // color: Colors.white, + ), + padding: EdgeInsets.all(12), + width: double.infinity, + child: Column( + children: [ + Row( + children: [ + Text(model + .creteVaccinationTableModelList[index] + .visit), + SizedBox( + width: 10, + ), + Expanded( + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Html( + // data:"
BCG
HEPATITIS B
"//model.creteVaccinationTableModelList[index].vaccinesDescription + data: model + .creteVaccinationTableModelList[ + index] + .vaccinesDescription, + ), + ], + ), + ), + Text(model + .creteVaccinationTableModelList[index] + .givenAt), + ], + ), + Divider( + color: Colors.black, + ), + ], + ))) + ], + ), ), - + ), ), - ), bottomSheet: Container( - height: MediaQuery.of(context).size.height * 0.12, + height: height * 0.15, width: double.infinity, - padding: EdgeInsets.all(12), child: SecondaryButton( - textColor: Colors.white, - color: checkedValue== false ?Colors.white24:Color.fromRGBO(63, 72, 74, 1,), - label: "Send Email ", - // - onTap: () { - //SelectGenderDialog(); + textColor: Colors.white, + color: checkedValue == false + ? Colors.white24 + : Color.fromRGBO( + 63, + 72, + 74, + 1, + ), + label: TranslationBase.of(context).sendEmail, + // + onTap: () { + //SelectGenderDialog(); //=============== - showDialog( - context: context, - child: SelectGenderDialog( - ), - ); - //========= - } - - - ), + showDialog( + context: context, + child: SelectGenderDialog( + okFunction: () async { + await model.getCreateVaccinationTable(babyInfo, true); + if (model.state == ViewState.Idle) { + AppToast.showSuccessToast( + message: TranslationBase.of(context) + .emailSentSuccessfully); + } else { + AppToast.showErrorToast( + message: TranslationBase.of(context) + .EmailSentError); + } + }, + ), + ); + //========= + }), ), ), ); diff --git a/lib/pages/ErService/AmbulanceReq.dart b/lib/pages/ErService/AmbulanceReq.dart index fe245133..1d4e78ee 100644 --- a/lib/pages/ErService/AmbulanceReq.dart +++ b/lib/pages/ErService/AmbulanceReq.dart @@ -107,7 +107,7 @@ class _AmbulanceReqState extends State Container( width: MediaQuery.of(context).size.width * 0.30, child: Center( - child: Texts("Orders Log"), + child: Texts(TranslationBase.of(context).ordersLog), ), ), ], diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/AmbulanceRequestIndex.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/AmbulanceRequestIndex.dart index c07adabc..1fb47cec 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/AmbulanceRequestIndex.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/AmbulanceRequestIndex.dart @@ -46,7 +46,7 @@ class _AmbulanceRequestIndexPageState extends State { @override Widget build(BuildContext context) { return AppScaffold( - body: false + body: widget.amRequestViewModel.pickUpRequestPresOrder != null ? Column( children: [ SizedBox( diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart index aeb61609..051f672e 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart @@ -5,6 +5,7 @@ import 'package:diplomaticquarterapp/pages/Blood/new_text_Field.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -45,306 +46,309 @@ class _BillAmountState extends State { @override Widget build(BuildContext context) { - return SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Container( - margin: EdgeInsets.only(left: 12, right: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts(TranslationBase.of(context).billAmount), - SizedBox( - height: 10, - ), - Table( - border: TableBorder.symmetric( - inside: BorderSide(width: 1.0, color: Colors.grey[300]), - outside: BorderSide(width: 1.0, color: Colors.grey[300])), - children: [ - TableRow( - children: [ - Container( - height: MediaQuery.of(context).size.height * 0.09, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), + return AppScaffold( + isShowDecPage: false, + isShowAppBar: false, + body: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: Container( + margin: EdgeInsets.only(left: 12, right: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts(TranslationBase.of(context).billAmount), + SizedBox( + height: 10, + ), + Table( + border: TableBorder.symmetric( + inside: BorderSide(width: 1.0, color: Colors.grey[300]), + outside: BorderSide(width: 1.0, color: Colors.grey[300])), + children: [ + TableRow( + children: [ + Container( + height: MediaQuery.of(context).size.height * 0.09, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(10.0), + ), ), - ), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).patientShareB, - textAlign: TextAlign.start, - color: Colors.black, - fontSize: 15, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).patientShareB, + textAlign: TextAlign.start, + color: Colors.black, + fontSize: 15, + ), ), ), - ), - Container( - height: MediaQuery.of(context).size.height * 0.09, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.only( - topRight: Radius.circular(10.0), + Container( + height: MediaQuery.of(context).size.height * 0.09, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + topRight: Radius.circular(10.0), + ), ), - ), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.price}', - color: Colors.black, - textAlign: TextAlign.start, - fontSize: 15, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.price}', + color: Colors.black, + textAlign: TextAlign.start, + fontSize: 15, + ), ), ), - ), - ], - ), - TableRow( - children: [ - Container( - color: Colors.white, - height: MediaQuery.of(context).size.height * 0.09, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).patientShareTax, - color: Colors.black, - fontSize: 15, - textAlign: TextAlign.start, - ), - ), - ), - Container( - height: MediaQuery.of(context).size.height * 0.09, - color: Colors.white, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.vAT}', - color: Colors.black, - fontSize: 15, - textAlign: TextAlign.start, + ], + ), + TableRow( + children: [ + Container( + color: Colors.white, + height: MediaQuery.of(context).size.height * 0.09, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).patientShareTax, + color: Colors.black, + fontSize: 15, + textAlign: TextAlign.start, + ), ), ), - ), - ], - ), - TableRow( - children: [ - Container( - height: MediaQuery.of(context).size.height * 0.09, - decoration: BoxDecoration( + Container( + height: MediaQuery.of(context).size.height * 0.09, color: Colors.white, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(10.0), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.vAT}', + color: Colors.black, + fontSize: 15, + textAlign: TextAlign.start, + ), ), ), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).patientShareTotal, - color: Colors.black, - fontSize: 15, - textAlign: TextAlign.start, - bold: true, + ], + ), + TableRow( + children: [ + Container( + height: MediaQuery.of(context).size.height * 0.09, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(10.0), + ), ), - ), - ), - Container( - height: MediaQuery.of(context).size.height * 0.09, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(10.0), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).patientShareTotal, + color: Colors.black, + fontSize: 15, + textAlign: TextAlign.start, + bold: true, + ), ), ), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Texts( - TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.totalPrice}', - color: Colors.black, - fontSize: 15, - textAlign: TextAlign.start, + Container( + height: MediaQuery.of(context).size.height * 0.09, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(10.0), + ), + ), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Texts( + TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.totalPrice}', + color: Colors.black, + fontSize: 15, + textAlign: TextAlign.start, + ), ), ), - ), - ], - ), - ], - ), - SizedBox( - height: 10, - ), - Texts(TranslationBase.of(context).selectAmbulate,bold: true,), - SizedBox(height: 5,), - Row( - children: [ - Expanded( - child: InkWell( - onTap: () { - setState(() { - _ambulate = Ambulate.Wheelchair; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).wheelchair), - leading: Radio( - value: Ambulate.Wheelchair, - groupValue: _ambulate, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _ambulate = value; - }); - }, + ], + ), + ], + ), + SizedBox( + height: 10, + ), + Texts(TranslationBase.of(context).selectAmbulate,bold: true,), + SizedBox(height: 5,), + Row( + children: [ + Expanded( + child: InkWell( + onTap: () { + setState(() { + _ambulate = Ambulate.Wheelchair; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Text(TranslationBase.of(context).wheelchair), + leading: Radio( + value: Ambulate.Wheelchair, + groupValue: _ambulate, + onChanged: (value) { + setState(() { + _ambulate = value; + }); + }, + ), ), ), ), ), - ), - Expanded( - child: InkWell( - onTap: () { - setState(() { - _ambulate = Ambulate.Walker; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).walker), - leading: Radio( - value: Ambulate.Walker, - groupValue: _ambulate, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _ambulate = value; - }); - }, + Expanded( + child: InkWell( + onTap: () { + setState(() { + _ambulate = Ambulate.Walker; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Text(TranslationBase.of(context).walker), + leading: Radio( + value: Ambulate.Walker, + groupValue: _ambulate, + + onChanged: (value) { + setState(() { + _ambulate = value; + }); + }, + ), ), ), ), ), - ), - ], - ), - SizedBox(height: 5,), - Row( - children: [ - Expanded( - child: InkWell( - onTap: () { - setState(() { - _ambulate = Ambulate.Stretcher; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).stretcher), - leading: Radio( - value: Ambulate.Stretcher, - groupValue: _ambulate, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _ambulate = value; - }); - }, + ], + ), + SizedBox(height: 5,), + Row( + children: [ + Expanded( + child: InkWell( + onTap: () { + setState(() { + _ambulate = Ambulate.Stretcher; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Text(TranslationBase.of(context).stretcher), + leading: Radio( + value: Ambulate.Stretcher, + groupValue: _ambulate, + + onChanged: (value) { + setState(() { + _ambulate = value; + }); + }, + ), ), ), ), ), - ), - Expanded( - child: InkWell( - onTap: () { - setState(() { - _ambulate = Ambulate.None; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).none), - leading: Radio( - value: Ambulate.None, - groupValue: _ambulate, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _ambulate = value; - }); - }, + Expanded( + child: InkWell( + onTap: () { + setState(() { + _ambulate = Ambulate.None; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Text(TranslationBase.of(context).none), + leading: Radio( + value: Ambulate.None, + groupValue: _ambulate, + + onChanged: (value) { + setState(() { + _ambulate = value; + }); + }, + ), ), ), ), ), - ), - ], - ), - SizedBox(height: 12,), - NewTextFields( - hintText: TranslationBase.of(context).notes, - initialValue: note, - onChanged: (value){ - setState(() { - note = value; - }); - }, - ), - - SizedBox( - height: 15, - ), - Container( - padding: EdgeInsets.all(15), - width: double.maxFinite, - height: 76, - child: SecondaryButton( - color: Colors.grey[800], - textColor: Colors.white, - onTap: () { + ], + ), + SizedBox(height: 12,), + NewTextFields( + hintText: TranslationBase.of(context).notes, + initialValue: note, + onChanged: (value){ setState(() { - widget.patientER.ambulate = _ambulate; - widget.patientER.requesterNote = note; - widget.patientER.selectedAmbulate = _ambulate.selectAmbulateNumber(); - widget.changeCurrentTab(3); + note = value; }); }, - label: TranslationBase.of(context).next, ), - ) - ], + + SizedBox( + height: 15, + ), + ], + ), + ), + ), + bottomSheet: Container( + padding: EdgeInsets.all(15), + width: double.maxFinite, + height: 90, + child: SecondaryButton( + color: Colors.grey[800], + textColor: Colors.white, + onTap: () { + setState(() { + widget.patientER.ambulate = _ambulate; + widget.patientER.requesterNote = note; + widget.patientER.selectedAmbulate = _ambulate.selectAmbulateNumber(); + widget.changeCurrentTab(3); + }); + }, + label: TranslationBase.of(context).next, ), ), ); diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/PickupLocation.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/PickupLocation.dart index f6ebfde9..1ea0f7f5 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/PickupLocation.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/PickupLocation.dart @@ -5,23 +5,20 @@ import 'package:diplomaticquarterapp/core/viewModels/er/am_request_view_model.da import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart'; import 'package:diplomaticquarterapp/pages/Blood/dialogs/SelectHospitalDialog.dart'; import 'package:diplomaticquarterapp/pages/ErService/widgets/AppointmentCard.dart'; -import 'package:diplomaticquarterapp/pages/landing/home_page.dart'; import 'package:diplomaticquarterapp/uitl/ProgressDialog.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; +import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/pickupLocation/PickupLocationFromMap.dart'; -import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:geolocator/geolocator.dart'; import 'package:google_maps_place_picker/google_maps_place_picker.dart'; -import 'package:google_maps_flutter/google_maps_flutter.dart'; - -import '../AmbulanceReq.dart'; import '../AvailableAppointmentsPage.dart'; enum HaveAppointment { YES, NO } @@ -68,370 +65,397 @@ class _PickupLocationState extends State { @override Widget build(BuildContext context) { - return SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Container( - margin: EdgeInsets.only(left: 12, right: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (widget.patientER.direction == 1) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts(TranslationBase.of(context).pickupLocation), - SizedBox( - height: 15, - ), - InkWell( - onTap: (){ - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PickupLocationFromMap( - latitude: _latitude, - longitude: _longitude, - onPick: (value) { + return AppScaffold( + isShowAppBar: false, + isShowDecPage: false, + body: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: Container( + margin: EdgeInsets.only(left: 12, right: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.patientER.direction == 1) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts(TranslationBase.of(context).pickupLocation), + SizedBox( + height: 15, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PickupLocationFromMap( + latitude: _latitude, + longitude: _longitude, + onPick: (value) { + setState(() { + _result = value; + }); + }, + ), + ), + ); + }, + child: Container( + padding: EdgeInsets.all(12), + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded(child: Texts(getSelectFromMapName(context))), + Icon( + FontAwesomeIcons.mapMarkerAlt, + size: 24, + color: Colors.black, + ) + ], + ), + ), + ), + SizedBox( + height: 12, + ), + Texts(TranslationBase.of(context).pickupSpot), + SizedBox( + height: 5, + ), + InkWell( + onTap: () { + setState(() { + _isInsideHome = !_isInsideHome; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Texts(TranslationBase.of(context).insideHome), + leading: Checkbox( + value: _isInsideHome, + onChanged: (value) { setState(() { - _result = value; + _isInsideHome = value; }); }, ), ), - ); - }, - child: Container( - padding: EdgeInsets.all(12), - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts(getSelectFromMapName(context)), - Icon( - FontAwesomeIcons.mapMarkerAlt, - size: 24, - color: Colors.black, - ) - ], ), ), - ), - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).pickupSpot), - SizedBox( - height: 5, - ), - InkWell( - onTap: () { - setState(() { - _isInsideHome = !_isInsideHome; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Texts(TranslationBase.of(context).insideHome), - leading: Checkbox( - activeColor: Colors.red[800], - value: _isInsideHome, - onChanged: (value) { - setState(() { - _isInsideHome = value; - }); - }, - ), - ), + SizedBox( + height: 12, + ), + Texts(TranslationBase.of(context).haveAppo), + SizedBox( + height: 5, ), - ), - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).haveAppo), - SizedBox( - height: 5, - ), - Row( - children: [ - Expanded( - child: InkWell( - onTap: () { - if (myAppointment == null) { - getAppointment(); + Row( + children: [ + Expanded( + child: InkWell( + onTap: () { + if (myAppointment == null) { + getAppointment(); + setState(() { + _haveAppointment = HaveAppointment.YES; + }); + } + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Texts(TranslationBase.of(context).yes), + leading: Radio( + value: HaveAppointment.YES, + groupValue: _haveAppointment, + onChanged: (value) { + if (myAppointment == null) { + getAppointment(); + setState(() { + _haveAppointment = value; + }); + } + }, + ), + ), + ), + ), + ), + Expanded( + child: InkWell( + onTap: () { setState(() { - _haveAppointment = HaveAppointment.YES; + _haveAppointment = HaveAppointment.NO; + myAppointment = null; }); - } - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Texts(TranslationBase.of(context).yes), - leading: Radio( - value: HaveAppointment.YES, - groupValue: _haveAppointment, - activeColor: Colors.red[800], - onChanged: (value) { - if (myAppointment == null) { - getAppointment(); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Texts(TranslationBase.of(context).no), + leading: Radio( + value: HaveAppointment.NO, + groupValue: _haveAppointment, + onChanged: (value) { setState(() { _haveAppointment = value; + myAppointment = null; }); - } - }, + }, + ), ), ), ), ), - ), - Expanded( - child: InkWell( - onTap: () { - setState(() { - _haveAppointment = HaveAppointment.NO; - myAppointment = null; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Texts(TranslationBase.of(context).no), - leading: Radio( - value: HaveAppointment.NO, - groupValue: _haveAppointment, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _haveAppointment = value; - myAppointment = null; - }); - }, - ), - ), - ), - ), - ), - ], - ), - if (myAppointment != null) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - height: 12, - ), - AppointmentCard( - appointment: myAppointment, - ) ], ), - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).dropoffLocation), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - confirmSelectHospitalDialog( - widget.amRequestViewModel.hospitals); - }, - child: Container( - padding: EdgeInsets.all(12), - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + if (myAppointment != null) + Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Texts(getHospitalName(TranslationBase.of(context).pickupLocation)), - Icon( - Icons.arrow_drop_down, - size: 24, - color: Colors.black, + SizedBox( + height: 12, + ), + AppointmentCard( + appointment: myAppointment, ) ], ), + SizedBox( + height: 12, ), - ), - ], - ), - if (widget.patientER.direction == 0) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts(TranslationBase.of(context).pickupLocation), - SizedBox( - height: 15, - ), - InkWell( - onTap: () { - confirmSelectHospitalDialog( - widget.amRequestViewModel.hospitals); - }, - child: Container( - padding: EdgeInsets.all(12), - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, + Texts(TranslationBase.of(context).dropoffLocation), + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + confirmSelectHospitalDialog( + widget.amRequestViewModel.hospitals); + }, + child: Container( + padding: EdgeInsets.all(12), + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(getHospitalName( + TranslationBase.of(context).pickupLocation)), + Icon( + Icons.arrow_drop_down, + size: 24, + color: Colors.black, + ) + ], + ), ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts(getHospitalName(TranslationBase.of(context).pickupLocation)), - Icon( - Icons.arrow_drop_down, - size: 24, - color: Colors.black, - ) - ], + ), + ], + ), + if (widget.patientER.direction == 0) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts(TranslationBase.of(context).pickupLocation), + SizedBox( + height: 15, + ), + InkWell( + onTap: () { + confirmSelectHospitalDialog( + widget.amRequestViewModel.hospitals); + }, + child: Container( + padding: EdgeInsets.all(12), + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(getHospitalName( + TranslationBase.of(context).pickupLocation)), + Icon( + Icons.arrow_drop_down, + size: 24, + color: Colors.black, + ) + ], + ), ), ), - ), - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).dropoffLocation), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PickupLocationFromMap( - latitude: _latitude, - longitude: _longitude, - onPick: (value) { - setState(() { - _result = value; - }); - }, + SizedBox( + height: 12, + ), + Texts(TranslationBase.of(context).dropoffLocation), + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PickupLocationFromMap( + latitude: _latitude, + longitude: _longitude, + onPick: (value) { + setState(() { + _result = value; + }); + }, + ), ), + ); + }, + child: Container( + padding: EdgeInsets.all(12), + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded(child: Texts(getSelectFromMapName(context))), + Icon( + FontAwesomeIcons.mapMarkerAlt, + size: 24, + color: Colors.black, + ) + ], ), - ); - }, - child: Container( - padding: EdgeInsets.all(12), - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts(getSelectFromMapName(context)), - Icon( - FontAwesomeIcons.mapMarkerAlt, - size: 24, - color: Colors.black, - ) - ], ), ), - ), - ], + ], + ), + SizedBox( + height: 45, ), - SizedBox( - height: 45, - ), - Container( - padding: EdgeInsets.all(15), - width: double.maxFinite, - height: 76, - child: SecondaryButton( - color: Colors.grey[800], - textColor: Colors.white, - onTap: () { - if (_result == null || _selectedHospital == null) - AppToast.showErrorToast( - message: TranslationBase.of(context).selectAll); - else - setState(() { - widget.patientER.pickupSpot = _isInsideHome ? 1 : 0; - if (widget.patientER.direction == 0) { - widget.patientER.pickupLocationLattitude = _result.geometry.location.lat.toString(); - widget.patientER.pickupLocationLongitude = _result.geometry.location.lng.toString(); - widget.patientER.dropoffLocationLattitude = _selectedHospital.latitude; - widget.patientER.dropoffLocationLongitude = _selectedHospital.longitude; - } else { - widget.patientER.pickupLocationLattitude = _selectedHospital.latitude; - widget.patientER.pickupLocationLongitude = _selectedHospital.longitude; - widget.patientER.dropoffLocationLattitude = _result.geometry.location.lat.toString(); - widget.patientER.dropoffLocationLongitude = _result.geometry.location.lng.toString(); - } + ], + ), + ), + ), + bottomSheet: Container( + padding: EdgeInsets.all(15), + width: double.maxFinite, + height: 90, + child: SecondaryButton( + color: Colors.grey[800], + textColor: Colors.white, + onTap: () { + if (_result == null || _selectedHospital == null) + AppToast.showErrorToast( + message: TranslationBase.of(context).selectAll); + else + setState(() { + widget.patientER.pickupSpot = _isInsideHome ? 1 : 0; + if (widget.patientER.direction == 0) { + widget.patientER.pickupLocationLattitude = + _result.geometry.location.lat.toString(); + widget.patientER.pickupLocationLongitude = + _result.geometry.location.lng.toString(); + widget.patientER.dropoffLocationLattitude = + _selectedHospital.latitude; + widget.patientER.dropoffLocationLongitude = + _selectedHospital.longitude; + } else { + widget.patientER.pickupLocationLattitude = + _selectedHospital.latitude; + widget.patientER.pickupLocationLongitude = + _selectedHospital.longitude; + widget.patientER.dropoffLocationLattitude = + _result.geometry.location.lat.toString(); + widget.patientER.dropoffLocationLongitude = + _result.geometry.location.lng.toString(); + } - widget.patientER.latitude = widget.patientER.pickupLocationLattitude; - widget.patientER.longitude = widget.patientER.pickupLocationLongitude; - widget.patientER.dropoffLocationName = _selectedHospital.name; - widget.patientER.createdBy = widget.amRequestViewModel.user.patientID; - widget.patientER.isOutPatient = widget.amRequestViewModel.user.outSA; - widget.patientER.patientIdentificationID = widget.amRequestViewModel.user.patientIdentificationNo; - widget.patientER.pickupDateTime = DateUtil.convertDateToStringLocation(DateTime.now()); - widget.patientER.pickupLocationName = _result.formattedAddress; - widget.patientER.projectID = widget.amRequestViewModel.user.projectID; - widget.patientER.requesterFileNo = widget.amRequestViewModel.user.patientID; - widget.patientER.requesterIsOutSA = false; - widget.patientER.lineItemNo =0; - widget.patientER.requesterMobileNo = widget.amRequestViewModel.user.mobileNumber; + widget.patientER.latitude = + widget.patientER.pickupLocationLattitude; + widget.patientER.longitude = + widget.patientER.pickupLocationLongitude; + widget.patientER.dropoffLocationName = + _selectedHospital.name; + widget.patientER.createdBy = + widget.amRequestViewModel.user.patientID; + widget.patientER.isOutPatient = + widget.amRequestViewModel.user.outSA; + widget.patientER.patientIdentificationID = widget + .amRequestViewModel.user.patientIdentificationNo; + widget.patientER.pickupDateTime = + DateUtil.convertDateToStringLocation(DateTime.now()); + widget.patientER.pickupLocationName = + _result.formattedAddress; + widget.patientER.projectID = + widget.amRequestViewModel.user.projectID; + widget.patientER.requesterFileNo = + widget.amRequestViewModel.user.patientID; + widget.patientER.requesterIsOutSA = false; + widget.patientER.lineItemNo = 0; + widget.patientER.requesterMobileNo = + widget.amRequestViewModel.user.mobileNumber; - if (_haveAppointment == HaveAppointment.YES) { - widget.patientER.appointmentNo = myAppointment.appointmentNo.toString(); - widget.patientER.appointmentClinicName = myAppointment.clinicName; - widget.patientER.appointmentDoctorName = myAppointment.doctorNameObj; - widget.patientER.appointmentBranch = myAppointment.projectName; - widget.patientER.appointmentTime = myAppointment.appointmentDate; - widget.patientER.haveAppointment = true; - } else { - widget.patientER.appointmentNo = "0"; - widget.patientER.appointmentClinicName = null; - widget.patientER.appointmentDoctorName = null; - widget.patientER.appointmentBranch = null; - widget.patientER.appointmentTime = null; - widget.patientER.haveAppointment = false; - } + if (_haveAppointment == HaveAppointment.YES) { + widget.patientER.appointmentNo = + myAppointment.appointmentNo.toString(); + widget.patientER.appointmentClinicName = + myAppointment.clinicName; + widget.patientER.appointmentDoctorName = + myAppointment.doctorNameObj; + widget.patientER.appointmentBranch = + myAppointment.projectName; + widget.patientER.appointmentTime = + myAppointment.appointmentDate; + widget.patientER.haveAppointment = true; + } else { + widget.patientER.appointmentNo = "0"; + widget.patientER.appointmentClinicName = null; + widget.patientER.appointmentDoctorName = null; + widget.patientER.appointmentBranch = null; + widget.patientER.appointmentTime = null; + widget.patientER.haveAppointment = false; + } - widget.patientER.pickupSpot = _isInsideHome ? 1 : 0; - widget.changeCurrentTab(2); - }); - }, - label: TranslationBase.of(context).next, - ), - ) - ], + widget.patientER.pickupSpot = _isInsideHome ? 1 : 0; + widget.changeCurrentTab(2); + }); + }, + label: TranslationBase.of(context).next, ), ), ); @@ -457,11 +481,13 @@ class _PickupLocationState extends State { } String getSelectFromMapName(context) { - return _result != null ? _result.formattedAddress : TranslationBase.of(context).selectMap; + return _result != null + ? _result.formattedAddress + : TranslationBase.of(context).selectMap; } getAppointment() { - ProgressDialogUtil.showProgressDialog(context); + GifLoaderDialogUtils.showMyDialog(context); widget.amRequestViewModel.getAppointmentHistory().then((value) { if (widget.amRequestViewModel.state == ViewState.Error || widget.amRequestViewModel.state == ViewState.ErrorLocal) { @@ -469,7 +495,7 @@ class _PickupLocationState extends State { } else if (widget .amRequestViewModel.appoitmentAllHistoryResultList.length > 0) { - ProgressDialogUtil.hideProgressDialog(context); + GifLoaderDialogUtils.hideDialog(context); Navigator.push( context, MaterialPageRoute( @@ -491,14 +517,15 @@ class _PickupLocationState extends State { } }); } else { - ProgressDialogUtil.hideProgressDialog(context); + GifLoaderDialogUtils.hideDialog(context); setState(() { _haveAppointment = HaveAppointment.NO; }); - AppToast.showErrorToast(message: TranslationBase.of(context).noAppointment); + AppToast.showErrorToast( + message: TranslationBase.of(context).noAppointment); } }).catchError((e) { - ProgressDialogUtil.hideProgressDialog(context); + GifLoaderDialogUtils.hideDialog(context); AppToast.showErrorToast(message: e); }); } diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/SelectTransportationMethod.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/SelectTransportationMethod.dart index 69669ed3..0770448e 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/SelectTransportationMethod.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/SelectTransportationMethod.dart @@ -1,15 +1,15 @@ import 'package:diplomaticquarterapp/core/enum/OrderService.dart'; -import 'package:diplomaticquarterapp/core/enum/OrderService.dart'; -import 'package:diplomaticquarterapp/core/enum/OrderService.dart'; -import 'package:diplomaticquarterapp/core/enum/OrderService.dart'; import 'package:diplomaticquarterapp/core/model/er/PatientER.dart'; import 'package:diplomaticquarterapp/core/model/er/get_all_transportation_method_list_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/er/am_request_view_model.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; enum Direction { ToHospital, FromHospital } enum Way { OneWay, TwoWays } @@ -58,251 +58,267 @@ class _SelectTransportationMethodState @override Widget build(BuildContext context) { - return SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Container( - margin: EdgeInsets.only(left: 12, right: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).transportHeading), - ...List.generate( - widget.amRequestViewModel.amRequestModeList.length, - (index) => InkWell( - onTap: () { - setState(() { - _erTransportationMethod = - widget.amRequestViewModel.amRequestModeList[index]; - }); - }, - child: Container( - margin: EdgeInsets.all(5), - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: Row( - children: [ - Expanded( - flex: 3, - child: ListTile( - title: Text(widget.amRequestViewModel - .amRequestModeList[index].title), - leading: Radio( - value: widget - .amRequestViewModel.amRequestModeList[index], - groupValue: _erTransportationMethod, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _erTransportationMethod = value; - }); - }, + ProjectViewModel projectViewModel = Provider.of(context); + return AppScaffold( + isShowAppBar: false, + isShowDecPage: false, + body: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: Container( + margin: EdgeInsets.only(left: 12, right: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: 12, + ), + Texts(TranslationBase.of(context).transportHeading), + ...List.generate( + widget.amRequestViewModel.amRequestModeList.length, + (index) => InkWell( + onTap: () { + setState(() { + _erTransportationMethod = + widget.amRequestViewModel.amRequestModeList[index]; + }); + }, + child: Container( + margin: EdgeInsets.all(5), + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: Row( + children: [ + Expanded( + flex: 3, + child: ListTile( + title: Texts(projectViewModel.isArabic + ? widget.amRequestViewModel + .amRequestModeList[index].titleAR + : widget.amRequestViewModel + .amRequestModeList[index].title), + leading: Radio( + value: widget + .amRequestViewModel.amRequestModeList[index], + groupValue: _erTransportationMethod, + onChanged: (value) { + setState(() { + _erTransportationMethod = value; + }); + }, + ), ), ), - ), - Expanded( - flex: 1, - child: Texts( - TranslationBase.of(context).sar+' ${widget.amRequestViewModel.amRequestModeList[index].price}'), - ) - ], + Expanded( + flex: 1, + child: Texts(TranslationBase.of(context).sar + + ' ${widget.amRequestViewModel.amRequestModeList[index].price}'), + ) + ], + ), ), ), ), - ), - SizedBox( - height: 12, - ), - Texts(TranslationBase.of(context).directionHeading), - SizedBox( - height: 5, - ), - Container( - width: double.maxFinite, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Expanded( - child: InkWell( - onTap: () { - setState(() { - _direction = Direction.ToHospital; - }); - }, - child: Container( - width: double.maxFinite, - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).toHospital), - leading: Radio( - value: Direction.ToHospital, - groupValue: _direction, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _direction = value; - }); - }, + SizedBox( + height: 12, + ), + Texts(TranslationBase.of(context).directionHeading), + SizedBox( + height: 5, + ), + Container( + width: double.maxFinite, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + child: InkWell( + onTap: () { + setState(() { + _direction = Direction.ToHospital; + }); + }, + child: Container( + width: double.maxFinite, + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: Texts(TranslationBase.of(context).toHospital), + leading: Radio( + value: Direction.ToHospital, + groupValue: _direction, + onChanged: (value) { + setState(() { + _direction = value; + }); + }, + ), ), ), ), ), - ), - Expanded( - child: InkWell( - onTap: () { - setState(() { - _direction = Direction.FromHospital; - }); - }, - child: Container( - width: double.maxFinite, - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).fromHospital), - leading: Radio( - value: Direction.FromHospital, - groupValue: _direction, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _direction = value; - }); - }, + Expanded( + child: InkWell( + onTap: () { + setState(() { + _direction = Direction.FromHospital; + }); + }, + child: Container( + width: double.maxFinite, + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: + Texts(TranslationBase.of(context).fromHospital), + leading: Radio( + value: Direction.FromHospital, + groupValue: _direction, + onChanged: (value) { + setState(() { + _direction = value; + }); + }, + ), ), ), ), ), - ), - ], + ], + ), ), - ), - if (_direction == Direction.ToHospital) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - height: 8, - ), - Texts(TranslationBase.of(context).directionHeading), - SizedBox( - height: 5, - ), - Row( - children: [ - Expanded( - child: InkWell( - onTap: () { - setState(() { - _way = Way.OneWay; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).oneDirec), - leading: Radio( - value: Way.OneWay, - groupValue: _way, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _way = value; - }); - }, + if (_direction == Direction.ToHospital) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: 8, + ), + Texts(TranslationBase.of(context).directionHeading), + SizedBox( + height: 5, + ), + Row( + children: [ + Expanded( + child: InkWell( + onTap: () { + setState(() { + _way = Way.OneWay; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: + Texts(TranslationBase.of(context).oneDirec), + leading: Radio( + value: Way.OneWay, + groupValue: _way, + onChanged: (value) { + setState(() { + _way = value; + }); + }, + ), ), ), ), ), - ), - Expanded( - child: InkWell( - onTap: () { - setState(() { - _way = Way.TwoWays; - }); - }, - child: Container( - decoration: BoxDecoration( - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(8), - border: - Border.all(color: Colors.grey, width: 0.5), - color: Colors.white, - ), - child: ListTile( - title: Text(TranslationBase.of(context).twoDirec), - leading: Radio( - value: Way.TwoWays, - groupValue: _way, - activeColor: Colors.red[800], - onChanged: (value) { - setState(() { - _way = value; - }); - }, + Expanded( + child: InkWell( + onTap: () { + setState(() { + _way = Way.TwoWays; + }); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.grey, width: 0.5), + color: Colors.white, + ), + child: ListTile( + title: + Texts(TranslationBase.of(context).twoDirec), + leading: Radio( + value: Way.TwoWays, + groupValue: _way, + onChanged: (value) { + setState(() { + _way = value; + }); + }, + ), ), ), ), ), - ), - ], - ), - ], - ), - SizedBox( - height: 15, - ), - Container( - padding: EdgeInsets.all(15), - width: double.maxFinite, - height: 76, - child: SecondaryButton( - color: Colors.grey[800], - textColor: Colors.white, - onTap: () { - setState(() { - widget.patientER.transportationMethodId =(widget.amRequestViewModel.amRequestModeList.indexOf(_erTransportationMethod) + 1); - widget.patientER.direction = _direction == Direction.ToHospital ? 1 : 0; - widget.patientER.tripType = _way == Way.TwoWays ? 0 : 1; - widget.patientER.selectedAmbulate = (widget.amRequestViewModel.amRequestModeList.indexOf(_erTransportationMethod) + 1); - widget.patientER.patientERTransportationMethod = _erTransportationMethod; - widget.patientER.orderServiceID = _orderService.getIdOrderService(); - widget.patientER.pickupUrgency = 1; - widget.patientER.lineItemNo = 1; - widget.patientER.cost = _erTransportationMethod.price; - widget.patientER.vAT = _erTransportationMethod.vAT ?? 0; - widget.patientER.totalPrice = _erTransportationMethod.totalPrice; - widget.changeCurrentTab(1); - }); - }, - label: TranslationBase.of(context).next, + ], + ), + ], + ), + SizedBox( + height: 15, ), - ) - ], + ], + ), + ), + ), + bottomSheet: Container( + padding: EdgeInsets.all(15), + width: double.maxFinite, + height: 90, + child: SecondaryButton( + color: Colors.grey[800], + textColor: Colors.white, + onTap: () { + setState(() { + widget.patientER.transportationMethodId = (widget + .amRequestViewModel.amRequestModeList + .indexOf(_erTransportationMethod) + + 1); + widget.patientER.direction = + _direction == Direction.ToHospital ? 1 : 0; + widget.patientER.tripType = _way == Way.TwoWays ? 0 : 1; + widget.patientER.selectedAmbulate = (widget + .amRequestViewModel.amRequestModeList + .indexOf(_erTransportationMethod) + + 1); + widget.patientER.patientERTransportationMethod = + _erTransportationMethod; + widget.patientER.orderServiceID = + _orderService.getIdOrderService(); + widget.patientER.pickupUrgency = 1; + widget.patientER.lineItemNo = 1; + widget.patientER.cost = _erTransportationMethod.price; + widget.patientER.vAT = _erTransportationMethod.vAT ?? 0; + widget.patientER.totalPrice = + _erTransportationMethod.totalPrice; + widget.changeCurrentTab(1); + }); + }, + label: TranslationBase.of(context).next, ), ), ); diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/Summary.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/Summary.dart index 8fd72b8f..6140dc62 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/Summary.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/Summary.dart @@ -3,6 +3,7 @@ import 'package:diplomaticquarterapp/core/viewModels/er/am_request_view_model.da import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:diplomaticquarterapp/core/enum/Ambulate.dart'; @@ -18,89 +19,93 @@ class Summary extends StatefulWidget { _SummaryState createState() => _SummaryState(); } -//TODO it should be dynamic class _SummaryState extends State { @override Widget build(BuildContext context) { - return SingleChildScrollView( - child: Container( - margin: EdgeInsets.only(left: 12, right: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts(TranslationBase.of(context).RRTSummary), - SizedBox(height: 5,), - Container( - width: double.infinity, - padding: EdgeInsets.all(10), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts(TranslationBase.of(context).transportMethod,color: Colors.grey,), - Texts('${widget.patientER.patientERTransportationMethod.title}',bold: true,), - SizedBox(height: 8,), + return AppScaffold( + isShowDecPage: false, + isShowAppBar: false, + body: SingleChildScrollView( + child: Container( + margin: EdgeInsets.only(left: 12, right: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts(TranslationBase.of(context).RRTSummary), + SizedBox(height: 5,), + Container( + width: double.infinity, + padding: EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Texts(TranslationBase.of(context).transportMethod,color: Colors.grey,), + Texts('${widget.patientER.patientERTransportationMethod.title}',bold: true,), + SizedBox(height: 8,), - Texts(TranslationBase.of(context).directions,color: Colors.grey,), - Texts('From Hospital',bold: true,), - SizedBox(height: 8,), + Texts(TranslationBase.of(context).directions,color: Colors.grey,), + Texts(widget.patientER.direction ==0? TranslationBase.of(context).toHospital:TranslationBase.of(context).fromHospital,bold: true,), + SizedBox(height: 8,), - Texts('Pickup Location',color: Colors.grey,), - Texts('SZR Medical Center',bold: true,), - SizedBox(height: 8,), + Texts(TranslationBase.of(context).pickupLocation,color: Colors.grey,), + Texts('${widget.patientER.pickupLocationName}',bold: true,), + SizedBox(height: 8,), - Texts('Drop off location',color: Colors.grey,), - Texts('6199, Al Ameen wlfn nif',bold: true,), - SizedBox(height: 8,), + Texts(TranslationBase.of(context).dropoffLocation,color: Colors.grey,), + Texts('${widget.patientER.dropoffLocationName}',bold: true,), + SizedBox(height: 8,), - Texts('Select Ambulate',color: Colors.grey,), - Texts('${widget.patientER.ambulate.getAmbulateTitle(context)}',bold: true,), - SizedBox(height: 8,), + Texts(TranslationBase.of(context).selectAmbulate,color: Colors.grey,), + Texts('${widget.patientER.ambulate.getAmbulateTitle(context)}',bold: true,), + SizedBox(height: 8,), - Texts('Note',color: Colors.grey,), - Texts('${widget.patientER.requesterNote?? '---'}',bold: true,), - SizedBox(height: 8,), - ], - ), - ), - SizedBox(height: 20,), - Texts('Bill Amount',textAlign: TextAlign.start,), - SizedBox(height: 5,), - Container( - height: 55, - padding: EdgeInsets.all(10), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8) + Texts(TranslationBase.of(context).notes,color: Colors.grey,), + Texts('${widget.patientER.requesterNote?? '---'}',bold: true,), + SizedBox(height: 8,), + ], + ), ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts('Total amount payable:'), - Texts('SR ${widget.patientER.patientERTransportationMethod.totalPrice}') - ], + SizedBox(height: 20,), + Texts(TranslationBase.of(context).billAmount,textAlign: TextAlign.start,), + SizedBox(height: 5,), + Container( + height: 55, + padding: EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8) + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(TranslationBase.of(context).patientShareTotal+':'), + Texts(TranslationBase.of(context).sar+' ${widget.patientER.patientERTransportationMethod.totalPrice}') + ], + ), ), - ), - SizedBox(height: 45,), - Container( - padding: EdgeInsets.all(15), - width: double.maxFinite, - height: 76, - child:SecondaryButton( - color: Colors.grey[800], - textColor: Colors.white, - label: TranslationBase.of(context).send, - onTap: () async { - await widget.amRequestViewModel.insertERPressOrder(patientER: widget.patientER); + SizedBox(height: 45,), - } - ), - ) - ], + ], + ), + ), + ), + bottomSheet: Container( + padding: EdgeInsets.all(15), + width: double.maxFinite, + height: 90, + child:SecondaryButton( + color: Colors.grey[800], + textColor: Colors.white, + label: TranslationBase.of(context).send, + onTap: () async { + await widget.amRequestViewModel.insertERPressOrder(patientER: widget.patientER); + + } ), ), ); diff --git a/lib/pages/ErService/OrderLogPage.dart b/lib/pages/ErService/OrderLogPage.dart index 6929cd0b..7d2a4a5b 100644 --- a/lib/pages/ErService/OrderLogPage.dart +++ b/lib/pages/ErService/OrderLogPage.dart @@ -30,28 +30,28 @@ class OrderLogPage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ OrderLogItem( - title: 'Request ID', + title: TranslationBase.of(context).reqId, value: amRequestViewModel.patientAllPresOrdersList[index].iD .toString(), ), OrderLogItem( - title: 'Status', + title: TranslationBase.of(context).orderStatus, value: amRequestViewModel .patientAllPresOrdersList[index].description, ), OrderLogItem( - title: 'Pickup Date', + title: TranslationBase.of(context).pickupDate, value: DateUtil.getDayMonthYearDateFormatted( DateUtil.convertStringToDate(amRequestViewModel .patientAllPresOrdersList[index].createdOn)), ), OrderLogItem( - title: 'Pickup Location', + title: TranslationBase.of(context).pickupLocation, value: amRequestViewModel .patientAllPresOrdersList[index].pickupLocationName, ), OrderLogItem( - title: 'Drop off Location', + title: TranslationBase.of(context).dropoffLocation, value: amRequestViewModel .patientAllPresOrdersList[index].dropoffLocationName, ), diff --git a/lib/pages/ErService/widgets/StepsWidget.dart b/lib/pages/ErService/widgets/StepsWidget.dart index c5864710..56b3de6b 100644 --- a/lib/pages/ErService/widgets/StepsWidget.dart +++ b/lib/pages/ErService/widgets/StepsWidget.dart @@ -13,7 +13,8 @@ class StepsWidget extends StatelessWidget { @override Widget build(BuildContext context) { ProjectViewModel projectViewModel = Provider.of(context); - return projectViewModel.isArabic? Stack( + return projectViewModel.isArabic? + Stack( children: [ Container( height: 50, @@ -29,7 +30,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - left: 0, + right: 0, child: InkWell( onTap: () => changeCurrentTab(0), child: Container( @@ -51,7 +52,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - left: MediaQuery.of(context).size.width * 0.3, + right: MediaQuery.of(context).size.width * 0.3, child: InkWell( onTap: () => index >= 2 ? changeCurrentTab(1) : null, child: Container( @@ -73,7 +74,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - left: MediaQuery.of(context).size.width * 0.6, + right: MediaQuery.of(context).size.width * 0.6, child: InkWell( onTap: () => index >= 3 ? changeCurrentTab(2) : null, child: Container( @@ -95,7 +96,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - right: 0, + left: 0, child: InkWell( onTap: () => index == 2 ?changeCurrentTab(3):null, child: Container( @@ -117,7 +118,8 @@ class StepsWidget extends StatelessWidget { ), ), ], - ):Stack( + ): + Stack( children: [ Container( height: 50, @@ -133,7 +135,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - right: 0, + left: 0, child: InkWell( onTap: () => changeCurrentTab(0), child: Container( @@ -155,7 +157,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - right: MediaQuery.of(context).size.width * 0.3, + left: MediaQuery.of(context).size.width * 0.3, child: InkWell( onTap: () => index >= 2 ? changeCurrentTab(1) : null, child: Container( @@ -177,7 +179,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - right: MediaQuery.of(context).size.width * 0.6, + left: MediaQuery.of(context).size.width * 0.6, child: InkWell( onTap: () => index >= 3 ? changeCurrentTab(2) : null, child: Container( @@ -199,7 +201,7 @@ class StepsWidget extends StatelessWidget { ), Positioned( top: 10, - left: 0, + right: 0, child: InkWell( onTap: () => index == 2 ?changeCurrentTab(3):null, child: Container( diff --git a/lib/pages/landing/landing_page.dart b/lib/pages/landing/landing_page.dart index 81ea68a5..d3f3959c 100644 --- a/lib/pages/landing/landing_page.dart +++ b/lib/pages/landing/landing_page.dart @@ -164,15 +164,23 @@ class _LandingPageState extends State with WidgetsBindingObserver { _firebaseMessaging.requestNotificationPermissions(); } - _firebaseMessaging.getToken().then((String token) async { - sharedPref.setString(PUSH_TOKEN, token); - if (token != null && await sharedPref.getObject(USER_PROFILE) == null) { - DEVICE_TOKEN = token; - checkUserStatus(token); - } - requestPermissions(); - }).catchError((err) { - print(err); + requestPermissions().then((results) { + registerGeofences(); + + if (results[Permission.notification].isGranted) + _firebaseMessaging.getToken().then((String token) { + sharedPref.setString(PUSH_TOKEN, token); + if (token != null && DEVICE_TOKEN == "") { + DEVICE_TOKEN = token; + checkUserStatus(token); + } + }); + if (results[Permission.location].isGranted) ; + if (results[Permission.storage].isGranted) ; + if (results[Permission.camera].isGranted) ; + if (results[Permission.photos].isGranted) ; + if (results[Permission.accessMediaLocation].isGranted) ; + if (results[Permission.calendar].isGranted) ; }); requestPermissions(); // }); @@ -416,8 +424,6 @@ class _LandingPageState extends State with WidgetsBindingObserver { } }); } - - requestPermissions().then((results) {}); } login() async { diff --git a/lib/pages/medical/balance/dialogs/SelectCiteisDialog.dart b/lib/pages/medical/balance/dialogs/SelectCiteisDialog.dart index 3d07c08c..19e4fea4 100644 --- a/lib/pages/medical/balance/dialogs/SelectCiteisDialog.dart +++ b/lib/pages/medical/balance/dialogs/SelectCiteisDialog.dart @@ -1,9 +1,11 @@ //import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart'; import 'package:diplomaticquarterapp/core/model/blooddonation/get_all_cities.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; class SelectCiteisDialog extends StatefulWidget { final List hospitals; @@ -12,6 +14,7 @@ class SelectCiteisDialog extends StatefulWidget { SelectCiteisDialog( {Key key, this.hospitals, this.onValueSelected, this.selectedHospital}); + @override _SelectCiteisDialogState createState() => _SelectCiteisDialogState(); } @@ -24,9 +27,10 @@ class _SelectCiteisDialogState extends State { widget.selectedHospital = widget.selectedHospital ?? widget.hospitals[0]; } - @override Widget build(BuildContext context) { + ProjectViewModel projectProvider = Provider.of(context); + return SimpleDialog( children: [ Column( @@ -34,7 +38,7 @@ class _SelectCiteisDialogState extends State { Divider(), ...List.generate( widget.hospitals.length, - (index) => Column( + (index) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( @@ -53,7 +57,9 @@ class _SelectCiteisDialogState extends State { child: ListTile( // title: Text(widget.hospitals[index].description + // ' ${widget.hospitals[index].distanceInKilometers} KM'), - title: Text(widget.hospitals[index].description), + title: Text(projectProvider.isArabic + ? widget.hospitals[index].descriptionN + : widget.hospitals[index].description), leading: Radio( value: widget.hospitals[index], groupValue: widget.selectedHospital, @@ -116,9 +122,9 @@ class _SelectCiteisDialogState extends State { padding: const EdgeInsets.all(8.0), child: Center( child: Texts( - TranslationBase.of(context).ok, - fontWeight: FontWeight.w400, - )), + TranslationBase.of(context).ok, + fontWeight: FontWeight.w400, + )), ), ), ), diff --git a/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart b/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart index 00f06a25..f39479ac 100644 --- a/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart +++ b/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart @@ -3,18 +3,37 @@ import 'package:diplomaticquarterapp/core/viewModels/medical/blood_sugar_view_mo import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/medical/balance/new_text_Field.dart'; +import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; +import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/dialogs/RadioStringDialog.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; -import 'package:feather_icons_flutter/feather_icons_flutter.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; import 'package:provider/provider.dart'; class AddBloodSugarPage extends StatefulWidget { + final DateTime bloodSugarDate; + final String measureUnitSelectedType; + final bool isUpdate; + final String measuredTime; + final String bloodSugarValue; + final int lineItemNo; + final BloodSugarViewMode bloodSugarViewMode; + + AddBloodSugarPage( + {Key key, + this.bloodSugarDate, + this.measureUnitSelectedType, + this.isUpdate = false, + this.measuredTime, + this.bloodSugarValue, this.lineItemNo, this.bloodSugarViewMode}) + : super(key: key); + @override _AddBloodSugarPageState createState() => _AddBloodSugarPageState(); } @@ -24,7 +43,7 @@ class _AddBloodSugarPageState extends State { DateTime bloodSugarDate = DateTime.now(); DateTime timeSugarDate = DateTime.now(); String measureUnitSelectedType = 'mg/dlt'; - int measuredTime=1; + int measuredTime = 1; final List measureUnitList = ['mg/dlt', 'mol/L']; final List measureTimeEnList = [ 'Before Breakfast', @@ -39,270 +58,229 @@ class _AddBloodSugarPageState extends State { 'Other', ]; final List measureTimeArList = [ - 'Before Breakfast', - 'After Breakfast', - 'Before Lunch', - 'After Lunch', - 'Before Dinner', - 'After Dinner', - 'Before Sleep', - 'After Sleep', - 'Fasting', - 'Other', + "قبل الإفطار", + "بعد الإفطار", + "بعد الغداء", + "بعد الغداء", + "قبل العشاء", + "بعد العشاء", + "قبل النوم", + "بعد النوم", + "صائم", + "آخر", ]; String measureTimeSelectedType; + @override + void initState() { + super.initState(); + if (widget.isUpdate) { + bloodSugarDate = widget.bloodSugarDate; + timeSugarDate = widget.bloodSugarDate; + measureUnitSelectedType = widget.measureUnitSelectedType; + if (measureTimeEnList.contains(widget.measuredTime)) + measuredTime = measureTimeEnList.indexOf(widget.measuredTime); + else if (measureTimeArList.contains(widget.measuredTime)) + measuredTime = measureTimeArList.indexOf(widget.measuredTime); + _bloodSugarValueController.text = widget.bloodSugarValue; + } + } @override Widget build(BuildContext context) { ProjectViewModel projectViewModel = Provider.of(context); - showTaskOptions() { - showModalBottomSheet( - backgroundColor: Colors.white, - context: context, - builder: (BuildContext bc) { - return Container( - padding: EdgeInsets.symmetric(vertical: 12.0), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.only( - topLeft: Radius.circular(16.0), - topRight: Radius.circular(16.0))), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - decoration: BoxDecoration( - color: Colors.grey[200], - borderRadius: BorderRadius.circular(3.0)), - width: 40.0, - height: 6.0, - ), - InkWell( - onTap: () { - Navigator.pop(context); - }, - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: 18.0, vertical: 18.0), - child: Row( - children: [ - Icon( - FeatherIcons.share, - color: Theme - .of(context) - .primaryColor, - size: 18.0, - ), - SizedBox(width: 24.0), - Texts('Share Task', - variant: "body2Link", color: Colors.grey[800]), - ], - ), - ), - ), - InkWell( - onTap: () { - Navigator.pop(context); - // Navigator.of(context).push(SlideUpPageRoute(widget: PostTaskIndex(task: new Task(category: task?.category, description: task?.description, title: task?.title)))); - }, - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: 18.0, vertical: 18.0), - child: Row( - children: [ - Icon( - FeatherIcons.copy, - color: Theme - .of(context) - .primaryColor, - size: 18.0, - ), - SizedBox(width: 24.0), - Texts('Post Similar Task', - variant: "body2Link", color: Colors.grey[800]), - ], - ), - ), + return AppScaffold( + isShowAppBar: true, + appBarTitle: widget.isUpdate + ? TranslationBase.of(context).update + : TranslationBase.of(context).add, + body: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: Container( + margin: EdgeInsets.all(15), + child: Column( + children: [ + SizedBox( + height: 15, + ), + NewTextFields( + hintText: TranslationBase.of(context).sugarAdd, + controller: _bloodSugarValueController, + keyboardType: TextInputType.number, + ), + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + confirmSelectMeasureUnitDialog(); + }, + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 65, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(measureUnitSelectedType), + Icon( + Icons.arrow_drop_down, + color: Colors.grey, + ) + ], ), - ], + ), ), - ); - }); - } - - return BaseView( - builder: (_, model, w) => - AppScaffold( - isShowAppBar: true, - appBarTitle: 'Add', - body: SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Container( - margin: EdgeInsets.all(15), - child: Column( - children: [ - SizedBox( - height: 15, - ), - NewTextFields( - hintText: 'Enter Blood Sugar Value', - controller: _bloodSugarValueController, - keyboardType: TextInputType.number, - ), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - confirmSelectMeasureUnitDialog(); - }, - child: Container( - padding: EdgeInsets.all(12), - width: double.infinity, - height: 65, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(12), - color: Colors.white), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts(measureUnitSelectedType), - Icon( - Icons.arrow_drop_down, - color: Colors.grey, - ) - ], - ), - ), - ), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - DatePicker.showDatePicker(context, - showTitleActions: true, - minTime: DateTime(DateTime - .now() - .year - 1, 1, 1), - maxTime: DateTime.now(), - onConfirm: (date) { - print('confirm $date'); - setState(() { - bloodSugarDate = date; - }); - }, - currentTime: bloodSugarDate, - locale: projectViewModel.localeType); - }, - child: Container( - padding: EdgeInsets.all(12), - width: double.infinity, - height: 65, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(12), - color: Colors.white), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts('Date'), - Texts(getDate()), - ], - ), - ), - ), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - DatePicker.showTimePicker( - context, showTitleActions: true, - onConfirm: (date) { - print('confirm $date'); - setState(() { - timeSugarDate = date; - }); - }, - currentTime: timeSugarDate, - locale: projectViewModel.localeType); + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + DatePicker.showDatePicker(context, + showTitleActions: true, + minTime: DateTime(DateTime.now().year - 1, 1, 1), + maxTime: DateTime.now(), onConfirm: (date) { + setState(() { + bloodSugarDate = date; + }); }, - child: Container( - padding: EdgeInsets.all(12), - width: double.infinity, - height: 65, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(12), - color: Colors.white), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [Texts('Time'), Texts(getTime())], - ), - ), - ), - SizedBox( - height: 8, - ), - InkWell( - onTap: () { - confirmSelectMeasureTimeDialog(projectViewModel.isArabic - ? measureTimeEnList - : measureTimeArList); + currentTime: bloodSugarDate, + locale: projectViewModel.localeType); + }, + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 65, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(TranslationBase.of(context).date), + Texts(getDate()), + ], + ), + ), + ), + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + DatePicker.showTimePicker(context, showTitleActions: true, + onConfirm: (date) { + setState(() { + timeSugarDate = date; + }); }, - child: Container( - padding: EdgeInsets.all(12), - width: double.infinity, - height: 65, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(12), - color: Colors.white), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Texts(measureTimeSelectedType ?? 'Others'), - Icon( - Icons.arrow_drop_down, - color: Colors.grey, - ) - ], - ), - ), - ), - ], + currentTime: timeSugarDate, + locale: projectViewModel.localeType); + }, + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 65, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(TranslationBase.of(context).time), + Texts(getTime()) + ], + ), ), ), - ), - bottomSheet: Container( - color: Colors.transparent, - width: double.infinity, - height: MediaQuery - .of(context) - .size - .width * 0.2, - child: Padding( - padding: const EdgeInsets.all(15.0), - child: SecondaryButton( - loading: model.state == ViewState.BusyLocal, - label: 'SAVE', textColor: Colors.white, onTap: () { - if (_bloodSugarValueController.text.isNotEmpty) { - model.addDiabtecResult(diabtecUnit: measureUnitSelectedType, - measuredTime: measuredTime, - bloodSugerResult:_bloodSugarValueController.text.toString(), - bloodSugerDateChart: '${bloodSugarDate.year}-${bloodSugarDate.month}-${bloodSugarDate.day} ${timeSugarDate.hour}:${timeSugarDate.minute}:00', - - ); - } - }), + SizedBox( + height: 8, + ), + InkWell( + onTap: () { + confirmSelectMeasureTimeDialog(projectViewModel.isArabic + ? measureTimeArList + : measureTimeEnList); + }, + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 65, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts(measureTimeSelectedType ?? + TranslationBase.of(context).other), + Icon( + Icons.arrow_drop_down, + color: Colors.grey, + ) + ], + ), + ), ), - ), + ], ), + ), + ), + bottomSheet: Container( + color: Colors.transparent, + width: double.infinity, + height: MediaQuery.of(context).size.width * 0.2, + child: Padding( + padding: const EdgeInsets.all(15.0), + child: SecondaryButton( + label: TranslationBase.of(context).save, + textColor: Colors.white, + onTap: () { + if (_bloodSugarValueController.text.isNotEmpty) { + GifLoaderDialogUtils.showMyDialog(context); + if (widget.isUpdate) + widget.bloodSugarViewMode.updateDiabtecResult( + month: bloodSugarDate, + hour: timeSugarDate, + diabtecUnit: measureUnitSelectedType, + measuredTime: measuredTime, + lineItemNo: widget.lineItemNo, + bloodSugerResult: + _bloodSugarValueController.text.toString()).then((value) { + GifLoaderDialogUtils.hideDialog(context); + if(widget.bloodSugarViewMode.state == ViewState.Error) + AppToast.showErrorToast(message: widget.bloodSugarViewMode.error); + else + Navigator.pop(context); + + }); + else + widget.bloodSugarViewMode.addDiabtecResult( + diabtecUnit: measureUnitSelectedType, + measuredTime: measuredTime, + bloodSugerResult: + _bloodSugarValueController.text.toString(), + bloodSugerDateChart: + '${bloodSugarDate.year}-${bloodSugarDate.month}-${bloodSugarDate.day} ${timeSugarDate.hour}:${timeSugarDate.minute}:00', + ).then((value) { + GifLoaderDialogUtils.hideDialog(context); + if(widget.bloodSugarViewMode.state == ViewState.Error) + AppToast.showErrorToast(message: widget.bloodSugarViewMode.error); + else + Navigator.pop(context); + }); + } + }), + ), + ), ); } String getDate() { - return "${DateUtil.getMonth(bloodSugarDate.month)} ${bloodSugarDate - .day}, ${bloodSugarDate.year}"; + return "${DateUtil.getMonth(bloodSugarDate.month)} ${bloodSugarDate.day}, ${bloodSugarDate.year}"; } String getTime() { @@ -314,7 +292,7 @@ class _AddBloodSugarPageState extends State { context: context, child: RadioStringDialog( radioList: measureUnitList, - title: 'Measure unit', + title: TranslationBase.of(context).measureUnit, selectedValue: measureUnitSelectedType, onValueSelected: (value) { setState(() { @@ -330,7 +308,7 @@ class _AddBloodSugarPageState extends State { context: context, child: RadioStringDialog( radioList: list, - title: 'Measure time', + title: TranslationBase.of(context).measureTime, selectedValue: measureTimeSelectedType, onValueSelected: (value) { setState(() { diff --git a/lib/pages/medical/my_trackers/blood_suger/BloodMonthly.dart b/lib/pages/medical/my_trackers/blood_suger/BloodMonthly.dart index fdd7b348..fa49382f 100644 --- a/lib/pages/medical/my_trackers/blood_suger/BloodMonthly.dart +++ b/lib/pages/medical/my_trackers/blood_suger/BloodMonthly.dart @@ -1,13 +1,16 @@ import 'package:diplomaticquarterapp/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart'; import 'package:diplomaticquarterapp/core/model/my_trakers/chartData/WeekChartDate.dart'; import 'package:diplomaticquarterapp/core/model/my_trakers/chartData/YearMonthlyChartDate.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:charts_flutter/flutter.dart' as charts; import 'package:hexcolor/hexcolor.dart'; +import 'package:provider/provider.dart'; class BloodMonthlyPage extends StatelessWidget { final List> data; @@ -17,6 +20,7 @@ class BloodMonthlyPage extends StatelessWidget { : super(key: key); @override Widget build(BuildContext context) { + ProjectViewModel projectViewModel = Provider.of(context); return AppScaffold( body: ListView( children: [ @@ -34,7 +38,7 @@ class BloodMonthlyPage extends StatelessWidget { ), Padding( padding: const EdgeInsets.all(8.0), - child: Texts('Details'), + child: Texts(TranslationBase.of(context).details), ), Container( padding: EdgeInsets.all(10), @@ -46,7 +50,7 @@ class BloodMonthlyPage extends StatelessWidget { border: TableBorder.symmetric( inside: BorderSide(width: 2.0, color: Colors.grey[300]), ), - children: fullData(), + children: fullData(context,projectViewModel), ), ], ), @@ -56,7 +60,7 @@ class BloodMonthlyPage extends StatelessWidget { ); } - List fullData() { + List fullData(BuildContext context,ProjectViewModel projectViewModel) { List tableRow = []; tableRow.add( TableRow( @@ -64,14 +68,15 @@ class BloodMonthlyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), + topLeft: projectViewModel.isArabic? Radius.circular(0.0):Radius.circular(10.0), + topRight: projectViewModel.isArabic? Radius.circular(10.0):Radius.circular(0.0), ), ), child: Center( child: Texts( - 'Date', + TranslationBase.of(context).date, color: Colors.white, fontSize: 15, ), @@ -82,11 +87,11 @@ class BloodMonthlyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Time', + TranslationBase.of(context).time, color: Colors.white, fontSize: 15, ), @@ -96,11 +101,11 @@ class BloodMonthlyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Measured', + TranslationBase.of(context).measured, color: Colors.white, fontSize: 15, ), @@ -110,20 +115,22 @@ class BloodMonthlyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topRight: Radius.circular(10.0), + topLeft: projectViewModel.isArabic? Radius.circular(10.0):Radius.circular(0.0), + topRight: projectViewModel.isArabic? Radius.circular(0.0):Radius.circular(10.0), ), ), child: Center( child: Texts( - 'Value', + TranslationBase.of(context).value, color: Colors.white, fontSize: 15, ), ), height: 40), ), + ], ), ); diff --git a/lib/pages/medical/my_trackers/blood_suger/BloodYeaPage.dart b/lib/pages/medical/my_trackers/blood_suger/BloodYeaPage.dart index 47f87847..69f00e61 100644 --- a/lib/pages/medical/my_trackers/blood_suger/BloodYeaPage.dart +++ b/lib/pages/medical/my_trackers/blood_suger/BloodYeaPage.dart @@ -1,12 +1,15 @@ import 'package:diplomaticquarterapp/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart'; import 'package:diplomaticquarterapp/core/model/my_trakers/chartData/WeekChartDate.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:charts_flutter/flutter.dart' as charts; import 'package:hexcolor/hexcolor.dart'; +import 'package:provider/provider.dart'; class BloodYearPage extends StatelessWidget { final List> data; @@ -17,6 +20,7 @@ class BloodYearPage extends StatelessWidget { @override Widget build(BuildContext context) { + ProjectViewModel projectViewModel = Provider.of(context); return AppScaffold( body: ListView( children: [ @@ -34,7 +38,7 @@ class BloodYearPage extends StatelessWidget { ), Padding( padding: const EdgeInsets.all(8.0), - child: Texts('Details'), + child: Texts(TranslationBase.of(context).details), ), Container( padding: EdgeInsets.all(10), @@ -46,7 +50,7 @@ class BloodYearPage extends StatelessWidget { border: TableBorder.symmetric( inside: BorderSide(width: 2.0, color: Colors.grey[300]), ), - children: fullData(), + children: fullData(context,projectViewModel), ), ], ), @@ -56,7 +60,7 @@ class BloodYearPage extends StatelessWidget { ); } - List fullData() { + List fullData(BuildContext context,ProjectViewModel projectViewModel) { List tableRow = []; tableRow.add( TableRow( @@ -64,14 +68,15 @@ class BloodYearPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), + topLeft: projectViewModel.isArabic? Radius.circular(0.0):Radius.circular(10.0), + topRight: projectViewModel.isArabic? Radius.circular(10.0):Radius.circular(0.0), ), ), child: Center( child: Texts( - 'Date', + TranslationBase.of(context).date, color: Colors.white, fontSize: 15, ), @@ -82,11 +87,11 @@ class BloodYearPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Time', + TranslationBase.of(context).time, color: Colors.white, fontSize: 15, ), @@ -96,11 +101,11 @@ class BloodYearPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Measured', + TranslationBase.of(context).measured, color: Colors.white, fontSize: 15, ), @@ -110,20 +115,22 @@ class BloodYearPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topRight: Radius.circular(10.0), + topLeft: projectViewModel.isArabic? Radius.circular(10.0):Radius.circular(0.0), + topRight: projectViewModel.isArabic? Radius.circular(0.0):Radius.circular(10.0), ), ), child: Center( child: Texts( - 'Value', + TranslationBase.of(context).value, color: Colors.white, fontSize: 15, ), ), height: 40), ), + ], ), ); diff --git a/lib/pages/medical/my_trackers/blood_suger/blood_sugar_home_page.dart b/lib/pages/medical/my_trackers/blood_suger/blood_sugar_home_page.dart index 71df9a3a..70cdea0f 100644 --- a/lib/pages/medical/my_trackers/blood_suger/blood_sugar_home_page.dart +++ b/lib/pages/medical/my_trackers/blood_suger/blood_sugar_home_page.dart @@ -43,7 +43,7 @@ class _BloodSugarHomePageState extends State onModelReady: (model) => model.getBloodSugar(), builder: (_, model, w) => AppScaffold( isShowAppBar: true, - appBarTitle: 'Blood Sugar', + appBarTitle: TranslationBase.of(context).bloodSugar, baseViewModel: model, body: Scaffold( extendBodyBehindAppBar: true, @@ -81,21 +81,21 @@ class _BloodSugarHomePageState extends State unselectedLabelColor: Colors.grey[800], tabs: [ Container( - width: MediaQuery.of(context).size.width * 0.27, + width: MediaQuery.of(context).size.width * 0.33, child: Center( - child: Texts('Weekly'), + child: Texts(TranslationBase.of(context).weekly), ), ), Container( - width: MediaQuery.of(context).size.width * 0.27, + width: MediaQuery.of(context).size.width * 0.33, child: Center( - child: Texts('Monthly'), + child: Texts(TranslationBase.of(context).monthlyT), ), ), Container( - width: MediaQuery.of(context).size.width * 0.27, + width: MediaQuery.of(context).size.width * 0.34, child: Center( - child: Texts('Yearly'), + child: Texts(TranslationBase.of(context).yearly), ), ), ], @@ -116,6 +116,7 @@ class _BloodSugarHomePageState extends State BloodSugarWeeklyPage( data: model.getBloodWeeklySeries(), diabtecPatientResult: model.weekDiabtecPatientResult, + bloodSugarViewMode: model, ), BloodMonthlyPage( data: model.getBloodMonthlyTimeSeriesSales(), @@ -132,13 +133,13 @@ class _BloodSugarHomePageState extends State ), floatingActionButton: InkWell( onTap: () { - Navigator.push(context, FadePage(page: AddBloodSugarPage())); + Navigator.push(context, FadePage(page: AddBloodSugarPage(bloodSugarViewMode: model,))); }, child: Container( width: 55, height: 55, decoration: BoxDecoration( - shape: BoxShape.circle, color: HexColor('515B5D')), + shape: BoxShape.circle, color:Theme.of(context).primaryColor), child: Center( child: Icon( Icons.add, diff --git a/lib/pages/medical/my_trackers/blood_suger/blood_sugar_weekly_page.dart b/lib/pages/medical/my_trackers/blood_suger/blood_sugar_weekly_page.dart index 4b007929..139548e1 100644 --- a/lib/pages/medical/my_trackers/blood_suger/blood_sugar_weekly_page.dart +++ b/lib/pages/medical/my_trackers/blood_suger/blood_sugar_weekly_page.dart @@ -1,22 +1,31 @@ import 'package:diplomaticquarterapp/core/model/my_trakers/blood_sugar/DiabtecPatientResult.dart'; import 'package:diplomaticquarterapp/core/model/my_trakers/chartData/WeekChartDate.dart'; +import 'package:diplomaticquarterapp/core/viewModels/medical/blood_sugar_view_model.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; +import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:charts_flutter/flutter.dart' as charts; import 'package:hexcolor/hexcolor.dart'; +import 'package:provider/provider.dart'; + +import 'AddBloodSugarPage.dart'; class BloodSugarWeeklyPage extends StatelessWidget { final List> data; final List diabtecPatientResult; + final BloodSugarViewMode bloodSugarViewMode; - const BloodSugarWeeklyPage({Key key, this.data, this.diabtecPatientResult}) + const BloodSugarWeeklyPage({Key key, this.data, this.diabtecPatientResult, this.bloodSugarViewMode}) : super(key: key); @override Widget build(BuildContext context) { + ProjectViewModel projectViewModel = Provider.of(context); return AppScaffold( body: ListView( children: [ @@ -34,7 +43,7 @@ class BloodSugarWeeklyPage extends StatelessWidget { ), Padding( padding: const EdgeInsets.all(8.0), - child: Texts('Details'), + child: Texts(TranslationBase.of(context).details), ), Container( padding: EdgeInsets.all(10), @@ -46,7 +55,7 @@ class BloodSugarWeeklyPage extends StatelessWidget { border: TableBorder.symmetric( inside: BorderSide(width: 2.0, color: Colors.grey[300]), ), - children: fullData(), + children: fullData(context, projectViewModel,bloodSugarViewMode), ), ], ), @@ -56,7 +65,8 @@ class BloodSugarWeeklyPage extends StatelessWidget { ); } - List fullData() { + List fullData( + BuildContext context, ProjectViewModel projectViewModel, BloodSugarViewMode bloodSugarViewMode) { List tableRow = []; tableRow.add( TableRow( @@ -64,14 +74,19 @@ class BloodSugarWeeklyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), + topLeft: projectViewModel.isArabic + ? Radius.circular(0.0) + : Radius.circular(10.0), + topRight: projectViewModel.isArabic + ? Radius.circular(10.0) + : Radius.circular(0.0), ), ), child: Center( child: Texts( - 'Date', + TranslationBase.of(context).date, color: Colors.white, fontSize: 15, ), @@ -82,11 +97,11 @@ class BloodSugarWeeklyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Time', + TranslationBase.of(context).time, color: Colors.white, fontSize: 15, ), @@ -96,11 +111,11 @@ class BloodSugarWeeklyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Measured', + TranslationBase.of(context).measured, color: Colors.white, fontSize: 15, ), @@ -110,11 +125,11 @@ class BloodSugarWeeklyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, ), child: Center( child: Texts( - 'Value', + TranslationBase.of(context).value, color: Colors.white, fontSize: 15, ), @@ -124,14 +139,19 @@ class BloodSugarWeeklyPage extends StatelessWidget { Container( child: Container( decoration: BoxDecoration( - color: HexColor('#515B5D'), + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only( - topRight: Radius.circular(10.0), + topLeft: projectViewModel.isArabic + ? Radius.circular(10.0) + : Radius.circular(0.0), + topRight: projectViewModel.isArabic + ? Radius.circular(0.0) + : Radius.circular(10.0), ), ), child: Center( child: Texts( - 'Edit', + TranslationBase.of(context).edit, color: Colors.white, fontSize: 15, ), @@ -203,12 +223,30 @@ class BloodSugarWeeklyPage extends StatelessWidget { ), ), Container( - child: Container( - height: 70, - padding: EdgeInsets.all(10), - color: Colors.white, - child: Center( - child: Icon(Icons.edit), + child: InkWell( + onTap: () { + Navigator.push( + context, + FadePage( + page: AddBloodSugarPage( + isUpdate: true, + bloodSugarDate: diabtec.dateChart, + measuredTime: diabtec.measuredDesc, + bloodSugarValue: diabtec.resultValue.toString(), + lineItemNo: diabtec.lineItemNo, + measureUnitSelectedType: diabtec.unit, + bloodSugarViewMode: bloodSugarViewMode, + ), + ), + ); + }, + child: Container( + height: 70, + padding: EdgeInsets.all(10), + color: Colors.white, + child: Center( + child: Icon(Icons.edit), + ), ), ), ), diff --git a/lib/pages/medical/my_trackers/my_trackers.dart b/lib/pages/medical/my_trackers/my_trackers.dart index ecdf5a53..5e5c4527 100644 --- a/lib/pages/medical/my_trackers/my_trackers.dart +++ b/lib/pages/medical/my_trackers/my_trackers.dart @@ -1,3 +1,5 @@ +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; +import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; @@ -11,7 +13,7 @@ class MyTrackers extends StatelessWidget { @override Widget build(BuildContext context) { return AppScaffold( - appBarTitle: 'My Tracker', + appBarTitle: TranslationBase.of(context).myTracker, isShowAppBar: true, body: SingleChildScrollView( child: Container( @@ -41,7 +43,7 @@ class MyTrackers extends StatelessWidget { children: [ Image.asset('assets/tracker/blood-suger.png',width: 60.0,), SizedBox(height: 15,), - Text('Blood Sugar'), + Texts(TranslationBase.of(context).bloodSugar), ], ), ), @@ -65,7 +67,7 @@ class MyTrackers extends StatelessWidget { children: [ Image.asset('assets/tracker/blood-pressure.png',width: 60.0,), SizedBox(height: 15,), - Text('Blood Pressure'), + Texts(TranslationBase.of(context).bloodPressure), ], ), ), @@ -94,7 +96,7 @@ class MyTrackers extends StatelessWidget { children: [ Image.asset('assets/tracker/weight.png',width: 60.0,), SizedBox(height: 15,), - Text('Weight'), + Texts(TranslationBase.of(context).weight), ], ), ), diff --git a/lib/pages/medical/vital_sign/vital_sing_chart_and_detials.dart b/lib/pages/medical/vital_sign/vital_sing_chart_and_detials.dart index 43bc9f0a..b09a579d 100644 --- a/lib/pages/medical/vital_sign/vital_sing_chart_and_detials.dart +++ b/lib/pages/medical/vital_sign/vital_sing_chart_and_detials.dart @@ -1,5 +1,6 @@ import 'package:diplomaticquarterapp/core/model/vital_sign/vital_sign_res_model.dart'; import 'package:diplomaticquarterapp/pages/medical/vital_sign/vital_sign_details_wideget.dart'; +import 'package:diplomaticquarterapp/uitl/date_uitl.dart'; import 'package:diplomaticquarterapp/widgets/charts/app_time_series_chart.dart'; import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart'; import 'package:flutter/material.dart'; diff --git a/lib/pages/pharmacies/product_detail.dart b/lib/pages/pharmacies/product_detail.dart index 2040db11..ebb7fe39 100644 --- a/lib/pages/pharmacies/product_detail.dart +++ b/lib/pages/pharmacies/product_detail.dart @@ -279,6 +279,31 @@ class __ProductDetailPageState extends State { SizedBox( height: 10, ), + Container( + child: Text( + languageID == 'ar' + ? widget.product.shortDescriptionn + : widget.product.shortDescription, + style: TextStyle( + fontSize: 16, + fontFamily: 'WorkSans-Regular'), + ), + ), + SizedBox( + height: 10, + ), + Container( + child: Text( + TranslationBase.of(context).howToUse, + style: TextStyle( + fontSize: 17, + color: Colors.grey, + fontWeight: FontWeight.w600), + ), + ), + SizedBox( + height: 10, + ), Container( child: Text( languageID == 'ar' diff --git a/lib/pages/pharmacies/screens/pharmacy_module_page.dart b/lib/pages/pharmacies/screens/pharmacy_module_page.dart index fd51d6ef..b41c1804 100644 --- a/lib/pages/pharmacies/screens/pharmacy_module_page.dart +++ b/lib/pages/pharmacies/screens/pharmacy_module_page.dart @@ -2,6 +2,7 @@ import 'package:diplomaticquarterapp/config/size_config.dart'; import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/landing/home_page.dart'; +import 'package:diplomaticquarterapp/pages/medical/prescriptions/prescriptions_home_page.dart'; import 'package:diplomaticquarterapp/pages/offers_categorise_page.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/cart-order-page.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/lakum-main-page.dart'; @@ -15,11 +16,21 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_svg/svg.dart'; +import 'package:rating_bar/rating_bar.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/product-brands.dart'; import 'lacum-activitaion-vida-page.dart'; +import 'package:diplomaticquarterapp/widgets/data_display/medical/doctor_card.dart'; +import 'package:diplomaticquarterapp/core/viewModels/medical/prescriptions_view_model.dart'; class PharmacyPage extends StatelessWidget { + @override + void initState() { +// print("model prescription " + model.prescriptionsList.length); +// cancelOrderDetail(order) + } + @override Widget build(BuildContext context) { return BaseView( @@ -37,8 +48,242 @@ class PharmacyPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - BannerPager(model), - GridViewButtons(model), + BannerPager(model), + // GridViewButtons(model), + Container( + margin: EdgeInsets.fromLTRB(10, 10, 10, 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts( + TranslationBase.of(context).myPrescription, + bold: true, + ), + BorderedButton( + TranslationBase.of(context).viewAll, + hasBorder: true, + borderColor: Colors.green, + textColor: Colors.green, + vPadding: 6, + hPadding: 4, + handler: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + HomePrescriptionsPage())); + }, + ), + ], + ), + ), + + Container( + padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0), + height: MediaQuery.of(context).size.height * 0.30, +// width: 200.0, +// height: MediaQuery.of(context).size.height / 4 + 20, + margin: EdgeInsets.only(left: 10), + child: BaseView( + onModelReady: (model) => model.getPrescription(), + builder: (_, model, wi) => model.prescriptionsList.length != 0 +// model.getPrescription(); + ? ListView.builder( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + physics: ScrollPhysics(), + // physics: NeverScrollableScrollPhysics(), + // itemCount: 4, + itemCount: model.prescriptionsList.length, + itemBuilder: (context, index) { + return Container( +// width: 160.0, + height: MediaQuery.of(context).size.height * 0.6, + padding: EdgeInsets.only(bottom: 5.0, left: 5.0), + margin: EdgeInsets.only(right: 10.0), + decoration: BoxDecoration( + border: Border.all( + color: Colors.grey, + style: BorderStyle.solid, + width: 1.0, + ), + color: Colors.white, + borderRadius: BorderRadius.circular(10.0)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Column(children: [ + Container( + padding: EdgeInsets.only( + top: 10.0, + left: 10.0, + right: 3.0, + bottom: 15.0, + ), + child: Image.network( + model.prescriptionsList[index] + .doctorImageURL, + width: 60, + height: 60, + ), + ), + ]), + Column( +// crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + margin: EdgeInsets.only(left: 1), + padding: EdgeInsets.only( + left: 15.0, right: 15.0), + decoration: BoxDecoration( + border: Border.all( + color: Colors.green, + style: BorderStyle.solid, + width: 4.0, + ), + color: Colors.green, + borderRadius: + BorderRadius.circular( + 30.0)), + child: Text( + model.prescriptionsList[index] + .isInOutPatientDescription + .toString(), + style: TextStyle( + color: Colors.white, + fontSize: 15.0, +// fontWeight: FontWeight.bold, + ), + )), + Row(children: [ + Image.asset( + 'assets/images/Icon-awesome-calendar.png', + width: 30, + height: 30, + ), + Text( + model.prescriptionsList[index] + .appointmentDate + .toString(), + style: TextStyle( + color: Colors.black, + fontSize: 15.0, +// fontWeight: FontWeight.bold, + ), + ) + ]), + ], + ), + ], + ), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + margin: EdgeInsets.only(left: 5), + child: Row(children: [ + Text( + model.prescriptionsList[index] + .doctorTitle + .toString(), + style: TextStyle( + color: Colors.black, + fontSize: 15.0, + fontWeight: FontWeight.bold, + ), + ), + Text( + model.prescriptionsList[index] + .doctorName + .toString(), + style: TextStyle( + color: Colors.black, + fontSize: 15.0, + fontWeight: FontWeight.bold, + ), + ), + ]), + ), + ], + ), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + margin: EdgeInsets.only(left: 5), + child: Text( + model.prescriptionsList[index] + .clinicDescription + .toString(), + style: TextStyle( + color: Colors.green, + fontSize: 15.0, +// fontWeight: FontWeight.bold, + ), + ), + ), + ], + ), + Row( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Container( + margin: EdgeInsets.only(left: 5), + child: Align( + alignment: Alignment.topLeft, + child: RatingBar.readOnly( +// initialRating: productRate, + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), + ), + ) + ]), + ]), + ); + }) + : Container(), + ), + ), + Container( + margin: EdgeInsets.fromLTRB(10, 10, 10, 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Texts( + TranslationBase.of(context).recommended, + bold: true, + ), + BorderedButton( + TranslationBase.of(context).viewAll, + hasBorder: true, + borderColor: Colors.green, + textColor: Colors.green, + vPadding: 6, + hPadding: 4, + handler: () {}, + ), + ], + ), + ), + Container( + height: MediaQuery.of(context).size.height / 4 + 20, + child: ListView.builder( + itemBuilder: (ctx, i) => + ProductTileItem(model.bestSellerProduct[i]), + scrollDirection: Axis.horizontal, + itemCount: model.bestSellerProduct.length, + ), + ), + Container( margin: EdgeInsets.fromLTRB(10, 0, 10, 0), child: Row( @@ -55,8 +300,9 @@ class PharmacyPage extends StatelessWidget { hPadding: 4, borderColor: Colors.green, textColor: Colors.green, - handler: () =>{ - Navigator.push(context,FadePage(page: ProductBrandsPage())), + handler: () => { + Navigator.push( + context, FadePage(page: ProductBrandsPage())), }, ), ], @@ -119,8 +365,9 @@ class PharmacyPage extends StatelessWidget { textColor: Colors.green, vPadding: 6, hPadding: 4, - handler: () =>{ - Navigator.push(context,FadePage(page: ProductBrandsPage())), + handler: () => { + Navigator.push( + context, FadePage(page: ProductBrandsPage())), }, ), ], @@ -180,15 +427,15 @@ class GridViewButtons extends StatelessWidget { hasColorFilter: false, child: GridViewCard(TranslationBase.of(context).medicationRefill, 'assets/images/pharmacy_module/medication_icon.png', () { - model.checkUserIsActivated().then((isActivated) { - if (isActivated) { - Navigator.push(context, FadePage(page: LakumMainPage())); - } else { - Navigator.push( - context, FadePage(page: LakumActivationVidaPage())); - } - }); - }), + model.checkUserIsActivated().then((isActivated) { + if (isActivated) { + Navigator.push(context, FadePage(page: LakumMainPage())); + } else { + Navigator.push( + context, FadePage(page: LakumActivationVidaPage())); + } + }); + }), ), DashboardItem( imageName: 'pharmacy_module/bg_3.png', @@ -196,8 +443,9 @@ class GridViewButtons extends StatelessWidget { hasColorFilter: false, child: GridViewCard(TranslationBase.of(context).myPrescriptions, 'assets/images/pharmacy_module/prescription_icon.png', () { - Navigator.push(context, FadePage(page: PharmacyAddressesPage())); - }), + Navigator.push( + context, FadePage(page: PharmacyAddressesPage())); + }), ), DashboardItem( imageName: 'pharmacy_module/bg_4.png', @@ -206,7 +454,7 @@ class GridViewButtons extends StatelessWidget { child: GridViewCard( TranslationBase.of(context).searchAndScanMedication, 'assets/images/pharmacy_module/search_scan_icon.png', - () {}), + () {}), ), ], ), diff --git a/lib/pages/pharmacy/order/Order.dart b/lib/pages/pharmacy/order/Order.dart index 576bf2a0..4ef14389 100644 --- a/lib/pages/pharmacy/order/Order.dart +++ b/lib/pages/pharmacy/order/Order.dart @@ -9,6 +9,7 @@ import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:diplomaticquarterapp/services/pharmacy_services/order_service.dart'; import 'package:diplomaticquarterapp/pages/pharmacy/order/OrderDetails.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/order_model.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/orders_model.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; @@ -31,11 +32,11 @@ class _OrderPageState extends State with SingleTickerProviderStateMix String customerId = ""; String order =""; - List orderList = [] ; - List deliveredOrderList = [] ; - List processingOrderList = []; - List cancelledOrderList = []; - List pendingOrderList = []; + List orderList = [] ; + List deliveredOrderList = [] ; + List processingOrderList = []; + List cancelledOrderList = []; + List pendingOrderList = []; TabController _tabController; // AppSharedPreferences sharedPref = AppSharedPreferences(); @@ -66,6 +67,8 @@ class _OrderPageState extends State with SingleTickerProviderStateMix child: Column( children: [ TabBar( + labelPadding: + EdgeInsets.only(left: 3.0, right: 3.0), tabs: [ Tab(text: TranslationBase.of(context).delivered), Tab(text: TranslationBase.of(context).processing), @@ -103,16 +106,16 @@ class _OrderPageState extends State with SingleTickerProviderStateMix Widget getDeliveredOrder(OrderModelViewModel model){ - for(int i=0 ; i< model.order.length; i++){ - if( model.order[i].orderStatusId == 30 || model.order[i].orderStatusId == 997 - || model.order[i].orderStatusId == 994 + for(int i=0 ; i< model.orders.length; i++){ + if( model.orders[i].orderStatusId == 30 || model.orders[i].orderStatusId == 997 + || model.orders[i].orderStatusId == 994 ){ - deliveredOrderList.add(model.order[i]); + deliveredOrderList.add(model.orders[i]); } } return Container( width: MediaQuery.of(context).size.width, - child: model.order.length != 0 + child: model.orders.length != 0 ? SingleChildScrollView( child: Column( children: [ @@ -162,7 +165,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix ), ), Container( - child: Text(deliveredOrderList[index].createdOnUtc.toString().substring(0,11), + child: Text(deliveredOrderList[index].createdOnUtc.toString().substring(0,10), style: TextStyle(fontSize: 14.0, ), ), @@ -177,7 +180,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix child: InkWell( onTap: () { Navigator.push(context, - MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel:deliveredOrderList[index]))); + MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel: deliveredOrderList[index]),)); }, child: SvgPicture.asset( languageID == "ar" @@ -260,7 +263,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix Row( children: [ Container( - child: Text(deliveredOrderList[index].orderItems.length.toString(), + child: Text(deliveredOrderList[index].productCount.toString(), style: TextStyle(fontSize: 14.0, ), ), @@ -317,15 +320,15 @@ class _OrderPageState extends State with SingleTickerProviderStateMix } Widget getProcessingOrder(OrderModelViewModel model){ - for(int i=0 ; i< model.order.length; i++){ - if( model.order[i].orderStatusId == 20 || model.order[i].orderStatusId == 995 || - model.order[i].orderStatusId == 998 || model.order[i].orderStatusId == 999){ - processingOrderList.add(model.order[i]); + for(int i=0 ; i< model.orders.length; i++){ + if( model.orders[i].orderStatusId == 20 || model.orders[i].orderStatusId == 995 || + model.orders[i].orderStatusId == 998 || model.orders[i].orderStatusId == 999){ + processingOrderList.add(model.orders[i]); } } return Container( width: MediaQuery.of(context).size.width, - child: model.order.length != 0 + child: model.orders.length != 0 ? SingleChildScrollView( child: Column( children: [ @@ -375,7 +378,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix ), ), Container( - child: Text(processingOrderList[index].createdOnUtc.toString().substring(0,11), + child: Text(processingOrderList[index].createdOnUtc.toString().substring(0,10), style: TextStyle(fontSize: 14.0, ), ), @@ -390,8 +393,9 @@ class _OrderPageState extends State with SingleTickerProviderStateMix child: InkWell( onTap: () { Navigator.push(context, - MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel:processingOrderList[index]))); - }, + MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel :processingOrderList[index]))); + + }, child: SvgPicture.asset( languageID == "ar" ? 'assets/images/pharmacy/arrow_left.svg' @@ -473,7 +477,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix Row( children: [ Container( - child: Text(processingOrderList[index].orderItems.length.toString(), + child: Text(processingOrderList[index].productCount.toString(), style: TextStyle(fontSize: 14.0, ), ), @@ -709,13 +713,13 @@ class _OrderPageState extends State with SingleTickerProviderStateMix } Widget getPendingOrder(OrderModelViewModel model){ - for(int i=0 ; i< model.order.length; i++){ - if( model.order[i].orderStatusId == 10){ - pendingOrderList.add(model.order[i]); + for(int i=0 ; i< model.orders.length; i++){ + if( model.orders[i].orderStatusId == 10){ + pendingOrderList.add(model.orders[i]); } } return Container( - child: model.order.length != 0 + child: model.orders.length != 0 ? SingleChildScrollView( child: Column( children: [ @@ -766,7 +770,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix ), ), Container( - child: Text(pendingOrderList[index].createdOnUtc.toString().substring(0,11), + child: Text(pendingOrderList[index].createdOnUtc.toString().substring(0,10), style: TextStyle(fontSize: 14.0, ), ), @@ -782,7 +786,8 @@ class _OrderPageState extends State with SingleTickerProviderStateMix onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel:pendingOrderList[index]))); - }, + + }, child: SvgPicture.asset( languageID == "ar" ? 'assets/images/pharmacy/arrow_left.svg' @@ -864,7 +869,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix Row( children: [ Container( - child: Text(pendingOrderList[index].orderItems.length.toString(), + child: Text(pendingOrderList[index].productCount.toString(), style: TextStyle(fontSize: 14.0, ), ), @@ -924,14 +929,14 @@ class _OrderPageState extends State with SingleTickerProviderStateMix } Widget getCancelledOrder(OrderModelViewModel model){ - for(int i=0 ; i< model.order.length; i++){ - if( model.order[i].orderStatusId == 40 || model.order[i].orderStatusId == 996 - || model.order[i].orderStatusId == 200){ - cancelledOrderList.add(model.order[i]); + for(int i=0 ; i< model.orders.length; i++){ + if( model.orders[i].orderStatusId == 40 || model.orders[i].orderStatus == 996 + || model.orders[i].orderStatusId == 200){ + cancelledOrderList.add(model.orders[i]); } } return Container( - child: model.order.length != 0 + child: model.orders.length != 0 ? SingleChildScrollView( child: Column( children: [ @@ -982,7 +987,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix ), ), Container( - child: Text(cancelledOrderList[index].createdOnUtc.toString().substring(0,11), + child: Text(cancelledOrderList[index].createdOnUtc.toString().substring(0,10), style: TextStyle(fontSize: 14.0, ), ), @@ -997,7 +1002,8 @@ class _OrderPageState extends State with SingleTickerProviderStateMix child: InkWell( onTap: () { Navigator.push(context, - MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel:cancelledOrderList[index]))); + MaterialPageRoute(builder: (context) => OrderDetailsPage(orderModel: cancelledOrderList[index]))); + }, child: SvgPicture.asset( languageID == "ar" @@ -1080,7 +1086,7 @@ class _OrderPageState extends State with SingleTickerProviderStateMix Row( children: [ Container( - child: Text(cancelledOrderList[index].orderItems.length.toString(), + child: Text(cancelledOrderList[index].productCount.toString(), style: TextStyle(fontSize: 14.0, ), ), @@ -1136,13 +1142,17 @@ class _OrderPageState extends State with SingleTickerProviderStateMix ), ), ); - } + int test = Test()["1"]; + } } - - - - - +class Test{ + static const values = { + "1":1, + "2":2, + "3":3 + }; + int operator [](String key) => values[key]; +} \ No newline at end of file diff --git a/lib/pages/pharmacy/order/OrderDetails.dart b/lib/pages/pharmacy/order/OrderDetails.dart index 5438663d..670cb951 100644 --- a/lib/pages/pharmacy/order/OrderDetails.dart +++ b/lib/pages/pharmacy/order/OrderDetails.dart @@ -1,6 +1,8 @@ +import 'package:diplomaticquarterapp/core/model/pharmacies/orders_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/order_model_view_model.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/pharmacy/order/Order.dart'; +import 'package:diplomaticquarterapp/pages/pharmacy/order/TrackDriver.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; @@ -17,15 +19,16 @@ import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:provider/provider.dart'; - - - dynamic languageID; -class OrderDetailsPage extends StatefulWidget { - OrderModel orderModel; +class OrderDetailsPage extends StatefulWidget { + Orders orderModel; OrderDetailsPage({@required this.orderModel}); + // Orders orderModel; +// OrderModel orderModelDetails; +// OrderDetailsPage({@required this.orderModel, this.orderModelDetails}); + @override _OrderDetailsPageState createState() => _OrderDetailsPageState(); } @@ -36,9 +39,8 @@ class _OrderDetailsPageState extends State { } // AppSharedPreferences sharedPref = AppSharedPreferences(); - String orderId = ""; String customerId; - List orderList = []; + List ordersList = []; List cancelledOrderList = []; @@ -46,6 +48,7 @@ class _OrderDetailsPageState extends State { var model; var isCancel = false; var isRefund = false; + var isActiveDelivery = true; var dataIsCancel; var dataIsRefund; @@ -53,8 +56,10 @@ class _OrderDetailsPageState extends State { void initState() { getLanguageID(); super.initState(); - print(widget.orderModel.orderItems.length); +// print(widget.orderModel.orderItems.length); getCancelOrder(widget.orderModel.id); + + print("ID is" + widget.orderModel.id); // cancelOrderDetail(order) } @@ -105,9 +110,11 @@ class _OrderDetailsPageState extends State { color: getStatusBackgroundColor(), borderRadius: BorderRadius.circular(30.0)), child: Text( - languageID == "ar" - ? widget.orderModel.orderStatusn.toString(): - widget.orderModel.orderStatus.toString().substring(12) , + languageID == "ar" + ? model.orderListModel[0].orderStatusn.toString() + : model.orderListModel[0].orderStatus + .toString() + .substring(12), // TranslationBase.of(context).delivered, style: TextStyle( color: Colors.white, @@ -124,11 +131,11 @@ class _OrderDetailsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - widget.orderModel.shippingAddress.firstName + model.orderListModel[0].shippingAddress.firstName .toString() .substring(10) + ' ' + - widget.orderModel.shippingAddress.lastName + model.orderListModel[0].shippingAddress.lastName .toString() .substring(9), style: TextStyle( @@ -141,19 +148,19 @@ class _OrderDetailsPageState extends State { Container( margin: EdgeInsets.fromLTRB(10.0, 5.0, 1.0, 5.0), child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - widget.orderModel.shippingAddress.address1 - .toString() - .substring(9), - style: TextStyle( - fontSize: 10.0, - fontWeight: FontWeight.bold, - color: Colors.grey, - ), - ),] - ), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + model.orderListModel[0].shippingAddress.address1 + .toString() + .substring(9), + style: TextStyle( + fontSize: 10.0, + fontWeight: FontWeight.bold, + color: Colors.grey, + ), + ), + ]), ), Container( margin: EdgeInsets.fromLTRB(10.0, 5.0, 1.0, 5.0), @@ -161,14 +168,15 @@ class _OrderDetailsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - widget.orderModel.shippingAddress.address2 + model.orderListModel[0].shippingAddress.address2 .toString() .substring(9) + ' ' + - widget.orderModel.shippingAddress.country + model.orderListModel[0].shippingAddress.country .toString() + ' ' + - widget.orderModel.shippingAddress.zipPostalCode + model.orderListModel[0].shippingAddress + .zipPostalCode .toString(), style: TextStyle( fontSize: 10.0, @@ -191,7 +199,7 @@ class _OrderDetailsPageState extends State { Container( margin: EdgeInsets.only(top: 5.0, bottom: 5.0), child: Text( - widget.orderModel.shippingAddress.phoneNumber + model.orderListModel[0].shippingAddress.phoneNumber .toString(), style: TextStyle( fontSize: 15.0, @@ -230,7 +238,8 @@ class _OrderDetailsPageState extends State { ), Container( child: flutterImage.Image.asset( - widget.orderModel.shippingRateComputationMethodSystemName != + model.orderListModel[0] + .shippingRateComputationMethodSystemName != "Shipping.Aramex" ? "assets/images/pharmacy_module/payment/LogoParmacyGreen.png" : "assets/images/pharmacy_module/payment/aramex_shipping_logo.png", @@ -282,7 +291,9 @@ class _OrderDetailsPageState extends State { Container( margin: EdgeInsets.only(bottom: 10.0, top: 10.0), child: Text( - widget.orderModel.paymentName.toString().substring(12), + model.orderListModel[0].paymentName + .toString() + .substring(12), style: TextStyle( fontSize: 13.0, fontWeight: FontWeight.bold, @@ -318,23 +329,40 @@ class _OrderDetailsPageState extends State { scrollDirection: Axis.vertical, shrinkWrap: true, physics: ScrollPhysics(), - itemCount:widget.orderModel.orderItems.length, - itemBuilder: (context, index){ - return Container( - child: productTile(productName: widget.orderModel.orderItems[index].product.name.toString(), - productPrice: widget.orderModel.orderItems[index].product.price.toString(), - productRate: widget.orderModel.orderItems[index].product.approvedRatingSum.toDouble(), - productReviews:widget.orderModel.orderItems[index].product.approvedTotalReviews, - totalPrice: "${(widget.orderModel.orderItems[index].product.price - * widget.orderModel.orderItems[index].quantity).toStringAsFixed(2)}", - qyt: widget.orderModel.orderItems[index].quantity.toString(), - isOrderDetails:true, - imgs: widget.orderModel.orderItems[index].product.images != null && - widget.orderModel.orderItems[index].product.images.length != 0 - ? widget.orderModel.orderItems[index].product.images [0].src.toString() - : null, - status: widget.orderModel.orderStatusId, - product: widget.orderModel.orderItems[index].product, + itemCount: model.orderListModel[0].orderItems.length, + itemBuilder: (context, index) { + return Container( + child: productTile( + productName: model + .orderListModel[0].orderItems[index].product.name + .toString(), + productPrice: model + .orderListModel[0].orderItems[index].product.price + .toString(), + productRate: model.orderListModel[0].orderItems[index] + .product.approvedRatingSum + .toDouble(), + productReviews: model.orderListModel[0] + .orderItems[index].product.approvedTotalReviews, + totalPrice: + "${(model.orderListModel[0].orderItems[index].product.price * model.orderListModel[0].orderItems[index].quantity).toStringAsFixed(2)}", + qyt: model + .orderListModel[0].orderItems[index].quantity + .toString(), + isOrderDetails: true, + imgs: model.orderListModel[0].orderItems[index] + .product.images != + null && + model.orderListModel[0].orderItems[index] + .product.images.length != + 0 + ? model.orderListModel[0].orderItems[index] + .product.images[0].src + .toString() + : null, + status: model.orderListModel[0].orderStatusId, + product: + model.orderListModel[0].orderItems[index].product, ), ); }), @@ -383,7 +411,8 @@ class _OrderDetailsPageState extends State { ), ), Text( - widget.orderModel.orderSubtotalExclTax.toString(), + model.orderListModel[0].orderSubtotalExclTax + .toString(), style: TextStyle( fontSize: 13.0, ), @@ -421,7 +450,8 @@ class _OrderDetailsPageState extends State { ), ), Text( - widget.orderModel.orderShippingExclTax.toString(), + model.orderListModel[0].orderShippingExclTax + .toString(), style: TextStyle( fontSize: 13.0, ), @@ -459,7 +489,7 @@ class _OrderDetailsPageState extends State { ), ), Text( - widget.orderModel.orderTax.toString(), + model.orderListModel[0].orderTax.toString(), style: TextStyle( fontSize: 13.0, ), @@ -497,7 +527,7 @@ class _OrderDetailsPageState extends State { ), ), Text( - widget.orderModel.orderTotal.toString(), + model.orderListModel[0].orderTotal.toString(), style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, @@ -508,10 +538,10 @@ class _OrderDetailsPageState extends State { ), ], ), - widget.orderModel.orderStatusId == 10 + model.orderListModel[0].orderStatusId == 10 ? InkWell( onTap: () { - model.makeOrder(); + model.makeOrder(); }, child: Container( // margin: EdgeInsets.only(top: 20.0), @@ -543,8 +573,8 @@ class _OrderDetailsPageState extends State { isCancel ? InkWell( onTap: () { - presentConfirmDialog(model, - widget.orderModel.id); //(widget.orderModel.id)); + presentConfirmDialog(model, widget.orderModel.id); + // model.orderListModel[0].id//(widget.orderModel.id)); // }, child: Container( @@ -563,6 +593,29 @@ class _OrderDetailsPageState extends State { ), ) : Container(), + isActiveDelivery + ? InkWell( + onTap: () { + // Navigator.push( + // context, + // MaterialPageRoute(builder: (context) => TrackDriver(order: widget.orderModel), + // )); + }, + child: Container( + height: 50.0, + color: Colors.transparent, + child: Center( + child: Text( + TranslationBase.of(context).trackDeliveryDriver, + style: TextStyle( + color: Colors.green[900], + fontWeight: FontWeight.normal, + decoration: TextDecoration.none), + ), + ), + ), + ) + : Container(), ], ), ), @@ -630,6 +683,7 @@ class _OrderDetailsPageState extends State { context, MaterialPageRoute( builder: (context) => OrderPage( +// customerID: model.ordersList[0].customerId.toString() customerID: widget.orderModel.customerId.toString())), ); }), diff --git a/lib/pages/pharmacy/order/TrackDriver.dart b/lib/pages/pharmacy/order/TrackDriver.dart new file mode 100644 index 00000000..b9a8056f --- /dev/null +++ b/lib/pages/pharmacy/order/TrackDriver.dart @@ -0,0 +1,211 @@ +import 'dart:async'; + +import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/order_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_polyline_points/flutter_polyline_points.dart'; +import 'package:google_maps_flutter/google_maps_flutter.dart'; +import 'package:location/location.dart'; + + +class TrackDriver extends StatefulWidget { + final OrderModel order; + TrackDriver({this.order}); + + @override + State createState() => _TrackDriverState(); +} + +class _TrackDriverState extends State { + OrderModel _order; + + Completer _controller = Completer(); + + + double CAMERA_ZOOM = 16; + double CAMERA_TILT = 0; + double CAMERA_BEARING = 30; + LatLng SOURCE_LOCATION = null; + LatLng DEST_LOCATION = null; + + // for my drawn routes on the map + Set _polylines = Set(); + List polylineCoordinates = []; + PolylinePoints polylinePoints; + + Set _markers = Set(); + + BitmapDescriptor sourceIcon; // for my custom marker pins + BitmapDescriptor destinationIcon; // for my custom marker pins + Location location;// wrapper around the location API + + @override + void initState() { + _order = widget.order; + DEST_LOCATION = _order.shippingAddress.getLocation(); + location = new Location(); + polylinePoints = PolylinePoints(); + setSourceAndDestinationIcons(); + } + + @override + Widget build(BuildContext context) { + return new Scaffold( + body: GoogleMap( + myLocationEnabled: true, + compassEnabled: true, + markers: _markers, + polylines: _polylines, + mapType: MapType.normal, + initialCameraPosition: _orderDeliveryLocationCamera(), + onMapCreated: (GoogleMapController controller) { + _controller.complete(controller); + showPinsOnMap(); + }, + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _goToDriver, + label: Text('To the lake!'), + icon: Icon(Icons.directions_boat), + ), + ); + } + + + void setSourceAndDestinationIcons() async { + sourceIcon = await BitmapDescriptor.fromAssetImage( + ImageConfiguration(devicePixelRatio: 2.5), + 'assets/images/map_markers/source_map_marker.png'); + + destinationIcon = await BitmapDescriptor.fromAssetImage( + ImageConfiguration(devicePixelRatio: 2.5), + 'assets/images/map_markers/destination_map_marker.png'); + } + + CameraPosition _orderDeliveryLocationCamera(){ + + final CameraPosition orderDeliveryLocCamera = CameraPosition( + bearing: CAMERA_BEARING, + target: DEST_LOCATION, + tilt: CAMERA_TILT, + zoom: CAMERA_ZOOM); + return orderDeliveryLocCamera; + } + + CameraPosition _driverLocationCamera(){ + final CameraPosition driverLocCamera = CameraPosition( + bearing: CAMERA_BEARING, + target: SOURCE_LOCATION, + tilt: CAMERA_TILT, + zoom: CAMERA_ZOOM); + return driverLocCamera; + } + + + Future _goToOrderDeliveryLocation() async { + final GoogleMapController controller = await _controller.future; + final CameraPosition orderDeliveryLocCamera = _orderDeliveryLocationCamera(); + controller.animateCamera(CameraUpdate.newCameraPosition(orderDeliveryLocCamera)); + } + + Future _goToDriver() async { + final GoogleMapController controller = await _controller.future; + final CameraPosition driverLocCamera = _driverLocationCamera(); + controller.animateCamera(CameraUpdate.newCameraPosition(driverLocCamera)); + } + + + Future _fitCameraBetweenBothPoints() async { + final GoogleMapController controller = await _controller.future; + final CameraPosition driverLocCamera = CameraPosition( + bearing: CAMERA_BEARING, + target: SOURCE_LOCATION, + tilt: CAMERA_TILT, + zoom: CAMERA_ZOOM); + controller.animateCamera(CameraUpdate.newCameraPosition(driverLocCamera)); + } + + void showPinsOnMap() { + // source pin + if(SOURCE_LOCATION != null){ + setState(() { + var pinPosition = SOURCE_LOCATION; + _markers.add(Marker( + markerId: MarkerId('sourcePin'), + position: pinPosition, + icon: sourceIcon + )); + }); + } + + // destination pin + if(DEST_LOCATION != null){ + setState(() { + var destPosition = DEST_LOCATION; + _markers.add(Marker( + markerId: MarkerId('destPin'), + position: destPosition, + icon: destinationIcon + )); + }); + } + // set the route lines on the map from source to destination + // for more info follow this tutorial + // drawRoute(); + } + + void updatePinOnMap() async { + // create a new CameraPosition instance + // every time the location changes, so the camera + // follows the pin as it moves with an animation + CameraPosition cPosition = CameraPosition( + zoom: CAMERA_ZOOM, + tilt: CAMERA_TILT, + bearing: CAMERA_BEARING, + target: SOURCE_LOCATION, + ); + final GoogleMapController controller = await _controller.future; + controller.animateCamera(CameraUpdate.newCameraPosition(cPosition)); + // do this inside the setState() so Flutter gets notified + // that a widget update is due + setState(() { + // updated position + var pinPosition = SOURCE_LOCATION; + + // the trick is to remove the marker (by id) + // and add it again at the updated location + _markers.removeWhere((m) => m.markerId.value == 'sourcePin'); + _markers.add(Marker( + markerId: MarkerId('sourcePin'), + position: pinPosition, // updated position + icon: sourceIcon + )); + }); + } + + void drawRoute() async { + return; // Ignore draw Route + + List result = await polylinePoints.getRouteBetweenCoordinates( + GOOGLE_API_KEY, + SOURCE_LOCATION.latitude, + SOURCE_LOCATION.longitude, + DEST_LOCATION.latitude, + DEST_LOCATION.longitude); + if(result.isNotEmpty){ + result.forEach((PointLatLng point){ + polylineCoordinates.add( + LatLng(point.latitude,point.longitude) + ); + }); + setState(() { + _polylines.add(Polyline( + width: 5, // set the width of the polylines + polylineId: PolylineId('poly'), + color: Color.fromARGB(255, 40, 122, 198), + points: polylineCoordinates + )); + }); + } + } +} \ No newline at end of file diff --git a/lib/pages/pharmacy/profile/profile.dart b/lib/pages/pharmacy/profile/profile.dart index ba742179..fb1e1c2a 100644 --- a/lib/pages/pharmacy/profile/profile.dart +++ b/lib/pages/pharmacy/profile/profile.dart @@ -6,6 +6,8 @@ import 'package:diplomaticquarterapp/pages/ContactUs/findus/findus_page.dart'; import 'package:diplomaticquarterapp/pages/DrawerPages/family/my-family.dart'; import 'package:diplomaticquarterapp/pages/login/welcome.dart'; import 'package:diplomaticquarterapp/pages/medical/prescriptions/prescriptions_home_page.dart'; +import 'package:diplomaticquarterapp/pages/pharmacies/compare.dart'; +import 'package:diplomaticquarterapp/pages/pharmacies/my_reviews.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/lakum-main-page.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/lakum-terms-conditions-page.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart'; @@ -27,7 +29,8 @@ import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/my_reviews.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/compare.dart'; -dynamic languageID ; +dynamic languageID; + class PharmacyProfilePage extends StatefulWidget { @override _ProfilePageState createState() => _ProfilePageState(); @@ -44,40 +47,43 @@ class _ProfilePageState extends State { String lastName, mobileNo, identificationNo; int languageId; - _ProfilePageState({this.customerId }); + _ProfilePageState({this.customerId}); getLanguageID() async { languageID = await sharedPref.getString(APP_LANGUAGE); } + getCustomer() async { String custID; custID = await sharedPref.getString(PHARMACY_CUSTOMER_ID); setState(() { customerId = custID; }); - print("customer Id is"+ customerId); + print("customer Id is" + customerId); return customerId; } getUser() async { var userData = await sharedPref.getObject(USER_PROFILE); - if (userData != null){ user = AuthenticatedUser.fromJson(userData); - setState(() { - firstName = user.firstName.toString(); - print("this is user" + user.firstName.toString()); - print("this is user" + user.firstNameN.toString()); - }); - } else{ - if(userData == null){ - Navigator.push(context, - MaterialPageRoute(builder: (context) => - WelcomeLogin()), + if (userData != null) { + user = AuthenticatedUser.fromJson(userData); + setState(() { + firstName = user.firstName.toString(); + print("this is user" + user.firstName.toString()); + print("this is user" + user.firstNameN.toString()); + }); + } else { + if (userData == null) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => WelcomeLogin()), ); } } // this.isLogin = user != null; } + void initState() { getCustomer(); getLanguageID(); @@ -88,539 +94,566 @@ class _ProfilePageState extends State { @override Widget build(BuildContext context) { return BaseView( - onModelReady: (model) => model.getOrder(customerId, page_id), - builder: (_, model, wi) => AppScaffold( - appBarTitle: TranslationBase.of(context).myAccount, - isShowAppBar:false, - isShowDecPage: false, - isPharmacy: true, - body: user != null ? Container( - child: SingleChildScrollView( - child: Column( - children: [ - Container( - child: Row( - children: [ - Container( - padding: EdgeInsets.only( - top: 20.0, - left: 10.0, - right: 10.0, - bottom: 10.0, - ), - child: LargeAvatar( - name: "profile", - url: '', - ), - ), - Container( + onModelReady: (model) => model.getOrder(customerId, page_id), + builder: (_, model, wi) => AppScaffold( + appBarTitle: TranslationBase.of(context).myAccount, + isShowAppBar: false, + isShowDecPage: false, + isPharmacy: true, + body: user != null + ? Container( + child: SingleChildScrollView( child: Column( - children: [ - Text( - TranslationBase.of(context).welcome, - style: TextStyle(fontSize: 14.0, - fontWeight: FontWeight.bold, - color:Colors.grey + children: [ + Container( + child: Row( + children: [ + Container( + child: Row( + children: [ + Container( + padding: EdgeInsets.only( + top: 20.0, + left: 10.0, + right: 10.0, + bottom: 10.0, + ), + child: LargeAvatar( + name: "profile", + url: '', + ), + ), + Text( + languageID == "ar" + ? user.firstNameN.toString() + + " " + + user.lastNameN.toString() + : user.firstName.toString() + + " " + + user.lastName.toString(), + style: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.bold), + ), + ], + ), + ) + ], ), ), - Text( - languageID == "ar" - ? user.firstNameN.toString()+ " " + user.lastNameN.toString() - : user.firstName.toString()+ " " + user.lastName.toString(), - style: TextStyle( - fontSize: 14.0, fontWeight: FontWeight.bold), + Divider( + color: Colors.grey[350], + height: 20, + thickness: 5, + indent: 0, + endIndent: 0, ), - ], - ), - - ) - ], - ), - ), - Divider( - color: Colors.grey[350], - height: 20, - thickness: 5, - indent: 0, - endIndent: 0, - ), - SizedBox( - height: 15, - ), - Container( - child: Row( - children: [ - Expanded( - child: InkWell( - onTap: () { - if(customerId == null){ - AppToast.showErrorToast(message: "Customer not found"); - return; - } - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => OrderPage(customerID: customerId))); - }, - child: Column( + SizedBox( + height: 15, + ), + Container( + child: Row( children: [ + Expanded( + child: InkWell( + onTap: () { + if (customerId == null) { + AppToast.showErrorToast( + message: "Customer not found"); + return; + } + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => OrderPage( + customerID: customerId))); + }, + child: Column( + children: [ // Image(image: AssetImage('assets/images/pharmacy/orders_icon.svg')), - SvgPicture.asset( - 'assets/images/pharmacy/orders_icon.svg', - width: 50, - height: 50, - ), - SizedBox( - height: 5, - ), - Text( - TranslationBase.of(context).orders, - style: TextStyle( - fontSize: 13.0, - fontWeight: FontWeight.bold, + SvgPicture.asset( + 'assets/images/pharmacy/orders_icon.svg', + width: 50, + height: 50, + ), + SizedBox( + height: 5, + ), + Text( + TranslationBase.of(context).orders, + style: TextStyle( + fontSize: 13.0, + fontWeight: FontWeight.bold, + ), + ), + ], + ), ), ), - ], - ), - ), - ), - Expanded( - child: InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => LakumMainPage())); - }, - child: Column( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/lakum_icon.svg', - width: 50, - height: 50, - ), - SizedBox( - height: 5, - ), - Text( - TranslationBase.of(context).lakum, - style: TextStyle( - fontSize: 13.0, fontWeight: FontWeight.bold), + Expanded( + child: InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + LakumMainPage())); + }, + child: Column( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/lakum_icon.svg', + width: 50, + height: 50, + ), + SizedBox( + height: 5, + ), + Text( + TranslationBase.of(context).lakum, + style: TextStyle( + fontSize: 13.0, + fontWeight: FontWeight.bold), + ), + ], + ), + ), ), - ], - ), - ), - ), - Expanded( - child: InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => WishlistPage())); - }, - child: Column( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/wishlist_icon.svg', - width: 50, - height: 50, - - ),SizedBox( - height: 5, + Expanded( + child: InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + WishlistPage())); + }, + child: Column( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/wishlist_icon.svg', + width: 50, + height: 50, + ), + SizedBox( + height: 5, + ), + Text( + TranslationBase.of(context).wishlist, + style: TextStyle( + fontSize: 13.0, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), ), - Text( - TranslationBase.of(context).wishlist, - style: TextStyle( - fontSize: 13.0, - fontWeight: FontWeight.bold, + Expanded( + child: InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + MyReviewsPage())); + }, + child: Column( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/review_icon.svg', + width: 50, + height: 50, + ), + SizedBox( + height: 5, + ), + Text( + TranslationBase.of(context).reviews, + style: TextStyle( + fontSize: 13.0, + fontWeight: FontWeight.bold, + ), + ), + ], + ), ), ), ], - ), - ), - ), - Expanded( - child: InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MyReviewsPage())); - },child: Column( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/review_icon.svg', - width: 50, - height: 50, - ), - SizedBox( - height: 5, - ), - Text( - TranslationBase.of(context).reviews, - style: TextStyle( - fontSize: 13.0, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - ), - ), - ], - )), - SizedBox( - height: 15, - ), - Divider( - color: Colors.grey[350], - height: 20, - thickness: 5, - indent: 0, - endIndent: 0, - ), - SizedBox( - height: 10, - ), - Container( - padding: EdgeInsets.only(left: 10.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - TranslationBase.of(context).myAccount, - style: TextStyle( - fontSize: 16.0, fontWeight: FontWeight.bold), - ), - SizedBox( - height: 10, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => HomePrescriptionsPage())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/my_prescription_icon.svg', - width: 28, - height: 28, - ), - SizedBox( - width: 15, - ), - Text( - TranslationBase.of(context).myPrescription, - style: TextStyle( - fontSize: 13.0, - ), - ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ComparePage())); - }, - child: Row( - children: [ - Image.asset('assets/images/pharmacy/compare.png', - width: 35, height: 35), - SizedBox( - width: 15, - ), - Text( - TranslationBase.of(context).compare, - style: TextStyle( - fontSize: 13.0, - ), - ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => HomePrescriptionsPage())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/medication_refill_icon.svg', - width: 30, - height: 30, - ), + )), SizedBox( - width: 20, - ), - Text( - TranslationBase.of(context).medicationsRefill, - style: TextStyle( - fontSize: 13.0, - ), + height: 15, ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MyFamily())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/my_family_icon.svg', - width: 20, + Divider( + color: Colors.grey[350], height: 20, + thickness: 5, + indent: 0, + endIndent: 0, ), SizedBox( - width: 20, - ), - Text( - TranslationBase.of(context).family, - style: TextStyle( - fontSize: 13.0, - ), - ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PharmacyAddressesPage())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/shipping_addresses_icon.svg', - width: 30, - height: 30, - ), - SizedBox( - width: 20, - ), - Text( - TranslationBase.of(context).shippingAddresses, - style: TextStyle( - fontSize: 13.0, - ), - ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PharmacyTermsConditions())); - }, - child: Row( - children: [ - Image.asset('assets/images/pharmacy/terms.png', - width: 25, - height: 25, - ), - - SizedBox( - width: 10, - ), - Text( - TranslationBase.of(context).conditionsHMG, - style: TextStyle( - fontSize: 13.0, - ), - ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => LakumTermsConditions(this.identificationNo, this.firstName, this.lastName, - this.mobileNo, this.languageId))); - }, - child: Row( - children: [ - Image.asset('assets/images/pharmacy/terms.png', - width: 25, - height: 25, + height: 10, ), + Container( + padding: EdgeInsets.only(left: 10.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + TranslationBase.of(context).myAccount, + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold), + ), + SizedBox( + height: 10, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + HomePrescriptionsPage())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/my_prescription_icon.svg', + width: 28, + height: 28, + ), + SizedBox( + width: 15, + ), + Text( + TranslationBase.of(context) + .myPrescription, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + ComparePage())); + }, + child: Row( + children: [ + Image.asset( + 'assets/images/pharmacy/compare.png', + width: 35, + height: 35), + SizedBox( + width: 15, + ), + Text( + TranslationBase.of(context).compare, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + HomePrescriptionsPage())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/medication_refill_icon.svg', + width: 30, + height: 30, + ), + SizedBox( + width: 20, + ), + Text( + TranslationBase.of(context) + .medicationsRefill, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + MyFamily())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/my_family_icon.svg', + width: 20, + height: 20, + ), + SizedBox( + width: 20, + ), + Text( + TranslationBase.of(context).family, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + PharmacyAddressesPage())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/shipping_addresses_icon.svg', + width: 30, + height: 30, + ), + SizedBox( + width: 20, + ), + Text( + TranslationBase.of(context) + .shippingAddresses, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + PharmacyTermsConditions())); + }, + child: Row( + children: [ + Image.asset( + 'assets/images/pharmacy/terms.png', + width: 25, + height: 25, + ), + SizedBox( + width: 10, + ), + Text( + TranslationBase.of(context) + .conditionsHMG, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + LakumTermsConditions( + this.identificationNo, + this.firstName, + this.lastName, + this.mobileNo, + this.languageId))); + }, + child: Row( + children: [ + Image.asset( + 'assets/images/pharmacy/terms.png', + width: 25, + height: 25, + ), // IconButton(icon: Icon(Icons.error_outline), iconSize: 30, // color: Colors.black,), - SizedBox( - width: 10, - ), - Text( - TranslationBase.of(context).conditions, - style: TextStyle( - fontSize: 13.0, + SizedBox( + width: 10, + ), + Text( + TranslationBase.of(context) + .conditions, + style: TextStyle( + fontSize: 13.0, + ), + ), + ], + ), + ), + ], ), ), - ], - ), - ), - ], - ), - ), - SizedBox( - height: 10, - ), - Divider( - color: Colors.grey[350], - height: 20, - thickness: 5, - indent: 0, - endIndent: 0, - ), - SizedBox( - height: 10, - ), - Container( - padding: EdgeInsets.only(left: 10.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - TranslationBase.of(context).reachUs, - style: TextStyle( - fontSize: 16.0, fontWeight: FontWeight.bold), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => LiveChatPage())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/contact_us_icon.svg', - width: 20, - height: 20, - ), SizedBox( - width: 20, - ), - Text( - TranslationBase.of(context).contactUs, - style: TextStyle(fontSize: 13.0), + height: 10, ), - ], - ), - ), - SizedBox( - height: 5, - ), - Divider( - color: Colors.grey, - height: 20, - ), - InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => FindUsPage())); - }, - child: Row( - children: [ - SvgPicture.asset( - 'assets/images/pharmacy/our_locations_icon.svg', - width: 30, - height: 30, + Divider( + color: Colors.grey[350], + height: 20, + thickness: 5, + indent: 0, + endIndent: 0, ), SizedBox( - width: 20, - ), - Text( - TranslationBase.of(context).ourLocations, - style: TextStyle(fontSize: 13.0), + height: 10, ), + Container( + padding: EdgeInsets.only(left: 10.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + TranslationBase.of(context).reachUs, + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + LiveChatPage())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/contact_us_icon.svg', + width: 20, + height: 20, + ), + SizedBox( + width: 20, + ), + Text( + TranslationBase.of(context).contactUs, + style: TextStyle(fontSize: 13.0), + ), + ], + ), + ), + SizedBox( + height: 5, + ), + Divider( + color: Colors.grey, + height: 20, + ), + InkWell( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + FindUsPage())); + }, + child: Row( + children: [ + SvgPicture.asset( + 'assets/images/pharmacy/our_locations_icon.svg', + width: 30, + height: 30, + ), + SizedBox( + width: 20, + ), + Text( + TranslationBase.of(context) + .ourLocations, + style: TextStyle(fontSize: 13.0), + ), + ], + ), + ) + ], + ), + ) ], ), - ) - ], - ), - ) - ], - ), - ), - ) : Container(), - )); - }} - - - - + ), + ) + : Container(), + )); + } +} diff --git a/lib/services/pharmacy_services/orderDetails_service.dart b/lib/services/pharmacy_services/orderDetails_service.dart index a3bb9976..b8ea8214 100644 --- a/lib/services/pharmacy_services/orderDetails_service.dart +++ b/lib/services/pharmacy_services/orderDetails_service.dart @@ -16,20 +16,20 @@ class OrderDetailsService extends BaseService{ AuthenticatedUser authUser = new AuthenticatedUser(); AuthProvider authProvider = new AuthProvider(); - - List get orderDetails => orderDetails; +// String url =""; +// List get orderDetails => ordeDetails; List _orderList = List(); List get orderList => _orderList; - Future getOrderDetails(orderId) async { - print("step 2" + orderId); + Future getOrderDetails(OrderId) async { hasError = false; - await baseAppClient.getPharmacy(GET_ORDER_DETAILS+orderId, + await baseAppClient.getPharmacy(GET_ORDER_DETAILS+OrderId, onSuccess: (dynamic response, int statusCode) { _orderList.clear(); response['orders'].forEach((item) { _orderList.add(OrderModel.fromJson(item)); + print(response); }); }, onFailure: (String error, int statusCode) { hasError = true; diff --git a/lib/services/pharmacy_services/order_service.dart b/lib/services/pharmacy_services/order_service.dart index e426b801..3f1ece78 100644 --- a/lib/services/pharmacy_services/order_service.dart +++ b/lib/services/pharmacy_services/order_service.dart @@ -5,7 +5,7 @@ import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.da import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart'; import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:flutter/material.dart'; -import 'package:diplomaticquarterapp/core/model/pharmacies/order_model.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/orders_model.dart'; class OrderService extends BaseService{ @@ -14,21 +14,23 @@ class OrderService extends BaseService{ AuthenticatedUser authUser = new AuthenticatedUser(); AuthProvider authProvider = new AuthProvider(); - List _orderList = List(); - List get orderList => _orderList; + List _orderList = List(); + List get orderList => _orderList; String url =""; Future getOrder(customerId, pageId) async { hasError = false; // url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=1&limit=200&customer_id=1367368"; - url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=$pageId&limit=200&customer_id=$customerId"; + // url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=$pageId&limit=200&customer_id=$customerId"; + url =GET_ORDER+"customer=1&fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc,product_count,can_cancel,can_refund&page=$pageId&limit=200&customer_id=$customerId"; print(url); await baseAppClient.getPharmacy(url, onSuccess: (dynamic response, int statusCode) { _orderList.clear(); + response['orders'].forEach((item) { - _orderList.add(OrderModel.fromJson(item)); + _orderList.add(Orders.fromJson(item)); }); print(_orderList.length); print(response); @@ -39,25 +41,27 @@ class OrderService extends BaseService{ } - Future getProductReview(orderId) async { - print("step 1"); - hasError = false; - url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=1&limit=200&customer_id=1367368"; -// url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=$page_id&limit=200&customer_id=$custmerId"; - print(url); - await baseAppClient.getPharmacy(url, - onSuccess: (dynamic response, int statusCode) { - _orderList.clear(); - response['orders'].forEach((item) { - _orderList.add(OrderModel.fromJson(item)); - }); - print(_orderList.length); - print(response); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - }); - } +// Future getProductReview(orderId) async { +// print("step 1"); +// hasError = false; +// url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=1&limit=200&customer_id=1367368"; +//// url =GET_ORDER+"customer=1,fields=id,order_total,order_status,order_statusn,order_status_id,created_on_utc&page=$page_id&limit=200&customer_id=$custmerId"; +// print(url); +// await baseAppClient.getPharmacy(url, +// onSuccess: (dynamic response, int statusCode) { +// _orderList.clear(); +// response['orders'].forEach((item) { +// _orderList.add(OrderModel.fromJson(item)); +// }); +// print(_orderList.length); +// print(response); +// }, onFailure: (String error, int statusCode) { +// hasError = true; +// super.error = error; +// }); +// } + + // Future getOrder(BuildContext context ) async { // // if (await this.sharedPref.getObject(USER_PROFILE) != null) { diff --git a/lib/uitl/HMGNetworkConnectivity.dart b/lib/uitl/HMGNetworkConnectivity.dart index 228edf93..c4044573 100644 --- a/lib/uitl/HMGNetworkConnectivity.dart +++ b/lib/uitl/HMGNetworkConnectivity.dart @@ -47,18 +47,28 @@ class HMGNetworkConnectivity { void confirmFromUser() { TranslationBase translator = TranslationBase.of(context); - ConfirmDialog( - context: context, - confirmMessage: translator.wantToConnectWithHmgNetwork, - okText: translator.yes, - okFunction: () { - ConfirmDialog.closeAlertDialog(context); - callBack(); - }, - cancelText: translator.no, - cancelFunction: () { - ConfirmDialog.closeAlertDialog(context); - }).showAlertDialog(context); + + void doIt() { + ConfirmDialog( + context: context, + confirmMessage: translator.wantToConnectWithHmgNetwork, + okText: translator.yes, + okFunction: () { + ConfirmDialog.closeAlertDialog(context); + callBack(); + }, + cancelText: translator.no, + cancelFunction: () { + ConfirmDialog.closeAlertDialog(context); + }).showAlertDialog(context); + } + + if (Platform.isAndroid) + Wifi.list(SSID).then((value) { + if (!value.indexWhere((element) => element.ssid == SSID).isNegative) doIt(); + }); + else + doIt(); } void showFailDailog(String message) { diff --git a/lib/uitl/date_uitl.dart b/lib/uitl/date_uitl.dart index 460a4066..9f959885 100644 --- a/lib/uitl/date_uitl.dart +++ b/lib/uitl/date_uitl.dart @@ -4,7 +4,7 @@ import 'package:intl/intl.dart'; class DateUtil { /// convert String To Date function /// [date] String we want to convert - static DateTime convertStringToDate(String date) { + static DateTime convertStringToDate(String date) { // /Date(1585774800000+0300)/ if (date != null) { const start = "/Date("; const end = "+0300)"; diff --git a/lib/uitl/translations_delegate_base.dart b/lib/uitl/translations_delegate_base.dart index 06c6628c..0285f512 100644 --- a/lib/uitl/translations_delegate_base.dart +++ b/lib/uitl/translations_delegate_base.dart @@ -272,6 +272,7 @@ class TranslationBase { localizedValues['pharmaciesList'][locale.languageCode]; String get description => localizedValues['description'][locale.languageCode]; + String get howToUse => localizedValues['howToUse'][locale.languageCode]; String get price => localizedValues['price'][locale.languageCode]; @@ -577,6 +578,8 @@ class TranslationBase { localizedValues['Prescriptions'][locale.languageCode]; String get history => localizedValues['History'][locale.languageCode]; String get orderNo => localizedValues['OrderNo'][locale.languageCode]; + String get trackDeliveryDriver => + localizedValues['trackDeliveryDriver'][locale.languageCode]; String get orderDetails => localizedValues['OrderDetails'][locale.languageCode]; String get vitalSign => localizedValues['VitalSign'][locale.languageCode]; @@ -608,6 +611,8 @@ class TranslationBase { localizedValues['UpdateSuccessfully'][locale.languageCode]; String get emailSentSuccessfully => localizedValues['EmailSentSuccessfully'][locale.languageCode]; + String get EmailSentError => + localizedValues['EmailSentError'][locale.languageCode]; String get checkVaccineAvailability => localizedValues['CHECK_VACCINE_AVAILABILITY'][locale.languageCode]; String get myVaccinesAvailability => @@ -640,6 +645,7 @@ class TranslationBase { localizedValues['SelectFamilyPatientName'][locale.languageCode]; String get selectHospital => localizedValues['SelectHospital'][locale.languageCode]; + String get selectCity => localizedValues['selectCity'][locale.languageCode]; String get myAccount => localizedValues['MyAccount'][locale.languageCode]; String get otherAccount => localizedValues['OtherAccount'][locale.languageCode]; @@ -816,6 +822,7 @@ class TranslationBase { String get recentlyViewed => localizedValues['recentlyViewed'][locale.languageCode]; String get bestSellers => localizedValues['bestSellers'][locale.languageCode]; + String get recommended => localizedValues['recommended'][locale.languageCode]; String get deleteAllItems => localizedValues['deleteAllItems'][locale.languageCode]; String get selectAddress => @@ -1261,6 +1268,9 @@ class TranslationBase { String get pharmacyServiceTermsCondition => localizedValues['pharmacyServiceTermsCondition'][locale.languageCode]; + String get recordDeleted => + localizedValues['recordDeleted'][locale.languageCode]; + String get referralStatus => localizedValues['referralStatus'][locale.languageCode]; String get referralDate => @@ -1321,6 +1331,43 @@ class TranslationBase { String get instructionAgree => localizedValues['instructionAgree'][locale.languageCode]; String get reqId => localizedValues['reqId'][locale.languageCode]; + String get ordersLog => + localizedValues['RRT-orders-log'][locale.languageCode]; + String get bloodSugar => localizedValues['blood-sugar'][locale.languageCode]; + String get myTracker => localizedValues['my-tracker'][locale.languageCode]; + String get weekly => localizedValues['weekly'][locale.languageCode]; + String get monthlyT => localizedValues['monthly'][locale.languageCode]; + String get yearly => localizedValues['yearly'][locale.languageCode]; + String get measured => localizedValues['measured'][locale.languageCode]; + String get sugarAdd => localizedValues['sugar-add'][locale.languageCode]; + String get other => localizedValues['other'][locale.languageCode]; + String get measureUnit => + localizedValues['measure-unit'][locale.languageCode]; + String get measureTime => + localizedValues['measure-time'][locale.languageCode]; + String get update => localizedValues['update'][locale.languageCode]; + + String get covid19_driveThrueTest => + localizedValues['covid19_driveThrueTest'][locale.languageCode]; + String get eReferral => localizedValues['E-Referral'][locale.languageCode]; + + String get msg_email_address_up_to_date => + localizedValues["msg_email_address_up_to_date"][locale.languageCode]; + String get updateEmailMsg => + localizedValues["update-email-msg"][locale.languageCode]; + + String get addNewChild => + localizedValues["add-new-child"][locale.languageCode]; + String get sendChildEmailMsg => + localizedValues["send-child-email-msg"][locale.languageCode]; + String get vaccinationAddChildMsg => + localizedValues["vaccination-add-child-msg"][locale.languageCode]; + String get childAddedSuccessfully => + localizedValues["child_added_successfully"][locale.languageCode]; + String get bloodDEnterDesc => + localizedValues["bloodD-enter-desc"][locale.languageCode]; + String get viewTermsConditions => + localizedValues["viewTermsConditions"][locale.languageCode]; } class TranslationBaseDelegate extends LocalizationsDelegate { diff --git a/lib/uitl/utils.dart b/lib/uitl/utils.dart index 58ef9421..b2c52b2b 100644 --- a/lib/uitl/utils.dart +++ b/lib/uitl/utils.dart @@ -4,7 +4,9 @@ import 'dart:typed_data'; import 'package:badges/badges.dart'; import 'package:connectivity/connectivity.dart'; +import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; +import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/pages/Blood/my_balance_page.dart'; import 'package:diplomaticquarterapp/pages/MyAppointments/MyAppointments.dart'; import 'package:diplomaticquarterapp/pages/insurance/insurance_approval_screen.dart'; @@ -26,15 +28,19 @@ import 'package:diplomaticquarterapp/pages/medical/reports/report_home_page.dart import 'package:diplomaticquarterapp/pages/medical/smart_watch_health_data/smart_watch_instructions.dart'; import 'package:diplomaticquarterapp/pages/medical/vital_sign/vital_sign_details_screen.dart'; import 'package:diplomaticquarterapp/pages/vaccine/my_vaccines_screen.dart'; +import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/medical/medical_profile_item.dart'; +import 'package:diplomaticquarterapp/widgets/dialogs/alert_dialog.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../Constants.dart'; import 'app_shared_preferences.dart'; import 'app_toast.dart'; +import 'gif_loader_dialog_utils.dart'; AppSharedPreferences sharedPref = new AppSharedPreferences(); @@ -488,13 +494,25 @@ class Utils { ), )); } - if (projectViewModel.havePrivilege(32)) { + if (projectViewModel.havePrivilege(32) || true) { medical.add(InkWell( - //TODO -// onTap: () { -// Navigator.push( -// context, FadePage(page: DoctorHomePage())); -// }, + onTap: () { + userData().then((userData_){ + if (projectViewModel.isLogin && userData_ != null) { + String patientID = userData_.patientID.toString(); + GifLoaderDialogUtils.showMyDialog(context); + projectViewModel.platformBridge().connectHMGInternetWifi(patientID).then((value) => {GifLoaderDialogUtils.hideDialog(context)}); + } else { + AlertDialogBox( + context: context, + confirmMessage: "Please login with your account first to use this feature", + okText: "OK", + okFunction: () { + AlertDialogBox.closeAlertDialog(context); + }).showAlertDialog(context); + } + }); + }, child: MedicalProfileItem( title: TranslationBase.of(context).internet, imagePath: 'insurance_card_icon.png', @@ -521,6 +539,11 @@ class Utils { } } +Future userData() async { + var userData = AuthenticatedUser.fromJson(await AppSharedPreferences().getObject(MAIN_USER)); + return userData; +} + // extension function that use in iterations(list.. etc) to iterate items and get index and item it self extension IndexedIterable on Iterable { Iterable mapIndexed(T Function(E e, int i) f) { diff --git a/lib/widgets/drawer/app_drawer_widget.dart b/lib/widgets/drawer/app_drawer_widget.dart index 5b8f4d5e..081021cb 100644 --- a/lib/widgets/drawer/app_drawer_widget.dart +++ b/lib/widgets/drawer/app_drawer_widget.dart @@ -416,6 +416,7 @@ class _AppDrawerState extends State { await sharedPref.clear(); this.user = null; Navigator.of(context).pushNamed(HOME); + // projectProvider.platformBridge().unRegisterHmgGeofences(); } login() async { diff --git a/pubspec.yaml b/pubspec.yaml index f49a1cd5..e9c5c00b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -86,6 +86,8 @@ dependencies: # Qr code Scanner TODO fix it # barcode_scanner: ^1.0.1 barcode_scan: any + flutter_polyline_points: ^0.1.0 + location: ^2.3.5 # Qr code Scanner barcode_scan_fix: ^1.0.2 @@ -192,6 +194,7 @@ flutter: # assets: assets: - assets/images/ + - assets/images/map_markers/ - assets/images/pharmacy/ - assets/images/medical/ - assets/images/new-design/