Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/OpenBankProject/OBP-API
Browse files Browse the repository at this point in the history
…into develop
  • Loading branch information
simonredfern committed Jul 6, 2016
2 parents 58b64e4 + fe685ed commit e5cc818
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 45 deletions.
13 changes: 11 additions & 2 deletions src/main/scala/code/api/v2_0_0/APIMethods200.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1549,13 +1549,20 @@ trait APIMethods200 {
for {
u <- user ?~! "User must be logged in to post Customer" // TODO. CHECK user has role to create a customer / create a customer for another user id.
bank <- Bank(bankId) ?~! {ErrorMessages.BankNotFound}
canCreateCustomer <- Entitlement.entitlement.vend.getEntitlement(bank.bankId.value, u.userId, CanCreateCustomer.toString) ?~ {ErrorMessages.UserDoesNotHaveRole + CanCreateCustomer +"."}
postedData <- tryo{json.extract[CreateCustomerJson]} ?~! ErrorMessages.InvalidJsonFormat
isLoggedUser <- booleanToBox(postedData.user_id.nonEmpty == false || postedData.user_id.equalsIgnoreCase(u.userId)) ?~ "User can create a customer for themself only"
canCreateCustomer <- tryo(hasEntitlement(bank.bankId.value, u.userId, CanCreateCustomer))
isLoggedUser <- booleanToBox(postedData.user_id.nonEmpty == false || canCreateCustomer == true || postedData.user_id.equalsIgnoreCase(u.userId)) ?~ "User can create a customer for themself only"
checkAvailable <- tryo(assert(Customer.customerProvider.vend.checkCustomerNumberAvailable(bankId, postedData.customer_number) == true)) ?~! ErrorMessages.CustomerNumberAlreadyExists
// TODO The user id we expose should be a uuid . For now we have a long direct from the database.
user_id <- tryo (if (postedData.user_id.nonEmpty) postedData.user_id else u.userId) ?~ s"Problem getting user_id"
customer_user <- User.findByUserId(user_id) ?~! ErrorMessages.UserNotFoundById
userCustomerLinks <- UserCustomerLink.userCustomerLink.vend.getUserCustomerLinks
//Find all user to customer links by user_id
userCustomerLinks <- tryo(userCustomerLinks.filter(u => u.userId.equalsIgnoreCase(user_id)))
customerIds: List[String] <- tryo(userCustomerLinks.map(p => p.customerId))
//Try to find an existing customer at BANK_ID
alreadyHasCustomer <-booleanToBox(customerIds.forall(x => Customer.customerProvider.vend.getCustomer(x, bank.bankId).isEmpty == true)) ?~ ErrorMessages.CustomerAlreadyExistsForUser
// TODO we still store the user inside the customer, we should only store the user in the usercustomer link
customer <- booleanToBox(Customer.customerProvider.vend.getCustomer(bankId, customer_user).isEmpty) ?~ ErrorMessages.CustomerAlreadyExistsForUser
customer <- Customer.customerProvider.vend.addCustomer(bankId,
customer_user,
Expand All @@ -1572,6 +1579,8 @@ trait APIMethods200 {
postedData.employment_status,
postedData.kyc_status,
postedData.last_ok_date) ?~! "Could not create customer"
userCustomerLink <- booleanToBox(UserCustomerLink.userCustomerLink.vend.getUserCustomerLink(user_id, customer.customerId).isEmpty == true) ?~ ErrorMessages.CustomerAlreadyExistsForUser
userCustomerLink <- UserCustomerLink.userCustomerLink.vend.createUserCustomerLink(user_id, customer.customerId, exampleDate, true) ?~! "Could not create user_customer_links"
} yield {
val successJson = Extraction.decompose(customer)
successJsonResponse(successJson, 201)
Expand Down
100 changes: 57 additions & 43 deletions src/main/scala/code/bankconnectors/KafkaMappedConnector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@ object KafkaMappedConnector extends Connector with CreateViewImpls with Loggable
}

def setAccountOwner(owner : String, account: KafkaInboundAccount) : Unit = {
logger.error(s"------------> list of all apiusers: ${APIUser.findAll}")
println(s"------------> list of all apiusers: ${APIUser.findAll}")
logger.error(s"------------> owner=${owner}")
println(s"------------> owner=${owner}")
val apiUserOwner = APIUser.findAll.find(user => owner == user.emailAddress)
logger.info(s"------------> list of all apiusers: ${APIUser.findAll}")
logger.info(s"------------> looking for: ${owner}, found: apiUserOwner ${apiUserOwner}")
Expand All @@ -94,50 +90,48 @@ object KafkaMappedConnector extends Connector with CreateViewImpls with Loggable
}
}

def updateUserAccountViews( apiUser: APIUser ) = {
logger.info(s"------------> UPDATING VIEWS")
println(s"------------> UPDATING VIEWS")

def updateSingleAccountViews( user: APIUser, account: KafkaInboundAccount ) = {
val res = {
val views = createSaveableViews(account, account.owners.contains(user.email.get))
views.foreach(_.save())
views.map(_.value).foreach(v => {
Views.views.vend.addPermission(v.uid, user)
logger.info(s"------------> added view: ${v.name}, ${v.uid} for apiuser: ${user} and account ${account}")
})
setAccountOwner(user.email.get, account)
}
res
}

def updateUserAccountViews( user: APIUser ) = {
// Generate random uuid to be used as request-response match id
val reqId: String = UUID.randomUUID().toString
// Create argument list with reqId
// in order to fetch corresponding response
val argList = Map("username" -> apiUser.email.get)
val argList = Map("username" -> user.email.get)
// Since result is single account, we need only first list entry
implicit val formats = net.liftweb.json.DefaultFormats
val rList = {
cachedUserAccounts.getOrElseUpdate( argList.toString, () => process(reqId, "getUserAccounts", argList).extract[List[KafkaInboundAccount]])
}


logger.info(s"------------> userAccounts from Kafka: " + rList)



for (r <- rList) {
logger.info("------------>view " + r + "exists=" + viewExists(r))
}





val res = {
// TODO CHECK
// for (r <- rList if ! viewExists(r)) yield {
for (r <- rList) yield {
val views = createSaveableViews(r)
for (r <- rList) {
val views = createSaveableViews(r, r.owners.contains(user.email.get))
views.foreach(_.save())
views.map(_.value).filterNot(_.isPublic).foreach(v => {
Views.views.vend.addPermission(v.uid, apiUser)
logger.info(s"------------> added view: ${v.uid} for apiuser: ${apiUser}")
Views.views.vend.addPermission(v.uid, user)
logger.info(s"------------> added view: ${v.name}, ${v.uid} for apiuser: ${user}")
})
setAccountOwner(apiUser.email.get, r)
setAccountOwner(user.email.get, r)
}
}
res
}

def updatePublicAccountViews( user: APIUser ): List[List[Saveable[ViewType]]] = {
def updatePublicAccountViews( user: APIUser ) = {
// Generate random uuid to be used as request-response match id
val reqId: String = UUID.randomUUID().toString
// Create argument list with reqId
Expand All @@ -147,53 +141,66 @@ object KafkaMappedConnector extends Connector with CreateViewImpls with Loggable
val rList = {
cachedPublicAccounts.getOrElseUpdate( argList.toString, () => process(reqId, "getPublicAccounts", argList).extract[List[KafkaInboundAccount]])
}

logger.info(s"------------> publicAccounts from Kafka: " + rList)

val res = {
for (r <- rList if ! viewExists(r)) yield {
val views = createSaveableViews(r)
for (r <- rList) {
val views = createSaveableViews(r, ! r.owners.contains(user.email.get))
views.foreach(_.save())
views
}
}
res
}

// TODO check me ! (no view name)
def viewExists(acc: KafkaInboundAccount): Boolean = {
def viewExists(acc: KafkaInboundAccount, name: String): Boolean = {
//logger.info(s"------------> all views: " + ViewImpl.findAll)
val res = ViewImpl.findAll.filter { v =>
if (v.bankPermalink.get == acc.bank && v.accountPermalink.get == acc.id)
if (v.bankPermalink.get == acc.bank &&
v.accountPermalink.get == acc.id &&
v.name_ == name)
true
else
false
}
res.nonEmpty
}

def createSaveableViews(acc : KafkaInboundAccount) : List[Saveable[ViewType]] = {

def createSaveableViews(acc : KafkaInboundAccount, owner: Boolean = false) : List[Saveable[ViewType]] = {
logger.info(s"Kafka createSaveableViews acc is $acc")
val bankId = BankId(acc.bank)
val accountId = AccountId(acc.id)

val ownerView = createSaveableOwnerView(bankId, accountId)
val ownerView =
if(owner && ! viewExists(acc, "Owner")) Some(createSaveableOwnerView(bankId, accountId))
else None

logger.info(s"Kafka createSaveableViews ownerView is $ownerView")

val publicView =
if(acc.generate_public_view) Some(createSaveablePublicView(bankId, accountId))
if(acc.generate_public_view && ! viewExists(acc, "Public")) {
logger.info("Creating public view")
Some(createSaveablePublicView(bankId, accountId))
}
else None

val accountantsView =
if(acc.generate_accountants_view) Some(createSaveableAccountantsView(bankId, accountId))
if(acc.generate_accountants_view && ! viewExists(acc, "Accountant")) {
logger.info("Creating accountants view")
Some(createSaveableAccountantsView(bankId, accountId))
}
else None

val auditorsView =
if(acc.generate_auditors_view) Some(createSaveableAuditorsView(bankId, accountId))
if(acc.generate_auditors_view && ! viewExists(acc, "Auditor") ) {
logger.info("Creating auditors view")
Some(createSaveableAuditorsView(bankId, accountId))
}
else None




List(Some(ownerView), publicView, accountantsView, auditorsView).flatten
List(ownerView, publicView, accountantsView, auditorsView).flatten
}

//gets banks handled by this connector
Expand Down Expand Up @@ -320,7 +327,14 @@ object KafkaMappedConnector extends Connector with CreateViewImpls with Loggable
cachedAccount.getOrElseUpdate( argList.toString, () => process(reqId, "getBankAccount", argList).extract[KafkaInboundAccount])
}
val res = new KafkaBankAccount(r)
Full(res)
for {
e <- tryo{OBPUser.getCurrentUserUsername}
u <- OBPUser.getApiUserByEmail(e)
}
yield {
updateSingleAccountViews(u, r)
}
Full(res)
}

override def getBankAccounts(accts: List[(BankId, AccountId)]): List[KafkaBankAccount] = {
Expand Down
2 changes: 2 additions & 0 deletions src/main/scala/code/customer/CustomerProvider.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ trait CustomerProvider {

def getCustomerByCustomerId(customerId: String): Box[Customer]

def getCustomer(customerId: String, bankId : BankId): Box[Customer]

def getUser(bankId : BankId, customerNumber : String) : Box[User]

def checkCustomerNumberAvailable(bankId : BankId, customerNumber : String) : Boolean
Expand Down
7 changes: 7 additions & 0 deletions src/main/scala/code/customer/MappedCustomerProvider.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ object MappedCustomerProvider extends CustomerProvider {
)
}

override def getCustomer(customerId: String, bankId : BankId): Box[Customer] = {
MappedCustomer.find(
By(MappedCustomer.mCustomerId, customerId),
By(MappedCustomer.mBank, bankId.value)
)
}

override def getUser(bankId: BankId, customerNumber: String): Box[User] = {
MappedCustomer.find(
By(MappedCustomer.mBank, bankId.value),
Expand Down
5 changes: 5 additions & 0 deletions src/test/scala/code/api/v1_4_0/CustomerTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ class CustomerTest extends V140ServerSetup with DefaultUsers {
else Empty
}

override def getCustomer(customerId: String, bankId: BankId): Box[Customer] = {
if(customerId == mocCustomerId && bankId == mockBankId) Full(mockCustomer)
else Empty
}

override def getUser(bankId: BankId, customerId: String): Box[User] = Empty
override def addCustomer(bankId : BankId, user : User, number : String, legalName : String, mobileNumber : String, email : String, faceImage: CustomerFaceImage,
dateOfBirth: Date,
Expand Down

0 comments on commit e5cc818

Please sign in to comment.