Merge branch 'development_new_design_2.0' of https://gitlab.com/Cloud_Solution/diplomatic-quarter into nov_fixes

merge-requests/502/head
Elham Rababh 4 years ago
commit 4e54349e3b

@ -1631,11 +1631,40 @@ const Map localizedValues = {
"RRTTitle": {"en": "RRT", "ar": "خدمة فريق"}, "RRTTitle": {"en": "RRT", "ar": "خدمة فريق"},
"RRTSubTitle": {"en": "Service", "ar": "الاستجابة السريع"}, "RRTSubTitle": {"en": "Service", "ar": "الاستجابة السريع"},
"transportation": {"en": "Transportation", "ar": "النقل"}, "transportation": {"en": "Transportation", "ar": "النقل"},
"neck": {"en": "Neck", "ar": "رقبه"}, "neck": {"en": "Neck", "ar": "رقبه"},
"waist": {"en": "Waist", "ar": "وسط"}, "waist": {"en": "Waist", "ar": "وسط"},
"hip": {"en": "Hip", "ar": "ورك او نتوء"}, "hip": {"en": "Hip", "ar": "ورك او نتوء"},
"carbsProtin": {"en": "Carbs, Protein and Fat", "ar": "الكربوهيدرات والبروتينات والدهون"}, "carbsProtin": {"en": "Carbs, Protein and Fat", "ar": "الكربوهيدرات والبروتينات والدهون"},
"myCart": {"en": "Cart", "ar": "عربة التسوق"}, "myCart": {"en": "Cart", "ar": "عربة التسوق"},
"browseOffers": {"en": "Browse offers by clinic", "ar": "تصفح العروض حسب العيادة"}, "browseOffers": {"en": "Browse offers by clinic", "ar": "تصفح العروض حسب العيادة"},
"inactiveAct":{"en":"Almost inactive (little or no exercise)","ar":"غير نشط تقريبا (ممارسة الرياضة قليلة أو منعدمة)"},
"light":{"en":"Lightly active (1-3) days per week","ar":"خفيف النشاط (1-3 أيام في الأسبوع)"},
"moderate":{"en":"Moderately active (3-5) days per week)","ar":"معتدل النشاط (3-5 أيام في الأسبوع)"},
"very":{"en":"Very active (6-7) days per week)","ar":"نشط جداُ (6-7 أيام في الأسبوع)"},
"super":{"en":"Super active (very hard exercise)","ar":"عالي النشاط (ممارسة الرياضة الصعبة)"},
"resultCalories": {"en": "Daily intake is (#) calories", "ar": "الإحتياج اليومي (#) سعرة حرارية"},
"bmrDesc": {"en": "Calculates the amount of energy that the persons body expends in a day", "ar": "معدل الأيض القاعدي: هو حساب كمية الطاقة التي يحتاجها الجسم في اليوم الواحد"},
"idealWeightDesc": {"en": "Calculates the ideal body weight based on height, Weight, and Body Size", "ar": "حساب الوزن المثالي والوزن الصحي للجسم على أساس الطول، والوزن ،والجسم"},
"bodyFrame": {"en": "Body Frame Size", "ar": "مقاس هيكل الجسم"},
"bodyFrameSmall": {"en": "Small (fingers overlap)", "ar": "رفيع (الأصابع تتداخل)"},
"bodyFrameMedium": {"en": "Medium (fingers touch)", "ar": "متوسط (الأصابع تتلامس)"},
"bodyFrameLarge": {"en": "Large (fingers don't touch)", "ar": "عريض (الأصابع لا تتلامس)"},
"bodyFatDesc": {"en": "Estimates the total body fat based on the size", "ar": "حساب الدهون في الجسم بناءاً على الحجم"},
"essential":{"en":"The category falls under Essential Fat.","ar":"تندرج تحت فئة دهون أساسية"},
"athlete":{"en":" The category falls under Athlete.","ar":"تندرج تحت فئة دهون جسم رياضي"},
"fitness":{"en":" The category falls under Fitness.","ar":"تندرج تحت فئة دهون جسم صحي"},
"acceptable":{"en":"The category falls under Acceptable","ar":"تندرج تحت فئة دهون مقبولة"},
"obeseBodyFat":{"en":"The category falls under Obese.","ar":"تندرج تحت فئة دهون جسم سمين"},
"invalid":{"en":"Invalid input for calculation.","ar":"البيانات المدخلة غير صالحة للحساب"},
"more":{"en":"Please check the value you have entered, since the body fat percentage has crossed the limits.","ar":"يرجى التحقق من القيمة التي أدخلتها ، نظرًا لأن نسبة الدهون في الجسم قد تجاوزت الحدود"},
"less":{"en":"Please check the value you have entered, since the body fat percentage cannot be this low.","ar":"يرجى التحقق من القيمة التي أدخلتها ، نظرًا لأن نسبة الدهون في الجسم لا يمكن أن تكون منخفضة"},
"carbProteinDesc": {"en": "Calculates carbohydrate protein and fat ratio in calories and grams according to a pre-set ratio", "ar": "حساب نسب الكربوهيدرات و البروتينات و الدهون بالسعرات الحرارية والغرامات وفقا لنسب محددة مسبقا"},
"calDay": {"en": "Calories Per Day", "ar": "السعرات الحرارية في اليوم الواحد"},
"notSure": {"en": "Not sure? click here", "ar": "غير متأكد؟ اضغط هنا"},
"selectDiet": {"en": "Select Diet Type", "ar": "حدد نوع النظام الغذائي"},
"dietVeryLow":{"en":"Very Low Carb","ar":"حمية منخفضة جدا في الكربوهيدرات"},
"dietLow":{"en":"Low Carb","ar":"حمية منخفضة الكربوهيدرات"},
"dietModerate":{"en":"Moderate Carb","ar":"حمية معتدلة الكربوهيدرات"},
"dietUSDA":{"en":"USDA Guidelines","ar":"ارشادات وزارة الزراعة الأمريكية"},
"dietZone":{"en":"Zone Diet","ar":"حمية زون"},
}; };

@ -481,7 +481,7 @@ class BaseAppClient {
simplePost( simplePost(
String fullUrl, { String fullUrl, {
Map<String, dynamic> body, Map<dynamic, dynamic> body,
Map<String, String> headers, Map<String, String> headers,
Function(dynamic response, int statusCode) onSuccess, Function(dynamic response, int statusCode) onSuccess,
Function(String error, int statusCode) onFailure, Function(String error, int statusCode) onFailure,
@ -496,7 +496,6 @@ class BaseAppClient {
body: json.encode(body), body: json.encode(body),
headers: headers, headers: headers,
); );
final int statusCode = response.statusCode; final int statusCode = response.statusCode;
print("statusCode :$statusCode"); print("statusCode :$statusCode");
if (await handleUnauthorized(statusCode, forUrl: fullUrl)) simplePost(fullUrl, onFailure: onFailure, onSuccess: onSuccess, body: body, headers: headers); if (await handleUnauthorized(statusCode, forUrl: fullUrl)) simplePost(fullUrl, onFailure: onFailure, onSuccess: onSuccess, body: body, headers: headers);

@ -4,6 +4,7 @@ import 'dart:developer';
import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/ResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/ResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/CreateCustomerRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/CreateCustomerRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart';
@ -15,13 +16,11 @@ import 'package:diplomaticquarterapp/core/model/packages_offers/responses/Packag
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/order_response_model.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/order_response_model.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/tamara_payment_option.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/tamara_payment_option.dart';
import 'package:diplomaticquarterapp/core/service/base_service.dart'; import 'package:diplomaticquarterapp/core/service/base_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
var packagesAuthHeader = <String, String>{'Authorization': ''}; Map<String, String> packagesAuthHeader = {};
class OffersAndPackagesServices extends BaseService { class OffersAndPackagesServices extends BaseService {
AuthenticatedUser patientUser; AuthenticatedUser patientUser;
@ -32,64 +31,52 @@ class OffersAndPackagesServices extends BaseService {
List<PackagesResponseModel> bestSellerList = List(); List<PackagesResponseModel> bestSellerList = List();
List<PackagesResponseModel> bannersList = List(); List<PackagesResponseModel> bannersList = List();
List<PackagesCartItemsResponseModel> cartItemList = List(); List<PackagesCartItemsResponseModel> cartItemList = List();
List<HospitalsModel> _hospitals = List();
List<HospitalsModel> get hospitals => _hospitals;
String cartItemCount = ""; String cartItemCount = "";
PackagesCustomerResponseModel customer; PackagesCustomerResponseModel customer;
Future<List<PackagesCategoriesResponseModel>> getAllCategories( Future<List<PackagesCategoriesResponseModel>> getAllCategories(OffersCategoriesRequestModel request) async {
OffersCategoriesRequestModel request) async {
Future errorThrow; Future errorThrow;
var url = EXA_CART_API_BASE_URL + PACKAGES_CATEGORIES; var url = EXA_CART_API_BASE_URL + PACKAGES_CATEGORIES;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['categories'].forEach((json) { jsonResponse['categories'].forEach((json) {
categoryList.add(PackagesCategoriesResponseModel().fromJson(json)); categoryList.add(PackagesCategoriesResponseModel().fromJson(json));
}); });
} }
}, }, onFailure: (String error, int statusCode) {}, queryParams: request.toFlatMap());
onFailure: (String error, int statusCode) {},
queryParams: request.toFlatMap());
return categoryList; return categoryList;
} }
Future<List<PackagesResponseModel>> getAllProducts( Future<List<PackagesResponseModel>> getAllProducts({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async {
{@required OffersProductsRequestModel request,
@required BuildContext context,
@required bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
request.sinceId = (productList.isNotEmpty) ? productList.last.id : 0; request.sinceId = (productList.isNotEmpty) ? productList.last.id : 0;
productList = List(); productList = List();
var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['products'].forEach((json) { jsonResponse['products'].forEach((json) {
productList.add(PackagesResponseModel().fromJson(json)); productList.add(PackagesResponseModel().fromJson(json));
}); });
} }
}, }, onFailure: (String error, int statusCode) {}, queryParams: request.toFlatMap());
onFailure: (String error, int statusCode) {},
queryParams: request.toFlatMap());
return productList; return productList;
} }
Future<List<TamaraPaymentOption>> getTamaraOptions( Future<List<TamaraPaymentOption>> getTamaraOptions({@required BuildContext context, @required bool showLoading = true}) async {
{@required BuildContext context, if (tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty) return tamaraPaymentOptions;
@required bool showLoading = true}) async {
if (tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty)
return tamaraPaymentOptions;
var url = EXA_CART_API_BASE_URL + PACKAGES_TAMARA_OPT; var url = EXA_CART_API_BASE_URL + PACKAGES_TAMARA_OPT;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['payment_option'].forEach((json) { jsonResponse['payment_option'].forEach((json) {
@ -103,14 +90,10 @@ class OffersAndPackagesServices extends BaseService {
return tamaraPaymentOptions; return tamaraPaymentOptions;
} }
Future<List<PackagesResponseModel>> getLatestOffers( Future<List<PackagesResponseModel>> getLatestOffers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async {
{@required OffersProductsRequestModel request,
@required BuildContext context,
@required bool showLoading = true}) async {
var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) { latestOffersList.clear();
latestOffersList.clear();
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['products'].forEach((json) { jsonResponse['products'].forEach((json) {
@ -124,14 +107,10 @@ class OffersAndPackagesServices extends BaseService {
return latestOffersList; return latestOffersList;
} }
Future<List<PackagesResponseModel>> getBestSellers( Future<List<PackagesResponseModel>> getBestSellers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async {
{@required OffersProductsRequestModel request,
@required BuildContext context,
@required bool showLoading = true}) async {
var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) { bestSellerList.clear();
bestSellerList.clear();
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['products'].forEach((json) { jsonResponse['products'].forEach((json) {
@ -145,13 +124,9 @@ class OffersAndPackagesServices extends BaseService {
return bestSellerList; return bestSellerList;
} }
Future<List<PackagesResponseModel>> getBanners( Future<List<PackagesResponseModel>> getBanners({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async {
{@required OffersProductsRequestModel request,
@required BuildContext context,
@required bool showLoading = true}) async {
var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
if (statusCode == 200) { if (statusCode == 200) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
jsonResponse['products'].forEach((json) { jsonResponse['products'].forEach((json) {
@ -165,10 +140,7 @@ class OffersAndPackagesServices extends BaseService {
return bannersList; return bannersList;
} }
Future loadOffersPackagesDataForMainPage( Future loadOffersPackagesDataForMainPage({@required BuildContext context, bool showLoading = true, Function completion}) async {
{@required BuildContext context,
bool showLoading = true,
Function completion}) async {
var finished = 0; var finished = 0;
var totalCalls = 2; var totalCalls = 2;
@ -190,30 +162,20 @@ class OffersAndPackagesServices extends BaseService {
// Check and Create Customer // Check and Create Customer
if (patientUser != null) { if (patientUser != null) {
customer = customer = await getCurrentCustomer(context: context, showLoading: showLoading);
await getCurrentCustomer(context: context, showLoading: showLoading);
if (customer == null) { if (customer == null) {
createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), context: context);
context: context);
} }
} }
// Performing Parallel Request on same time // Performing Parallel Request on same time
// # 1 // # 1
getBestSellers( getBestSellers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value) {
request: OffersProductsRequestModel(),
context: context,
showLoading: false)
.then((value) {
completedAll(); completedAll();
}); });
// # 2 // # 2
getLatestOffers( getLatestOffers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value) {
request: OffersProductsRequestModel(),
context: context,
showLoading: false)
.then((value) {
completedAll(); completedAll();
}); });
@ -230,10 +192,7 @@ class OffersAndPackagesServices extends BaseService {
// -------------------- // --------------------
// Create Customer // Create Customer
// -------------------- // --------------------
Future createCustomer(PackagesCustomerRequestModel request, Future createCustomer(PackagesCustomerRequestModel request, {@required BuildContext context, bool showLoading = true, Function(bool) completion}) async {
{@required BuildContext context,
bool showLoading = true,
Function(bool) completion}) async {
if (customer != null) return Future.value(customer); if (customer != null) return Future.value(customer);
customer = null; customer = null;
@ -241,9 +200,7 @@ class OffersAndPackagesServices extends BaseService {
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER; var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER;
await baseAppClient await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) {
.simplePost(url, headers: packagesAuthHeader, body: request.json(),
onSuccess: (dynamic stringResponse, int statusCode) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
var customerJson = jsonResponse['customers'].first; var customerJson = jsonResponse['customers'].first;
customer = PackagesCustomerResponseModel.fromJson(customerJson); customer = PackagesCustomerResponseModel.fromJson(customerJson);
@ -258,16 +215,12 @@ class OffersAndPackagesServices extends BaseService {
return errorThrow ?? customer; return errorThrow ?? customer;
} }
Future<PackagesCustomerResponseModel> getCurrentCustomer( Future<PackagesCustomerResponseModel> getCurrentCustomer({@required BuildContext context, bool showLoading = true}) async {
{@required BuildContext context, bool showLoading = true}) async {
if (customer != null) return Future.value(customer); if (customer != null) return Future.value(customer);
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER + "/username/${patientUser.patientID}";
PACKAGES_CUSTOMER + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
"/username/${patientUser.patientID}";
await baseAppClient.simpleGet(url, headers: packagesAuthHeader,
onSuccess: (dynamic stringResponse, int statusCode) {
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
var customerJson = jsonResponse['customers'].first; var customerJson = jsonResponse['customers'].first;
customer = PackagesCustomerResponseModel.fromJson(customerJson); customer = PackagesCustomerResponseModel.fromJson(customerJson);
@ -282,17 +235,14 @@ class OffersAndPackagesServices extends BaseService {
// -------------------- // --------------------
// Shopping Cart // Shopping Cart
// -------------------- // --------------------
Future<Map<String, dynamic>> cartItems( Future<Map<String, dynamic>> cartItems({@required BuildContext context, bool showLoading = true}) async {
{@required BuildContext context, bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
cartItemList.clear(); cartItemList.clear();
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}';
EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}';
Map<String, dynamic> jsonResponse; Map<String, dynamic> jsonResponse;
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
jsonResponse = json.decode(stringResponse); jsonResponse = json.decode(stringResponse);
@ -308,10 +258,7 @@ class OffersAndPackagesServices extends BaseService {
return errorThrow ?? jsonResponse; return errorThrow ?? jsonResponse;
} }
Future<ResponseModel<PackagesCartItemsResponseModel>> addProductToCart( Future<ResponseModel<PackagesCartItemsResponseModel>> addProductToCart(AddProductToCartRequestModel request, {@required BuildContext context, bool showLoading = true}) async {
AddProductToCartRequestModel request,
{@required BuildContext context,
bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
ResponseModel<PackagesCartItemsResponseModel> response; ResponseModel<PackagesCartItemsResponseModel> response;
@ -319,38 +266,27 @@ class OffersAndPackagesServices extends BaseService {
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART; var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART;
await baseAppClient await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) {
.simplePost(url, headers: packagesAuthHeader, body: request.json(),
onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
var jsonCartItem = jsonResponse["shopping_carts"][0]; var jsonCartItem = jsonResponse["shopping_carts"][0];
response = ResponseModel( response = ResponseModel(status: true, data: PackagesCartItemsResponseModel.fromJson(jsonCartItem), error: null);
status: true,
data: PackagesCartItemsResponseModel.fromJson(jsonCartItem),
error: null);
cartItemCount = (jsonResponse['count'] ?? 0).toString(); cartItemCount = (jsonResponse['count'] ?? 0).toString();
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
errorThrow = errorThrow = Future.error(ResponseModel(status: true, data: null, error: error));
Future.error(ResponseModel(status: true, data: null, error: error));
}); });
return errorThrow ?? response; return errorThrow ?? response;
} }
Future updateProductToCart(int cartItemID, Future updateProductToCart(int cartItemID, {UpdateProductToCartRequestModel request, @required BuildContext context, bool showLoading = true}) async {
{UpdateProductToCartRequestModel request,
@required BuildContext context,
bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID';
await baseAppClient await baseAppClient.simplePut(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) {
.simplePut(url, headers: packagesAuthHeader, body: request.json(),
onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
@ -363,16 +299,13 @@ class OffersAndPackagesServices extends BaseService {
return errorThrow ?? bannersList; return errorThrow ?? bannersList;
} }
Future<bool> deleteProductFromCart(int cartItemID, Future<bool> deleteProductFromCart(int cartItemID, {@required BuildContext context, bool showLoading = true}) async {
{@required BuildContext context, bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID';
await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
// var jsonResponse = json.decode(stringResponse);
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
log(error); log(error);
@ -385,28 +318,23 @@ class OffersAndPackagesServices extends BaseService {
// -------------------- // --------------------
// Place Order // Place Order
// -------------------- // --------------------
Future placeOrder( Future placeOrder({@required Map<dynamic, dynamic> paymentParams, @required int projectID, @required BuildContext context, bool showLoading = true}) async {
{@required Map<dynamic, dynamic> paymentParams,
@required BuildContext context,
bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
Map<dynamic, dynamic> jsonBody = { Map<dynamic, dynamic> jsonBody = {
"customer_id": customer.id, "customer_id": customer.id,
"billing_address": { "project_id": projectID,
"email": patientUser.emailAddress, "billing_address": {"email": patientUser.emailAddress, "phone_number": patientUser.mobileNumber},
"phone_number": patientUser.mobileNumber
},
}; };
jsonBody.addAll(paymentParams); jsonBody.addAll(paymentParams);
jsonBody = {'order': jsonBody}; jsonBody = {'order': jsonBody};
print(jsonBody);
int order_id; int order_id;
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS; var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS;
await baseAppClient.simplePost(url, await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode) {
headers: packagesAuthHeader,
body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
@ -420,21 +348,18 @@ class OffersAndPackagesServices extends BaseService {
return errorThrow ?? order_id; return errorThrow ?? order_id;
} }
Future<ResponseModel<PackagesOrderResponseModel>> getOrderById(int id, Future<ResponseModel<PackagesOrderResponseModel>> getOrderById(int id, {@required BuildContext context, bool showLoading = true}) async {
{@required BuildContext context, bool showLoading = true}) async {
Future errorThrow; Future errorThrow;
ResponseModel<PackagesOrderResponseModel> response; ResponseModel<PackagesOrderResponseModel> response;
_showLoading(context, showLoading); _showLoading(context, showLoading);
var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS + '/$id'; var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS + '/$id';
await baseAppClient.simpleGet(url, headers: packagesAuthHeader, await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) {
onSuccess: (dynamic stringResponse, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
var jsonResponse = json.decode(stringResponse); var jsonResponse = json.decode(stringResponse);
var jsonOrder = jsonResponse['orders'][0]; var jsonOrder = jsonResponse['orders'][0];
response = ResponseModel( response = ResponseModel(status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder));
status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder));
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
_hideLoading(context, showLoading); _hideLoading(context, showLoading);
errorThrow = Future.error(ResponseModel(status: false, error: error)); errorThrow = Future.error(ResponseModel(status: false, error: error));
@ -442,6 +367,26 @@ class OffersAndPackagesServices extends BaseService {
return errorThrow ?? response; return errorThrow ?? response;
} }
Future getHospitals({bool isResBasedOnLoc = true}) async {
Map<String, dynamic> body = Map();
body['Latitude'] = await this.sharedPref.getDouble(USER_LAT);
body['Longitude'] = await this.sharedPref.getDouble(USER_LONG);
body['IsOnlineCheckIn'] = isResBasedOnLoc;
body['PatientOutSA'] = 0;
await baseAppClient.post(GET_PROJECT,
onSuccess: (dynamic response, int statusCode) {
_hospitals.clear();
response['ListProject'].forEach((hospital) {
_hospitals.add(HospitalsModel.fromJson(hospital));
});
}, onFailure: (String error, int statusCode) {
hasError = true;
super.error = error;
}, body: body);
}
} }
_showLoading(BuildContext context, bool flag) { _showLoading(BuildContext context, bool flag) {

@ -1,3 +1,4 @@
import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCartItemsResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCartItemsResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCategoriesResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCategoriesResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart';
@ -22,6 +23,7 @@ class PackagesViewModel extends BaseViewModel {
List<PackagesResponseModel> get bestSellerList => service.bestSellerList; List<PackagesResponseModel> get bestSellerList => service.bestSellerList;
List<PackagesResponseModel> get bannersList => service.bannersList; List<PackagesResponseModel> get bannersList => service.bannersList;
List<PackagesCartItemsResponseModel> get cartItemList => service.cartItemList; List<PackagesCartItemsResponseModel> get cartItemList => service.cartItemList;
List<HospitalsModel> get hospitals => service.hospitals;
String _cartItemCount = ""; String _cartItemCount = "";

@ -1,21 +1,20 @@
import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.dart';
import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'package:diplomaticquarterapp/models/pharmacy/Wishlist.dart'; import 'package:diplomaticquarterapp/models/pharmacy/Wishlist.dart';
import 'package:diplomaticquarterapp/models/pharmacy/locationModel.dart'; import 'package:diplomaticquarterapp/models/pharmacy/locationModel.dart';
import 'package:diplomaticquarterapp/models/pharmacy/productDetailModel.dart'; import 'package:diplomaticquarterapp/models/pharmacy/productDetailModel.dart';
import 'package:diplomaticquarterapp/services/pharmacy_services/product_detail_service.dart';
import 'package:diplomaticquarterapp/models/pharmacy/specification.dart'; import 'package:diplomaticquarterapp/models/pharmacy/specification.dart';
import 'package:diplomaticquarterapp/services/pharmacy_services/product_detail_service.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/navigation_service.dart'; import 'package:diplomaticquarterapp/uitl/navigation_service.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../../../locator.dart'; import '../../../locator.dart';
class ProductDetailViewModel extends BaseViewModel{ class ProductDetailViewModel extends BaseViewModel {
ProductDetailService _productDetailService = locator<ProductDetailService>(); ProductDetailService _productDetailService = locator<ProductDetailService>();
List<ProductDetail> get productDetailService => _productDetailService.productDetailList; List<ProductDetail> get productDetailService => _productDetailService.productDetailList;
@ -28,6 +27,11 @@ class ProductDetailViewModel extends BaseViewModel{
bool hasError = false; bool hasError = false;
num get stockQuantity => _productDetailService.stockQuantity;
String get stockAvailability => _productDetailService.stockAvailability;
bool get isStockAvailable => _productDetailService.isStockAvailable;
Future getProductReviewsData(productID) async { Future getProductReviewsData(productID) async {
hasError = false; hasError = false;
@ -72,8 +76,7 @@ class ProductDetailViewModel extends BaseViewModel{
setState(ViewState.ErrorLocal); setState(ViewState.ErrorLocal);
} else { } else {
setState(ViewState.Idle); setState(ViewState.Idle);
Provider.of<OrderPreviewViewModel>(locator<NavigationService>().navigatorKey.currentContext, listen: false) Provider.of<OrderPreviewViewModel>(locator<NavigationService>().navigatorKey.currentContext, listen: false).setShoppingCartResponse(object);
.setShoppingCartResponse( object);
} }
} }
@ -103,11 +106,9 @@ class ProductDetailViewModel extends BaseViewModel{
Future addToWishlistData(itemID) async { Future addToWishlistData(itemID) async {
hasError = false; hasError = false;
setState(ViewState.BusyLocal); setState(ViewState.BusyLocal);
GifLoaderDialogUtils.showMyDialog( GifLoaderDialogUtils.showMyDialog(locator<NavigationService>().navigatorKey.currentContext);
locator<NavigationService>().navigatorKey.currentContext);
await _productDetailService.addToWishlist(itemID); await _productDetailService.addToWishlist(itemID);
GifLoaderDialogUtils.hideDialog( GifLoaderDialogUtils.hideDialog(locator<NavigationService>().navigatorKey.currentContext);
locator<NavigationService>().navigatorKey.currentContext);
if (_productDetailService.hasError) { if (_productDetailService.hasError) {
error = _productDetailService.error; error = _productDetailService.error;
@ -127,15 +128,12 @@ class ProductDetailViewModel extends BaseViewModel{
setState(ViewState.Idle); setState(ViewState.Idle);
} }
Future deleteWishlistData(itemID) async { Future deleteWishlistData(itemID) async {
hasError = false; hasError = false;
setState(ViewState.BusyLocal); setState(ViewState.BusyLocal);
GifLoaderDialogUtils.showMyDialog( GifLoaderDialogUtils.showMyDialog(locator<NavigationService>().navigatorKey.currentContext);
locator<NavigationService>().navigatorKey.currentContext);
await _productDetailService.deleteItemFromWishlist(itemID); await _productDetailService.deleteItemFromWishlist(itemID);
GifLoaderDialogUtils.hideDialog( GifLoaderDialogUtils.hideDialog(locator<NavigationService>().navigatorKey.currentContext);
locator<NavigationService>().navigatorKey.currentContext);
if (_productDetailService.hasError) { if (_productDetailService.hasError) {
error = _productDetailService.error; error = _productDetailService.error;
@ -144,7 +142,6 @@ class ProductDetailViewModel extends BaseViewModel{
setState(ViewState.Idle); setState(ViewState.Idle);
} }
Future productSpecificationData(itemID) async { Future productSpecificationData(itemID) async {
hasError = false; hasError = false;
setState(ViewState.Busy); setState(ViewState.Busy);
@ -156,10 +153,7 @@ class ProductDetailViewModel extends BaseViewModel{
setState(ViewState.Idle); setState(ViewState.Idle);
} }
clearReview(){ clearReview() {
productDetailService.clear(); productDetailService.clear();
} }
}
}

@ -1,7 +1,3 @@
// To parse this JSON data, do
//
// final productDetail = productDetailFromJson(jsonString);
import 'dart:convert'; import 'dart:convert';
List<ProductDetail> productDetailFromJson(String str) => List<ProductDetail>.from(json.decode(str).map((x) => ProductDetail.fromJson(x))); List<ProductDetail> productDetailFromJson(String str) => List<ProductDetail>.from(json.decode(str).map((x) => ProductDetail.fromJson(x)));
@ -16,12 +12,12 @@ class ProductDetail {
List<Review> reviews; List<Review> reviews;
factory ProductDetail.fromJson(Map<String, dynamic> json) => ProductDetail( factory ProductDetail.fromJson(Map<String, dynamic> json) => ProductDetail(
reviews: List<Review>.from(json["reviews"].map((x) => Review.fromJson(x))), reviews: List<Review>.from(json["reviews"].map((x) => Review.fromJson(x))),
); );
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"reviews": List<dynamic>.from(reviews.map((x) => x.toJson())), "reviews": List<dynamic>.from(reviews.map((x) => x.toJson())),
}; };
} }
class Review { class Review {
@ -62,42 +58,42 @@ class Review {
dynamic product; dynamic product;
factory Review.fromJson(Map<String, dynamic> json) => Review( factory Review.fromJson(Map<String, dynamic> json) => Review(
id: json["id"], id: json["id"],
position: json["position"], position: json["position"],
reviewId: json["review_id"], reviewId: json["review_id"],
customerId: json["customer_id"], customerId: json["customer_id"],
productId: json["product_id"], productId: json["product_id"],
storeId: json["store_id"], storeId: json["store_id"],
isApproved: json["is_approved"], isApproved: json["is_approved"],
title: json["title"], title: json["title"],
reviewText: json["review_text"], reviewText: json["review_text"],
replyText: json["reply_text"], replyText: json["reply_text"],
rating: json["rating"], rating: json["rating"],
helpfulYesTotal: json["helpful_yes_total"], helpfulYesTotal: json["helpful_yes_total"],
helpfulNoTotal: json["helpful_no_total"], helpfulNoTotal: json["helpful_no_total"],
createdOnUtc: DateTime.parse(json["created_on_utc"]), createdOnUtc: DateTime.parse(json["created_on_utc"]),
customer: Customer.fromJson(json["customer"]), customer: Customer.fromJson(json["customer"]),
product: json["product"], product: json["product"],
); );
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"id": id, "id": id,
"position": position, "position": position,
"review_id": reviewId, "review_id": reviewId,
"customer_id": customerId, "customer_id": customerId,
"product_id": productId, "product_id": productId,
"store_id": storeId, "store_id": storeId,
"is_approved": isApproved, "is_approved": isApproved,
"title": title, "title": title,
"review_text": reviewText, "review_text": reviewText,
"reply_text": replyText, "reply_text": replyText,
"rating": rating, "rating": rating,
"helpful_yes_total": helpfulYesTotal, "helpful_yes_total": helpfulYesTotal,
"helpful_no_total": helpfulNoTotal, "helpful_no_total": helpfulNoTotal,
"created_on_utc": createdOnUtc.toIso8601String(), "created_on_utc": createdOnUtc.toIso8601String(),
"customer": customer.toJson(), "customer": customer.toJson(),
"product": product, "product": product,
}; };
} }
class Customer { class Customer {
@ -164,75 +160,73 @@ class Customer {
dynamic registeredInStoreId; dynamic registeredInStoreId;
factory Customer.fromJson(Map<String, dynamic> json) => Customer( factory Customer.fromJson(Map<String, dynamic> json) => Customer(
fileNumber: json["file_number"], fileNumber: json["file_number"],
iqamaNumber: json["iqama_number"], iqamaNumber: json["iqama_number"],
isOutSa: json["is_out_sa"], isOutSa: json["is_out_sa"],
patientType: json["patient_type"], patientType: json["patient_type"],
gender: json["gender"], gender: json["gender"],
birthDate: DateTime.parse(json["birth_date"]), birthDate: DateTime.parse(json["birth_date"]),
phone: json["phone"], phone: json["phone"],
countryCode: json["country_code"], countryCode: json["country_code"],
yahalaAccountno: json["yahala_accountno"], yahalaAccountno: json["yahala_accountno"],
billingAddress: json["billing_address"], billingAddress: json["billing_address"],
shippingAddress: json["shipping_address"], shippingAddress: json["shipping_address"],
id: json["id"], id: json["id"],
username: emailValues.map[json["username"]], username: emailValues.map[json["username"]],
email: emailValues.map[json["email"]], email: emailValues.map[json["email"]],
firstName: json["first_name"], firstName: json["first_name"],
lastName: json["last_name"], lastName: json["last_name"],
languageId: json["language_id"], languageId: json["language_id"],
adminComment: json["admin_comment"], adminComment: json["admin_comment"],
isTaxExempt: json["is_tax_exempt"], isTaxExempt: json["is_tax_exempt"],
hasShoppingCartItems: json["has_shopping_cart_items"], hasShoppingCartItems: json["has_shopping_cart_items"],
active: json["active"], active: json["active"],
deleted: json["deleted"], deleted: json["deleted"],
isSystemAccount: json["is_system_account"], isSystemAccount: json["is_system_account"],
systemName: json["system_name"], systemName: json["system_name"],
lastIpAddress: json["last_ip_address"], lastIpAddress: json["last_ip_address"],
createdOnUtc: json["created_on_utc"], createdOnUtc: json["created_on_utc"],
lastLoginDateUtc: json["last_login_date_utc"], lastLoginDateUtc: json["last_login_date_utc"],
lastActivityDateUtc: json["last_activity_date_utc"], lastActivityDateUtc: json["last_activity_date_utc"],
registeredInStoreId: json["registered_in_store_id"], registeredInStoreId: json["registered_in_store_id"],
); );
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"file_number": fileNumber, "file_number": fileNumber,
"iqama_number": iqamaNumber, "iqama_number": iqamaNumber,
"is_out_sa": isOutSa, "is_out_sa": isOutSa,
"patient_type": patientType, "patient_type": patientType,
"gender": gender, "gender": gender,
"birth_date": birthDate.toIso8601String(), "birth_date": birthDate.toIso8601String(),
"phone": phone, "phone": phone,
"country_code": countryCode, "country_code": countryCode,
"yahala_accountno": yahalaAccountno, "yahala_accountno": yahalaAccountno,
"billing_address": billingAddress, "billing_address": billingAddress,
"shipping_address": shippingAddress, "shipping_address": shippingAddress,
"id": id, "id": id,
"username": emailValues.reverse[username], "username": emailValues.reverse[username],
"email": emailValues.reverse[email], "email": emailValues.reverse[email],
"first_name": firstName, "first_name": firstName,
"last_name": lastName, "last_name": lastName,
"language_id": languageId, "language_id": languageId,
"admin_comment": adminComment, "admin_comment": adminComment,
"is_tax_exempt": isTaxExempt, "is_tax_exempt": isTaxExempt,
"has_shopping_cart_items": hasShoppingCartItems, "has_shopping_cart_items": hasShoppingCartItems,
"active": active, "active": active,
"deleted": deleted, "deleted": deleted,
"is_system_account": isSystemAccount, "is_system_account": isSystemAccount,
"system_name": systemName, "system_name": systemName,
"last_ip_address": lastIpAddress, "last_ip_address": lastIpAddress,
"created_on_utc": createdOnUtc, "created_on_utc": createdOnUtc,
"last_login_date_utc": lastLoginDateUtc, "last_login_date_utc": lastLoginDateUtc,
"last_activity_date_utc": lastActivityDateUtc, "last_activity_date_utc": lastActivityDateUtc,
"registered_in_store_id": registeredInStoreId, "registered_in_store_id": registeredInStoreId,
}; };
} }
enum Email { STEVE_GATES_NOP_COMMERCE_COM } enum Email { STEVE_GATES_NOP_COMMERCE_COM }
final emailValues = EnumValues({ final emailValues = EnumValues({"steve_gates@nopCommerce.com": Email.STEVE_GATES_NOP_COMMERCE_COM});
"steve_gates@nopCommerce.com": Email.STEVE_GATES_NOP_COMMERCE_COM
});
class EnumValues<T> { class EnumValues<T> {
Map<String, T> map; Map<String, T> map;

@ -4,13 +4,11 @@ import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import '../health_calc_desc.dart';
import 'result_page.dart'; import 'result_page.dart';
const activeCardColor = Color(0xff70777A); const activeCardColor = Color(0xff70777A);
@ -47,9 +45,10 @@ class _BMICalculatorState extends State<BMICalculator> {
} }
double calculateBMI() { double calculateBMI() {
if (_isHeightCM) { if (!_isHeightCM) _heightValue = convertToCm(_heightValue.toDouble());
convertToCm(_heightValue.toDouble());
} if (!_isWeightKG) _weightValue = convertToKg(_weightValue);
bmiResult = _weightValue / pow(_heightValue / 100, 2); bmiResult = _weightValue / pow(_heightValue / 100, 2);
return bmiResult; return bmiResult;

@ -78,7 +78,7 @@ class _ResultPageState extends State<ResultPage> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Text(
TranslationBase.of(context).bodyMassIndex + widget.finalResult.toString(), TranslationBase.of(context).bodyMassIndex + widget.finalResult.toStringAsFixed(2),
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
letterSpacing: -0.64, letterSpacing: -0.64,

@ -48,7 +48,7 @@ class _BmrCalculatorState extends State<BmrCalculator> {
// int height = 0; // int height = 0;
// int weight = 0; // int weight = 0;
double bmrResult = 0; double bmrResult = 0;
String dropdownValue = 'Lighty Active (1-3) days per week'; String dropdownValue = '';
double calories = 0; double calories = 0;
void updateColor(int type) { void updateColor(int type) {
@ -122,13 +122,13 @@ class _BmrCalculatorState extends State<BmrCalculator> {
} }
void calculateCalories() { void calculateCalories() {
if (dropdownValue == "Almost Inactive(Little or no exercises)") { if (dropdownValue == TranslationBase.of(context).inactiveAct) {
calories = bmrResult * 1.2; calories = bmrResult * 1.2;
} else if (dropdownValue == "Lighty Active (1-3) days per week") { } else if (dropdownValue == TranslationBase.of(context).light) {
calories = bmrResult * 1.375; calories = bmrResult * 1.375;
} else if (dropdownValue == "very Active(6-7) days per week") { } else if (dropdownValue == TranslationBase.of(context).very) {
calories = bmrResult * 1.55; calories = bmrResult * 1.55;
} else if (dropdownValue == "Super Active(very hard exercises)") { } else if (dropdownValue == TranslationBase.of(context).superAct) {
calories = bmrResult * 1.725; calories = bmrResult * 1.725;
} else if (dropdownValue == "") { } else if (dropdownValue == "") {
calories = bmrResult * 10.725; calories = bmrResult * 10.725;
@ -137,6 +137,7 @@ class _BmrCalculatorState extends State<BmrCalculator> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
dropdownValue = TranslationBase.of(context).light;
ProjectViewModel projectViewModel = Provider.of(context); ProjectViewModel projectViewModel = Provider.of(context);
_weightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)]; _weightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)];
_heightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)]; _heightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)];
@ -161,7 +162,7 @@ class _BmrCalculatorState extends State<BmrCalculator> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Calculates the amount of energy that the persons body expends in a day', TranslationBase.of(context).bmrDesc,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@ -362,14 +363,14 @@ class _BmrCalculatorState extends State<BmrCalculator> {
}); });
}, },
items: <String>[ items: <String>[
'Almost Inactive(Little or no exercises)', TranslationBase.of(context).inactiveAct,
'Lighty Active (1-3) days per week', TranslationBase.of(context).light,
'very Active(6-7) days per week', TranslationBase.of(context).very,
'Super Active(very hard exercises)' TranslationBase.of(context).superAct,
].map<DropdownMenuItem<String>>((String value) { ].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(value), child: Text(value, style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)),
); );
}).toList(), }).toList(),
), ),

@ -4,7 +4,6 @@ import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -23,7 +22,6 @@ class BodyFat extends StatefulWidget {
} }
class _BodyFatState extends State<BodyFat> { class _BodyFatState extends State<BodyFat> {
final GlobalKey clinicDropdownKey = GlobalKey(); final GlobalKey clinicDropdownKey = GlobalKey();
bool _isHeightCM = true; bool _isHeightCM = true;
bool _isNeckKG = true; bool _isNeckKG = true;
@ -34,7 +32,6 @@ class _BodyFatState extends State<BodyFat> {
double _waistValue = 0; double _waistValue = 0;
double _hipValue = 0; double _hipValue = 0;
TextEditingController _heightController = new TextEditingController(); TextEditingController _heightController = new TextEditingController();
TextEditingController _neckController = TextEditingController(); TextEditingController _neckController = TextEditingController();
TextEditingController _waistController = TextEditingController(); TextEditingController _waistController = TextEditingController();
@ -45,12 +42,12 @@ class _BodyFatState extends State<BodyFat> {
List<PopupMenuItem> _waistPopupList = List(); List<PopupMenuItem> _waistPopupList = List();
List<PopupMenuItem> _hipPopupList = List(); List<PopupMenuItem> _hipPopupList = List();
bool isMale = false; bool isMale = false;
// bool isHeightCm = true; // bool isHeightCm = true;
Color maleCard = activeCardColorGender; Color maleCard = activeCardColorGender;
Color femaleCard = inactiveCardColorGender; Color femaleCard = inactiveCardColorGender;
// Color neckCmCard = activeCardColor; // Color neckCmCard = activeCardColor;
// Color neckFtCard = inactiveCardColor; // Color neckFtCard = inactiveCardColor;
Color waistCmCard = activeCardColor; Color waistCmCard = activeCardColor;
@ -59,6 +56,7 @@ class _BodyFatState extends State<BodyFat> {
Color hipFtCard = inactiveCardColor; Color hipFtCard = inactiveCardColor;
Color cmCard = activeCardColor; Color cmCard = activeCardColor;
Color ftCard = inactiveCardColor; Color ftCard = inactiveCardColor;
// int neck = 10; // int neck = 10;
// int heightCm = 0; // int heightCm = 0;
// int heightFt = 0; // int heightFt = 0;
@ -67,6 +65,7 @@ class _BodyFatState extends State<BodyFat> {
double minRange; double minRange;
double maxRange; double maxRange;
double overWeightBy; double overWeightBy;
// int waist = 5; // int waist = 5;
double bodyFat = 0; double bodyFat = 0;
double fat = 0; double fat = 0;
@ -74,8 +73,6 @@ class _BodyFatState extends State<BodyFat> {
double calories = 0; double calories = 0;
String textResult = ''; String textResult = '';
@override @override
void initState() { void initState() {
_neckController.text = _neckValue.toString(); _neckController.text = _neckValue.toString();
@ -105,8 +102,6 @@ class _BodyFatState extends State<BodyFat> {
} }
} }
void updateColorWaist(int type) { void updateColorWaist(int type) {
//MG/DLT card //MG/DLT card
if (type == 1) { if (type == 1) {
@ -183,33 +178,33 @@ class _BodyFatState extends State<BodyFat> {
void showTextResult() { void showTextResult() {
if (isMale == false) { if (isMale == false) {
if (bodyFat > 9 && bodyFat <= 13) { if (bodyFat > 9 && bodyFat <= 13) {
textResult = 'The category falls under essential'; textResult = TranslationBase.of(context).essential;
} else if (bodyFat > 13 && bodyFat <= 20) { } else if (bodyFat > 13 && bodyFat <= 20) {
textResult = 'The category falls under athlete'; textResult = TranslationBase.of(context).athlete;
} else if (bodyFat > 20 && bodyFat <= 24) { } else if (bodyFat > 20 && bodyFat <= 24) {
textResult = 'The category falls under fitness'; textResult = TranslationBase.of(context).fitness;
} else if (bodyFat > 24 && bodyFat <= 31) { } else if (bodyFat > 24 && bodyFat <= 31) {
textResult = 'The category falls under acceptable'; textResult = TranslationBase.of(context).acceptable;
} else if (bodyFat > 31 && bodyFat <= 60) { } else if (bodyFat > 31 && bodyFat <= 60) {
textResult = 'The category falls under obese'; textResult = TranslationBase.of(context).obeseBodyFat;
} else if (bodyFat > 60) { } else if (bodyFat > 60) {
textResult = 'Please check the value you have entered, since the body fat percentage has crosed the limits.'; textResult = TranslationBase.of(context).more;
} else if (bodyFat <= 9) { } else if (bodyFat <= 9) {
textResult = 'Please check the value you have entered, since the body fat percentage cannot be this low.'; textResult = TranslationBase.of(context).less;
} }
} else { } else {
if (bodyFat > 5 && fat <= 13) { if (bodyFat > 5 && fat <= 13) {
textResult = 'The category falls under essential'; textResult = TranslationBase.of(context).essential;
} else if (bodyFat > 13 && bodyFat <= 17) { } else if (bodyFat > 13 && bodyFat <= 17) {
textResult = 'The category falls under athlete'; textResult = TranslationBase.of(context).athlete;
} else if (bodyFat > 17 && bodyFat <= 24) { } else if (bodyFat > 17 && bodyFat <= 24) {
textResult = 'The category falls under fitness'; textResult = TranslationBase.of(context).fitness;
} else if (bodyFat > 24 && bodyFat <= 45) { } else if (bodyFat > 24 && bodyFat <= 45) {
textResult = 'The category falls under obese'; textResult = TranslationBase.of(context).obeseBodyFat;
} else if (bodyFat > 45) { } else if (bodyFat > 45) {
textResult = 'Please check the value you have entered, since the body fat percentage has crosed the limits.'; textResult = TranslationBase.of(context).more;
} else if (bodyFat <= 5) { } else if (bodyFat <= 5) {
textResult = 'Please check the value you have entered, since the body fat percentage cannot be this low.'; textResult = TranslationBase.of(context).less;
} }
} }
} }
@ -234,12 +229,12 @@ class _BodyFatState extends State<BodyFat> {
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
child: Container( child: Container(
padding: EdgeInsets.all(20), padding: EdgeInsets.all(20),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Estimates the total body fat based on\nthe size', TranslationBase.of(context).bodyFatDesc,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@ -346,14 +341,14 @@ class _BodyFatState extends State<BodyFat> {
1, 1,
270, 270,
_heightValue, _heightValue,
(text) { (text) {
_heightController.text = text; _heightController.text = text;
}, },
(value) { (value) {
_heightValue = value; _heightValue = value;
}, },
_isHeightCM ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, _isHeightCM ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
(value) { (value) {
if (_isHeightCM != value) { if (_isHeightCM != value) {
setState(() { setState(() {
_isHeightCM = value; _isHeightCM = value;
@ -371,14 +366,14 @@ class _BodyFatState extends State<BodyFat> {
1, 1,
270, 270,
_neckValue, _neckValue,
(text) { (text) {
_neckController.text = text; _neckController.text = text;
}, },
(value) { (value) {
_neckValue = value; _neckValue = value;
}, },
_isNeckKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, _isNeckKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
(value) { (value) {
if (_isNeckKG != value) { if (_isNeckKG != value) {
setState(() { setState(() {
_isNeckKG = value; _isNeckKG = value;
@ -387,7 +382,6 @@ class _BodyFatState extends State<BodyFat> {
}, },
_neckPopupList, _neckPopupList,
), ),
SizedBox( SizedBox(
height: 12.0, height: 12.0,
), ),
@ -397,14 +391,14 @@ class _BodyFatState extends State<BodyFat> {
1, 1,
270, 270,
_waistValue, _waistValue,
(text) { (text) {
_waistController.text = text; _waistController.text = text;
}, },
(value) { (value) {
_waistValue = value; _waistValue = value;
}, },
_isWaistKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, _isWaistKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
(value) { (value) {
if (_isWaistKG != value) { if (_isWaistKG != value) {
setState(() { setState(() {
_isWaistKG = value; _isWaistKG = value;
@ -422,14 +416,14 @@ class _BodyFatState extends State<BodyFat> {
1, 1,
270, 270,
_hipValue, _hipValue,
(text) { (text) {
_hipController.text = text; _hipController.text = text;
}, },
(value) { (value) {
_hipValue = value; _hipValue = value;
}, },
_isHipKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, _isHipKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft,
(value) { (value) {
if (_isHipKG != value) { if (_isHipKG != value) {
setState(() { setState(() {
_isHipKG = value; _isHipKG = value;
@ -438,7 +432,6 @@ class _BodyFatState extends State<BodyFat> {
}, },
_hipPopupList, _hipPopupList,
), ),
SizedBox( SizedBox(
height: 12.0, height: 12.0,
), ),
@ -463,10 +456,10 @@ class _BodyFatState extends State<BodyFat> {
context, context,
FadePage( FadePage(
page: FatResult( page: FatResult(
bodyFat: bodyFat, bodyFat: bodyFat,
fat: fat, fat: fat,
textResult: textResult, textResult: textResult,
)), )),
); );
} }
}); });
@ -477,6 +470,7 @@ class _BodyFatState extends State<BodyFat> {
), ),
); );
} }
Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String prefix, bool isEnable = true, bool hasSelection = false}) { Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String prefix, bool isEnable = true, bool hasSelection = false}) {
return Container( return Container(
padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
@ -534,15 +528,15 @@ class _BodyFatState extends State<BodyFat> {
prefixIcon: prefix == null prefixIcon: prefix == null
? null ? null
: Text( : Text(
"+" + prefix, "+" + prefix,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
height: 21 / 14, height: 21 / 14,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
color: Color(0xff2E303A), color: Color(0xff2E303A),
letterSpacing: -0.56, letterSpacing: -0.56,
), ),
), ),
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
border: InputBorder.none, border: InputBorder.none,
focusedBorder: InputBorder.none, focusedBorder: InputBorder.none,
@ -683,5 +677,3 @@ class CommonDropDownView extends StatelessWidget {
); );
} }
} }

@ -3,7 +3,6 @@ import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -296,14 +295,15 @@ class _CalorieCalculatorState extends State<CalorieCalculator> {
}); });
}, },
items: <String>[ items: <String>[
'Almost Inactive(Little or no exercises)', TranslationBase.of(context).inactiveAct,
'Lighty Active (1-3) days per week', TranslationBase.of(context).light,
'very Active(6-7) days per week', TranslationBase.of(context).very,
'Super Active(very hard exercises)' TranslationBase.of(context).superAct,
].map<DropdownMenuItem<String>>((String value) { ].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(value), child: Text(value,
style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)),
); );
}).toList(), }).toList(),
), ),

@ -35,7 +35,7 @@ class CalorieResultPage extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
"Calories", TranslationBase.of(context).calories,
style: TextStyle( style: TextStyle(
fontSize: 19, fontSize: 19,
letterSpacing: -1.34, letterSpacing: -1.34,
@ -63,7 +63,7 @@ class CalorieResultPage extends StatelessWidget {
height: 5.0, height: 5.0,
), ),
Text( Text(
'Calories', TranslationBase.of(context).calories,
style: TextStyle( style: TextStyle(
fontSize: 18, fontSize: 18,
letterSpacing: -1.08, letterSpacing: -1.08,
@ -78,7 +78,8 @@ class CalorieResultPage extends StatelessWidget {
), ),
mHeight(20), mHeight(20),
Text( Text(
'Daily intake is ${calorie.toStringAsFixed(1)} calories', TranslationBase.of(context).resultCalories.replaceAll("(#)", calorie.toStringAsFixed(1)),
// 'Daily intake is ${calorie.toStringAsFixed(1)} calories',
style: TextStyle(fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600, color: CustomColors.textColor), style: TextStyle(fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600, color: CustomColors.textColor),
), ),
], ],

@ -1,13 +1,13 @@
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart'; import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart';
import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'carbs_result_page.dart'; import 'carbs_result_page.dart';
@ -38,27 +38,27 @@ class _CarbsState extends State<Carbs> {
double fCalMeal; double fCalMeal;
void calculateDietRatios() { void calculateDietRatios() {
if (dropdownValue == 'Very Low Carb') { if (dropdownValue == TranslationBase.of(context).dietVeryLow) {
meals = 3; meals = 3;
protein = 45; protein = 45;
carbs = 10; carbs = 10;
fat = 45; fat = 45;
} else if (dropdownValue == 'Low Carb') { } else if (dropdownValue == TranslationBase.of(context).dietLow) {
meals = 3; meals = 3;
protein = 40; protein = 40;
carbs = 30; carbs = 30;
fat = 30; fat = 30;
} else if (dropdownValue == 'Moderate Carb') { } else if (dropdownValue == TranslationBase.of(context).dietModerate) {
meals = 3; meals = 3;
protein = 25; protein = 25;
carbs = 50; carbs = 50;
fat = 25; fat = 25;
} else if (dropdownValue == 'USDA Gudilines') { } else if (dropdownValue == TranslationBase.of(context).dietUSDA) {
meals = 3; meals = 3;
protein = 15; protein = 15;
carbs = 55; carbs = 55;
fat = 30; fat = 30;
} else if (dropdownValue == 'Zone Diet') { } else if (dropdownValue == TranslationBase.of(context).dietZone) {
meals = 3; meals = 3;
protein = 30; protein = 30;
carbs = 40; carbs = 40;
@ -82,6 +82,7 @@ class _CarbsState extends State<Carbs> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ProjectViewModel projectViewModel = Provider.of(context);
return AppScaffold( return AppScaffold(
isShowAppBar: true, isShowAppBar: true,
isShowDecPage: false, isShowDecPage: false,
@ -107,7 +108,7 @@ class _CarbsState extends State<Carbs> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Calculates carbohydrate protein and fat ratio in calories and grams according to a pre-set ratio', TranslationBase.of(context).carbProteinDesc,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@ -122,7 +123,7 @@ class _CarbsState extends State<Carbs> {
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
inputWidget("The Calories per day", "0", textController), inputWidget(TranslationBase.of(context).calDay, "0", textController),
InkWell( InkWell(
onTap: () { onTap: () {
Navigator.push( Navigator.push(
@ -133,7 +134,7 @@ class _CarbsState extends State<Carbs> {
child: Padding( child: Padding(
padding: const EdgeInsets.all(12.0), padding: const EdgeInsets.all(12.0),
child: Text( child: Text(
'NOT SURE? CLICK HERE', TranslationBase.of(context).notSure,
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.accentColor, decoration: TextDecoration.underline), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.accentColor, decoration: TextDecoration.underline),
), ),
), ),
@ -159,7 +160,7 @@ class _CarbsState extends State<Carbs> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
"Select Diet Type", TranslationBase.of(context).selectDiet,
style: TextStyle( style: TextStyle(
fontSize: 11, fontSize: 11,
letterSpacing: -0.44, letterSpacing: -0.44,
@ -186,10 +187,16 @@ class _CarbsState extends State<Carbs> {
calculateDietRatios(); calculateDietRatios();
}); });
}, },
items: <String>['Very Low Carb', 'Low Carb', 'Moderate Carb', 'USDA Gudilines', 'Zone Diet'].map<DropdownMenuItem<String>>((String value) { items: <String>[
TranslationBase.of(context).dietVeryLow,
TranslationBase.of(context).dietLow,
TranslationBase.of(context).dietModerate,
TranslationBase.of(context).dietUSDA,
TranslationBase.of(context).dietZone
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(value), child: Text(value, style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)),
); );
}).toList(), }).toList(),
), ),

@ -1,11 +1,13 @@
import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'ideal_body_result_page.dart'; import 'ideal_body_result_page.dart';
@ -34,7 +36,7 @@ class _IdealBodyState extends State<IdealBody> {
double overWeightBy; double overWeightBy;
int weight = 0; int weight = 0;
double idealWeight = 0; double idealWeight = 0;
String dropdownValue = 'Medium(fingers touch)'; String dropdownValue = TranslationBase.of(AppGlobal.context).bodyFrameMedium;
double calories = 0; double calories = 0;
String textResult = ''; String textResult = '';
double maxIdealWeight; double maxIdealWeight;
@ -52,17 +54,15 @@ class _IdealBodyState extends State<IdealBody> {
List<PopupMenuItem> _heightPopupList = List(); List<PopupMenuItem> _heightPopupList = List();
List<PopupMenuItem> _weightPopupList = List(); List<PopupMenuItem> _weightPopupList = List();
void calculateIdealWeight() { void calculateIdealWeight() {
heightInches = int.parse(_heightController.text) * .39370078740157477; heightInches = int.parse(_heightController.text) * .39370078740157477;
heightFeet = heightInches / 12; heightFeet = heightInches / 12;
idealWeight = (50 + 2.3 * (heightInches - 60)); idealWeight = (50 + 2.3 * (heightInches - 60));
if (dropdownValue == 'Small(fingers overlap)') { if (dropdownValue == TranslationBase.of(context).bodyFrameSmall) {
idealWeight = idealWeight - 10; idealWeight = idealWeight - 10;
} else if (dropdownValue == 'Medium(fingers touch)') { } else if (dropdownValue == TranslationBase.of(context).bodyFrameMedium) {
idealWeight = idealWeight; idealWeight = idealWeight;
} else if (dropdownValue == 'Large(fingers don\'n touch)') { } else if (dropdownValue == TranslationBase.of(context).bodyFrameLarge) {
idealWeight = idealWeight + 10; idealWeight = idealWeight + 10;
} }
@ -75,6 +75,7 @@ class _IdealBodyState extends State<IdealBody> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ProjectViewModel projectViewModel = Provider.of(context);
_weightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)]; _weightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)];
_heightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)]; _heightPopupList = <PopupMenuItem>[PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)];
@ -94,7 +95,7 @@ class _IdealBodyState extends State<IdealBody> {
child: Column( child: Column(
children: [ children: [
Text( Text(
'Calculates the ideal body weight based on height, Weight, and Body Size', TranslationBase.of(context).idealWeightDesc,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@ -177,7 +178,7 @@ class _IdealBodyState extends State<IdealBody> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
"Body Frame Size", TranslationBase.of(context).bodyFrame,
style: TextStyle( style: TextStyle(
fontSize: 11, fontSize: 11,
letterSpacing: -0.44, letterSpacing: -0.44,
@ -204,13 +205,14 @@ class _IdealBodyState extends State<IdealBody> {
}); });
}, },
items: <String>[ items: <String>[
'Small(fingers overlap)', TranslationBase.of(context).bodyFrameSmall,
'Medium(fingers touch)', TranslationBase.of(context).bodyFrameMedium,
'Large(fingers don\'n touch)', TranslationBase.of(context).bodyFrameLarge,
].map<DropdownMenuItem<String>>((String value) { ].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(value), child: Text(value,
style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)),
); );
}).toList(), }).toList(),
), ),
@ -498,5 +500,3 @@ class CommonDropDownView extends StatelessWidget {
); );
} }
} }

@ -59,13 +59,6 @@ class _BillAmountState extends State<BillAmount> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Text(TranslationBase.of(context).testFee,
// style: TextStyle(
// color: Colors.black,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// letterSpacing: -0.64,
// )),
Container( Container(
width: double.infinity, width: double.infinity,
padding: EdgeInsets.only(top: 10, bottom: 3), padding: EdgeInsets.only(top: 10, bottom: 3),

@ -1,19 +1,23 @@
import 'package:after_layout/after_layout.dart'; import 'package:after_layout/after_layout.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/ResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/ResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/tamara_payment_option.dart';
import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/PackageOrderCompletedPage.dart'; import 'package:diplomaticquarterapp/pages/packages_offers/PackageOrderCompletedPage.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart' as utils; import 'package:diplomaticquarterapp/uitl/utils.dart' as utils;
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart'; import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesCartItemCard.dart'; import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesCartItemCard.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/single_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -22,6 +26,9 @@ import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
dynamic languageID; dynamic languageID;
const _columnCount = 1; const _columnCount = 1;
bool _agreeTerms = false;
String _selectedPaymentMethod;
Map<dynamic, dynamic> _selectedPaymentParams;
AnimationController _animationController; AnimationController _animationController;
@ -38,6 +45,8 @@ class _PackagesCartPageState extends State<PackagesCartPage> with AfterLayoutMix
} }
double subtotal, tax, total; double subtotal, tax, total;
int _selectedHospitalIndex = -1;
HospitalsModel _selectedHospital;
@override @override
void initState() { void initState() {
@ -67,9 +76,8 @@ class _PackagesCartPageState extends State<PackagesCartPage> with AfterLayoutMix
} }
onPayNowClick() async { onPayNowClick() async {
await viewModel.service.placeOrder(context: context, paymentParams: _selectedPaymentParams).then((orderId) { await viewModel.service.placeOrder(context: context, projectID: _selectedHospital.iD, paymentParams: _selectedPaymentParams).then((orderId) {
if (orderId.runtimeType == int) { if (orderId.runtimeType == int) {
// result == order_id
var browser = MyInAppBrowser(context: context, onExitCallback: (data, isDone) => paymentClosed(orderId: orderId, withStatus: isDone, data: data)); var browser = MyInAppBrowser(context: context, onExitCallback: (data, isDone) => paymentClosed(orderId: orderId, withStatus: isDone, data: data));
browser.openPackagesPaymentBrowser(customer_id: viewModel.service.customer.id, order_id: orderId); browser.openPackagesPaymentBrowser(customer_id: viewModel.service.customer.id, order_id: orderId);
} else { } else {
@ -83,100 +91,248 @@ class _PackagesCartPageState extends State<PackagesCartPage> with AfterLayoutMix
@override @override
void afterFirstLayout(BuildContext context) { void afterFirstLayout(BuildContext context) {
fetchData(); fetchData();
viewModel.service.getHospitals();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BaseView<PackagesViewModel>( return BaseView<PackagesViewModel>(
allowAny: true, allowAny: true,
onModelReady: (model) => viewModel = model, onModelReady: (model) => viewModel = model,
builder: (_, model, wi) { builder: (_, model, wi) {
return AppScaffold( return AppScaffold(
appBarTitle: TranslationBase.of(context).offerAndPackages, appBarTitle: TranslationBase.of(context).offerAndPackages,
isShowAppBar: true, isShowAppBar: true,
isPharmacy: false, isPharmacy: false,
showPharmacyCart: false, showPharmacyCart: false,
showHomeAppBarIcon: false, showHomeAppBarIcon: false,
isOfferPackages: true, isOfferPackages: true,
showOfferPackagesCart: false, showOfferPackagesCart: false,
isShowDecPage: false, isShowDecPage: false,
showNewAppBar: true, showNewAppBar: true,
showNewAppBarTitle: true, showNewAppBarTitle: true,
body: Column( body: viewModel.cartItemList.length > 0
children: [ ? Column(
Expanded( children: [
child: StaggeredGridView.countBuilder( Expanded(
crossAxisCount: (_columnCount * _columnCount), child: StaggeredGridView.countBuilder(
itemCount: viewModel.cartItemList.length, crossAxisCount: (_columnCount * _columnCount),
itemBuilder: (BuildContext context, int index) { itemCount: viewModel.cartItemList.length,
var item = viewModel.cartItemList[index]; itemBuilder: (BuildContext context, int index) {
return Dismissible( var item = viewModel.cartItemList[index];
key: Key(index.toString()), return Dismissible(
direction: DismissDirection.startToEnd, key: Key(index.toString()),
background: _cartItemDeleteContainer(), direction: DismissDirection.startToEnd,
secondaryBackground: _cartItemDeleteContainer(), background: _cartItemDeleteContainer(),
confirmDismiss: (direction) async { secondaryBackground: _cartItemDeleteContainer(),
bool status = await viewModel.service.deleteProductFromCart(item.id, context: context, showLoading: false); confirmDismiss: (direction) async {
return status; bool status = await viewModel.service.deleteProductFromCart(item.id, context: context, showLoading: false);
}, return status;
onDismissed: (direction) { },
viewModel.cartItemList.removeAt(index); onDismissed: (direction) {
}, viewModel.cartItemList.removeAt(index);
child: PackagesCartItemCard( },
itemModel: item, child: PackagesCartItemCard(
viewModel: viewModel, itemModel: item,
getCartItems: fetchData, viewModel: viewModel,
shouldStepperChangeApply: (apply, total) async { getCartItems: fetchData,
var request = AddProductToCartRequestModel(product_id: item.productId, quantity: apply); shouldStepperChangeApply: (apply, total) async {
ResponseModel response = await viewModel.service.addProductToCart(request, context: context, showLoading: false).catchError((error) { var request = AddProductToCartRequestModel(product_id: item.productId, quantity: apply);
utils.Utils.showErrorToast(error); ResponseModel response = await viewModel.service.addProductToCart(request, context: context, showLoading: false).catchError((error) {
}); utils.Utils.showErrorToast(error);
if (response.status) { });
fetchData(); if (response.status) {
} fetchData();
return response.status ?? false; }
}, return response.status ?? false;
)); },
}, ));
staggeredTileBuilder: (int index) => StaggeredTile.fit(_columnCount), },
mainAxisSpacing: 0, staggeredTileBuilder: (int index) => StaggeredTile.fit(_columnCount),
crossAxisSpacing: 10, mainAxisSpacing: 0,
), crossAxisSpacing: 10,
), ),
Container( ),
height: 0.25, Container(
color: Theme.of(context).primaryColor, height: 0.25,
), color: Theme.of(context).primaryColor,
Container( ),
],
)
: getNoDataWidget(context),
bottomSheet: viewModel.cartItemList.length > 0
? Container(
padding: EdgeInsets.all(21.0),
width: double.infinity,
color: Colors.white, color: Colors.white,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [ children: [
Texts(TranslationBase.of(context).selectPaymentOption, fontSize: 10, fontWeight: FontWeight.bold),
Container( Container(
height: 0.25, margin: EdgeInsets.only(bottom: 12.0),
width: 100, child: InkWell(
color: Colors.grey[300], onTap: () => confirmSelectHospitalDialog(model.hospitals),
child: Container(
padding: EdgeInsets.all(12),
width: double.infinity,
height: 50,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), border: Border.all(color: CustomColors.devider), color: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
getHospitalName(),
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
letterSpacing: -0.46,
),
),
Icon(Icons.arrow_drop_down),
],
),
),
),
),
Container(
margin: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0),
child: Text(TranslationBase.of(context).YouCanPayByTheFollowingOptions, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600)),
),
Container(
width: MediaQuery.of(context).size.width * 0.75,
margin: EdgeInsets.fromLTRB(0.0, 8.0, 20.0, 5.0),
child: getPaymentMethods(),
),
Container(
margin: EdgeInsets.only(top: 14.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 24.0,
width: 24.0,
child: Checkbox(
value: _agreeTerms,
onChanged: (v) {
setState(() => _agreeTerms = v);
}),
),
Expanded(
child: Text(
TranslationBase.of(context).iAcceptTermsConditions,
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: CustomColors.textColor, letterSpacing: -0.48),
),
),
],
),
), ),
_paymentOptions(context, (paymentMethod) {
setState(() => _selectedPaymentMethod = paymentMethod);
}, viewModel: viewModel),
Container( Container(
height: 0.25, child: Column(
color: Colors.grey[300], crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
padding: EdgeInsets.only(top: 12, bottom: 3),
child: Row(
children: [
Expanded(
child: _getNormalText(TranslationBase.of(context).patientShareToDo),
),
Expanded(
child: _getNormalText(TranslationBase.of(context).sar + " " + (subtotal ?? 0.0).toStringAsFixed(2), isBold: true),
)
],
),
),
mDivider(Colors.grey[200]),
Container(
width: double.infinity,
padding: EdgeInsets.only(top: 3, bottom: 3),
child: Row(
children: [
Expanded(
child: _getNormalText(TranslationBase.of(context).patientTaxToDo),
),
Expanded(
child: _getNormalText(TranslationBase.of(context).sar + ' ' + (tax ?? 0.0).toStringAsFixed(2), isBold: true),
)
],
),
),
mDivider(Colors.grey[200]),
Container(
width: double.infinity,
padding: EdgeInsets.only(top: 3, bottom: 3),
child: Row(
children: [
Expanded(
child: _getNormalText(TranslationBase.of(context).patientShareTotalToDo),
),
Expanded(
child: _getNormalText(TranslationBase.of(context).sar + ' ' + (total ?? 0.0).toStringAsFixed(2), isBold: true, isTotal: true),
)
],
),
),
],
),
), ),
Container(height: 40, child: _termsAndCondition(context, onSelected: onTermsClick, onInfoClick: onTermsInfoClick)),
Container( Container(
height: 0.25, padding: EdgeInsets.only(top: 21, bottom: 21),
color: Colors.grey[300], child: DefaultButton(
TranslationBase.of(context).payNow,
(_agreeTerms && _selectedHospital != null)
? () {
Navigator.push(context, FadePage(page: PaymentMethod(onSelectedMethod: (String metohd) {
setState(() {});
}))).then((value) {
print(value);
if (value != null) {
_selectedPaymentMethod = value;
_selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": value};
onPayNowClick();
}
});
}
: null,
color: CustomColors.green,
disabledColor: CustomColors.grey2,
),
), ),
_payNow(context, subtotal: subtotal, tax: tax, total: total, onPayNowClick: onPayNowClick)
], ],
), ),
) )
], : SizedBox(),
), );
); },
}); );
}
void confirmSelectHospitalDialog(List<HospitalsModel> hospitals) {
List<RadioSelectionDialogModel> list = [
for (int i = 0; i < hospitals.length; i++) RadioSelectionDialogModel(hospitals[i].name + ' ${hospitals[i].distanceInKilometers} ' + TranslationBase.of(context).km, i),
];
showDialog(
context: context,
child: RadioSelectionDialog(
listData: list,
selectedIndex: _selectedHospitalIndex,
isScrollable: true,
onValueSelected: (index) {
_selectedHospitalIndex = index;
_selectedHospital = hospitals[index];
setState(() {});
},
),
);
}
String getHospitalName() {
if (_selectedHospital != null)
return _selectedHospital.name;
else
return TranslationBase.of(context).selectHospital;
} }
fetchData() async { fetchData() async {
@ -201,196 +357,73 @@ class _PackagesCartPageState extends State<PackagesCartPage> with AfterLayoutMix
} }
} }
// /* Payment Footer Widgets */ // Widget _payNow(BuildContext context, {double subtotal, double tax, double total, @required VoidCallback onPayNowClick}) {
// --------------------------- // bool isPayNowAQctive = (_agreeTerms && (_selectedPaymentMethod != null));
String _selectedPaymentMethod; //
Map<dynamic, dynamic> _selectedPaymentParams; // String _subtotal = (subtotal ?? 0.0).toStringAsFixed(2);
// String _tax = (tax ?? 0.0).toStringAsFixed(2);
// String _total = (total ?? 0).toStringAsFixed(2);
//
// return Padding(
// padding: const EdgeInsets.all(5),
// child: Container(
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.end,
// children: [
// Padding(
// padding: const EdgeInsets.all(5),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Texts('${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8),
// Texts('${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8),
// Padding(
// padding: const EdgeInsets.all(3),
// child: Container(
// height: 0.25,
// width: 120,
// color: Colors.grey[300],
// ),
// ),
// Texts('${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 15)
// ],
// ),
// ),
// Expanded(child: Container()),
// RaisedButton(
// elevation: 0,
// child: Texts(
// TranslationBase.of(context).payNow,
// fontSize: 15,
// color: Colors.white,
// fontWeight: FontWeight.bold,
// ),
// padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0),
// shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5), side: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)),
// color: Theme.of(context).primaryColor,
// onPressed: isPayNowAQctive ? onPayNowClick : null,
// ),
// ],
// )),
// );
// }
Widget _paymentOptions(BuildContext context, Function(String) onSelected, {PackagesViewModel viewModel}) { _getNormalText(text, {bool isBold = false, bool isTotal = false}) {
double height = 30; return Text(
text,
Widget buttonContent(bool isSelected, String imageName) { style: TextStyle(
return Container( fontSize: isBold
decoration: BoxDecoration( ? isTotal
color: Colors.white, ? 16
boxShadow: [ : 12
BoxShadow( : 10,
color: isSelected ? Colors.green[50] : Colors.grey[200], letterSpacing: -0.5,
blurRadius: 1, color: isBold ? Colors.black : Colors.grey[700],
spreadRadius: 2, fontWeight: FontWeight.w600,
),
],
borderRadius: BorderRadius.all(Radius.circular(5)),
border: Border.all(color: isSelected ? Colors.green : Colors.grey, width: isSelected ? 1 : 0.5)),
child: Padding(
padding: const EdgeInsets.all(4),
child: Image.asset('assets/images/new-design/$imageName'),
));
}
Future<String> selectTamaraPaymentOption() async {
final tamara_options = await viewModel.service.getTamaraOptions(context: context, showLoading: true);
final selected =
await SingleSelectionDialog<TamaraPaymentOption>(tamara_options, icon: Image.asset('assets/images/new-design/tamara.png'), title: TranslationBase.of(context).tamaraInstPlan).show(context);
return selected.name;
}
return Padding(
padding: const EdgeInsets.all(5),
child: Container(
height: height,
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
child: buttonContent(_selectedPaymentMethod == "tamara", 'tamara.png'),
onTap: () async {
final tamara_option = await selectTamaraPaymentOption();
_selectedPaymentParams = {"channel": "Web", "payment_method_system_name": "Payments.Tamara", "payment_option": tamara_option};
onSelected("tamara");
},
),
SizedBox(
width: 5,
),
InkWell(
child: buttonContent(_selectedPaymentMethod == "mada", 'mada.png'),
onTap: () {
_selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MADA"};
onSelected("mada");
},
),
SizedBox(
width: 5,
),
InkWell(
child: buttonContent(_selectedPaymentMethod == "visa", 'visa.png'),
onTap: () {
_selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "VISA"};
onSelected("visa");
},
),
SizedBox(
width: 5,
),
InkWell(
child: buttonContent(_selectedPaymentMethod == "mastercard", 'mastercard.png'),
onTap: () {
_selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MASTERCARD"};
onSelected("mastercard");
},
),
// SizedBox(
// width: 5,
// ),
// InkWell(
// child: buttonContent(
// _selectedPaymentMethod == "installment", 'installment.png'),
// onTap: () {
// _selectedPaymentParams = {"payment_method_system_name" : "Payments.PayFort", "payment_option" : "INSTALLMENT"};
// onSelected("installment");
// },
// ),
],
),
), ),
); );
} }
bool _agreeTerms = false;
Widget _termsAndCondition(BuildContext context, {@required Function(bool) onSelected, @required VoidCallback onInfoClick}) {
return Padding(
padding: const EdgeInsets.all(5),
child: Row(
children: [
InkWell(
child: Icon(
_agreeTerms ? Icons.check_circle : Icons.radio_button_unchecked_sharp,
size: 20,
color: _agreeTerms ? Colors.green[600] : Colors.grey[400],
),
onTap: () {
onSelected(!_agreeTerms);
},
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Texts(
TranslationBase.of(context).pharmacyServiceTermsCondition,
fontWeight: FontWeight.normal,
fontSize: 13,
),
)),
InkWell(
child: Icon(
Icons.info,
size: 20,
color: Colors.grey[600],
),
onTap: () {
onInfoClick();
},
),
],
),
);
}
Widget _payNow(BuildContext context, {double subtotal, double tax, double total, @required VoidCallback onPayNowClick}) {
bool isPayNowAQctive = (_agreeTerms && (_selectedPaymentMethod != null));
String _subtotal = (subtotal ?? 0.0).toStringAsFixed(2);
String _tax = (tax ?? 0.0).toStringAsFixed(2);
String _total = (total ?? 0).toStringAsFixed(2);
return Padding(
padding: const EdgeInsets.all(5),
child: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Texts('${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8),
Texts('${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8),
Padding(
padding: const EdgeInsets.all(3),
child: Container(
height: 0.25,
width: 120,
color: Colors.grey[300],
),
),
Texts('${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 15)
],
),
),
Expanded(child: Container()),
RaisedButton(
elevation: 0,
child: Texts(
TranslationBase.of(context).payNow,
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold,
),
padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5), side: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)),
color: Theme.of(context).primaryColor,
onPressed: isPayNowAQctive ? onPayNowClick : null,
),
],
)),
);
}
// -------------------
Widget _cartItemDeleteContainer() { Widget _cartItemDeleteContainer() {
_animationController.duration = Duration(milliseconds: 500); _animationController.duration = Duration(milliseconds: 500);
_animationController.repeat(reverse: true); _animationController.repeat(reverse: true);

@ -68,7 +68,7 @@ class _FooterWidgetState extends State<FooterWidget> {
Padding( Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: Text( child: Text(
"Quantity", TranslationBase.of(context).quantity,
style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
), ),
), ),
@ -157,17 +157,19 @@ class _FooterWidgetState extends State<FooterWidget> {
), ),
], ],
), ),
onPressed: () { onPressed: widget.isAvailable && !widget.item.isRx
setState(() { ? () {
if (showUI) { setState(() {
quantityUI = 80; if (showUI) {
showUI = false; quantityUI = 80;
} else { showUI = false;
quantityUI = 160; } else {
showUI = true; quantityUI = 160;
} showUI = true;
}); }
}, });
}
: null,
), ),
), ),
SizedBox( SizedBox(
@ -207,20 +209,20 @@ class _FooterWidgetState extends State<FooterWidget> {
); );
} else { } else {
await widget.addToShoppingCartFunction(quantity: widget.quantity, itemID: widget.item.id, model: widget.model); await widget.addToShoppingCartFunction(quantity: widget.quantity, itemID: widget.item.id, model: widget.model);
Navigator.of(context).pushNamed( // Navigator.of(context).pushNamed(
CART_ORDER_PAGE, // CART_ORDER_PAGE,
);
// Navigator.push(
// context,
// FadePage(page: CartOrderPage()),
// ); // );
Navigator.push(
context,
FadePage(page: CartOrderPage()),
);
} }
}, },
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
borderColor: Colors.grey[800], borderColor: Colors.grey[800],
borderRadius: 3, borderRadius: 3,
disableColor: Colors.grey[700], disableColor: Colors.grey[700],
color: !widget.isAvailable && widget.quantity > 0 || widget.quantity > widget.quantityLimit || widget.item.rxMessage != null ? Colors.grey : Colors.grey[800], color: !widget.isAvailable && widget.quantity > 0 || widget.quantity > widget.quantityLimit || widget.item.isRx ? Colors.grey : Colors.grey[800],
), ),
), ),
], ],

@ -87,6 +87,9 @@ class __ProductDetailPageState extends State<ProductDetailPage> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BaseView<ProductDetailViewModel>( return BaseView<ProductDetailViewModel>(
allowAny: true, allowAny: true,
onModelReady: (model) {
model.getProductReviewsData(widget.product.id);
},
builder: (_, model, wi) => AppScaffold( builder: (_, model, wi) => AppScaffold(
appBarTitle: TranslationBase.of(context).productDetails, appBarTitle: TranslationBase.of(context).productDetails,
isShowAppBar: true, isShowAppBar: true,
@ -146,6 +149,7 @@ class __ProductDetailPageState extends State<ProductDetailPage> {
notifyMeWhenAvailable(itemId: itemId, customerId: customerId, model: model); notifyMeWhenAvailable(itemId: itemId, customerId: customerId, model: model);
}, },
isInWishList: isInWishList, isInWishList: isInWishList,
isStockAvailable: model.isStockAvailable,
), ),
), ),
SizedBox( SizedBox(
@ -302,10 +306,10 @@ class __ProductDetailPageState extends State<ProductDetailPage> {
), ),
), ),
bottomSheet: FooterWidget( bottomSheet: FooterWidget(
widget.product.stockAvailability != 'Out of stock', model.isStockAvailable,
widget.product.orderMaximumQuantity, widget.product.orderMaximumQuantity,
widget.product.orderMinimumQuantity, widget.product.orderMinimumQuantity,
widget.product.stockQuantity, model.stockQuantity,
widget.product, widget.product,
quantity: quantity, quantity: quantity,
isOverQuantity: isOverQuantity, isOverQuantity: isOverQuantity,

@ -1,7 +1,6 @@
import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart'; import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart'; import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -20,16 +19,12 @@ class ProductNameAndPrice extends StatefulWidget {
final Function notifyMeWhenAvailable; final Function notifyMeWhenAvailable;
final Function addToWishlistFunction; final Function addToWishlistFunction;
final Function deleteFromWishlistFunction; final Function deleteFromWishlistFunction;
final bool isStockAvailable;
AuthenticatedUserObject authenticatedUserObject = AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();
locator<AuthenticatedUserObject>();
ProductNameAndPrice(this.context, this.item, ProductNameAndPrice(this.context, this.item,
{this.customerId, {this.customerId, this.isInWishList, this.notifyMeWhenAvailable, this.addToWishlistFunction, this.deleteFromWishlistFunction, @required this.isStockAvailable});
this.isInWishList,
this.notifyMeWhenAvailable,
this.addToWishlistFunction,
this.deleteFromWishlistFunction});
@override @override
_ProductNameAndPriceState createState() => _ProductNameAndPriceState(); _ProductNameAndPriceState createState() => _ProductNameAndPriceState();
@ -51,25 +46,18 @@ class _ProductNameAndPriceState extends State<ProductNameAndPrice> {
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Texts(widget.item.price.toString() + " " + "SR", Texts(widget.item.price.toString() + " " + TranslationBase.of(context).sar, fontWeight: FontWeight.bold, fontSize: 20),
fontWeight: FontWeight.bold, fontSize: 20),
Texts( Texts(
projectViewModel.isArabic projectViewModel.isArabic ? widget.item.stockAvailabilityn : widget.item.stockAvailability,
? widget.item.stockAvailabilityn
: widget.item.stockAvailability,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 15, fontSize: 15,
color: widget.item.stockAvailability == 'Out of stock' color: widget.isStockAvailable ? Colors.green : Colors.red,
? Colors.red
: Colors.green,
), ),
// SizedBox(width: 20), // SizedBox(width: 20),
if (widget.authenticatedUserObject.isLogin) if (widget.authenticatedUserObject.isLogin)
widget.item.stockAvailability == 'Out of stock' && widget.isStockAvailable && widget.customerId != null
widget.customerId != null
? InkWell( ? InkWell(
onTap: () => widget.notifyMeWhenAvailable( onTap: () => widget.notifyMeWhenAvailable(context, widget.item.id),
context, widget.item.id),
child: Row(children: [ child: Row(children: [
Texts( Texts(
TranslationBase.of(context).notifyMe, TranslationBase.of(context).notifyMe,
@ -85,23 +73,15 @@ class _ProductNameAndPriceState extends State<ProductNameAndPrice> {
]), ]),
) )
: IconWithBg( : IconWithBg(
icon: !widget.isInWishList icon: !widget.isInWishList ? Icons.favorite_border : Icons.favorite,
? Icons.favorite_border color: !widget.isInWishList ? Colors.white : Colors.red[800],
: Icons.favorite,
color: !widget.isInWishList
? Colors.white
: Colors.red[800],
onPress: () async { onPress: () async {
{ {
if (widget.customerId != null) { if (widget.customerId != null) {
if (!widget.isInWishList) { if (!widget.isInWishList) {
await widget.addToWishlistFunction(widget.item.id);
await widget
.addToWishlistFunction(widget.item.id);
} else { } else {
await widget await widget.deleteFromWishlistFunction(widget.item.id);
.deleteFromWishlistFunction(widget.item.id);
} }
} else { } else {
return; return;
@ -118,13 +98,9 @@ class _ProductNameAndPriceState extends State<ProductNameAndPrice> {
child: Container( child: Container(
margin: EdgeInsets.only(left: 5), margin: EdgeInsets.only(left: 5),
child: Align( child: Align(
alignment: projectViewModel.isArabic alignment: projectViewModel.isArabic ? Alignment.topRight : Alignment.topLeft,
? Alignment.topRight
: Alignment.topLeft,
child: Text( child: Text(
projectViewModel.isArabic projectViewModel.isArabic ? widget.item.namen : widget.item.name,
? widget.item.namen
: widget.item.name,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
), ),
), ),
@ -140,8 +116,7 @@ class _ProductNameAndPriceState extends State<ProductNameAndPrice> {
child: Row( child: Row(
children: [ children: [
RatingBar.readOnly( RatingBar.readOnly(
initialRating: double.parse( initialRating: double.parse(widget.item.approvedRatingSum.toString()),
widget.item.approvedRatingSum.toString()),
size: 15.0, size: 15.0,
filledColor: Colors.yellow[700], filledColor: Colors.yellow[700],
emptyColor: Colors.grey[400], emptyColor: Colors.grey[400],
@ -172,19 +147,9 @@ class _ProductNameAndPriceState extends State<ProductNameAndPrice> {
Row( Row(
children: [ children: [
Text( Text(
projectViewModel.isArabic projectViewModel.isArabic ? widget.item.rxMessagen.toString() : widget.item.rxMessage.toString(),
? widget.item.rxMessagen.toString()
: widget.item.rxMessage.toString(),
style: TextStyle(color: Colors.red, fontSize: 10), style: TextStyle(color: Colors.red, fontSize: 10),
), ),
SizedBox(
width: 5,
),
Icon(
FontAwesomeIcons.questionCircle,
color: Colors.red,
size: 15.0,
)
], ],
) )
], ],

@ -15,36 +15,53 @@ import 'package:diplomaticquarterapp/uitl/app_toast.dart';
class ProductDetailService extends BaseService { class ProductDetailService extends BaseService {
bool isLogin = false; bool isLogin = false;
num _stockQuantity;
num get stockQuantity => _stockQuantity;
String _stockAvailability;
String get stockAvailability => _stockAvailability;
bool _isStockAvailable;
bool get isStockAvailable => _isStockAvailable;
List<ProductDetail> _productDetailList = List(); List<ProductDetail> _productDetailList = List();
List<ProductDetail> get productDetailList => _productDetailList; List<ProductDetail> get productDetailList => _productDetailList;
List<LocationModel> _productLocationList = List(); List<LocationModel> _productLocationList = List();
List<LocationModel> get productLocationList => _productLocationList; List<LocationModel> get productLocationList => _productLocationList;
List<Wishlist> _addToCartModel = List(); List<Wishlist> _addToCartModel = List();
List<Wishlist> get addToCartModel => _addToCartModel; List<Wishlist> get addToCartModel => _addToCartModel;
List<Wishlist> _wishListProducts = List(); List<Wishlist> _wishListProducts = List();
List<Wishlist> get wishListProducts => _wishListProducts; List<Wishlist> get wishListProducts => _wishListProducts;
List<SpecificationModel> _productSpecification = List(); List<SpecificationModel> _productSpecification = List();
List<SpecificationModel> get productSpecification => _productSpecification;
List<SpecificationModel> get productSpecification => _productSpecification;
Future getProductReviews(productID) async { Future getProductReviews(productID) async {
hasError = false; hasError = false;
await baseAppClient.getPharmacy(GET_PRODUCT_DETAIL+productID+"?fields=reviews", await baseAppClient.getPharmacy(GET_PRODUCT_DETAIL + productID + "?fields=reviews,stock_quantity,stock_availability,IsStockAvailable", onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _productDetailList.clear();
_productDetailList.clear(); response['products'].forEach((item) {
response['products'].forEach((item) { _productDetailList.add(ProductDetail.fromJson(item));
_productDetailList.add(ProductDetail.fromJson(item)); print(response);
print(response); });
}); _stockQuantity = response['products'][0]['stock_quantity'];
}, onFailure: (String error, int statusCode) { _stockAvailability = response['products'][0]['stock_availability'];
hasError = true; _isStockAvailable = response['products'][0]['IsStockAvailable'];
super.error = error; }, onFailure: (String error, int statusCode) {
}); hasError = true;
super.error = error;
});
} }
Future getProductAvailabiltyDetail() async { Future getProductAvailabiltyDetail() async {
@ -52,29 +69,28 @@ class ProductDetailService extends BaseService {
Map<String, dynamic> request; Map<String, dynamic> request;
request = { request = {
"Channel": 3, // "Channel": 3,
"DeviceTypeID": 2, // "DeviceTypeID": 2,
"IPAdress": "10.20.10.20", // "IPAdress": "10.20.10.20",
"LanguageID": 2, // "LanguageID": 2,
"PatientOutSA": 0, // "PatientOutSA": 0,
"SKU": "6720020025", // "SKU": "6720020025",
"SessionID": null, // "SessionID": null,
"VersionID": 5.6, // "VersionID": 5.6,
"generalid": "Cs2020@2016\$2958", // "generalid": "Cs2020@2016\$2958",
"isDentalAllowedBackend": false // "isDentalAllowedBackend": false
}; };
await baseAppClient.post(GET_LOCATION, await baseAppClient.post(GET_LOCATION, onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _productLocationList.clear();
_productLocationList.clear(); response['PharmList'].forEach((item) {
response['PharmList'].forEach((item) { _productLocationList.add(LocationModel.fromJson(item));
_productLocationList.add(LocationModel.fromJson(item)); print(_productLocationList);
print(_productLocationList); print(response);
print(response); });
}); }, onFailure: (String error, int statusCode) {
}, onFailure: (String error, int statusCode) { hasError = true;
hasError = true; super.error = error;
super.error = error; }, body: request);
}, body: request);
} }
Future<Map> addToCart(quantity, itemID) async { Future<Map> addToCart(quantity, itemID) async {
@ -83,30 +99,22 @@ class ProductDetailService extends BaseService {
Map<String, dynamic> request; Map<String, dynamic> request;
request = { request = {
"shopping_cart_item": "shopping_cart_item": {"quantity": quantity, "shopping_cart_type": "1", "product_id": itemID, "customer_id": customerId, "language_id": 1}
{
"quantity": quantity,
"shopping_cart_type": "1",
"product_id": itemID,
"customer_id": customerId,
"language_id": 1
}
}; };
dynamic localRes; dynamic localRes;
await baseAppClient.pharmacyPost(GET_SHOPPING_CART, isExternal: false, await baseAppClient.pharmacyPost(GET_SHOPPING_CART, isExternal: false, onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _addToCartModel.clear();
_addToCartModel.clear(); response['shopping_carts'].forEach((item) {
response['shopping_carts'].forEach((item) { _addToCartModel.add(Wishlist.fromJson(item));
_addToCartModel.add(Wishlist.fromJson(item)); });
}); AppToast.showSuccessToast(message: 'You have added a product to the cart');
AppToast.showSuccessToast(message: 'You have added a product to the cart'); localRes = response;
localRes = response; }, onFailure: (String error, int statusCode) {
}, onFailure: (String error, int statusCode) { hasError = true;
hasError = true; super.error = error;
super.error = error; AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage());
AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); }, body: request);
}, body: request);
return Future.value(localRes); return Future.value(localRes);
} }
@ -118,7 +126,7 @@ class ProductDetailService extends BaseService {
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
hasError = true; hasError = true;
super.error = error; super.error = error;
AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage());
}); });
} }
@ -130,67 +138,61 @@ class ProductDetailService extends BaseService {
request = { request = {
"shopping_cart_item": {"quantity": 1, "shopping_cart_type": "Wishlist", "product_id": itemID, "customer_id": customerId, "language_id": 1} "shopping_cart_item": {"quantity": 1, "shopping_cart_type": "Wishlist", "product_id": itemID, "customer_id": customerId, "language_id": 1}
}; };
await baseAppClient.pharmacyPost(GET_SHOPPING_CART, await baseAppClient.pharmacyPost(GET_SHOPPING_CART, onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _wishListProducts.clear();
_wishListProducts.clear(); response['shopping_carts'].forEach((item) {
response['shopping_carts'].forEach((item) { _wishListProducts.add(Wishlist.fromJson(item));
_wishListProducts.add(Wishlist.fromJson(item)); });
}); AppToast.showSuccessToast(message: 'You have added a product to the Wishlist');
AppToast.showSuccessToast(message: 'You have added a product to the Wishlist'); }, onFailure: (String error, int statusCode) {
hasError = true;
}, onFailure: (String error, int statusCode) { super.error = error;
hasError = true; AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage());
super.error = error; }, body: request);
AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage());
}, body: request);
} }
Future getWishlistItems() async { Future getWishlistItems() async {
var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID); var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
hasError = false; hasError = false;
await baseAppClient.getPharmacy(GET_WISHLIST+customerId+"?shopping_cart_type=2", await baseAppClient.getPharmacy(GET_WISHLIST + customerId + "?shopping_cart_type=2", onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _wishListProducts.clear();
_wishListProducts.clear(); response['shopping_carts'].forEach((item) {
response['shopping_carts'].forEach((item) { _wishListProducts.add(Wishlist.fromJson(item));
_wishListProducts.add(Wishlist.fromJson(item)); });
}); }, onFailure: (String error, int statusCode) {
}, onFailure: (String error, int statusCode) { hasError = true;
hasError = true; super.error = error;
super.error = error; });
});
} }
Future deleteItemFromWishlist(itemID) async { Future deleteItemFromWishlist(itemID) async {
var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID); var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
hasError = false; hasError = false;
await baseAppClient.getPharmacy(DELETE_WISHLIST+customerId+"+&product_id="+itemID+"&cart_type=Wishlist", await baseAppClient.getPharmacy(DELETE_WISHLIST + customerId + "+&product_id=" + itemID + "&cart_type=Wishlist", onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _wishListProducts.clear();
_wishListProducts.clear(); response['shopping_carts'].forEach((item) {
response['shopping_carts'].forEach((item) { _wishListProducts.add(Wishlist.fromJson(item));
_wishListProducts.add(Wishlist.fromJson(item)); });
}); AppToast.showSuccessToast(message: 'You have removed a product from the Wishlist');
AppToast.showSuccessToast(message: 'You have removed a product from the Wishlist'); }, onFailure: (String error, int statusCode) {
}, onFailure: (String error, int statusCode) { hasError = true;
hasError = true; super.error = error;
super.error = error; AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage());
AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); });
});
} }
Future productSpecificationData(itemID) async { Future productSpecificationData(itemID) async {
hasError = false; hasError = false;
await baseAppClient.getPharmacy(GET_SPECIFICATION+itemID, await baseAppClient.getPharmacy(GET_SPECIFICATION + itemID, onSuccess: (dynamic response, int statusCode) {
onSuccess: (dynamic response, int statusCode) { _productSpecification.clear();
_productSpecification.clear(); response['specification'].forEach((item) {
response['specification'].forEach((item) { _productSpecification.add(SpecificationModel.fromJson(item));
_productSpecification.add(SpecificationModel.fromJson(item)); print(_productSpecification);
print(_productSpecification); });
}); }, onFailure: (String error, int statusCode) {
}, onFailure: (String error, int statusCode) { hasError = true;
hasError = true; super.error = error;
super.error = error; });
});
} }
} }

@ -2624,10 +2624,74 @@ class TranslationBase {
String get browseOffers => localizedValues["browseOffers"][locale.languageCode]; String get browseOffers => localizedValues["browseOffers"][locale.languageCode];
String get myCart => localizedValues["myCart"][locale.languageCode]; String get myCart => localizedValues["myCart"][locale.languageCode];
String get neck => localizedValues["neck"][locale.languageCode]; String get neck => localizedValues["neck"][locale.languageCode];
String get waist => localizedValues["waist"][locale.languageCode]; String get waist => localizedValues["waist"][locale.languageCode];
String get hip => localizedValues["hip"][locale.languageCode]; String get hip => localizedValues["hip"][locale.languageCode];
String get carbsProtin => localizedValues["carbsProtin"][locale.languageCode]; String get carbsProtin => localizedValues["carbsProtin"][locale.languageCode];
String get inactiveAct => localizedValues["inactiveAct"][locale.languageCode];
String get light => localizedValues["light"][locale.languageCode];
String get moderate => localizedValues["moderate"][locale.languageCode];
String get very => localizedValues["very"][locale.languageCode];
String get superAct => localizedValues["super"][locale.languageCode];
String get resultCalories => localizedValues["resultCalories"][locale.languageCode];
String get bmrDesc => localizedValues["bmrDesc"][locale.languageCode];
String get idealWeightDesc => localizedValues["idealWeightDesc"][locale.languageCode];
String get bodyFrame => localizedValues["bodyFrame"][locale.languageCode];
String get bodyFrameSmall => localizedValues["bodyFrameSmall"][locale.languageCode];
String get bodyFrameMedium => localizedValues["bodyFrameMedium"][locale.languageCode];
String get bodyFrameLarge => localizedValues["bodyFrameLarge"][locale.languageCode];
String get bodyFatDesc => localizedValues["bodyFatDesc"][locale.languageCode];
String get essential => localizedValues["essential"][locale.languageCode];
String get athlete => localizedValues["athlete"][locale.languageCode];
String get fitness => localizedValues["fitness"][locale.languageCode];
String get acceptable => localizedValues["acceptable"][locale.languageCode];
String get obeseBodyFat => localizedValues["obeseBodyFat"][locale.languageCode];
String get invalid => localizedValues["invalid"][locale.languageCode];
String get more => localizedValues["more"][locale.languageCode];
String get less => localizedValues["less"][locale.languageCode];
String get carbProteinDesc => localizedValues["carbProteinDesc"][locale.languageCode];
String get calDay => localizedValues["calDay"][locale.languageCode];
String get notSure => localizedValues["notSure"][locale.languageCode];
String get selectDiet => localizedValues["selectDiet"][locale.languageCode];
String get dietVeryLow => localizedValues["dietVeryLow"][locale.languageCode];
String get dietLow => localizedValues["dietLow"][locale.languageCode];
String get dietModerate => localizedValues["dietModerate"][locale.languageCode];
String get dietUSDA => localizedValues["dietUSDA"][locale.languageCode];
String get dietZone => localizedValues["dietZone"][locale.languageCode];
} }
class TranslationBaseDelegate extends LocalizationsDelegate<TranslationBase> { class TranslationBaseDelegate extends LocalizationsDelegate<TranslationBase> {

Loading…
Cancel
Save