diff --git a/obp-api/src/main/resources/ResourceDocs/ResourceDocs-Chinese.json b/obp-api/src/main/resources/ResourceDocs/ResourceDocs-Chinese.json index 0de8d4327..da926e035 100644 --- a/obp-api/src/main/resources/ResourceDocs/ResourceDocs-Chinese.json +++ b/obp-api/src/main/resources/ResourceDocs/ResourceDocs-Chinese.json @@ -1190,7 +1190,7 @@ "request_url": "/obp/v2.2.0/message-docs/CONNECTOR", "summary": "获取消息文档", "description": "映射(类型->字符串)", - "description_markdown": "These message docs provide example messages sent by OBP to the (Kafka) message queue for processing by the Core Banking / Payment system Adapter - together with an example expected response and possible error codes.\n Integrators can use these messages to build Adapters that provide core banking services to OBP.\n\n Note: API Explorer provides a Message Docs page where these messages are displayed.\n \n `CONNECTOR`:kafka_vMar2017 , kafka_vJune2017, kafka_vSept2018 ... \n ", + "description_markdown": "These message docs provide example messages sent by OBP to the (Kafka) message queue for processing by the Core Banking / Payment system Adapter - together with an example expected response and possible error codes.\n Integrators can use these messages to build Adapters that provide core banking services to OBP.\n\n Note: API Explorer provides a Message Docs page where these messages are displayed.\n \n `CONNECTOR`: kafka_vSept2018 ... \n ", "example_request_body": { "jsonString": "{}" }, diff --git a/obp-api/src/main/resources/props/sample.props.template b/obp-api/src/main/resources/props/sample.props.template index 2f6815f6f..11100b121 100644 --- a/obp-api/src/main/resources/props/sample.props.template +++ b/obp-api/src/main/resources/props/sample.props.template @@ -14,8 +14,6 @@ ## Which data connector to use, if config `star` as connector, please also check `starConnector_supported_types` connector=mapped #connector=mongodb -#connector=kafka -#conenctor=kafka_vMar2017 #connector=akka_vDec2018 #connector=rest_vMar2019 #connector=stored_procedure_vDec2019 diff --git a/obp-api/src/main/scala/code/api/v2_2_0/APIMethods220.scala b/obp-api/src/main/scala/code/api/v2_2_0/APIMethods220.scala index 8e4969bbe..5ce324627 100644 --- a/obp-api/src/main/scala/code/api/v2_2_0/APIMethods220.scala +++ b/obp-api/src/main/scala/code/api/v2_2_0/APIMethods220.scala @@ -386,7 +386,7 @@ trait APIMethods220 { | | Note: API Explorer provides a Message Docs page where these messages are displayed. | - | `CONNECTOR`:kafka_vMar2017 , kafka_vJune2017, kafka_vSept2018, stored_procedure_vDec2019 ... + | `CONNECTOR`: kafka_vSept2018, stored_procedure_vDec2019 ... """.stripMargin, emptyObjectJson, messageDocsJson, @@ -398,9 +398,8 @@ trait APIMethods220 { case "message-docs" :: connector :: Nil JsonGet _ => { cc => { for { - //kafka_vJune2017 --> vJune2017 : get the valid version for search the connector object. connectorObject <- Future(tryo{Connector.getConnectorInstance(connector)}) map { i => - val msg = "$InvalidConnector Current Input is $connector. It should be eg: kafka_vJune2017, kafka_vSept2018..." + val msg = "$InvalidConnector Current Input is $connector. It should be eg: kafka_vSept2018..." unboxFullOrFail(i, cc.callContext, msg) } } yield { diff --git a/obp-api/src/main/scala/code/bankconnectors/Connector.scala b/obp-api/src/main/scala/code/bankconnectors/Connector.scala index 2e5e9d7e9..aa5b290e2 100644 --- a/obp-api/src/main/scala/code/bankconnectors/Connector.scala +++ b/obp-api/src/main/scala/code/bankconnectors/Connector.scala @@ -20,8 +20,6 @@ import code.bankconnectors.LocalMappedConnector.setUnimplementedError import code.bankconnectors.akka.AkkaConnector_vDec2018 import code.bankconnectors.rest.RestConnector_vMar2019 import code.bankconnectors.storedprocedure.StoredProcedureConnector_vDec2019 -import code.bankconnectors.vJune2017.KafkaMappedConnector_vJune2017 -import code.bankconnectors.vMar2017.KafkaMappedConnector_vMar2017 import code.bankconnectors.vMay2019.KafkaMappedConnector_vMay2019 import code.bankconnectors.vSept2018.KafkaMappedConnector_vSept2018 import code.endpointTag.EndpointTagT @@ -82,9 +80,6 @@ object Connector extends SimpleInjector { "mapped" -> lazyValue(LocalMappedConnector), "akka_vDec2018" -> lazyValue(AkkaConnector_vDec2018), "mongodb" -> lazyValue(LocalRecordConnector), - "kafka" -> lazyValue(KafkaMappedConnector), - "kafka_vMar2017" -> lazyValue(KafkaMappedConnector_vMar2017), - "kafka_vJune2017" -> lazyValue(KafkaMappedConnector_vJune2017), "kafka_vSept2018" -> lazyValue(KafkaMappedConnector_vSept2018), "kafka_vMay2019" -> lazyValue(KafkaMappedConnector_vMay2019), "rest_vMar2019" -> lazyValue(RestConnector_vMar2019), diff --git a/obp-api/src/main/scala/code/bankconnectors/KafkaMappedConnector.scala b/obp-api/src/main/scala/code/bankconnectors/KafkaMappedConnector.scala deleted file mode 100644 index 9186bcddb..000000000 --- a/obp-api/src/main/scala/code/bankconnectors/KafkaMappedConnector.scala +++ /dev/null @@ -1,1410 +0,0 @@ -package code.bankconnectors - -/* -Open Bank Project - API -Copyright (C) 2011-2019, TESOBE GmbH - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see http://www.gnu.org/licenses/. - -Email: contact@tesobe.com -TESOBE GmbH -Osloerstrasse 16/17 -Berlin 13359, Germany -*/ - -import java.util.Date - -import code.api.util.ErrorMessages._ -import com.openbankproject.commons.model.enums.StrongCustomerAuthentication.SCA -import code.api.util._ -import code.bankconnectors.vMar2017.KafkaMappedConnector_vMar2017 -import code.branches.Branches.Branch -import code.fx.fx -import code.kafka.KafkaHelper -import code.management.ImporterAPI.ImporterTransaction -import code.metadata.comments.Comments -import code.metadata.counterparties.Counterparties -import code.metadata.narrative.MappedNarrative -import code.metadata.tags.Tags -import code.metadata.transactionimages.TransactionImages -import code.metadata.wheretags.WhereTags -import code.model._ -import code.model.dataAccess._ -import com.openbankproject.commons.model.Product -import code.transaction.MappedTransaction -import code.transactionrequests.TransactionRequests.TransactionRequestTypes._ -import code.transactionrequests.TransactionRequests._ -import code.transactionrequests.TransactionRequests -import com.openbankproject.commons.model.TransactionRequestTypeCharge -import code.util.Helper.MdcLoggable -import code.util.{Helper, TTLCache} -import code.views.Views -import com.openbankproject.commons.model.{Bank, _} -import net.liftweb.common._ -import net.liftweb.mapper._ -import net.liftweb.util.Helpers._ - -import scala.collection.immutable.{List, Seq} -import com.openbankproject.commons.ExecutionContext.Implicits.global -import com.openbankproject.commons.dto.GetProductsParam - -import scala.concurrent.Future - -object KafkaMappedConnector extends Connector with KafkaHelper with MdcLoggable { - - implicit override val nameOfConnector = KafkaMappedConnector.getClass.getSimpleName - - // Local TTL Cache - val cacheTTL = APIUtil.getPropsValue("connector.cache.ttl.seconds", "10").toInt - val cachedUser = TTLCache[KafkaInboundValidatedUser](cacheTTL) - val cachedBank = TTLCache[KafkaInboundBank](cacheTTL) - val cachedAccount = TTLCache[KafkaInboundAccount](cacheTTL) - val cachedBanks = TTLCache[List[KafkaInboundBank]](cacheTTL) - val cachedAccounts = TTLCache[List[KafkaInboundAccount]](cacheTTL) - val cachedPublicAccounts = TTLCache[List[KafkaInboundAccount]](cacheTTL) - val cachedUserAccounts = TTLCache[List[KafkaInboundAccount]](cacheTTL) - val cachedFxRate = TTLCache[KafkaInboundFXRate](cacheTTL) - val cachedCounterparty = TTLCache[KafkaInboundCounterparty](cacheTTL) - val cachedTransactionRequestTypeCharge = TTLCache[KafkaInboundTransactionRequestTypeCharge](cacheTTL) - - // - // "Versioning" of the messages sent by this or similar connector might work like this: - // Use Case Classes (e.g. KafkaInbound... KafkaOutbound... as below to describe the message structures. - // Probably should be in a separate file e.g. Nov2016_messages.scala - // Once the message format is STABLE, freeze the key/value pair names there. For now, new keys may be added but none modified. - // If we want to add a new message format, create a new file e.g. March2017_messages.scala - // Then add a suffix to the connector value i.e. instead of kafka we might have kafka_march_2017. - // Then in this file, populate the different case classes depending on the connector name and send to Kafka - // - - val formatVersion: String = "Nov2016" - - // TODO Create and use a case class for each Map so we can document each structure. - - - override def getUser( username: String, password: String ): Box[InboundUser] = { - for { - req <- tryo {Map[String, String]( - "north" -> "getUser", - "version" -> formatVersion, // rename version to messageFormat or maybe connector (see above) - "name" -> "get", // For OBP-JVM compatibility but key name will change - "target" -> "user", // For OBP-JVM compatibility but key name will change - "username" -> username, - "password" -> password - )} - u <- tryo{cachedUser.getOrElseUpdate( req.toString, () => process(req).extract[KafkaInboundValidatedUser])} - recUsername <- tryo{u.displayName} - } yield { - if (username == u.displayName) new InboundUser( recUsername, password, recUsername) - else null - } - } - - override def updateUserAccountViewsOld( user: ResourceUser ) = { - val accounts: List[KafkaInboundAccount] = getBanksLegacy(None).map(_._1).openOrThrowException(attemptedToOpenAnEmptyBox).flatMap { bank => { - val bankId = bank.bankId.value - logger.info(s"ObpJvm updateUserAccountViews for user.email ${user.email} user.name ${user.name} at bank ${bankId}") - for { - username <- tryo {user.name} - req <- tryo { Map[String, String]( - "north" -> "getBankAccounts", - "version" -> formatVersion, - "name" -> "get", - "username" -> user.name, - "userId" -> user.userId, - "bankId" -> bankId, - "target" -> "accounts")} - // Generate random uuid to be used as request-response match id - } yield { - cachedUserAccounts.getOrElseUpdate(req.toString, () => process(req).extract[List[KafkaInboundAccount]]) - } - } - }.flatten - - val views = for { - acc <- accounts - username <- tryo {user.name} - views <- tryo {createViews( BankId(acc.bankId), - AccountId(acc.accountId), - acc.owners.contains(username), - acc.generate_public_view, - acc.generate_accountants_view, - acc.generate_auditors_view - )} - existing_views <- tryo {Views.views.vend.assignedViewsForAccount(BankIdAccountId(BankId(acc.bankId), AccountId(acc.accountId)))} - } yield { - setAccountHolder(username, BankId(acc.bankId), AccountId(acc.accountId), acc.owners) - views.foreach(v => { - Views.views.vend.grantAccessToCustomView(v.uid, user) - //logger.info(s"------------> updated view ${v.uid} for resourceuser ${user} and account ${acc}") - }) - existing_views.filterNot(_.users.contains(user.userPrimaryKey)).foreach (v => { - Views.views.vend.grantAccessToCustomView(v.uid, user) - //logger.info(s"------------> added resourceuser ${user} to view ${v.uid} for account ${acc}") - }) - } - } - - - //gets banks handled by this connector - override def getBanksLegacy(callContext: Option[CallContext]) = { - val req = Map( - "north" -> "getBanks", - "version" -> formatVersion, - "name" -> "get", - "target" -> "banks", - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername - ) - - logger.debug(s"Kafka getBanks says: req is: $req") - - logger.debug(s"Kafka getBanks before cachedBanks.getOrElseUpdate") - val rList = { - cachedBanks.getOrElseUpdate( req.toString, () => process(req).extract[List[KafkaInboundBank]]) - } - - logger.debug(s"Kafka getBanks says rList is $rList") - - // Loop through list of responses and create entry for each - val res = { for ( r <- rList ) yield { - new KafkaBank(r) - } - } - // Return list of results - - logger.debug(s"Kafka getBanks says res is $res") - Full(res, callContext) - } - - // Gets current challenge level for transaction request - override def getChallengeThreshold(bankId: String, accountId: String, viewId: String, transactionRequestType: String, currency: String, userId: String, username: String, callContext: Option[CallContext]) = Future{ - // Create argument list - val req = Map( - "north" -> "getChallengeThreshold", - "action" -> "obp.getChallengeThreshold", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "bankId" -> bankId, - "accountId" -> accountId, - "viewId" -> viewId, - "transactionRequestType" -> transactionRequestType, - "currency" -> currency, - "userId" -> userId, - "username" -> username - ) - val r: Option[KafkaInboundChallengeLevel] = process(req).extractOpt[KafkaInboundChallengeLevel] - // Return result - r match { - // Check does the response data match the requested data - case Some(x) => (Full(AmountOfMoney(x.currency, x.limit)), callContext) - case _ => { - val limit = BigDecimal("0") - val rate = fx.exchangeRate ("EUR", currency, Some(bankId)) - val convertedLimit = fx.convert(limit, rate) - (Full(AmountOfMoney(currency,convertedLimit.toString())), callContext) - } - } - } - - override def getChargeLevel(bankId: BankId, - accountId: AccountId, - viewId: ViewId, - userId: String, - username: String, - transactionRequestType: String, - currency: String, - callContext:Option[CallContext]) = Future{ - // Create argument list - val req = Map( - "north" -> "getChargeLevel", - "action" -> "obp.getChargeLevel", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "bankId" -> bankId.value, - "accountId" -> accountId.value, - "viewId" -> viewId.value, - "transactionRequestType" -> transactionRequestType, - "currency" -> currency, - "userId" -> userId, - "username" -> username - ) - val r: Option[KafkaInboundChargeLevel] = process(req).extractOpt[KafkaInboundChargeLevel] - // Return result - val chargeValue = r match { - // Check does the response data match the requested data - case Some(x) => AmountOfMoney(x.currency, x.amount) - case _ => { - AmountOfMoney("EUR", "0.0001") - } - } - (Full(chargeValue), callContext) - } - - override def createChallenge(bankId: BankId, accountId: AccountId, userId: String, transactionRequestType: TransactionRequestType, transactionRequestId: String, scaMethod: Option[SCA], callContext: Option[CallContext]) = Future { - // Create argument list - val req = Map( - "north" -> "createChallenge", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "bankId" -> bankId.value, - "accountId" -> accountId.value, - "userId" -> userId, - "username" -> AuthUser.getCurrentUserUsername, - "transactionRequestType" -> transactionRequestType.value, - "transactionRequestId" -> transactionRequestId - ) - val r: Option[KafkaInboundCreateChallange] = process(req).extractOpt[KafkaInboundCreateChallange] - // Return result - r match { - // Check does the response data match the requested data - case Some(x) => (Full(x.challengeId), callContext) - case _ => (Empty, callContext) - } - } - - override def validateChallengeAnswer(challengeId: String, hashOfSuppliedAnswer: String, callContext: Option[CallContext]) = Future{ - // Create argument list - val req = Map( - "north" -> "validateChallengeAnswer", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "challengeId" -> challengeId, - "hashOfSuppliedAnswer" -> hashOfSuppliedAnswer - ) - val r: Option[KafkaInboundValidateChallangeAnswer] = process(req).extractOpt[KafkaInboundValidateChallangeAnswer] - // Return result - r match { - // Check does the response data match the requested data - //TODO, error handling, if return the error message, it is not a boolean. - case Some(x) => (Full(x.answer.toBoolean), callContext) - case _ => (Empty, callContext) - } - } - - // Gets bank identified by bankId - override def getBankLegacy(bankId: BankId, callContext: Option[CallContext]) = { - // Create argument list - val req = Map( - "north" -> "getBank", - "version" -> formatVersion, - "name" -> "get", - "target" -> "bank", - "bankId" -> bankId.toString, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername - ) - val r = { - cachedBank.getOrElseUpdate( req.toString, () => process(req).extract[KafkaInboundBank]) - } - // Return result - Full(new KafkaBank(r), callContext) - } - - // Gets transaction identified by bankid, accountid and transactionId - override def getTransactionLegacy(bankId: BankId, accountId: AccountId, transactionId: TransactionId, callContext: Option[CallContext]) = { - val req = Map( - "north" -> "getTransaction", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> "transaction", - "bankId" -> bankId.toString, - "accountId" -> accountId.toString, - "transactionId" -> transactionId.toString - ) - // Since result is single account, we need only first list entry - val r = process(req).extractOpt[KafkaInboundTransaction] - r match { - // Check does the response data match the requested data - case Some(x) if transactionId.value != x.transactionId => Failure(ErrorMessages.InvalidConnectorResponseForGetTransaction, Empty, Empty) - case Some(x) if transactionId.value == x.transactionId => createNewTransaction(x).map(transaction => (transaction, callContext)) - case _ => Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - } - - } - - override def getTransactionsLegacy(bankId: BankId, accountId: AccountId, callContext: Option[CallContext], queryParams: List[OBPQueryParam]) = { - val limit: OBPLimit = queryParams.collect { case OBPLimit(value) => OBPLimit(value) }.headOption.get - val offset = queryParams.collect { case OBPOffset(value) => OBPOffset(value) }.headOption.get - val fromDate = queryParams.collect { case OBPFromDate(date) => OBPFromDate(date) }.headOption.get - val toDate = queryParams.collect { case OBPToDate(date) => OBPToDate(date)}.headOption.get - val ordering = queryParams.collect { - //we don't care about the intended sort field and only sort on finish date for now - case OBPOrdering(field, direction) => OBPOrdering(field, direction)}.headOption.get - val optionalParams = Seq(limit, offset, fromDate, toDate, ordering) - - val req = Map( - "north" -> "getTransactions", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> "transactions", - "bankId" -> bankId.toString, - "accountId" -> accountId.toString, - "queryParams" -> queryParams.toString - ) - val rList = process(req).extract[List[KafkaInboundTransaction]] - // Check does the response data match the requested data - val isCorrect = rList.forall(x=>x.accountId == accountId.value && x.bankId == bankId.value) - if (!isCorrect) throw new Exception(ErrorMessages.InvalidConnectorResponseForGetTransactions) - // Populate fields and generate result - val res = for { - r <- rList - transaction <- createNewTransaction(r) - } yield { - transaction - } - Full(res, callContext) - //TODO is this needed updateAccountTransactions(bankId, accountId) - } - - override def getBankAccountLegacy(bankId: BankId, accountId: AccountId, callContext: Option[CallContext]) = { - // Generate random uuid to be used as request-response match id - val req = Map( - "north" -> "getBankAccount", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> "account", - "bankId" -> bankId.toString, - "accountId" -> accountId.value - ) - // Since result is single account, we need only first list entry - val r = { - cachedAccount.getOrElseUpdate( req.toString, () => process(req).extract[KafkaInboundAccount]) - } - // Check does the response data match the requested data - val accResp = List((BankId(r.bankId), AccountId(r.accountId))).toSet - val acc = List((bankId, accountId)).toSet - if ((accResp diff acc).size > 0) throw new Exception(ErrorMessages.InvalidConnectorResponseForGetBankAccount) - - createMappedAccountDataIfNotExisting(r.bankId, r.accountId, r.label) - - Full(new KafkaBankAccount(r),callContext) - } - - @deprecated("No sense to use list of its to get bankaccount back.","26/04/2019") - def getBankAccounts(accts: List[(BankId, AccountId)]): List[BankAccount] = { - val primaryUserIdentifier = AuthUser.getCurrentUserUsername - - val r:List[KafkaInboundAccount] = accts.flatMap { a => { - - logger.info (s"KafkaMappedConnnector.getBankAccounts with params ${a._1.value} and ${a._2.value} and primaryUserIdentifier is $primaryUserIdentifier") - - val req = Map( - "north" -> "getBankAccounts", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> "accounts", - "bankId" -> a._1.value, - "accountId" -> a._2.value - ) - val r = { - cachedAccounts.getOrElseUpdate( req.toString, () => process(req).extract[List[KafkaInboundAccount]]) - } - r - } - } - - - // Check does the response data match the requested data - val accRes = for(row <- r) yield { - (BankId(row.bankId), AccountId(row.accountId)) - } - if ((accRes.toSet diff accts.toSet).size > 0) throw new Exception(ErrorMessages.InvalidConnectorResponseForGetBankAccounts) - - r.map { t => - createMappedAccountDataIfNotExisting(t.bankId, t.accountId, t.label) - new KafkaBankAccount(t) } - } - - private def getAccountByNumber(bankId : BankId, number : String) : Box[BankAccount] = { - // Generate random uuid to be used as request-respose match id - val req = Map( - "north" -> "getBankAccount", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> "accounts", - "bankId" -> bankId.toString, - "number" -> number - ) - // Since result is single account, we need only first list entry - val r = { - cachedAccount.getOrElseUpdate( req.toString, () => process(req).extract[KafkaInboundAccount]) - } - createMappedAccountDataIfNotExisting(r.bankId, r.accountId, r.label) - Full(new KafkaBankAccount(r)) - } - - /** - * - * refreshes transactions via hbci if the transaction info is sourced from hbci - * - * Checks if the last update of the account was made more than one hour ago. - * if it is the case we put a message in the message queue to ask for - * transactions updates - * - * It will be used each time we fetch transactions from the DB. But the test - * is performed in a different thread. - */ - /* - private def updateAccountTransactions(bankId : BankId, accountId : AccountId) = { - - for { - (bank, _)<- getBank(bankId, None) - account <- getBankAccountType(bankId, accountId) - } { - spawn{ - val useMessageQueue = APIUtil.getPropsAsBoolValue("messageQueue.updateBankAccountsTransaction", false) - val outDatedTransactions = Box!!account.lastUpdate match { - case Full(l) => now after time(l.getTime + hours(APIUtil.getPropsAsIntValue("messageQueue.updateTransactionsInterval", 1))) - case _ => true - } - //if(outDatedTransactions && useMessageQueue) { - // UpdatesRequestSender.sendMsg(UpdateBankAccount(account.number, bank.national_identifier.get)) - //} - } - } - } - */ - - - override def getCounterparty(thisBankId: BankId, thisAccountId: AccountId, couterpartyId: String): Box[Counterparty] = { - //note: kafka mode just used the mapper data - LocalMappedConnector.getCounterparty(thisBankId, thisAccountId, couterpartyId) - } - - // Get one counterparty by the Counterparty Id - override def getCounterpartyByCounterpartyId(counterpartyId: CounterpartyId, callContext: Option[CallContext]) = Future{ - - if (APIUtil.getPropsAsBoolValue("get_counterparties_from_OBP_DB", true)) { - (Counterparties.counterparties.vend.getCounterparty(counterpartyId.value), callContext) - } else { - val req = Map( - "north" -> "getCounterpartyByCounterpartyId", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "action" -> "obp.getCounterpartyByCounterpartyId", - "counterpartyId" -> counterpartyId.toString - ) - // Since result is single account, we need only first list entry - val r = { - cachedCounterparty.getOrElseUpdate( req.toString, () => process(req).extract[KafkaInboundCounterparty]) - } - (tryo(new KafkaCounterparty(r)), callContext) - } - } - - - - - - override def getCounterpartyByIban(iban: String, callContext: Option[CallContext]) = Future { - - if (APIUtil.getPropsAsBoolValue("get_counterparties_from_OBP_DB", true)) { - (Counterparties.counterparties.vend.getCounterpartyByIban(iban), callContext) - } else { - val req = Map( - "north" -> "getCounterpartyByIban", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "get", - "target" -> COUNTERPARTY.toString, - "action" -> "obp.getCounterpartyByIban", - "otherAccountRoutingAddress" -> iban, - "otherAccountRoutingScheme" -> "IBAN" - ) - - val r = process(req).extract[KafkaInboundCounterparty] - - (tryo{KafkaCounterparty(r)}, callContext) - } - } - - protected override def makePaymentImpl(fromAccount: BankAccount, - toAccount: BankAccount, - transactionRequestCommonBody: TransactionRequestCommonBodyJSON, - amt: BigDecimal, - description: String, - transactionRequestType: TransactionRequestType, - chargePolicy: String): Box[TransactionId] = { - - val sentTransactionId = saveTransaction(fromAccount, - toAccount, - transactionRequestCommonBody, - amt, - description, - transactionRequestType, - chargePolicy) - - sentTransactionId - } - - - /** - * Saves a transaction with amount @amount and counterparty @counterparty for account @account. Returns the id - * of the saved transaction. - */ - private def saveTransaction(fromAccount: BankAccount, - toAccount: BankAccount, - transactionRequestCommonBody: TransactionRequestCommonBodyJSON, - amount: BigDecimal, - description: String, - transactionRequestType: TransactionRequestType, - chargePolicy: String) = { - - val transactionTime = now - val currency = fromAccount.currency - - //update the balance of the account for which a transaction is being created - //val newAccountBalance : Long = account.balance.toLong + Helper.convertToSmallestCurrencyUnits(amount, account.currency) - //account.balance = newAccountBalance - - val req: Map[String, String] = Map("north" -> "putTransaction", - "action" -> "obp.putTransaction", - "version" -> formatVersion, - "userId" -> AuthUser.getCurrentResourceUserUserId, - "username" -> AuthUser.getCurrentUserUsername, - "name" -> "put", - "target" -> "transaction", - "description" -> description, - "transactionRequestType" -> transactionRequestType.value, - "toCurrency" -> currency, //Now, http request currency must equal fromAccount.currency - "toAmount" -> amount.toString, - "chargePolicy" -> chargePolicy, - //fromAccount - "fromBankId" -> fromAccount.bankId.value, - "fromAccountId" -> fromAccount.accountId.value, - //toAccount - "toBankId" -> toAccount.bankId.value, - "toAccountId" -> toAccount.accountId.value, - //toCounterty - "toCounterpartyId" -> toAccount.accountId.value, - "toCounterpartyOtherBankRoutingAddress" -> toAccount.bankRoutingAddress, - "toCounterpartyOtherAccountRoutingAddress" -> toAccount.accountRoutings.headOption.map(_.address).getOrElse(""), - "toCounterpartyOtherAccountRoutingScheme" -> toAccount.accountRoutings.headOption.map(_.scheme).getOrElse(""), - "toCounterpartyOtherBankRoutingScheme" -> toAccount.bankRoutingScheme, - "type" -> "AC") - - - // Since result is single account, we need only first list entry - val r = process(req) - - r.extract[KafkaInboundTransactionId] match { - case r: KafkaInboundTransactionId => Full(TransactionId(r.transactionId)) - case _ => Full(TransactionId("0")) - } - - } - - /* - Transaction Requests - */ - override def getTransactionRequestStatusesImpl() : Box[TransactionRequestStatus] ={ - logger.info("Kafka getTransactionRequestStatusesImpl response -- This is KafkaMappedConnector, just call KafkaMappedConnector_vMar2017 methods:") - KafkaMappedConnector_vMar2017.getTransactionRequestStatusesImpl() - } - - override def createTransactionRequestImpl(transactionRequestId: TransactionRequestId, transactionRequestType: TransactionRequestType, - account : BankAccount, counterparty : BankAccount, body: TransactionRequestBody, - status: String, charge: TransactionRequestCharge) : Box[TransactionRequest] = { - TransactionRequests.transactionRequestProvider.vend.createTransactionRequestImpl(transactionRequestId, - transactionRequestType, - account, - counterparty, - body, - status, - charge) - } - - //Note: now call the local mapper to store data - override def saveTransactionRequestTransactionImpl(transactionRequestId: TransactionRequestId, transactionId: TransactionId): Box[Boolean] = { - LocalMappedConnector.saveTransactionRequestTransactionImpl(transactionRequestId: TransactionRequestId, transactionId: TransactionId) - } - - override def saveTransactionRequestChallengeImpl(transactionRequestId: TransactionRequestId, challenge: TransactionRequestChallenge): Box[Boolean] = { - TransactionRequests.transactionRequestProvider.vend.saveTransactionRequestChallengeImpl(transactionRequestId, challenge) - } - - override def saveTransactionRequestStatusImpl(transactionRequestId: TransactionRequestId, status: String): Box[Boolean] = { - TransactionRequests.transactionRequestProvider.vend.saveTransactionRequestStatusImpl(transactionRequestId, status) - } - - - override def getTransactionRequestsImpl(fromAccount : BankAccount) : Box[List[TransactionRequest]] = { - TransactionRequests.transactionRequestProvider.vend.getTransactionRequests(fromAccount.bankId, fromAccount.accountId) - } - - override def getTransactionRequestsImpl210(fromAccount : BankAccount) : Box[List[TransactionRequest]] = { - TransactionRequests.transactionRequestProvider.vend.getTransactionRequests(fromAccount.bankId, fromAccount.accountId) - } - - /* - Bank account creation - */ - - //creates a bank account (if it doesn't exist) and creates a bank (if it doesn't exist) - //again assume national identifier is unique - override def createBankAndAccount( - bankName: String, - bankNationalIdentifier: String, - accountNumber: String, - accountType: String, - accountLabel: String, - currency: String, - accountHolderName: String, - branchId: String, - accountRoutingScheme: String, - accountRoutingAddress: String - ) = { - //don't require and exact match on the name, just the identifier - val bank: Bank = MappedBank.find(By(MappedBank.national_identifier, bankNationalIdentifier)) match { - case Full(b) => - logger.info(s"bank with id ${b.bankId} and national identifier ${b.nationalIdentifier} found") - b - case _ => - logger.info(s"creating bank with national identifier $bankNationalIdentifier") - //TODO: need to handle the case where generatePermalink returns a permalink that is already used for another bank - MappedBank.create - .permalink(Helper.generatePermalink(bankName)) - .fullBankName(bankName) - .shortBankName(bankName) - .national_identifier(bankNationalIdentifier) - .saveMe() - } - - //TODO: pass in currency as a parameter? - val account = createAccountIfNotExisting( - bank.bankId, - AccountId(APIUtil.generateUUID()), - accountNumber, - accountType, - accountLabel, - currency, - 0L, - accountHolderName - ) - - Full((bank, account)) - } - - //for sandbox use -> allows us to check if we can generate a new test account with the given number - override def accountExists(bankId: BankId, accountNumber: String)= { - Full(getAccountByNumber(bankId, accountNumber) != null) - } - - //remove an account and associated transactions - override def removeAccount(bankId: BankId, accountId: AccountId) = { - //delete comments on transactions of this account - val commentsDeleted = Comments.comments.vend.bulkDeleteComments(bankId, accountId) - - //delete narratives on transactions of this account - val narrativesDeleted = MappedNarrative.bulkDelete_!!( - By(MappedNarrative.bank, bankId.value), - By(MappedNarrative.account, accountId.value) - ) - - //delete narratives on transactions of this account - val tagsDeleted = Tags.tags.vend.bulkDeleteTags(bankId, accountId) - - //delete WhereTags on transactions of this account - val whereTagsDeleted = WhereTags.whereTags.vend.bulkDeleteWhereTags(bankId, accountId) - - //delete transaction images on transactions of this account - val transactionImagesDeleted = TransactionImages.transactionImages.vend.bulkDeleteTransactionImage(bankId, accountId) - - //delete transactions of account - val transactionsDeleted = MappedTransaction.bulkDelete_!!( - By(MappedTransaction.bank, bankId.value), - By(MappedTransaction.account, accountId.value) - ) - - //remove view privileges - val privilegesDeleted = Views.views.vend.removeAllPermissions(bankId, accountId) - - //delete views of account - val viewsDeleted = Views.views.vend.removeAllViews(bankId, accountId) - - //delete account - val account = getBankAccountOld(bankId, accountId) - - val accountDeleted = account match { - case acc => true //acc.delete_! //TODO - // case _ => false - } - - Full(commentsDeleted && narrativesDeleted && tagsDeleted && whereTagsDeleted && transactionImagesDeleted && - transactionsDeleted && privilegesDeleted && viewsDeleted && accountDeleted) -} - - //creates a bank account for an existing bank, with the appropriate values set. Can fail if the bank doesn't exist - override def createSandboxBankAccount( - bankId: BankId, - accountId: AccountId, - accountNumber: String, - accountType: String, - accountLabel: String, - currency: String, - initialBalance: BigDecimal, - accountHolderName: String, - branchId: String, - accountRoutings: List[AccountRouting] - ): Box[BankAccount] = { - - for { - (bank, _)<- getBankLegacy(bankId, None) //bank is not really used, but doing this will ensure account creations fails if the bank doesn't - } yield { - - val balanceInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(initialBalance, currency) - createAccountIfNotExisting(bankId, accountId, accountNumber, accountType, accountLabel, currency, balanceInSmallestCurrencyUnits, accountHolderName) - } - - } - - private def createAccountIfNotExisting(bankId: BankId, accountId: AccountId, accountNumber: String, - accountType: String, accountLabel: String, currency: String, - balanceInSmallestCurrencyUnits: Long, accountHolderName: String) : BankAccount = { - getBankAccountOld(bankId, accountId) match { - case Full(a) => - logger.info(s"account with id $accountId at bank with id $bankId already exists. No need to create a new one.") - a - case _ => null //TODO - /* - new KafkaBankAccount - .bank(bankId.value) - .theAccountId(accountId.value) - .accountNumber(accountNumber) - .accountType(accountType) - .accountLabel(accountLabel) - .accountCurrency(currency) - .accountBalance(balanceInSmallestCurrencyUnits) - .holder(accountHolderName) - .saveMe() - */ - } - } - - private def createMappedAccountDataIfNotExisting(bankId: String, accountId: String, label: String) : Boolean = { - MappedBankAccountData.find(By(MappedBankAccountData.accountId, accountId), - By(MappedBankAccountData.bankId, bankId)) match { - case Empty => - val data = new MappedBankAccountData - data.setAccountId(accountId) - data.setBankId(bankId) - data.setLabel(label) - data.save() - true - case _ => - logger.info(s"account data with id $accountId at bank with id $bankId already exists. No need to create a new one.") - false - } - } - - /* - End of bank account creation - */ - - - /* - Transaction importer api - */ - - //used by the transaction import api - override def updateAccountBalance(bankId: BankId, accountId: AccountId, newBalance: BigDecimal) = { - - //this will be Full(true) if everything went well - val result = for { - acc <- getBankAccountOld(bankId, accountId) - (bank, _)<- getBankLegacy(bankId, None) - } yield { - //acc.balance = newBalance - setBankAccountLastUpdated(bank.nationalIdentifier, acc.number, now).openOrThrowException(attemptedToOpenAnEmptyBox) - } - - Full(result.getOrElse(false)) - } - - //transaction import api uses bank national identifiers to uniquely indentify banks, - //which is unfortunate as theoretically the national identifier is unique to a bank within - //one country - private def getBankByNationalIdentifier(nationalIdentifier : String) : Box[Bank] = { - MappedBank.find(By(MappedBank.national_identifier, nationalIdentifier)) - } - - - private val bigDecimalFailureHandler : PartialFunction[Throwable, Unit] = { - case ex : NumberFormatException => { - logger.warn(s"could not convert amount to a BigDecimal: $ex") - } - } - - //used by transaction import api call to check for duplicates - override def getMatchingTransactionCount(bankNationalIdentifier : String, accountNumber : String, amount: String, completed: Date, otherAccountHolder: String) = { - //we need to convert from the legacy bankNationalIdentifier to BankId, and from the legacy accountNumber to AccountId - val count = for { - bankId <- getBankByNationalIdentifier(bankNationalIdentifier).map(_.bankId) - account <- getAccountByNumber(bankId, accountNumber) - amountAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(amount)) - } yield { - - val amountInSmallestCurrencyUnits = - Helper.convertToSmallestCurrencyUnits(amountAsBigDecimal, account.currency) - - MappedTransaction.count( - By(MappedTransaction.bank, bankId.value), - By(MappedTransaction.account, account.accountId.value), - By(MappedTransaction.amount, amountInSmallestCurrencyUnits), - By(MappedTransaction.tFinishDate, completed), - By(MappedTransaction.counterpartyAccountHolder, otherAccountHolder)) - } - - //icky - Full(count.map(_.toInt) getOrElse 0) - } - - //used by transaction import api - override def createImportedTransaction(transaction: ImporterTransaction): Box[Transaction] = { - //we need to convert from the legacy bankNationalIdentifier to BankId, and from the legacy accountNumber to AccountId - val obpTransaction = transaction.obp_transaction - val thisAccount = obpTransaction.this_account - val nationalIdentifier = thisAccount.bank.national_identifier - val accountNumber = thisAccount.number - for { - bank <- getBankByNationalIdentifier(transaction.obp_transaction.this_account.bank.national_identifier) ?~! - s"No bank found with national identifier $nationalIdentifier" - bankId = bank.bankId - account <- getAccountByNumber(bankId, accountNumber) - details = obpTransaction.details - amountAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(details.value.amount)) - newBalanceAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(details.new_balance.amount)) - amountInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(amountAsBigDecimal, account.currency) - newBalanceInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(newBalanceAsBigDecimal, account.currency) - otherAccount = obpTransaction.other_account - mappedTransaction = MappedTransaction.create - .bank(bankId.value) - .account(account.accountId.value) - .transactionType(details.kind) - .amount(amountInSmallestCurrencyUnits) - .newAccountBalance(newBalanceInSmallestCurrencyUnits) - .currency(account.currency) - .tStartDate(details.posted.`$dt`) - .tFinishDate(details.completed.`$dt`) - .description(details.label) - .counterpartyAccountNumber(otherAccount.number) - .counterpartyAccountHolder(otherAccount.holder) - .counterpartyAccountKind(otherAccount.kind) - .counterpartyNationalId(otherAccount.bank.national_identifier) - .counterpartyBankName(otherAccount.bank.name) - .counterpartyIban(otherAccount.bank.IBAN) - .saveMe() - transaction <- mappedTransaction.toTransaction(account) - } yield transaction - } - - override def setBankAccountLastUpdated(bankNationalIdentifier: String, accountNumber : String, updateDate: Date) = { - val result = for { - bankId <- getBankByNationalIdentifier(bankNationalIdentifier).map(_.bankId) - account <- getAccountByNumber(bankId, accountNumber) - } yield { - val acc = getBankAccountOld(bankId, account.accountId) - acc match { - case a => true //a.lastUpdate = updateDate //TODO - // case _ => logger.warn("can't set bank account.lastUpdated because the account was not found"); false - } - } - Full(result.getOrElse(false)) - } - - /* - End of transaction importer api - */ - - - override def updateAccountLabel(bankId: BankId, accountId: AccountId, label: String) = { - //this will be Full(true) if everything went well - val result = for { - acc <- getBankAccountOld(bankId, accountId) - (bank, _)<- getBankLegacy(bankId, None) - d <- MappedBankAccountData.find(By(MappedBankAccountData.accountId, accountId.value), By(MappedBankAccountData.bankId, bank.bankId.value)) - } yield { - d.setLabel(label) - d.save() - } - Full(result.getOrElse(false)) - } - - - override def getProducts(bankId: BankId, params: List[GetProductsParam]): Box[List[Product]] = Empty - - override def getProduct(bankId: BankId, productCode: ProductCode): Box[Product] = Empty - - override def createOrUpdateBranch(branch: BranchT): Box[BranchT] = Empty - - override def createOrUpdateBank( - bankId: String, - fullBankName: String, - shortBankName: String, - logoURL: String, - websiteURL: String, - swiftBIC: String, - national_identifier: String, - bankRoutingScheme: String, - bankRoutingAddress: String - ): Box[Bank] = Empty - - - // get the latest FXRate specified by fromCurrencyCode and toCurrencyCode. - override def getCurrentFxRate(bankId: BankId, fromCurrencyCode: String, toCurrencyCode: String): Box[FXRate] = { - // Create request argument list - val req = Map( - "north" -> "getCurrentFxRate", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "bankId" -> bankId.value, - "fromCurrencyCode" -> fromCurrencyCode, - "toCurrencyCode" -> toCurrencyCode - ) - val r = { - cachedFxRate.getOrElseUpdate(req.toString, () => process(req).extract[KafkaInboundFXRate]) - } - // Return result - Full(new KafkaFXRate(r)) - } - - //get the current charge specified by bankId, accountId, viewId and transactionRequestType - override def getTransactionRequestTypeCharge(bankId: BankId, accountId: AccountId, viewId: ViewId, transactionRequestType: TransactionRequestType): Box[TransactionRequestTypeCharge] = { - - // Create request argument list - val req = Map( - "north" -> "getTransactionRequestTypeCharge", - "version" -> formatVersion, - "name" -> AuthUser.getCurrentUserUsername, - "bankId" -> bankId.value, - "accountId" -> accountId.value, - "viewId" -> viewId.value, - "transactionRequestType" -> transactionRequestType.value - ) - // send the request to kafka and get response - // TODO the error handling is not good enough, it should divide the error, empty and no-response. - val r = tryo { - cachedTransactionRequestTypeCharge.getOrElseUpdate(req.toString, () => process(req).extract[KafkaInboundTransactionRequestTypeCharge]) - } - // Return result - val result = r match { - case Full(f) => Full(KafkaTransactionRequestTypeCharge(f)) - case _ => - for { - fromAccount <- getBankAccountOld(bankId, accountId) - fromAccountCurrency <- tryo{ fromAccount.currency } - } yield { - KafkaTransactionRequestTypeCharge(KafkaInboundTransactionRequestTypeCharge(transactionRequestType.value, bankId.value, fromAccountCurrency, "0.00", "Warning! Default value!")) - } - } - result - } - - override def getEmptyBankAccount(): Box[BankAccount] = { - Full(new KafkaBankAccount(KafkaInboundAccount(accountId = "", - bankId = "", - label = "", - number = "", - `type` = "", - balanceAmount = "", - balanceCurrency = "", - iban = "", - owners = Nil, - generate_public_view = true, - generate_accountants_view = true, - generate_auditors_view = true))) - } - - ///////////////////////////////////////////////////////////////////////////// - - - - // Helper for creating a transaction - def createNewTransaction(r: KafkaInboundTransaction):Box[Transaction] = { - var datePosted: Date = null - if (r.postedDate != null) // && r.details.posted.matches("^[0-9]{8}$")) - datePosted = APIUtil.DateWithMsFormat.parse(r.postedDate) - - var dateCompleted: Date = null - if (r.completedDate != null) // && r.details.completed.matches("^[0-9]{8}$")) - dateCompleted = APIUtil.DateWithMsFormat.parse(r.completedDate) - - for { - counterpartyId <- tryo{r.counterpartyId} - counterpartyName <- tryo{r.counterpartyName} - thisAccount <- getBankAccountOld(BankId(r.bankId), AccountId(r.accountId)) - //creates a dummy OtherBankAccount without an OtherBankAccountMetadata, which results in one being generated (in OtherBankAccount init) - dummyOtherBankAccount <- tryo{createCounterparty(counterpartyId, counterpartyName, thisAccount, None)} - //and create the proper OtherBankAccount with the correct "id" attribute set to the metadataId of the OtherBankAccountMetadata object - //note: as we are passing in the OtherBankAccountMetadata we don't incur another db call to get it in OtherBankAccount init - counterparty <- tryo{createCounterparty(counterpartyId, counterpartyName, thisAccount, Some(dummyOtherBankAccount.metadata))} - } yield { - // Create new transaction - new Transaction( - r.transactionId, // uuid:String - TransactionId(r.transactionId), // id:TransactionId - thisAccount, // thisAccount:BankAccount - counterparty, // otherAccount:OtherBankAccount - r.`type`, // transactionType:String - BigDecimal(r.amount), // val amount:BigDecimal - thisAccount.currency, // currency:String - Some(r.description), // description:Option[String] - datePosted, // startDate:Date - dateCompleted, // finishDate:Date - BigDecimal(r.newBalanceAmount) // balance:BigDecimal) - ) - } - } - - - case class KafkaBank(r: KafkaInboundBank) extends Bank { - def fullName = r.name - def shortName = r.name - def logoUrl = r.logo - def bankId = BankId(r.bankId) - def nationalIdentifier = "None" //TODO - def swiftBic = "None" //TODO - def websiteUrl = r.url - def bankRoutingScheme = "None" - def bankRoutingAddress = "None" - } - - // Helper for creating other bank account - def createCounterparty(counterpartyId: String, counterpartyName: String, o: BankAccount, alreadyFoundMetadata : Option[CounterpartyMetadata]) = { - new Counterparty( - counterpartyId = alreadyFoundMetadata.map(_.getCounterpartyId).getOrElse(""), - counterpartyName = counterpartyName, - nationalIdentifier = "", - otherBankRoutingAddress = None, - otherAccountRoutingAddress = None, - thisAccountId = AccountId(counterpartyId), - thisBankId = BankId(""), - kind = "", - otherBankRoutingScheme = "", - otherAccountRoutingScheme="", - otherAccountProvider = "", - isBeneficiary = true - ) - } - case class KafkaBankAccount(r: KafkaInboundAccount) extends BankAccount { - def accountId : AccountId = AccountId(r.accountId) - def accountType : String = r.`type` - def balance : BigDecimal = BigDecimal(r.balanceAmount) - def currency : String = r.balanceCurrency - def name : String = r.owners.head - def iban : Option[String] = Some(r.iban) - def number : String = r.number - def bankId : BankId = BankId(r.bankId) - def lastUpdate : Date = APIUtil.DateWithMsFormat.parse(today.getTime.toString) - def accountHolder : String = r.owners.head - def accountRoutingScheme: String = r.accountRoutingScheme - def accountRoutingAddress: String = r.accountRoutingAddress - def branchId: String = r.branchId - def accountRoutings: List[AccountRouting] = List() - def accountRules: List[AccountRule] = List() - - // Fields modifiable from OBP are stored in mapper - def label : String = (for { - d <- MappedBankAccountData.find(By(MappedBankAccountData.accountId, r.accountId)) - } yield { - d.getLabel - }).getOrElse(r.number) - - } - - case class KafkaFXRate(kafkaInboundFxRate: KafkaInboundFXRate) extends FXRate { - def bankId: BankId = kafkaInboundFxRate.bank_id - def fromCurrencyCode : String= kafkaInboundFxRate.from_currency_code - def toCurrencyCode : String= kafkaInboundFxRate.to_currency_code - def conversionValue : Double= kafkaInboundFxRate.conversion_value - def inverseConversionValue : Double= kafkaInboundFxRate.inverse_conversion_value - //TODO need to add error handling here for String --> Date transfer - def effectiveDate : Date= APIUtil.DateWithMsFormat.parse(kafkaInboundFxRate.effective_date) - } - - case class KafkaCounterparty(counterparty: KafkaInboundCounterparty) extends CounterpartyTrait { - def createdByUserId: String = counterparty.created_by_user_id - def name: String = counterparty.name - def thisBankId: String = counterparty.this_bank_id - def thisAccountId: String = counterparty.this_account_id - def thisViewId: String = counterparty.this_view_id - def counterpartyId: String = counterparty.counterparty_id - def otherAccountRoutingScheme: String = counterparty.other_account_routing_scheme - def otherAccountRoutingAddress: String = counterparty.other_account_routing_address - def otherBankRoutingScheme: String = counterparty.other_bank_routing_scheme - def otherBankRoutingAddress: String = counterparty.other_bank_routing_address - def otherBranchRoutingScheme: String = counterparty.other_branch_routing_scheme - def otherBranchRoutingAddress: String = counterparty.other_branch_routing_address - def isBeneficiary : Boolean = counterparty.is_beneficiary - def description: String = "" - def currency: String = "" - def otherAccountSecondaryRoutingScheme: String = "" - def otherAccountSecondaryRoutingAddress: String = "" - def bespoke: List[CounterpartyBespoke] = Nil - } - - case class KafkaTransactionRequestTypeCharge(kafkaInboundTransactionRequestTypeCharge: KafkaInboundTransactionRequestTypeCharge) extends TransactionRequestTypeCharge{ - def transactionRequestTypeId: String = kafkaInboundTransactionRequestTypeCharge.transaction_request_type_id - def bankId: String = kafkaInboundTransactionRequestTypeCharge.bank_id - def chargeCurrency: String = kafkaInboundTransactionRequestTypeCharge.charge_currency - def chargeAmount: String = kafkaInboundTransactionRequestTypeCharge.charge_amount - def chargeSummary: String = kafkaInboundTransactionRequestTypeCharge.charge_summary - } - - case class KafkaInboundBank( - bankId : String, - name : String, - logo : String, - url : String) - - - /** Bank Branches - * - * @param id Uniquely identifies the Branch within the Bank. SHOULD be url friendly (no spaces etc.) Used in URLs - * @param bank_id MUST match bank_id in Banks - * @param name Informal name for the Branch - * @param address Address - * @param location Geolocation - * @param meta Meta information including the license this information is published under - * @param lobby Info about when the lobby doors are open - * @param driveUp Info about when automated facilities are open e.g. cash point machine - */ - case class KafkaInboundBranch( - id : String, - bank_id: String, - name : String, - address : KafkaInboundAddress, - location : KafkaInboundLocation, - meta : KafkaInboundMeta, - lobby : Option[KafkaInboundLobby], - driveUp : Option[KafkaInboundDriveUp]) - - case class KafkaInboundLicense( - id : String, - name : String) - - case class KafkaInboundMeta( - license : KafkaInboundLicense) - - case class KafkaInboundLobby( - hours : String) - - case class KafkaInboundDriveUp( - hours : String) - - /** - * - * @param line_1 Line 1 of Address - * @param line_2 Line 2 of Address - * @param line_3 Line 3 of Address - * @param city City - * @param county County i.e. Division of State - * @param state State i.e. Division of Country - * @param post_code Post Code or Zip Code - * @param country_code 2 letter country code: ISO 3166-1 alpha-2 - */ - case class KafkaInboundAddress( - line_1 : String, - line_2 : String, - line_3 : String, - city : String, - county : String, // Division of State - state : String, // Division of Country - post_code : String, - country_code: String) - - case class KafkaInboundLocation( - latitude : Double, - longitude : Double) - - case class KafkaInboundValidatedUser(email: String, - displayName: String) - - // TODO Be consistent use camelCase - - case class KafkaInboundAccount( - accountId : String, - bankId : String, - label : String, - number : String, - `type` : String, - balanceAmount: String, - balanceCurrency: String, - iban : String, - owners : List[String], - generate_public_view : Boolean, - generate_accountants_view : Boolean, - generate_auditors_view : Boolean, - accountRoutingScheme: String = "None", - accountRoutingAddress: String = "None", - branchId: String = "None" - ) - - case class KafkaInboundTransaction( - transactionId : String, - accountId : String, - amount: String, - bankId : String, - completedDate: String, - counterpartyId: String, - counterpartyName: String, - currency: String, - description: String, - newBalanceAmount: String, - newBalanceCurrency: String, - postedDate: String, - `type`: String, - userId: String - ) - - case class KafkaInboundAtm( - id : String, - bank_id: String, - name : String, - address : KafkaInboundAddress, - location : KafkaInboundLocation, - meta : KafkaInboundMeta - ) - - case class KafkaInboundProduct( - bank_id : String, - code: String, - name : String, - category : String, - family : String, - super_family : String, - more_info_url : String, - meta : KafkaInboundMeta - ) - - case class KafkaInboundAccountData( - banks : List[KafkaInboundBank], - users : List[InboundUser], - accounts : List[KafkaInboundAccount] - ) - - // We won't need this. TODO clean up. - case class KafkaInboundData( - banks : List[KafkaInboundBank], - users : List[InboundUser], - accounts : List[KafkaInboundAccount], - transactions : List[KafkaInboundTransaction], - branches: List[KafkaInboundBranch], - atms: List[KafkaInboundAtm], - products: List[KafkaInboundProduct], - crm_events: List[KafkaInboundCrmEvent] - ) - - case class KafkaInboundCrmEvent( - id : String, // crmEventId - bank_id : String, - customer: KafkaInboundCustomer, - category : String, - detail : String, - channel : String, - actual_date: String - ) - - case class KafkaInboundCustomer( - name: String, - number : String // customer number, also known as ownerId (owner of accounts) aka API User? - ) - - case class KafkaInboundTransactionId( - transactionId : String - ) - - case class KafkaOutboundTransaction( - north: String, - version: String, - name: String, - accountId: String, - currency: String, - amount: String, - otherAccountId: String, - otherAccountCurrency: String, - transactionType: String) - - case class KafkaInboundChallengeLevel( - limit: String, - currency: String - ) - case class KafkaInboundTransactionRequestStatus( - transactionRequestId : String, - bulkTransactionsStatus: List[KafkaInboundTransactionStatus] - ) - case class KafkaInboundTransactionStatus( - transactionId : String, - transactionStatus: String, - transactionTimestamp: String - ) - case class KafkaInboundCreateChallange(challengeId: String) - case class KafkaInboundValidateChallangeAnswer(answer: String) - - case class KafkaInboundChargeLevel( - currency: String, - amount: String - ) - - case class KafkaInboundFXRate( - bank_id: BankId, - from_currency_code: String, - to_currency_code: String, - conversion_value: Double, - inverse_conversion_value: Double, - effective_date: String - ) - - case class KafkaInboundCounterparty( - name: String, - created_by_user_id: String, - this_bank_id: String, - this_account_id: String, - this_view_id: String, - counterparty_id: String, - other_bank_routing_scheme: String, - other_account_routing_scheme: String, - other_bank_routing_address: String, - other_account_routing_address: String, - other_branch_routing_scheme: String, - other_branch_routing_address: String, - is_beneficiary: Boolean - ) - - - case class KafkaInboundTransactionRequestTypeCharge( - transaction_request_type_id: String, - bank_id: String, - charge_currency: String, - charge_amount: String, - charge_summary: String - ) - - -} - - diff --git a/obp-api/src/main/scala/code/bankconnectors/rest/RestConnector_vMar2019.scala b/obp-api/src/main/scala/code/bankconnectors/rest/RestConnector_vMar2019.scala index c10496bf8..08240e492 100644 --- a/obp-api/src/main/scala/code/bankconnectors/rest/RestConnector_vMar2019.scala +++ b/obp-api/src/main/scala/code/bankconnectors/rest/RestConnector_vMar2019.scala @@ -41,7 +41,6 @@ import code.api.util.RSAUtil.{computeXSign, getPrivateKeyFromString} import code.api.util.{APIUtil, CallContext, OBPQueryParam} import code.api.v4_0_0.dynamic.MockResponseHolder import code.bankconnectors._ -import code.bankconnectors.vJune2017.AuthInfo import code.context.UserAuthContextProvider import code.customer.internalMapping.MappedCustomerIdMappingProvider import code.kafka.KafkaHelper diff --git a/obp-api/src/main/scala/code/bankconnectors/storedprocedure/StoredProcedureConnector_vDec2019.scala b/obp-api/src/main/scala/code/bankconnectors/storedprocedure/StoredProcedureConnector_vDec2019.scala index 3d7933114..85cbed4f8 100644 --- a/obp-api/src/main/scala/code/bankconnectors/storedprocedure/StoredProcedureConnector_vDec2019.scala +++ b/obp-api/src/main/scala/code/bankconnectors/storedprocedure/StoredProcedureConnector_vDec2019.scala @@ -32,7 +32,6 @@ import code.api.util.ErrorMessages._ import code.api.util.ExampleValue._ import code.api.util.{APIUtil, CallContext, HashUtil, OBPQueryParam} import code.bankconnectors._ -import code.bankconnectors.vJune2017.AuthInfo import code.customer.internalMapping.MappedCustomerIdMappingProvider import code.model.dataAccess.internalMapping.MappedAccountIdMappingProvider import code.util.Helper diff --git a/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaJsonFactory_vJune2017.scala b/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaJsonFactory_vJune2017.scala deleted file mode 100644 index b3df253de..000000000 --- a/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaJsonFactory_vJune2017.scala +++ /dev/null @@ -1,455 +0,0 @@ -package code.bankconnectors.vJune2017 - -import java.lang -import java.util.Date - -import code.api.util.APIUtil -import com.openbankproject.commons.model.CheckbookOrdersJson -import code.bankconnectors.vMar2017._ -import code.branches.Branches.{DriveUpString, LobbyString} - -import code.model.dataAccess.MappedBankAccountData -import com.openbankproject.commons.model.TransactionRequest -import com.openbankproject.commons.model.{CounterpartyTrait, CreditLimit, _} -import net.liftweb.mapper.By -import net.liftweb.util.Helpers.today - -import scala.collection.immutable.List - -/** - * case classes used to define topics, these are outbound kafka messages - */ - -case class OutboundGetAdapterInfo(authInfo: AuthInfo, date: String) extends TopicTrait -case class OutboundGetBanks(authInfo: AuthInfo) extends TopicTrait -case class OutboundGetBank(authInfo: AuthInfo, bankId: String) extends TopicTrait -case class OutboundGetAccounts(authInfo: AuthInfo, customers:InternalBasicCustomers) extends TopicTrait -case class OutboundGetAccountbyAccountID(authInfo: AuthInfo, bankId: String, accountId: String)extends TopicTrait -case class OutboundCheckBankAccountExists(authInfo: AuthInfo, bankId: String, accountId: String)extends TopicTrait -case class OutboundGetCoreBankAccounts(authInfo: AuthInfo, bankIdAccountIds: List[BankIdAccountId])extends TopicTrait -case class OutboundGetTransactions(authInfo: AuthInfo,bankId: String, accountId: String, limit: Int, fromDate: String, toDate: String) extends TopicTrait -case class OutboundGetTransaction(authInfo: AuthInfo, bankId: String, accountId: String, transactionId: String) extends TopicTrait -case class OutboundGetBranches(authInfo: AuthInfo,bankId: String) extends TopicTrait -case class OutboundGetBranch(authInfo: AuthInfo, bankId: String, branchId: String)extends TopicTrait -case class OutboundGetAtms(authInfo: AuthInfo,bankId: String) extends TopicTrait -case class OutboundGetAtm(authInfo: AuthInfo,bankId: String, atmId: String) extends TopicTrait - -case class OutboundCreateChallengeJune2017( - authInfo: AuthInfo, - bankId: String, - accountId: String, - userId: String, - username: String, - transactionRequestType: String, - transactionRequestId: String -) extends TopicTrait - -case class OutboundCreateCounterparty( - authInfo: AuthInfo, - counterparty: OutboundCounterparty -) extends TopicTrait - -case class OutboundGetTransactionRequests210( - authInfo: AuthInfo, - counterparty: OutboundTransactionRequests -) extends TopicTrait - -case class OutboundGetCounterparties( - authInfo: AuthInfo, - counterparty: InternalOutboundGetCounterparties -) extends TopicTrait - -case class OutboundGetCounterpartyByCounterpartyId( - authInfo: AuthInfo, - counterparty: OutboundGetCounterpartyById -) extends TopicTrait -case class OutboundGetCounterparty(authInfo: AuthInfo, thisBankId: String, thisAccountId: String, counterpartyId: String) extends TopicTrait - -case class OutboundGetCustomersByUserId( - authInfo: AuthInfo -) extends TopicTrait - -case class OutboundGetCheckbookOrderStatus( - authInfo: AuthInfo, - bankId: String, - accountId: String, - originatorApplication: String, - originatorStationIP: String, - primaryAccount: String -)extends TopicTrait - -case class OutboundGetCreditCardOrderStatus( - authInfo: AuthInfo, - bankId: String, - accountId: String, - originatorApplication: String, - originatorStationIP: String, - primaryAccount: String -)extends TopicTrait - - - -/** - * case classes used in Kafka message, these are InBound Kafka messages - */ - -case class InboundAdapterInfo(authInfo: AuthInfo, data: InboundAdapterInfoInternal) -case class InboundGetUserByUsernamePassword(authInfo: AuthInfo, data: InboundValidatedUser) -case class InboundGetBanks(authInfo: AuthInfo, status: Status,data: List[InboundBank]) -case class InboundGetBank(authInfo: AuthInfo, status: Status, data: InboundBank) -case class InboundGetAccounts(authInfo: AuthInfo, status: Status, data: List[InboundAccountJune2017]) -case class InboundGetAccountbyAccountID(authInfo: AuthInfo, status: Status, data: Option[InboundAccountJune2017]) -case class InboundCheckBankAccountExists(authInfo: AuthInfo, status: Status, data: Option[InboundAccountJune2017]) -case class InboundGetCoreBankAccounts(authInfo: AuthInfo, data: List[InternalInboundCoreAccount]) -case class InboundGetTransactions(authInfo: AuthInfo, status: Status, data: List[InternalTransaction_vJune2017]) -case class InboundGetTransaction(authInfo: AuthInfo, status: Status, data: Option[InternalTransaction_vJune2017]) -case class InboundCreateChallengeJune2017(authInfo: AuthInfo, data: InternalCreateChallengeJune2017) -case class InboundCreateCounterparty(authInfo: AuthInfo, status: Status, data: Option[InternalCounterparty]) -case class InboundGetTransactionRequests210(authInfo: AuthInfo, status: Status, data: List[TransactionRequest]) -case class InboundGetCounterparties(authInfo: AuthInfo, status: Status, data: List[InternalCounterparty]) -case class InboundGetCounterparty(authInfo: AuthInfo, status: Status, data: Option[InternalCounterparty]) -case class InboundGetCustomersByUserId(authInfo: AuthInfo, status: Status, data: List[InternalCustomer]) -case class InboundGetBranches(authInfo: AuthInfo,status: Status,data: List[InboundBranchVJune2017]) -case class InboundGetBranch(authInfo: AuthInfo,status: Status, data: Option[InboundBranchVJune2017]) -case class InboundGetAtms(authInfo: AuthInfo, status: Status, data: List[InboundAtmJune2017]) -case class InboundGetAtm(authInfo: AuthInfo, status: Status, data: Option[InboundAtmJune2017]) -case class InboundGetChecksOrderStatus(authInfo: AuthInfo, status: Status, data: CheckbookOrdersJson) -case class InboundGetCreditCardOrderStatus(authInfo: AuthInfo, status: Status, data: List[InboundCardDetails]) - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -// These are case classes, used in internal message mapping -case class InternalInboundCoreAccount( - errorCode: String, - backendMessages: List[InboundStatusMessage], - id : String, - label : String, - bankId : String, - accountType: String, - accountRoutings: List[AccountRouting] -) -case class Status( - errorCode: String, - backendMessages: List[InboundStatusMessage] - ) -case class AuthInfo(userId: String = "", username: String ="", cbsToken: String ="", isFirst: Boolean = true, correlationId: String="", sessionId :String = "") - -case class InboundAccountJune2017( - errorCode: String, - cbsToken: String, //TODO, this maybe move to AuthInfo, but it is used in GatewayLogin - bankId: String, - branchId: String, - accountId: String, - accountNumber: String, - accountType: String, - balanceAmount: String, - balanceCurrency: String, - owners: List[String], - viewsToGenerate: List[String], - bankRoutingScheme: String, - bankRoutingAddress: String, - branchRoutingScheme: String, - branchRoutingAddress: String, - accountRoutingScheme: String, - accountRoutingAddress: String, - accountRouting: List[AccountRouting], - accountRules: List[AccountRule] -) extends InboundMessageBase with InboundAccount - -case class BankAccountJune2017(r: InboundAccountJune2017) extends BankAccount { - - def accountId: AccountId = AccountId(r.accountId) - def accountType: String = r.accountType - def balance: BigDecimal = BigDecimal(r.balanceAmount) - def currency: String = r.balanceCurrency - def name: String = r.owners.head - // Note: deprecated, extends from BankAccount - def iban: Option[String] = Some("iban") - def number: String = r.accountNumber - def bankId: BankId = BankId(r.bankId) - def lastUpdate: Date = APIUtil.DateWithMsFormat.parse(today.getTime.toString) - def accountHolder: String = r.owners.head - - // Fields modifiable from OBP are stored in mapper - def label: String = (for { - d <- MappedBankAccountData.find(By(MappedBankAccountData.accountId, r.accountId)) - } yield { - d.getLabel - }).getOrElse(r.accountNumber) - - def accountRoutingScheme: String = r.accountRoutingScheme - def accountRoutingAddress: String = r.accountRoutingAddress - def accountRoutings: List[AccountRouting] = List() - def branchId: String = r.branchId - - def accountRules: List[AccountRule] = r.accountRules - -} - -case class InternalBasicCustomer( - bankId:String, - customerId: String, - customerNumber: String, - legalName: String, - dateOfBirth: Date -) - -case class InternalBasicCustomers(customers: List[InternalBasicCustomer]) - -case class InternalCreateChallengeJune2017( - errorCode: String, - backendMessages: List[InboundStatusMessage], - answer : String -) - -case class InternalGetTransactionRequests( - errorCode: String, - backendMessages: List[InboundStatusMessage], - transactionRequests:List[TransactionRequest] -) - -case class OutboundCounterparty( - name: String, - description: String, - createdByUserId: String, - thisBankId: String, - thisAccountId: String, - thisViewId: String, - otherAccountRoutingScheme: String, - otherAccountRoutingAddress: String, - otherAccountSecondaryRoutingScheme: String, - otherAccountSecondaryRoutingAddress: String, - otherBankRoutingScheme: String, - otherBankRoutingAddress: String, - otherBranchRoutingScheme: String, - otherBranchRoutingAddress: String, - isBeneficiary:Boolean, - bespoke: List[CounterpartyBespoke] -) - -case class InternalOutboundGetCounterparties( - thisBankId: String, - thisAccountId: String, - viewId :String -) - -case class OutboundGetCounterpartyById( - counterpartyId : String -) - -case class OutboundTransactionRequests( - accountId: String, - accountType: String, - currency: String, - iban: String, - number: String, - bankId: String, - branchId: String, - accountRoutingScheme: String, - accountRoutingAddress: String -) - - -case class InternalCounterparty( - createdByUserId: String, - name: String, - thisBankId: String, - thisAccountId: String, - thisViewId: String, - counterpartyId: String, - otherAccountRoutingScheme: String, - otherAccountRoutingAddress: String, - otherBankRoutingScheme: String, - otherBankRoutingAddress: String, - otherBranchRoutingScheme: String, - otherBranchRoutingAddress: String, - isBeneficiary: Boolean, - description: String, - currency: String, - otherAccountSecondaryRoutingScheme: String, - otherAccountSecondaryRoutingAddress: String, - bespoke: List[CounterpartyBespoke]) extends CounterpartyTrait - - -case class InternalCustomer( - customerId: String, - bankId: String, - number: String, - legalName: String, - mobileNumber: String, - email: String, - faceImage: CustomerFaceImage, - dateOfBirth: Date, - relationshipStatus: String, - dependents: Integer, - dobOfDependents: List[Date], - highestEducationAttained: String, - employmentStatus: String, - creditRating: CreditRating, - creditLimit: CreditLimit, - kycStatus: lang.Boolean, - lastOkDate: Date -) - -case class ObpCustomer( - customerId: String, - bankId: String, - number: String, - legalName: String, - mobileNumber: String, - email: String, - faceImage: CustomerFaceImage, - dateOfBirth: Date, - relationshipStatus: String, - dependents: Integer, - dobOfDependents: List[Date], - highestEducationAttained: String, - employmentStatus: String, - creditRating: CreditRating, - creditLimit: CreditLimit, - kycStatus: lang.Boolean, - lastOkDate: Date, - title: String = "", //These new fields for V310, not from Connector for now. - branchId: String = "", //These new fields for V310, not from Connector for now. - nameSuffix: String = "", //These new fields for V310, not from Connector for now. -) extends Customer - -case class InboundBranchVJune2017( - branchId: BranchId, - bankId: BankId, - name: String, - address: Address, - location: Location, - lobbyString: Option[LobbyString], - driveUpString: Option[DriveUpString], - meta: Meta, - branchRouting: Option[Routing], - lobby: Option[Lobby], - driveUp: Option[DriveUp], - // Easy access for people who use wheelchairs etc. - isAccessible : Option[Boolean], - accessibleFeatures: Option[String], - branchType : Option[String], - moreInfo : Option[String], - phoneNumber : Option[String], - isDeleted : Option[Boolean] - ) extends BranchT - -case class InboundAtmJune2017( - atmId : AtmId, - bankId : BankId, - name : String, - address : Address, - location : Location, - meta : Meta, - - OpeningTimeOnMonday : Option[String], - ClosingTimeOnMonday : Option[String], - - OpeningTimeOnTuesday : Option[String], - ClosingTimeOnTuesday : Option[String], - - OpeningTimeOnWednesday : Option[String], - ClosingTimeOnWednesday : Option[String], - - OpeningTimeOnThursday : Option[String], - ClosingTimeOnThursday: Option[String], - - OpeningTimeOnFriday : Option[String], - ClosingTimeOnFriday : Option[String], - - OpeningTimeOnSaturday : Option[String], - ClosingTimeOnSaturday : Option[String], - - OpeningTimeOnSunday: Option[String], - ClosingTimeOnSunday : Option[String], - - isAccessible : Option[Boolean], - - locatedAt : Option[String], - moreInfo : Option[String], - hasDepositCapability : Option[Boolean], - supportedLanguages: Option[List[String]] = None, - services: Option[List[String]] = None, - notes: Option[List[String]] = None, - accessibilityFeatures: Option[List[String]] = None, - supportedCurrencies: Option[List[String]] = None, - minimumWithdrawal: Option[String] = None, - branchIdentification: Option[String] = None, - locationCategories: Option[List[String]] = None, - siteIdentification: Option[String] = None, - siteName: Option[String] = None, - cashWithdrawalNationalFee: Option[String] = None, - cashWithdrawalInternationalFee: Option[String] = None, - balanceInquiryFee: Option[String] = None, - ) extends AtmT - -case class InternalTransaction_vJune2017( - transactionId: String, - accountId: String, - amount: String, - bankId: String, - completedDate: String, - counterpartyId: String, - counterpartyName: String, - currency: String, - description: String, - newBalanceAmount: String, - newBalanceCurrency: String, - postedDate: String, - `type`: String, - userId: String - ) - -case class InboundCardDetails( - orderId: String, - creditCardType: String, - cardDescription: String, - useType: String, - orderDate: String, - deliveryStatus: String, - statusDate: String, - branch: String -) - -object JsonFactory_vJune2017 { - def createCustomerJson(customer : Customer) : InternalBasicCustomer = { - InternalBasicCustomer( - bankId=customer.bankId, - customerId = customer.customerId, - customerNumber = customer.number, - legalName = customer.legalName, - dateOfBirth = customer.dateOfBirth - ) - } - def createObpCustomer(customer : InternalCustomer) : Customer = { - ObpCustomer( - customerId = customer.customerId, - bankId = customer.bankId, - number = customer.number, - legalName = customer.legalName, - mobileNumber = customer.mobileNumber, - email = customer.email, - faceImage = customer.faceImage, - dateOfBirth = customer.dateOfBirth, - relationshipStatus = customer.relationshipStatus, - dependents = customer.dependents, - dobOfDependents = customer.dobOfDependents, - highestEducationAttained = customer.highestEducationAttained, - employmentStatus = customer.employmentStatus, - creditRating = customer.creditRating, - creditLimit = customer.creditLimit, - kycStatus = customer.kycStatus, - lastOkDate = customer.lastOkDate, - ) - } - - def createCustomersJson(customers : List[Customer]) : InternalBasicCustomers = { - InternalBasicCustomers(customers.map(createCustomerJson)) - } - - def createObpCustomers(customers : List[InternalCustomer]) : List[Customer] = { - customers.map(createObpCustomer) - } -} \ No newline at end of file diff --git a/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaMappedConnector_vJune2017.scala b/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaMappedConnector_vJune2017.scala deleted file mode 100644 index 7a2cba025..000000000 --- a/obp-api/src/main/scala/code/bankconnectors/vJune2017/KafkaMappedConnector_vJune2017.scala +++ /dev/null @@ -1,2331 +0,0 @@ -package code.bankconnectors.vJune2017 - -/* -Open Bank Project - API -Copyright (C) 2011-2017, TESOBE GmbH - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see http://www.gnu.org/licenses/. - -Email: contact@tesobe.com -TESOBE GmbH -Osloerstrasse 16/17 -Berlin 13359, Germany -*/ - -import java.text.SimpleDateFormat -import java.util.UUID.randomUUID -import java.util.{Date, Locale} - -import code.api.ResourceDocs1_4_0.SwaggerDefinitionsJSON -import code.api.cache.Caching -import code.api.util.APIUtil.{MessageDoc, getSecondsCache, saveConnectorMetric} -import code.api.util.ErrorMessages._ -import code.api.util._ -import code.api.util.APIUtil._ -import com.openbankproject.commons.model.enums.StrongCustomerAuthentication.SCA -import com.openbankproject.commons.model.{AccountV310Json, CardObjectJson, CheckbookOrdersJson} -import code.bankconnectors._ -import code.bankconnectors.vMar2017._ -import code.customer._ -import code.kafka.KafkaHelper -import code.model._ -import code.model.dataAccess._ -import code.transactionrequests.TransactionRequests._ -import code.util.Helper.MdcLoggable -import com.google.common.cache.CacheBuilder -import com.openbankproject.commons.model.{CounterpartyTrait, _} -import com.sksamuel.avro4s.SchemaFor -import com.tesobe.{CacheKeyFromArguments, CacheKeyOmit} -import net.liftweb.common.{Box, _} -import net.liftweb.json -import net.liftweb.json.Extraction._ -import net.liftweb.json.JsonAST.JValue -import net.liftweb.json.{Extraction, MappingException, parse} -import net.liftweb.util.Helpers.tryo - -import scala.collection.immutable.{List, Nil} -import scala.collection.mutable.ArrayBuffer -import com.openbankproject.commons.ExecutionContext.Implicits.global -import com.openbankproject.commons.model.enums.AccountRoutingScheme - -import scala.concurrent.Future -import scala.concurrent.duration._ -import scala.language.postfixOps - -trait KafkaMappedConnector_vJune2017 extends Connector with KafkaHelper with MdcLoggable { - - implicit override val nameOfConnector = KafkaMappedConnector_vJune2017.toString - - // "Versioning" of the messages sent by this or similar connector works like this: - // Use Case Classes (e.g. KafkaInbound... KafkaOutbound... as below to describe the message structures. - // Each connector has a separate file like this one. - // Once the message format is STABLE, freeze the key/value pair names there. For now, new keys may be added but none modified. - // If we want to add a new message format, create a new file e.g. March2017_messages.scala - // Then add a suffix to the connector value i.e. instead of kafka we might have kafka_march_2017. - // Then in this file, populate the different case classes depending on the connector name and send to Kafka - val messageFormat: String = "June2017" - - //This is special method, it is only used for the first cbs call. cbsToken can be empty here. - def getAuthInfoFirstCbsCall (username: String, callContext: Option[CallContext]): Box[AuthInfo]= - for{ - cc <- tryo {callContext.get} ?~! NoCallContext - gatewayLoginRequestPayLoad <- cc.gatewayLoginRequestPayload - isFirst <- Full(gatewayLoginRequestPayLoad.is_first) - correlationId <- Full(cc.correlationId) - sessionId <- Full(cc.sessionId.getOrElse("")) - } yield{ - AuthInfo("",username, "", isFirst, correlationId, sessionId) - } - - def getAuthInfo (callContext: Option[CallContext]): Box[AuthInfo]= - for{ - cc <- tryo {callContext.get} ?~! NoCallContext - user <- cc.user - username <- Full(user.name) - currentResourceUserId <- Some(user.userId) - gatewayLoginRequestPayLoad <- cc.gatewayLoginRequestPayload - cbs_token <- gatewayLoginRequestPayLoad.cbs_token.orElse(Full("")) - isFirst <- Full(gatewayLoginRequestPayLoad.is_first) - correlationId <- Full(cc.correlationId) - sessionId <- Full(cc.sessionId.getOrElse("")) - } yield{ - AuthInfo(currentResourceUserId,username, cbs_token, isFirst,correlationId, sessionId) - } - - val authInfoExample = AuthInfo(userId = "userId", username = "username", cbsToken = "cbsToken") - val inboundStatusMessagesExample = List(InboundStatusMessage("ESB", "Success", "0", "OK")) - val errorCodeExample = "INTERNAL-OBP-ADAPTER-6001: ..." - val statusExample = Status(errorCodeExample, inboundStatusMessagesExample) - - messageDocs += MessageDoc( - process = "obp.getAdapterInfo", - messageFormat = messageFormat, - description = "getAdapterInfo from Adapter, just for testing kafka and Adapter setting. ", - exampleOutboundMessage = ( - OutboundGetAdapterInfo(authInfoExample, date = DateWithSecondsExampleString) - ), - exampleInboundMessage = ( - InboundAdapterInfo( - authInfoExample, - InboundAdapterInfoInternal( - errorCodeExample, - inboundStatusMessagesExample, - name = "Obp-Kafka-South", - version = "June2017", - git_commit = "...", - date = DateWithSecondsExampleString - ) - ) - ), - outboundAvroSchema = Some(parse(SchemaFor[OutboundGetAdapterInfo]().toString(true))), - inboundAvroSchema = Some(parse(SchemaFor[InboundAdapterInfoInternal]().toString(true))) - ) - override def getAdapterInfo(callContext: Option[CallContext]): Future[Box[(InboundAdapterInfoInternal, Option[CallContext])]] = { - val req = OutboundGetAdapterInfo( - AuthInfo(sessionId = callContext.get.correlationId), - DateWithSecondsExampleString - ) - - logger.debug(s"Kafka getAdapterInfo Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetAdapterInfo](req) map { - f => - try { - f.extract[InboundAdapterInfo] - } catch { - case e: Exception => - val received = json.compactRender(f) - val expected = SchemaFor[InboundAdapterInfo]().toString(false) - val err = s"Extraction Failed: You received this ($received). We expected this ($expected)" - sendOutboundAdapterError(err) - throw new MappingException(err, e) - } - } map { - x => x.data - } - } yield { - Full(res) - } - - val res = future map { - case Full(list) if (list.errorCode=="") => - Full(list, callContext) - case Full(list) if (list.errorCode!="") => - Failure("INTERNAL-"+ list.errorCode+". + CoreBank-Status:"+ list.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - logger.debug(s"Kafka getAdapterInfo says res is $res") - res - } - - - - messageDocs += MessageDoc( - process = "obp.getBanks", - messageFormat = messageFormat, - description = "getBanks", - exampleOutboundMessage = ( - OutboundGetBanks(authInfoExample) - ), - exampleInboundMessage = ( - InboundGetBanks( - authInfoExample, - Status( - errorCode = errorCodeExample, - inboundStatusMessagesExample), - InboundBank( - bankId = "gh.29.uk", - name = "sushan", - logo = "TESOBE", - url = "https://tesobe.com/" - ) :: Nil - ) - ), - outboundAvroSchema = Some(parse(SchemaFor[OutboundGetBanks]().toString(true))), - inboundAvroSchema = Some(parse(SchemaFor[InboundGetBanks]().toString(true))) - ) - override def getBanksLegacy(callContext: Option[CallContext])= saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(banksTTL second){ - val req = OutboundGetBanks(AuthInfo()) - logger.debug(s"Kafka getBanks Req is: $req") - - val box = for { - _ <- Full(logger.debug("Enter GetBanks BOX1: prekafka") ) - kafkaMessage <- processToBox(req) - _ <- Full(logger.debug(s"Enter GetBanks BOX2: postkafka: $kafkaMessage") ) - inboundGetBanks <- tryo{kafkaMessage.extract[InboundGetBanks]} ?~! s"$InboundGetBanks extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - _ <- Full(logger.debug(s"Enter GetBanks BOX3 : $inboundGetBanks") ) - (authInfo, inboundBanks, status) <- Full(inboundGetBanks.authInfo, inboundGetBanks.data, inboundGetBanks.status) - _ <- Full(logger.debug(s"Enter GetBanks BOX4: $inboundBanks") ) - } yield { - (authInfo, inboundBanks, status) - } - - logger.debug(s"Kafka getBanks Res says: is: $box") - val res = box match { - case Full((authInfo, banks, status)) if (status.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full((banks.map(Bank2(_)), callContextUpdated)) - case Full((authInfo, banks, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - logger.debug(s"Kafka getBanks says res is $res") - res - } - } - }("getBanks") - - override def getBanks(callContext: Option[CallContext]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(banksTTL second){ - val req = OutboundGetBanks(AuthInfo()) - logger.debug(s"Kafka getBanksFuture Req is: $req") - - val future = for { - res <- processToFuture[OutboundGetBanks](req) map { - f => - try { - f.extract[InboundGetBanks] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetBanks extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - (x => (x.authInfo, x.data, x.status)) - } - } yield { - Full(res) - } - - val res = future map { - case Full((authInfo, banks, status)) if (status.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - val banksResponse = banks map (new Bank2(_)) - logger.debug(s"Kafka getBanksFuture Res says: is: $banksResponse") - Full((banksResponse, callContextUpdated)) - case Full((authInfo, banks, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - logger.debug(s"Kafka getBanksFuture says res is $res") - res - } - } - }("getBanks") - - messageDocs += MessageDoc( - process = "obp.getBank", - messageFormat = messageFormat, - description = "getBank from kafka ", - exampleOutboundMessage = ( - OutboundGetBank(authInfoExample,"bankId") - ), - exampleInboundMessage = ( - InboundGetBank( - authInfoExample, - Status( - errorCodeExample, - inboundStatusMessagesExample), - InboundBank( - bankId = "gh.29.uk", - name = "sushan", - logo = "TESOBE", - url = "https://tesobe.com/" - ) - ) - ), - outboundAvroSchema = Some(parse(SchemaFor[OutboundGetBank]().toString(true))), - inboundAvroSchema = Some(parse(SchemaFor[InboundGetBank]().toString(true))) - ) - override def getBankLegacy(bankId: BankId, callContext: Option[CallContext]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(bankTTL second) { - val req = OutboundGetBank( - authInfo = AuthInfo(), - bankId = bankId.toString - ) - logger.debug(s"Kafka getBank Req says: is: $req") - - val box= for { - kafkaMessage <- processToBox(req) - inboundGetBank <- tryo { - kafkaMessage.extract[InboundGetBank] - } ?~! s"$InboundGetBank extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (authInfo, inboundBank, status) <- Full(inboundGetBank.authInfo, inboundGetBank.data, inboundGetBank.status) - } yield { - (authInfo, inboundBank, status) - } - - - logger.debug(s"Kafka getBank Res says: is: $box") - - box match { - case Full((authInfo, bank, status)) if (status.errorCode == "") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full((new Bank2(bank), callContextUpdated)) - case Full((_, _, status)) if (status.errorCode != "") => - Failure("INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - logger.error(msg, e) - logger.error(msg) - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - - } - } - }("getBank") - - override def getBank(bankId: BankId, callContext: Option[CallContext]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(banksTTL second){ - val req = OutboundGetBank(authInfo = AuthInfo(), bankId.toString) - logger.debug(s"Kafka getBankFuture Req is: $req") - - val future = for { - res <- processToFuture[OutboundGetBank](req) map { - f => - try { - f.extract[InboundGetBank] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetBank extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - (x => (x.authInfo, x.data, x.status)) - } - } yield { - Full(res) - } - - val res = future map { - case Full((authInfo, bank, status)) if (status.errorCode=="") => - val bankResponse = (new Bank2(bank)) - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - logger.debug(s"Kafka getBankFuture Res says: is: $bankResponse") - Full((bankResponse, callContextUpdated)) - case Full((authInfo, bank, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - logger.debug(s"Kafka getBankFuture says res is $res") - res - } - } - }("getBank") - - messageDocs += MessageDoc( - process = "obp.getAccounts", - messageFormat = messageFormat, - description = "getBankAccounts from kafka", - exampleOutboundMessage = ( - OutboundGetAccounts( - authInfoExample, - InternalBasicCustomers(customers =List( - InternalBasicCustomer( - bankId="bankId", - customerId = "customerId", - customerNumber = "customerNumber", - legalName = "legalName", - dateOfBirth = DateWithSecondsExampleObject - )))) - ), - exampleInboundMessage = ( - InboundGetAccounts(authInfoExample, statusExample, InboundAccountJune2017("", cbsToken ="cbsToken", bankId = "gh.29.uk", branchId = "222", accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = "Susan" :: " Frank" :: Nil, viewsToGenerate = "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil) :: Nil) - ) - ) - override def getBankAccountsForUserLegacy(username: String, callContext: Option[CallContext]): Box[(List[InboundAccount], Option[CallContext])] = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext], internalCustomers: InternalBasicCustomers) = { - val box = for { - authInfo <- getAuthInfoFirstCbsCall(username, callContext) - req = OutboundGetAccounts(authInfo, internalCustomers) - kafkaMessage <- processToBox(req) - inboundGetAccounts <- tryo { - kafkaMessage.extract[InboundGetAccounts] - } ?~! s"$InboundGetAccounts extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (inboundAccountJune2017, status) <- Full(inboundGetAccounts.data, inboundGetAccounts.status) - } yield { - (inboundAccountJune2017, status, callContext) - } - logger.debug(s"Kafka getBankAccounts says res is $box") - - box - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(accountsTTL second) { - //TODO, these Customers should not be get from here, it make some side effects. It is better get it from Parameters. - val currentResourceUserId = AuthUser.getCurrentResourceUserUserId - val customerList :List[Customer]= CustomerX.customerProvider.vend.getCustomersByUserId(currentResourceUserId) - val internalCustomers = JsonFactory_vJune2017.createCustomersJson(customerList) - - val box = callAdapter(callContext, internalCustomers) - - box match { - case Full((data, status, callerContext)) if (status.errorCode=="") => - Full(data, callerContext) - case Full((data, status, callerContext)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBankAccounts") - - override def getBankAccountsForUser(username: String, callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(accountsTTL second) { - //TODO, these Customers should not be get from here, it make some side effects. It is better get it from Parameters. - val currentResourceUserId = AuthUser.getCurrentResourceUserUserId - val customerList :List[Customer]= CustomerX.customerProvider.vend.getCustomersByUserId(currentResourceUserId) - val internalCustomers = JsonFactory_vJune2017.createCustomersJson(customerList) - - def callAdapter(callContext: Option[CallContext], internalCustomers: InternalBasicCustomers) = { - val req = OutboundGetAccounts(getAuthInfoFirstCbsCall(username, callContext).openOrThrowException(s"$attemptedToOpenAnEmptyBox getBankAccountsFuture.callContext is Empty !"), internalCustomers) - logger.debug(s"Kafka getBankAccountsFuture says: req is: $req") - - val future = for { - res <- processToFuture[OutboundGetAccounts](req) map { - f => - try { - f.extract[InboundGetAccounts] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetAccounts extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - (x => (x.data, x.status, callContext)) - } - } yield { - res - } - logger.debug(s"Kafka getBankAccounts says res is $future") - future - } - - val future: Future[(List[InboundAccountJune2017], Status, Option[CallContext])] = callAdapter(callContext, internalCustomers) - - future map { - case (data, status, callContext ) if (status.errorCode=="") => - Full(data, callContext) - case (data, status, callContext) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case (List(), status, callContext) => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBankAccountsFuture") - - messageDocs += MessageDoc( - process = "obp.getAccount", - messageFormat = messageFormat, - description = "getBankAccount from kafka", - exampleOutboundMessage = ( - OutboundGetAccountbyAccountID( - authInfoExample, - "bankId", - "accountId" - ) - ), - exampleInboundMessage = ( - InboundGetAccountbyAccountID( - authInfoExample, - statusExample, - Some(InboundAccountJune2017("", cbsToken = "cbsToken", bankId = "gh.29.uk", branchId = "222", accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = "Susan" :: " Frank" :: Nil, viewsToGenerate = "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil)))) - ) - override def getBankAccountLegacy(bankId: BankId, accountId: AccountId, @CacheKeyOmit callContext: Option[CallContext])= saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(accountTTL second){ - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundGetAccountbyAccountID(authInfo, bankId.toString, accountId.value) - _ <- Full(logger.debug(s"Kafka getBankAccount says: req is: $req")) - kafkaMessage <- processToBox(req) - inboundGetAccountbyAccountID <- tryo{kafkaMessage.extract[InboundGetAccountbyAccountID]} ?~! s"$InboundGetAccountbyAccountID extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (inboundAccountJune2017, status) <- Full(inboundGetAccountbyAccountID.data, inboundGetAccountbyAccountID.status) - } yield{ - (inboundAccountJune2017, status) - } - - logger.debug(s"Kafka getBankAccount says res is $box") - box match { - case Full((Some(data), status)) if (status.errorCode=="") => - Full(new BankAccountJune2017(data), callContext) - case Full((data, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBankAccount") - - messageDocs += MessageDoc( - process = "obp.checkBankAccountExists", - messageFormat = messageFormat, - description = "checkBankAccountExists from kafka", - exampleOutboundMessage = ( - OutboundCheckBankAccountExists( - authInfoExample, - "bankId", - "accountId" - ) - ), - exampleInboundMessage = ( - InboundCheckBankAccountExists( - authInfoExample, - statusExample, - Some(InboundAccountJune2017("", cbsToken = "cbsToken", bankId = "gh.29.uk", branchId = "222", accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = "Susan" :: " Frank" :: Nil, viewsToGenerate = "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil))) - ) - ) - override def checkBankAccountExistsLegacy(bankId: BankId, accountId: AccountId, @CacheKeyOmit callContext: Option[CallContext]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundCheckBankAccountExists( - authInfo = authInfo, - bankId = bankId.toString, - accountId = accountId.value - ) - _ <- Full(logger.debug(s"Kafka checkBankAccountExists says: req is: $req")) - kafkaMessage <- processToBox(req) - inboundCheckBankAccountExists <- tryo { - kafkaMessage.extract[InboundCheckBankAccountExists] - } ?~! s"$InboundCheckBankAccountExists extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (inboundAccountJune2017, status) <- Full(inboundCheckBankAccountExists.data, inboundCheckBankAccountExists.status) - } yield { - (inboundAccountJune2017, status, callContext) - } - - logger.debug(s"Kafka checkBankAccountExists says res is $box") - box - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(accountTTL second){ - val box = callAdapter(callContext) - - box match { - case Full((Some(data), status, callContext)) if (status.errorCode=="") => - Full(new BankAccountJune2017(data), callContext) - case Full((data,status,_)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBankAccount") - - override def checkBankAccountExists(bankId: BankId, accountId: AccountId, callContext: Option[CallContext]) = - Future { - (checkBankAccountExistsLegacy(bankId, accountId, callContext).map(_._1), callContext) - } - - messageDocs += MessageDoc( - process = "obp.getCoreBankAccounts", - messageFormat = messageFormat, - description = "getCoreBankAccounts from kafka", - exampleOutboundMessage = ( - OutboundGetAccountbyAccountID( - authInfoExample, - "bankId", - "accountId" - ) - ), - exampleInboundMessage = ( - InboundGetAccountbyAccountID( - authInfoExample, - statusExample, - Some(InboundAccountJune2017("", cbsToken = "cbsToken", bankId = "gh.29.uk", branchId = "222", accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = "Susan" :: " Frank" :: Nil, viewsToGenerate = "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil)))) - ) - override def getCoreBankAccountsLegacy(BankIdAccountIds: List[BankIdAccountId], @CacheKeyOmit callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundGetCoreBankAccounts( - authInfo = authInfo, - BankIdAccountIds - ) - _ <- Full(logger.debug(s"Kafka getCoreBankAccounts says: req is: $req")) - kafkaMessage <- processToBox(req) - inboundGetCoreBankAccounts <- tryo { - kafkaMessage.extract[InboundGetCoreBankAccounts] - } ?~! s"$InboundGetCoreBankAccounts extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - internalInboundCoreAccounts <- Full(inboundGetCoreBankAccounts.data) - } yield { - (internalInboundCoreAccounts,callContext) - } - logger.debug(s"Kafka getCoreBankAccounts says res is $box") - box - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(accountTTL second){ - val box= callAdapter(callContext) - - box match { - case Full((list, callContext)) if (list.head.errorCode=="") => - Full(list.map( x => CoreAccount(x.id,x.label,x.bankId,x.accountType, x.accountRoutings)), callContext) - case Full((f,_)) if (f.head.errorCode!="") => - Failure("INTERNAL-"+ f.head.errorCode+". + CoreBank-Status:"+ f.head.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBankAccounts") - - override def getCoreBankAccounts(BankIdAccountIds: List[BankIdAccountId], @CacheKeyOmit callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val req = OutboundGetCoreBankAccounts( - authInfo = getAuthInfo(callContext).openOrThrowException(NoCallContext), - BankIdAccountIds - ) - logger.debug(s"Kafka getCoreBankAccountsFuture says: req is: $req") - - val future = for { - res <- processToFuture[OutboundGetCoreBankAccounts](req) map { - f => - try { - f.extract[InboundGetCoreBankAccounts] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetCoreBankAccounts extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - (_.data) - } - } yield { - (res, callContext) - } - logger.debug(s"Kafka getCoreBankAccountsFuture says res is $future") - future - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(accountsTTL second){ - - val future = callAdapter(callContext) - - future map { - case (list, callContext) if (list.head.errorCode=="") => - Full(list.map( x => CoreAccount(x.id,x.label,x.bankId,x.accountType, x.accountRoutings)), callContext) - case (list,_) if (list.head.errorCode!="") => - Failure("INTERNAL-"+ list.head.errorCode+". + CoreBank-Status:"+ list.head.backendMessages) - case (List(),_) => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getCoreBankAccountsFuture") - - messageDocs += MessageDoc( - process = "obp.getTransactions", - messageFormat = messageFormat, - description = "getTransactions from kafka", - exampleOutboundMessage = ( - OutboundGetTransactions( - authInfo = authInfoExample, - bankId = "bankId", - accountId = "accountId", - limit =100, - fromDate="DateWithSecondsExampleObject", - toDate="DateWithSecondsExampleObject" - ) - ), - exampleInboundMessage = ( - InboundGetTransactions( - authInfoExample, - statusExample, - InternalTransaction_vJune2017( - transactionId = "String", - accountId = "String", - amount = "String", - bankId = "String", - completedDate = "String", - counterpartyId = "String", - counterpartyName = "String", - currency = "String", - description = "String", - newBalanceAmount = "String", - newBalanceCurrency = "String", - postedDate = "String", - `type` = "String", - userId = "String")::Nil)) - ) - // TODO Get rid on these param lookups and document. - override def getTransactionsLegacy(bankId: BankId, accountId: AccountId, callContext: Option[CallContext], queryParams: List[OBPQueryParam]) = saveConnectorMetric { - val limit = queryParams.collect { case OBPLimit(value) => value }.headOption.getOrElse(100) - val fromDate = queryParams.collect { case OBPFromDate(date) => date.toString }.headOption.getOrElse(APIUtil.DefaultFromDate.toString) - val toDate = queryParams.collect { case OBPToDate(date) => date.toString }.headOption.getOrElse(APIUtil.DefaultToDate.toString) - - - - //Note: because there is `queryParams: List[OBPQueryParam]` in getTransactions, so create the getTransactionsCached to cache data. - def getTransactionsCached(bankId: BankId, accountId: AccountId, limit: Int, fromDate: String, toDate: String, callContext: Option[CallContext]): Box[(List[Transaction], Option[CallContext])] = { - - val req = OutboundGetTransactions( - authInfo = getAuthInfo(callContext).openOrThrowException(NoCallContext), - bankId = bankId.toString, - accountId = accountId.value, - limit = limit, - fromDate = fromDate, - toDate = toDate - ) - - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - def callAdapter(callContext: Option[CallContext]) = { - val box = for { - kafkaMessage <- processToBox(req) - inboundGetTransactions <- tryo { - kafkaMessage.extract[InboundGetTransactions] - } ?~! s"$InvalidConnectorResponseForGetTransactions $InboundGetTransactions extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (internalTransactions, status) <- Full(inboundGetTransactions.data, inboundGetTransactions.status) - } yield { - (internalTransactions, status, callContext) - } - logger.debug(s"Kafka getTransactions says: res is: $box") - box - } - - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(transactionsTTL second) { - logger.debug(s"Kafka getTransactions says: req is: $req") - val box = callAdapter(callContext) - - box match { - case Full((data, status, _)) if (status.errorCode != "") => - Failure("INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages) - case Full((data, status,_)) if (!data.forall(x => x.accountId == accountId.value && x.bankId == bankId.value)) => - Failure(InvalidConnectorResponseForGetTransactions) - case Full((data, status,callContext)) if (status.errorCode == "") => - val bankAccountAndcallContext1 = checkBankAccountExistsLegacy(BankId(data.head.bankId), AccountId(data.head.accountId), callContext) - - val res = for { - internalTransaction <- data - thisBankAccount <- bankAccountAndcallContext1.map(_._1) ?~! ErrorMessages.BankAccountNotFound - transaction <- createInMemoryTransaction(thisBankAccount, internalTransaction) - } yield { - transaction - } - Full((res, bankAccountAndcallContext1.map(_._2).openOrThrowException(attemptedToOpenAnEmptyBox))) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - } - getTransactionsCached(bankId: BankId, accountId: AccountId, limit: Int, fromDate: String, toDate: String, callContext: Option[CallContext]) - - }("getTransactions") - - override def getTransactionsCore(bankId: BankId, accountId: AccountId, queryParams: List[OBPQueryParam], callContext: Option[CallContext]) = saveConnectorMetric{ - val limit = queryParams.collect { case OBPLimit(value) => value}.headOption.getOrElse(100) - val fromDate = queryParams.collect { case OBPFromDate(date) => date.toString}.headOption.getOrElse(APIUtil.DefaultFromDate.toString) - val toDate = queryParams.collect { case OBPToDate(date) => date.toString}.headOption.getOrElse(APIUtil.DefaultToDate.toString) - - - - //Note: because there is `queryParams: List[OBPQueryParam]` in getTransactions, so create the getTransactionsCoreCached to cache data. - //Note: getTransactionsCoreCached and getTransactionsCached have the same parameters,but the different method name. - //TODO, here the cache need to be fixed, no sense use callContext as the cache key here. - def getTransactionsCoreCached(bankId: BankId, accountId: AccountId, limit: Int,fromDate :String, toDate: String, callContext: Option[CallContext]): Box[(List[TransactionCore], Option[CallContext])] = { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - def callAdapter(callContext: Option[CallContext]) = { - val req = OutboundGetTransactions( - authInfo = getAuthInfo(callContext).openOrThrowException(NoCallContext), - bankId = bankId.toString, - accountId = accountId.value, - limit = limit, - fromDate = fromDate, - toDate = toDate - ) - - logger.debug(s"Kafka getTransactions says: req is: $req") - val box = for { - kafkaMessage <- processToBox(req) - inboundGetTransactions <- tryo { - kafkaMessage.extract[InboundGetTransactions] - } ?~! s"$InvalidConnectorResponseForGetTransactions $InboundGetTransactions extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (internalTransactions, status) <- Full(inboundGetTransactions.data, inboundGetTransactions.status) - } yield { - (internalTransactions, status, callContext) - } - logger.debug(s"Kafka getTransactions says: res is: $box") - box - } - - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(transactionsTTL second) { - val box = callAdapter(callContext) - - box match { - case Full((data, status,callContext)) if (status.errorCode != "") => - Failure("INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages) - case Full((data, status,callContext)) if (!data.forall(x => x.accountId == accountId.value && x.bankId == bankId.value)) => - Failure(InvalidConnectorResponseForGetTransactions) - case Full((data, status,callContext)) if (status.errorCode == "") => - val bankAccountAndCallContext = checkBankAccountExistsLegacy(BankId(data.head.bankId), AccountId(data.head.accountId), callContext) - - val res = for { - internalTransaction <- data - thisBankAccount <- bankAccountAndCallContext.map(_._1) ?~! ErrorMessages.BankAccountNotFound - transaction <- createInMemoryTransactionCore(thisBankAccount, internalTransaction) - } yield { - transaction - } - Full(res, bankAccountAndCallContext.map(_._2).openOrThrowException(s"$attemptedToOpenAnEmptyBox. getTransactionsCoreCached.bankAccountAndCallContext.map(_._2).")) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - } - Future{getTransactionsCoreCached(bankId: BankId, accountId: AccountId, limit: Int,fromDate :String, toDate: String, callContext: Option[CallContext])} - - }("getTransactions") - - messageDocs += MessageDoc( - process = "obp.getTransaction", - messageFormat = messageFormat, - description = "getTransaction from kafka ", - exampleOutboundMessage = ( - OutboundGetTransaction( - authInfoExample, - "bankId", - "accountId", - "transactionId" - ) - ), - exampleInboundMessage = ( - InboundGetTransaction(authInfoExample, statusExample, Some(InternalTransaction_vJune2017( - transactionId = "String", - accountId = "String", - amount = "String", - bankId = "String", - completedDate = "String", - counterpartyId = "String", - counterpartyName = "String", - currency = "String", - description = "String", - newBalanceAmount = "String", - newBalanceCurrency = "String", - postedDate = "String", - `type` = "String", - userId = "String" - ))) - ) - ) - override def getTransactionLegacy(bankId: BankId, accountId: AccountId, transactionId: TransactionId, callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundGetTransaction(authInfo, bankId.value, accountId.value, transactionId.value) - _ <- Full(logger.debug(s"Kafka getTransaction Req says: is: $req")) - kafkaMessage <- processToBox(req) - inboundGetTransaction <- tryo { - kafkaMessage.extract[InboundGetTransaction] - } ?~! s"$InvalidConnectorResponseForGetTransaction $InboundGetTransaction extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (internalTransaction, status) <- Full(inboundGetTransaction.data, inboundGetTransaction.status) - } yield { - (internalTransaction, status, callContext) - } - logger.debug(s"Kafka getTransaction Res says: is: $box") - box - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(transactionTTL second){ - val box = callAdapter(callContext) - - box match { - // Check does the response data match the requested data - case Full((Some(data), status, callContext)) if (transactionId.value != data.transactionId) => - Failure(s"$InvalidConnectorResponseForGetTransaction") - case Full((data,status, callContext)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Full((Some(data), status, callContext)) if (transactionId.value == data.transactionId && status.errorCode=="") => - for { - (bankAccount, callContext) <- checkBankAccountExistsLegacy(BankId(data.bankId), AccountId(data.accountId),callContext) ?~! ErrorMessages.BankAccountNotFound - transaction: Transaction <- createInMemoryTransaction(bankAccount,data) - } yield { - (transaction,callContext) - } - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - }}("getTransaction") - - messageDocs += MessageDoc( - process = "obp.createChallenge", - messageFormat = messageFormat, - description = "CreateChallenge from kafka ", - exampleOutboundMessage = ( - OutboundChallengeBase( - action = "obp.createChallenge", - messageFormat = messageFormat, - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - transactionRequestType = "SANDBOX_TAN", - transactionRequestId = "1234567" - ) - ), - exampleInboundMessage = ( - InboundCreateChallengeJune2017( - authInfoExample, - InternalCreateChallengeJune2017( - errorCodeExample, - inboundStatusMessagesExample, - "1234" - ) - ) - ), - outboundAvroSchema = Some(parse(SchemaFor[OutboundCreateChallengeJune2017]().toString(true))), - inboundAvroSchema = Some(parse(SchemaFor[InboundCreateChallengeJune2017]().toString(true))) - ) - override def createChallenge(bankId: BankId, accountId: AccountId, userId: String, transactionRequestType: TransactionRequestType, transactionRequestId: String, scaMethod: Option[SCA], callContext: Option[CallContext]) = { - - val authInfo = getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox) - val req = OutboundCreateChallengeJune2017( - authInfo = authInfo, - bankId = bankId.value, - accountId = accountId.value, - userId = userId, - username = AuthUser.getCurrentUserUsername, - transactionRequestType = transactionRequestType.value, - transactionRequestId = transactionRequestId - ) - - logger.debug(s"Kafka createChallenge Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundCreateChallengeJune2017](req) map { - f => - try { - f.extract[InboundCreateChallengeJune2017] - } catch { - case e: Exception => throw new MappingException(s"$InboundCreateChallengeJune2017 extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { x => (x.authInfo, x.data) } - } yield { - Full(res) - } - - val res = future map { - case Full((authInfo,x)) if (x.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - (Full(x.answer), callContextUpdated) - case Full((authInfo, x)) if (x.errorCode!="") => - (Failure("INTERNAL-"+ x.errorCode+". + CoreBank-Status:"+ x.backendMessages), callContext) - case _ => - (Failure(ErrorMessages.UnknownError), callContext) - } - res - } - - messageDocs += MessageDoc( - process = "obp.createCounterparty", - messageFormat = messageFormat, - description = "createCounterparty from kafka ", - exampleOutboundMessage = ( - OutboundCreateCounterparty( - authInfoExample, - OutboundCounterparty( - name = "name", - description = "description", - createdByUserId = "createdByUserId", - thisBankId = "thisBankId", - thisAccountId = "thisAccountId", - thisViewId = "thisViewId", - otherAccountRoutingScheme = "otherAccountRoutingScheme", - otherAccountRoutingAddress = "otherAccountRoutingAddress", - otherAccountSecondaryRoutingScheme = "otherAccountSecondaryRoutingScheme", - otherAccountSecondaryRoutingAddress = "otherAccountSecondaryRoutingAddress", - otherBankRoutingScheme = "otherBankRoutingScheme", - otherBankRoutingAddress = "otherBankRoutingAddress", - otherBranchRoutingScheme = "otherBranchRoutingScheme", - otherBranchRoutingAddress = "otherBranchRoutingAddress", - isBeneficiary = true, - bespoke = CounterpartyBespoke("key","value") ::Nil - ) - ) - ), - exampleInboundMessage = ( - InboundCreateCounterparty( - authInfoExample, - statusExample, - Some(InternalCounterparty( - createdByUserId= "String", - name= "String", - thisBankId= "String", - thisAccountId= "String", - thisViewId= "String", - counterpartyId= "String", - otherAccountRoutingScheme= "String", - otherAccountRoutingAddress= "String", - otherBankRoutingScheme= "String", - otherBankRoutingAddress= "String", - otherBranchRoutingScheme= "String", - otherBranchRoutingAddress= "String", - isBeneficiary = false, - description= "String", - currency= "String", - otherAccountSecondaryRoutingScheme= "String", - otherAccountSecondaryRoutingAddress= "String", - bespoke = List(CounterpartyBespoke( - key = "String", - value = "String" - ))))) - ) - ) - override def createCounterparty( - name: String, - description: String, - currency: String, - createdByUserId: String, - thisBankId: String, - thisAccountId: String, - thisViewId: String, - otherAccountRoutingScheme: String, - otherAccountRoutingAddress: String, - otherAccountSecondaryRoutingScheme: String, - otherAccountSecondaryRoutingAddress: String, - otherBankRoutingScheme: String, - otherBankRoutingAddress: String, - otherBranchRoutingScheme: String, - otherBranchRoutingAddress: String, - isBeneficiary:Boolean, - bespoke: List[CounterpartyBespoke], - callContext: Option[CallContext]) = { - - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundCreateCounterparty( - authInfo = authInfo, - counterparty = OutboundCounterparty( - name: String, - description: String, - createdByUserId: String, - thisBankId: String, - thisAccountId: String, - thisViewId: String, - otherAccountRoutingScheme: String, - otherAccountRoutingAddress: String, - otherAccountSecondaryRoutingScheme: String, - otherAccountSecondaryRoutingAddress: String, - otherBankRoutingScheme: String, - otherBankRoutingAddress: String, - otherBranchRoutingScheme: String, - otherBranchRoutingAddress: String, - isBeneficiary:Boolean, - bespoke: List[CounterpartyBespoke]) - ) - _<- Full(logger.debug(s"Kafka createCounterparty Req says: is: $req")) - kafkaMessage <- processToBox(req) - inboundCreateCounterparty <- tryo{kafkaMessage.extract[InboundCreateCounterparty]} ?~! s"$InboundCreateCounterparty extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (authInfo, internalCounterparty, status) <- Full(inboundCreateCounterparty.authInfo, inboundCreateCounterparty.data, inboundCreateCounterparty.status) - } yield{ - (authInfo, internalCounterparty, status) - } - logger.debug(s"Kafka createCounterparty Res says: is: $box") - - val res = box match { - case Full((authInfo, Some(data), status)) if (status.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full(data, callContextUpdated) - case Full((authInfo, data, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - res - } - - messageDocs += MessageDoc( - process = "obp.getTransactionRequests210", - messageFormat = messageFormat, - description = "getTransactionRequests210 from kafka ", - exampleOutboundMessage = ( - OutboundGetTransactionRequests210( - authInfoExample, - OutboundTransactionRequests( - "accountId: String", - "accountType: String", - "currency: String", - "iban: String", - "number: String", - "bankId: BankId", - "branchId: String", - "accountRoutingScheme: String", - "accountRoutingAddress: String" - ) - ) - ), - exampleInboundMessage = ( - InboundGetTransactionRequests210( - authInfoExample, - statusExample, - List( - TransactionRequest( - id = TransactionRequestId("id"), - `type` = "String", - from = TransactionRequestAccount("10", "12"), - body = SwaggerDefinitionsJSON.transactionRequestBodyAllTypes, - transaction_ids = "", - status = "COMPLETED", - start_date = DateWithSecondsExampleObject, - end_date = DateWithSecondsExampleObject, - challenge = TransactionRequestChallenge("", 0, ""), - charge = TransactionRequestCharge( - "", - AmountOfMoney("ILS", "0") - ), - charge_policy = "", - counterparty_id = CounterpartyId(""), - name = "name", - this_bank_id = BankId("10"), - this_account_id = AccountId("1"), - this_view_id = ViewId(""), - other_account_routing_scheme = "", - other_account_routing_address = "", - other_bank_routing_scheme = "", - other_bank_routing_address = "", - is_beneficiary = false) - ) - ) - ) - - ) - override def getTransactionRequests210(user : User, fromAccount : BankAccount, callContext: Option[CallContext] = None) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundGetTransactionRequests210( - authInfo = authInfo, - counterparty = OutboundTransactionRequests( - accountId = fromAccount.accountId.value, - accountType = fromAccount.accountType, - currency = fromAccount.currency, - iban = fromAccount.accountRoutings.find(_.scheme == AccountRoutingScheme.IBAN.toString).map(_.scheme).getOrElse(""), - number = fromAccount.number, - bankId = fromAccount.bankId.value, - branchId = fromAccount.bankId.value, - accountRoutingScheme = fromAccount.accountRoutings.headOption.map(_.scheme).getOrElse(""), - accountRoutingAddress = fromAccount.accountRoutings.headOption.map(_.address).getOrElse("")) - ) - _ <- Full(logger.debug(s"Kafka getTransactionRequests210 Req says: is: $req")) - kafkaMessage <- processToBox(req) - inboundGetTransactionRequests210 <- tryo { - kafkaMessage.extract[InboundGetTransactionRequests210] - } ?~! s"$InvalidConnectorResponseForGetTransactionRequests210, $InboundGetTransactionRequests210 extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (internalGetTransactionRequests, status) <- Full(inboundGetTransactionRequests210.data, inboundGetTransactionRequests210.status) - } yield { - (internalGetTransactionRequests, status, callContext) - } - logger.debug(s"Kafka getTransactionRequests210 Res says: is: $box") - box - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(transactionRequests210TTL second){ - - val box = callAdapter(callContext) - - val res = box match { - case Full((data, status, callContext)) if (status.errorCode=="") => - //For consistency with sandbox mode, we need combine obp transactions in database and adapter transactions - val transactionRequests = for{ - adapterTransactionRequests <- Full(data) - //TODO, this will cause performance issue, we need limit the number of transaction requests. - obpTransactionRequests <- LocalMappedConnector.getTransactionRequestsImpl210(fromAccount) ?~! s"$InvalidConnectorResponse, error on LocalMappedConnector.getTransactionRequestsImpl210" - } yield { - adapterTransactionRequests ::: obpTransactionRequests - } - transactionRequests.map(transactionRequests =>(transactionRequests, callContext)) - case Full((data, status, _)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - res - } - } - }("getTransactionRequests210") - - messageDocs += MessageDoc( - process = "obp.getCounterparties", - messageFormat = messageFormat, - description = "getCounterparties from kafka ", - exampleOutboundMessage = ( - OutboundGetCounterparties( - authInfoExample, - InternalOutboundGetCounterparties( - thisBankId = "String", - thisAccountId = "String", - viewId = "String" - ) - ) - ), - exampleInboundMessage = ( - InboundGetCounterparties(authInfoExample, statusExample, - InternalCounterparty( - createdByUserId = "", - name = "", - thisBankId = "", - thisAccountId = "", - thisViewId = "", - counterpartyId = "", - otherAccountRoutingScheme = "", - otherAccountRoutingAddress = "", - otherBankRoutingScheme = "", - otherBankRoutingAddress = "", - otherBranchRoutingScheme = "", - otherBranchRoutingAddress = "", - isBeneficiary = true, - description = "", - currency= "", - otherAccountSecondaryRoutingScheme = "", - otherAccountSecondaryRoutingAddress = "", - bespoke = List( - CounterpartyBespoke(key = "key", value = "value")) - ) :: Nil - ) - ) - ) - - override def getCounterpartiesLegacy(thisBankId: BankId, thisAccountId: AccountId, viewId :ViewId, callContext: Option[CallContext] ) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(counterpartiesTTL second){ - val box = for { - authInfo <- getAuthInfo(callContext) - req = OutboundGetCounterparties( - authInfo = authInfo, - counterparty = InternalOutboundGetCounterparties( - thisBankId = thisBankId.value, - thisAccountId = thisAccountId.value, - viewId = viewId.value) - ) - _<-Full(logger.debug(s"Kafka getCounterparties Req says: is: $req")) - kafkaMessage <- processToBox(req) - inboundGetCounterparties <- tryo{kafkaMessage.extract[InboundGetCounterparties]} ?~! s"$InboundGetCounterparties extract error. Both check API and Adapter Inbound Case Classes need be the same ! " - (authInfo, internalCounterparties, status) <- Full(inboundGetCounterparties.authInfo, inboundGetCounterparties.data, inboundGetCounterparties.status) - } yield{ - (authInfo, internalCounterparties, status) - } - logger.debug(s"Kafka getCounterparties Res says: is: $box") - - val res = box match { - case Full((authInfo, data, status)) if (status.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full((data, callContextUpdated)) - case Full((authInfo, data, status)) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case Empty => - Failure(ErrorMessages.InvalidConnectorResponse) - case Failure(msg, e, c) => - Failure(msg, e, c) - case _ => - Failure(ErrorMessages.UnknownError) - } - res - } - } - }("getCounterparties") - override def getCounterparties(thisBankId: BankId, thisAccountId: AccountId, viewId: ViewId, callContext: Option[CallContext] = None): OBPReturnType[Box[List[CounterpartyTrait]]] = Future { - (getCounterpartiesLegacy(thisBankId, thisAccountId, viewId, callContext) map (i => i._1), callContext) - } - - messageDocs += MessageDoc( - process = "obp.getCounterpartyByCounterpartyId", - messageFormat = messageFormat, - description = "getCounterpartyByCounterpartyId from kafka ", - exampleOutboundMessage = ( - OutboundGetCounterpartyByCounterpartyId( - authInfoExample, - OutboundGetCounterpartyById( - counterpartyId = "String" - ) - ) - ), - exampleInboundMessage = ( - InboundGetCounterparty(authInfoExample, statusExample, Some(InternalCounterparty(createdByUserId = "String", name = "String", thisBankId = "String", thisAccountId = "String", thisViewId = "String", counterpartyId = "String", otherAccountRoutingScheme = "String", otherAccountRoutingAddress = "String", otherBankRoutingScheme = "String", otherBankRoutingAddress = "String", otherBranchRoutingScheme = "String", otherBranchRoutingAddress = "String", isBeneficiary = true, description = "String", currency = "String", otherAccountSecondaryRoutingScheme = "String", otherAccountSecondaryRoutingAddress = "String", bespoke = Nil))) - ) - ) - override def getCounterpartyByCounterpartyId(counterpartyId: CounterpartyId, callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(counterpartyByCounterpartyIdTTL second) { - val req = OutboundGetCounterpartyByCounterpartyId(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), OutboundGetCounterpartyById(counterpartyId.value)) - logger.debug(s"Kafka getCounterpartyByCounterpartyId Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetCounterpartyByCounterpartyId](req) map { - f => - try { - f.extract[InboundGetCounterparty] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetCounterparty extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { x => (x.authInfo, x.data, x.status) } - } yield { - Full(res) - } - logger.debug(s"Kafka getCounterpartyByCounterpartyId Res says: is: $future") - - val res = future map { - case Full((authInfo, Some(data), status)) if (status.errorCode == "") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - (Full(data), callContextUpdated) - case Full((authInfo, data, status)) if (status.errorCode != "") => - (Failure("INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages), callContext) - case _ => - (Failure(ErrorMessages.UnknownError), callContext) - } - res - } - } - }("getCounterpartyByCounterpartyId") - - - override def getCounterpartyTrait(thisBankId: BankId, thisAccountId: AccountId, couterpartyId: String, callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(counterpartyTrait second){ - - val req = OutboundGetCounterparty(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), thisBankId.value, thisAccountId.value, couterpartyId) - logger.debug(s"Kafka getCounterpartyTrait Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetCounterparty](req) map { - f => - try { - f.extract[InboundGetCounterparty] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetCounterparty extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { x => (x.authInfo, x.data, x.status) } - } yield { - Full(res) - } - logger.debug(s"Kafka getCounterpartyTrait Res says: is: $future") - - val res = future map { - case Full((authInfo, Some(data), status)) if (status.errorCode=="") => - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - (Full(data), callContextUpdated) - case Full((authInfo, data, status)) if (status.errorCode!="") => - (Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages), callContext) - case _ => - (Failure(ErrorMessages.UnknownError), callContext) - } - res - } - } - }("getCounterpartyTrait") - - - messageDocs += MessageDoc( - process = "obp.getCustomersByUserIdBox", - messageFormat = messageFormat, - description = "getCustomersByUserIdBox from kafka ", - exampleOutboundMessage = ( - OutboundGetCustomersByUserId( - authInfoExample - ) - ), - exampleInboundMessage = ( - InboundGetCustomersByUserId( - authInfoExample, - statusExample, - InternalCustomer( - customerId = "String", bankId = "String", number = "String", - legalName = "String", mobileNumber = "String", email = "String", - faceImage = CustomerFaceImage(date = DateWithSecondsExampleObject, url = "String"), - dateOfBirth = DateWithSecondsExampleObject, relationshipStatus = "String", - dependents = 1, dobOfDependents = List(DateWithSecondsExampleObject), - highestEducationAttained = "String", employmentStatus = "String", - creditRating = CreditRating(rating = "String", source = "String"), - creditLimit = CreditLimit(currency = "String", amount = "String"), - kycStatus = false, lastOkDate = DateWithSecondsExampleObject - ) :: Nil - ) - ), - outboundAvroSchema = None, - inboundAvroSchema = None - ) - - override def getCustomersByUserId(userId: String, @CacheKeyOmit callContext: Option[CallContext]) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - - def callAdapter(callContext: Option[CallContext]) = { - val req = OutboundGetCustomersByUserId(getAuthInfo(callContext).openOrThrowException(NoCallContext)) - logger.debug(s"Kafka getCustomersByUserIdFuture Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetCustomersByUserId](req) map { - f => - try { - f.extract[InboundGetCustomersByUserId] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetCustomersByUserId extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { x => (x.data, x.status, callContext) } - } yield { - res - } - logger.debug(s"Kafka getCustomersByUserIdFuture Res says: is: $future") - future - } - - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(customersByUserIdTTL second) { - - val future: Future[(List[InternalCustomer], Status, Option[CallContext])] = callAdapter(callContext) - - val res = future map { - case (list, status, callerContext1) if (status.errorCode=="") => - Full(JsonFactory_vJune2017.createObpCustomers(list), callerContext1) - case (_, status, _) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:" + status.backendMessages) - case (List(),status, _) => - Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - case _ => - Failure(ErrorMessages.UnknownError) - } - res - } - } - }("getCustomersByUserIdFuture") - - - messageDocs += MessageDoc( - process = "obp.getStatusOfCheckbookOrdersFuture", - messageFormat = messageFormat, - description = "getStatusOfCheckbookOrdersFuture from kafka ", - exampleOutboundMessage = ( - OutboundGetCheckbookOrderStatus( - authInfoExample, - bankId = "bankId", - accountId ="accountId", - originatorApplication ="String", - originatorStationIP = "String", - primaryAccount =""//TODO not sure for now. - ) - ), - exampleInboundMessage = ( - InboundGetChecksOrderStatus( - authInfoExample, - statusExample, - SwaggerDefinitionsJSON.checkbookOrdersJson - ) - ) - ) - - override def getCheckbookOrders( - bankId: String, - accountId: String, - @CacheKeyOmit callContext: Option[CallContext] - ) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(statusOfCheckbookOrders second) { - - val req = OutboundGetCheckbookOrderStatus( - authInfo = getAuthInfo(callContext).openOrThrowException(NoCallContext), - bankId = bankId, - accountId =accountId, - originatorApplication = "String", - originatorStationIP = "String", - primaryAccount = "" - ) - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCheckbookOrdersFuture Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetCheckbookOrderStatus](req) map { - f => - try { - f.extract[InboundGetChecksOrderStatus] - } catch { - case e: Exception => throw new MappingException(s"correlationId(${req.authInfo.correlationId}): $InboundGetChecksOrderStatus extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map {x => (x.authInfo, x.data, x.status)} - } yield{ - res - } - - val res = future map { - case (authInfo, checksOrderStatusResponseDetails, status) if (status.errorCode=="") => - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCheckbookOrdersFuture Res says: is: $checksOrderStatusResponseDetails") - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full((checksOrderStatusResponseDetails, callContextUpdated)) - case (authInfo, accountDetails, status) if (status.errorCode!="") => - val errorMessage = "INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCheckbookOrdersFuture Res says: is: $errorMessage") - Failure(errorMessage) - case _ => - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCheckbookOrdersFuture Res says: is: $UnknownError") - Failure(UnknownError) - } - res - } - } - }("getCheckbookOrdersFuture") - - - messageDocs += MessageDoc( - process = "obp.getStatusOfCreditCardOrderFuture", - messageFormat = messageFormat, - description = "getStatusOfCreditCardOrderFuture from kafka ", - exampleOutboundMessage = ( - OutboundGetCreditCardOrderStatus( - authInfoExample, - bankId = "bankId", - accountId ="accountId", - originatorApplication = "String", - originatorStationIP = "String", - primaryAccount = "" - ) - ), - exampleInboundMessage = ( - InboundGetCreditCardOrderStatus( - authInfoExample, - statusExample, - List(InboundCardDetails( - "OrderId", - "CreditCardType" , - "CardDescription", - "UseType", - "OrderDate", - "DeliveryStatus", - "StatusDate", - "Branch" - ) - ) - )) - ) - - override def getStatusOfCreditCardOrder( - bankId: String, - accountId: String, - @CacheKeyOmit callContext: Option[CallContext] - ) = saveConnectorMetric{ - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(statusOfCreditcardOrders second) { - - val req = OutboundGetCreditCardOrderStatus( - authInfo = getAuthInfo(callContext).openOrThrowException(NoCallContext), - bankId = bankId, - accountId =accountId, - originatorApplication ="String", - originatorStationIP = "String", - primaryAccount =""//TODO not sure for now. - ) - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCreditCardOrderFuture Req says: is: $req") - - val future = for { - res <- processToFuture[OutboundGetCreditCardOrderStatus](req) map { - f => - try { - f.extract[InboundGetCreditCardOrderStatus] - } catch { - case e: Exception => throw new MappingException(s"correlationId(${req.authInfo.correlationId}): $InboundCardDetails extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map {x => (x.authInfo, x.data, x.status)} - } yield{ - res - } - - val res = future map { - case (authInfo, checksOrderStatusResponseDetails, status) if (status.errorCode=="") => - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCreditCardOrderFuture Res says: is: $checksOrderStatusResponseDetails") - val callContextUpdated = ApiSession.updateSessionId(callContext, authInfo.sessionId) - Full(checksOrderStatusResponseDetails.map( - card =>CardObjectJson( - card_type= card.creditCardType, - card_description = card.cardDescription, - use_type= card.creditCardType - )), callContextUpdated) - case (authInfo, accountDetails, status) if (status.errorCode!="") => - val errorMessage = "INTERNAL-" + status.errorCode + ". + CoreBank-Status:" + status.backendMessages - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCreditCardOrderFuture Res says: is: $errorMessage") - Failure(errorMessage) - case _ => - logger.debug(s"correlationId(${req.authInfo.correlationId}): Kafka getStatusOfCreditCardOrderFuture Res says: is: $UnknownError") - Failure(UnknownError) - } - res - } - } - }("getStatusOfCreditCardOrderFuture") - - ///////////////////////////////////////////////////////////////////////////// - // Helper for creating a transaction - def createInMemoryTransaction(bankAccount: BankAccount,internalTransaction: InternalTransaction_vJune2017): Box[Transaction] = { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(memoryTransactionTTL second) { - for { - datePosted <- tryo { - new SimpleDateFormat(DateWithDay2).parse(internalTransaction.postedDate) - } ?~! s"$InvalidConnectorResponseForGetTransaction Wrong posteDate format should be $DateWithDay2, current is ${internalTransaction.postedDate}" - dateCompleted <- tryo { - new SimpleDateFormat(DateWithDay2).parse(internalTransaction.completedDate) - } ?~! s"$InvalidConnectorResponseForGetTransaction Wrong completedDate format should be $DateWithDay2, current is ${internalTransaction.completedDate}" - - counterpartyName <- tryo { - internalTransaction.counterpartyName - } ?~! s"$InvalidConnectorResponseForGetTransaction. Can not get counterpartyName from Adapter. " - //2018-07-18, here we can not get enough data from Adapter, so we only use counterpartyName set to otherAccountRoutingScheme and otherAccountRoutingAddress. - counterpartyId <- Full(APIUtil.createImplicitCounterpartyId(bankAccount.bankId.value, bankAccount.accountId.value, counterpartyName,counterpartyName,counterpartyName)) - counterparty <- createInMemoryCounterparty(bankAccount, counterpartyName, counterpartyId) - - } yield { - // Create new transaction - new Transaction( - internalTransaction.transactionId, // uuid:String - TransactionId(internalTransaction.transactionId), // id:TransactionId - bankAccount, // thisAccount:BankAccount - counterparty, // otherAccount:OtherBankAccount - internalTransaction.`type`, // transactionType:String - BigDecimal(internalTransaction.amount), // val amount:BigDecimal - bankAccount.currency, // currency:String - Some(internalTransaction.description), // description:Option[String] - datePosted, // startDate:Date - dateCompleted, // finishDate:Date - BigDecimal(internalTransaction.newBalanceAmount) // balance:BigDecimal) - ) - } - } - } - } - - def createInMemoryTransactionCore(bankAccount: BankAccount,internalTransaction: InternalTransaction_vJune2017): Box[TransactionCore] = { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(memoryTransactionTTL second) { - for { - datePosted <- tryo { - new SimpleDateFormat(DateWithDay2).parse(internalTransaction.postedDate) - } ?~! s"$InvalidConnectorResponseForGetTransaction Wrong posteDate format should be $DateWithDay2, current is ${internalTransaction.postedDate}" - dateCompleted <- tryo { - new SimpleDateFormat(DateWithDay2).parse(internalTransaction.completedDate) - } ?~! s"$InvalidConnectorResponseForGetTransaction Wrong completedDate format should be $DateWithDay2, current is ${internalTransaction.completedDate}" - counterpartyCore <- Full(CounterpartyCore( - //2018-07-18, here we can not get enough data from Adapter, so we only use counterpartyName set to otherAccountRoutingScheme and otherAccountRoutingAddress. - counterpartyId = APIUtil.createImplicitCounterpartyId(bankAccount.bankId.value, bankAccount.accountId.value, internalTransaction.counterpartyName, - internalTransaction.counterpartyName,internalTransaction.counterpartyName), - counterpartyName = internalTransaction.counterpartyName, - kind = null, - thisBankId = BankId(""), - thisAccountId = AccountId(""), - otherBankRoutingScheme = "", - otherBankRoutingAddress = None, - otherAccountRoutingScheme = "", - otherAccountRoutingAddress = None, - otherAccountProvider = "", - isBeneficiary = true - )) - } yield { - // Create new transaction - TransactionCore( - TransactionId(internalTransaction.transactionId), // id:TransactionId - bankAccount, // thisAccount:BankAccount - counterpartyCore, // otherAccount:OtherBankAccount - internalTransaction.`type`, // transactionType:String - BigDecimal(internalTransaction.amount), // val amount:BigDecimal - bankAccount.currency, // currency:String - Some(internalTransaction.description), // description:Option[String] - datePosted, // startDate:Date - dateCompleted, // finishDate:Date - BigDecimal(internalTransaction.newBalanceAmount) // balance:BigDecimal) - ) - } - } - } - } - - // Helper for creating other bank account, this will not create it in database, only in scala code. - //Note, we have a method called createCounterparty in this connector, so named it here. - def createInMemoryCounterparty(bankAccount: BankAccount, counterpartyName: String, counterpartyId: String): Box[Counterparty] = { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeSyncWithProvider(Some(cacheKey.toString()))(memoryCounterpartyTTL second){ - Full( - Counterparty( - thisBankId = BankId(bankAccount.bankId.value), - thisAccountId = bankAccount.accountId, - counterpartyId = counterpartyId, - counterpartyName = counterpartyName, - - otherBankRoutingAddress = None, - otherAccountRoutingAddress = None, - otherBankRoutingScheme = null, - otherAccountRoutingScheme = null, - otherAccountProvider = null, - isBeneficiary = true, - - kind = null, - nationalIdentifier = null - ) - ) - } - } - } - - messageDocs += MessageDoc( - process = "obp.getBranches", - messageFormat = messageFormat, - description = "getBranches", - exampleOutboundMessage = ( - OutboundGetBranches(authInfoExample,"bankid") - ), - exampleInboundMessage = ( - InboundGetBranches( - authInfoExample, - Status("", - inboundStatusMessagesExample), - InboundBranchVJune2017( - branchId = BranchId(""), - bankId = BankId(""), - name = "", - address = Address(line1 = "", - line2 = "", - line3 = "", - city = "", - county = Some(""), - state = "", - postCode = "", - //ISO_3166-1_alpha-2 - countryCode = ""), - location = Location(11,11, None,None), - lobbyString = None, - driveUpString = None, - meta = Meta(License("","")), - branchRouting = None, - lobby = Some(Lobby(monday = List(OpeningTimes("","")), - tuesday = List(OpeningTimes("","")), - wednesday = List(OpeningTimes("","")), - thursday = List(OpeningTimes("","")), - friday = List(OpeningTimes("","")), - saturday = List(OpeningTimes("","")), - sunday = List(OpeningTimes("","")) - )), - driveUp = None, - // Easy access for people who use wheelchairs etc. - isAccessible = Some(true), - accessibleFeatures = None, - branchType = Some(""), - moreInfo = Some(""), - phoneNumber = Some(""), - isDeleted = Some(false) - ) :: Nil - ) - - ) - ) - - override def getBranches(bankId: BankId, callContext: Option[CallContext], queryParams: List[OBPQueryParam]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(branchesTTL second){ - val req = OutboundGetBranches(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), bankId.toString) - logger.debug(s"Kafka getBranchesFuture Req is: $req") - - val future: Future[(List[InboundBranchVJune2017], Status)] = for { - res <- processToFuture[OutboundGetBranches](req) map { - f => - try { - f.extract[InboundGetBranches] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetBranches extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - d => (d.data, d.status) - } - } yield { - res - } - - logger.debug(s"Kafka getBranchFuture Res says: is: $future") - future map { - case (branches, status) if (status.errorCode=="") => - Full(branches, callContext) - case (_, status) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBranchesFuture") - - messageDocs += MessageDoc( - process = "obp.getBranch", - messageFormat = messageFormat, - description = "getBranch", - exampleOutboundMessage = ( - OutboundGetBranch(authInfoExample,"bankid", "branchid") - ), - exampleInboundMessage = ( - InboundGetBranch( - authInfoExample, - Status("", - inboundStatusMessagesExample), - Some(InboundBranchVJune2017( - branchId = BranchId(""), - bankId = BankId(""), - name = "", - address = Address(line1 = "", - line2 = "", - line3 = "", - city = "", - county = Some(""), - state = "", - postCode = "", - //ISO_3166-1_alpha-2 - countryCode = ""), - location = Location(11,11, None,None), - lobbyString = None, - driveUpString = None, - meta = Meta(License("","")), - branchRouting = None, - lobby = Some(Lobby(monday = List(OpeningTimes("","")), - tuesday = List(OpeningTimes("","")), - wednesday = List(OpeningTimes("","")), - thursday = List(OpeningTimes("","")), - friday = List(OpeningTimes("","")), - saturday = List(OpeningTimes("","")), - sunday = List(OpeningTimes("","")) - )), - driveUp = None, - // Easy access for people who use wheelchairs etc. - isAccessible = Some(true), - accessibleFeatures = None, - branchType = Some(""), - moreInfo = Some(""), - phoneNumber = Some(""), - isDeleted = Some(false) - )) - ) - - ) - ) - - override def getBranch(bankId : BankId, branchId: BranchId, callContext: Option[CallContext]) = saveConnectorMetric { - - logger.debug("Enter getBranch for: " + branchId) - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(branchTTL second){ - val req = OutboundGetBranch(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), bankId.toString, branchId.toString) - logger.debug(s"Kafka getBranchFuture Req is: $req") - - val future: Future[(Option[InboundBranchVJune2017], Status)] = for { - res <- processToFuture[OutboundGetBranch](req) map { - f => - try { - f.extract[InboundGetBranch] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetBranch extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - d => (d.data, d.status) - } - } yield { - res - } - - logger.debug(s"Kafka getBranchFuture Res says: is: $future") - future map { - case (Some(branch), status) if (status.errorCode=="") => - Full(branch, callContext) - case (_, status) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getBranchFuture") - - - messageDocs += MessageDoc( - process = "obp.getAtms", - messageFormat = messageFormat, - description = "getAtms", - exampleOutboundMessage = ( - OutboundGetAtms(authInfoExample,"bankid") - ), - exampleInboundMessage = ( - InboundGetAtms( - authInfoExample, - Status(errorCodeExample, inboundStatusMessagesExample), - InboundAtmJune2017( - atmId = AtmId("333"), - bankId = BankId("10"), - name = "", - address = Address(line1 = "", - line2 = "", - line3 = "", - city = "", - county = Some(""), - state = "", - postCode = "", - //ISO_3166-1_alpha-2 - countryCode = ""), - location = Location(11,11, None,None), - meta = Meta(License(id = "pddl", name = "Open Data Commons Public Domain Dedication and License (PDDL)")), - OpeningTimeOnMonday = Some(""), - ClosingTimeOnMonday = Some(""), - - OpeningTimeOnTuesday = Some(""), - ClosingTimeOnTuesday = Some(""), - - OpeningTimeOnWednesday = Some(""), - ClosingTimeOnWednesday = Some(""), - - OpeningTimeOnThursday = Some(""), - ClosingTimeOnThursday = Some(""), - - OpeningTimeOnFriday = Some(""), - ClosingTimeOnFriday = Some(""), - - OpeningTimeOnSaturday = Some(""), - ClosingTimeOnSaturday = Some(""), - - OpeningTimeOnSunday = Some(""), - ClosingTimeOnSunday = Some(""), - isAccessible = Some(true), - - locatedAt = Some(""), - moreInfo = Some(""), - hasDepositCapability = Some(true) - ) :: Nil - ) - - ) - ) - - override def getAtms(bankId: BankId, callContext: Option[CallContext], queryParams: List[OBPQueryParam]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(atmsTTL second){ - val req = OutboundGetAtms(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), bankId.value) - logger.debug(s"Kafka getAtmsFuture Req is: $req") - - val future = for { - res <- processToFuture[OutboundGetAtms](req) map { - f => - try { - f.extract[InboundGetAtms] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetAtms extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - d => (d.data, d.status) - } - } yield { - res - } - - logger.debug(s"Kafka getAtmsFuture Res says: is: $future") - future map { - case (atms, status) if (status.errorCode=="") => - Full(atms, callContext) - case (_, status) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getAtmsFuture") - - messageDocs += MessageDoc( - process = "obp.getAtm", - messageFormat = messageFormat, - description = "getAtm", - exampleOutboundMessage = ( - OutboundGetAtm(authInfoExample,"bankId", "atmId") - ), - exampleInboundMessage = ( - InboundGetAtm( - authInfoExample, - Status(errorCodeExample, inboundStatusMessagesExample), - Some(InboundAtmJune2017( - atmId = AtmId("333"), - bankId = BankId("10"), - name = "", - address = Address(line1 = "", - line2 = "", - line3 = "", - city = "", - county = Some(""), - state = "", - postCode = "", - //ISO_3166-1_alpha-2 - countryCode = ""), - location = Location(11,11, None,None), - meta = Meta(License(id = "pddl", name = "Open Data Commons Public Domain Dedication and License (PDDL)")), - OpeningTimeOnMonday = Some(""), - ClosingTimeOnMonday = Some(""), - - OpeningTimeOnTuesday = Some(""), - ClosingTimeOnTuesday = Some(""), - - OpeningTimeOnWednesday = Some(""), - ClosingTimeOnWednesday = Some(""), - - OpeningTimeOnThursday = Some(""), - ClosingTimeOnThursday = Some(""), - - OpeningTimeOnFriday = Some(""), - ClosingTimeOnFriday = Some(""), - - OpeningTimeOnSaturday = Some(""), - ClosingTimeOnSaturday = Some(""), - - OpeningTimeOnSunday = Some(""), - ClosingTimeOnSunday = Some(""), - isAccessible = Some(true), - - locatedAt = Some(""), - moreInfo = Some(""), - hasDepositCapability = Some(true) - ) - )) - - ) - ) - - override def getAtm(bankId : BankId, atmId: AtmId, callContext: Option[CallContext]) = saveConnectorMetric { - /** - * Please note that "var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString)" - * is just a temporary value field with UUID values in order to prevent any ambiguity. - * The real value will be assigned by Macro during compile time at this line of a code: - * https://github.com/OpenBankProject/scala-macros/blob/master/macros/src/main/scala/com/tesobe/CacheKeyFromArgumentsMacro.scala#L49 - */ - var cacheKey = (randomUUID().toString, randomUUID().toString, randomUUID().toString) - CacheKeyFromArguments.buildCacheKey { - Caching.memoizeWithProvider(Some(cacheKey.toString()))(atmTTL second){ - val req = OutboundGetAtm(getAuthInfo(callContext).openOrThrowException(attemptedToOpenAnEmptyBox), bankId.value, atmId.value) - logger.debug(s"Kafka getAtmFuture Req is: $req") - - val future: Future[(Option[InboundAtmJune2017], Status)] = for { - res <- processToFuture[OutboundGetAtm](req) map { - f => - try { - f.extract[InboundGetAtm] - } catch { - case e: Exception => throw new MappingException(s"$InboundGetAtm extract error. Both check API and Adapter Inbound Case Classes need be the same ! ", e) - } - } map { - d => (d.data, d.status) - } - } yield { - res - } - - logger.debug(s"Kafka getAtmFuture Res says: is: $future") - future map { - case (Some(atm), status) if (status.errorCode=="") => - Full(atm, callContext) - case (_, status) if (status.errorCode!="") => - Failure("INTERNAL-"+ status.errorCode+". + CoreBank-Status:"+ status.backendMessages) - case _ => - Failure(ErrorMessages.UnknownError) - } - } - } - }("getAtmFuture") - - -} - - -object KafkaMappedConnector_vJune2017 extends KafkaMappedConnector_vJune2017{ - -} \ No newline at end of file diff --git a/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaJsonFactory_vMar2017.scala b/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaJsonFactory_vMar2017.scala deleted file mode 100644 index 09e40d2c5..000000000 --- a/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaJsonFactory_vMar2017.scala +++ /dev/null @@ -1,600 +0,0 @@ -/** -Open Bank Project - API -Copyright (C) 2011-2019, TESOBE GmbH. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -Email: contact@tesobe.com -TESOBE GmbH. -Osloer Strasse 16/17 -Berlin 13359, Germany - -This product includes software developed at -TESOBE (http://www.tesobe.com/) - - */ -package code.bankconnectors.vMar2017 - -import java.util.Date - -import code.api.util.APIUtil -import code.api.util.APIUtil.{MessageDoc} -import com.openbankproject.commons.model.FXRate -import code.model._ -import code.model.dataAccess.MappedBankAccountData -import com.openbankproject.commons.model.TransactionRequestTypeCharge -import com.openbankproject.commons.model.{CounterpartyTrait, _} -import net.liftweb.json.JsonAST.JValue -import net.liftweb.mapper.By -import net.liftweb.util.Helpers.today - -import scala.collection.immutable.List - - - -// Only used for import -case class InboundAccountData( - banks: List[InboundBank], - users: List[InboundUser], - accounts: List[InboundAccount_vMar2017] -) - -case class OutboundUserByUsernamePasswordBase( - messageFormat: String, - action: String, - username: String, - password: String -)extends OutboundMessageBase - -case class OutboundAdapterInfo( - messageFormat: String, - action: String, - date: String -) extends OutboundMessageBase - -case class OutboundUserAccountViewsBase( - messageFormat: String, - action: String, - username: String, - userId: String, - bankId: String -)extends OutboundMessageBase - - -case class OutboundBanksBase( - messageFormat: String, - action: String, - username: String, - userId: String -) extends OutboundMessageBase - -case class OUTTBank( - messageFormat: String, - action: String, - bankId: String, - userId: String, - username: String -)extends OutboundMessageBase - -case class OutboundChallengeThresholdBase( - messageFormat: String, - action: String, - bankId: String, - accountId: String, - viewId: String, - transactionRequestType: String, - currency: String, - userId: String, - username: String -) extends OutboundMessageBase - -case class OutboundChargeLevelBase( - messageFormat: String, - action: String, - bankId: String, - accountId: String, - viewId: String, - userId: String, - username: String, - transactionRequestType: String, - currency: String -) extends OutboundMessageBase - -case class OutboundChallengeBase( - messageFormat: String, - action: String, - bankId: String, - accountId: String, - userId: String, - username: String, - transactionRequestType: String, - transactionRequestId: String -) extends OutboundMessageBase - -case class OutboundChallengeAnswerBase( - messageFormat: String, - action: String, - userId: String, - username: String, - challengeId: String, - hashOfSuppliedAnswer: String -) extends OutboundMessageBase - -case class OutboundTransactionQueryBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - accountId: String, - transactionId: String -) extends OutboundMessageBase - -case class OutboundTransactionsQueryWithParamsBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - accountId: String, - queryParams: String -) extends OutboundMessageBase - -case class OutboundBankAccountBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - accountId: String -) extends OutboundMessageBase - -case class OutboundBankAccountsBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - accountId: String -) extends OutboundMessageBase - -case class OutboundAccountByNumberBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - number: String -) extends OutboundMessageBase - -case class OutboundCounterpartyByIbanBase( - messageFormat: String, - action: String, - userId: String, - username: String, - otherAccountRoutingAddress: String, - otherAccountRoutingScheme: String -) extends OutboundMessageBase - -case class OutboundCounterpartyByCounterpartyIdBase( - messageFormat: String, - action: String, - userId: String, - username: String, - counterpartyId: String -) extends OutboundMessageBase - -case class OutboundSaveTransactionBase( - messageFormat: String, - action: String, - userId: String, - username: String, - - // fromAccount - fromAccountName: String, - fromAccountId: String, - fromAccountBankId: String, - - // transaction details - transactionId: String, - transactionRequestType: String, - transactionAmount: String, - transactionCurrency: String, - transactionChargePolicy: String, - transactionChargeAmount: String, - transactionChargeCurrency: String, - transactionDescription: String, - transactionPostedDate: String, - - // toAccount or toCounterparty - toCounterpartyId: String, - toCounterpartyName: String, - toCounterpartyCurrency: String, - toCounterpartyRoutingAddress: String, - toCounterpartyRoutingScheme: String, - toCounterpartyBankRoutingAddress: String, - toCounterpartyBankRoutingScheme: String -) extends OutboundMessageBase - -case class OutboundTransactionRequestStatusesBase( - messageFormat: String, - action: String -) extends OutboundMessageBase - -case class OutboundCurrentFxRateBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - fromCurrencyCode: String, - toCurrencyCode: String -) extends OutboundMessageBase - -case class OutboundTransactionRequestTypeChargeBase( - messageFormat: String, - action: String, - userId: String, - username: String, - bankId: String, - accountId: String, - viewId: String, - transactionRequestType: String -) extends OutboundMessageBase - -case class InboundValidatedUser( - errorCode: String, - backendMessages: List[InboundStatusMessage], - email: String, - displayName: String -) extends InboundMessageBase - -case class InboundCounterparty( - errorCode: String, - name: String, - createdByUserId: String, - thisBankId: String, - thisAccountId: String, - thisViewId: String, - counterpartyId: String, - otherBankRoutingScheme: String, - otherBankRoutingAddress: String, - otherAccountRoutingScheme: String, - otherAccountRoutingAddress: String, - otherBranchRoutingScheme: String, - otherBranchRoutingAddress: String, - isBeneficiary: Boolean -) extends InboundMessageBase - -case class CounterpartyTrait2(counterparty: InboundCounterparty) extends CounterpartyTrait { - - def createdByUserId: String = counterparty.createdByUserId - def name: String = counterparty.name - def thisBankId: String = counterparty.thisBankId - def thisAccountId: String = counterparty.thisAccountId - def thisViewId: String = counterparty.thisViewId - def counterpartyId: String = counterparty.counterpartyId - def otherAccountRoutingScheme: String = counterparty.otherAccountRoutingScheme - def otherAccountRoutingAddress: String = counterparty.otherAccountRoutingAddress - def otherBankRoutingScheme: String = counterparty.otherBankRoutingScheme - def otherBankRoutingAddress: String = counterparty.otherBankRoutingAddress - def otherBranchRoutingScheme: String = counterparty.otherBranchRoutingScheme - def otherBranchRoutingAddress: String = counterparty.otherBranchRoutingAddress - def isBeneficiary: Boolean = counterparty.isBeneficiary - def description: String = "" - def currency: String = "" - def otherAccountSecondaryRoutingScheme: String = "" - def otherAccountSecondaryRoutingAddress: String = "" - def bespoke: List[CounterpartyBespoke] = Nil -} - -case class InboundBank( - bankId: String, - name: String, - logo: String, - url: String -) - -case class Bank2(r: InboundBank) extends Bank { - - def fullName = r.name - def shortName = r.name - def logoUrl = r.logo - def bankId = BankId(r.bankId) - def nationalIdentifier = "None" - def swiftBic = "None" - def websiteUrl = r.url - def bankRoutingScheme = "None" - def bankRoutingAddress = "None" -} - -case class InboundAccount_vMar2017( - errorCode: String, - accountId: String, - bankId: String, - label: String, - number: String, - `type`: String, - balanceAmount: String, - balanceCurrency: String, - iban: String, - owners: List[String], - generatePublicView: Boolean, - generateAccountantsView: Boolean, - generateAuditorsView: Boolean, - accountRoutingScheme: String = "None", - accountRoutingAddress: String = "None", - branchId: String = "None" -)extends InboundMessageBase - - - - - - -case class BankAccount2(r: InboundAccount_vMar2017) extends BankAccount { - - def accountId: AccountId = AccountId(r.accountId) - def accountType: String = r.`type` - def balance: BigDecimal = BigDecimal(r.balanceAmount) - def currency: String = r.balanceCurrency - def name: String = r.owners.head - def iban: Option[String] = Some(r.iban) - def number: String = r.number - def bankId: BankId = BankId(r.bankId) - def lastUpdate: Date = APIUtil.DateWithMsFormat.parse(today.getTime.toString) - def accountHolder: String = r.owners.head - - // Fields modifiable from OBP are stored in mapper - def label: String = (for { - d <- MappedBankAccountData.find(By(MappedBankAccountData.accountId, r.accountId)) - } yield { - d.getLabel - }).getOrElse(r.number) - - def accountRoutingScheme: String = r.accountRoutingScheme - def accountRoutingAddress: String = r.accountRoutingAddress - def accountRoutings: List[AccountRouting] = List() - def branchId: String = r.branchId - - def accountRules: List[AccountRule] = List() - -} - -case class InboundFXRate( - errorCode: String, - bankId: String, - fromCurrencyCode: String, - toCurrencyCode: String, - conversionValue: Double, - inverseConversionValue: Double, - effectiveDate: String -)extends InboundMessageBase - -case class FXRate2(inboundFxRate: InboundFXRate) extends FXRate { - - def bankId: BankId = BankId(inboundFxRate.bankId) - def fromCurrencyCode: String = inboundFxRate.fromCurrencyCode - def toCurrencyCode: String = inboundFxRate.toCurrencyCode - def conversionValue: Double = inboundFxRate.conversionValue - def inverseConversionValue: Double = inboundFxRate.inverseConversionValue - //TODO need to add error handling here for String --> Date transfer - def effectiveDate: Date = APIUtil.DateWithMsFormat.parse(inboundFxRate.effectiveDate) -} - -case class InboundTransactionRequestTypeCharge( - errorCode: String, - transactionRequestType: String, - bankId: String, - chargeCurrency: String, - chargeAmount: String, - chargeSummary: String -)extends InboundMessageBase - -case class TransactionRequestTypeCharge2(inboundTransactionRequestTypeCharge: InboundTransactionRequestTypeCharge) extends TransactionRequestTypeCharge { - - def transactionRequestTypeId: String = inboundTransactionRequestTypeCharge.transactionRequestType - def bankId: String = inboundTransactionRequestTypeCharge.bankId - def chargeCurrency: String = inboundTransactionRequestTypeCharge.chargeCurrency - def chargeAmount: String = inboundTransactionRequestTypeCharge.chargeAmount - def chargeSummary: String = inboundTransactionRequestTypeCharge.chargeSummary -} - -case class InboundTransactionStatus( - transactionId: String, - transactionStatus: String, - transactionTimestamp: String -) extends TransactionStatus - -case class InboundTransactionRequestStatus( - transactionRequestId: String, - bulkTransactionsStatus: List[InboundTransactionStatus] -) - -case class TransactionRequestStatus2(kafkaInboundTransactionRequestStatus: InboundTransactionRequestStatus) extends TransactionRequestStatus { - - override def transactionRequestId: String = kafkaInboundTransactionRequestStatus.transactionRequestId - override def bulkTransactionsStatus: List[TransactionStatus] = kafkaInboundTransactionRequestStatus.bulkTransactionsStatus -} - - -/** Bank Branches - * - * @param id Uniquely identifies the Branch within the Bank. SHOULD be url friendly (no spaces etc.) Used in URLs - * @param bankId MUST match bank_id in Banks - * @param name Informal name for the Branch - * @param address Address - * @param location Geolocation - * @param meta Meta information including the license this information is published under - * @param lobby Info about when the lobby doors are open - * @param driveUp Info about when automated facilities are open e.g. cash point machine - */ -case class InboundBranch( - id: String, - bankId: String, - name: String, - address: InboundAddress, - location: InboundLocation, - meta: InboundMeta, - lobby: Option[InboundLobby], - driveUp: Option[InboundDriveUp] -) - -case class InboundLicense( - id: String, - name: String -) - -case class InboundMeta( - license: InboundLicense -) - -case class InboundLobby( - hours: String -) - -case class InboundDriveUp( - hours: String -) - -/** - * - * @param line1 Line 1 of Address - * @param line2 Line 2 of Address - * @param line3 Line 3 of Address - * @param city City - * @param county County i.e. Division of State - * @param state State i.e. Division of Country - * @param postCode Post Code or Zip Code - * @param countryCode 2 letter country code: ISO 3166-1 alpha-2 - */ -case class InboundAddress( - line1: String, - line2: String, - line3: String, - city: String, - county: String, // Division of State - state: String, // Division of Country - postCode: String, - countryCode: String -) - -case class InboundLocation( - latitude: Double, - longitude: Double -) - - -//InboundTransaction --> InternalTransaction -->OutboundTransaction -case class InternalTransaction( - errorCode: String, - backendMessages: List[InboundStatusMessage], - transactionId: String, - accountId: String, - amount: String, - bankId: String, - completedDate: String, - counterpartyId: String, - counterpartyName: String, - currency: String, - description: String, - newBalanceAmount: String, - newBalanceCurrency: String, - postedDate: String, - `type`: String, - userId: String -)extends InboundMessageBase - -case class InboundAtm( - id: String, - bankId: String, - name: String, - address: InboundAddress, - location: InboundLocation, - meta: InboundMeta -) - -case class InboundProduct( - bankId: String, - code: String, - name: String, - category: String, - family: String, - superFamily: String, - moreInfoUrl: String, - meta: InboundMeta -) - - -case class InboundCrmEvent( - id: String, // crmEventId - bankId: String, - customer: InboundCustomer, - category: String, - detail: String, - channel: String, - actualDate: String -) - -case class InboundCustomer( - name: String, - number: String // customer number, also known as ownerId (owner of accounts) aka API User? -) - -case class InboundTransactionId( - errorCode: String, - transactionId: String -)extends InboundMessageBase - -case class OutboundTransaction( - action: String, - version: String, - userId: String, - userName: String, - accountId: String, - currency: String, - amount: String, - otherAccountId: String, - otherAccountCurrency: String, - transactionType: String) - -case class InboundChallengeLevel( - errorCode: String, - limit: String, - currency: String -)extends InboundMessageBase - - -case class InboundCreateChallange( - errorCode: String, - challengeId: String -)extends InboundMessageBase - -case class InboundValidateChallangeAnswer( - answer: String, - errorCode: String -)extends InboundMessageBase - -case class InboundChargeLevel( - errorCode: String, - currency: String, - amount: String -)extends InboundMessageBase - - -object JsonFactory_vMar2017 { - // moved to Json factory v2.0.0 -} - - diff --git a/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaMappedConnector_vMar2017.scala b/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaMappedConnector_vMar2017.scala deleted file mode 100644 index b49e27138..000000000 --- a/obp-api/src/main/scala/code/bankconnectors/vMar2017/KafkaMappedConnector_vMar2017.scala +++ /dev/null @@ -1,1650 +0,0 @@ -package code.bankconnectors.vMar2017 - -/* -Open Bank Project - API -Copyright (C) 2011-2017, TESOBE GmbH - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see http://www.gnu.org/licenses/. - -Email: contact@tesobe.com -TESOBE GmbH -Osloerstrasse 16/17 -Berlin 13359, Germany -*/ - -import java.util.Date - -import code.api.Constant._ -import code.api.util.APIUtil.MessageDoc -import code.api.util.ErrorMessages._ -import com.openbankproject.commons.model.enums.StrongCustomerAuthentication.SCA -import code.api.util._ -import code.api.v2_1_0._ -import code.bankconnectors._ -import code.branches.Branches.Branch -import code.fx.fx -import com.openbankproject.commons.model.FXRate -import code.kafka.KafkaHelper -import code.management.ImporterAPI.ImporterTransaction -import code.metadata.comments.Comments -import code.metadata.counterparties.Counterparties -import code.metadata.narrative.MappedNarrative -import code.metadata.tags.Tags -import code.metadata.transactionimages.TransactionImages -import code.metadata.wheretags.WhereTags -import code.model._ -import code.model.dataAccess._ -import com.openbankproject.commons.model.Product -import code.transaction.MappedTransaction -import code.transactionrequests.TransactionRequests.TransactionRequestTypes._ -import code.transactionrequests.TransactionRequests._ -import code.transactionrequests.TransactionRequests -import com.openbankproject.commons.model.TransactionRequestTypeCharge -import code.util.Helper.MdcLoggable -import code.util.{Helper, TTLCache} -import code.views.Views -import com.openbankproject.commons.model.{Bank, _} -import net.liftweb.common._ -import net.liftweb.mapper._ -import net.liftweb.util.Helpers._ - -import scala.collection.immutable.{List, Nil, Seq} -import com.openbankproject.commons.ExecutionContext.Implicits.global -import com.openbankproject.commons.dto.GetProductsParam - -import scala.concurrent.Future - -trait KafkaMappedConnector_vMar2017 extends Connector with KafkaHelper with MdcLoggable { - - implicit override val nameOfConnector = KafkaMappedConnector_vMar2017.getClass.getSimpleName - - // Local TTL Cache - val cacheTTL = APIUtil.getPropsValue("connector.cache.ttl.seconds", "10").toInt - val cachedUser = TTLCache[InboundValidatedUser](cacheTTL) - val cachedBank = TTLCache[InboundBank](cacheTTL) - val cachedAccount = TTLCache[InboundAccount_vMar2017](cacheTTL) - val cachedBanks = TTLCache[List[InboundBank]](cacheTTL) - val cachedAccounts = TTLCache[List[InboundAccount_vMar2017]](cacheTTL) - val cachedPublicAccounts = TTLCache[List[InboundAccount_vMar2017]](cacheTTL) - val cachedUserAccounts = TTLCache[List[InboundAccount_vMar2017]](cacheTTL) - val cachedFxRate = TTLCache[InboundFXRate](cacheTTL) - val cachedCounterparty = TTLCache[InboundCounterparty](cacheTTL) - val cachedTransactionRequestTypeCharge = TTLCache[InboundTransactionRequestTypeCharge](cacheTTL) - - - // "Versioning" of the messages sent by this or similar connector works like this: - // Use Case Classes (e.g. KafkaInbound... KafkaOutbound... as below to describe the message structures. - // Each connector has a separate file like this one. - // Once the message format is STABLE, freeze the key/value pair names there. For now, new keys may be added but none modified. - // If we want to add a new message format, create a new file e.g. March2017_messages.scala - // Then add a suffix to the connector value i.e. instead of kafka we might have kafka_march_2017. - // Then in this file, populate the different case classes depending on the connector name and send to Kafka - - - val messageFormat: String = "Mar2017" - - val currentResourceUserId = AuthUser.getCurrentResourceUserUserId - - // Each Message Doc has a process, description, example outbound and inbound messages. - - messageDocs += MessageDoc( - process = "obp.getUser", - messageFormat = messageFormat, - description = "getUser from kafka ", - exampleOutboundMessage = ( - OutboundUserByUsernamePasswordBase( - messageFormat = messageFormat, - action = "obp.getUser", - username = "susan.uk.29@example.com", - password = "2b78e8" - ) - ), - exampleInboundMessage = ( - InboundValidatedUser( - errorCode = "OBP-6001: ...", - List(InboundStatusMessage("ESB", "Success", "0", "OK")), - email = "susan.uk.29@example.com", - displayName = "susan" - ) - ) - ) - - override def getUser( - username: String, - password: String - ): Box[InboundUser] = { - for { - req <- Full(OutboundUserByUsernamePasswordBase( - action = "obp.getUser", - messageFormat = messageFormat, - username = username, - password = password)) - u <- tryo { cachedUser.getOrElseUpdate(req.toString, () => process(req).extract[InboundValidatedUser]) } - recUsername <- tryo { u.displayName } - } yield { - if (username == u.displayName) new InboundUser(recUsername, password, recUsername) - else null - } - } - - // TODO this is confused ? method name is updateUserAccountViews, but action is 'obp.getAccounts' - messageDocs += MessageDoc( - process = "obp.getAccounts", - messageFormat = messageFormat, - description = "updateUserAccountViews from kafka ", - exampleOutboundMessage = ( - OutboundUserAccountViewsBase( - action = "obp.getAccounts", - messageFormat = messageFormat, - username = "susan.uk.29@example.com", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - bankId = "gh.29.uk" - ) - ), - exampleInboundMessage = ( - InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: " Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) - :: InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: " Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) - :: Nil - ) - ) - - override def updateUserAccountViewsOld( user: ResourceUser ) = { - val accounts: List[InboundAccount_vMar2017] = getBanksLegacy(None).map(_._1).openOrThrowException(attemptedToOpenAnEmptyBox).flatMap { bank => { - val bankId = bank.bankId.value - logger.info(s"ObpJvm updateUserAccountViews for user.email ${user.email} user.name ${user.name} at bank ${bankId}") - for { - username <- tryo {user.name} - req <- Full(OutboundUserAccountViewsBase( - messageFormat = messageFormat, - action = "obp.getAccounts", - username = user.name, - userId = user.name, - bankId = bankId)) - - // Generate random uuid to be used as request-response match id - } yield { - cachedUserAccounts.getOrElseUpdate(req.toString, () => process(req).extract[List[InboundAccount_vMar2017]]) - } - } - }.flatten - - val views = for { - acc <- accounts - username <- tryo {user.name} - views <- tryo {createViews( BankId(acc.bankId), - AccountId(acc.accountId), - acc.owners.contains(username), - acc.generatePublicView, - acc.generateAccountantsView, - acc.generateAuditorsView - )} - existing_views <- tryo {Views.views.vend.assignedViewsForAccount(BankIdAccountId(BankId(acc.bankId), AccountId(acc.accountId)))} - } yield { - setAccountHolder(username, BankId(acc.bankId), AccountId(acc.accountId), acc.owners) - views.foreach(v => { - Views.views.vend.grantAccessToCustomView(v.uid, user) - logger.info(s"------------> updated view ${v.uid} for resourceuser ${user} and account ${acc}") - }) - existing_views.filterNot(_.users.contains(user.userPrimaryKey)).foreach (v => { - Views.views.vend.grantAccessToCustomView(v.uid, user) - logger.info(s"------------> added resourceuser ${user} to view ${v.uid} for account ${acc}") - }) - } - } - - messageDocs += MessageDoc( - process = "obp.getBanks", - messageFormat = messageFormat, - description = "getBanks", - exampleOutboundMessage = ( - OutboundBanksBase( - action = "obp.getBanks", - messageFormat = messageFormat, - username = "susan.uk.29@example.com", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a" - ) - ), - exampleInboundMessage = ( - InboundBank( - bankId = "gh.29.uk", - name = "sushan", - logo = "TESOBE", - url = "https://tesobe.com/" - ):: Nil - ) - ) - - //gets banks handled by this connector - override def getBanksLegacy(callContext: Option[CallContext]) = { - val req = OutboundBanksBase( - messageFormat = messageFormat, - action = "obp.getBanks", - username = currentResourceUserId, - userId = AuthUser.getCurrentUserUsername - ) - - logger.debug(s"Kafka getBanks says: req is: $req") - - logger.debug(s"Kafka getBanks before cachedBanks.getOrElseUpdate") - val rList = { - cachedBanks.getOrElseUpdate( req.toString, () => process(req).extract[List[InboundBank]]) - } - logger.debug(s"Kafka getBanks says rList is $rList") - - // Loop through list of responses and create entry for each - val res = { for ( r <- rList ) yield { - new Bank2(r) - } - } - // Return list of results - - logger.debug(s"Kafka getBanks says res is $res") - Full(res, callContext) - } - - messageDocs += MessageDoc( - process = "obp.getChallengeThreshold", - messageFormat = messageFormat, - description = "getChallengeThreshold from kafka ", - exampleOutboundMessage = ( - OutboundChallengeThresholdBase( - messageFormat = messageFormat, - action = "obp.getChallengeThreshold", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - viewId = SYSTEM_OWNER_VIEW_ID, - transactionRequestType = SANDBOX_TAN.toString, - currency = "GBP", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com" - ) - ), - exampleInboundMessage = ( - InboundChallengeLevel( - errorCode = "OBP-6001: ...", - limit = "1000", - currency = "EUR" - ) - ) - ) - - // Gets current challenge level for transaction request - override def getChallengeThreshold(bankId: String, accountId: String, viewId: String, transactionRequestType: String, currency: String, userId: String, username: String, callContext: Option[CallContext]) = Future{ - // Create argument list - val req = OutboundChallengeThresholdBase( - action = "obp.getChallengeThreshold", - messageFormat = messageFormat, - bankId = bankId, - accountId = accountId, - viewId = viewId, - transactionRequestType = transactionRequestType, - currency = currency, - userId = userId, - username = username) - - val r: Option[InboundChallengeLevel] = process(req).extractOpt[InboundChallengeLevel] - // Return result - r match { - // Check does the response data match the requested data - case Some(x) => (Full(AmountOfMoney(x.currency, x.limit)), callContext) - case _ => { - val limit = BigDecimal("0") - val rate = fx.exchangeRate ("EUR", currency, Some(bankId)) - val convertedLimit = fx.convert(limit, rate) - (Full(AmountOfMoney(currency,convertedLimit.toString())), callContext) - } - } - } - - messageDocs += MessageDoc( - process = "obp.getChargeLevel", - messageFormat = messageFormat, - description = "ChargeLevel from kafka ", - exampleOutboundMessage = (OutboundChargeLevelBase( - action = "obp.getChargeLevel", - messageFormat = messageFormat, - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - viewId = SYSTEM_OWNER_VIEW_ID, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - transactionRequestType = SANDBOX_TAN.toString, - currency = "EUR" - ) - ), - exampleInboundMessage = ( - InboundChargeLevel( - errorCode = "OBP-6001: ...", - currency = "EUR", - amount = "" - ) - ) - ) - - override def getChargeLevel( - bankId: BankId, - accountId: AccountId, - viewId: ViewId, - userId: String, - username: String, - transactionRequestType: String, - currency: String, - callContext:Option[CallContext]) = Future { - // Create argument list - val req = OutboundChargeLevelBase( - action = "obp.getChargeLevel", - messageFormat = messageFormat, - bankId = bankId.value, - accountId = accountId.value, - viewId = viewId.value, - transactionRequestType = transactionRequestType, - currency = currency, - userId = userId, - username = username - ) - - val r: Option[InboundChargeLevel] = process(req).extractOpt[InboundChargeLevel] - // Return result - val chargeValue = r match { - // Check does the response data match the requested data - case Some(x) => AmountOfMoney(x.currency, x.amount) - case _ => { - AmountOfMoney("EUR", "0.0001") - } - } - (Full(chargeValue), callContext) - } - - messageDocs += MessageDoc( - process = "obp.createChallenge", - messageFormat = messageFormat, - description = "CreateChallenge from kafka ", - exampleOutboundMessage = ( - OutboundChallengeBase( - action = "obp.createChallenge", - messageFormat = messageFormat, - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - transactionRequestType = SANDBOX_TAN.toString, - transactionRequestId = "1234567" - ) - ), - exampleInboundMessage = ( - InboundCreateChallange( - errorCode = "OBP-6001: ...", - challengeId = "1234567" - ) - ) - ) - - override def createChallenge(bankId: BankId, accountId: AccountId, userId: String, transactionRequestType: TransactionRequestType, transactionRequestId: String, scaMethod: Option[SCA], callContext: Option[CallContext]) = Future { - // Create argument list - val req = OutboundChallengeBase( - messageFormat = messageFormat, - action = "obp.createChallenge", - bankId = bankId.value, - accountId = accountId.value, - userId = userId, - username = AuthUser.getCurrentUserUsername, - transactionRequestType = transactionRequestType.value, - transactionRequestId = transactionRequestId - ) - - val r: Option[InboundCreateChallange] = process(req - ).extractOpt[InboundCreateChallange] - // Return result - r match { - // Check does the response data match the requested data - case Some(x) => (Full(x.challengeId), callContext) - case _ => (Empty, callContext) - } - } - - messageDocs += MessageDoc( - process = "obp.validate.ChallengeAnswer", - messageFormat = messageFormat, - description = "validateChallengeAnswer from kafka ", - exampleOutboundMessage = ( - OutboundChallengeAnswerBase( - messageFormat = messageFormat, - action = "obp.validate.ChallengeAnswer", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - challengeId = "1234", - hashOfSuppliedAnswer = "" - ) - ), - exampleInboundMessage = ( - InboundValidateChallangeAnswer( - errorCode = "OBP-6001: ...", - answer = "" - ) - ) - ) - override def validateChallengeAnswer(challengeId: String, hashOfSuppliedAnswer: String, callContext: Option[CallContext]) = Future { - // Create argument list - val req = OutboundChallengeAnswerBase( - messageFormat = messageFormat, - action = "obp.validate.ChallengeAnswer", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - challengeId = challengeId, - hashOfSuppliedAnswer = hashOfSuppliedAnswer) - - val r: Option[InboundValidateChallangeAnswer] = process(req).extractOpt[InboundValidateChallangeAnswer] - // Return result - r match { - // Check does the response data match the requested data - case Some(x) => (Full(x.answer.toBoolean),callContext) - case _ => (Empty,callContext) - } - } - - messageDocs += MessageDoc( - process = "obp.getBank", - messageFormat = messageFormat, - description = "getBank from kafka ", - exampleOutboundMessage = ( - OUTTBank( - action = "obp.getBank", - messageFormat = messageFormat, - bankId = "gh.29.uk", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com" - ) - ), - exampleInboundMessage = ( - InboundBank( - bankId = "gh.29.uk", - name = "sushan", - logo = "TESOBE", - url = "https://tesobe.com/" - ) - ) - ) - override def getBankLegacy(bankId: BankId, callContext: Option[CallContext]) = { - // Create argument list - val req = OUTTBank( - messageFormat = messageFormat, - action = "obp.getBank", - bankId = bankId.toString, - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername) - - val r = { - cachedBank.getOrElseUpdate(req.toString, () => process(req).extract[InboundBank]) - } - // Return result - Full(new Bank2(r), callContext) - } - - messageDocs += MessageDoc( - process = "obp.getTransaction", - messageFormat = messageFormat, - description = "getTransaction from kafka ", - exampleOutboundMessage = ( - OutboundTransactionQueryBase( - action = "obp.getTransaction", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - transactionId = "" - ) - ), - exampleInboundMessage = ( - InternalTransaction( - errorCode = "OBP-6001: ...", - List(InboundStatusMessage("ESB", "Success", "0", "OK")), - transactionId = "1234", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - amount = "100", - bankId = "gh.29.uk", - completedDate = "", - counterpartyId = "1234", - counterpartyName = "obp", - currency = "EUR", - description = "Good Boy", - newBalanceAmount = "10000", - newBalanceCurrency = "1000", - postedDate = "", - `type` = "AC", - userId = "1234" - ) - ) - ) - // Gets transaction identified by bankid, accountid and transactionId - override def getTransactionLegacy(bankId: BankId, accountId: AccountId, transactionId: TransactionId, callContext: Option[CallContext])= { - val req = OutboundTransactionQueryBase( - messageFormat = messageFormat, - action = "obp.getTransaction", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.toString, - accountId = accountId.toString, - transactionId = transactionId.toString) - - // Since result is single account, we need only first list entry - val r = process(req).extractOpt[InternalTransaction] - r match { - // Check does the response data match the requested data - case Some(x) if transactionId.value != x.transactionId => Failure(ErrorMessages.InvalidConnectorResponseForGetTransaction, Empty, Empty) - case Some(x) if transactionId.value == x.transactionId => createNewTransaction(x).map(transaction =>(transaction, callContext)) - case _ => Failure(ErrorMessages.InvalidConnectorResponse, Empty, Empty) - } - - } - - messageDocs += MessageDoc( - process = "obp.getTransactions", - messageFormat = messageFormat, - description = "getTransactions from kafka", - exampleOutboundMessage = ( - OutboundTransactionsQueryWithParamsBase( - messageFormat = messageFormat, - action = "obp.getTransactions", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - queryParams = "" - ) - ), - exampleInboundMessage = ( - InternalTransaction( - errorCode = "OBP-6001: ...", - List(InboundStatusMessage("ESB", "Success", "0", "OK")), - transactionId = "1234", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - amount = "100", - bankId = "gh.29.uk", - completedDate = "", - counterpartyId = "1234", - counterpartyName = "obp", - currency = "EUR", - description = "Good Boy", - newBalanceAmount = "10000", - newBalanceCurrency = "1000", - postedDate = "", - `type` = "AC", - userId = "1234" - ) :: Nil - ) - ) - //TODO, this action is different from method name - override def getTransactionsLegacy(bankId: BankId, accountId: AccountId, callContext: Option[CallContext], queryParams: List[OBPQueryParam])= { - val limit: OBPLimit = queryParams.collect { case OBPLimit(value) => OBPLimit(value) }.headOption.get - val offset = queryParams.collect { case OBPOffset(value) => OBPOffset(value) }.headOption.get - val fromDate = queryParams.collect { case OBPFromDate(date) => OBPFromDate(date) }.headOption.get - val toDate = queryParams.collect { case OBPToDate(date) => OBPToDate(date)}.headOption.get - val ordering = queryParams.collect { - //we don't care about the intended sort field and only sort on finish date for now - case OBPOrdering(field, direction) => OBPOrdering(field, direction)}.headOption.get - val optionalParams = Seq(limit, offset, fromDate, toDate, ordering) - - val req = OutboundTransactionsQueryWithParamsBase( - messageFormat = messageFormat, - action = "obp.getTransactions", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.toString, - accountId = accountId.toString, - queryParams = queryParams.toString) - - implicit val formats = CustomJsonFormats.formats - val rList = process(req).extract[List[InternalTransaction]] - // Check does the response data match the requested data - val isCorrect = rList.forall(x=>x.accountId == accountId.value && x.bankId == bankId.value) - if (!isCorrect) throw new Exception(ErrorMessages.InvalidConnectorResponseForGetTransactions) - // Populate fields and generate result - val res = for { - r <- rList - transaction <- createNewTransaction(r) - } yield { - transaction - } - Full(res, callContext) - //TODO is this needed updateAccountTransactions(bankId, accountId) - } - - messageDocs += MessageDoc( - process = "obp.getAccount", - messageFormat = messageFormat, - description = "getBankAccount from kafka", - exampleOutboundMessage = ( - OutboundBankAccountBase( - action = "obp.getAccount", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0" - ) - ), - exampleInboundMessage = ( - InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: "Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) - ) - ) - override def getBankAccountLegacy(bankId: BankId, accountId: AccountId, callContext: Option[CallContext]): Box[(BankAccount, Option[CallContext])] = { - // Generate random uuid to be used as request-response match id - val req = OutboundBankAccountBase( - action = "obp.getAccount", - messageFormat = messageFormat, - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.toString, - accountId = accountId.value - ) - - // Since result is single account, we need only first list entry - implicit val formats = CustomJsonFormats.formats - val r = { - cachedAccount.getOrElseUpdate( req.toString, () => process(req).extract[InboundAccount_vMar2017]) - } - // Check does the response data match the requested data - val accResp = List((BankId(r.bankId), AccountId(r.accountId))).toSet - val acc = List((bankId, accountId)).toSet - if ((accResp diff acc).size > 0) throw new Exception(ErrorMessages.InvalidConnectorResponseForGetBankAccount) - - createMappedAccountDataIfNotExisting(r.bankId, r.accountId, r.label) - - Full(new BankAccount2(r), callContext) - } - - messageDocs += MessageDoc( - process = "obp.getAccounts", - messageFormat = messageFormat, - description = "getBankAccounts from kafka", - exampleOutboundMessage = ( - OutboundBankAccountsBase( - messageFormat = messageFormat, - action = "obp.getAccounts", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0" - ) - ), - exampleInboundMessage = ( - InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: "Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) :: InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: "Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) :: Nil - ) - ) - - //TODO the method name is different from action - messageDocs += MessageDoc( - process = "obp.getAccount", - messageFormat = messageFormat, - description = "getAccountByNumber from kafka", - exampleOutboundMessage = ( - OutboundAccountByNumberBase( - action = "obp.getAccount", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - number = "" - ) - ), - exampleInboundMessage = ( - InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = "Susan" :: " Frank" :: Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) - ) - ) - - private def getAccountByNumber(bankId : BankId, number : String) : Box[BankAccount] = { - // Generate random uuid to be used as request-respose match id - val req = OutboundAccountByNumberBase( - messageFormat = messageFormat, - action = "obp.getAccount", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.toString, - number = number - ) - - // Since result is single account, we need only first list entry - implicit val formats = CustomJsonFormats.formats - val r = { - cachedAccount.getOrElseUpdate( req.toString, () => process(req).extract[InboundAccount_vMar2017]) - } - createMappedAccountDataIfNotExisting(r.bankId, r.accountId, r.label) - Full(new BankAccount2(r)) - } - - override def getCounterparty(thisBankId: BankId, thisAccountId: AccountId, couterpartyId: String): Box[Counterparty] = { - //note: kafka mode just used the mapper data - LocalMappedConnector.getCounterparty(thisBankId, thisAccountId, couterpartyId) - } - - - messageDocs += MessageDoc( - process = "obp.getCounterpartyByCounterpartyId", - messageFormat = messageFormat, - description = "getCounterpartyByCounterpartyId from kafka ", - exampleOutboundMessage = ( - OutboundCounterpartyByCounterpartyIdBase( - messageFormat = messageFormat, - action = "obp.getCounterpartyByCounterpartyId", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - counterpartyId = "12344" - ) - ), - exampleInboundMessage = ( - InboundCounterparty( - errorCode = "OBP-6001: ...", - name = "sushan", - createdByUserId = "12345", - thisBankId = "gh.29.uk", - thisAccountId = "12344", - thisViewId = SYSTEM_OWNER_VIEW_ID, - counterpartyId = "123", - otherBankRoutingScheme = "obp", - otherAccountRoutingScheme = "obp", - otherBankRoutingAddress = "1234", - otherAccountRoutingAddress = "1234", - otherBranchRoutingScheme = "OBP", - otherBranchRoutingAddress = "Berlin", - isBeneficiary = true - ) - ) - ) - - override def getCounterpartyByCounterpartyId(counterpartyId: CounterpartyId, callContext: Option[CallContext]) = Future{ - if (APIUtil.getPropsAsBoolValue("get_counterparties_from_OBP_DB", true)) { - (Counterparties.counterparties.vend.getCounterparty(counterpartyId.value), callContext) - } else { - val req = OutboundCounterpartyByCounterpartyIdBase( - messageFormat = messageFormat, - action = "obp.getCounterpartyByCounterpartyId", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - counterpartyId = counterpartyId.toString - ) - // Since result is single account, we need only first list entry - implicit val formats = CustomJsonFormats.formats - val r = { - cachedCounterparty.getOrElseUpdate(req.toString, () => process(req).extract[InboundCounterparty]) - } - (tryo(CounterpartyTrait2(r)), callContext) - } - } - - messageDocs += MessageDoc( - process = "obp.getCounterpartyByIban", - messageFormat = messageFormat, - description = "getCounterpartyByIban from kafka ", - exampleOutboundMessage = ( - OutboundCounterpartyByIbanBase( - messageFormat = messageFormat, - action = "obp.getCounterpartyByIban", - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - otherAccountRoutingAddress = "1234", - otherAccountRoutingScheme = "1234" - ) - ), - exampleInboundMessage = ( - CounterpartyTrait2( - InboundCounterparty( - errorCode = "OBP-6001: ...", - name = "sushan", - createdByUserId = "12345", - thisBankId = "gh.29.uk", - thisAccountId = "12344", - thisViewId = SYSTEM_OWNER_VIEW_ID, - counterpartyId = "123", - otherBankRoutingScheme = "obp", - otherAccountRoutingScheme = "obp", - otherBankRoutingAddress = "1234", - otherAccountRoutingAddress = "1234", - otherBranchRoutingScheme = "OBP", - otherBranchRoutingAddress = "Berlin", - isBeneficiary = true - ) - ) - ) - ) - - override def getCounterpartyByIban(iban: String, callContext: Option[CallContext])= Future{ - if (APIUtil.getPropsAsBoolValue("get_counterparties_from_OBP_DB", true)) { - (Counterparties.counterparties.vend.getCounterpartyByIban(iban), callContext) - } else { - val req = OutboundCounterpartyByIbanBase( - messageFormat = messageFormat, - action = "obp.getCounterpartyByIban", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - otherAccountRoutingAddress = iban, - otherAccountRoutingScheme = "IBAN" - ) - val r = process(req).extract[InboundCounterparty] - (tryo{CounterpartyTrait2(r)}, callContext) - } - } - - messageDocs += MessageDoc( - process = "obp.put.Transaction", - messageFormat = messageFormat, - description = "saveTransaction from kafka", - exampleOutboundMessage = ( - OutboundSaveTransactionBase( - action = "obp.put.Transaction", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - - // fromAccount - fromAccountName = "OBP", - fromAccountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - fromAccountBankId = "gh.29.uk", - - // transaction details - transactionId = "1234", - transactionRequestType = SANDBOX_TAN.toString, - transactionAmount = "100", - transactionCurrency = "EUR", - transactionChargePolicy = "RECEIVER", - transactionChargeAmount = "1000", - transactionChargeCurrency = "12", - transactionDescription = "Tesobe is a good company !", - transactionPostedDate = "", - - // toAccount or toCounterparty - toCounterpartyId = "1234", - toCounterpartyName = "obp", - toCounterpartyCurrency = "EUR", - toCounterpartyRoutingAddress = "1234", - toCounterpartyRoutingScheme = "OBP", - toCounterpartyBankRoutingAddress = "12345", - toCounterpartyBankRoutingScheme = "OBP" - ) - ), - exampleInboundMessage = ( - InboundTransactionId( - - errorCode = "OBP-6001: ...", - transactionId = "1234" - ) - ) - ) - - /** - * Saves a transaction with amount @amount and counterparty @counterparty for account @account. Returns the id - * of the saved transaction. - */ - private def saveTransaction(fromAccount: BankAccount, - toAccount: BankAccount, - transactionRequestCommonBody: TransactionRequestCommonBodyJSON, - amount: BigDecimal, - description: String, - transactionRequestType: TransactionRequestType, - chargePolicy: String): Box[TransactionId] = { - - val postedDate = APIUtil.DateWithMsFormat.format(now) - val transactionId = APIUtil.generateUUID() - - val req = OutboundSaveTransactionBase( - messageFormat = messageFormat, - action = "obp.put.Transaction", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - - // fromAccount - fromAccountName = fromAccount.name, - fromAccountId = fromAccount.accountId.value, - fromAccountBankId = fromAccount.bankId.value, - - // transaction details - transactionId = transactionId, - transactionRequestType = transactionRequestType.value, - transactionAmount = amount.bigDecimal.toString, - transactionCurrency = fromAccount.currency, - transactionChargePolicy = chargePolicy, - transactionChargeAmount = "0.0", // TODO get correct charge amount - transactionChargeCurrency = fromAccount.currency, // TODO get correct charge currency - transactionDescription = description, - transactionPostedDate = postedDate, - - // toCounterparty - toCounterpartyId = toAccount.accountId.value, - toCounterpartyName = toAccount.name, - toCounterpartyCurrency = fromAccount.currency, // TODO toCounterparty.currency - toCounterpartyRoutingAddress = toAccount.accountRoutings.headOption.map(_.address).getOrElse(""), - toCounterpartyRoutingScheme = toAccount.accountRoutings.headOption.map(_.scheme).getOrElse(""), - toCounterpartyBankRoutingAddress = toAccount.bankRoutingAddress, - toCounterpartyBankRoutingScheme = toAccount.bankRoutingScheme - ) - - - // Since result is single account, we need only first list entry - val r = process(req) - - r.extract[InboundTransactionId] match { - case r: InboundTransactionId => Full(TransactionId(r.transactionId)) - case _ => Empty - } - - } - messageDocs += MessageDoc( - process = "obp.getTransactionRequestStatusesImpl", - messageFormat = messageFormat, - description = "getTransactionRequestStatusesImpl from kafka", - exampleOutboundMessage = ( - OutboundTransactionRequestStatusesBase( - messageFormat = messageFormat, - action = "obp.getTransactionRequestStatusesImpl" - ) - ), - exampleInboundMessage = ( - InboundTransactionRequestStatus( - transactionRequestId = "123", - bulkTransactionsStatus = InboundTransactionStatus( - transactionId = "1234", - transactionStatus = "", - transactionTimestamp = "" - ) :: InboundTransactionStatus( - transactionId = "1234", - transactionStatus = "", - transactionTimestamp = "" - ) :: Nil - ) - ) - ) - override def getTransactionRequestStatusesImpl() : Box[TransactionRequestStatus] = { - logger.info(s"tKafka getTransactionRequestStatusesImpl sart: ") - val req = OutboundTransactionRequestStatusesBase( - messageFormat = messageFormat, - action = "obp.getTransactionRequestStatusesImpl" - ) - //TODO need more clear error handling to user, if it is Empty or Error now,all response Empty. - val r = try{ - val response = process(req).extract[InboundTransactionRequestStatus] - Full(new TransactionRequestStatus2(response)) - }catch { - case _ : Throwable => Empty - } - - logger.info(s"Kafka getTransactionRequestStatusesImpl response: ${r.toString}") - r - } - - messageDocs += MessageDoc( - process = "obp.getCurrentFxRate", - messageFormat = messageFormat, - description = "getCurrentFxRate from kafka", - exampleOutboundMessage = ( - OutboundCurrentFxRateBase( - action = "obp.getCurrentFxRate", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "bankid543", - fromCurrencyCode = "1234", - toCurrencyCode = "" - ) - ), - exampleInboundMessage = ( - InboundFXRate( - errorCode = "OBP-6XXXX: .... ", - bankId = "bankid654", - fromCurrencyCode = "1234", - toCurrencyCode = "1234", - conversionValue = 123.44, - inverseConversionValue = 123.44, - effectiveDate = "" - ) - ) - ) - // get the latest FXRate specified by fromCurrencyCode and toCurrencyCode. - override def getCurrentFxRate(bankId: BankId, fromCurrencyCode: String, toCurrencyCode: String): Box[FXRate] = { - // Create request argument list - val req = OutboundCurrentFxRateBase( - messageFormat = messageFormat, - action = "obp.getCurrentFxRate", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.value, - fromCurrencyCode = fromCurrencyCode, - toCurrencyCode = toCurrencyCode) - - val r = { - cachedFxRate.getOrElseUpdate(req.toString, () => process(req).extract[InboundFXRate]) - } - // Return result - Full(new FXRate2(r)) - } - - messageDocs += MessageDoc( - process = "obp.getTransactionRequestTypeCharge", - messageFormat = messageFormat, - description = "getTransactionRequestTypeCharge from kafka", - exampleOutboundMessage = ( - OutboundTransactionRequestTypeChargeBase( - action = "obp.getTransactionRequestTypeCharge", - messageFormat = messageFormat, - userId = "c7b6cb47-cb96-4441-8801-35b57456753a", - username = "susan.uk.29@example.com", - bankId = "gh.29.uk", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - viewId = SYSTEM_OWNER_VIEW_ID, - transactionRequestType = "" - ) - ), - exampleInboundMessage = ( - InboundTransactionRequestTypeCharge( - errorCode = "OBP-6001: ...", - transactionRequestType = "", - bankId = "gh.29.uk", - chargeCurrency = "EUR", - chargeAmount = "2", - chargeSummary = " charge 1 eur" - ) - ) - ) - //get the current charge specified by bankId, accountId, viewId and transactionRequestType - override def getTransactionRequestTypeCharge( - bankId: BankId, - accountId: AccountId, - viewId: ViewId, - transactionRequestType: TransactionRequestType - ): Box[TransactionRequestTypeCharge] = { - - // Create request argument list - val req = OutboundTransactionRequestTypeChargeBase( - messageFormat = messageFormat, - action = "obp.getTransactionRequestTypeCharge", - userId = currentResourceUserId, - username = AuthUser.getCurrentUserUsername, - bankId = bankId.value, - accountId = accountId.value, - viewId = viewId.value, - transactionRequestType = transactionRequestType.value - ) - - // send the request to kafka and get response - // TODO the error handling is not good enough, it should divide the error, empty and no-response. - val r = tryo {cachedTransactionRequestTypeCharge.getOrElseUpdate(req.toString, () => process(req).extract[InboundTransactionRequestTypeCharge])} - - // Return result - val result = r match { - case Full(f) => Full(TransactionRequestTypeCharge2(f)) - case _ => - for { - fromAccount <- getBankAccountOld(bankId, accountId) - fromAccountCurrency <- tryo{ fromAccount.currency } - } yield { - TransactionRequestTypeCharge2(InboundTransactionRequestTypeCharge( - - errorCode = "OBP-6001: ...", - transactionRequestType.value, - bankId.value, - fromAccountCurrency, - "0.00", - "Warning! Default value!" - ) - ) - } - } - - result - } - - -//////////////////////////////Following is not over Kafka now ////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////////// - - protected override def makePaymentImpl( - fromAccount: BankAccount, - toAccount: BankAccount, - transactionRequestCommonBody: TransactionRequestCommonBodyJSON, - amt: BigDecimal, - description: String, - transactionRequestType: TransactionRequestType, - chargePolicy: String): Box[TransactionId] = { - - val sentTransactionId = saveTransaction(fromAccount, - toAccount, - transactionRequestCommonBody, - amt, - description, - transactionRequestType, - chargePolicy) - - sentTransactionId - } - - - override def createTransactionRequestImpl(transactionRequestId: TransactionRequestId, transactionRequestType: TransactionRequestType, - account : BankAccount, counterparty : BankAccount, body: TransactionRequestBody, - status: String, charge: TransactionRequestCharge) : Box[TransactionRequest] = { - TransactionRequests.transactionRequestProvider.vend.createTransactionRequestImpl(transactionRequestId, - transactionRequestType, - account, - counterparty, - body, - status, - charge) - } - - //Note: now call the local mapper to store data - override def saveTransactionRequestTransactionImpl(transactionRequestId: TransactionRequestId, transactionId: TransactionId): Box[Boolean] = { - LocalMappedConnector.saveTransactionRequestTransactionImpl(transactionRequestId: TransactionRequestId, transactionId: TransactionId) - } - - override def saveTransactionRequestChallengeImpl(transactionRequestId: TransactionRequestId, challenge: TransactionRequestChallenge): Box[Boolean] = { - TransactionRequests.transactionRequestProvider.vend.saveTransactionRequestChallengeImpl(transactionRequestId, challenge) - } - - override def saveTransactionRequestStatusImpl(transactionRequestId: TransactionRequestId, status: String): Box[Boolean] = { - TransactionRequests.transactionRequestProvider.vend.saveTransactionRequestStatusImpl(transactionRequestId, status) - } - - - override def getTransactionRequestsImpl(fromAccount : BankAccount) : Box[List[TransactionRequest]] = { - TransactionRequests.transactionRequestProvider.vend.getTransactionRequests(fromAccount.bankId, fromAccount.accountId) - } - - override def getTransactionRequestsImpl210(fromAccount : BankAccount) : Box[List[TransactionRequest]] = { - TransactionRequests.transactionRequestProvider.vend.getTransactionRequests(fromAccount.bankId, fromAccount.accountId) - } - - /* - Bank account creation - */ - - //creates a bank account (if it doesn't exist) and creates a bank (if it doesn't exist) - //again assume national identifier is unique - override def createBankAndAccount( - bankName: String, - bankNationalIdentifier: String, - accountNumber: String, - accountType: String, - accountLabel: String, - currency: String, - accountHolderName: String, - branchId: String, - accountRoutingScheme: String, - accountRoutingAddress: String - ) = { - //don't require and exact match on the name, just the identifier - val bank: Bank = MappedBank.find(By(MappedBank.national_identifier, bankNationalIdentifier)) match { - case Full(b) => - logger.info(s"bank with id ${b.bankId} and national identifier ${b.nationalIdentifier} found") - b - case _ => - logger.info(s"creating bank with national identifier $bankNationalIdentifier") - //TODO: need to handle the case where generatePermalink returns a permalink that is already used for another bank - MappedBank.create - .permalink(Helper.generatePermalink(bankName)) - .fullBankName(bankName) - .shortBankName(bankName) - .national_identifier(bankNationalIdentifier) - .saveMe() - } - - //TODO: pass in currency as a parameter? - val account = createAccountIfNotExisting( - bank.bankId, - AccountId(APIUtil.generateUUID()), - accountNumber, - accountType, - accountLabel, - currency, - 0L, - accountHolderName - ) - - Full((bank, account)) - } - - //for sandbox use -> allows us to check if we can generate a new test account with the given number - override def accountExists(bankId: BankId, accountNumber: String) = { - Full(getAccountByNumber(bankId, accountNumber) != null) - } - - //remove an account and associated transactions - override def removeAccount(bankId: BankId, accountId: AccountId) = { - //delete comments on transactions of this account - val commentsDeleted = Comments.comments.vend.bulkDeleteComments(bankId, accountId) - - //delete narratives on transactions of this account - val narrativesDeleted = MappedNarrative.bulkDelete_!!( - By(MappedNarrative.bank, bankId.value), - By(MappedNarrative.account, accountId.value) - ) - - //delete narratives on transactions of this account - val tagsDeleted = Tags.tags.vend.bulkDeleteTags(bankId, accountId) - - //delete WhereTags on transactions of this account - val whereTagsDeleted = WhereTags.whereTags.vend.bulkDeleteWhereTags(bankId, accountId) - - //delete transaction images on transactions of this account - val transactionImagesDeleted = TransactionImages.transactionImages.vend.bulkDeleteTransactionImage(bankId, accountId) - - //delete transactions of account - val transactionsDeleted = MappedTransaction.bulkDelete_!!( - By(MappedTransaction.bank, bankId.value), - By(MappedTransaction.account, accountId.value) - ) - - //remove view privileges - val privilegesDeleted = Views.views.vend.removeAllPermissions(bankId, accountId) - - //delete views of account - val viewsDeleted = Views.views.vend.removeAllViews(bankId, accountId) - - //delete account - val account = getBankAccountOld(bankId, accountId) - - val accountDeleted = account match { - case acc => true //acc.delete_! //TODO - // case _ => false - } - - Full(commentsDeleted && narrativesDeleted && tagsDeleted && whereTagsDeleted && transactionImagesDeleted && - transactionsDeleted && privilegesDeleted && viewsDeleted && accountDeleted) -} - - //creates a bank account for an existing bank, with the appropriate values set. Can fail if the bank doesn't exist - override def createSandboxBankAccount( - bankId: BankId, - accountId: AccountId, - accountNumber: String, - accountType: String, - accountLabel: String, - currency: String, - initialBalance: BigDecimal, - accountHolderName: String, - branchId: String, - accountRoutings: List[AccountRouting] - ): Box[BankAccount] = { - - for { - (bank, _)<- getBankLegacy(bankId, None) //bank is not really used, but doing this will ensure account creations fails if the bank doesn't - } yield { - - val balanceInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(initialBalance, currency) - createAccountIfNotExisting(bankId, accountId, accountNumber, accountType, accountLabel, currency, balanceInSmallestCurrencyUnits, accountHolderName) - } - - } - - - private def createAccountIfNotExisting(bankId: BankId, accountId: AccountId, accountNumber: String, - accountType: String, accountLabel: String, currency: String, - balanceInSmallestCurrencyUnits: Long, accountHolderName: String) : BankAccount = { - getBankAccountOld(bankId, accountId) match { - case Full(a) => - logger.info(s"account with id $accountId at bank with id $bankId already exists. No need to create a new one.") - a - case _ => null //TODO - /* - new KafkaBankAccount - .bank(bankId.value) - .theAccountId(accountId.value) - .accountNumber(accountNumber) - .accountType(accountType) - .accountLabel(accountLabel) - .accountCurrency(currency) - .accountBalance(balanceInSmallestCurrencyUnits) - .holder(accountHolderName) - .saveMe() - */ - } - } - - private def createMappedAccountDataIfNotExisting(bankId: String, accountId: String, label: String) : Boolean = { - MappedBankAccountData.find(By(MappedBankAccountData.accountId, accountId), - By(MappedBankAccountData.bankId, bankId)) match { - case Empty => - val data = new MappedBankAccountData - data.setAccountId(accountId) - data.setBankId(bankId) - data.setLabel(label) - data.save() - true - case _ => - logger.info(s"account data with id $accountId at bank with id $bankId already exists. No need to create a new one.") - false - } - } - - /* - End of bank account creation - */ - - - /* - Transaction importer api - */ - - //used by the transaction import api - override def updateAccountBalance(bankId: BankId, accountId: AccountId, newBalance: BigDecimal) = { - - //this will be Full(true) if everything went well - val result = for { - acc <- getBankAccountOld(bankId, accountId) - (bank, _)<- getBankLegacy(bankId, None) - } yield { - //acc.balance = newBalance - setBankAccountLastUpdated(bank.nationalIdentifier, acc.number, now).openOrThrowException(attemptedToOpenAnEmptyBox) - } - - Full(result.getOrElse(false)) - } - - //transaction import api uses bank national identifiers to uniquely indentify banks, - //which is unfortunate as theoretically the national identifier is unique to a bank within - //one country - private def getBankByNationalIdentifier(nationalIdentifier : String) : Box[Bank] = { - MappedBank.find(By(MappedBank.national_identifier, nationalIdentifier)) - } - - - private val bigDecimalFailureHandler : PartialFunction[Throwable, Unit] = { - case ex : NumberFormatException => { - logger.warn(s"could not convert amount to a BigDecimal: $ex") - } - } - - //used by transaction import api call to check for duplicates - override def getMatchingTransactionCount(bankNationalIdentifier : String, accountNumber : String, amount: String, completed: Date, otherAccountHolder: String) = { - //we need to convert from the legacy bankNationalIdentifier to BankId, and from the legacy accountNumber to AccountId - val count = for { - bankId <- getBankByNationalIdentifier(bankNationalIdentifier).map(_.bankId) - account <- getAccountByNumber(bankId, accountNumber) - amountAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(amount)) - } yield { - - val amountInSmallestCurrencyUnits = - Helper.convertToSmallestCurrencyUnits(amountAsBigDecimal, account.currency) - - MappedTransaction.count( - By(MappedTransaction.bank, bankId.value), - By(MappedTransaction.account, account.accountId.value), - By(MappedTransaction.amount, amountInSmallestCurrencyUnits), - By(MappedTransaction.tFinishDate, completed), - By(MappedTransaction.counterpartyAccountHolder, otherAccountHolder)) - } - - //icky - Full(count.map(_.toInt) getOrElse 0) - } - - //used by transaction import api - override def createImportedTransaction(transaction: ImporterTransaction): Box[Transaction] = { - //we need to convert from the legacy bankNationalIdentifier to BankId, and from the legacy accountNumber to AccountId - val obpTransaction = transaction.obp_transaction - val thisAccount = obpTransaction.this_account - val nationalIdentifier = thisAccount.bank.national_identifier - val accountNumber = thisAccount.number - for { - bank <- getBankByNationalIdentifier(transaction.obp_transaction.this_account.bank.national_identifier) ?~! - s"No bank found with national identifier $nationalIdentifier" - bankId = bank.bankId - account <- getAccountByNumber(bankId, accountNumber) - details = obpTransaction.details - amountAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(details.value.amount)) - newBalanceAsBigDecimal <- tryo(bigDecimalFailureHandler)(BigDecimal(details.new_balance.amount)) - amountInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(amountAsBigDecimal, account.currency) - newBalanceInSmallestCurrencyUnits = Helper.convertToSmallestCurrencyUnits(newBalanceAsBigDecimal, account.currency) - otherAccount = obpTransaction.other_account - mappedTransaction = MappedTransaction.create - .bank(bankId.value) - .account(account.accountId.value) - .transactionType(details.kind) - .amount(amountInSmallestCurrencyUnits) - .newAccountBalance(newBalanceInSmallestCurrencyUnits) - .currency(account.currency) - .tStartDate(details.posted.`$dt`) - .tFinishDate(details.completed.`$dt`) - .description(details.label) - .counterpartyAccountNumber(otherAccount.number) - .counterpartyAccountHolder(otherAccount.holder) - .counterpartyAccountKind(otherAccount.kind) - .counterpartyNationalId(otherAccount.bank.national_identifier) - .counterpartyBankName(otherAccount.bank.name) - .counterpartyIban(otherAccount.bank.IBAN) - .saveMe() - transaction <- mappedTransaction.toTransaction(account) - } yield transaction - } - - override def setBankAccountLastUpdated(bankNationalIdentifier: String, accountNumber : String, updateDate: Date) = { - val result = for { - bankId <- getBankByNationalIdentifier(bankNationalIdentifier).map(_.bankId) - account <- getAccountByNumber(bankId, accountNumber) - } yield { - val acc = getBankAccountOld(bankId, account.accountId) - acc match { - case a => true //a.lastUpdate = updateDate //TODO - // case _ => logger.warn("can't set bank account.lastUpdated because the account was not found"); false - } - } - Full(result.getOrElse(false)) - } - - /* - End of transaction importer api - */ - - - override def updateAccountLabel(bankId: BankId, accountId: AccountId, label: String) = { - //this will be Full(true) if everything went well - val result = for { - acc <- getBankAccountOld(bankId, accountId) - (bank, _)<- getBankLegacy(bankId, None) - d <- MappedBankAccountData.find(By(MappedBankAccountData.accountId, accountId.value), By(MappedBankAccountData.bankId, bank.bankId.value)) - } yield { - d.setLabel(label) - d.save() - } - Full(result.getOrElse(false)) - } - - - override def getProducts(bankId: BankId, params: List[GetProductsParam]): Box[List[Product]] = Empty - - override def getProduct(bankId: BankId, productCode: ProductCode): Box[Product] = Empty - - override def createOrUpdateBranch(branch: BranchT): Box[BranchT] = Empty - - override def createOrUpdateBank( - bankId: String, - fullBankName: String, - shortBankName: String, - logoURL: String, - websiteURL: String, - swiftBIC: String, - national_identifier: String, - bankRoutingScheme: String, - bankRoutingAddress: String - ): Box[Bank] = Empty - - - override def getEmptyBankAccount(): Box[BankAccount] = { - Full(new BankAccount2( - InboundAccount_vMar2017( - errorCode = "OBP-6001: ...", - accountId = "8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", - bankId = "gh.29.uk", - label = "Good", - number = "123", - `type` = "AC", - balanceAmount = "50", - balanceCurrency = "EUR", - iban = "12345", - owners = Nil, - generatePublicView = true, - generateAccountantsView = true, - generateAuditorsView = true - ) - ) - ) - } - - ///////////////////////////////////////////////////////////////////////////// - - // Helper for creating a transaction - def createNewTransaction(r: InternalTransaction):Box[Transaction] = { - var datePosted: Date = null - if (r.postedDate != null) // && r.details.posted.matches("^[0-9]{8}$")) - datePosted = APIUtil.DateWithMsFormat.parse(r.postedDate) - - var dateCompleted: Date = null - if (r.completedDate != null) // && r.details.completed.matches("^[0-9]{8}$")) - dateCompleted = APIUtil.DateWithMsFormat.parse(r.completedDate) - - for { - counterpartyId <- tryo{r.counterpartyId} - counterpartyName <- tryo{r.counterpartyName} - thisAccount <- getBankAccountOld(BankId(r.bankId), AccountId(r.accountId)) - //creates a dummy OtherBankAccount without an OtherBankAccountMetadata, which results in one being generated (in OtherBankAccount init) - dummyOtherBankAccount <- tryo{createCounterparty(counterpartyId, counterpartyName, thisAccount, None)} - //and create the proper OtherBankAccount with the correct "id" attribute set to the metadataId of the OtherBankAccountMetadata object - //note: as we are passing in the OtherBankAccountMetadata we don't incur another db call to get it in OtherBankAccount init - counterparty <- tryo{createCounterparty(counterpartyId, counterpartyName, thisAccount, Some(dummyOtherBankAccount.metadata))} - } yield { - // Create new transaction - new Transaction( - r.transactionId, // uuid:String - TransactionId(r.transactionId), // id:TransactionId - thisAccount, // thisAccount:BankAccount - counterparty, // otherAccount:OtherBankAccount - r.`type`, // transactionType:String - BigDecimal(r.amount), // val amount:BigDecimal - thisAccount.currency, // currency:String - Some(r.description), // description:Option[String] - datePosted, // startDate:Date - dateCompleted, // finishDate:Date - BigDecimal(r.newBalanceAmount) // balance:BigDecimal) - ) - } - } - - - - // Helper for creating other bank account - def createCounterparty(counterpartyId: String, counterpartyName: String, o: BankAccount, alreadyFoundMetadata : Option[CounterpartyMetadata]) = { - new Counterparty( - counterpartyId = alreadyFoundMetadata.map(_.getCounterpartyId).getOrElse(""), - counterpartyName = counterpartyName, - nationalIdentifier = "1234", - otherBankRoutingAddress = None, - otherAccountRoutingAddress = None, - thisAccountId = AccountId(counterpartyId), - thisBankId = BankId(""), - kind = "1234", - otherBankRoutingScheme = "obp", - otherAccountRoutingScheme="obp", - otherAccountProvider = "obp", - isBeneficiary = true - ) - } - -} - -object KafkaMappedConnector_vMar2017 extends KafkaMappedConnector_vMar2017{ - -} - - diff --git a/obp-api/src/main/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019.scala b/obp-api/src/main/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019.scala index 3dc0c51aa..112c9a4ba 100644 --- a/obp-api/src/main/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019.scala +++ b/obp-api/src/main/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019.scala @@ -37,8 +37,6 @@ import code.api.util.ExampleValue._ import code.api.util._ import code.api.v2_1_0.TransactionRequestBodyCommonJSON import code.bankconnectors._ -import code.bankconnectors.vJune2017.{InternalCustomer, JsonFactory_vJune2017} -import code.bankconnectors.vMar2017._ import code.bankconnectors.vSept2018.KafkaMappedConnector_vSept2018 import code.customer._ import code.kafka.{KafkaHelper, Topics} diff --git a/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaJsonFactory_vSept2018.scala b/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaJsonFactory_vSept2018.scala index 1c3bbba44..69db999ac 100644 --- a/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaJsonFactory_vSept2018.scala +++ b/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaJsonFactory_vSept2018.scala @@ -3,8 +3,6 @@ package code.bankconnectors.vSept2018 import java.util.Date import code.api.util.APIUtil -import code.bankconnectors.vJune2017.InternalCustomer -import code.bankconnectors.vMar2017._ import code.branches.Branches.{DriveUpString, LobbyString} import code.model.dataAccess.MappedBankAccountData import com.openbankproject.commons.model.{CounterpartyTrait, Customer, UserAuthContext, _} @@ -164,18 +162,6 @@ case class InternalInboundCoreAccount( accountRoutings: List[AccountRouting] ) -case class AuthInfo( - userId: String = "", - username: String = "", - cbsToken: String = "", - isFirst: Boolean = true, - correlationId: String = "", - sessionId: String = "", - linkedCustomers: List[BasicCustomer] = Nil, - userAuthContexts: List[BasicUserAuthContext]= Nil, - authViews: List[AuthView] = Nil, -) - case class InboundAuthInfo( cbsToken: String = "", sessionId: String = "" @@ -236,12 +222,6 @@ case class BankAccountSept2018(r: InboundAccountSept2018) extends BankAccount { } -case class BasicCustomer( - customerId: String, - customerNumber: String, - legalName: String, -) - case class InternalCreateChallengeSept2018( errorCode: String, backendMessages: List[InboundStatusMessage], diff --git a/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaMappedConnector_vSept2018.scala b/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaMappedConnector_vSept2018.scala index c7cf38abb..89c5ecfda 100644 --- a/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaMappedConnector_vSept2018.scala +++ b/obp-api/src/main/scala/code/bankconnectors/vSept2018/KafkaMappedConnector_vSept2018.scala @@ -39,8 +39,6 @@ import com.openbankproject.commons.model.enums.StrongCustomerAuthentication.SCA import code.api.util._ import code.api.v2_1_0.TransactionRequestBodyCommonJSON import code.bankconnectors._ -import code.bankconnectors.vJune2017.{InternalCustomer, JsonFactory_vJune2017} -import code.bankconnectors.vMar2017._ import code.context.UserAuthContextProvider import code.customer._ import code.kafka.{KafkaHelper, Topics} @@ -1499,7 +1497,7 @@ trait KafkaMappedConnector_vSept2018 extends Connector with KafkaHelper with Mdc future map { case Full(inbound) if (inbound.status.hasNoError) => - Full(JsonFactory_vJune2017.createObpCustomers(inbound.data)) + Full(KafkaMappedConnector_vSept2018.createObpCustomers(inbound.data)) case Full(inbound) if (inbound.status.hasError) => Failure("INTERNAL-"+ inbound.status.errorCode+". + CoreBank-Status:" + inbound.status.backendMessages) case failureOrEmpty => failureOrEmpty @@ -3839,7 +3837,44 @@ trait KafkaMappedConnector_vSept2018 extends Connector with KafkaHelper with Mdc object KafkaMappedConnector_vSept2018 extends KafkaMappedConnector_vSept2018{ - + def createCustomerJson(customer : Customer) : InternalBasicCustomer = { + InternalBasicCustomer( + bankId=customer.bankId, + customerId = customer.customerId, + customerNumber = customer.number, + legalName = customer.legalName, + dateOfBirth = customer.dateOfBirth + ) + } + def createObpCustomer(customer : InternalCustomer) : Customer = { + ObpCustomer( + customerId = customer.customerId, + bankId = customer.bankId, + number = customer.number, + legalName = customer.legalName, + mobileNumber = customer.mobileNumber, + email = customer.email, + faceImage = customer.faceImage, + dateOfBirth = customer.dateOfBirth, + relationshipStatus = customer.relationshipStatus, + dependents = customer.dependents, + dobOfDependents = customer.dobOfDependents, + highestEducationAttained = customer.highestEducationAttained, + employmentStatus = customer.employmentStatus, + creditRating = customer.creditRating, + creditLimit = customer.creditLimit, + kycStatus = customer.kycStatus, + lastOkDate = customer.lastOkDate, + ) + } + + def createCustomersJson(customers : List[Customer]) : InternalBasicCustomers = { + InternalBasicCustomers(customers.map(createCustomerJson)) + } + + def createObpCustomers(customers : List[InternalCustomer]) : List[Customer] = { + customers.map(createObpCustomer) + } } diff --git a/obp-api/src/test/scala/code/api/gateWayloginTest.scala b/obp-api/src/test/scala/code/api/gateWayloginTest.scala index 8a8a93810..180c8ae22 100644 --- a/obp-api/src/test/scala/code/api/gateWayloginTest.scala +++ b/obp-api/src/test/scala/code/api/gateWayloginTest.scala @@ -1,7 +1,7 @@ package code.api import code.api.util.{APIUtil, ErrorMessages} -import code.bankconnectors.vJune2017.InboundAccountJune2017 +import com.openbankproject.commons.model._ import code.setup.{APIResponse, DefaultUsers, ServerSetup} import net.liftweb.common.Full import net.liftweb.json diff --git a/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala b/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala index 9e832639b..74b496d80 100644 --- a/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala +++ b/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala @@ -418,8 +418,8 @@ class API2_2_0Test extends V220ServerSetup with DefaultUsers { } feature("Get Message Docs - v2.2.0"){ - scenario("Get Message Docs - kafka_vJune2017") { - val request = (v2_2Request / "message-docs" / "kafka_vJune2017" ) + scenario("Get Message Docs - kafka_vMay2019") { + val request = (v2_2Request / "message-docs" / "kafka_vMay2019" ) val response: APIResponse = makeGetRequest(request) response.code should be (200) diff --git a/obp-api/src/test/scala/code/bankconnectors/StoredProcedureConnector_vDec2019Test.scala b/obp-api/src/test/scala/code/bankconnectors/StoredProcedureConnector_vDec2019Test.scala index 4f8f2da7a..c60464054 100644 --- a/obp-api/src/test/scala/code/bankconnectors/StoredProcedureConnector_vDec2019Test.scala +++ b/obp-api/src/test/scala/code/bankconnectors/StoredProcedureConnector_vDec2019Test.scala @@ -29,7 +29,6 @@ import code.api.JSONFactoryGateway.PayloadOfJwtJSON import code.api.util.{APIUtil, CallContext, CustomJsonFormats} import code.bankconnectors.Connector import code.bankconnectors.storedprocedure.StoredProcedureConnector_vDec2019 -import code.bankconnectors.vMar2017.InboundBank import code.bankconnectors.vSept2018._ import code.kafka.KafkaHelper import code.setup.{DefaultUsers, KafkaSetup, ServerSetupWithTestData} diff --git a/obp-api/src/test/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019Test.scala b/obp-api/src/test/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019Test.scala index ff0b63bfd..7efa63742 100644 --- a/obp-api/src/test/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019Test.scala +++ b/obp-api/src/test/scala/code/bankconnectors/vMay2019/KafkaMappedConnector_vMay2019Test.scala @@ -27,7 +27,6 @@ Berlin 13359, Germany import code.api.JSONFactoryGateway.PayloadOfJwtJSON import code.api.util.{APIUtil, CallContext, CustomJsonFormats} import code.bankconnectors.Connector -import code.bankconnectors.vMar2017.InboundBank import code.bankconnectors.vSept2018._ import code.kafka.KafkaHelper import code.setup.{KafkaSetup, ServerSetupWithTestData} diff --git a/obp-api/src/test/scala/code/connector/June2017Test.scala b/obp-api/src/test/scala/code/connector/June2017Test.scala deleted file mode 100644 index 005926a0e..000000000 --- a/obp-api/src/test/scala/code/connector/June2017Test.scala +++ /dev/null @@ -1,25 +0,0 @@ -package code.connector - -import code.accountholders.MapperAccountHolders -import code.bankconnectors.Connector -import code.setup.{DefaultUsers, ServerSetup} -import code.views.system.ViewDefinition - -class June2017Test extends ServerSetup with DefaultUsers { - - - override def beforeAll() = { - super.beforeAll() - Connector.connector.default.set(MockedJune2017Connector) - ViewDefinition.bulkDelete_!!() - MapperAccountHolders.bulkDelete_!!() - } - - override def afterEach() = { - super.afterEach() - Connector.connector.default.set(Connector.buildOne) - ViewDefinition.bulkDelete_!!() - MapperAccountHolders.bulkDelete_!!() - } - -} diff --git a/obp-api/src/test/scala/code/connector/June2017UnitTest.scala b/obp-api/src/test/scala/code/connector/June2017UnitTest.scala deleted file mode 100644 index e2556ef67..000000000 --- a/obp-api/src/test/scala/code/connector/June2017UnitTest.scala +++ /dev/null @@ -1,39 +0,0 @@ -package code.connector - - -import code.api.util.APIUtil.MessageDoc -import code.api.util.CustomJsonFormats -import code.bankconnectors.vJune2017.{InboundGetTransactionRequests210, InternalGetTransactionRequests, KafkaMappedConnector_vJune2017, OutboundGetTransactionRequests210} -import com.openbankproject.commons.model.TransactionRequest -import code.util.Helper.MdcLoggable -import net.liftweb.json.Extraction -import net.liftweb.json.JsonAST.JValue -import org.scalatest._ - -import scala.collection.mutable.ArrayBuffer - -class June2017UnitTest extends FunSuite - with Matchers - with MdcLoggable with CustomJsonFormats { - - - test("getTransactionRequests210 kafka message") { - val messageDocs: ArrayBuffer[MessageDoc] = KafkaMappedConnector_vJune2017.messageDocs.filter(_.process=="obp.getTransactionRequests210") - val outboundMessage: JValue = Extraction.decompose(messageDocs.head.exampleOutboundMessage) - val inboundMessage: JValue = Extraction.decompose(messageDocs.head.exampleInboundMessage) - - - val outboundGetTransactionRequests210: OutboundGetTransactionRequests210 = outboundMessage.extract[OutboundGetTransactionRequests210] - - val inboundGetTransactionRequests210: InboundGetTransactionRequests210 = inboundMessage.extract[InboundGetTransactionRequests210] - val internalGetTransactionRequests: List[TransactionRequest] = inboundGetTransactionRequests210.data - - - outboundGetTransactionRequests210 shouldBe a [OutboundGetTransactionRequests210] - internalGetTransactionRequests shouldBe a [List[_]] - - } - - - -} diff --git a/obp-api/src/test/scala/code/connector/MockedCbsConnector.scala b/obp-api/src/test/scala/code/connector/MockedCbsConnector.scala new file mode 100644 index 000000000..c9018be76 --- /dev/null +++ b/obp-api/src/test/scala/code/connector/MockedCbsConnector.scala @@ -0,0 +1,56 @@ +package code.connector + +import code.api.util.{CallContext, CustomJsonFormats} +import code.bankconnectors._ +import code.setup.{DefaultConnectorTestSetup, DefaultUsers, ServerSetup} +import code.util.Helper.MdcLoggable +import com.openbankproject.commons.model.{AccountId, BankId, BankIdAccountId, InboundAccount, InboundAccountCommons} +import net.liftweb.common.{Box, Full} + +import scala.collection.immutable.List +import com.openbankproject.commons.ExecutionContext.Implicits.global +import net.liftweb.json.Formats + +import scala.concurrent.Future + +/** + * Created by zhanghongwei on 14/07/2017. + */ +object MockedCbsConnector extends ServerSetup + with Connector with DefaultUsers + with DefaultConnectorTestSetup with MdcLoggable { + override implicit val formats: Formats = CustomJsonFormats.nullTolerateFormats + implicit override val nameOfConnector = "MockedCardConnector" + + //These bank id and account ids are real data over adapter + val bankIdAccountId = BankIdAccountId(BankId("obp-bank-x-gh"),AccountId("KOa4M8UfjUuWPIXwPXYPpy5FoFcTUwpfHgXC1qpSluc")) + val bankIdAccountId2 = BankIdAccountId(BankId("obp-bank-x-gh"),AccountId("tKWSUBy6sha3Vhxc/vw9OK96a0RprtoxUuObMYR29TI")) + + override def getBankAccountsForUserLegacy(username: String, callContext: Option[CallContext]): Box[(List[InboundAccount], Option[CallContext])] = { + Full( + List(InboundAccountCommons( + bankId = bankIdAccountId.bankId.value, + branchId = "", + accountId = bankIdAccountId.accountId.value, + accountNumber = "", + accountType = "", + balanceAmount = "", + balanceCurrency = "", + owners = List(""), + viewsToGenerate = "Owner" :: "_Public" :: "Accountant" :: "Auditor" :: Nil, + bankRoutingScheme = "", + bankRoutingAddress = "", + branchRoutingScheme = "", + branchRoutingAddress = "", + accountRoutingScheme = "", + accountRoutingAddress = "", + )), + callContext + ) + } + + override def getBankAccountsForUser(username: String, callContext: Option[CallContext]): Future[Box[(List[InboundAccount], Option[CallContext])]] = Future{ + getBankAccountsForUserLegacy(username,callContext) + } +} + diff --git a/obp-api/src/test/scala/code/connector/MockedJune2017Connector.scala b/obp-api/src/test/scala/code/connector/MockedJune2017Connector.scala deleted file mode 100644 index 4ec675c62..000000000 --- a/obp-api/src/test/scala/code/connector/MockedJune2017Connector.scala +++ /dev/null @@ -1,41 +0,0 @@ -package code.connector - -import code.api.util.{CallContext, CustomJsonFormats} -import code.bankconnectors._ -import code.bankconnectors.vJune2017.InboundAccountJune2017 -import code.setup.{DefaultConnectorTestSetup, DefaultUsers, ServerSetup} -import code.util.Helper.MdcLoggable -import com.openbankproject.commons.model.{AccountId, BankId, BankIdAccountId} -import net.liftweb.common.{Box, Full} - -import scala.collection.immutable.List -import com.openbankproject.commons.ExecutionContext.Implicits.global -import net.liftweb.json.Formats - -import scala.concurrent.Future - -/** - * Created by zhanghongwei on 14/07/2017. - */ -object MockedJune2017Connector extends ServerSetup - with Connector with DefaultUsers - with DefaultConnectorTestSetup with MdcLoggable { - override implicit val formats: Formats = CustomJsonFormats.nullTolerateFormats - implicit override val nameOfConnector = "MockedCardConnector" - - //These bank id and account ids are real data over adapter - val bankIdAccountId = BankIdAccountId(BankId("obp-bank-x-gh"),AccountId("KOa4M8UfjUuWPIXwPXYPpy5FoFcTUwpfHgXC1qpSluc")) - val bankIdAccountId2 = BankIdAccountId(BankId("obp-bank-x-gh"),AccountId("tKWSUBy6sha3Vhxc/vw9OK96a0RprtoxUuObMYR29TI")) - - override def getBankAccountsForUserLegacy(username: String, callContext: Option[CallContext]): Box[(List[InboundAccountJune2017], Option[CallContext])] = { - Full( - InboundAccountJune2017("", cbsToken = "cbsToken", bankId = bankIdAccountId.bankId.value, branchId = "222", accountId = bankIdAccountId.accountId.value, accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = Nil, viewsToGenerate = "Owner" :: "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil) :: InboundAccountJune2017("", cbsToken = "cbsToken", bankId = bankIdAccountId2.bankId.value, branchId = "222", accountId = bankIdAccountId2.accountId.value, accountNumber = "123", accountType = "AC", balanceAmount = "50", balanceCurrency = "EUR", owners = Nil, viewsToGenerate = "Owner" :: "_Public" :: "Accountant" :: "Auditor" :: Nil, bankRoutingScheme = "iban", bankRoutingAddress = "bankRoutingAddress", branchRoutingScheme = "branchRoutingScheme", branchRoutingAddress = " branchRoutingAddress", accountRoutingScheme = "accountRoutingScheme", accountRoutingAddress = "accountRoutingAddress", accountRouting = Nil, accountRules = Nil) :: Nil, - callContext - ) - } - - override def getBankAccountsForUser(username: String, callContext: Option[CallContext]): Future[Box[(List[InboundAccountJune2017], Option[CallContext])]] = Future{ - getBankAccountsForUserLegacy(username,callContext) - } -} - diff --git a/obp-api/src/test/scala/code/kafka/KafkaTest.scala b/obp-api/src/test/scala/code/kafka/KafkaTest.scala index 0f7da50c0..b5a7aa280 100644 --- a/obp-api/src/test/scala/code/kafka/KafkaTest.scala +++ b/obp-api/src/test/scala/code/kafka/KafkaTest.scala @@ -6,7 +6,6 @@ import code.api.JSONFactoryGateway.PayloadOfJwtJSON import code.api.util.{APIUtil, CallContext, CustomJsonFormats} import code.api.v2_1_0.TransactionRequestBodyCommonJSON import code.bankconnectors.Connector -import code.bankconnectors.vMar2017.InboundBank import code.bankconnectors.vSept2018._ import code.setup.{KafkaSetup, ServerSetupWithTestData} import com.openbankproject.commons.dto.{InBoundGetKycChecks, InBoundGetKycMedias, InBoundGetKycStatuses} diff --git a/obp-api/src/test/scala/code/model/AuthUserTest.scala b/obp-api/src/test/scala/code/model/AuthUserTest.scala index 08489694b..7d02a2810 100644 --- a/obp-api/src/test/scala/code/model/AuthUserTest.scala +++ b/obp-api/src/test/scala/code/model/AuthUserTest.scala @@ -2,7 +2,7 @@ package code.model import code.accountholders.MapperAccountHolders import code.bankconnectors.Connector -import code.connector.MockedJune2017Connector +import code.connector.MockedCbsConnector import code.model.dataAccess.{AuthUser, ViewImpl, ViewPrivileges} import code.setup.{DefaultUsers, ServerSetup} import code.views.MapperViews @@ -15,7 +15,7 @@ class AuthUserTest extends ServerSetup with DefaultUsers { override def beforeAll() = { super.beforeAll() - Connector.connector.default.set(MockedJune2017Connector) + Connector.connector.default.set(MockedCbsConnector) ViewDefinition.bulkDelete_!!() MapperAccountHolders.bulkDelete_!!() } @@ -27,8 +27,8 @@ class AuthUserTest extends ServerSetup with DefaultUsers { MapperAccountHolders.bulkDelete_!!() } - val bankIdAccountId = MockedJune2017Connector.bankIdAccountId - val bankIdAccountId2 = MockedJune2017Connector.bankIdAccountId2 + val bankIdAccountId = MockedCbsConnector.bankIdAccountId + val bankIdAccountId2 = MockedCbsConnector.bankIdAccountId2 feature("Test the updateUserAccountViews method") { diff --git a/obp-commons/src/main/scala/com/openbankproject/commons/model/CommonModel.scala b/obp-commons/src/main/scala/com/openbankproject/commons/model/CommonModel.scala index dc3ddc125..57448a7ff 100644 --- a/obp-commons/src/main/scala/com/openbankproject/commons/model/CommonModel.scala +++ b/obp-commons/src/main/scala/com/openbankproject/commons/model/CommonModel.scala @@ -35,6 +35,7 @@ import com.openbankproject.commons.util.{ReflectUtils, optional} import net.liftweb.json.JsonAST.{JObject, JValue} import net.liftweb.json.{JInt, JString} +import java.lang import scala.collection.immutable.List import scala.reflect.runtime.universe._ //import code.customeraddress.CustomerAddress @@ -886,6 +887,125 @@ case class InboundAdapterCallContext( generalContext: Option[List[BasicGeneralContext]]= None, //be set by backend, send it back to the header? not finish yet. ) +case class BasicCustomer( + customerId: String, + customerNumber: String, + legalName: String, +) + +case class AuthInfo( + userId: String = "", + username: String = "", + cbsToken: String = "", + isFirst: Boolean = true, + correlationId: String = "", + sessionId: String = "", + linkedCustomers: List[BasicCustomer] = Nil, + userAuthContexts: List[BasicUserAuthContext]= Nil, + authViews: List[AuthView] = Nil, +) + +case class ObpCustomer( + customerId: String, + bankId: String, + number: String, + legalName: String, + mobileNumber: String, + email: String, + faceImage: CustomerFaceImage, + dateOfBirth: Date, + relationshipStatus: String, + dependents: Integer, + dobOfDependents: List[Date], + highestEducationAttained: String, + employmentStatus: String, + creditRating: CreditRating, + creditLimit: CreditLimit, + kycStatus: lang.Boolean, + lastOkDate: Date, + title: String = "", //These new fields for V310, not from Connector for now. + branchId: String = "", //These new fields for V310, not from Connector for now. + nameSuffix: String = "", //These new fields for V310, not from Connector for now. +) extends Customer + +case class InternalCustomer( + customerId: String, + bankId: String, + number: String, + legalName: String, + mobileNumber: String, + email: String, + faceImage: CustomerFaceImage, + dateOfBirth: Date, + relationshipStatus: String, + dependents: Integer, + dobOfDependents: List[Date], + highestEducationAttained: String, + employmentStatus: String, + creditRating: CreditRating, + creditLimit: CreditLimit, + kycStatus: lang.Boolean, + lastOkDate: Date +) + +case class InboundAccountJune2017( + errorCode: String, + cbsToken: String, //TODO, this maybe move to AuthInfo, but it is used in GatewayLogin + bankId: String, + branchId: String, + accountId: String, + accountNumber: String, + accountType: String, + balanceAmount: String, + balanceCurrency: String, + owners: List[String], + viewsToGenerate: List[String], + bankRoutingScheme: String, + bankRoutingAddress: String, + branchRoutingScheme: String, + branchRoutingAddress: String, + accountRoutingScheme: String, + accountRoutingAddress: String, + accountRouting: List[AccountRouting], + accountRules: List[AccountRule] +) extends InboundMessageBase with InboundAccount + +case class Bank2(r: InboundBank) extends Bank { + def fullName = r.name + def shortName = r.name + def logoUrl = r.logo + def bankId = BankId(r.bankId) + def nationalIdentifier = "None" + def swiftBic = "None" + def websiteUrl = r.url + def bankRoutingScheme = "None" + def bankRoutingAddress = "None" +} + +case class InboundBank( + bankId: String, + name: String, + logo: String, + url: String +) + +case class InboundValidatedUser( + errorCode: String, + backendMessages: List[InboundStatusMessage], + email: String, + displayName: String +) extends InboundMessageBase + +case class OutboundChallengeBase( + messageFormat: String, + action: String, + bankId: String, + accountId: String, + userId: String, + username: String, + transactionRequestType: String, + transactionRequestId: String +) extends OutboundMessageBase //Note: this is used for connector method: 'def getUser(name: String, password: String): Box[InboundUser]' case class InboundUser( diff --git a/obp-commons/src/main/scala/com/openbankproject/commons/model/ViewModel.scala b/obp-commons/src/main/scala/com/openbankproject/commons/model/ViewModel.scala index 8397bb438..ff6bfad16 100644 --- a/obp-commons/src/main/scala/com/openbankproject/commons/model/ViewModel.scala +++ b/obp-commons/src/main/scala/com/openbankproject/commons/model/ViewModel.scala @@ -228,7 +228,7 @@ trait View { * 2rd: the view can grant the access to any other (not owner) users. eg: Simon's accountant view can grant access to Carola, then Carola can see Simon's accountant data * also look into some createView methods in code, you can understand more: * create1: code.bankconnectors.Connector.createViews - * need also look into here code.bankconnectors.vMar2017.KafkaMappedConnector_vMar2017.updateUserAccountViewsOld + * need also look into here KafkaMappedConnector_vMar2017.updateUserAccountViewsOld * after createViews method, always need call addPermission(v.uid, user). This will create this field * Create2: code.model.dataAccess.BankAccountCreation.createOwnerView * after create view, always need call `addPermission(ownerViewUID, user)`, this will create this field