v1.0.0 outsourced from aitrainer_app

This commit is contained in:
Tibor Bossanyi (Freelancer)
2023-01-28 12:53:16 +01:00
commit ca96abf8c0
87 changed files with 7189 additions and 0 deletions
@@ -0,0 +1,74 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/customer_exercise_device.dart';
import 'package:workouttest_util/model/exercise_device.dart';
import 'package:workouttest_util/model/model_change.dart';
import 'package:workouttest_util/service/customer_exercise_device_service.dart';
class CustomerExerciseDeviceRepository {
List<CustomerExerciseDevice> _devices = [];
List<CustomerExerciseDevice> getDevices() => this._devices;
void setDevices(List<CustomerExerciseDevice> devices) => this._devices = devices;
Future<List<CustomerExerciseDevice>?> getDBDevices() async {
if (Cache().userLoggedIn != null) {
final int customerId = Cache().userLoggedIn!.customerId!;
this._devices = await CustomerExerciseDeviceApi().getDevices(customerId);
}
return this._devices;
}
Future<void> addDevice(ExerciseDevice device) async {
CustomerExerciseDevice? found;
this._devices.forEach((element) {
if (element.exerciseDeviceId == device.exerciseDeviceId) {
found = element;
}
});
if (found == null) {
int? customerId;
if (Cache().userLoggedIn != null) {
customerId = Cache().userLoggedIn!.customerId!;
}
CustomerExerciseDevice newDevice =
CustomerExerciseDevice(customerId: customerId!, exerciseDeviceId: device.exerciseDeviceId, favourite: false);
newDevice.change = ModelChange.add;
CustomerExerciseDevice saved = await CustomerExerciseDeviceApi().addDevice(newDevice);
this._devices.add(saved);
Cache().setCustomerDevices(_devices);
}
}
Future<void> removeDevice(ExerciseDevice device) async {
CustomerExerciseDevice? found;
this._devices.forEach((element) {
if (element.exerciseDeviceId == device.exerciseDeviceId) {
found = element;
}
});
if (found != null) {
this._devices.remove(found);
//if (found.change != ModelChange.add) {
await CustomerExerciseDeviceApi().removeDevice(found!.customerExerciseDeviceId!);
//}
Cache().setCustomerDevices(_devices);
}
}
bool hasDevice(int exerciseDeviceId) {
bool found = false;
this._devices.forEach((element) {
if (element.exerciseDeviceId == exerciseDeviceId) {
found = true;
}
});
return found;
}
}
+573
View File
@@ -0,0 +1,573 @@
import 'dart:collection';
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/customer.dart';
import 'package:workouttest_util/model/customer_property.dart';
import 'package:workouttest_util/model/property.dart';
import 'package:workouttest_util/model/purchase.dart';
import 'package:workouttest_util/model/sport.dart';
import 'package:workouttest_util/repository/property_repository.dart';
import 'package:workouttest_util/service/customer_service.dart';
import 'package:workouttest_util/util/logging.dart';
import 'package:workouttest_util/service/purchase_service.dart';
import 'package:workouttest_util/util/enums.dart';
class GenderItem {
GenderItem(this.dbValue, this.name);
final String dbValue;
String name;
}
class CustomerRepository with Logging {
Customer? customer;
Customer? _trainee;
List<Customer>? _trainees;
List<CustomerProperty>? _properties;
//List<CustomerProperty>? _allCustomerProperties;
final PropertyRepository propertyRepository = PropertyRepository();
final List<Property> womanSizes = [];
final List<Property> manSizes = [];
final double baseWidth = 312;
final double baseHeight = 675.2;
double mediaWidth = 0;
double mediaHeight = 0;
bool isMan = true;
//List<CustomerRepository> customerList = List<CustomerRepository>();
bool visibleDetails = false;
late List<GenderItem> genders;
CustomerRepository() {
customer = Customer();
if (Cache().userLoggedIn != null) {
isMan = (Cache().userLoggedIn!.sex == "m");
}
//_allCustomerProperties = Cache().getCustomerPropertyAll();
}
String? getGenderByName(String name) {
String? dbValue;
genders.forEach((element) {
if (element.name == name) {
dbValue = element.dbValue;
}
});
return dbValue;
}
String? getGenderByDBValue(String dbValue) {
String? name;
genders.forEach((element) {
if (element.dbValue == dbValue) {
name = element.name;
}
});
return name;
}
String? get name {
return this.customer != null && this.customer!.name != null ? this.customer!.name : "";
}
String? get firstName {
return this.customer != null && this.customer!.firstname != null ? this.customer!.firstname : "";
}
String get sex {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.sex == "m" ? "Man" : "Woman";
}
int? get birthYear {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.birthYear;
}
String? get goal {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.goal;
}
String? getSportString() {
if (this.customer == null) throw Exception("Initialize the customer object");
String? sport;
List<Sport>? sports = Cache().getSports();
if (sports != null) {
for (Sport sportObject in sports) {
if (sportObject.sportId == this.customer!.sportId) {
sport = sportObject.name;
break;
}
}
}
return sport;
}
Sport? getSport() {
if (this.customer == null) throw Exception("Initialize the customer object");
Sport? sport;
List<Sport>? sports = Cache().getSports();
if (sports != null) {
for (Sport sportObject in sports) {
if (sportObject.sportId == this.customer!.sportId) {
sport = sportObject;
break;
}
}
}
return sport;
}
String? get fitnessLevel {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.fitnessLevel;
}
String? get bodyType {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.bodyType;
}
setName(String name) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.name = name;
}
setFirstName(String firstName) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.firstname = firstName;
}
setPassword(String password) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.password = password;
}
setEmail(String email) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.email = email;
}
setSex(String sex) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.sex = sex;
}
setWeight(double weight) {
final propertyName = "Weight";
this.setCustomerProperty(propertyName, weight);
}
setHeight(int height) {
final propertyName = "Height";
this.setCustomerProperty(propertyName, height.toDouble());
}
setCustomerProperty(String propertyName, double value, {id = 0}) {
if (this.customer == null) {
throw Exception("Initialize the customer object");
}
if (this.customer!.properties[propertyName] == null) {
this.customer!.properties[propertyName] = CustomerProperty(
propertyId: propertyRepository.getPropertyByName("Height")!.propertyId,
customerId: this.customer!.customerId == null ? 0 : this.customer!.customerId!,
propertyValue: value,
dateAdd: DateTime.now());
} else {
this.customer!.properties[propertyName]!.propertyValue = value;
}
this.customer!.properties[propertyName]!.dateAdd = DateTime.now();
this.customer!.properties[propertyName]!.newData = true;
if (id > 0) {
this.customer!.properties[propertyName]!.customerPropertyId = id;
}
Cache().addCustomerProperty(this.customer!.properties[propertyName]!);
}
double getWeight() {
return getCustomerPropertyValue("Weight");
}
double getHeight() {
return getCustomerPropertyValue("Height");
}
double getCustomerPropertyValue(String propertyName) {
if (this.customer == null || this.customer!.properties[propertyName] == null) {
return 0.0;
} else {
return this.customer!.properties[propertyName]!.propertyValue;
}
}
CustomerProperty? getCustomerProperty(String propertyName) {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!.properties[propertyName];
}
setBirthYear(int birthYear) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.birthYear = birthYear;
}
setFitnessLevel(String level) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.fitnessLevel = level;
}
setGoal(String goal) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.goal = goal;
}
setSportString(String selectedSport) {
if (this.customer == null) throw Exception("Initialize the customer object");
List<Sport>? sports = Cache().getSports();
if (sports != null) {
for (Sport sportObject in sports) {
if (sportObject.name == selectedSport) {
this.customer!.sportId = sportObject.sportId;
break;
}
}
}
}
setBodyType(String bodyType) {
if (this.customer == null) throw Exception("Initialize the customer object");
this.customer!.bodyType = bodyType;
}
createNew() {
this.customer = Customer();
}
Customer getCustomer() {
if (this.customer == null) throw Exception("Initialize the customer object");
return this.customer!;
}
void setCustomer(Customer customer) {
this.customer = customer;
}
Future<void> addCustomer() async {
if (this.customer == null) throw Exception("Initialize the customer object");
final Customer modelCustomer = customer!;
await CustomerApi().addCustomer(modelCustomer);
}
Future<void> saveCustomer() async {
if (this.customer == null) throw Exception("Initialize the customer object");
final Customer modelCustomer = customer!;
if (modelCustomer.sex == null) {
modelCustomer.sex = "m";
}
if (modelCustomer.fitnessLevel == null) {
modelCustomer.fitnessLevel = "beginner";
}
await CustomerApi().saveCustomer(modelCustomer);
await this.saveProperties(modelCustomer.properties);
}
Future<void> saveProperties(LinkedHashMap<String, CustomerProperty> properties) async {
properties.forEach((propertyName, property) async {
if (property.newData == true) {
await CustomerApi().addProperty(property);
property.newData = false;
}
});
}
Future<void> savePropertyByName(String name) async {
await Future.forEach(this._properties!, (element) async {
final CustomerProperty customerProperty = element as CustomerProperty;
final Property? property = propertyRepository.getPropertyByName(name);
if (property != null) {
if (property.propertyId == customerProperty.propertyId) {
await CustomerApi().updateProperty(customerProperty);
}
}
});
}
Future<Customer?> getTraineeAsCustomer() async {
this._trainee = await CustomerApi().getTrainee(Cache().userLoggedIn!.customerId!);
return _trainee;
}
Future<List<Customer?>?> getTrainees() async {
int trainerId = Cache().userLoggedIn!.customerId!;
final results = await CustomerApi().getTrainees(trainerId);
this._trainees = results;
return results;
}
Future<List<CustomerProperty>> getAllCustomerProperties() async {
int customerId = Cache().userLoggedIn!.customerId!;
final results = await CustomerApi().getAllProperties(customerId);
this._properties = results;
return results;
}
List<CustomerProperty>? getAllProperties() {
return this._properties;
}
List<Customer>? getTraineesList() {
return _trainees;
}
void setTrainee(int traineeId) {
if (_trainees == null) {
return;
}
_trainees!.forEach((element) {
if (traineeId == element.customerId) {
this._trainee = element;
}
});
}
void emptyTrainees() {
_trainees = null;
_trainee = null;
}
Customer? getTrainee() {
return this._trainee;
}
Customer? getTraineeById(int customerId) {
if (_trainees == null) {
return null;
}
_trainees!.forEach((element) {
if (customerId == element.customerId) {
this._trainee = element;
}
});
return _trainee;
}
Future<List<Purchase>> getPurchase() async {
int customerId = Cache().userLoggedIn!.customerId!;
List<Purchase> purchases = await PurchaseApi().getPurchasesByCustomer(customerId);
return purchases;
}
Future<void> addPurchase(Purchase purchase) async {
await PurchaseApi().savePurchase(purchase);
}
void setMediaDimensions(double width, double height) {
this.mediaHeight = height;
this.mediaWidth = width;
this.addSizes(this.sex);
}
void addSizes(String sex) {
if (this.customer == null) throw Exception("Initialize the customer object");
List<Property>? properties = Cache().getProperties();
if (properties == null) {
return;
}
final double distortionWidth = mediaWidth / baseWidth;
final double distortionHeight = mediaHeight / baseHeight;
if (isMan) {
properties.forEach((element) {
if (element.propertyName == "Shoulder") {
element.top = (122 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Shoulder");
manSizes.add(element);
} else if (element.propertyName == "Neck") {
element.top = (68 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Neck");
manSizes.add(element);
} else if (element.propertyName == "Biceps") {
element.top = (178 * distortionHeight).toInt();
element.left = (208 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Biceps");
manSizes.add(element);
} else if (element.propertyName == "Chest") {
element.top = (154 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Chest");
manSizes.add(element);
} else if (element.propertyName == "Belly") {
element.top = (244 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Belly");
manSizes.add(element);
} else if (element.propertyName == "Hip") {
element.top = (308 * distortionHeight).toInt();
element.left = (130 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Hip");
manSizes.add(element);
} else if (element.propertyName == "Thigh Top") {
element.top = (332 * distortionHeight).toInt();
element.left = (165 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Top");
manSizes.add(element);
} else if (element.propertyName == "Thigh Middle") {
element.top = (382 * distortionHeight).toInt();
element.left = (100 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Middle");
manSizes.add(element);
} else if (element.propertyName == "Knee") {
element.top = (464 * distortionHeight).toInt();
element.left = (97 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Knee");
manSizes.add(element);
} else if (element.propertyName == "Calf") {
element.top = (520 * distortionHeight).toInt();
element.left = (97 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Calf");
manSizes.add(element);
} else if (element.propertyName == "Ankle") {
element.top = (620 * distortionHeight).toInt();
element.left = (150 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Ankle");
manSizes.add(element);
} else if (element.propertyName == "Weight") {
element.top = (402 * distortionHeight).toInt();
element.left = (240 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Weight");
manSizes.add(element);
}
});
} else {
properties.forEach((element) {
if (element.propertyName == "Shoulder") {
element.top = (122 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Shoulder");
manSizes.add(element);
} else if (element.propertyName == "Neck") {
element.top = (78 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Neck");
manSizes.add(element);
} else if (element.propertyName == "Biceps") {
element.top = (178 * distortionHeight).toInt();
element.left = (212 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Biceps");
manSizes.add(element);
} else if (element.propertyName == "Chest") {
element.top = (154 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Chest");
manSizes.add(element);
} else if (element.propertyName == "Belly") {
element.top = (230 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Belly");
manSizes.add(element);
} else if (element.propertyName == "Hip") {
element.top = (294 * distortionHeight).toInt();
element.left = (151 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Hip");
manSizes.add(element);
} else if (element.propertyName == "Thigh Top") {
element.top = (335 * distortionHeight).toInt();
element.left = (185 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Top");
manSizes.add(element);
} else if (element.propertyName == "Thigh Middle") {
element.top = (377 * distortionHeight).toInt();
element.left = (125 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Thigh Middle");
manSizes.add(element);
} else if (element.propertyName == "Knee") {
element.top = (468 * distortionHeight).toInt();
element.left = (129 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Knee");
manSizes.add(element);
} else if (element.propertyName == "Calf") {
element.top = (525 * distortionHeight).toInt();
element.left = (129 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Calf");
manSizes.add(element);
} else if (element.propertyName == "Ankle") {
element.top = (620 * distortionHeight).toInt();
element.left = (162 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Ankle");
manSizes.add(element);
} else if (element.propertyName == "Weight") {
element.top = (402 * distortionHeight).toInt();
element.left = (240 * distortionWidth).toInt();
element.value = this.customer!.getProperty("Weight");
manSizes.add(element);
}
});
}
}
int? getWeightCoordinate(isMan, {isTop = false, isLeft = false}) {
int? value = 0;
this.manSizes.forEach((element) {
if (element.propertyName == SizesEnum.Weight.toStr()) {
if (isTop == true) {
value = element.top;
} else if (isLeft == true) {
value = element.left;
}
}
});
return value;
}
Property? getPropertyByName(String propertyName) {
Property? property;
List<Property> sizes;
if (this.sex == "m") {
sizes = this.manSizes;
} else {
sizes = this.womanSizes;
}
sizes.forEach((element) {
if (element.propertyName == propertyName) {
property = element;
}
});
return property;
}
void updateSizes(String propertyName, double value) {
List<Property> sizes;
if (this.sex == "m") {
sizes = this.manSizes;
} else {
sizes = this.womanSizes;
}
sizes.forEach((element) {
if (element.propertyName == propertyName) {
element.value = value;
}
});
}
List<CustomerProperty> getAllCustomerPropertyByName(String propertyName) {
List<CustomerProperty> allProperties = [];
Property? property = propertyRepository.getPropertyByName(propertyName);
print(property);
if (property == null || Cache().getCustomerPropertyAll() == null) {
return allProperties;
}
Cache().getCustomerPropertyAll()!.forEach((element) {
if (element.propertyId == property.propertyId) {
allProperties.add(element);
}
});
return allProperties;
}
}
@@ -0,0 +1,52 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/exercise_device.dart';
import 'package:workouttest_util/service/exercise_device_service.dart';
class ExerciseDeviceRepository {
List<ExerciseDevice> _devices = [];
List<ExerciseDevice> getDevices() {
return this._devices;
}
void setDevices(List<ExerciseDevice> list) {
_devices = list;
}
Future<List<ExerciseDevice>> getDBDevices() async {
this._devices = await ExerciseDeviceApi().getDevices();
return this._devices;
}
bool isGym(int deviceId) {
bool isGym = false;
_devices.forEach((element) {
isGym = isGymElement(element.name);
});
return isGym;
}
bool isGymElement(String name) {
return name == "Cable" ||
name == "Baar" ||
name == "Gym Machine" ||
name == "Dumbbells" ||
name == "Barbell" ||
name == "HOME" ||
name == "STREET";
}
List<ExerciseDevice> getGymDevices() {
if (Cache().getDevices() == null) return [];
final List<ExerciseDevice> gymDevices = [];
if (_devices.isEmpty) {
_devices = Cache().getDevices()!;
}
_devices.forEach((element) {
if (isGymElement(element.name)) {
gymDevices.add(element);
}
});
return gymDevices;
}
}
+538
View File
@@ -0,0 +1,538 @@
import 'dart:collection';
import 'package:workouttest_util/util/app_language.dart';
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/customer.dart';
import 'package:workouttest_util/model/exercise.dart';
import 'package:workouttest_util/model/exercise_type.dart';
import 'package:workouttest_util/model/workout_menu_tree.dart';
import 'package:workouttest_util/service/exercise_service.dart';
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart';
class ExerciseRepository {
Exercise? exercise;
Customer? customer;
ExerciseType? exerciseType;
List<Exercise>? exerciseList;
List<Exercise>? exerciseLogList = [];
List<Exercise>? actualExerciseList = [];
bool noRegistration = false;
double rmWendler = 0;
double rmMcglothlin = 0;
double rmLombardi = 0;
double rmMayhew = 0;
double rmOconner = 0;
double rmWathen = 0;
DateTime? start;
DateTime? end;
ExerciseRepository() {
this.createNew();
}
createNew() {
this.exercise = Exercise();
exercise!.dateAdd = DateTime.now();
}
setQuantity(double quantity) {
if (this.exercise == null) {
this.createNew();
}
this.exercise!.quantity = quantity;
}
setUnitQuantity(double unitQuantity) {
if (this.exercise == null) {
this.createNew();
}
this.exercise!.unitQuantity = unitQuantity;
}
setUnit(String unit) {
if (this.exercise == null) {
this.createNew();
}
this.exercise!.unit = unit;
}
setDatetimeExercise(DateTime datetimeExercise) {
if (this.exercise == null) {
this.createNew();
}
this.exercise!.dateAdd = datetimeExercise;
}
double? get unitQuantity => this.exercise!.unitQuantity;
double? get quantity => this.exercise!.quantity;
Exercise? getExercise() => this.exercise;
Future<Exercise> addExercise() async {
if (this.customer == null) {
throw Exception("Please log in");
}
final Exercise modelExercise = this.exercise!;
modelExercise.customerId = this.customer!.customerId;
modelExercise.exerciseTypeId = this.exerciseType!.exerciseTypeId;
if (exerciseType!.unitQuantity != "1") {
modelExercise.unitQuantity = null;
}
Exercise copy = modelExercise.copy();
this.actualExerciseList!.add(copy);
//final int index = this.actualExerciseList.length - 1;
//print("$index. actual exercise " + this.actualExerciseList[index].toJson().toString());
Exercise savedExercise = await ExerciseApi().addExercise(modelExercise);
//this.actualExerciseList[index].exerciseId = savedExercise.exerciseId;
if (customer!.customerId == Cache().userLoggedIn!.customerId) {
Cache().addExercise(savedExercise);
} else if (Cache().getTrainee() != null && customer!.customerId == Cache().getTrainee()!.customerId) {
Cache().addExerciseTrainee(savedExercise);
}
return savedExercise;
}
void addExerciseNoRegistration() {
final Exercise modelExercise = this.exercise!;
modelExercise.exerciseTypeId = this.exerciseType!.exerciseTypeId;
if (exerciseType!.unitQuantity != "1") {
modelExercise.unitQuantity = null;
}
Exercise copy = modelExercise.copy();
this.actualExerciseList!.add(copy);
this.exerciseList = [];
this.exerciseList!.add(copy);
this.noRegistration = true;
}
void initExercise() {
this.createNew();
this.exerciseType = exerciseType;
this.setUnit(exerciseType!.unit);
exercise!.exerciseTypeId = this.exerciseType!.exerciseTypeId;
this.setQuantity(12);
this.setUnitQuantity(30);
this.exercise!.exercisePlanDetailId = 0;
exercise!.exerciseId = 0;
this.start = DateTime.now();
}
Future<void> deleteExercise(Exercise exercise) async {
await ExerciseApi().deleteExercise(exercise);
}
setCustomer(Customer customer) => this.customer = customer;
setExerciseType(ExerciseType exerciseType) => this.exerciseType = exerciseType;
Future<List<Exercise>> getExercisesByCustomer(int customerId) async {
final results = await ExerciseApi().getExercisesByCustomer(customerId);
this.exerciseList = results;
if (Cache().userLoggedIn != null) {
if (customerId == Cache().userLoggedIn!.customerId) {
Cache().setExercises(exerciseList!);
} else if (Cache().getTrainee() != null && customerId == Cache().getTrainee()!.customerId) {
Cache().setExercisesTrainee(exerciseList!);
}
}
return this.exerciseList!;
}
List<Exercise>? getExerciseList() {
this.exerciseList = Cache().getExercises();
return this.exerciseList;
}
List<Exercise>? getExerciseListTrainee() {
this.exerciseList = Cache().getExercisesTrainee();
return this.exerciseList;
}
String? nextMissingBaseExercise(SplayTreeMap sortedTree) {
if (exerciseList == null) {
exerciseList = Cache().getExercises();
}
if (exerciseList == null) {
return null;
}
String? missingTreeName;
String? foundTreeName;
bool isBreak = false;
sortedTree.forEach((key, list) {
List<WorkoutMenuTree> listByMuscle = list as List<WorkoutMenuTree>;
String treeName = key as String;
treeName = treeName.substring(3);
foundTreeName = null;
listByMuscle.forEach((exercise) {
if (missingTreeName == null) {
missingTreeName = treeName;
}
if (exercise.base) {
if (exerciseList != null) {
exerciseList!.forEach((element) {
if (element.exerciseTypeId == exercise.exerciseTypeId) {
foundTreeName = treeName;
//print("Found " + foundTreeName + " Missing actual: " + missingTreeName);
isBreak = true;
}
});
}
}
});
if (foundTreeName == null && !isBreak) {
missingTreeName = treeName;
isBreak = true;
}
});
return missingTreeName;
}
void getBaseExerciseFinishedPercent() {
List<int> checkedExerciseTypeId = [];
List<int> baseTreeItem = [];
List<int> checkedBaseTreeItem = [];
int count1RMExercises = 0;
LinkedHashMap<String, WorkoutMenuTree> tree = Cache().getWorkoutMenuTree();
if (tree.isEmpty) {
return;
}
tree.forEach((key, value) {
WorkoutMenuTree treeItem = value;
if (treeItem.exerciseType != null && treeItem.exerciseType!.base == true && !baseTreeItem.contains(treeItem.parent)) {
baseTreeItem.add(treeItem.parent);
}
});
if (exerciseList == null) {
exerciseList = Cache().getExercises();
}
if (exerciseList == null) {
return;
}
exerciseList!.forEach((element) {
Exercise exercise = element;
if (!checkedExerciseTypeId.contains(exercise.exerciseTypeId)) {
checkedExerciseTypeId.add(exercise.exerciseTypeId!);
tree.forEach((key, value) {
WorkoutMenuTree treeItem = value;
if (treeItem.exerciseType != null &&
treeItem.exerciseType!.base == true &&
exercise.exerciseTypeId == treeItem.exerciseType!.exerciseTypeId &&
!checkedBaseTreeItem.contains(treeItem.parent)) {
//print ("id: " + exercise.exerciseTypeId.toString());
checkedBaseTreeItem.add(treeItem.parent);
count1RMExercises++;
}
});
}
});
//print ("checkedExerciseTypeid: " + checkedExerciseTypeId.toString());
//print ("baseTreeItem: " + baseTreeItem.toString());
//print ("count1RMExercises: " + count1RMExercises.toString());
final double percent = count1RMExercises / baseTreeItem.length;
Cache().setPercentExercises(percent);
}
void getLastExercise() {
List<Exercise>? exercises = this.getExerciseList();
Exercise? lastExercise = exercises == null ? null : exercises[0];
if (exercises != null) {
exercises.forEach((element) {
Exercise actualExercise = element;
if (actualExercise.dateAdd!.compareTo(lastExercise!.dateAdd!) > 0) {
lastExercise = actualExercise;
}
});
}
this.exercise = lastExercise;
this.customer = Cache().userLoggedIn!;
this.exerciseType = getExerciseTypeById(exercise!.exerciseTypeId!);
return;
}
ExerciseType? getExerciseTypeById(int exerciseTypeId) {
ExerciseType? actualExerciseType;
List<ExerciseType>? exercises = Cache().getExerciseTypes();
if (exercises != null) {
exercises.forEach((element) {
ExerciseType exerciseType = element;
if (exerciseType.exerciseTypeId == exerciseTypeId) {
actualExerciseType = exerciseType;
}
});
}
if (actualExerciseType == null) {
throw Exception("Data error, no ExerciseType for exerciseTypeId $exerciseTypeId");
}
return actualExerciseType;
}
void getSameExercise(int exerciseTypeId, String day) {
if (!this.noRegistration) {
this.actualExerciseList = [];
}
if (exerciseList != null) {
int index = 0;
for (int i = 0; i < this.exerciseList!.length; i++) {
Exercise exercise = exerciseList![i];
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exerciseTypeId == exercise.exerciseTypeId && exerciseDate == day && index < 4) {
this.actualExerciseList!.add(exercise);
index++;
}
}
}
}
double calculate1RM(Exercise exercise) {
double weight = exercise.unitQuantity!;
double repeat = exercise.quantity!;
if (weight == 0 || repeat == 0) {
return 0;
}
double rmWendler = weight * repeat * 0.0333 + weight;
double rmOconner = weight * (1 + repeat / 40);
double average = (rmWendler + rmOconner) / 2;
return average;
}
double getBest1RM(Exercise exercise) {
double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises();
}
final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = this.calculate1RM(exercise);
result = toCompare;
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(DateTime.now());
List<Exercise> oldExercises = [];
if (exerciseList == null) {
return toCompare;
}
this.exerciseList!.forEach((exercise) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise);
}
});
if (oldExercises.isNotEmpty) {
oldExercises.sort((a, b) {
double sumA = 0;
double sumB = 0;
if (a.unitQuantity != null && b.unitQuantity != null) {
sumA = a.quantity! * a.unitQuantity!;
sumB = b.quantity! * b.unitQuantity!;
} else {
sumA = a.quantity!;
sumB = b.quantity!;
}
return sumA >= sumB ? 1 : -1;
});
double withCompare = this.calculate1RM(oldExercises.last);
//result = toCompare >= withCompare ? (1 - toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
result = toCompare >= withCompare ? toCompare : withCompare;
}
return result;
}
double getLast1RMPercent(Exercise exercise) {
double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises();
}
final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = this.calculate1RM(exercise);
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
List<Exercise> oldExercises = [];
if (exerciseList == null) {
return result;
}
this.exerciseList!.forEach((exercise) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise);
}
});
if (oldExercises.isNotEmpty) {
double withCompare = this.calculate1RM(oldExercises.first);
result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
}
return result;
}
double getBestVolume(Exercise exercise) {
double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises();
}
final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = exercise.unitQuantity != null ? exercise.quantity! * exercise.unitQuantity! : exercise.quantity!;
result = toCompare;
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(DateTime.now());
List<Exercise> oldExercises = [];
if (exerciseList == null) {
return toCompare;
}
this.exerciseList!.forEach((exercise) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise);
}
});
if (oldExercises.isNotEmpty) {
oldExercises.sort((a, b) {
double sumA = 0;
double sumB = 0;
if (a.unitQuantity != null && b.unitQuantity != null) {
sumA = a.quantity! * a.unitQuantity!;
sumB = b.quantity! * b.unitQuantity!;
} else {
sumA = a.quantity!;
sumB = b.quantity!;
}
return sumA >= sumB ? 1 : -1;
});
double withCompare =
oldExercises.last.unitQuantity != null ? oldExercises.last.quantity! * oldExercises.last.unitQuantity! : oldExercises.last.quantity!;
//result = toCompare >= withCompare ? (1 - toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
//print("Last Best: ${oldExercises.last} - result: $result");
result = toCompare >= withCompare ? toCompare : withCompare;
}
return result;
}
double getLastExercisePercent(Exercise exercise) {
double result = 0;
if (this.exerciseList == null || this.exerciseList!.isEmpty) {
this.exerciseList = Cache().getExercises();
}
final int exerciseTypeId = exercise.exerciseTypeId!;
double toCompare = exercise.unitQuantity != null ? exercise.quantity! * exercise.unitQuantity! : exercise.quantity!;
final String today = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
List<Exercise> oldExercises = [];
if (exerciseList == null) {
return result;
}
this.exerciseList!.forEach((exercise) {
final String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
if (exercise.exerciseTypeId == exerciseTypeId && exerciseDate.compareTo(today) < 0) {
oldExercises.add(exercise);
}
});
if (oldExercises.isNotEmpty) {
double withCompare =
oldExercises.first.unitQuantity != null ? oldExercises.first.quantity! * oldExercises.first.unitQuantity! : oldExercises.first.quantity!;
result = toCompare >= withCompare ? (toCompare / withCompare) * 100 : (1 - toCompare / withCompare) * -100;
print("Last Last: ${oldExercises.first} vs. $exercise - - result: $result");
}
return result;
}
void sortByDate() {
if (exerciseList == null || exerciseList!.isEmpty) {
return;
}
exerciseList!.sort((a, b) {
final String datePartA = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(a.dateAdd!);
String aId = datePartA + "_" + a.exerciseTypeId.toString();
final String datePartB = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(b.dateAdd!);
String bId = datePartB + "_" + b.exerciseTypeId.toString();
return bId.compareTo(aId);
});
this.exerciseLogList = [];
String summary = "";
String prevDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exerciseList![0].dateAdd!);
int prevExerciseTypeId = exerciseList![0].exerciseTypeId!;
Exercise prevExercise = exerciseList![0];
int prevCount = 0;
for (int i = 0; i < this.exerciseList!.length; i++) {
Exercise exercise = exerciseList![i];
int exerciseTypeId = exercise.exerciseTypeId!;
String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!);
//print(" -- $prevExerciseTypeId - '$prevDate' against $exerciseTypeId - '$exerciseDate'");
if (exerciseTypeId != prevExerciseTypeId || prevDate != exerciseDate) {
ExerciseType? exerciseType = Cache().getExerciseTypeById(prevExercise.exerciseTypeId!);
String unit = exerciseType != null && exerciseType.unitQuantityUnit != null ? exerciseType.unitQuantityUnit! : prevExercise.unit!;
prevExercise.summary = summary + " " + unit;
exerciseLogList!.add(prevExercise);
//print("Log add " + exercise.toJson().toString());
summary = "";
prevCount = 0;
}
String delimiter = "";
if (prevCount > 0) delimiter = ", ";
double quantity = exercise.quantity == null ? 0 : exercise.quantity!;
summary += delimiter + quantity.toStringAsFixed(0);
ExerciseType? exerciseType = Cache().getExerciseTypeById(exercise.exerciseTypeId!);
//print("exerciseType " + (exerciseType == null ? "NULL" : exerciseType.name) + " ID " + exercise.exerciseTypeId.toString());
if (exerciseType != null) {
if (exerciseType.unitQuantity == "1") {
summary += "x" + exercise.unitQuantity!.toStringAsFixed(0);
}
//print(" --- sum " + exerciseType.name + " $summary");
}
prevExerciseTypeId = exerciseTypeId;
prevDate = exerciseDate;
prevExercise = exercise;
prevCount++;
}
prevExercise.summary = summary;
exerciseLogList!.add(prevExercise);
}
List<Exercise> getExercisesByExerciseTypeId(int exerciseTypeId) {
List<Exercise> list = [];
List<Exercise>? allExercise = Cache().getExercises();
if (allExercise == null) {
return list;
}
allExercise.forEach((element) {
if (element.exerciseTypeId == exerciseTypeId) {
list.add(element);
}
});
return list;
}
}
@@ -0,0 +1,26 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/exercise_type.dart';
import 'package:workouttest_util/util/logging.dart';
class ExerciseTypeRepository with Logging {
static List<ExerciseType> getExerciseTypeAlternatives(int? exerciseTypeId) {
if (exerciseTypeId == null || exerciseTypeId <= 0) {
return [];
}
List<ExerciseType> list = [];
List<ExerciseType>? exerciseTypes = Cache().getExerciseTypes();
if (exerciseTypes != null) {
exerciseTypes.forEach((exerciseType) {
if (exerciseType.alternatives.isNotEmpty) {
exerciseType.alternatives.forEach((childId) {
if (childId == exerciseTypeId) {
list.add(exerciseType);
}
});
}
});
}
return list;
}
}
+93
View File
@@ -0,0 +1,93 @@
// ignore: depend_on_referenced_packages
import 'package:intl/intl.dart';
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/mautic.dart';
import 'package:workouttest_util/repository/customer_repository.dart';
import 'package:workouttest_util/service/mautic.dart';
import 'package:workouttest_util/util/app_language.dart';
class MauticRepository {
final CustomerRepository customerRepository;
const MauticRepository({required this.customerRepository});
Future<void> sendMauticSubscription() async {
Mautic mautic = Mautic();
mautic.formId = 2;
mautic.databaseId = Cache().userLoggedIn!.customerId!;
mautic.firstname = customerRepository.customer!.firstname == null ? "" : customerRepository.customer!.firstname!;
mautic.lastname = customerRepository.customer!.name == null ? "" : customerRepository.customer!.name!;
mautic.email = customerRepository.customer!.email == null ? "" : customerRepository.customer!.email!;
if (mautic.email == null || mautic.email!.contains("privaterelay.appleid.com")) {
return;
}
mautic.fitnessLevel = customerRepository.customer!.fitnessLevel == null ? "" : customerRepository.customer!.fitnessLevel!;
mautic.goal = customerRepository.customer!.goal == null ? "" : customerRepository.customer!.goal!;
mautic.subscriptionDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
mautic.language = AppLanguage().appLocal.languageCode;
await MauticApi().sendMauticForm(mautic);
customerRepository.customer!.syncedDate = DateTime.now();
await customerRepository.saveCustomer();
}
Future<void> sendMauticDataChange() async {
Mautic mautic = Mautic();
mautic.formId = 3;
mautic.databaseId = Cache().userLoggedIn!.customerId!;
mautic.firstname = customerRepository.customer!.firstname == null ? "" : customerRepository.customer!.firstname!;
mautic.lastname = customerRepository.customer!.name == null ? "" : customerRepository.customer!.name!;
mautic.email = customerRepository.customer!.email == null ? "" : customerRepository.customer!.email!;
if (mautic.email == null || mautic.email!.contains("privaterelay.appleid.com")) {
return;
}
mautic.fitnessLevel = customerRepository.customer!.fitnessLevel == null ? "" : customerRepository.customer!.fitnessLevel!;
mautic.goal = customerRepository.customer!.goal == null ? "" : customerRepository.customer!.goal!;
mautic.language = AppLanguage().appLocal.languageCode;
await MauticApi().sendMauticForm(mautic);
}
Future<void> sendMauticPurchase() async {
Mautic mautic = Mautic();
mautic.formId = 4;
mautic.firstname = customerRepository.customer!.firstname == null ? "" : customerRepository.customer!.firstname!;
mautic.lastname = customerRepository.customer!.name == null ? "" : customerRepository.customer!.name!;
mautic.email = customerRepository.customer!.email == null ? "" : customerRepository.customer!.email!;
if (mautic.email == null || mautic.email!.contains("privaterelay.appleid.com")) {
return;
}
mautic.purchaseDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
await MauticApi().sendMauticForm(mautic);
}
Future<void> sendMauticExercise() async {
Mautic mautic = Mautic();
mautic.formId = 5;
mautic.firstname = customerRepository.customer!.firstname == null ? "" : customerRepository.customer!.firstname!;
mautic.lastname = customerRepository.customer!.name == null ? "" : customerRepository.customer!.name!;
mautic.email = customerRepository.customer!.email == null ? "" : customerRepository.customer!.email!;
if (mautic.email == null || mautic.email!.contains("privaterelay.appleid.com")) {
return;
}
mautic.exerciseDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
mautic.databaseId = Cache().userLoggedIn!.customerId!;
await MauticApi().sendMauticForm(mautic);
}
Future<void> sendMauticTrial() async {
Mautic mautic = Mautic();
mautic.formId = 6;
mautic.email = customerRepository.customer!.email == null ? "" : customerRepository.customer!.email!;
if (mautic.email == null || mautic.email!.contains("privaterelay.appleid.com")) {
return;
}
mautic.trialDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
mautic.databaseId = Cache().userLoggedIn!.customerId!;
await MauticApi().sendMauticForm(mautic);
}
}
+31
View File
@@ -0,0 +1,31 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/property.dart';
import 'package:workouttest_util/service/property_service.dart';
class PropertyRepository {
List<Property>? _properties;
Future<List<Property>?> getDBProperties() async {
this._properties = await PropertyApi().getProperties();
return this._properties;
}
List<Property>? getProperties() {
return this._properties;
}
Property? getPropertyByName(String name) {
Property? property;
if (_properties == null) {
_properties = Cache().getProperties();
}
if (_properties != null) {
this._properties!.forEach((element) {
if (name == element.propertyName) {
property = element;
}
});
}
return property;
}
}
@@ -0,0 +1,35 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/training_plan.dart';
import 'package:workouttest_util/util/app_language.dart';
class TrainingPlanDayRepository {
const TrainingPlanDayRepository();
void assignTrainingPlanDays() {
List<TrainingPlan>? plans = Cache().getTrainingPlans();
if (plans == null) {
return;
}
plans.forEach((plan) {
if (plan.details != null) {
plan.details!.forEach((element) {
element.day = this.getNameById(element.dayId);
});
}
});
}
String? getNameById(int? dayId) {
if (dayId == null) {
return "";
}
String? name;
for (var day in Cache().getTrainingPlanDays()) {
if (day.dayId == dayId) {
name = day.nameTranslations[AppLanguage().appLocal.languageCode];
break;
}
}
return name;
}
}
@@ -0,0 +1,448 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/customer_training_plan.dart';
import 'package:workouttest_util/model/customer_training_plan_details.dart';
import 'package:workouttest_util/model/exercise.dart';
import 'package:workouttest_util/model/exercise_plan_detail.dart';
import 'package:workouttest_util/model/exercise_tree.dart';
import 'package:workouttest_util/model/fitness_state.dart';
import 'package:workouttest_util/model/training_plan.dart';
import 'package:workouttest_util/model/training_plan_detail.dart';
import 'package:workouttest_util/repository/exercise_type_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/common.dart';
class TrainingPlanRepository with Common {
ExerciseTree? parentTree;
List<TrainingPlan> getPlansByParent(String parent) {
final List<TrainingPlan> resultList = [];
final List<ExerciseTree>? exerciseTree = Cache().getExerciseTree();
int? parentId;
if (exerciseTree != null) {
exerciseTree.forEach((element) {
if (element.internalName == parent) {
parentId = element.treeId;
parentTree = element;
}
});
}
final List<TrainingPlan>? plans = Cache().getTrainingPlans();
if (plans != null && parentId != null) {
plans.forEach((element) {
if (element.treeId == parentId) {
resultList.add(element);
}
});
}
return resultList;
}
/// 1. deactivate old training plans - update all
/// 2. calculate customer_training_plan_details weights / repleats
/// 3. create new customer_training_plan
CustomerTrainingPlan? activateTrainingPlan(int trainingPlanId) {
print(" **** Activate Plan: $trainingPlanId");
// 1. deactivate
if (Cache().getCustomerTrainingPlans() != null) {
Cache().getCustomerTrainingPlans()!.forEach((plan) {
plan.active = false;
if (plan.customerTrainingPlanId != null) {
//TrainingPlanApi().updateCustomerTrainingPlan(plan, plan.customerTrainingPlanId!);
}
});
}
CustomerTrainingPlan plan = CustomerTrainingPlan();
plan.customerId = Cache().userLoggedIn!.customerId;
plan.trainingPlanId = trainingPlanId;
plan.active = true;
plan.status = "open";
plan.dateAdd = DateTime.now();
TrainingPlan? trainingPlan = this.getTrainingPlanById(trainingPlanId);
if (trainingPlan == null || trainingPlan.details == null) {
print("trainingPlan null");
return null;
}
plan.name = trainingPlan.nameTranslations[AppLanguage().appLocal.toString()];
// 3 calculate weights
int index = 0;
int exerciseTypeIdOrig = 0;
trainingPlan.details!.forEach((elem) {
List<CustomerTrainingPlanDetails> list = createDetail(plan, elem, exerciseTypeIdOrig, index);
exerciseTypeIdOrig = elem.exerciseTypeId;
list.forEach((element) {
plan.details.add(element);
index++;
});
});
Cache().myTrainingPlan = plan;
return plan;
}
CustomerTrainingPlanDetails? getDetailById(CustomerTrainingPlan? plan, int customerTrainingPlanDetailsId) {
CustomerTrainingPlanDetails? foundDetail;
if (plan == null || plan.details.length == 0 || customerTrainingPlanDetailsId == 0) {
return foundDetail;
}
for (var detail in plan.details) {
if (detail.customerTrainingPlanDetailsId == customerTrainingPlanDetailsId) {
foundDetail = detail;
break;
}
}
return foundDetail;
}
CustomerTrainingPlanDetails createAlternativeDetail(
CustomerTrainingPlan plan, CustomerTrainingPlanDetails detail, TrainingPlanDetail elem, int exerciseTypeId) {
CustomerTrainingPlanDetails alternativeDetail = CustomerTrainingPlanDetails();
alternativeDetail.copy(detail);
alternativeDetail.exerciseTypeId = exerciseTypeId;
alternativeDetail.exerciseType = Cache().getExerciseTypeById(exerciseTypeId);
if (elem.weight == -1) {
if (alternativeDetail.exerciseType!.unitQuantityUnit != null) {
alternativeDetail = getCalculatedWeightRepeats(elem.exerciseTypeId, alternativeDetail);
} else {
alternativeDetail.weight = 0;
}
} else if (elem.weight == -2) {
final CustomerTrainingPlanDetails calculated = this.isWeightCalculatedByExerciseType(elem.exerciseTypeId, alternativeDetail, plan);
if (calculated.weight != -1) {
alternativeDetail.weight = calculated.weight;
} else {
alternativeDetail.weight = -2;
}
} else {
alternativeDetail.weight = elem.weight;
}
//print("Detail $alternativeDetail exerciseType: ${alternativeDetail.exerciseType!.exerciseTypeId}");
return alternativeDetail;
}
List<CustomerTrainingPlanDetails> createDetail(CustomerTrainingPlan plan, TrainingPlanDetail elem, int exerciseTypeIdOrig, int index,
{bool changeExerciseType = false}) {
List<CustomerTrainingPlanDetails> list = [];
CustomerTrainingPlanDetails detail = CustomerTrainingPlanDetails();
detail.customerTrainingPlanDetailsId = ++index;
detail.trainingPlanDetailsId = elem.trainingPlanDetailId;
detail.exerciseTypeId = changeExerciseType ? exerciseTypeIdOrig : elem.exerciseTypeId;
detail.repeats = elem.repeats;
detail.set = elem.set;
detail.dayId = elem.dayId;
TrainingPlanDayRepository trainingPlanDayRepository = TrainingPlanDayRepository();
detail.day = trainingPlanDayRepository.getNameById(elem.dayId);
detail.parallel = elem.parallel;
detail.restingTime = elem.restingTime;
detail.exerciseType = Cache().getExerciseTypeById(detail.exerciseTypeId!);
detail.alternatives = ExerciseTypeRepository.getExerciseTypeAlternatives(detail.exerciseTypeId);
if (elem.weight == -1) {
if (detail.exerciseType!.unitQuantityUnit != null) {
detail = getCalculatedWeightRepeats(elem.exerciseTypeId, detail);
} else {
detail.weight = 0;
}
} else if (elem.weight == -2) {
final CustomerTrainingPlanDetails calculated = this.isWeightCalculatedByExerciseType(elem.exerciseTypeId, detail, plan);
if (calculated.weight != -1) {
detail.weight = calculated.weight;
} else {
detail.weight = -2;
}
} else {
detail.weight = elem.weight;
}
print("Detail $detail exerciseType: ${detail.exerciseType!.exerciseTypeId}");
detail.state = ExercisePlanDetailState.start;
if (detail.weight != null && detail.weight! > 0) {
detail.baseOneRepMax = calculate1RM(detail.weight!, detail.repeats!.toDouble());
}
// first repeat: 50% more
if (detail.weight != null && detail.weight! > 0 && exerciseTypeIdOrig != detail.exerciseTypeId && detail.repeats! > 0) {
CustomerTrainingPlanDetails firstDetail = CustomerTrainingPlanDetails();
firstDetail.copy(detail);
firstDetail.repeats = (detail.repeats! * 1.5).round();
firstDetail.baseOneRepMax = calculate1RM(firstDetail.weight!, firstDetail.repeats!.toDouble());
firstDetail.set = 1;
detail.set = detail.set! - 1;
if (detail.set! > 0) {
index++;
}
detail.customerTrainingPlanDetailsId = index;
list.add(firstDetail);
}
if (detail.set! > 0) {
list.add(detail);
}
return list;
}
CustomerTrainingPlanDetails isWeightCalculatedByExerciseType(int exerciseTypeId, CustomerTrainingPlanDetails detail, CustomerTrainingPlan plan) {
CustomerTrainingPlanDetails calculated = detail;
for (var element in plan.details) {
if (element.exerciseTypeId == exerciseTypeId) {
calculated = element;
break;
}
}
return calculated;
}
TrainingPlan? getTrainingPlanById(int trainingPlanId) {
TrainingPlan? plan;
if (Cache().getTrainingPlans() == null) {
return plan;
}
for (var trainingPlan in Cache().getTrainingPlans()!) {
if (trainingPlan.trainingPlanId == trainingPlanId) {
plan = trainingPlan;
break;
}
}
return plan;
}
int? getTrainingPlanByInternalName(String internalName) {
int? id;
if (Cache().getTrainingPlans() == null) {
return id;
}
for (var trainingPlan in Cache().getTrainingPlans()!) {
//print("internal ${trainingPlan.internalName}");
if (trainingPlan.internalName == internalName) {
id = trainingPlan.trainingPlanId;
break;
}
}
return id;
}
CustomerTrainingPlanDetails getCalculatedWeightRepeats(int exerciseTypeId, CustomerTrainingPlanDetails detail) {
double weight = -1;
if (Cache().getExercises() == null) {
detail.weight = weight;
detail.isTest = true;
return detail;
}
Exercise? lastExercise1RM;
DateTime dt = DateTime.now().subtract(Duration(days: 30));
List<Exercise> exercises = Cache().getExercises()!;
exercises.sort((a, b) {
// reverse
return a.dateAdd!.compareTo(b.dateAdd!);
});
exercises.forEach((exercise) {
if (exercise.exerciseTypeId == exerciseTypeId && exercise.dateAdd!.compareTo(dt) >= 0) {
detail.weight = weight;
lastExercise1RM = exercise;
//print("last exercise: $exercise");
}
});
if (lastExercise1RM == null || lastExercise1RM!.unitQuantity == null) {
detail.weight = weight;
detail.isTest = true;
return detail;
}
double oneRepMax = calculateMax1RMSameDay(lastExercise1RM!);
// Common.calculate1RM(lastExercise1RM!.unitQuantity!, lastExercise1RM!.quantity!);
//print("Exercise $exerciseTypeId - 1RM : $oneRepMax");
weight = oneRepMax * Common.get1RMPercent(detail.repeats!);
//print("Exercise $exerciseTypeId - weight : $weight");
//weight = Common.roundWeight(weight);
//detail.weight = Common.calculateWeigthByChangedQuantity(detail.weight!, detail.repeats!.toDouble(), lastExercise1RM!.quantity!);
//weight = lastExercise1RM!.unitQuantity! * detail.repeats! / lastExercise1RM!.quantity!;
weight = Common.roundWeight(weight);
//print("Recaluclated weight ${detail.weight} - repeat: ${detail.repeats}");
//detail.repeats = Common.calculateQuantityByChangedWeight(oneRepMax, weight, detail.repeats!.toDouble());
detail.weight = weight;
return detail;
}
double calculateMax1RMSameDay(Exercise actual) {
List<Exercise> exercises = Cache().getExercises()!;
double max1RM = 0.0;
exercises.forEach((exercise) {
if (actual.exerciseTypeId == exercise.exerciseTypeId &&
actual.dateAdd!.year == exercise.dateAdd!.year &&
actual.dateAdd!.month == exercise.dateAdd!.month &&
actual.dateAdd!.day == exercise.dateAdd!.day) {
double oneRepMax = calculate1RM(exercise.unitQuantity!, exercise.quantity!);
if (max1RM < oneRepMax) {
max1RM = oneRepMax;
}
}
});
return max1RM;
}
int getOriginalRepeats(int trainingPlanId, CustomerTrainingPlanDetails detail) {
TrainingPlan? plan = getTrainingPlanById(trainingPlanId);
if (plan == null) {
return 0;
}
int originalRepeats = 0;
plan.details!.forEach((element) {
if (element.trainingPlanDetailId == detail.trainingPlanDetailsId) {
originalRepeats = element.repeats ?? 0;
}
});
return originalRepeats;
}
double getOriginalWeight(int trainingPlanId, CustomerTrainingPlanDetails detail) {
TrainingPlan? plan = getTrainingPlanById(trainingPlanId);
if (plan == null) {
return 0;
}
double originalWeight = 0;
plan.details!.forEach((element) {
if (element.trainingPlanDetailId == detail.trainingPlanDetailsId) {
originalWeight = element.weight ?? 0;
}
});
return originalWeight;
}
CustomerTrainingPlanDetails recalculateDetailFixRepeats(int trainingPlanId, CustomerTrainingPlanDetails detail) {
TrainingPlan? plan = getTrainingPlanById(trainingPlanId);
if (plan == null) {
return detail;
}
int originalRepeats = getOriginalRepeats(trainingPlanId, detail);
detail.weight = Common.calculateWeigthByChangedQuantity(detail.weight!, detail.repeats!.toDouble(), originalRepeats.toDouble());
detail.weight = Common.roundWeight(detail.weight!);
print("Recalculated weight: ${detail.weight}");
detail.repeats = originalRepeats;
return detail;
}
CustomerTrainingPlanDetails recalculateDetailFixRepeatsSet1(
int trainingPlanId, CustomerTrainingPlanDetails detail, CustomerTrainingPlanDetails detailWithData) {
TrainingPlan? plan = getTrainingPlanById(trainingPlanId);
if (plan == null) {
return detail;
}
int originalRepeats = getOriginalRepeats(trainingPlanId, detail);
detail.weight = Common.calculateWeigthByChangedQuantity(detailWithData.weight!, detailWithData.repeats!.toDouble(), originalRepeats.toDouble());
detail.weight = Common.roundWeight(detail.weight!);
print("Recalculated weight: ${detail.weight}");
detail.repeats = originalRepeats;
return detail;
}
CustomerTrainingPlanDetails recalculateDetail(int trainingPlanId, CustomerTrainingPlanDetails detail, CustomerTrainingPlanDetails nextDetail) {
CustomerTrainingPlanDetails recalculatedDetail = nextDetail;
// 1. get original repeats
// 1a get original plan
TrainingPlan? plan = getTrainingPlanById(trainingPlanId);
if (plan == null) {
return recalculatedDetail;
}
// 1.b get the original detail's repeat
int originalRepeats = detail.repeats!;
plan.details!.forEach((element) {
if (element.trainingPlanDetailId == detail.trainingPlanDetailsId) {
originalRepeats = element.repeats ?? 0;
}
});
// 2 get recalculated repeats
recalculatedDetail.weight = Common.calculateWeigthByChangedQuantity(detail.weight!, detail.repeats!.toDouble(), originalRepeats.toDouble());
recalculatedDetail.weight = Common.roundWeight(recalculatedDetail.weight!);
print("recalculated repeats for $originalRepeats: ${recalculatedDetail.weight}");
//recalculatedDetail.repeats = originalRepeats;
return recalculatedDetail;
}
void generateTrainingPlan() {
int? trainingPlanId;
if (Cache().userLoggedIn == null) {
return;
}
bool isWoman = Cache().userLoggedIn!.sex == "w";
if (Cache().userLoggedIn!.goal == "shape_forming") {
if (Cache().userLoggedIn!.fitnessLevel == FitnessState.beginner) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("women_shape_L1") : getTrainingPlanByInternalName("man_routine1");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.intermediate) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("women_shape_L2") : getTrainingPlanByInternalName("man_routine3");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.advanced) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("women_shape_L3") : getTrainingPlanByInternalName("man_routine4");
} else {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("women_shape_L4") : getTrainingPlanByInternalName("man_routine2");
}
} else if (Cache().userLoggedIn!.goal == "muscle_endurance") {
if (Cache().userLoggedIn!.fitnessLevel == FitnessState.beginner) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_se_l1") : getTrainingPlanByInternalName("man_se_l1");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.intermediate) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_se_l2") : getTrainingPlanByInternalName("man_se_l2");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.advanced) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_se_l3") : getTrainingPlanByInternalName("man_se_l3");
} else {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_se_l4") : getTrainingPlanByInternalName("man_se_l4");
}
} else if (Cache().userLoggedIn!.goal == "gain_strength") {
if (Cache().userLoggedIn!.fitnessLevel == FitnessState.beginner) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_power_l1") : getTrainingPlanByInternalName("man_power_l1");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.intermediate) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_power_l2") : getTrainingPlanByInternalName("man_power_l2");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.advanced) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_power_l3") : getTrainingPlanByInternalName("man_power_l3");
} else {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_power_l4") : getTrainingPlanByInternalName("man_power_l4");
}
} else if (Cache().userLoggedIn!.goal == "gain_muscle") {
if (Cache().userLoggedIn!.fitnessLevel == FitnessState.beginner) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("woman_beginner") : getTrainingPlanByInternalName("beginner_man");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.intermediate) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("woman_beginner_split") : getTrainingPlanByInternalName("man_foundation");
} else if (Cache().userLoggedIn!.fitnessLevel == FitnessState.advanced) {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("woman_advanced") : getTrainingPlanByInternalName("basic_mass_building");
} else {
trainingPlanId = isWoman ? getTrainingPlanByInternalName("man_routine2") : getTrainingPlanByInternalName("mass_building");
}
}
print("Generated plan $trainingPlanId fitness ${Cache().userLoggedIn!.fitnessLevel} - ${FitnessState.beginner}");
if (trainingPlanId != null) {
CustomerTrainingPlan? customerTrainingPlan = activateTrainingPlan(trainingPlanId);
if (customerTrainingPlan != null) {
Cache().myTrainingPlan = customerTrainingPlan;
Cache().saveMyTrainingPlan();
}
}
}
}
+224
View File
@@ -0,0 +1,224 @@
import 'package:workouttest_util/model/cache.dart';
import 'package:workouttest_util/model/user.dart';
import 'package:workouttest_util/service/customer_service.dart';
import 'package:workouttest_util/service/firebase_api.dart';
import 'package:workouttest_util/util/logging.dart';
import 'package:workouttest_util/util/not_found_exception.dart';
import 'package:firebase_auth/firebase_auth.dart' as auth;
class UserRepository with Logging {
late User user;
UserRepository() {
this.createNewUser();
}
setEmail(String email) {
this.user.email = email;
}
setPassword(String password) {
this.user.password = password;
}
createNewUser() {
this.user = User();
}
Future<void> addUser() async {
final User modelUser = this.user;
try {
String rc = await FirebaseApi().registerEmail(modelUser.email!, modelUser.password!);
if (rc == FirebaseApi.SIGN_IN_OK) {
modelUser.firebaseUid = Cache().firebaseUid;
await CustomerApi().addUser(modelUser);
}
} catch (e) {
final String message = e.toString();
log(message);
if (message.contains("CERT_ALREADY_IN_HASH_TABLE")) {
} else {
throw new Exception(e);
}
}
}
Future<void> addUserFB() async {
final User modelUser = this.user;
try {
Map<String, dynamic> userData = await FirebaseApi().registerWithFacebook();
modelUser.email = userData['email'];
if (modelUser.email == null) {
throw new Exception("Facebook signup was not successful. Please try another method");
}
modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid;
await CustomerApi().addUser(modelUser);
} on auth.FirebaseAuthException catch (e) {
if (e.code == 'email-already-in-use') {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
} else if (e.code == 'weak-password') {
log('The password provided is too weak.');
throw Exception("Password too short");
} else if (e.code == 'account-exists-with-different-credential') {
log(e.code);
throw Exception("The account exists with different credential");
} else {
print(e.code);
throw Exception(e);
}
} on WorkoutTestException catch (ex) {
if (ex.code == WorkoutTestException.CUSTOMER_EXISTS) {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
}
} on Exception catch (ex) {
log("FB exception: " + ex.toString());
throw Exception("Facebook Sign In failed");
}
}
Future<void> addUserGoogle() async {
final User modelUser = this.user;
try {
Map<String, dynamic> userData = await FirebaseApi().registerWithGoogle();
modelUser.email = userData['email'];
if (modelUser.email == null) {
throw new Exception("Google signup was not successful. Please try another method");
}
modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid;
await CustomerApi().addUser(modelUser);
} on auth.FirebaseAuthException catch (e) {
if (e.code == 'email-already-in-use') {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
} else {
throw Exception(e);
}
} on WorkoutTestException catch (ex) {
if (ex.code == WorkoutTestException.CUSTOMER_EXISTS) {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
}
} on Exception catch (ex) {
log("Google exception: " + ex.toString());
throw Exception("Google Sign In failed");
}
}
Future<void> addUserApple() async {
final User modelUser = this.user;
try {
Map<String, dynamic> userData = await FirebaseApi().registerWithApple();
modelUser.email = userData['email'];
if (modelUser.email == null) {
throw new Exception("Apple signup was not successful. Please try another method");
}
modelUser.password = Cache().firebaseUid;
modelUser.firebaseUid = Cache().firebaseUid;
await CustomerApi().addUser(modelUser);
} on auth.FirebaseAuthException catch (e) {
if (e.code == 'email-already-in-use') {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
}
} on WorkoutTestException catch (ex) {
if (ex.code == WorkoutTestException.CUSTOMER_EXISTS) {
log('The account already exists for that email.');
throw Exception("The email address has been registered already");
}
} on Exception catch (ex) {
log("Apple exception: " + ex.toString());
throw Exception(ex);
}
}
Future<void> getUserByFB() async {
final User modelUser = this.user;
try {
Map<String, dynamic> userData = await FirebaseApi().signInWithFacebook();
modelUser.email = userData['email'];
await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin();
} /* on FacebookAuthException catch (e) {
switch (e.errorCode) {
case FacebookAuthErrorCode.OPERATION_IN_PROGRESS:
throw Exception("You have a previous Facebook login operation in progress");
break;
case FacebookAuthErrorCode.CANCELLED:
throw Exception("Facebook login cancelled");
break;
case FacebookAuthErrorCode.FAILED:
throw Exception("Facebook login failed");
break;
}
} */
on NotFoundException catch (ex) {
log("FB exception: " + ex.toString());
throw Exception("Customer does not exist or the password is wrong");
} on Exception catch (e) {
log(e.toString());
throw new Exception(e);
}
}
Future<void> getUserByGoogle() async {
final User modelUser = this.user;
try {
Map<String, dynamic> userData = await FirebaseApi().signInWithGoogle();
if (userData['email'] == null) {
throw new Exception("Google login was not successful");
}
modelUser.email = userData['email'];
await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin();
} on Exception catch (ex) {
log("Google exception: " + ex.toString());
throw Exception(ex);
}
}
Future<void> getUserByApple() async {
final User modelUser = this.user;
Map<String, dynamic> userData = await FirebaseApi().signInWithApple();
if (userData['email'] == null) {
throw new Exception("Apple login was not successful");
}
modelUser.email = userData['email'];
try {
await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin();
} on Exception catch (ex) {
log("Apple exception: " + ex.toString());
throw Exception("Customer does not exist or the password is wrong");
}
}
Future<void> getUser() async {
final User modelUser = this.user;
String rc = await FirebaseApi().signInEmail(modelUser.email, modelUser.password);
try {
if (rc == FirebaseApi.SIGN_IN_OK) {
await CustomerApi().getUserByEmail(modelUser.email!);
await Cache().afterFirebaseLogin();
} else {
log("Exception: user not found or password is wrong");
throw Exception("Customer does not exist or the password is wrong");
}
} on NotFoundException catch (_) {
throw Exception("Customer does not exist or the password is wrong");
}
}
Future<void> resetPassword() async {
final User modelUser = this.user;
await FirebaseApi().resetPassword(modelUser.email!);
}
}