Modification of the Treasure Model and new validations
Here is the lesson code:
Model Treasure {
String name
Double latitude
Double longitude
Integer points
Bool hasBeenFound value(false)
User creator
User win
Array participants
}
Module Accounts {
User getLocalPersistedUser () {
User user
if (broker.localPersistence.hasKey("loggedUserName")) {
user = User()
user.name = broker.localPersistence.get("loggedUserName")
user.score = broker.localPersistence.get("loggedUserScore")
user.password = broker.localKeychain.get("loggedUserPassword")
user = Accounts.performLogin(user.name, user.password)
}
return user
}
Bool validateTreasureName (String treasureName) {
Filter filter = Filter(modelName: "Treasure")
filter.equalTo("name", treasureName)
Array treasures = broker.cloudPersistence.getWithFilter(filter)
if (treasures.size() > 0) {
return false
}
return true
}
}
RuleContext CreateTreasureContext {
Rule createTreasure {
CreateTreasure ct = broker.ui.getDataSource()
if (ct.name != null && ct.name != “” && ct.latitude != null && ct.longitude != null && ct.points.selected().size() > 0) {
if (Accounts.validateTreasureName(ct.name)) {
Treasure newTreasure = Treasure()
newTreasure.name = ct.name
newTreasure.latitude = ct.latitude
newTreasure.longitude = ct.longitude
newTreasure.creator = loggedUser
Integer index = ct.points.selected().get(0)
newTreasure.points = ct.points.get(index)
broker.cloudPersistence.save(newTreasure)
broker.ui.showAlert(“Yeah!”, "Thanks for adding a new treasure.")
} else {
broker.ui.showAlert("Oops", "Please select a different name, this name is already in use.")
}
} else {
broker.ui.showAlert("Oops", "Please, complete all the fields.")
}
}
}
Module Accounts {
User performLogin (String username, String password) {
if (username == null || username.trim().length() < 1) {
broker.ui.showAlert(“Oops”, 'Please enter your username.')
return null
}
if (password == null || password.length() < 1) {
broker.ui.showAlert(“Oops”, “Please enter your password.”)
return null
}
Filter userNameFilter = Filter(modelName: "User")
userNameFilter.equalTo("name", username.trim())
Array existingUsers = broker.cloudPersistence.getWithFilter(userNameFilter)
if (existingUsers.size() == 0) {
broker.ui.showAlert(“Oops”, "There's no user with username: " + username)
Accounts.removeLocalPersistedUser()
return null
}
User user = existingUsers.get(0)
if (user.password != password) {
broker.ui.showAlert(“Oops”, "The password you have entered is wrong.")
Accounts.removeLocalPersistedUser()
return null
}
return user
}
}
Application {
Array treasureScores
User loggedUser
OnInit {
treasureScores = [10, 20, 30, 50, 100]
broker.ui.push("Login")
loggedUser = Accounts.getLocalPersistedUser()
if (loggedUser != null) {
Accounts.navigateToMainMenu()
}
}
}