v1.0.3 webapi client

This commit is contained in:
Tibor Bossanyi 2023-02-12 22:42:51 +01:00
parent af0fbaf180
commit 65e9daa273
64 changed files with 1160 additions and 1014 deletions

View File

@ -5,8 +5,8 @@ firebase_analytics=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dar
firebase_analytics_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_analytics_web-0.5.1+8\\ firebase_analytics_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_analytics_web-0.5.1+8\\
firebase_auth=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_auth-4.2.5\\ firebase_auth=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_auth-4.2.5\\
firebase_auth_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_auth_web-5.2.4\\ firebase_auth_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_auth_web-5.2.4\\
firebase_core=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_core-2.4.1\\ firebase_core=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_core-2.5.0\\
firebase_core_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_core_web-2.1.0\\ firebase_core_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_core_web-2.1.1\\
firebase_messaging=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_messaging-14.2.1\\ firebase_messaging=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_messaging-14.2.1\\
firebase_messaging_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_messaging_web-3.2.11\\ firebase_messaging_web=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_messaging_web-3.2.11\\
firebase_remote_config=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_remote_config-3.0.9\\ firebase_remote_config=C:\\Users\\bossa\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dartlang.org\\firebase_remote_config-3.0.9\\

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,8 @@
Workout Test and Diet 4 You Common Util Functions Workout Test and Diet 4 You Common Util Functions
Version 1.0.3
Warning fixes, webapi client
Version 1.0.2 Version 1.0.2
Open AI API support Open AI API support

View File

@ -139,7 +139,7 @@ class Cache with Logging {
List<ExerciseType>? _exerciseTypes; List<ExerciseType>? _exerciseTypes;
List<ExerciseTree>? _exerciseTree; List<ExerciseTree>? _exerciseTree;
List<Evaluation>? _evaluations; List<Evaluation>? evaluations;
List<Exercise>? _exercises; List<Exercise>? _exercises;
ExercisePlan? _myExercisePlan; ExercisePlan? _myExercisePlan;
@ -196,7 +196,7 @@ class Cache with Logging {
Cache._internal() { Cache._internal() {
String testEnv = EnvironmentConfig.test_env; String testEnv = EnvironmentConfig.test_env;
testEnvironment = testEnv; testEnvironment = testEnv;
print("testEnv $testEnv"); log("testEnv $testEnv");
if (testEnv == "1") { if (testEnv == "1") {
baseUrl = baseUrlTest; baseUrl = baseUrlTest;
liveServer = false; liveServer = false;
@ -280,11 +280,11 @@ class Cache with Logging {
//String jsonPlan = savedTrainingPlanJson.replaceAllMapped(RegExp(r'[a-zA-Z]+\:'), (Match m) => "\"${m[0]}\""); //String jsonPlan = savedTrainingPlanJson.replaceAllMapped(RegExp(r'[a-zA-Z]+\:'), (Match m) => "\"${m[0]}\"");
Map<String, dynamic> map; Map<String, dynamic> map;
try { try {
map = JsonDecoder().convert(savedTrainingPlanJson); map = const JsonDecoder().convert(savedTrainingPlanJson);
//print("Training plan: $savedTrainingPlanJson"); //log("Training plan: $savedTrainingPlanJson");
this.myTrainingPlan = CustomerTrainingPlan.fromJsonWithDetails(map); myTrainingPlan = CustomerTrainingPlan.fromJsonWithDetails(map);
} on Exception catch (e) { } on Exception catch (e) {
print(e.toString()); log(e.toString());
} }
} }
@ -294,8 +294,8 @@ class Cache with Logging {
sharedPreferences = await prefs; sharedPreferences = await prefs;
sharedPreferences.remove(Cache.activeExercisePlanDateKey); sharedPreferences.remove(Cache.activeExercisePlanDateKey);
this.activeExercisePlan = null; activeExercisePlan = null;
this.activeExercisePlanDetails = null; activeExercisePlanDetails = null;
} }
Future<void> getActiveExercisePlan() async { Future<void> getActiveExercisePlan() async {
@ -312,29 +312,29 @@ class Cache with Logging {
DateTime savedPlanDate; DateTime savedPlanDate;
savedPlanDate = format.parse(savedPlanDateString); savedPlanDate = format.parse(savedPlanDateString);
print("Saved plan: $savedPlanDate"); log("Saved plan: $savedPlanDate");
final DateTime now = DateTime.now(); final DateTime now = DateTime.now();
final DateTime added = savedPlanDate.add(Duration(days: 1)); final DateTime added = savedPlanDate.add(const Duration(days: 1));
if (added.isBefore(now)) { if (added.isBefore(now)) {
return; return;
} }
String? exercisePlanJson = sharedPreferences.getString(Cache.activeExercisePlanKey); String? exercisePlanJson = sharedPreferences.getString(Cache.activeExercisePlanKey);
if (exercisePlanJson != null) { if (exercisePlanJson != null) {
final Map<String, dynamic> map = JsonDecoder().convert(exercisePlanJson); final Map<String, dynamic> map = const JsonDecoder().convert(exercisePlanJson);
this.activeExercisePlan = ExercisePlan.fromJson(map); activeExercisePlan = ExercisePlan.fromJson(map);
} }
String? detailsJson = sharedPreferences.getString(Cache.activeExercisePlanDetailsKey); String? detailsJson = sharedPreferences.getString(Cache.activeExercisePlanDetailsKey);
if (detailsJson != null) { if (detailsJson != null) {
Iterable json = jsonDecode(detailsJson); Iterable json = jsonDecode(detailsJson);
this.activeExercisePlanDetails = json.map((details) => ExercisePlanDetail.fromJsonWithExerciseList(details)).toList(); activeExercisePlanDetails = json.map((details) => ExercisePlanDetail.fromJsonWithExerciseList(details)).toList();
} }
} }
Future<void> setServer(bool live) async { Future<void> setServer(bool live) async {
if (this.testEnvironment == "1") { if (testEnvironment == "1") {
liveServer = false; liveServer = false;
live = false; live = false;
} }
@ -366,23 +366,23 @@ class Cache with Logging {
SharedPreferences sharedPreferences; SharedPreferences sharedPreferences;
sharedPreferences = await prefs; sharedPreferences = await prefs;
sharedPreferences.setBool(Cache.hardwareKey, hasHardware); sharedPreferences.setBool(Cache.hardwareKey, hasHardware);
this.hasHardware = hasHardware; hasHardware = hasHardware;
} }
void setServerAddress(SharedPreferences prefs) { void setServerAddress(SharedPreferences prefs) {
if (testEnvironment == "1") { if (testEnvironment == "1") {
baseUrl = baseUrlTest; baseUrl = baseUrlTest;
print("TestEnv $baseUrl"); log("TestEnv $baseUrl");
return; return;
} else if ( testEnvironment == "2") { } else if ( testEnvironment == "2") {
baseUrl = baseUrlLocal; baseUrl = baseUrlLocal;
print("TestEnv $baseUrl"); log("TestEnv $baseUrl");
return; return;
} }
final bool? live = prefs.getBool(Cache.serverKey); final bool? live = prefs.getBool(Cache.serverKey);
if (live == null) { if (live == null) {
baseUrl = baseUrlLive; baseUrl = baseUrlLive;
print("Live Env $baseUrl"); log("Live Env $baseUrl");
liveServer = true; liveServer = true;
return; return;
} }
@ -393,7 +393,7 @@ class Cache with Logging {
baseUrl = baseUrlTest; baseUrl = baseUrlTest;
} }
print("Env $baseUrl"); log("Env $baseUrl");
} }
Future<void> setLoginTypeFromPrefs() async { Future<void> setLoginTypeFromPrefs() async {
@ -410,7 +410,7 @@ class Cache with Logging {
} else if (loginType == LoginType.email.toString()) { } else if (loginType == LoginType.email.toString()) {
type = LoginType.email; type = LoginType.email;
} }
//print("LoginType: " + loginType == null ? "NULL" : loginType); //log("LoginType: " + loginType == null ? "NULL" : loginType);
Cache().setLoginType(type); Cache().setLoginType(type);
} }
@ -460,7 +460,7 @@ class Cache with Logging {
} }
logout() async { logout() async {
if (this.accessTokenFacebook != null) { if (accessTokenFacebook != null) {
await FirebaseApi().logOutFacebook(); await FirebaseApi().logOutFacebook();
} }
userLoggedIn = null; userLoggedIn = null;
@ -472,7 +472,7 @@ class Cache with Logging {
_traineeExercisePlan = null; _traineeExercisePlan = null;
_exercises = []; _exercises = [];
_myExercisesPlanDetails = LinkedHashMap(); _myExercisesPlanDetails = LinkedHashMap();
log("Trainees is null? " + (_trainee == null).toString()); log("Trainees is null? ${_trainee == null}");
Future<SharedPreferences> prefs = SharedPreferences.getInstance(); Future<SharedPreferences> prefs = SharedPreferences.getInstance();
await setPreferences(prefs, SharePrefsChange.logout, 0, ""); await setPreferences(prefs, SharePrefsChange.logout, 0, "");
} }
@ -504,60 +504,60 @@ class Cache with Logging {
} }
void setExerciseTypes(List<ExerciseType> exerciseTypes) { void setExerciseTypes(List<ExerciseType> exerciseTypes) {
this._exerciseTypes = exerciseTypes; _exerciseTypes = exerciseTypes;
} }
void setExerciseTree(List<ExerciseTree> exerciseTree) { void setExerciseTree(List<ExerciseTree> exerciseTree) {
this._exerciseTree = exerciseTree; _exerciseTree = exerciseTree;
} }
void setExercises(List<Exercise> exercises) => this._exercises = exercises; void setExercises(List<Exercise> exercises) => _exercises = exercises;
void setExercisesTrainee(List<Exercise> exercises) { void setExercisesTrainee(List<Exercise> exercises) {
this._exercisesTrainee = exercises; _exercisesTrainee = exercises;
} }
void setWorkoutMenuTree(LinkedHashMap<String, WorkoutMenuTree> tree) { void setWorkoutMenuTree(LinkedHashMap<String, WorkoutMenuTree> tree) {
this._tree = tree; _tree = tree;
} }
List<ExerciseType>? getExerciseTypes() => this._exerciseTypes; List<ExerciseType>? getExerciseTypes() => _exerciseTypes;
ExerciseType? getExerciseTypeById(int exerciseTypeId) { ExerciseType? getExerciseTypeById(int exerciseTypeId) {
ExerciseType? exerciseType; ExerciseType? exerciseType;
if (_exerciseTypes != null) { if (_exerciseTypes != null) {
this._exerciseTypes!.forEach((element) { for (var element in _exerciseTypes!) {
if (element.exerciseTypeId == exerciseTypeId) { if (element.exerciseTypeId == exerciseTypeId) {
exerciseType = element; exerciseType = element;
} }
}); }
} }
return exerciseType; return exerciseType;
} }
List<ExerciseTree>? getExerciseTree() => this._exerciseTree; List<ExerciseTree>? getExerciseTree() => _exerciseTree;
List<Exercise>? getExercises() => this._exercises; List<Exercise>? getExercises() => _exercises;
List<Exercise>? getExercisesTrainee() => this._exercisesTrainee; List<Exercise>? getExercisesTrainee() => _exercisesTrainee;
LinkedHashMap<String, WorkoutMenuTree> getWorkoutMenuTree() => this._tree; LinkedHashMap<String, WorkoutMenuTree> getWorkoutMenuTree() => _tree;
void setPercentExercises(double percent) => this._percentExercises = percent; void setPercentExercises(double percent) => _percentExercises = percent;
double getPercentExercises() => this._percentExercises; double getPercentExercises() => _percentExercises;
void addExercise(Exercise exercise) => _exercises!.add(exercise); void addExercise(Exercise exercise) => _exercises!.add(exercise);
void addExerciseTrainee(Exercise exercise) => _exercisesTrainee!.add(exercise); void addExerciseTrainee(Exercise exercise) => _exercisesTrainee!.add(exercise);
Customer? getTrainee() => this._trainee; Customer? getTrainee() => _trainee;
void setTrainee(Customer trainee) => _trainee = trainee; void setTrainee(Customer trainee) => _trainee = trainee;
void setTraineeExercisePlan(ExercisePlan exercisePlan) => this._traineeExercisePlan = exercisePlan; void setTraineeExercisePlan(ExercisePlan exercisePlan) => _traineeExercisePlan = exercisePlan;
ExercisePlan? getTraineesExercisePlan() => this._traineeExercisePlan; ExercisePlan? getTraineesExercisePlan() => _traineeExercisePlan;
void setMyExercisePlan(ExercisePlan exercisePlan) => _myExercisePlan = exercisePlan; void setMyExercisePlan(ExercisePlan exercisePlan) => _myExercisePlan = exercisePlan;
@ -573,31 +573,31 @@ class Cache with Logging {
void resetMyExercisePlanDetails() => _myExercisesPlanDetails = LinkedHashMap<int, ExercisePlanDetail>(); void resetMyExercisePlanDetails() => _myExercisesPlanDetails = LinkedHashMap<int, ExercisePlanDetail>();
void updateMyExercisePlanDetail(ExercisePlanDetail detail) { void updateMyExercisePlanDetail(ExercisePlanDetail detail) {
this.addToMyExercisePlanDetails(detail); addToMyExercisePlanDetails(detail);
} }
void deleteMyExercisePlanDetail(ExercisePlanDetail detail) => this.deleteMyExercisePlanDetailByExerciseTypeId(detail.exerciseTypeId); void deleteMyExercisePlanDetail(ExercisePlanDetail detail) => deleteMyExercisePlanDetailByExerciseTypeId(detail.exerciseTypeId);
void deletedMyExercisePlanDetail(ExercisePlanDetail detail) => void deletedMyExercisePlanDetail(ExercisePlanDetail detail) =>
this._myExercisesPlanDetails[detail.exerciseTypeId]!.change = ModelChange.deleted; _myExercisesPlanDetails[detail.exerciseTypeId]!.change = ModelChange.deleted;
void deleteMyExercisePlanDetailByExerciseTypeId(int exerciseTypeId) { void deleteMyExercisePlanDetailByExerciseTypeId(int exerciseTypeId) {
this._myExercisesPlanDetails[exerciseTypeId]!.change = ModelChange.delete; _myExercisesPlanDetails[exerciseTypeId]!.change = ModelChange.delete;
} }
void setProperties(List<Property> properties) => this._properties = properties; void setProperties(List<Property> properties) => _properties = properties;
List<Property>? getProperties() => _properties; List<Property>? getProperties() => _properties;
List<Sport>? getSports() => _sports; List<Sport>? getSports() => _sports;
void setSports(List<Sport> sports) => this._sports = sports; void setSports(List<Sport> sports) => _sports = sports;
void setDevices(List<ExerciseDevice> devices) => this._devices = devices; void setDevices(List<ExerciseDevice> devices) => _devices = devices;
List<ExerciseDevice>? getDevices() => this._devices; List<ExerciseDevice>? getDevices() => _devices;
void setCustomerDevices(List<CustomerExerciseDevice> devices) => this._customerDevices = devices; void setCustomerDevices(List<CustomerExerciseDevice> devices) => _customerDevices = devices;
List<CustomerExerciseDevice>? getCustomerDevices() => this._customerDevices; List<CustomerExerciseDevice>? getCustomerDevices() => _customerDevices;
LinkedHashMap getBadges() => _badges; LinkedHashMap getBadges() => _badges;
@ -634,17 +634,17 @@ class Cache with Logging {
return; return;
} }
customerRepository.setCustomer(userLoggedIn!); customerRepository.setCustomer(userLoggedIn!);
int _ecto = customerRepository.getCustomerPropertyValue(PropertyEnum.Ectomorph.toStr()).toInt(); int ecto = customerRepository.getCustomerPropertyValue(PropertyEnum.Ectomorph.toStr()).toInt();
int _mezo = customerRepository.getCustomerPropertyValue(PropertyEnum.Mesomorph.toStr()).toInt(); int mezo = customerRepository.getCustomerPropertyValue(PropertyEnum.Mesomorph.toStr()).toInt();
int _endo = customerRepository.getCustomerPropertyValue(PropertyEnum.Endomorph.toStr()).toInt(); int endo = customerRepository.getCustomerPropertyValue(PropertyEnum.Endomorph.toStr()).toInt();
//print("endo " + _endo.toString() + " mezo " + _mezo.toString()); //log("endo " + _endo.toString() + " mezo " + _mezo.toString());
if (this.userLoggedIn != null) { if (userLoggedIn != null) {
if (this.userLoggedIn!.birthYear == null || this.userLoggedIn!.birthYear == 0) { if (userLoggedIn!.birthYear == null || userLoggedIn!.birthYear == 0) {
setBadge("personalData", true); setBadge("personalData", true);
setBadge("account", true); setBadge("account", true);
} }
if (this._customerDevices == null || this._customerDevices!.isEmpty) { if (_customerDevices == null || _customerDevices!.isEmpty) {
setBadge("customerDevice", true); setBadge("customerDevice", true);
setBadge("account", true); setBadge("account", true);
} }
@ -662,11 +662,11 @@ class Cache with Logging {
setBadge("My Body", true); setBadge("My Body", true);
setBadgeNr("home", 1); setBadgeNr("home", 1);
} }
if (_ecto == 0 && _mezo == 0 && _endo == 0) { if (ecto == 0 && mezo == 0 && endo == 0) {
setBadge("account", true); setBadge("account", true);
setBadge("bodyType", true); setBadge("bodyType", true);
} }
if (this._exercises == null || this._exercises!.isEmpty) { if (_exercises == null || _exercises!.isEmpty) {
setBadge("home", true); setBadge("home", true);
setBadge("Custom Tests", true); setBadge("Custom Tests", true);
setBadge("Start Training", true); setBadge("Start Training", true);
@ -685,7 +685,7 @@ class Cache with Logging {
setBadge("FitnessLevel", true); setBadge("FitnessLevel", true);
setBadge("account", true); setBadge("account", true);
} }
if (this._exercises != null && this._exercises!.isNotEmpty) { if (_exercises != null && _exercises!.isNotEmpty) {
if (!activitiesDone[ActivityDone.isExerciseLogSeen.toStr()]!) { if (!activitiesDone[ActivityDone.isExerciseLogSeen.toStr()]!) {
setBadge("exerciseLog", true); setBadge("exerciseLog", true);
setBadge("development", true); setBadge("development", true);
@ -696,7 +696,7 @@ class Cache with Logging {
} }
} }
} }
log("Badges: " + _badges.toString()); log("Badges: $_badges");
} }
List<Product>? get products => _products; List<Product>? get products => _products;
@ -727,11 +727,11 @@ class Cache with Logging {
} }
await Future.forEach(ActivityDone.values, (element) async { await Future.forEach(ActivityDone.values, (element) async {
ActivityDone activity = element as ActivityDone; ActivityDone activity = element;
await isActivityDonePrefs(activity); await isActivityDonePrefs(activity);
}); });
print("Firebase token save: $firebaseMessageToken"); log("Firebase token save: $firebaseMessageToken");
if (firebaseMessageToken != null) { if (firebaseMessageToken != null) {
userLoggedIn!.firebaseRegToken = firebaseMessageToken; userLoggedIn!.firebaseRegToken = firebaseMessageToken;
CustomerRepository customerRepository = CustomerRepository(); CustomerRepository customerRepository = CustomerRepository();
@ -745,13 +745,13 @@ class Cache with Logging {
} }
AccessToken? get getAccessTokenFacebook => accessTokenFacebook; AccessToken? get getAccessTokenFacebook => accessTokenFacebook;
set setAccessTokenFacebook(AccessToken accessTokenFacebook) => this.accessTokenFacebook = accessTokenFacebook; set setAccessTokenFacebook(AccessToken accessTokenFacebook) => accessTokenFacebook = accessTokenFacebook;
LoginType? getLoginType() => loginType; LoginType? getLoginType() => loginType;
void setLoginType(LoginType type) => this.loginType = type; void setLoginType(LoginType type) => loginType = type;
List get exercisePlanTemplates => this._exercisePlanTemplates; List get exercisePlanTemplates => _exercisePlanTemplates;
setExercisePlanTemplates(value) => this._exercisePlanTemplates = value; setExercisePlanTemplates(value) => _exercisePlanTemplates = value;
isActivityDonePrefs(ActivityDone activity) async { isActivityDonePrefs(ActivityDone activity) async {
Future<SharedPreferences> prefs = SharedPreferences.getInstance(); Future<SharedPreferences> prefs = SharedPreferences.getInstance();
@ -772,42 +772,37 @@ class Cache with Logging {
bool isActivityDone(ActivityDone activity) => activitiesDone[activity.toStr()] == true; bool isActivityDone(ActivityDone activity) => activitiesDone[activity.toStr()] == true;
List<Evaluation>? get evaluations => this._evaluations; List<CustomerActivity>? get customerActivities => _customerActivities;
set evaluations(List<Evaluation>? value) => this._evaluations = value; setCustomerActivities(List<CustomerActivity>? value) => _customerActivities = value;
List<CustomerActivity>? get customerActivities => this._customerActivities; List<Tutorial>? get tutorials => _tutorials;
setCustomerActivities(List<CustomerActivity>? value) => this._customerActivities = value; setTutorials(List<Tutorial>? value) => _tutorials = value;
List<Tutorial>? get tutorials => this._tutorials; FirebaseRemoteConfig? getRemoteConfig() => remoteConfig;
setTutorials(List<Tutorial>? value) => this._tutorials = value; setRemoteConfig(FirebaseRemoteConfig? remoteConfig) => remoteConfig = remoteConfig;
FirebaseRemoteConfig? getRemoteConfig() => this.remoteConfig; List<Description>? getDescriptions() => _descriptions;
setRemoteConfig(FirebaseRemoteConfig? remoteConfig) => this.remoteConfig = remoteConfig; setDescriptions(List<Description>? value) => _descriptions = value;
List<Description>? getDescriptions() => this._descriptions; List<Faq>? getFaqs() => _faqs;
setDescriptions(List<Description>? value) => this._descriptions = value; setFaqs(List<Faq>? value) => _faqs = value;
List<Faq>? getFaqs() => this._faqs; List<TrainingPlan>? getTrainingPlans() => _trainingPlans;
setFaqs(List<Faq>? value) => this._faqs = value; setTrainingPlans(List<TrainingPlan>? value) => _trainingPlans = value;
List<TrainingPlan>? getTrainingPlans() => this._trainingPlans; List<CustomerTrainingPlan>? getCustomerTrainingPlans() => _customerTrainingPlans;
setTrainingPlans(List<TrainingPlan>? value) => this._trainingPlans = value; setCustomerTrainingPlans(value) => _customerTrainingPlans = value;
List<CustomerTrainingPlan>? getCustomerTrainingPlans() => this._customerTrainingPlans; List<SplitTest> getSplitTests() => _splitTests;
setCustomerTrainingPlans(value) => this._customerTrainingPlans = value; setSplitTests(value) => _splitTests = value;
List<SplitTest> getSplitTests() => this._splitTests; List<TrainingPlanDay> getTrainingPlanDays() => _trainingPlanDays;
setSplitTests(value) => this._splitTests = value; setTrainingPlanDays(value) => _trainingPlanDays = value;
List<TrainingPlanDay> getTrainingPlanDays() => this._trainingPlanDays; List<CustomerProperty>? getCustomerPropertyAll() => _customerPropertyAll;
setTrainingPlanDays(value) => this._trainingPlanDays = value; setCustomerPropertyAll(value) => _customerPropertyAll = value;
List<CustomerProperty>? getCustomerPropertyAll() => this._customerPropertyAll;
setCustomerPropertyAll(value) => this._customerPropertyAll = value;
addCustomerProperty(CustomerProperty property) { addCustomerProperty(CustomerProperty property) {
if (this._customerPropertyAll == null) { _customerPropertyAll ??= [];
this._customerPropertyAll = []; _customerPropertyAll!.add(property);
}
this._customerPropertyAll!.add(property);
} }
} }

View File

@ -33,56 +33,56 @@ class Customer {
LinkedHashMap<String, CustomerProperty> properties = LinkedHashMap(); LinkedHashMap<String, CustomerProperty> properties = LinkedHashMap();
Customer( Customer(
{this.customerId, {customerId,
this.name, name,
this.firstname, firstname,
this.email, email,
this.sex, sex,
this.age, age,
this.active, active,
this.password, password,
this.birthYear, birthYear,
this.bodyType, bodyType,
this.fitnessLevel, fitnessLevel,
this.goal, goal,
this.admin, admin,
this.trainer, trainer,
this.dataPolicyAllowed, dataPolicyAllowed,
this.firebaseUid, firebaseUid,
this.dateAdd, dateAdd,
this.dateChange}) { dateChange}) {
dateAdd = DateTime.now(); dateAdd = DateTime.now();
dateChange = DateTime.now(); dateChange = DateTime.now();
} }
Customer.fromJson(Map json) { Customer.fromJson(Map json) {
this.customerId = json['customerId']; customerId = json['customerId'];
this.name = json['name']; name = json['name'];
this.firstname = json['firstname']; firstname = json['firstname'];
this.email = json['email']; email = json['email'];
this.sex = json['sex']; sex = json['sex'];
this.age = json['age']; age = json['age'];
this.active = json['active']; active = json['active'];
this.birthYear = json['birthYear']; birthYear = json['birthYear'];
this.bodyType = json['bodyType']; bodyType = json['bodyType'];
this.fitnessLevel = json['fitnessLevel']; fitnessLevel = json['fitnessLevel'];
this.goal = json['goal']; goal = json['goal'];
this.admin = json['admin']; admin = json['admin'];
this.lifeLong = json['lifeLong']; lifeLong = json['lifeLong'];
this.trainer = json['trainer']; trainer = json['trainer'];
this.firebaseUid = json['firebaseUid']; firebaseUid = json['firebaseUid'];
this.firebaseRegToken = json['firebaseRegToken']; firebaseRegToken = json['firebaseRegToken'];
this.lang = json['lang']; lang = json['lang'];
this.dataPolicyAllowed = json['dataPolicyAllowed']; dataPolicyAllowed = json['dataPolicyAllowed'];
this.emailSubscription = json['emailSubscription']; emailSubscription = json['emailSubscription'];
this.sportId = json['sportId']; sportId = json['sportId'];
this.syncedDate = json['syncedDate'] == null ? null : DateTime.parse(json['syncedDate']); syncedDate = json['syncedDate'] == null ? null : DateTime.parse(json['syncedDate']);
this.trialDate = json['trialDate'] == null ? null : DateTime.parse(json['trialDate']); trialDate = json['trialDate'] == null ? null : DateTime.parse(json['trialDate']);
this.dateAdd = json['dateAdd'] == null ? DateTime.parse("0000-00-00") : DateTime.parse(json['dateAdd']); dateAdd = json['dateAdd'] == null ? DateTime.parse("0000-00-00") : DateTime.parse(json['dateAdd']);
this.dateChange = json['dateChange'] == null ? DateTime.parse("0000-00-00") : DateTime.parse(json['dateChange']); dateChange = json['dateChange'] == null ? DateTime.parse("0000-00-00") : DateTime.parse(json['dateChange']);
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
@ -100,29 +100,29 @@ class Customer {
"admin": admin, "admin": admin,
"trainer": trainer, "trainer": trainer,
"dataPolicyAllowed": dataPolicyAllowed, "dataPolicyAllowed": dataPolicyAllowed,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd!),
"dateChange": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateChange!), "dateChange": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateChange!),
"emailSubscription": this.emailSubscription, "emailSubscription": emailSubscription,
"sportId": this.sportId, "sportId": sportId,
"syncedDate": this.syncedDate == null ? null : DateFormat('yyyy-MM-dd HH:mm:ss').format(this.syncedDate!), "syncedDate": syncedDate == null ? null : DateFormat('yyyy-MM-dd HH:mm:ss').format(syncedDate!),
"trialDate": this.trialDate == null ? null : DateFormat('yyyy-MM-dd HH:mm:ss').format(this.trialDate!), "trialDate": trialDate == null ? null : DateFormat('yyyy-MM-dd HH:mm:ss').format(trialDate!),
"firebaseRegToken": this.firebaseRegToken, "firebaseRegToken": firebaseRegToken,
"lang": this.lang, "lang": lang,
"lifeLong": this.lifeLong, "lifeLong": lifeLong,
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
double getProperty(String propertyName) { double getProperty(String propertyName) {
if (this.properties[propertyName] == null) { if (properties[propertyName] == null) {
return 0; return 0;
} else { } else {
return this.properties[propertyName]!.propertyValue; return properties[propertyName]!.propertyValue;
} }
} }
setProperty(String propertyName, double value) { setProperty(String propertyName, double value) {
this.properties[propertyName]!.propertyValue = value; properties[propertyName]!.propertyValue = value;
} }
} }

View File

@ -1,4 +1,3 @@
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class CustomerActivity { class CustomerActivity {

View File

@ -1,4 +1,3 @@
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class CustomerExerciseDevice { class CustomerExerciseDevice {

View File

@ -1,4 +1,3 @@
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import '../util/logging.dart'; import '../util/logging.dart';
@ -14,10 +13,10 @@ class CustomerProperty with Logging {
bool newData = false; bool newData = false;
CustomerProperty( CustomerProperty(
{required this.propertyId, {required propertyId,
required this.customerId, required customerId,
required this.dateAdd, required dateAdd,
required this.propertyValue}); required propertyValue});
CustomerProperty.fromJson(Map json) { CustomerProperty.fromJson(Map json) {
customerPropertyId = json['customerPropertyId']; customerPropertyId = json['customerPropertyId'];
@ -33,38 +32,39 @@ class CustomerProperty with Logging {
propertyValue = json['propertyValue']; propertyValue = json['propertyValue'];
print("Json $json, ${toString()}"); log("Json $json, ${toString()}");
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
if (customerPropertyId != null) { if (customerPropertyId != null) {
return { return {
"customerPropertyId": this.customerPropertyId, "customerPropertyId": customerPropertyId,
"propertyId": this.propertyId, "propertyId": propertyId,
"customerId": this.customerId, "customerId": customerId,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd!),
"propertyValue": this.propertyValue "propertyValue": propertyValue
}; };
} else { } else {
return { return {
"propertyId": this.propertyId, "propertyId": propertyId,
"customerId": this.customerId, "customerId": customerId,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd!),
"propertyValue": this.propertyValue "propertyValue": propertyValue
}; };
} }
} }
@override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
"customerPropertyId": this.customerPropertyId, "customerPropertyId": customerPropertyId,
"propertyId": this.propertyId, "propertyId": propertyId,
"customerId": this.customerId, "customerId": customerId,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd!),
"propertyValue": this.propertyValue, "propertyValue": propertyValue,
"dateYmd": this.dateYmd, "dateYmd": dateYmd,
"dateYm": this.dateYm, "dateYm": dateYm,
"dateY": this.dateY, "dateY": dateY,
}; };
return json.toString(); return json.toString();
} }

View File

@ -1,10 +1,10 @@
import 'dart:collection'; import 'dart:collection';
import 'dart:convert'; import 'dart:convert';
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:workouttest_util/repository/exercise_type_repository.dart'; import 'package:workouttest_util/repository/exercise_type_repository.dart';
import 'package:workouttest_util/model/customer_training_plan_details.dart'; import 'package:workouttest_util/model/customer_training_plan_details.dart';
import 'package:workouttest_util/util/logging.dart';
enum CustomerTrainingPlanType { custom, template, none } enum CustomerTrainingPlanType { custom, template, none }
@ -14,7 +14,7 @@ extension CustomerTrainingPlanTypeExt on CustomerTrainingPlanType {
bool equalsStringTo(String type) => toStr() == type; bool equalsStringTo(String type) => toStr() == type;
} }
class CustomerTrainingPlan { class CustomerTrainingPlan with Logging {
int? customerTrainingPlanId; int? customerTrainingPlanId;
int? customerId; int? customerId;
int? trainingPlanId; int? trainingPlanId;
@ -59,15 +59,15 @@ class CustomerTrainingPlan {
jsonDetails = jsonDetails =
jsonDetails.replaceAllMapped(RegExp(r'([0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})'), (Match m) => "\"${m[0]}\""); jsonDetails.replaceAllMapped(RegExp(r'([0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})'), (Match m) => "\"${m[0]}\"");
print("detail: $jsonDetails"); log("detail: $jsonDetails");
Iterable iterable = jsonDecode(jsonDetails); Iterable iterable = jsonDecode(jsonDetails);
this.details = iterable.map((detail) => CustomerTrainingPlanDetails.fromJsonWithExerciseList(detail)).toList(); this.details = iterable.map((detail) => CustomerTrainingPlanDetails.fromJsonWithExerciseList(detail)).toList();
this.details.forEach((detail) { for (var detail in this.details) {
detail.alternatives = ExerciseTypeRepository.getExerciseTypeAlternatives(detail.exerciseTypeId); detail.alternatives = ExerciseTypeRepository.getExerciseTypeAlternatives(detail.exerciseTypeId);
}); }
} on Exception catch (e) { } on Exception catch (e) {
print("JsonDecode error " + e.toString()); log("JsonDecode error $e");
} }
} }

View File

@ -3,8 +3,9 @@ import 'package:workouttest_util/model/exercise.dart';
import 'package:workouttest_util/model/exercise_plan_detail.dart'; import 'package:workouttest_util/model/exercise_plan_detail.dart';
import 'package:workouttest_util/model/exercise_type.dart'; import 'package:workouttest_util/model/exercise_type.dart';
import 'package:workouttest_util/repository/training_plan_day_repository.dart'; import 'package:workouttest_util/repository/training_plan_day_repository.dart';
import 'package:workouttest_util/util/logging.dart';
class CustomerTrainingPlanDetails { class CustomerTrainingPlanDetails with Logging {
/// customerTrainingPlanDetails /// customerTrainingPlanDetails
int? customerTrainingPlanDetailsId; int? customerTrainingPlanDetailsId;
@ -45,86 +46,86 @@ class CustomerTrainingPlanDetails {
CustomerTrainingPlanDetails(); CustomerTrainingPlanDetails();
CustomerTrainingPlanDetails.fromJson(Map json) { CustomerTrainingPlanDetails.fromJson(Map json) {
this.customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId']; customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.set = json['set']; set = json['set'];
this.repeats = json['repeats']; repeats = json['repeats'];
this.weight = json['weight']; weight = json['weight'];
this.restingTime = json['restingTime']; restingTime = json['restingTime'];
this.parallel = json['parallel']; parallel = json['parallel'];
this.day = json['day']; day = json['day'];
} }
CustomerTrainingPlanDetails.fromJsonWithExerciseList(Map json) { CustomerTrainingPlanDetails.fromJsonWithExerciseList(Map json) {
this.customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId'] == "null" || json['customerTrainingPlanDetailsId'] == null customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId'] == "null" || json['customerTrainingPlanDetailsId'] == null
? 0 ? 0
: json['customerTrainingPlanDetailsId']; : json['customerTrainingPlanDetailsId'];
this.trainingPlanDetailsId = json['trainingPlanDetailsId'] == "null" ? 0 : json['trainingPlanDetailsId']; trainingPlanDetailsId = json['trainingPlanDetailsId'] == "null" ? 0 : json['trainingPlanDetailsId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.set = json['set']; set = json['set'];
this.repeats = json['repeats'] == "null" ? -1 : json['repeats']; repeats = json['repeats'] == "null" ? -1 : json['repeats'];
this.weight = json['weight'] == "null" ? 0 : json['weight']; weight = json['weight'] == "null" ? 0 : json['weight'];
this.restingTime = json['restingTime']; restingTime = json['restingTime'];
this.parallel = json['parallel'] == "false" parallel = json['parallel'] == "false"
? false ? false
: json['parallel'] == "true" : json['parallel'] == "true"
? true ? true
: null; : null;
this.dayId = json['dayId'] == "null" ? null : json['dayId']; dayId = json['dayId'] == "null" ? null : json['dayId'];
TrainingPlanDayRepository trainingPlanDayRepository = TrainingPlanDayRepository(); TrainingPlanDayRepository trainingPlanDayRepository = const TrainingPlanDayRepository();
this.day = trainingPlanDayRepository.getNameById(this.dayId); day = trainingPlanDayRepository.getNameById(dayId);
try { try {
Iterable iterable = json['exercises']; Iterable iterable = json['exercises'];
this.exercises = iterable.map((exercise) => Exercise.fromJson(exercise)).toList(); exercises = iterable.map((exercise) => Exercise.fromJson(exercise)).toList();
} on Exception catch (e) { } on Exception catch (e) {
print("JsonDecode error " + e.toString()); log("JsonDecode error $e");
} }
if (json['state'] == ExercisePlanDetailState.finished.toStr()) { if (json['state'] == ExercisePlanDetailState.finished.toStr()) {
this.state = ExercisePlanDetailState.finished; state = ExercisePlanDetailState.finished;
} else if (json['state'] == ExercisePlanDetailState.inProgress.toStr()) { } else if (json['state'] == ExercisePlanDetailState.inProgress.toStr()) {
this.state = ExercisePlanDetailState.inProgress; state = ExercisePlanDetailState.inProgress;
} else if (json['state'] == ExercisePlanDetailState.skipped.toStr()) { } else if (json['state'] == ExercisePlanDetailState.skipped.toStr()) {
this.state = ExercisePlanDetailState.skipped; state = ExercisePlanDetailState.skipped;
} else { } else {
this.state = ExercisePlanDetailState.start; state = ExercisePlanDetailState.start;
} }
this.isTest = json['isTest'] == "true" ? true : false; isTest = json['isTest'] == "true" ? true : false;
this.exerciseType = Cache().getExerciseTypeById(exerciseTypeId!); exerciseType = Cache().getExerciseTypeById(exerciseTypeId!);
this.baseOneRepMax = json['baseOneRepMax'] == null ? 0 : json['baseOneRepMax']; baseOneRepMax = json['baseOneRepMax'] ?? 0;
} }
ExerciseType? getExerciseType() => exerciseType; ExerciseType? getExerciseType() => exerciseType;
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"customerTrainingPlanDetailsId": this.customerTrainingPlanDetailsId, "customerTrainingPlanDetailsId": customerTrainingPlanDetailsId,
"exerciseTypeId": this.exerciseTypeId, "exerciseTypeId": exerciseTypeId,
"set": this.set, "set": set,
"repeats": this.repeats, "repeats": repeats,
"weight": this.weight, "weight": weight,
"restingTime": this.restingTime, "restingTime": restingTime,
"parallel": this.parallel, "parallel": parallel,
"day": this.day == null ? '1.' : this.day, "day": day ?? '1.',
}; };
Map<String, dynamic> toJsonWithExercises() { Map<String, dynamic> toJsonWithExercises() {
final Map<String, dynamic> jsonMap = { final Map<String, dynamic> jsonMap = {
"customerTrainingPlanDetailsId": this.customerTrainingPlanDetailsId, "customerTrainingPlanDetailsId": customerTrainingPlanDetailsId,
"trainingPlanDetailsId": this.trainingPlanDetailsId, "trainingPlanDetailsId": trainingPlanDetailsId,
"exerciseTypeId": this.exerciseTypeId, "exerciseTypeId": exerciseTypeId,
"set": this.set, "set": set,
"repeats": this.repeats, "repeats": repeats,
"weight": this.weight, "weight": weight,
"restingTime": this.restingTime, "restingTime": restingTime,
"parallel": this.parallel, "parallel": parallel,
'exercises': exercises.isEmpty ? [].toString() : exercises.map((exercise) => exercise.toJson()).toList().toString(), 'exercises': exercises.isEmpty ? [].toString() : exercises.map((exercise) => exercise.toJson()).toList().toString(),
'state': this.state.toStr(), 'state': state.toStr(),
"isTest": this.isTest, "isTest": isTest,
"dayId": this.dayId, "dayId": dayId,
"baseOneRepMax": this.baseOneRepMax, "baseOneRepMax": baseOneRepMax,
}; };
//print("Detail toJson $jsonMap"); //print("Detail toJson $jsonMap");
@ -132,31 +133,31 @@ class CustomerTrainingPlanDetails {
} }
@override @override
String toString() => this.toJsonWithExercises().toString(); String toString() => toJsonWithExercises().toString();
void copy(CustomerTrainingPlanDetails from) { void copy(CustomerTrainingPlanDetails from) {
this.customerTrainingPlanDetailsId = from.customerTrainingPlanDetailsId; customerTrainingPlanDetailsId = from.customerTrainingPlanDetailsId;
this.trainingPlanDetailsId = from.trainingPlanDetailsId; trainingPlanDetailsId = from.trainingPlanDetailsId;
this.exerciseTypeId = from.exerciseTypeId; exerciseTypeId = from.exerciseTypeId;
this.exerciseType = from.exerciseType; exerciseType = from.exerciseType;
this.set = from.set; set = from.set;
this.repeats = from.repeats; repeats = from.repeats;
this.weight = from.weight; weight = from.weight;
this.restingTime = from.restingTime; restingTime = from.restingTime;
this.parallel = from.parallel; parallel = from.parallel;
this.exercises = from.exercises; exercises = from.exercises;
this.state = from.state; state = from.state;
this.isTest = from.isTest; isTest = from.isTest;
this.day = from.day; day = from.day;
this.dayId = from.dayId; dayId = from.dayId;
this.baseOneRepMax = from.baseOneRepMax; baseOneRepMax = from.baseOneRepMax;
if (from.exercises.length == 0) { if (from.exercises.isEmpty) {
this.exercises = []; exercises = [];
}
if (from.alternatives.isNotEmpty) {
for (var alternative in from.alternatives) {
alternatives.add(alternative);
} }
if (from.alternatives.length > 0) {
from.alternatives.forEach((alternative) {
this.alternatives.add(alternative);
});
} }
} }
} }

View File

@ -9,22 +9,22 @@ class CustomerTrainingPlanExercise {
CustomerTrainingPlanExercise(); CustomerTrainingPlanExercise();
CustomerTrainingPlanExercise.fromJson(Map json) { CustomerTrainingPlanExercise.fromJson(Map json) {
this.customerTrainingPlanExerciseId = json['customerTrainingPlanExerciseId']; customerTrainingPlanExerciseId = json['customerTrainingPlanExerciseId'];
this.customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId']; customerTrainingPlanDetailsId = json['customerTrainingPlanDetailsId'];
this.customerId = json['customerId']; customerId = json['customerId'];
this.exerciseId = json['exerciseId']; exerciseId = json['exerciseId'];
this.repeats = json['repeats']; repeats = json['repeats'];
this.weight = json['weight']; weight = json['weight'];
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"customerTrainingPlanDetailsId": this.customerTrainingPlanDetailsId, "customerTrainingPlanDetailsId": customerTrainingPlanDetailsId,
"customerId": this.customerId, "customerId": customerId,
"exerciseId": this.exerciseId, "exerciseId": exerciseId,
"weight": this.weight, "weight": weight,
"repeats": this.repeats "repeats": repeats
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -12,29 +12,29 @@ class Description {
String? descriptionTranslation; String? descriptionTranslation;
Description.fromJson(Map json) { Description.fromJson(Map json) {
this.descriptionId = json['descriptionId']; descriptionId = json['descriptionId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.version = json['version']; version = json['version'];
this.validFrom = json['validFrom']; validFrom = json['validFrom'];
this.validTo = json['validTo']; validTo = json['validTo'];
if (json['translations'] != null && json['translations'].length > 0) { if (json['translations'] != null && json['translations'].length > 0) {
this.descriptionTranslation = descriptionTranslation =
AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['descriptionTranslation'] : json['description']; AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['descriptionTranslation'] : json['description'];
} }
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"descriptionId": this.descriptionId, "descriptionId": descriptionId,
"name": this.name, "name": name,
"description": this.description, "description": description,
"version": this.version, "version": version,
"validFrom": this.validFrom, "validFrom": validFrom,
"validTo": this.validTo, "validTo": validTo,
"descriptionTranslation": this.descriptionTranslation "descriptionTranslation": descriptionTranslation
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -12,16 +12,16 @@ class Evaluation {
name = json['name']; name = json['name'];
exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
unit = json['unit']; unit = json['unit'];
this.attributes = json['attributes'].map((attr) => EvaluationAttribute.fromJson(attr)).toList(); attributes = json['attributes'].map((attr) => EvaluationAttribute.fromJson(attr)).toList();
} }
@override @override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
'evaluationId': this.evaluationId, 'evaluationId': evaluationId,
'name': this.name, 'name': name,
'exerciseTypeId': this.exerciseTypeId, 'exerciseTypeId': exerciseTypeId,
'unit': this.unit 'unit': unit
}; };
return json.toString(); return json.toString();
} }

View File

@ -26,15 +26,15 @@ class EvaluationAttribute {
@override @override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
'evaluationAttrId': this.evaluationAttrId, 'evaluationAttrId': evaluationAttrId,
'evaluationId': this.evaluationId, 'evaluationId': evaluationId,
'name': this.name, 'name': name,
'sex': this.sex, 'sex': sex,
'ageMin': this.ageMin, 'ageMin': ageMin,
'ageMax': this.ageMax, 'ageMax': ageMax,
'valueMin': this.valueMin, 'valueMin': valueMin,
'valueMax': this.valueMax, 'valueMax': valueMax,
'evaluation_text': this.evaluationText, 'evaluation_text': evaluationText,
}; };
return json.toString(); return json.toString();
} }

View File

@ -15,20 +15,20 @@ class Exercise {
double? calculated; double? calculated;
String? summary; String? summary;
Exercise({this.exerciseTypeId, this.customerId, this.quantity, this.dateAdd}); Exercise({exerciseTypeId, customerId, quantity, dateAdd});
Exercise.fromJson(Map json) { Exercise.fromJson(Map json) {
this.exerciseId = json['exerciseId']; exerciseId = json['exerciseId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.customerId = json['customerId']; customerId = json['customerId'];
this.quantity = json['quantity']; quantity = json['quantity'];
this.unit = json['unit']; unit = json['unit'];
this.unitQuantity = json['unitQuantity']; unitQuantity = json['unitQuantity'];
this.dateAdd = DateTime.parse(json['dateAdd']); dateAdd = DateTime.parse(json['dateAdd']);
this.datePart = DateFormat('yyyy-MM-dd').format(this.dateAdd!); datePart = DateFormat('yyyy-MM-dd').format(dateAdd!);
this.calculated = quantity; calculated = quantity;
this.exercisePlanDetailId = json['exercisePlanDetailId'] == "null" ? null : json['exercisePlanDetailId']; exercisePlanDetailId = json['exercisePlanDetailId'] == "null" ? null : json['exercisePlanDetailId'];
this.trainingPlanDetailsId = json['trainingPlanDetailsId'] == "null" ? null : json['trainingPlanDetailsId']; trainingPlanDetailsId = json['trainingPlanDetailsId'] == "null" ? null : json['trainingPlanDetailsId'];
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
@ -37,7 +37,7 @@ class Exercise {
"quantity": quantity, "quantity": quantity,
"unit": unit, "unit": unit,
"unitQuantity": unitQuantity, "unitQuantity": unitQuantity,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd!),
"exercisePlanDetailId": exercisePlanDetailId, "exercisePlanDetailId": exercisePlanDetailId,
"trainingPlanDetailsId": trainingPlanDetailsId, "trainingPlanDetailsId": trainingPlanDetailsId,
}; };
@ -49,20 +49,20 @@ class Exercise {
'calculated': calculated, 'calculated': calculated,
"unit": unit, "unit": unit,
"unitQuantity": unitQuantity, "unitQuantity": unitQuantity,
"datePart": this.datePart, "datePart": datePart,
}; };
Exercise copy() { Exercise copy() {
Exercise newExercise = Exercise newExercise =
Exercise(exerciseTypeId: this.exerciseTypeId, customerId: this.customerId, quantity: this.quantity, dateAdd: this.dateAdd); Exercise(exerciseTypeId: exerciseTypeId, customerId: customerId, quantity: quantity, dateAdd: dateAdd);
newExercise.unit = this.unit; newExercise.unit = unit;
newExercise.unitQuantity = this.unitQuantity; newExercise.unitQuantity = unitQuantity;
newExercise.exercisePlanDetailId = this.exercisePlanDetailId; newExercise.exercisePlanDetailId = exercisePlanDetailId;
return newExercise; return newExercise;
} }
@override @override
String toString() { String toString() {
return this.toJson().toString(); return toJson().toString();
} }
} }

View File

@ -1,9 +1,9 @@
enum ExerciseAbility { oneRepMax, endurance, running, mini_test_set, paralell_test, training, training_execute, none } enum ExerciseAbility { oneRepMax, endurance, running, mini_test_set, paralell_test, training, training_execute, none }
extension ExerciseAbilityExt on ExerciseAbility { extension ExerciseAbilityExt on ExerciseAbility {
String enumToString() => this.toString().split(".").last; String enumToString() => toString().split(".").last;
bool equalsTo(ExerciseAbility ability) => this.toString() == ability.toString(); bool equalsTo(ExerciseAbility ability) => toString() == ability.toString();
bool equalsStringTo(String ability) => this.enumToString() == ability; bool equalsStringTo(String ability) => enumToString() == ability;
String get description { String get description {
switch (this) { switch (this) {
case ExerciseAbility.endurance: case ExerciseAbility.endurance:

View File

@ -10,12 +10,12 @@ class ExerciseDevice {
bool? isGym; bool? isGym;
ExerciseDevice.fromJson(Map json) { ExerciseDevice.fromJson(Map json) {
this.exerciseDeviceId = json['exerciseDeviceId']; exerciseDeviceId = json['exerciseDeviceId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.imageUrl = json['imageUrl']; imageUrl = json['imageUrl'];
this.nameTranslation = json['translations'][0]['name']; nameTranslation = json['translations'][0]['name'];
this.sort = json['sort']; sort = json['sort'];
this.place = json['place'] == 1 ? true : false; place = json['place'] == 1 ? true : false;
} }
} }

View File

@ -12,21 +12,21 @@ class ExercisePlan {
int? exercisePlanTemplateId; int? exercisePlanTemplateId;
ExercisePlan(String name, int customerId) { ExercisePlan(String name, int customerId) {
this.customerId = customerId; customerId = customerId;
this.name = name; name = name;
this.dateUpd = DateTime.now(); dateUpd = DateTime.now();
} }
ExercisePlan.fromJson(Map json) { ExercisePlan.fromJson(Map json) {
this.exercisePlanId = json['exercisePlanId']; exercisePlanId = json['exercisePlanId'];
this.customerId = json['customerId']; customerId = json['customerId'];
this.name = json['name']; name = json['name'];
this.private = json['private']; private = json['private'];
this.description = json['description']; description = json['description'];
this.dateAdd = (json['dateAdd'] == null ? null : DateTime.parse(json['dateAdd']))!; dateAdd = (json['dateAdd'] == null ? null : DateTime.parse(json['dateAdd']))!;
this.dateUpd = (json['dateUpd'] == null ? null : DateTime.parse(json['dateUpd']))!; dateUpd = (json['dateUpd'] == null ? null : DateTime.parse(json['dateUpd']))!;
this.type = json['type']; type = json['type'];
this.exercisePlanTemplateId = json['exercisePlanTemplateId']; exercisePlanTemplateId = json['exercisePlanTemplateId'];
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {

View File

@ -2,16 +2,17 @@ import 'dart:convert';
import 'package:workouttest_util/model/exercise.dart'; import 'package:workouttest_util/model/exercise.dart';
import 'package:workouttest_util/model/exercise_type.dart'; import 'package:workouttest_util/model/exercise_type.dart';
import 'package:workouttest_util/util/logging.dart';
enum ExercisePlanDetailState { start, inProgress, skipped, finished, extra } enum ExercisePlanDetailState { start, inProgress, skipped, finished, extra }
extension ExericisePlanDetailStateExt on ExercisePlanDetailState { extension ExericisePlanDetailStateExt on ExercisePlanDetailState {
bool equalsTo(ExercisePlanDetailState state) => this.toString() == state.toString(); bool equalsTo(ExercisePlanDetailState state) => toString() == state.toString();
bool equalsStringTo(String state) => this.toString() == state; bool equalsStringTo(String state) => toString() == state;
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
} }
class ExercisePlanDetail { class ExercisePlanDetail with Logging {
int? exercisePlanDetailId; int? exercisePlanDetailId;
int? exercisePlanId; int? exercisePlanId;
late int exerciseTypeId; late int exerciseTypeId;
@ -31,25 +32,25 @@ class ExercisePlanDetail {
String? change; // 1: update -1:delete 0: new String? change; // 1: update -1:delete 0: new
ExercisePlanDetail(int exerciseTypeId) { ExercisePlanDetail(int exerciseTypeId) {
this.exerciseTypeId = exerciseTypeId; exerciseTypeId = exerciseTypeId;
} }
ExercisePlanDetail.fromJson(Map json) { ExercisePlanDetail.fromJson(Map json) {
this.exercisePlanDetailId = json['exercisePlanDetailId']; exercisePlanDetailId = json['exercisePlanDetailId'];
this.exercisePlanId = json['exercisePlanId']; exercisePlanId = json['exercisePlanId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.serie = json['serie']; serie = json['serie'];
this.repeats = json['repeats']; repeats = json['repeats'];
this.weightEquation = json['weightEquation']; weightEquation = json['weightEquation'];
} }
ExercisePlanDetail.fromJsonWithExerciseList(Map json) { ExercisePlanDetail.fromJsonWithExerciseList(Map json) {
this.exercisePlanDetailId = json['exercisePlanDetailId']; exercisePlanDetailId = json['exercisePlanDetailId'];
this.exercisePlanId = json['exercisePlanId']; exercisePlanId = json['exercisePlanId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.serie = json['serie']; serie = json['serie'];
this.repeats = json['repeats']; repeats = json['repeats'];
this.weightEquation = json['weightEquation']; weightEquation = json['weightEquation'];
try { try {
final String exercises = json['exercises']; final String exercises = json['exercises'];
String jsonExercises = exercises.replaceAllMapped( String jsonExercises = exercises.replaceAllMapped(
@ -61,12 +62,12 @@ class ExercisePlanDetail {
Iterable iterable = jsonDecode(jsonExercises); Iterable iterable = jsonDecode(jsonExercises);
this.exercises = iterable.map((exercise) => Exercise.fromJson(exercise)).toList(); this.exercises = iterable.map((exercise) => Exercise.fromJson(exercise)).toList();
} on Exception catch (e) { } on Exception catch (e) {
print("JsonDecode error " + e.toString()); log("JsonDecode error $e");
} }
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"exercisePlanId": exercisePlanId == null ? 0 : exercisePlanId, "exercisePlanId": exercisePlanId ?? 0,
"exerciseTypeId": exerciseTypeId, "exerciseTypeId": exerciseTypeId,
"serie": serie, "serie": serie,
"repeats": repeats, "repeats": repeats,

View File

@ -12,13 +12,13 @@ class ExercisePlanTemplate {
List<int> exerciseTypes = []; List<int> exerciseTypes = [];
ExercisePlanTemplate.fromJson(Map json) { ExercisePlanTemplate.fromJson(Map json) {
this.exercisePlanTemplateId = json['exercisePlanId']; exercisePlanTemplateId = json['exercisePlanId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.templateType = json['templateType']; templateType = json['templateType'];
if (json['translations'].length > 0) { if (json['translations'].length > 0) {
this.nameTranslation = AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['name'] : json['name']; nameTranslation = AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['name'] : json['name'];
this.descriptionTranslation = AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['description'] : json['description']; descriptionTranslation = AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['description'] : json['description'];
} }
if (json['details'] != null && (json['details']).length > 0) { if (json['details'] != null && (json['details']).length > 0) {
@ -30,9 +30,9 @@ class ExercisePlanTemplate {
return a['sort'] < b['sort'] ? -1 : 1; return a['sort'] < b['sort'] ? -1 : 1;
} }
}); });
details.forEach((element) { for (var element in details) {
exerciseTypes.add(element['exerciseTypeId']); exerciseTypes.add(element['exerciseTypeId']);
}); }
} }
} }

View File

@ -27,20 +27,20 @@ class ExerciseResult {
"exercisePlanId": exercisePlanId, "exercisePlanId": exercisePlanId,
"resultType": resultType, "resultType": resultType,
"value": value, "value": value,
"dateFrom": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateFrom), "dateFrom": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateFrom),
"dateTo": formattedDateTo, "dateTo": formattedDateTo,
}; };
} }
ExerciseResult.fromJson(Map json) { ExerciseResult.fromJson(Map json) {
this.exerciseResultId = json['exerciseResultId']; exerciseResultId = json['exerciseResultId'];
this.exerciseId = json['exerciseId']; exerciseId = json['exerciseId'];
this.exercisePlanId = json['exercisePlanId']; exercisePlanId = json['exercisePlanId'];
this.customerId = json['customerId']; customerId = json['customerId'];
this.resultType = json['resultType']; resultType = json['resultType'];
this.value = json["value"]; value = json["value"];
this.dateFrom = DateTime.parse(json['dateFrom']); dateFrom = DateTime.parse(json['dateFrom']);
this.dateTo = DateTime.parse(json['dateTo']); dateTo = DateTime.parse(json['dateTo']);
this.resultExtension = ResultExt(itemString: this.resultType); resultExtension = ResultExt(itemString: resultType);
} }
} }

View File

@ -28,18 +28,18 @@ class ExerciseTree {
ExerciseTree(); ExerciseTree();
ExerciseTree.fromJson(Map json) { ExerciseTree.fromJson(Map json) {
this.treeId = json['treeId']; treeId = json['treeId'];
this.name = json['name']; name = json['name'];
this.parentId = 0; parentId = 0;
this.imageUrl = json['imageUrl']; imageUrl = json['imageUrl'];
this.active = json['active']; active = json['active'];
this.nameTranslation = json['translations'] != null && (json['translations']).length > 0 ? json['translations'][0]['name'] : this.name; nameTranslation = json['translations'] != null && (json['translations']).length > 0 ? json['translations'][0]['name'] : name;
this.descriptionTranslation = descriptionTranslation =
json['translations'] != null && (json['translations']).length > 0 && json['translations'][0]['description'] != null json['translations'] != null && (json['translations']).length > 0 && json['translations'][0]['description'] != null
? json['translations'][0]['description'] ? json['translations'][0]['description']
: this.description; : description;
this.sort = 99; sort = 99;
this.internalName = json['internalName']; internalName = json['internalName'];
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
@ -57,19 +57,19 @@ class ExerciseTree {
} }
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
ExerciseTree copy(int parentId) { ExerciseTree copy(int parentId) {
ExerciseTree newTree = ExerciseTree(); ExerciseTree newTree = ExerciseTree();
newTree.treeId = this.treeId; newTree.treeId = treeId;
newTree.name = this.name; newTree.name = name;
newTree.imageUrl = this.imageUrl; newTree.imageUrl = imageUrl;
newTree.nameTranslation = this.nameTranslation; newTree.nameTranslation = nameTranslation;
if (parentId != -1) { if (parentId != -1) {
newTree.parentId = parentId; newTree.parentId = parentId;
} }
newTree.active = this.active; newTree.active = active;
newTree.sort = this.sort == null ? 99 : this.sort; newTree.sort = sort ?? 99;
return newTree; return newTree;
} }

View File

@ -5,9 +5,9 @@ class ExerciseTreeParents {
late int sort; late int sort;
ExerciseTreeParents.fromJson(Map json) { ExerciseTreeParents.fromJson(Map json) {
this.exerciseTreeParentsId = json['exerciseTreeParentsId']; exerciseTreeParentsId = json['exerciseTreeParentsId'];
this.exerciseTreeParentId = json['exerciseTreeParentId']; exerciseTreeParentId = json['exerciseTreeParentId'];
this.exerciseTreeChildId = json['exerciseTreeChildId']; exerciseTreeChildId = json['exerciseTreeChildId'];
this.sort = json['sort']; sort = json['sort'];
} }
} }

View File

@ -55,49 +55,49 @@ class ExerciseType {
/// custom training plan /// custom training plan
ExerciseTypeTrainingPlanState trainingPlanState = ExerciseTypeTrainingPlanState.none; ExerciseTypeTrainingPlanState trainingPlanState = ExerciseTypeTrainingPlanState.none;
ExerciseType({required this.name, required this.description}); ExerciseType({required name, required description});
ExerciseType.fromJson(Map json) { ExerciseType.fromJson(Map json) {
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
//this.treeId = json['treeId']; //treeId = json['treeId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.unit = json['unit']; unit = json['unit'];
this.unitQuantity = json['unitQuantity']; unitQuantity = json['unitQuantity'];
this.unitQuantityUnit = json['unitQuantityUnit']; unitQuantityUnit = json['unitQuantityUnit'];
this.active = json['active']; active = json['active'];
this.base = json['base']; base = json['base'];
this.buddyWarning = json['buddyWarning']; buddyWarning = json['buddyWarning'];
if (json['images'].length > 0) { if (json['images'].length > 0) {
this.imageUrl = json['images'][0]['url']; imageUrl = json['images'][0]['url'];
} }
if (json['translations'].length > 0) { if (json['translations'].length > 0) {
this.nameTranslation = AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['name'] : json['name']; nameTranslation = AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['name'] : json['name'];
this.descriptionTranslation = AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['description'] : json['description']; descriptionTranslation = AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['description'] : json['description'];
} }
if (json['devices'].length > 0) { if (json['devices'].length > 0) {
final List jsonDevices = json['devices']; final List jsonDevices = json['devices'];
jsonDevices.forEach((device) { for (var device in jsonDevices) {
this.devices.add(device['exerciseDeviceId']); devices.add(device['exerciseDeviceId']);
}); }
} }
if (json['parents'].length > 0) { if (json['parents'].length > 0) {
final List jsonParents = json['parents']; final List jsonParents = json['parents'];
jsonParents.forEach((parent) { for (var parent in jsonParents) {
this.parents.add(parent['exerciseTreeId']); parents.add(parent['exerciseTreeId']);
}); }
} }
if (json['alternatives'].length > 0) { if (json['alternatives'].length > 0) {
final List jsonAlternatives = json['alternatives']; final List jsonAlternatives = json['alternatives'];
jsonAlternatives.forEach((alternative) { for (var alternative in jsonAlternatives) {
this.alternatives.add(alternative['exerciseTypeChildId']); alternatives.add(alternative['exerciseTypeChildId']);
}); }
} }
} }
@ -110,25 +110,25 @@ class ExerciseType {
"active": active, "active": active,
"base": base, "base": base,
"buddyWarning": buddyWarning, "buddyWarning": buddyWarning,
"devices": this.devices.toString(), "devices": devices.toString(),
"nameTranslation": this.nameTranslation, "nameTranslation": nameTranslation,
"parents": this.parents.toString() "parents": parents.toString()
}; };
void setAbility(ExerciseAbility ability) { void setAbility(ExerciseAbility ability) {
this.ability = ability; ability = ability;
} }
ExerciseAbility getAbility() { ExerciseAbility getAbility() {
return this.ability!; return ability!;
} }
bool is1RM() { bool is1RM() {
return this.ability!.equalsTo(ExerciseAbility.oneRepMax); return ability!.equalsTo(ExerciseAbility.oneRepMax);
} }
@override @override
String toString() { String toString() {
return this.toJson().toString(); return toJson().toString();
} }
} }

View File

@ -5,7 +5,7 @@ class ExerciseTypeDevice {
ExerciseTypeDevice(); ExerciseTypeDevice();
ExerciseTypeDevice.fromJson(Map json) { ExerciseTypeDevice.fromJson(Map json) {
this.exerciseTypeDeviceId = json['exerciseTypeDeviceId']; exerciseTypeDeviceId = json['exerciseTypeDeviceId'];
this.exerciseDeviceId = json['exerciseDeviceId']; exerciseDeviceId = json['exerciseDeviceId'];
} }
} }

View File

@ -10,10 +10,10 @@ class Faq {
HashMap<String, String> descriptionTranslations = HashMap(); HashMap<String, String> descriptionTranslations = HashMap();
Faq.fromJson(Map json) { Faq.fromJson(Map json) {
this.faqId = json['faqId']; faqId = json['faqId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.sort = json['sort']; sort = json['sort'];
nameTranslations['en'] = name; nameTranslations['en'] = name;
descriptionTranslations['en'] = description; descriptionTranslations['en'] = description;
@ -26,12 +26,12 @@ class Faq {
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"faqId": this.faqId, "faqId": faqId,
"name": this.name, "name": name,
"description": this.description, "description": description,
"nameTranslation": this.nameTranslations.toString(), "nameTranslation": nameTranslations.toString(),
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -8,13 +8,13 @@ class FitnessState {
static String advanced = "advanced"; static String advanced = "advanced";
static String professional = "professional"; static String professional = "professional";
FitnessState({required this.value, required this.stateText, required this.explanation}); FitnessState({required value, required stateText, required explanation});
bool isEqual(FitnessState? state) { bool isEqual(FitnessState? state) {
if (state == null) { if (state == null) {
return false; return false;
} }
return state.value == this.value; return state.value == value;
} }
@override @override
@ -33,17 +33,17 @@ class FitnessItem {
FitnessItem._internal() { FitnessItem._internal() {
elements.add(FitnessState( elements.add(FitnessState(
value: FitnessState.beginner, stateText: _capitalize(FitnessState.beginner), explanation: "I am " + FitnessState.beginner)); value: FitnessState.beginner, stateText: _capitalize(FitnessState.beginner), explanation: "I am ${FitnessState.beginner}"));
elements.add(FitnessState( elements.add(FitnessState(
value: FitnessState.intermediate, value: FitnessState.intermediate,
stateText: _capitalize(FitnessState.intermediate), stateText: _capitalize(FitnessState.intermediate),
explanation: "I am " + FitnessState.intermediate)); explanation: "I am ${FitnessState.intermediate}"));
elements.add(FitnessState( elements.add(FitnessState(
value: FitnessState.advanced, stateText: _capitalize(FitnessState.advanced), explanation: "I am " + FitnessState.advanced)); value: FitnessState.advanced, stateText: _capitalize(FitnessState.advanced), explanation: "I am ${FitnessState.advanced}"));
elements.add(FitnessState( elements.add(FitnessState(
value: FitnessState.professional, value: FitnessState.professional,
stateText: _capitalize(FitnessState.professional), stateText: _capitalize(FitnessState.professional),
explanation: "I am " + FitnessState.professional)); explanation: "I am ${FitnessState.professional}"));
} }
String _capitalize(String value) { String _capitalize(String value) {
@ -53,15 +53,15 @@ class FitnessItem {
List<FitnessState> toList() => elements; List<FitnessState> toList() => elements;
FitnessState? getItem(String? value) { FitnessState? getItem(String? value) {
if (value == null || value.length == 0) { if (value == null || value.isEmpty) {
return elements[0]; return elements[0];
} }
FitnessState? selected; FitnessState? selected;
elements.forEach((element) { for (var element in elements) {
if (element.value == value) { if (element.value == value) {
selected = element; selected = element;
} }
}); }
return selected; return selected;
} }
} }

View File

@ -42,5 +42,5 @@ class Mautic {
} }
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -15,38 +15,38 @@ class Product {
String? localizedPrice; String? localizedPrice;
Product.fromJson(Map json) { Product.fromJson(Map json) {
this.productId = json['productId']; productId = json['productId'];
this.name = json['name']; name = json['name'];
this.description = json['description']; description = json['description'];
this.type = json['type']; type = json['type'];
this.appVersion = json['appVersion']; appVersion = json['appVersion'];
this.sort = json['sort']; sort = json['sort'];
this.productSet = json['productSet']; productSet = json['productSet'];
this.validFrom = (json['validFrom'] == null ? null : DateTime.parse(json['validFrom']))!; validFrom = (json['validFrom'] == null ? null : DateTime.parse(json['validFrom']))!;
this.validTo = json['validTo'] == null ? null : DateTime.parse(json['validTo']); validTo = json['validTo'] == null ? null : DateTime.parse(json['validTo']);
this.productIdIos = json['productIdIos']; productIdIos = json['productIdIos'];
this.productIdAndroid = json['productIdAndroid']; productIdAndroid = json['productIdAndroid'];
this.priceIos = json['priceIos']; priceIos = json['priceIos'];
this.priceAndroid = json['priceAndroid']; priceAndroid = json['priceAndroid'];
} }
@override @override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
'productId': this.productId, 'productId': productId,
'name': this.name, 'name': name,
'description': this.description, 'description': description,
'type': this.type, 'type': type,
'appVersion': this.appVersion, 'appVersion': appVersion,
'sort': this.sort, 'sort': sort,
'productSet': this.productSet, 'productSet': productSet,
'validFrom': this.validFrom, 'validFrom': validFrom,
'validTo': validTo, 'validTo': validTo,
'productIdIos': this.productIdIos, 'productIdIos': productIdIos,
'productIdAndroid': this.productIdAndroid, 'productIdAndroid': productIdAndroid,
'priceIos': this.priceIos, 'priceIos': priceIos,
'priceAndroid': this.priceAndroid, 'priceAndroid': priceAndroid,
'localizedPrice': this.localizedPrice 'localizedPrice': localizedPrice
}; };
return json.toString(); return json.toString();
} }

View File

@ -8,15 +8,16 @@ class Property {
double? value; double? value;
Property.fromJson(Map json) { Property.fromJson(Map json) {
this.propertyId = json['propertyId']; propertyId = json['propertyId'];
this.propertyName = json['propertyName']; propertyName = json['propertyName'];
this.propertyUnit = json['propertyUnit']; propertyUnit = json['propertyUnit'];
this.propertyNameTranslation = propertyNameTranslation =
json['translations'] != null && (json['translations']).length > 0 json['translations'] != null && (json['translations']).length > 0
? json['translations'][0]['propertyName'] ? json['translations'][0]['propertyName']
: this.propertyName; : propertyName;
} }
@override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
"propertyId": propertyId, "propertyId": propertyId,

View File

@ -9,15 +9,15 @@ class Purchase {
late double purchaseSum; late double purchaseSum;
late String currency; late String currency;
Purchase({required this.customerId, required this.productId}); Purchase({required customerId, required productId});
Purchase.fromJson(Map json) { Purchase.fromJson(Map json) {
this.purchaseId = json['purchaseId']; purchaseId = json['purchaseId'];
this.customerId = json['customerId']; customerId = json['customerId'];
this.productId = json['productId']; productId = json['productId'];
this.dateAdd = DateTime.parse(json['dateAdd']); dateAdd = DateTime.parse(json['dateAdd']);
this.purchaseSum = json['purchaseSum']; purchaseSum = json['purchaseSum'];
this.currency = json['currency']; currency = json['currency'];
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
@ -25,7 +25,7 @@ class Purchase {
"customerId": customerId, "customerId": customerId,
"productId": productId, "productId": productId,
"purchaseSum": purchaseSum, "purchaseSum": purchaseSum,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd),
"currency": currency, "currency": currency,
}; };
} }

View File

@ -59,8 +59,8 @@ extension ResultItemExt on ResultItem {
ResultItem.fatburn_percent: true, ResultItem.fatburn_percent: true,
}; };
bool equals(ResultItem item) => this.toString() == item.toString(); bool equals(ResultItem item) => toString() == item.toString();
bool equalsString(String item) => this.description == item; bool equalsString(String item) => description == item;
String? get description => ResultItemDesc[this]; String? get description => ResultItemDesc[this];
String? get image => ResultItemImg[this]; String? get image => ResultItemImg[this];
@ -78,24 +78,24 @@ class ResultExt {
DateTime? dateTo; DateTime? dateTo;
ResultExt({required this.itemString}) { ResultExt({required itemString}) {
ResultItem.values.forEach((element) { for (var element in ResultItem.values) {
if (element.equalsString(itemString)) { if (element.equalsString(itemString)) {
item = element; item = element;
} }
}); }
} }
String? getDescription() => item.description; String? getDescription() => item.description;
String getImage() => "asset/image/" + item.image!; String getImage() => "asset/image/${item.image!}";
bool? isHardware() => item.isHardware; bool? isHardware() => item.isHardware;
int? get getExerciseId => exerciseId; int? get getExerciseId => exerciseId;
set setExerciseId(int exerciseId) => this.exerciseId = exerciseId; set setExerciseId(int exerciseId) => exerciseId = exerciseId;
set setDateFrom(DateTime dateFrom) => this.dateFrom = dateFrom; set setDateFrom(DateTime dateFrom) => dateFrom = dateFrom;
DateTime? get getDateFrom => dateFrom; DateTime? get getDateFrom => dateFrom;
set setDateTo(DateTime dateTo) => this.dateTo = dateTo; set setDateTo(DateTime dateTo) => dateTo = dateTo;
DateTime? get getDateTo => dateTo; DateTime? get getDateTo => dateTo;
bool equals(ResultItem item) => this.item.equals(item); bool equals(ResultItem item) => item.equals(item);
bool equalsString(String item) => this.item.equalsString(item); bool equalsString(String item) => this.item.equalsString(item);
} }

View File

@ -9,26 +9,26 @@ class SplitTest {
DateTime? validTo; DateTime? validTo;
SplitTest.fromJson(Map json) { SplitTest.fromJson(Map json) {
this.testId = json['testId']; testId = json['testId'];
this.name = json['name']; name = json['name'];
this.remoteConfigKey = json['remoteConfigKey']; remoteConfigKey = json['remoteConfigKey'];
this.remoteConfigValue = json['remoteConfigValue']; remoteConfigValue = json['remoteConfigValue'];
this.testValue = json['testValue']; testValue = json['testValue'];
this.source = json['source']; source = json['source'];
this.active = json['active']; active = json['active'];
this.validTo = json['validTo'] == null ? null : DateTime.parse(json['validTo']); validTo = json['validTo'] == null ? null : DateTime.parse(json['validTo']);
} }
@override @override
String toString() { String toString() {
Map<String, dynamic> json = { Map<String, dynamic> json = {
'productId': this.testId, 'productId': testId,
'name': this.name, 'name': name,
'remoteConfigKey': this.remoteConfigKey, 'remoteConfigKey': remoteConfigKey,
'remoteConfigValue': this.remoteConfigValue, 'remoteConfigValue': remoteConfigValue,
'testValue': this.testValue, 'testValue': testValue,
'source': this.source, 'source': source,
'active': this.active, 'active': active,
'validTo': validTo, 'validTo': validTo,
}; };
return json.toString(); return json.toString();

View File

@ -7,8 +7,8 @@ class Sport {
HashMap<String, String> nameTranslations = HashMap(); HashMap<String, String> nameTranslations = HashMap();
Sport.fromJson(Map json) { Sport.fromJson(Map json) {
this.sportId = json['sportId']; sportId = json['sportId'];
this.name = json['name']; name = json['name'];
nameTranslations['en'] = name; nameTranslations['en'] = name;
if (json['translations'] != null && json['translations'].length > 0) { if (json['translations'] != null && json['translations'].length > 0) {
@ -25,6 +25,6 @@ class Sport {
@override @override
String toString() { String toString() {
return this.toJson().toString(); return toJson().toString();
} }
} }

View File

@ -14,11 +14,11 @@ class Tracking {
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"customerId": customerId, "customerId": customerId,
"dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd), "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(dateAdd),
"event": event, "event": event,
"eventValue": eventValue, "eventValue": eventValue,
"area": Platform.localeName, "area": Platform.localeName,
"platform": Platform.isAndroid ? "Android" : "iOS", "platform": Platform.isAndroid ? "Android" : "iOS",
"version": Cache().packageInfo != null ? Cache().packageInfo!.version + "+" + Cache().packageInfo!.buildNumber : "" "version": Cache().packageInfo != null ? "${Cache().packageInfo!.version}+${Cache().packageInfo!.buildNumber}" : ""
}; };
} }

View File

@ -5,9 +5,9 @@ import 'package:flutter/material.dart';
enum TrainingEvaluationExerciseType { weightBased, repeatBased, secondBased } enum TrainingEvaluationExerciseType { weightBased, repeatBased, secondBased }
extension TrainingEvaluationExerciseTypeExt on TrainingEvaluationExerciseType { extension TrainingEvaluationExerciseTypeExt on TrainingEvaluationExerciseType {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(TrainingEvaluationExerciseType value) => this.toString() == value.toString(); bool equalsTo(TrainingEvaluationExerciseType value) => toString() == value.toString();
bool equalsStringTo(String value) => this.toString() == value; bool equalsStringTo(String value) => toString() == value;
} }
class TrainingEvaluationExercise { class TrainingEvaluationExercise {

View File

@ -18,14 +18,14 @@ class TrainingPlan {
List<TrainingPlanDetail>? details; List<TrainingPlanDetail>? details;
TrainingPlan.fromJson(Map<String, dynamic> json) { TrainingPlan.fromJson(Map<String, dynamic> json) {
this.trainingPlanId = json['trainingPlanId']; trainingPlanId = json['trainingPlanId'];
this.name = json['name']; name = json['name'];
this.type = json['type']; type = json['type'];
this.internalName = json['internalName']; internalName = json['internalName'];
this.description = json['description']; description = json['description'];
this.free = json['free']; free = json['free'];
this.active = json['active']; active = json['active'];
this.treeId = json['treeId']; treeId = json['treeId'];
nameTranslations['en'] = name; nameTranslations['en'] = name;
descriptionTranslations['en'] = description ?? ""; descriptionTranslations['en'] = description ?? "";
@ -58,17 +58,17 @@ class TrainingPlan {
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"trainingPlanId": this.trainingPlanId, "trainingPlanId": trainingPlanId,
"treeId": this.treeId, "treeId": treeId,
"name": this.name, "name": name,
"type": this.type, "type": type,
"internalName": this.internalName, "internalName": internalName,
"free": this.free, "free": free,
"active": this.active, "active": active,
"description": this.description, "description": description,
"nameTranslation": this.nameTranslations.toString(), "nameTranslation": nameTranslations.toString(),
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -7,8 +7,8 @@ class TrainingPlanDay {
HashMap<String, String> nameTranslations = HashMap(); HashMap<String, String> nameTranslations = HashMap();
TrainingPlanDay.fromJson(Map json) { TrainingPlanDay.fromJson(Map json) {
this.dayId = json['dayId']; dayId = json['dayId'];
this.name = json['name']; name = json['name'];
nameTranslations['en'] = name; nameTranslations['en'] = name;
if (json['translations'] != null && json['translations'].length > 0) { if (json['translations'] != null && json['translations'].length > 0) {
@ -19,11 +19,11 @@ class TrainingPlanDay {
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"dayId": this.dayId, "dayId": dayId,
"name": this.name, "name": name,
"nameTranslation": this.nameTranslations.toString(), "nameTranslation": nameTranslations.toString(),
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -13,32 +13,32 @@ class TrainingPlanDetail {
String? summary; String? summary;
TrainingPlanDetail.fromJson(Map<String, dynamic> json) { TrainingPlanDetail.fromJson(Map<String, dynamic> json) {
this.trainingPlanDetailId = json['trainingPlanDetailId']; trainingPlanDetailId = json['trainingPlanDetailId'];
this.trainingPlanId = json['trainingPlanId']; trainingPlanId = json['trainingPlanId'];
this.exerciseTypeId = json['exerciseTypeId']; exerciseTypeId = json['exerciseTypeId'];
this.sort = json['sort']; sort = json['sort'];
this.set = json['set']; set = json['set'];
this.repeats = json['repeats']; repeats = json['repeats'];
this.weight = json['weight']; weight = json['weight'];
this.restingTime = json['restingTime']; restingTime = json['restingTime'];
this.parallel = json['parallel']; parallel = json['parallel'];
this.dayId = json['dayId']; dayId = json['dayId'];
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"trainingPlanDetailId": this.trainingPlanDetailId, "trainingPlanDetailId": trainingPlanDetailId,
"trainingPlanId": this.trainingPlanId, "trainingPlanId": trainingPlanId,
"exerciseType": this.exerciseTypeId, "exerciseType": exerciseTypeId,
"sort": this.sort, "sort": sort,
"repeats": this.repeats, "repeats": repeats,
"weight": this.weight, "weight": weight,
"restingTime": this.restingTime, "restingTime": restingTime,
"parallel": this.parallel, "parallel": parallel,
"dayId": this.dayId, "dayId": dayId,
"day": this.day, "day": day,
"summary": this.summary, "summary": summary,
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -9,8 +9,8 @@ class Tutorial {
List<TutorialStep>? steps; List<TutorialStep>? steps;
Tutorial.fromJson(Map<String, dynamic> json) { Tutorial.fromJson(Map<String, dynamic> json) {
this.tutorialId = json['tutorialId']; tutorialId = json['tutorialId'];
this.name = json['name']; name = json['name'];
if (json['steps'] != null && json['steps'].length > 0) { if (json['steps'] != null && json['steps'].length > 0) {
steps = json['steps'].map<TutorialStep>((step) => TutorialStep.fromJson(step)).toList(); steps = json['steps'].map<TutorialStep>((step) => TutorialStep.fromJson(step)).toList();
@ -30,8 +30,8 @@ class Tutorial {
} }
} }
Map<String, dynamic> toJson() => {'tutorialId': this.tutorialId, 'name': this.name, 'steps': steps.toString()}; Map<String, dynamic> toJson() => {'tutorialId': tutorialId, 'name': name, 'steps': steps.toString()};
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -18,33 +18,33 @@ class TutorialStepAction {
late int parent; late int parent;
TutorialStepAction.fromJson(Map json) { TutorialStepAction.fromJson(Map json) {
this.direction = json['direction']; direction = json['direction'];
this.top = json['top']; top = json['top'];
this.left = json['left']; left = json['left'];
this.showBubble = json['show_bubble']; showBubble = json['show_bubble'];
this.bubbleX = json['bubble_x']; bubbleX = json['bubble_x'];
this.bubbleY = json['bubble_y']; bubbleY = json['bubble_y'];
this.bubbleWidth = json['bubble_width']; bubbleWidth = json['bubble_width'];
this.bubbleHeight = json['bubble_height']; bubbleHeight = json['bubble_height'];
this.showCheckText = json['show_check_text']; showCheckText = json['show_check_text'];
this.parent = json['parent']; parent = json['parent'];
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"direction": this.direction, "direction": direction,
"top": this.top, "top": top,
"left": this.left, "left": left,
"showBubble": this.showBubble, "showBubble": showBubble,
"bubbleX": this.bubbleX, "bubbleX": bubbleX,
"bubbleY": this.bubbleY, "bubbleY": bubbleY,
"bubbleWidth": this.bubbleWidth, "bubbleWidth": bubbleWidth,
"bubbleHeight": this.bubbleHeight, "bubbleHeight": bubbleHeight,
"showCheckText": this.showCheckText, "showCheckText": showCheckText,
"parent": this.parent, "parent": parent,
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }
class TutorialStep { class TutorialStep {
@ -63,36 +63,36 @@ class TutorialStep {
String? errorTextTranslation; String? errorTextTranslation;
TutorialStep.fromJson(Map json) { TutorialStep.fromJson(Map json) {
this.tutorialStepId = json['tutorialStepId']; tutorialStepId = json['tutorialStepId'];
this.tutorialId = json['tutorialId']; tutorialId = json['tutorialId'];
this.step = json['step']; step = json['step'];
this.tutorialText = json['tutorialText']; tutorialText = json['tutorialText'];
this.checkText = json['checkText']; checkText = json['checkText'];
this.condition = json['condition']; condition = json['condition'];
if (this.condition != null) { if (condition != null) {
this.condition = condition!.replaceAll(r'\\', "replace"); condition = condition!.replaceAll(r'\\', "replace");
this.action = TutorialStepAction.fromJson(jsonDecode(condition!)); action = TutorialStepAction.fromJson(jsonDecode(condition!));
} }
if (json['translations'] != null && json['translations'].length > 0) { if (json['translations'] != null && json['translations'].length > 0) {
this.tutorialTextTranslation = tutorialTextTranslation =
AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['tutorialText'] : json['tutorialText']; AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['tutorialText'] : json['tutorialText'];
this.errorTextTranslation = AppLanguage().appLocal == Locale('hu') ? json['translations'][0]['errorText'] : json['errorText']; errorTextTranslation = AppLanguage().appLocal == const Locale('hu') ? json['translations'][0]['errorText'] : json['errorText'];
} }
} }
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"tutorialStepId": this.tutorialStepId, "tutorialStepId": tutorialStepId,
"tutorialId": this.tutorialId, "tutorialId": tutorialId,
"step": this.step, "step": step,
"tutorialText": this.tutorialText, "tutorialText": tutorialText,
"checkText": this.checkText, "checkText": checkText,
"tutorialTextTranslation": this.tutorialTextTranslation, "tutorialTextTranslation": tutorialTextTranslation,
"errorTextTranslation": this.errorTextTranslation, "errorTextTranslation": errorTextTranslation,
"condition": this.condition, "condition": condition,
"action": this.action != null ? this.action!.toJson() : "" "action": action != null ? action!.toJson() : ""
}; };
@override @override
String toString() => this.toJson().toString(); String toString() => toJson().toString();
} }

View File

@ -12,8 +12,8 @@ extension WorkoutTypeExt on WorkoutType {
WorkoutType.staticExercise: "Static" WorkoutType.staticExercise: "Static"
}; };
bool equals(WorkoutType type) => this.toString() == type.toString(); bool equals(WorkoutType type) => toString() == type.toString();
bool equalsString(String type) => this.toString() == type; bool equalsString(String type) => toString() == type;
String? get menu => WorkoutTypeMenu[this]; String? get menu => WorkoutTypeMenu[this];
} }
@ -43,23 +43,23 @@ class WorkoutMenuTree {
late String internalName; late String internalName;
WorkoutMenuTree( WorkoutMenuTree(
this.id, id,
this.parent, parent,
this.name, name,
this.imageName, imageName,
this.color, color,
this.fontSize, fontSize,
this.child, child,
this.exerciseTypeId, exerciseTypeId,
this.exerciseType, exerciseType,
this.base, base,
this.is1RM, is1RM,
this.isRunning, isRunning,
this.nameEnglish, nameEnglish,
this.parentName, parentName,
this.parentNameEnglish, parentNameEnglish,
this.sort, sort,
this.internalName); internalName);
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
@ -81,6 +81,6 @@ class WorkoutMenuTree {
@override @override
String toString() { String toString() {
return this.toJson().toString(); return toJson().toString();
} }
} }

View File

@ -7,26 +7,26 @@ import 'package:workouttest_util/service/customer_exercise_device_service.dart';
class CustomerExerciseDeviceRepository { class CustomerExerciseDeviceRepository {
List<CustomerExerciseDevice> _devices = []; List<CustomerExerciseDevice> _devices = [];
List<CustomerExerciseDevice> getDevices() => this._devices; List<CustomerExerciseDevice> getDevices() => _devices;
void setDevices(List<CustomerExerciseDevice> devices) => this._devices = devices; void setDevices(List<CustomerExerciseDevice> devices) => _devices = devices;
Future<List<CustomerExerciseDevice>?> getDBDevices() async { Future<List<CustomerExerciseDevice>?> getDBDevices() async {
if (Cache().userLoggedIn != null) { if (Cache().userLoggedIn != null) {
final int customerId = Cache().userLoggedIn!.customerId!; final int customerId = Cache().userLoggedIn!.customerId!;
this._devices = await CustomerExerciseDeviceApi().getDevices(customerId); _devices = await CustomerExerciseDeviceApi().getDevices(customerId);
} }
return this._devices; return _devices;
} }
Future<void> addDevice(ExerciseDevice device) async { Future<void> addDevice(ExerciseDevice device) async {
CustomerExerciseDevice? found; CustomerExerciseDevice? found;
this._devices.forEach((element) { for (var element in _devices) {
if (element.exerciseDeviceId == device.exerciseDeviceId) { if (element.exerciseDeviceId == device.exerciseDeviceId) {
found = element; found = element;
} }
}); }
if (found == null) { if (found == null) {
int? customerId; int? customerId;
@ -37,7 +37,7 @@ class CustomerExerciseDeviceRepository {
CustomerExerciseDevice(customerId: customerId!, exerciseDeviceId: device.exerciseDeviceId, favourite: false); CustomerExerciseDevice(customerId: customerId!, exerciseDeviceId: device.exerciseDeviceId, favourite: false);
newDevice.change = ModelChange.add; newDevice.change = ModelChange.add;
CustomerExerciseDevice saved = await CustomerExerciseDeviceApi().addDevice(newDevice); CustomerExerciseDevice saved = await CustomerExerciseDeviceApi().addDevice(newDevice);
this._devices.add(saved); _devices.add(saved);
Cache().setCustomerDevices(_devices); Cache().setCustomerDevices(_devices);
} }
} }
@ -45,16 +45,16 @@ class CustomerExerciseDeviceRepository {
Future<void> removeDevice(ExerciseDevice device) async { Future<void> removeDevice(ExerciseDevice device) async {
CustomerExerciseDevice? found; CustomerExerciseDevice? found;
this._devices.forEach((element) { for (var element in _devices) {
if (element.exerciseDeviceId == device.exerciseDeviceId) { if (element.exerciseDeviceId == device.exerciseDeviceId) {
found = element; found = element;
} }
}); }
if (found != null) { if (found != null) {
this._devices.remove(found); _devices.remove(found);
//if (found.change != ModelChange.add) { //if (found.change != ModelChange.add) {
await CustomerExerciseDeviceApi().removeDevice(found!.customerExerciseDeviceId!); await CustomerExerciseDeviceApi().removeDevice(found.customerExerciseDeviceId!);
//} //}
Cache().setCustomerDevices(_devices); Cache().setCustomerDevices(_devices);
} }
@ -63,11 +63,11 @@ class CustomerExerciseDeviceRepository {
bool hasDevice(int exerciseDeviceId) { bool hasDevice(int exerciseDeviceId) {
bool found = false; bool found = false;
this._devices.forEach((element) { for (var element in _devices) {
if (element.exerciseDeviceId == exerciseDeviceId) { if (element.exerciseDeviceId == exerciseDeviceId) {
found = true; found = true;
} }
}); }
return found; return found;
} }

View File

@ -50,54 +50,54 @@ class CustomerRepository with Logging {
String? getGenderByName(String name) { String? getGenderByName(String name) {
String? dbValue; String? dbValue;
genders.forEach((element) { for (var element in genders) {
if (element.name == name) { if (element.name == name) {
dbValue = element.dbValue; dbValue = element.dbValue;
} }
}); }
return dbValue; return dbValue;
} }
String? getGenderByDBValue(String dbValue) { String? getGenderByDBValue(String dbValue) {
String? name; String? name;
genders.forEach((element) { for (var element in genders) {
if (element.dbValue == dbValue) { if (element.dbValue == dbValue) {
name = element.name; name = element.name;
} }
}); }
return name; return name;
} }
String? get name { String? get name {
return this.customer != null && this.customer!.name != null ? this.customer!.name : ""; return customer != null && customer!.name != null ? customer!.name : "";
} }
String? get firstName { String? get firstName {
return this.customer != null && this.customer!.firstname != null ? this.customer!.firstname : ""; return customer != null && customer!.firstname != null ? customer!.firstname : "";
} }
String get sex { String get sex {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.sex == "m" ? "Man" : "Woman"; return customer!.sex == "m" ? "Man" : "Woman";
} }
int? get birthYear { int? get birthYear {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.birthYear; return customer!.birthYear;
} }
String? get goal { String? get goal {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.goal; return customer!.goal;
} }
String? getSportString() { String? getSportString() {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
String? sport; String? sport;
List<Sport>? sports = Cache().getSports(); List<Sport>? sports = Cache().getSports();
if (sports != null) { if (sports != null) {
for (Sport sportObject in sports) { for (Sport sportObject in sports) {
if (sportObject.sportId == this.customer!.sportId) { if (sportObject.sportId == customer!.sportId) {
sport = sportObject.name; sport = sportObject.name;
break; break;
} }
@ -107,12 +107,12 @@ class CustomerRepository with Logging {
} }
Sport? getSport() { Sport? getSport() {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
Sport? sport; Sport? sport;
List<Sport>? sports = Cache().getSports(); List<Sport>? sports = Cache().getSports();
if (sports != null) { if (sports != null) {
for (Sport sportObject in sports) { for (Sport sportObject in sports) {
if (sportObject.sportId == this.customer!.sportId) { if (sportObject.sportId == customer!.sportId) {
sport = sportObject; sport = sportObject;
break; break;
} }
@ -122,69 +122,69 @@ class CustomerRepository with Logging {
} }
String? get fitnessLevel { String? get fitnessLevel {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.fitnessLevel; return customer!.fitnessLevel;
} }
String? get bodyType { String? get bodyType {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.bodyType; return customer!.bodyType;
} }
setName(String name) { setName(String name) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.name = name; customer!.name = name;
} }
setFirstName(String firstName) { setFirstName(String firstName) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.firstname = firstName; customer!.firstname = firstName;
} }
setPassword(String password) { setPassword(String password) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.password = password; customer!.password = password;
} }
setEmail(String email) { setEmail(String email) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.email = email; customer!.email = email;
} }
setSex(String sex) { setSex(String sex) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.sex = sex; customer!.sex = sex;
} }
setWeight(double weight) { setWeight(double weight) {
final propertyName = "Weight"; const propertyName = "Weight";
this.setCustomerProperty(propertyName, weight); setCustomerProperty(propertyName, weight);
} }
setHeight(int height) { setHeight(int height) {
final propertyName = "Height"; const propertyName = "Height";
this.setCustomerProperty(propertyName, height.toDouble()); setCustomerProperty(propertyName, height.toDouble());
} }
setCustomerProperty(String propertyName, double value, {id = 0}) { setCustomerProperty(String propertyName, double value, {id = 0}) {
if (this.customer == null) { if (customer == null) {
throw Exception("Initialize the customer object"); throw Exception("Initialize the customer object");
} }
if (this.customer!.properties[propertyName] == null) { if (customer!.properties[propertyName] == null) {
this.customer!.properties[propertyName] = CustomerProperty( customer!.properties[propertyName] = CustomerProperty(
propertyId: propertyRepository.getPropertyByName("Height")!.propertyId, propertyId: propertyRepository.getPropertyByName("Height")!.propertyId,
customerId: this.customer!.customerId == null ? 0 : this.customer!.customerId!, customerId: customer!.customerId == null ? 0 : customer!.customerId!,
propertyValue: value, propertyValue: value,
dateAdd: DateTime.now()); dateAdd: DateTime.now());
} else { } else {
this.customer!.properties[propertyName]!.propertyValue = value; customer!.properties[propertyName]!.propertyValue = value;
} }
this.customer!.properties[propertyName]!.dateAdd = DateTime.now(); customer!.properties[propertyName]!.dateAdd = DateTime.now();
this.customer!.properties[propertyName]!.newData = true; customer!.properties[propertyName]!.newData = true;
if (id > 0) { if (id > 0) {
this.customer!.properties[propertyName]!.customerPropertyId = id; customer!.properties[propertyName]!.customerPropertyId = id;
} }
Cache().addCustomerProperty(this.customer!.properties[propertyName]!); Cache().addCustomerProperty(customer!.properties[propertyName]!);
} }
double getWeight() { double getWeight() {
@ -196,40 +196,40 @@ class CustomerRepository with Logging {
} }
double getCustomerPropertyValue(String propertyName) { double getCustomerPropertyValue(String propertyName) {
if (this.customer == null || this.customer!.properties[propertyName] == null) { if (customer == null || customer!.properties[propertyName] == null) {
return 0.0; return 0.0;
} else { } else {
return this.customer!.properties[propertyName]!.propertyValue; return customer!.properties[propertyName]!.propertyValue;
} }
} }
CustomerProperty? getCustomerProperty(String propertyName) { CustomerProperty? getCustomerProperty(String propertyName) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!.properties[propertyName]; return customer!.properties[propertyName];
} }
setBirthYear(int birthYear) { setBirthYear(int birthYear) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.birthYear = birthYear; customer!.birthYear = birthYear;
} }
setFitnessLevel(String level) { setFitnessLevel(String level) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.fitnessLevel = level; customer!.fitnessLevel = level;
} }
setGoal(String goal) { setGoal(String goal) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.goal = goal; customer!.goal = goal;
} }
setSportString(String selectedSport) { setSportString(String selectedSport) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
List<Sport>? sports = Cache().getSports(); List<Sport>? sports = Cache().getSports();
if (sports != null) { if (sports != null) {
for (Sport sportObject in sports) { for (Sport sportObject in sports) {
if (sportObject.name == selectedSport) { if (sportObject.name == selectedSport) {
this.customer!.sportId = sportObject.sportId; customer!.sportId = sportObject.sportId;
break; break;
} }
} }
@ -237,40 +237,36 @@ class CustomerRepository with Logging {
} }
setBodyType(String bodyType) { setBodyType(String bodyType) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
this.customer!.bodyType = bodyType; customer!.bodyType = bodyType;
} }
createNew() { createNew() {
this.customer = Customer(); customer = Customer();
} }
Customer getCustomer() { Customer getCustomer() {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
return this.customer!; return customer!;
} }
void setCustomer(Customer customer) { void setCustomer(Customer customer) {
this.customer = customer; customer = customer;
} }
Future<void> addCustomer() async { Future<void> addCustomer() async {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
final Customer modelCustomer = customer!; final Customer modelCustomer = customer!;
await CustomerApi().addCustomer(modelCustomer); await CustomerApi().addCustomer(modelCustomer);
} }
Future<void> saveCustomer() async { Future<void> saveCustomer() async {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
final Customer modelCustomer = customer!; final Customer modelCustomer = customer!;
if (modelCustomer.sex == null) { modelCustomer.sex ??= "m";
modelCustomer.sex = "m"; modelCustomer.fitnessLevel ??= "beginner";
}
if (modelCustomer.fitnessLevel == null) {
modelCustomer.fitnessLevel = "beginner";
}
await CustomerApi().saveCustomer(modelCustomer); await CustomerApi().saveCustomer(modelCustomer);
await this.saveProperties(modelCustomer.properties); await saveProperties(modelCustomer.properties);
} }
Future<void> saveProperties(LinkedHashMap<String, CustomerProperty> properties) async { Future<void> saveProperties(LinkedHashMap<String, CustomerProperty> properties) async {
@ -283,8 +279,8 @@ class CustomerRepository with Logging {
} }
Future<void> savePropertyByName(String name) async { Future<void> savePropertyByName(String name) async {
await Future.forEach(this._properties!, (element) async { await Future.forEach(_properties!, (element) async {
final CustomerProperty customerProperty = element as CustomerProperty; final CustomerProperty customerProperty = element;
final Property? property = propertyRepository.getPropertyByName(name); final Property? property = propertyRepository.getPropertyByName(name);
if (property != null) { if (property != null) {
if (property.propertyId == customerProperty.propertyId) { if (property.propertyId == customerProperty.propertyId) {
@ -295,26 +291,26 @@ class CustomerRepository with Logging {
} }
Future<Customer?> getTraineeAsCustomer() async { Future<Customer?> getTraineeAsCustomer() async {
this._trainee = await CustomerApi().getTrainee(Cache().userLoggedIn!.customerId!); _trainee = await CustomerApi().getTrainee(Cache().userLoggedIn!.customerId!);
return _trainee; return _trainee;
} }
Future<List<Customer?>?> getTrainees() async { Future<List<Customer?>?> getTrainees() async {
int trainerId = Cache().userLoggedIn!.customerId!; int trainerId = Cache().userLoggedIn!.customerId!;
final results = await CustomerApi().getTrainees(trainerId); final results = await CustomerApi().getTrainees(trainerId);
this._trainees = results; _trainees = results;
return results; return results;
} }
Future<List<CustomerProperty>> getAllCustomerProperties() async { Future<List<CustomerProperty>> getAllCustomerProperties() async {
int customerId = Cache().userLoggedIn!.customerId!; int customerId = Cache().userLoggedIn!.customerId!;
final results = await CustomerApi().getAllProperties(customerId); final results = await CustomerApi().getAllProperties(customerId);
this._properties = results; _properties = results;
return results; return results;
} }
List<CustomerProperty>? getAllProperties() { List<CustomerProperty>? getAllProperties() {
return this._properties; return _properties;
} }
List<Customer>? getTraineesList() { List<Customer>? getTraineesList() {
@ -325,11 +321,11 @@ class CustomerRepository with Logging {
if (_trainees == null) { if (_trainees == null) {
return; return;
} }
_trainees!.forEach((element) { for (var element in _trainees!) {
if (traineeId == element.customerId) { if (traineeId == element.customerId) {
this._trainee = element; _trainee = element;
}
} }
});
} }
void emptyTrainees() { void emptyTrainees() {
@ -338,18 +334,18 @@ class CustomerRepository with Logging {
} }
Customer? getTrainee() { Customer? getTrainee() {
return this._trainee; return _trainee;
} }
Customer? getTraineeById(int customerId) { Customer? getTraineeById(int customerId) {
if (_trainees == null) { if (_trainees == null) {
return null; return null;
} }
_trainees!.forEach((element) { for (var element in _trainees!) {
if (customerId == element.customerId) { if (customerId == element.customerId) {
this._trainee = element; _trainee = element;
}
} }
});
return _trainee; return _trainee;
} }
@ -364,13 +360,13 @@ class CustomerRepository with Logging {
} }
void setMediaDimensions(double width, double height) { void setMediaDimensions(double width, double height) {
this.mediaHeight = height; mediaHeight = height;
this.mediaWidth = width; mediaWidth = width;
this.addSizes(this.sex); addSizes(sex);
} }
void addSizes(String sex) { void addSizes(String sex) {
if (this.customer == null) throw Exception("Initialize the customer object"); if (customer == null) throw Exception("Initialize the customer object");
List<Property>? properties = Cache().getProperties(); List<Property>? properties = Cache().getProperties();
if (properties == null) { if (properties == null) {
return; return;
@ -378,139 +374,139 @@ class CustomerRepository with Logging {
final double distortionWidth = mediaWidth / baseWidth; final double distortionWidth = mediaWidth / baseWidth;
final double distortionHeight = mediaHeight / baseHeight; final double distortionHeight = mediaHeight / baseHeight;
if (isMan) { if (isMan) {
properties.forEach((element) { for (var element in properties) {
if (element.propertyName == "Shoulder") { if (element.propertyName == "Shoulder") {
element.top = (122 * distortionHeight).toInt(); element.top = (122 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt(); element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Shoulder"); element.value = customer!.getProperty("Shoulder");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Neck") { } else if (element.propertyName == "Neck") {
element.top = (68 * distortionHeight).toInt(); element.top = (68 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt(); element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Neck"); element.value = customer!.getProperty("Neck");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Biceps") { } else if (element.propertyName == "Biceps") {
element.top = (178 * distortionHeight).toInt(); element.top = (178 * distortionHeight).toInt();
element.left = (208 * distortionWidth).toInt(); element.left = (208 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Biceps"); element.value = customer!.getProperty("Biceps");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Chest") { } else if (element.propertyName == "Chest") {
element.top = (154 * distortionHeight).toInt(); element.top = (154 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt(); element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Chest"); element.value = customer!.getProperty("Chest");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Belly") { } else if (element.propertyName == "Belly") {
element.top = (244 * distortionHeight).toInt(); element.top = (244 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt(); element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Belly"); element.value = customer!.getProperty("Belly");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Hip") { } else if (element.propertyName == "Hip") {
element.top = (308 * distortionHeight).toInt(); element.top = (308 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt(); element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Hip"); element.value = customer!.getProperty("Hip");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Thigh Top") { } else if (element.propertyName == "Thigh Top") {
element.top = (332 * distortionHeight).toInt(); element.top = (332 * distortionHeight).toInt();
element.left = (165 * distortionWidth).toInt(); element.left = (165 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Top"); element.value = customer!.getProperty("Thigh Top");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Thigh Middle") { } else if (element.propertyName == "Thigh Middle") {
element.top = (382 * distortionHeight).toInt(); element.top = (382 * distortionHeight).toInt();
element.left = (100 * distortionWidth).toInt(); element.left = (100 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Middle"); element.value = customer!.getProperty("Thigh Middle");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Knee") { } else if (element.propertyName == "Knee") {
element.top = (464 * distortionHeight).toInt(); element.top = (464 * distortionHeight).toInt();
element.left = (97 * distortionWidth).toInt(); element.left = (97 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Knee"); element.value = customer!.getProperty("Knee");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Calf") { } else if (element.propertyName == "Calf") {
element.top = (520 * distortionHeight).toInt(); element.top = (520 * distortionHeight).toInt();
element.left = (97 * distortionWidth).toInt(); element.left = (97 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Calf"); element.value = customer!.getProperty("Calf");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Ankle") { } else if (element.propertyName == "Ankle") {
element.top = (620 * distortionHeight).toInt(); element.top = (620 * distortionHeight).toInt();
element.left = (150 * distortionWidth).toInt(); element.left = (150 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Ankle"); element.value = customer!.getProperty("Ankle");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Weight") { } else if (element.propertyName == "Weight") {
element.top = (402 * distortionHeight).toInt(); element.top = (402 * distortionHeight).toInt();
element.left = (240 * distortionWidth).toInt(); element.left = (240 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Weight"); element.value = customer!.getProperty("Weight");
manSizes.add(element); manSizes.add(element);
} }
}); }
} else { } else {
properties.forEach((element) { for (var element in properties) {
if (element.propertyName == "Shoulder") { if (element.propertyName == "Shoulder") {
element.top = (122 * distortionHeight).toInt(); element.top = (122 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt(); element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Shoulder"); element.value = customer!.getProperty("Shoulder");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Neck") { } else if (element.propertyName == "Neck") {
element.top = (78 * distortionHeight).toInt(); element.top = (78 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt(); element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Neck"); element.value = customer!.getProperty("Neck");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Biceps") { } else if (element.propertyName == "Biceps") {
element.top = (178 * distortionHeight).toInt(); element.top = (178 * distortionHeight).toInt();
element.left = (212 * distortionWidth).toInt(); element.left = (212 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Biceps"); element.value = customer!.getProperty("Biceps");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Chest") { } else if (element.propertyName == "Chest") {
element.top = (154 * distortionHeight).toInt(); element.top = (154 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt(); element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Chest"); element.value = customer!.getProperty("Chest");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Belly") { } else if (element.propertyName == "Belly") {
element.top = (230 * distortionHeight).toInt(); element.top = (230 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt(); element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Belly"); element.value = customer!.getProperty("Belly");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Hip") { } else if (element.propertyName == "Hip") {
element.top = (294 * distortionHeight).toInt(); element.top = (294 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt(); element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Hip"); element.value = customer!.getProperty("Hip");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Thigh Top") { } else if (element.propertyName == "Thigh Top") {
element.top = (335 * distortionHeight).toInt(); element.top = (335 * distortionHeight).toInt();
element.left = (185 * distortionWidth).toInt(); element.left = (185 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Top"); element.value = customer!.getProperty("Thigh Top");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Thigh Middle") { } else if (element.propertyName == "Thigh Middle") {
element.top = (377 * distortionHeight).toInt(); element.top = (377 * distortionHeight).toInt();
element.left = (125 * distortionWidth).toInt(); element.left = (125 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Middle"); element.value = customer!.getProperty("Thigh Middle");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Knee") { } else if (element.propertyName == "Knee") {
element.top = (468 * distortionHeight).toInt(); element.top = (468 * distortionHeight).toInt();
element.left = (129 * distortionWidth).toInt(); element.left = (129 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Knee"); element.value = customer!.getProperty("Knee");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Calf") { } else if (element.propertyName == "Calf") {
element.top = (525 * distortionHeight).toInt(); element.top = (525 * distortionHeight).toInt();
element.left = (129 * distortionWidth).toInt(); element.left = (129 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Calf"); element.value = customer!.getProperty("Calf");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Ankle") { } else if (element.propertyName == "Ankle") {
element.top = (620 * distortionHeight).toInt(); element.top = (620 * distortionHeight).toInt();
element.left = (162 * distortionWidth).toInt(); element.left = (162 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Ankle"); element.value = customer!.getProperty("Ankle");
manSizes.add(element); manSizes.add(element);
} else if (element.propertyName == "Weight") { } else if (element.propertyName == "Weight") {
element.top = (402 * distortionHeight).toInt(); element.top = (402 * distortionHeight).toInt();
element.left = (240 * distortionWidth).toInt(); element.left = (240 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Weight"); element.value = customer!.getProperty("Weight");
manSizes.add(element); manSizes.add(element);
} }
}); }
} }
} }
int? getWeightCoordinate(isMan, {isTop = false, isLeft = false}) { int? getWeightCoordinate(isMan, {isTop = false, isLeft = false}) {
int? value = 0; int? value = 0;
this.manSizes.forEach((element) { for (var element in manSizes) {
if (element.propertyName == SizesEnum.Weight.toStr()) { if (element.propertyName == SizesEnum.Weight.toStr()) {
if (isTop == true) { if (isTop == true) {
value = element.top; value = element.top;
@ -518,40 +514,40 @@ class CustomerRepository with Logging {
value = element.left; value = element.left;
} }
} }
}); }
return value; return value;
} }
Property? getPropertyByName(String propertyName) { Property? getPropertyByName(String propertyName) {
Property? property; Property? property;
List<Property> sizes; List<Property> sizes;
if (this.sex == "m") { if (sex == "m") {
sizes = this.manSizes; sizes = manSizes;
} else { } else {
sizes = this.womanSizes; sizes = womanSizes;
} }
sizes.forEach((element) { for (var element in sizes) {
if (element.propertyName == propertyName) { if (element.propertyName == propertyName) {
property = element; property = element;
} }
}); }
return property; return property;
} }
void updateSizes(String propertyName, double value) { void updateSizes(String propertyName, double value) {
List<Property> sizes; List<Property> sizes;
if (this.sex == "m") { if (sex == "m") {
sizes = this.manSizes; sizes = manSizes;
} else { } else {
sizes = this.womanSizes; sizes = womanSizes;
} }
sizes.forEach((element) { for (var element in sizes) {
if (element.propertyName == propertyName) { if (element.propertyName == propertyName) {
element.value = value; element.value = value;
} }
}); }
} }
List<CustomerProperty> getAllCustomerPropertyByName(String propertyName) { List<CustomerProperty> getAllCustomerPropertyByName(String propertyName) {
@ -563,11 +559,11 @@ class CustomerRepository with Logging {
return allProperties; return allProperties;
} }
Cache().getCustomerPropertyAll()!.forEach((element) { for (var element in Cache().getCustomerPropertyAll()!) {
if (element.propertyId == property.propertyId) { if (element.propertyId == property.propertyId) {
allProperties.add(element); allProperties.add(element);
} }
}); }
return allProperties; return allProperties;
} }
} }

View File

@ -7,10 +7,10 @@ import 'package:workouttest_util/model/exercise.dart';
import 'package:workouttest_util/model/exercise_type.dart'; import 'package:workouttest_util/model/exercise_type.dart';
import 'package:workouttest_util/model/workout_menu_tree.dart'; import 'package:workouttest_util/model/workout_menu_tree.dart';
import 'package:workouttest_util/service/exercise_service.dart'; import 'package:workouttest_util/service/exercise_service.dart';
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:workouttest_util/util/logging.dart';
class ExerciseRepository { class ExerciseRepository with Logging {
Exercise? exercise; Exercise? exercise;
Customer? customer; Customer? customer;
ExerciseType? exerciseType; ExerciseType? exerciseType;
@ -30,69 +30,69 @@ class ExerciseRepository {
DateTime? end; DateTime? end;
ExerciseRepository() { ExerciseRepository() {
this.createNew(); createNew();
} }
createNew() { createNew() {
this.exercise = Exercise(); exercise = Exercise();
exercise!.dateAdd = DateTime.now(); exercise!.dateAdd = DateTime.now();
} }
setQuantity(double quantity) { setQuantity(double quantity) {
if (this.exercise == null) { if (exercise == null) {
this.createNew(); createNew();
} }
this.exercise!.quantity = quantity; exercise!.quantity = quantity;
} }
setUnitQuantity(double unitQuantity) { setUnitQuantity(double unitQuantity) {
if (this.exercise == null) { if (exercise == null) {
this.createNew(); createNew();
} }
this.exercise!.unitQuantity = unitQuantity; exercise!.unitQuantity = unitQuantity;
} }
setUnit(String unit) { setUnit(String unit) {
if (this.exercise == null) { if (exercise == null) {
this.createNew(); createNew();
} }
this.exercise!.unit = unit; exercise!.unit = unit;
} }
setDatetimeExercise(DateTime datetimeExercise) { setDatetimeExercise(DateTime datetimeExercise) {
if (this.exercise == null) { if (exercise == null) {
this.createNew(); createNew();
} }
this.exercise!.dateAdd = datetimeExercise; exercise!.dateAdd = datetimeExercise;
} }
double? get unitQuantity => this.exercise!.unitQuantity; double? get unitQuantity => exercise!.unitQuantity;
double? get quantity => this.exercise!.quantity; double? get quantity => exercise!.quantity;
Exercise? getExercise() => this.exercise; Exercise? getExercise() => exercise;
Future<Exercise> addExercise() async { Future<Exercise> addExercise() async {
if (this.customer == null) { if (customer == null) {
throw Exception("Please log in"); throw Exception("Please log in");
} }
final Exercise modelExercise = this.exercise!; final Exercise modelExercise = exercise!;
modelExercise.customerId = this.customer!.customerId; modelExercise.customerId = customer!.customerId;
modelExercise.exerciseTypeId = this.exerciseType!.exerciseTypeId; modelExercise.exerciseTypeId = exerciseType!.exerciseTypeId;
if (exerciseType!.unitQuantity != "1") { if (exerciseType!.unitQuantity != "1") {
modelExercise.unitQuantity = null; modelExercise.unitQuantity = null;
} }
Exercise copy = modelExercise.copy(); Exercise copy = modelExercise.copy();
this.actualExerciseList!.add(copy); actualExerciseList!.add(copy);
//final int index = this.actualExerciseList.length - 1; //final int index = actualExerciseList.length - 1;
//print("$index. actual exercise " + this.actualExerciseList[index].toJson().toString()); //print("$index. actual exercise " + actualExerciseList[index].toJson().toString());
Exercise savedExercise = await ExerciseApi().addExercise(modelExercise); Exercise savedExercise = await ExerciseApi().addExercise(modelExercise);
//this.actualExerciseList[index].exerciseId = savedExercise.exerciseId; //actualExerciseList[index].exerciseId = savedExercise.exerciseId;
if (customer!.customerId == Cache().userLoggedIn!.customerId) { if (customer!.customerId == Cache().userLoggedIn!.customerId) {
Cache().addExercise(savedExercise); Cache().addExercise(savedExercise);
} else if (Cache().getTrainee() != null && customer!.customerId == Cache().getTrainee()!.customerId) { } else if (Cache().getTrainee() != null && customer!.customerId == Cache().getTrainee()!.customerId) {
@ -103,41 +103,41 @@ class ExerciseRepository {
} }
void addExerciseNoRegistration() { void addExerciseNoRegistration() {
final Exercise modelExercise = this.exercise!; final Exercise modelExercise = exercise!;
modelExercise.exerciseTypeId = this.exerciseType!.exerciseTypeId; modelExercise.exerciseTypeId = exerciseType!.exerciseTypeId;
if (exerciseType!.unitQuantity != "1") { if (exerciseType!.unitQuantity != "1") {
modelExercise.unitQuantity = null; modelExercise.unitQuantity = null;
} }
Exercise copy = modelExercise.copy(); Exercise copy = modelExercise.copy();
this.actualExerciseList!.add(copy); actualExerciseList!.add(copy);
this.exerciseList = []; exerciseList = [];
this.exerciseList!.add(copy); exerciseList!.add(copy);
this.noRegistration = true; noRegistration = true;
} }
void initExercise() { void initExercise() {
this.createNew(); createNew();
this.exerciseType = exerciseType; exerciseType = exerciseType;
this.setUnit(exerciseType!.unit); setUnit(exerciseType!.unit);
exercise!.exerciseTypeId = this.exerciseType!.exerciseTypeId; exercise!.exerciseTypeId = exerciseType!.exerciseTypeId;
this.setQuantity(12); setQuantity(12);
this.setUnitQuantity(30); setUnitQuantity(30);
this.exercise!.exercisePlanDetailId = 0; exercise!.exercisePlanDetailId = 0;
exercise!.exerciseId = 0; exercise!.exerciseId = 0;
this.start = DateTime.now(); start = DateTime.now();
} }
Future<void> deleteExercise(Exercise exercise) async { Future<void> deleteExercise(Exercise exercise) async {
await ExerciseApi().deleteExercise(exercise); await ExerciseApi().deleteExercise(exercise);
} }
setCustomer(Customer customer) => this.customer = customer; setCustomer(Customer customer) => customer = customer;
setExerciseType(ExerciseType exerciseType) => this.exerciseType = exerciseType; setExerciseType(ExerciseType exerciseType) => exerciseType = exerciseType;
Future<List<Exercise>> getExercisesByCustomer(int customerId) async { Future<List<Exercise>> getExercisesByCustomer(int customerId) async {
final results = await ExerciseApi().getExercisesByCustomer(customerId); final results = await ExerciseApi().getExercisesByCustomer(customerId);
this.exerciseList = results; exerciseList = results;
if (Cache().userLoggedIn != null) { if (Cache().userLoggedIn != null) {
if (customerId == Cache().userLoggedIn!.customerId) { if (customerId == Cache().userLoggedIn!.customerId) {
Cache().setExercises(exerciseList!); Cache().setExercises(exerciseList!);
@ -145,23 +145,21 @@ class ExerciseRepository {
Cache().setExercisesTrainee(exerciseList!); Cache().setExercisesTrainee(exerciseList!);
} }
} }
return this.exerciseList!; return exerciseList!;
} }
List<Exercise>? getExerciseList() { List<Exercise>? getExerciseList() {
this.exerciseList = Cache().getExercises(); exerciseList = Cache().getExercises();
return this.exerciseList; return exerciseList;
} }
List<Exercise>? getExerciseListTrainee() { List<Exercise>? getExerciseListTrainee() {
this.exerciseList = Cache().getExercisesTrainee(); exerciseList = Cache().getExercisesTrainee();
return this.exerciseList; return exerciseList;
} }
String? nextMissingBaseExercise(SplayTreeMap sortedTree) { String? nextMissingBaseExercise(SplayTreeMap sortedTree) {
if (exerciseList == null) { exerciseList ??= Cache().getExercises();
exerciseList = Cache().getExercises();
}
if (exerciseList == null) { if (exerciseList == null) {
return null; return null;
@ -175,22 +173,20 @@ class ExerciseRepository {
String treeName = key as String; String treeName = key as String;
treeName = treeName.substring(3); treeName = treeName.substring(3);
foundTreeName = null; foundTreeName = null;
listByMuscle.forEach((exercise) { for (var exercise in listByMuscle) {
if (missingTreeName == null) { missingTreeName ??= treeName;
missingTreeName = treeName;
}
if (exercise.base) { if (exercise.base) {
if (exerciseList != null) { if (exerciseList != null) {
exerciseList!.forEach((element) { for (var element in exerciseList!) {
if (element.exerciseTypeId == exercise.exerciseTypeId) { if (element.exerciseTypeId == exercise.exerciseTypeId) {
foundTreeName = treeName; foundTreeName = treeName;
//print("Found " + foundTreeName + " Missing actual: " + missingTreeName); //print("Found " + foundTreeName + " Missing actual: " + missingTreeName);
isBreak = true; isBreak = true;
} }
});
} }
} }
}); }
}
if (foundTreeName == null && !isBreak) { if (foundTreeName == null && !isBreak) {
missingTreeName = treeName; missingTreeName = treeName;
isBreak = true; isBreak = true;
@ -218,15 +214,13 @@ class ExerciseRepository {
} }
}); });
if (exerciseList == null) { exerciseList ??= Cache().getExercises();
exerciseList = Cache().getExercises();
}
if (exerciseList == null) { if (exerciseList == null) {
return; return;
} }
exerciseList!.forEach((element) { for (var element in exerciseList!) {
Exercise exercise = element; Exercise exercise = element;
if (!checkedExerciseTypeId.contains(exercise.exerciseTypeId)) { if (!checkedExerciseTypeId.contains(exercise.exerciseTypeId)) {
checkedExerciseTypeId.add(exercise.exerciseTypeId!); checkedExerciseTypeId.add(exercise.exerciseTypeId!);
@ -242,7 +236,7 @@ class ExerciseRepository {
} }
}); });
} }
}); }
//print ("checkedExerciseTypeid: " + checkedExerciseTypeId.toString()); //print ("checkedExerciseTypeid: " + checkedExerciseTypeId.toString());
//print ("baseTreeItem: " + baseTreeItem.toString()); //print ("baseTreeItem: " + baseTreeItem.toString());
@ -252,19 +246,19 @@ class ExerciseRepository {
} }
void getLastExercise() { void getLastExercise() {
List<Exercise>? exercises = this.getExerciseList(); List<Exercise>? exercises = getExerciseList();
Exercise? lastExercise = exercises == null ? null : exercises[0]; Exercise? lastExercise = exercises == null ? null : exercises[0];
if (exercises != null) { if (exercises != null) {
exercises.forEach((element) { for (var element in exercises) {
Exercise actualExercise = element; Exercise actualExercise = element;
if (actualExercise.dateAdd!.compareTo(lastExercise!.dateAdd!) > 0) { if (actualExercise.dateAdd!.compareTo(lastExercise!.dateAdd!) > 0) {
lastExercise = actualExercise; lastExercise = actualExercise;
} }
});
} }
this.exercise = lastExercise; }
this.customer = Cache().userLoggedIn!; exercise = lastExercise;
this.exerciseType = getExerciseTypeById(exercise!.exerciseTypeId!); customer = Cache().userLoggedIn!;
exerciseType = getExerciseTypeById(exercise!.exerciseTypeId!);
return; return;
} }
@ -272,12 +266,12 @@ class ExerciseRepository {
ExerciseType? actualExerciseType; ExerciseType? actualExerciseType;
List<ExerciseType>? exercises = Cache().getExerciseTypes(); List<ExerciseType>? exercises = Cache().getExerciseTypes();
if (exercises != null) { if (exercises != null) {
exercises.forEach((element) { for (var element in exercises) {
ExerciseType exerciseType = element; ExerciseType exerciseType = element;
if (exerciseType.exerciseTypeId == exerciseTypeId) { if (exerciseType.exerciseTypeId == exerciseTypeId) {
actualExerciseType = exerciseType; actualExerciseType = exerciseType;
} }
}); }
} }
if (actualExerciseType == null) { if (actualExerciseType == null) {
throw Exception("Data error, no ExerciseType for exerciseTypeId $exerciseTypeId"); throw Exception("Data error, no ExerciseType for exerciseTypeId $exerciseTypeId");
@ -286,16 +280,16 @@ class ExerciseRepository {
} }
void getSameExercise(int exerciseTypeId, String day) { void getSameExercise(int exerciseTypeId, String day) {
if (!this.noRegistration) { if (!noRegistration) {
this.actualExerciseList = []; actualExerciseList = [];
} }
if (exerciseList != null) { if (exerciseList != null) {
int index = 0; int index = 0;
for (int i = 0; i < this.exerciseList!.length; i++) { for (int i = 0; i < exerciseList!.length; i++) {
Exercise exercise = exerciseList![i]; Exercise exercise = exerciseList![i];
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exerciseTypeId == exercise.exerciseTypeId && exerciseDate == day && index < 4) { if (exerciseTypeId == exercise.exerciseTypeId && exerciseDate == day && index < 4) {
this.actualExerciseList!.add(exercise); actualExerciseList!.add(exercise);
index++; index++;
} }
} }
@ -318,12 +312,12 @@ class ExerciseRepository {
double getBest1RM(Exercise exercise) { double getBest1RM(Exercise exercise) {
double result = 0; double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) { if (exerciseList == null || exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises(); exerciseList = Cache().getExercises();
} }
final int exerciseTypeId = exercise.exerciseTypeId!; final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = this.calculate1RM(exercise); double toCompare = calculate1RM(exercise);
result = toCompare; result = toCompare;
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(DateTime.now()); final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(DateTime.now());
@ -331,12 +325,12 @@ class ExerciseRepository {
if (exerciseList == null) { if (exerciseList == null) {
return toCompare; return toCompare;
} }
this.exerciseList!.forEach((exercise) { for (var exercise in exerciseList!) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) { if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise); oldExercises.add(exercise);
} }
}); }
if (oldExercises.isNotEmpty) { if (oldExercises.isNotEmpty) {
oldExercises.sort((a, b) { oldExercises.sort((a, b) {
@ -352,7 +346,7 @@ class ExerciseRepository {
return sumA >= sumB ? 1 : -1; return sumA >= sumB ? 1 : -1;
}); });
double withCompare = this.calculate1RM(oldExercises.last); double withCompare = calculate1RM(oldExercises.last);
//result = toCompare >= withCompare ? (1 - toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100; //result = toCompare >= withCompare ? (1 - toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
result = toCompare >= withCompare ? toCompare : withCompare; result = toCompare >= withCompare ? toCompare : withCompare;
@ -362,12 +356,12 @@ class ExerciseRepository {
double getLast1RMPercent(Exercise exercise) { double getLast1RMPercent(Exercise exercise) {
double result = 0; double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) { if (exerciseList == null || exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises(); exerciseList = Cache().getExercises();
} }
final int exerciseTypeId = exercise.exerciseTypeId!; final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = this.calculate1RM(exercise); double toCompare = calculate1RM(exercise);
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
List<Exercise> oldExercises = []; List<Exercise> oldExercises = [];
@ -375,15 +369,15 @@ class ExerciseRepository {
if (exerciseList == null) { if (exerciseList == null) {
return result; return result;
} }
this.exerciseList!.forEach((exercise) { for (var exercise in exerciseList!) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) { if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise); oldExercises.add(exercise);
} }
}); }
if (oldExercises.isNotEmpty) { if (oldExercises.isNotEmpty) {
double withCompare = this.calculate1RM(oldExercises.first); double withCompare = calculate1RM(oldExercises.first);
result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100; result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
} }
return result; return result;
@ -391,8 +385,8 @@ class ExerciseRepository {
double getBestVolume(Exercise exercise) { double getBestVolume(Exercise exercise) {
double result = 0; double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) { if (exerciseList == null || exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises(); exerciseList = Cache().getExercises();
} }
final int exerciseTypeId = exercise.exerciseTypeId!; final int exerciseTypeId = exercise.exerciseTypeId!;
@ -404,12 +398,12 @@ class ExerciseRepository {
if (exerciseList == null) { if (exerciseList == null) {
return toCompare; return toCompare;
} }
this.exerciseList!.forEach((exercise) { for (var exercise in exerciseList!) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) { if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise); oldExercises.add(exercise);
} }
}); }
if (oldExercises.isNotEmpty) { if (oldExercises.isNotEmpty) {
oldExercises.sort((a, b) { oldExercises.sort((a, b) {
@ -437,8 +431,8 @@ class ExerciseRepository {
double getLastExercisePercent(Exercise exercise) { double getLastExercisePercent(Exercise exercise) {
double result = 0; double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) { if (exerciseList == null || exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises(); exerciseList = Cache().getExercises();
} }
final int exerciseTypeId = exercise.exerciseTypeId!; final int exerciseTypeId = exercise.exerciseTypeId!;
@ -449,19 +443,19 @@ class ExerciseRepository {
if (exerciseList == null) { if (exerciseList == null) {
return result; return result;
} }
this.exerciseList!.forEach((exercise) { for (var exercise in exerciseList!) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) { if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise); oldExercises.add(exercise);
} }
}); }
if (oldExercises.isNotEmpty) { if (oldExercises.isNotEmpty) {
double withCompare = double withCompare =
oldExercises.first.unitQuantity != null ? oldExercises.first.quantity! * oldExercises.first.unitQuantity! : oldExercises.first.quantity!; oldExercises.first.unitQuantity != null ? oldExercises.first.quantity! * oldExercises.first.unitQuantity! : oldExercises.first.quantity!;
result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100; result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
print("Last Last: ${oldExercises.first} vs. $exercise - - result: $result"); log("Last Last: ${oldExercises.first} vs. $exercise - - result: $result");
} }
return result; return result;
} }
@ -473,20 +467,20 @@ class ExerciseRepository {
exerciseList!.sort((a, b) { exerciseList!.sort((a, b) {
final String datePartA = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(a.dateAdd!); final String datePartA = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(a.dateAdd!);
String aId = datePartA + "_" + a.exerciseTypeId.toString(); String aId = "${datePartA}_${a.exerciseTypeId}";
final String datePartB = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(b.dateAdd!); final String datePartB = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(b.dateAdd!);
String bId = datePartB + "_" + b.exerciseTypeId.toString(); String bId = "${datePartB}_${b.exerciseTypeId}";
return bId.compareTo(aId); return bId.compareTo(aId);
}); });
this.exerciseLogList = []; exerciseLogList = [];
String summary = ""; String summary = "";
String prevDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exerciseList![0].dateAdd!); String prevDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exerciseList![0].dateAdd!);
int prevExerciseTypeId = exerciseList![0].exerciseTypeId!; int prevExerciseTypeId = exerciseList![0].exerciseTypeId!;
Exercise prevExercise = exerciseList![0]; Exercise prevExercise = exerciseList![0];
int prevCount = 0; int prevCount = 0;
for (int i = 0; i < this.exerciseList!.length; i++) { for (int i = 0; i < exerciseList!.length; i++) {
Exercise exercise = exerciseList![i]; Exercise exercise = exerciseList![i];
int exerciseTypeId = exercise.exerciseTypeId!; int exerciseTypeId = exercise.exerciseTypeId!;
String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
@ -494,7 +488,7 @@ class ExerciseRepository {
if (exerciseTypeId != prevExerciseTypeId || prevDate != exerciseDate) { if (exerciseTypeId != prevExerciseTypeId || prevDate != exerciseDate) {
ExerciseType? exerciseType = Cache().getExerciseTypeById(prevExercise.exerciseTypeId!); ExerciseType? exerciseType = Cache().getExerciseTypeById(prevExercise.exerciseTypeId!);
String unit = exerciseType != null && exerciseType.unitQuantityUnit != null ? exerciseType.unitQuantityUnit! : prevExercise.unit!; String unit = exerciseType != null && exerciseType.unitQuantityUnit != null ? exerciseType.unitQuantityUnit! : prevExercise.unit!;
prevExercise.summary = summary + " " + unit; prevExercise.summary = "$summary $unit";
exerciseLogList!.add(prevExercise); exerciseLogList!.add(prevExercise);
//print("Log add " + exercise.toJson().toString()); //print("Log add " + exercise.toJson().toString());
summary = ""; summary = "";
@ -508,7 +502,7 @@ class ExerciseRepository {
//print("exerciseType " + (exerciseType == null ? "NULL" : exerciseType.name) + " ID " + exercise.exerciseTypeId.toString()); //print("exerciseType " + (exerciseType == null ? "NULL" : exerciseType.name) + " ID " + exercise.exerciseTypeId.toString());
if (exerciseType != null) { if (exerciseType != null) {
if (exerciseType.unitQuantity == "1") { if (exerciseType.unitQuantity == "1") {
summary += "x" + exercise.unitQuantity!.toStringAsFixed(0); summary += "x${exercise.unitQuantity!.toStringAsFixed(0)}";
} }
//print(" --- sum " + exerciseType.name + " $summary"); //print(" --- sum " + exerciseType.name + " $summary");
} }
@ -528,11 +522,11 @@ class ExerciseRepository {
if (allExercise == null) { if (allExercise == null) {
return list; return list;
} }
allExercise.forEach((element) { for (var element in allExercise) {
if (element.exerciseTypeId == exerciseTypeId) { if (element.exerciseTypeId == exerciseTypeId) {
list.add(element); list.add(element);
} }
}); }
return list; return list;
} }
} }

View File

@ -11,15 +11,15 @@ class ExerciseTypeRepository with Logging {
List<ExerciseType> list = []; List<ExerciseType> list = [];
List<ExerciseType>? exerciseTypes = Cache().getExerciseTypes(); List<ExerciseType>? exerciseTypes = Cache().getExerciseTypes();
if (exerciseTypes != null) { if (exerciseTypes != null) {
exerciseTypes.forEach((exerciseType) { for (var exerciseType in exerciseTypes) {
if (exerciseType.alternatives.isNotEmpty) { if (exerciseType.alternatives.isNotEmpty) {
exerciseType.alternatives.forEach((childId) { for (var childId in exerciseType.alternatives) {
if (childId == exerciseTypeId) { if (childId == exerciseTypeId) {
list.add(exerciseType); list.add(exerciseType);
} }
});
} }
}); }
}
} }
return list; return list;
} }

View File

@ -6,25 +6,23 @@ class PropertyRepository {
List<Property>? _properties; List<Property>? _properties;
Future<List<Property>?> getDBProperties() async { Future<List<Property>?> getDBProperties() async {
this._properties = await PropertyApi().getProperties(); _properties = await PropertyApi().getProperties();
return this._properties; return _properties;
} }
List<Property>? getProperties() { List<Property>? getProperties() {
return this._properties; return _properties;
} }
Property? getPropertyByName(String name) { Property? getPropertyByName(String name) {
Property? property; Property? property;
if (_properties == null) { _properties ??= Cache().getProperties();
_properties = Cache().getProperties();
}
if (_properties != null) { if (_properties != null) {
this._properties!.forEach((element) { for (var element in _properties!) {
if (name == element.propertyName) { if (name == element.propertyName) {
property = element; property = element;
} }
}); }
} }
return property; return property;
} }

View File

@ -10,13 +10,13 @@ class TrainingPlanDayRepository {
if (plans == null) { if (plans == null) {
return; return;
} }
plans.forEach((plan) { for (var plan in plans) {
if (plan.details != null) { if (plan.details != null) {
plan.details!.forEach((element) { for (var element in plan.details!) {
element.day = this.getNameById(element.dayId); element.day = getNameById(element.dayId);
}); }
}
} }
});
} }
String? getNameById(int? dayId) { String? getNameById(int? dayId) {

View File

@ -11,8 +11,9 @@ import 'package:workouttest_util/repository/exercise_type_repository.dart';
import 'package:workouttest_util/repository/training_plan_day_repository.dart'; import 'package:workouttest_util/repository/training_plan_day_repository.dart';
import 'package:workouttest_util/util/app_language.dart'; import 'package:workouttest_util/util/app_language.dart';
import 'package:workouttest_util/util/common.dart'; import 'package:workouttest_util/util/common.dart';
import 'package:workouttest_util/util/logging.dart';
class TrainingPlanRepository with Common { class TrainingPlanRepository with Common, Logging {
ExerciseTree? parentTree; ExerciseTree? parentTree;
List<TrainingPlan> getPlansByParent(String parent) { List<TrainingPlan> getPlansByParent(String parent) {
final List<TrainingPlan> resultList = []; final List<TrainingPlan> resultList = [];
@ -44,7 +45,7 @@ class TrainingPlanRepository with Common {
/// 3. create new customer_training_plan /// 3. create new customer_training_plan
CustomerTrainingPlan? activateTrainingPlan(int trainingPlanId) { CustomerTrainingPlan? activateTrainingPlan(int trainingPlanId) {
print(" **** Activate Plan: $trainingPlanId"); log(" **** Activate Plan: $trainingPlanId");
// 1. deactivate // 1. deactivate
if (Cache().getCustomerTrainingPlans() != null) { if (Cache().getCustomerTrainingPlans() != null) {
Cache().getCustomerTrainingPlans()!.forEach((plan) { Cache().getCustomerTrainingPlans()!.forEach((plan) {
@ -61,9 +62,9 @@ class TrainingPlanRepository with Common {
plan.active = true; plan.active = true;
plan.status = "open"; plan.status = "open";
plan.dateAdd = DateTime.now(); plan.dateAdd = DateTime.now();
TrainingPlan? trainingPlan = this.getTrainingPlanById(trainingPlanId); TrainingPlan? trainingPlan = getTrainingPlanById(trainingPlanId);
if (trainingPlan == null || trainingPlan.details == null) { if (trainingPlan == null || trainingPlan.details == null) {
print("trainingPlan null"); log("trainingPlan null");
return null; return null;
} }
plan.name = trainingPlan.nameTranslations[AppLanguage().appLocal.toString()]; plan.name = trainingPlan.nameTranslations[AppLanguage().appLocal.toString()];
@ -88,7 +89,7 @@ class TrainingPlanRepository with Common {
CustomerTrainingPlanDetails? getDetailById(CustomerTrainingPlan? plan, int customerTrainingPlanDetailsId) { CustomerTrainingPlanDetails? getDetailById(CustomerTrainingPlan? plan, int customerTrainingPlanDetailsId) {
CustomerTrainingPlanDetails? foundDetail; CustomerTrainingPlanDetails? foundDetail;
if (plan == null || plan.details.length == 0 || customerTrainingPlanDetailsId == 0) { if (plan == null || plan.details.isEmpty || customerTrainingPlanDetailsId == 0) {
return foundDetail; return foundDetail;
} }
@ -116,7 +117,7 @@ class TrainingPlanRepository with Common {
alternativeDetail.weight = 0; alternativeDetail.weight = 0;
} }
} else if (elem.weight == -2) { } else if (elem.weight == -2) {
final CustomerTrainingPlanDetails calculated = this.isWeightCalculatedByExerciseType(elem.exerciseTypeId, alternativeDetail, plan); final CustomerTrainingPlanDetails calculated = isWeightCalculatedByExerciseType(elem.exerciseTypeId, alternativeDetail, plan);
if (calculated.weight != -1) { if (calculated.weight != -1) {
alternativeDetail.weight = calculated.weight; alternativeDetail.weight = calculated.weight;
} else { } else {
@ -140,7 +141,7 @@ class TrainingPlanRepository with Common {
detail.repeats = elem.repeats; detail.repeats = elem.repeats;
detail.set = elem.set; detail.set = elem.set;
detail.dayId = elem.dayId; detail.dayId = elem.dayId;
TrainingPlanDayRepository trainingPlanDayRepository = TrainingPlanDayRepository(); TrainingPlanDayRepository trainingPlanDayRepository = const TrainingPlanDayRepository();
detail.day = trainingPlanDayRepository.getNameById(elem.dayId); detail.day = trainingPlanDayRepository.getNameById(elem.dayId);
detail.parallel = elem.parallel; detail.parallel = elem.parallel;
detail.restingTime = elem.restingTime; detail.restingTime = elem.restingTime;
@ -153,7 +154,7 @@ class TrainingPlanRepository with Common {
detail.weight = 0; detail.weight = 0;
} }
} else if (elem.weight == -2) { } else if (elem.weight == -2) {
final CustomerTrainingPlanDetails calculated = this.isWeightCalculatedByExerciseType(elem.exerciseTypeId, detail, plan); final CustomerTrainingPlanDetails calculated = isWeightCalculatedByExerciseType(elem.exerciseTypeId, detail, plan);
if (calculated.weight != -1) { if (calculated.weight != -1) {
detail.weight = calculated.weight; detail.weight = calculated.weight;
} else { } else {
@ -244,7 +245,7 @@ class TrainingPlanRepository with Common {
} }
Exercise? lastExercise1RM; Exercise? lastExercise1RM;
DateTime dt = DateTime.now().subtract(Duration(days: 30)); DateTime dt = DateTime.now().subtract(const Duration(days: 30));
List<Exercise> exercises = Cache().getExercises()!; List<Exercise> exercises = Cache().getExercises()!;
exercises.sort((a, b) { exercises.sort((a, b) {
// reverse // reverse
@ -352,7 +353,7 @@ class TrainingPlanRepository with Common {
detail.weight = Common.calculateWeigthByChangedQuantity(detailWithData.weight!, detailWithData.repeats!.toDouble(), originalRepeats.toDouble()); detail.weight = Common.calculateWeigthByChangedQuantity(detailWithData.weight!, detailWithData.repeats!.toDouble(), originalRepeats.toDouble());
detail.weight = Common.roundWeight(detail.weight!); detail.weight = Common.roundWeight(detail.weight!);
print("Recalculated weight: ${detail.weight}"); log("Recalculated weight: ${detail.weight}");
detail.repeats = originalRepeats; detail.repeats = originalRepeats;
return detail; return detail;
} }
@ -379,7 +380,7 @@ class TrainingPlanRepository with Common {
// 2 get recalculated repeats // 2 get recalculated repeats
recalculatedDetail.weight = Common.calculateWeigthByChangedQuantity(detail.weight!, detail.repeats!.toDouble(), originalRepeats.toDouble()); recalculatedDetail.weight = Common.calculateWeigthByChangedQuantity(detail.weight!, detail.repeats!.toDouble(), originalRepeats.toDouble());
recalculatedDetail.weight = Common.roundWeight(recalculatedDetail.weight!); recalculatedDetail.weight = Common.roundWeight(recalculatedDetail.weight!);
print("recalculated repeats for $originalRepeats: ${recalculatedDetail.weight}"); log("recalculated repeats for $originalRepeats: ${recalculatedDetail.weight}");
//recalculatedDetail.repeats = originalRepeats; //recalculatedDetail.repeats = originalRepeats;
return recalculatedDetail; return recalculatedDetail;
@ -435,7 +436,7 @@ class TrainingPlanRepository with Common {
} }
} }
print("Generated plan $trainingPlanId fitness ${Cache().userLoggedIn!.fitnessLevel} - ${FitnessState.beginner}"); log("Generated plan $trainingPlanId fitness ${Cache().userLoggedIn!.fitnessLevel} - ${FitnessState.beginner}");
if (trainingPlanId != null) { if (trainingPlanId != null) {
CustomerTrainingPlan? customerTrainingPlan = activateTrainingPlan(trainingPlanId); CustomerTrainingPlan? customerTrainingPlan = activateTrainingPlan(trainingPlanId);

View File

@ -10,23 +10,23 @@ class UserRepository with Logging {
late User user; late User user;
UserRepository() { UserRepository() {
this.createNewUser(); createNewUser();
} }
setEmail(String email) { setEmail(String email) {
this.user.email = email; user.email = email;
} }
setPassword(String password) { setPassword(String password) {
this.user.password = password; user.password = password;
} }
createNewUser() { createNewUser() {
this.user = User(); user = User();
} }
Future<void> addUser() async { Future<void> addUser() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
String rc = await FirebaseApi().registerEmail(modelUser.email!, modelUser.password!); String rc = await FirebaseApi().registerEmail(modelUser.email!, modelUser.password!);
if (rc == FirebaseApi.SIGN_IN_OK) { if (rc == FirebaseApi.SIGN_IN_OK) {
@ -38,19 +38,19 @@ class UserRepository with Logging {
log(message); log(message);
if (message.contains("CERT_ALREADY_IN_HASH_TABLE")) { if (message.contains("CERT_ALREADY_IN_HASH_TABLE")) {
} else { } else {
throw new Exception(e); throw Exception(e);
} }
} }
} }
Future<void> addUserFB() async { Future<void> addUserFB() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
Map<String, dynamic> userData = await FirebaseApi().registerWithFacebook(); Map<String, dynamic> userData = await FirebaseApi().registerWithFacebook();
modelUser.email = userData['email']; modelUser.email = userData['email'];
if (modelUser.email == null) { if (modelUser.email == null) {
throw new Exception("Facebook signup was not successful. Please try another method"); throw Exception("Facebook signup was not successful. Please try another method");
} }
modelUser.password = Cache().firebaseUid; modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid; modelUser.firebaseUid = Cache().firebaseUid;
@ -66,7 +66,7 @@ class UserRepository with Logging {
log(e.code); log(e.code);
throw Exception("The account exists with different credential"); throw Exception("The account exists with different credential");
} else { } else {
print(e.code); log(e.code);
throw Exception(e); throw Exception(e);
} }
} on WorkoutTestException catch (ex) { } on WorkoutTestException catch (ex) {
@ -75,19 +75,19 @@ class UserRepository with Logging {
throw Exception("The email address has been registered already"); throw Exception("The email address has been registered already");
} }
} on Exception catch (ex) { } on Exception catch (ex) {
log("FB exception: " + ex.toString()); log("FB exception: $ex");
throw Exception("Facebook Sign In failed"); throw Exception("Facebook Sign In failed");
} }
} }
Future<void> addUserGoogle() async { Future<void> addUserGoogle() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
Map<String, dynamic> userData = await FirebaseApi().registerWithGoogle(); Map<String, dynamic> userData = await FirebaseApi().registerWithGoogle();
modelUser.email = userData['email']; modelUser.email = userData['email'];
if (modelUser.email == null) { if (modelUser.email == null) {
throw new Exception("Google signup was not successful. Please try another method"); throw Exception("Google signup was not successful. Please try another method");
} }
modelUser.password = Cache().firebaseUid; modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid; modelUser.firebaseUid = Cache().firebaseUid;
@ -105,19 +105,19 @@ class UserRepository with Logging {
throw Exception("The email address has been registered already"); throw Exception("The email address has been registered already");
} }
} on Exception catch (ex) { } on Exception catch (ex) {
log("Google exception: " + ex.toString()); log("Google exception: $ex");
throw Exception("Google Sign In failed"); throw Exception("Google Sign In failed");
} }
} }
Future<void> addUserApple() async { Future<void> addUserApple() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
Map<String, dynamic> userData = await FirebaseApi().registerWithApple(); Map<String, dynamic> userData = await FirebaseApi().registerWithApple();
modelUser.email = userData['email']; modelUser.email = userData['email'];
if (modelUser.email == null) { if (modelUser.email == null) {
throw new Exception("Apple signup was not successful. Please try another method"); throw Exception("Apple signup was not successful. Please try another method");
} }
modelUser.password = Cache().firebaseUid; modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid; modelUser.firebaseUid = Cache().firebaseUid;
@ -133,13 +133,13 @@ class UserRepository with Logging {
throw Exception("The email address has been registered already"); throw Exception("The email address has been registered already");
} }
} on Exception catch (ex) { } on Exception catch (ex) {
log("Apple exception: " + ex.toString()); log("Apple exception: $ex");
throw Exception(ex); throw Exception(ex);
} }
} }
Future<void> getUserByFB() async { Future<void> getUserByFB() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
Map<String, dynamic> userData = await FirebaseApi().signInWithFacebook(); Map<String, dynamic> userData = await FirebaseApi().signInWithFacebook();
modelUser.email = userData['email']; modelUser.email = userData['email'];
@ -160,49 +160,49 @@ class UserRepository with Logging {
} }
} */ } */
on NotFoundException catch (ex) { on NotFoundException catch (ex) {
log("FB exception: " + ex.toString()); log("FB exception: $ex");
throw Exception("Customer does not exist or the password is wrong"); throw Exception("Customer does not exist or the password is wrong");
} on Exception catch (e) { } on Exception catch (e) {
log(e.toString()); log(e.toString());
throw new Exception(e); throw Exception(e);
} }
} }
Future<void> getUserByGoogle() async { Future<void> getUserByGoogle() async {
final User modelUser = this.user; final User modelUser = user;
try { try {
Map<String, dynamic> userData = await FirebaseApi().signInWithGoogle(); Map<String, dynamic> userData = await FirebaseApi().signInWithGoogle();
if (userData['email'] == null) { if (userData['email'] == null) {
throw new Exception("Google login was not successful"); throw Exception("Google login was not successful");
} }
modelUser.email = userData['email']; modelUser.email = userData['email'];
await CustomerApi().getUserByEmail(modelUser.email!); await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin(); await Cache().afterFirebaseLogin();
} on Exception catch (ex) { } on Exception catch (ex) {
log("Google exception: " + ex.toString()); log("Google exception: $ex");
throw Exception(ex); throw Exception(ex);
} }
} }
Future<void> getUserByApple() async { Future<void> getUserByApple() async {
final User modelUser = this.user; final User modelUser = user;
Map<String, dynamic> userData = await FirebaseApi().signInWithApple(); Map<String, dynamic> userData = await FirebaseApi().signInWithApple();
if (userData['email'] == null) { if (userData['email'] == null) {
throw new Exception("Apple login was not successful"); throw Exception("Apple login was not successful");
} }
modelUser.email = userData['email']; modelUser.email = userData['email'];
try { try {
await CustomerApi().getUserByEmail(modelUser.email!); await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin(); await Cache().afterFirebaseLogin();
} on Exception catch (ex) { } on Exception catch (ex) {
log("Apple exception: " + ex.toString()); log("Apple exception: $ex");
throw Exception("Customer does not exist or the password is wrong"); throw Exception("Customer does not exist or the password is wrong");
} }
} }
Future<void> getUser() async { Future<void> getUser() async {
final User modelUser = this.user; final User modelUser = user;
String rc = await FirebaseApi().signInEmail(modelUser.email, modelUser.password); String rc = await FirebaseApi().signInEmail(modelUser.email, modelUser.password);
try { try {
if (rc == FirebaseApi.SIGN_IN_OK) { if (rc == FirebaseApi.SIGN_IN_OK) {
@ -218,7 +218,7 @@ class UserRepository with Logging {
} }
Future<void> resetPassword() async { Future<void> resetPassword() async {
final User modelUser = this.user; final User modelUser = user;
await FirebaseApi().resetPassword(modelUser.email!); await FirebaseApi().resetPassword(modelUser.email!);
} }
} }

View File

@ -1,6 +1,8 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:sentry_flutter/sentry_flutter.dart'; import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:workouttest_util/service/webapi.dart';
import 'package:workouttest_util/util/logging.dart'; import 'package:workouttest_util/util/logging.dart';
import 'package:workouttest_util/util/common.dart'; import 'package:workouttest_util/util/common.dart';
import 'package:workouttest_util/util/not_found_exception.dart'; import 'package:workouttest_util/util/not_found_exception.dart';
@ -19,6 +21,10 @@ class APIClient with Common, Logging {
} }
dynamic authenticateUser(String email, String password) async { dynamic authenticateUser(String email, String password) async {
if ( kIsWeb ) {
APIWebClient webClient = APIWebClient();
return webClient.authenticateUser(email, password);
}
var baseUrl = Cache().getBaseUrl(); var baseUrl = Cache().getBaseUrl();
log("Base URL: $baseUrl"); log("Base URL: $baseUrl");
var url = "${baseUrl}authenticate"; var url = "${baseUrl}authenticate";
@ -60,6 +66,10 @@ class APIClient with Common, Logging {
} }
Future<String> post(String endPoint, String body) async { Future<String> post(String endPoint, String body) async {
if ( kIsWeb ) {
APIWebClient webClient = APIWebClient();
return webClient.post(endPoint, body);
}
final url = Cache().getBaseUrl() + endPoint; final url = Cache().getBaseUrl() + endPoint;
trace(" ------------ http/post body $body - url: $url "); trace(" ------------ http/post body $body - url: $url ");
try { try {
@ -99,6 +109,10 @@ class APIClient with Common, Logging {
} }
Future<String> get(String endPoint, String param) async { Future<String> get(String endPoint, String param) async {
if ( kIsWeb ) {
APIWebClient webClient = APIWebClient();
return webClient.get(endPoint, param);
}
final url = Cache().getBaseUrl() + endPoint + param; final url = Cache().getBaseUrl() + endPoint + param;
try { try {
trace("-------- API get $url"); trace("-------- API get $url");

View File

@ -12,7 +12,7 @@ class CustomerExerciseDeviceApi with Logging {
List<CustomerExerciseDevice> devices = []; List<CustomerExerciseDevice> devices = [];
try { try {
log(" --- get customer_exercise_devices: "); log(" --- get customer_exercise_devices: ");
final body = await _client.get("customer_exercise_device/customer/" + customerId.toString(), ""); final body = await _client.get("customer_exercise_device/customer/$customerId", "");
final Iterable json = jsonDecode(body); final Iterable json = jsonDecode(body);
devices = json.map((device) => CustomerExerciseDevice.fromJson(device)).toList(); devices = json.map((device) => CustomerExerciseDevice.fromJson(device)).toList();
} on NotFoundException catch (_) { } on NotFoundException catch (_) {
@ -25,22 +25,22 @@ class CustomerExerciseDeviceApi with Logging {
Future<CustomerExerciseDevice> addDevice(CustomerExerciseDevice device) async { Future<CustomerExerciseDevice> addDevice(CustomerExerciseDevice device) async {
CustomerExerciseDevice savedDevice; CustomerExerciseDevice savedDevice;
try { try {
final String body = JsonEncoder().convert(device.toJson()); final String body = const JsonEncoder().convert(device.toJson());
log(" --- add customer_exercise_device: " + body); log(" --- add customer_exercise_device: $body");
final String responseBody = await _client.post("customer_exercise_device", body); final String responseBody = await _client.post("customer_exercise_device", body);
savedDevice = CustomerExerciseDevice.fromJson(jsonDecode(responseBody)); savedDevice = CustomerExerciseDevice.fromJson(jsonDecode(responseBody));
} on Exception catch (e) { } on Exception catch (e) {
throw new Exception(e.toString()); throw Exception(e.toString());
} }
return savedDevice; return savedDevice;
} }
Future<void> removeDevice(int id) async { Future<void> removeDevice(int id) async {
try { try {
log(" --- delete customer_exercise_device: " + id.toString()); log(" --- delete customer_exercise_device: $id");
await _client.post("customer_exercise_device/delete/" + id.toString(), ""); await _client.post("customer_exercise_device/delete/$id", "");
} on Exception catch (e) { } on Exception catch (e) {
throw new Exception(e.toString()); throw Exception(e.toString());
} }
return; return;
} }

View File

@ -7,9 +7,9 @@ class ExerciseApi with Logging {
final APIClient _client = APIClient(); final APIClient _client = APIClient();
Future<void> saveExercise(Exercise exercise) async { Future<void> saveExercise(Exercise exercise) async {
String body = JsonEncoder().convert(exercise.toJson()); String body = const JsonEncoder().convert(exercise.toJson());
log(" ===== saving exercise id: " + exercise.exerciseId.toString() + ":" + body); log(" ===== saving exercise id: ${exercise.exerciseId}:$body");
await _client.post("exercises/" + exercise.exerciseId.toString(), body); await _client.post("exercises/${exercise.exerciseId}", body);
} }
Future<List<Exercise>> getExercisesByCustomer(int customerId) async { Future<List<Exercise>> getExercisesByCustomer(int customerId) async {
@ -25,8 +25,8 @@ class ExerciseApi with Logging {
} }
Future<Exercise> addExercise(Exercise exercise) async { Future<Exercise> addExercise(Exercise exercise) async {
String body = JsonEncoder().convert(exercise.toJson()); String body = const JsonEncoder().convert(exercise.toJson());
log(" ===== add new exercise: " + body); log(" ===== add new exercise: $body");
final String response = await _client.post("exercises", body); final String response = await _client.post("exercises", body);
final Exercise savedExercise = Exercise.fromJson(jsonDecode(response)); final Exercise savedExercise = Exercise.fromJson(jsonDecode(response));
return savedExercise; return savedExercise;
@ -37,8 +37,8 @@ class ExerciseApi with Logging {
return; return;
} }
int exerciseId = exercise.exerciseId!; int exerciseId = exercise.exerciseId!;
log(" ===== delete exercise: " + exerciseId.toString()); log(" ===== delete exercise: $exerciseId");
await _client.post("exercises/" + exerciseId.toString(), ""); await _client.post("exercises/$exerciseId", "");
return; return;
} }
} }

View File

@ -18,7 +18,7 @@ class ExerciseTreeApi with Logging {
exerciseTrees = await getExerciseTreeParents(exerciseTrees); exerciseTrees = await getExerciseTreeParents(exerciseTrees);
await Future.forEach(exerciseTrees, (element) async { await Future.forEach(exerciseTrees, (element) async {
ExerciseTree exerciseTree = element as ExerciseTree; ExerciseTree exerciseTree = element;
exerciseTree.imageUrl = await buildImage(exerciseTree.imageUrl, exerciseTree.treeId); exerciseTree.imageUrl = await buildImage(exerciseTree.imageUrl, exerciseTree.treeId);
}); });
exerciseTrees = await getExerciseTreeParents(exerciseTrees); exerciseTrees = await getExerciseTreeParents(exerciseTrees);
@ -29,13 +29,13 @@ class ExerciseTreeApi with Logging {
} }
Future<String> buildImage(String imageUrl, int treeId) async { Future<String> buildImage(String imageUrl, int treeId) async {
String assetImage = 'asset/menu/' + imageUrl.substring(7); String assetImage = 'asset/menu/${imageUrl.substring(7)}';
print("asset image $assetImage"); log("asset image $assetImage");
return await rootBundle.load(assetImage).then((value) { return await rootBundle.load(assetImage).then((value) {
return assetImage; return assetImage;
}).catchError((_) { }).catchError((_) {
String imagePath = assetImage.substring(10); String imagePath = assetImage.substring(10);
String url = Cache.mediaUrl + 'images' + imagePath; String url = '${Cache.mediaUrl}images$imagePath';
return url; return url;
}); });
} }
@ -72,10 +72,10 @@ class ExerciseTreeApi with Logging {
List<ExerciseTree> copyList(List<ExerciseTree> tree) { List<ExerciseTree> copyList(List<ExerciseTree> tree) {
final List<ExerciseTree> copyList = []; final List<ExerciseTree> copyList = [];
tree.forEach((element) { for (var element in tree) {
final ExerciseTree copy = element.copy(-1); final ExerciseTree copy = element.copy(-1);
copyList.add(copy); copyList.add(copy);
}); }
return copyList; return copyList;
} }

View File

@ -1,13 +1,11 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'dart:convert'; import 'dart:convert';
// ignore: depend_on_referenced_packages
import 'package:crypto/crypto.dart'; import 'package:crypto/crypto.dart';
import 'package:workouttest_util/model/cache.dart'; import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/util/logging.dart' as logger; import 'package:workouttest_util/util/logging.dart' as logger;
import 'package:sentry_flutter/sentry_flutter.dart'; import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
// ignore: depend_on_referenced_packages
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart'; import 'package:firebase_remote_config/firebase_remote_config.dart';
@ -38,7 +36,7 @@ class FirebaseApi with logger.Logging {
// Wait for Firebase to initialize and set `_initialized` state to true // Wait for Firebase to initialize and set `_initialized` state to true
await Firebase.initializeApp(); await Firebase.initializeApp();
this.appleSignInAvailable = await SignInWithApple.isAvailable(); appleSignInAvailable = await SignInWithApple.isAvailable();
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
@ -46,17 +44,17 @@ class FirebaseApi with logger.Logging {
badge: true, badge: true,
sound: true, sound: true,
); );
this.firebaseRegToken = await FirebaseMessaging.instance.getToken(); firebaseRegToken = await FirebaseMessaging.instance.getToken();
Cache().firebaseMessageToken = firebaseRegToken; Cache().firebaseMessageToken = firebaseRegToken;
log("FirebaseMessaging token $firebaseRegToken"); log("FirebaseMessaging token $firebaseRegToken");
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) { FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!'); log('Got a message whilst in the foreground!');
print('Message data: ${message.data}'); log('Message data: ${message.data}');
if (message.notification != null) { if (message.notification != null) {
print('Message also contained a notification: ${message.notification}'); log('Message also contained a notification: ${message.notification}');
} }
}); });
} catch (e) { } catch (e) {
@ -172,7 +170,7 @@ class FirebaseApi with logger.Logging {
} }
Future<Map<String, dynamic>> registerWithApple() async { Future<Map<String, dynamic>> registerWithApple() async {
Map<String, dynamic> userData = Map(); Map<String, dynamic> userData = {};
final rawNonce = generateNonce(); final rawNonce = generateNonce();
final nonce = sha256ofString(rawNonce); final nonce = sha256ofString(rawNonce);
@ -209,7 +207,7 @@ class FirebaseApi with logger.Logging {
} }
Future<Map<String, dynamic>> signInWithGoogle() async { Future<Map<String, dynamic>> signInWithGoogle() async {
Map<String, dynamic> userData = Map(); Map<String, dynamic> userData = {};
// Trigger the authentication flow // Trigger the authentication flow
GoogleSignIn googleSignIn = GoogleSignIn( GoogleSignIn googleSignIn = GoogleSignIn(
@ -246,7 +244,7 @@ class FirebaseApi with logger.Logging {
} }
Future<Map<String, dynamic>> registerWithGoogle() async { Future<Map<String, dynamic>> registerWithGoogle() async {
Map<String, dynamic> userData = Map(); Map<String, dynamic> userData = {};
// Trigger the authentication flow // Trigger the authentication flow
GoogleSignIn googleSignIn = GoogleSignIn( GoogleSignIn googleSignIn = GoogleSignIn(
@ -319,7 +317,7 @@ class FirebaseApi with logger.Logging {
// Once signed in, return the UserCredential // Once signed in, return the UserCredential
final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential); final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
log("Email by FB: " + userData['email'] + " FB credential: " + userCredential.toString()); log("Email by FB: ${userData['email']} FB credential: $userCredential");
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;
} else { } else {

View File

@ -22,7 +22,7 @@ class PurchaseApi with Logging {
} }
Future<void> savePurchase(Purchase purchase) async { Future<void> savePurchase(Purchase purchase) async {
String body = JsonEncoder().convert(purchase.toJson()); String body = const JsonEncoder().convert(purchase.toJson());
log(" ===== saving purchase:$body"); log(" ===== saving purchase:$body");
await _client.post("purchase", body); await _client.post("purchase", body);
} }

123
lib/service/webapi.dart Normal file
View File

@ -0,0 +1,123 @@
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/util/common.dart';
import 'package:workouttest_util/util/logging.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:workouttest_util/util/not_found_exception.dart';
class APIWebClient with Common, Logging {
static final APIWebClient _singleton = APIWebClient._internal();
late bool cert;
factory APIWebClient() {
return _singleton;
}
APIWebClient._internal() {
cert = false;
}
dynamic authenticateUser(String email, String password) async {
var baseUrl = Cache().getBaseUrl();
log("Base URL: $baseUrl");
var url = "${baseUrl}authenticate";
try {
final body = jsonEncode(<String, String>{
'username': email,
'password': password
});
var uri = Uri.parse(url);
var result = await http.post(uri, body: body, headers: {
"Content-Type": "application/json",
"Authorization": "1",
});
if (result.statusCode != 200) {
log("authentication response: ${result.statusCode} with URL: $url");
throw Exception("Authentication error: ${result.statusCode}");
}
String response = result.body;
log("Authentication status: ${result.statusCode}, response: $response");
final data = jsonDecode(response);
return data;
} catch (exception) {
log(exception.toString());
try {
await Sentry.captureException(exception);
} on Exception catch (e) {
log(e.toString());
}
throw Exception("Network error, try again later!");
}
}
Future<String> post(String endPoint, String body) async {
final url = Cache().getBaseUrl() + endPoint;
trace(" ------------ http/post body $body - url: $url ");
try {
String authToken = Cache().getAuthToken();
if (authToken.isEmpty) {
var responseJson = await authenticateUser(Cache.username, Cache.password);
authToken = responseJson['token'];
Cache().authToken = authToken;
}
var uri = Uri.parse(url);
var result = await http.post(uri, body: body, headers: {
"Content-Type": "application/json",
"Authorization": 'Bearer $authToken',
});
trace(" ------------post response code: ${result.statusCode}");
if (result.statusCode == 200) {
return result.body;
} else if (result.statusCode == 404) {
throw const NotFoundException(message: "Not Found");
} else {
throw Exception("Network Error, please try again later");
}
} on NotFoundException catch(e) {
throw NotFoundException(message: "Not Found ${e.message}");
} on Exception catch (e) {
log("Post Exception: $e");
await Sentry.captureException(e);
throw Exception("Network Error, please try again later");
}
}
Future<String> get(String endPoint, String param) async {
final url = Cache().getBaseUrl() + endPoint + param;
try {
trace("-------- API get $url");
String authToken = Cache().getAuthToken();
if (authToken.isEmpty) {
var responseJson = await authenticateUser(Cache.username, Cache.password);
authToken = responseJson['token'];
Cache().authToken = authToken;
}
var uri = Uri.parse(url);
var result = await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": 'Bearer $authToken',
});
trace(" ------------get response code: ${result.statusCode}");
if (result.statusCode == 200) {
return result.body;
} else if (result.statusCode == 404) {
throw const NotFoundException(message: "Not Found");
} else {
throw Exception("Network Error, please try again later");
}
} on NotFoundException catch(e) {
throw NotFoundException(message: "Not Found ${e.message}");
} on Exception catch (e) {
log("Post Exception: $e");
await Sentry.captureException(e);
throw Exception("Network Error, please try again later");
}
}
}

View File

@ -7,7 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart';
class AppLanguage with Logging { class AppLanguage with Logging {
static final AppLanguage _singleton = AppLanguage._internal(); static final AppLanguage _singleton = AppLanguage._internal();
Locale? _appLocale = Locale('en'); Locale? _appLocale = const Locale('en');
factory AppLanguage() { factory AppLanguage() {
return _singleton; return _singleton;
@ -19,18 +19,18 @@ class AppLanguage with Logging {
return _singleton; return _singleton;
} }
Locale get appLocal => _appLocale ?? Locale("en"); Locale get appLocal => _appLocale ?? const Locale("en");
Future<void> fetchLocale() async { Future<void> fetchLocale() async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
String? langCode = prefs.getString('language_code'); String? langCode = prefs.getString('language_code');
log(" ---- lang code $langCode"); log(" ---- lang code $langCode");
if (langCode == null) { if (langCode == null) {
_appLocale = Locale('en'); _appLocale = const Locale('en');
} else { } else {
_appLocale = Locale(langCode); _appLocale = Locale(langCode);
} }
log(" ---- Fetched lang: " + _appLocale.toString()); log(" ---- Fetched lang: $_appLocale");
} }
getLocale(SharedPreferences prefs) { getLocale(SharedPreferences prefs) {
@ -38,15 +38,15 @@ class AppLanguage with Logging {
if (langCode == null) { if (langCode == null) {
final String localName = Platform.localeName; final String localName = Platform.localeName;
if (localName.endsWith("HU")) { if (localName.endsWith("HU")) {
_appLocale = Locale('hu'); _appLocale = const Locale('hu');
langCode = "hu"; langCode = "hu";
} else { } else {
_appLocale = Locale('en'); _appLocale = const Locale('en');
langCode = "en"; langCode = "en";
} }
} }
_appLocale = Locale(langCode); _appLocale = Locale(langCode);
log(" ---- Get lang: " + _appLocale.toString() + " lang code $langCode"); log(" ---- Get lang: $_appLocale lang code $langCode");
} }
void changeLanguage(Locale type) async { void changeLanguage(Locale type) async {
@ -54,15 +54,15 @@ class AppLanguage with Logging {
if (_appLocale == type) { if (_appLocale == type) {
return; return;
} }
if (type == Locale("hu")) { if (type == const Locale("hu")) {
_appLocale = Locale("hu"); _appLocale = const Locale("hu");
await prefs.setString('language_code', 'hu'); await prefs.setString('language_code', 'hu');
await prefs.setString('countryCode', 'HU'); await prefs.setString('countryCode', 'HU');
} else { } else {
_appLocale = Locale("en"); _appLocale = const Locale("en");
await prefs.setString('language_code', 'en'); await prefs.setString('language_code', 'en');
await prefs.setString('countryCode', 'US'); await prefs.setString('countryCode', 'US');
} }
log(" ---- Stored lang: " + _appLocale.toString()); log(" ---- Stored lang: $_appLocale");
} }
} }

View File

@ -26,7 +26,7 @@ class AppLocalizations with Logging {
Future<bool> load() async { Future<bool> load() async {
// Load the language JSON file from the "lang" folder // Load the language JSON file from the "lang" folder
log(" -- load language pieces " + locale.languageCode); log(" -- load language pieces ${locale.languageCode}");
String jsonString = await rootBundle.loadString('i18n/${locale.languageCode}.json'); String jsonString = await rootBundle.loadString('i18n/${locale.languageCode}.json');
Map<String, dynamic> jsonMap = json.decode(jsonString); Map<String, dynamic> jsonMap = json.decode(jsonString);
@ -45,7 +45,7 @@ class AppLocalizations with Logging {
String translate(String key) { String translate(String key) {
if (isTest) return key; if (isTest) return key;
String? translated = _localizedStrings[key]; String? translated = _localizedStrings[key];
return translated != null ? translated : key; return translated ?? key;
} }
} }
@ -64,7 +64,7 @@ class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
@override @override
Future<AppLocalizations> load(Locale locale) async { Future<AppLocalizations> load(Locale locale) async {
// AppLocalizations class is where the JSON loading actually runs // AppLocalizations class is where the JSON loading actually runs
AppLocalizations localizations = new AppLocalizations(locale, isTest: this.isTest); AppLocalizations localizations = AppLocalizations(locale, isTest: isTest);
if (isTest) { if (isTest) {
await localizations.loadTest(locale); await localizations.loadTest(locale);
} else { } else {

View File

@ -2,7 +2,6 @@ import 'dart:convert';
import 'package:workouttest_util/util/app_language.dart'; import 'package:workouttest_util/util/app_language.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class DateRate { class DateRate {

View File

@ -3,8 +3,8 @@ import 'package:workouttest_util/util/string_extension.dart';
enum LoginType { email, fb, google, apple } enum LoginType { email, fb, google, apple }
extension LoginTypeExt on LoginType { extension LoginTypeExt on LoginType {
bool equalsTo(LoginType type) => this.toString() == type.toString(); bool equalsTo(LoginType type) => toString() == type.toString();
bool equalsStringTo(String type) => this.toString() == type; bool equalsStringTo(String type) => toString() == type;
} }
enum TrackingEvent { enum TrackingEvent {
@ -69,60 +69,60 @@ T enumFromString<T>(Iterable<T> values, String value) {
} }
extension TrackingEventExt on TrackingEvent { extension TrackingEventExt on TrackingEvent {
String enumToString() => this.toString().split(".").last; String enumToString() => toString().split(".").last;
bool equalsTo(TrackingEvent event) => this.toString() == event.toString(); bool equalsTo(TrackingEvent event) => toString() == event.toString();
bool equalsStringTo(String event) => this.toString() == event; bool equalsStringTo(String event) => toString() == event;
} }
enum PropertyEnum { Ectomorph, Mesomorph, Endomorph } enum PropertyEnum { Ectomorph, Mesomorph, Endomorph }
extension PropertyExt on PropertyEnum { extension PropertyExt on PropertyEnum {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(PropertyEnum event) => this.toString() == event.toString(); bool equalsTo(PropertyEnum event) => toString() == event.toString();
bool equalsStringTo(String event) => this.toString() == event; bool equalsStringTo(String event) => toString() == event;
} }
enum SizesEnum { Weight, Height, Shoulder, Neck, Biceps, Chest, Belly, Hip, ThighTop, ThighMiddle, Knee, Calf, Ankle, Underarm, Lowerarm } enum SizesEnum { Weight, Height, Shoulder, Neck, Biceps, Chest, Belly, Hip, ThighTop, ThighMiddle, Knee, Calf, Ankle, Underarm, Lowerarm }
extension SizesExt on SizesEnum { extension SizesExt on SizesEnum {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(SizesEnum event) => this.toString() == event.toString(); bool equalsTo(SizesEnum event) => toString() == event.toString();
bool equalsStringTo(String event) => this.toString() == event; bool equalsStringTo(String event) => toString() == event;
} }
enum EvaluationText { very_poor, poor, fair, below_average, average, above_average, good, excellent, elite } enum EvaluationText { very_poor, poor, fair, below_average, average, above_average, good, excellent, elite }
extension EvaluationTextExt on EvaluationText { extension EvaluationTextExt on EvaluationText {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(EvaluationText eval) => this.toString() == eval.toString(); bool equalsTo(EvaluationText eval) => toString() == eval.toString();
bool equalsStringTo(String eval) => this.toStr() == eval; bool equalsStringTo(String eval) => toStr() == eval;
} }
enum ExerciseTypeTrainingPlanState { none, added, executed } enum ExerciseTypeTrainingPlanState { none, added, executed }
extension ExerciseTypeTrainingPlanStateExt on ExerciseTypeTrainingPlanState { extension ExerciseTypeTrainingPlanStateExt on ExerciseTypeTrainingPlanState {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(ExerciseTypeTrainingPlanState state) => this.toString() == state.toString(); bool equalsTo(ExerciseTypeTrainingPlanState state) => toString() == state.toString();
bool equalsStringTo(String state) => this.toStr() == state; bool equalsStringTo(String state) => toStr() == state;
} }
enum ExerciseSaveType { test, training, test_set } enum ExerciseSaveType { test, training, test_set }
extension ExerciseSaveTypeExt on ExerciseSaveType { extension ExerciseSaveTypeExt on ExerciseSaveType {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
bool equalsTo(ExerciseSaveType type) => this.toString() == type.toString(); bool equalsTo(ExerciseSaveType type) => toString() == type.toString();
bool equalsStringTo(String type) => this.toStr() == type; bool equalsStringTo(String type) => toStr() == type;
} }
enum MuscleGroup { chest, biceps, triceps, back, shoulders, core, thigh, calf } enum MuscleGroup { chest, biceps, triceps, back, shoulders, core, thigh, calf }
extension MuscleGroupExt on MuscleGroup { extension MuscleGroupExt on MuscleGroup {
String toStr() => this.toString().split(".").last; String toStr() => toString().split(".").last;
String toText() => this.toString().split(".").last.capitalize(); String toText() => toString().split(".").last.capitalize();
bool equalsTo(MuscleGroup type) => this.toString() == type.toString(); bool equalsTo(MuscleGroup type) => toString() == type.toString();
bool equalsStringTo(String type) => this.toStr() == type; bool equalsStringTo(String type) => toStr() == type;
String getStrByIndex(int index) => MuscleGroup.values.elementAt(index).toStr(); String getStrByIndex(int index) => MuscleGroup.values.elementAt(index).toStr();
MuscleGroup getByIndex(int index) => MuscleGroup.values.elementAt(index); MuscleGroup getByIndex(int index) => MuscleGroup.values.elementAt(index);
String getTextByIndex(int index) => MuscleGroup.values.elementAt(index).toText(); String getTextByIndex(int index) => MuscleGroup.values.elementAt(index).toText();

View File

@ -1,5 +1,5 @@
extension StringExtension on String { extension StringExtension on String {
String capitalize() { String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}"; return "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
} }
} }

33
test/api_test.dart Normal file
View File

@ -0,0 +1,33 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/service/api.dart';
import 'package:workouttest_util/service/webapi.dart';
main() {
setUp(() {
Cache().setLocalBaseUrl();
});
group('api', () {
test('connect api auth successfully', () async {
var api = APIClient();
var responseJson = await api.authenticateUser("bosi", "andio2009");
print(responseJson);
Cache().authToken = responseJson['token'];
final body = await api.get("app_package", "");
print(body);
});
test('connect webapi auth successfully', () async {
var api = APIWebClient();
var responseJson = await api.authenticateUser("bosi", "andio2009");
print(responseJson);
Cache().authToken = responseJson['token'];
final body = await api.get("app_package", "");
print(body);
});
});
}

View File

@ -1,9 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workouttest_util/workouttest_util.dart';
void main() {
test('adds one to input values', () {
});
}