remove all comments

This commit is contained in:
etreschenkov 2024-06-27 13:03:53 +03:00
parent cc95a67759
commit b67248a0af
824 changed files with 4303 additions and 12853 deletions

View file

@ -52,12 +52,11 @@ public class AccountValidationConfig {
addImdg.accept(IMDGDistributedNames.Map_Currency); addImdg.accept(IMDGDistributedNames.Map_Currency);
return new ValidatorImpl<>(context, return new ValidatorImpl<>(context,
IdPresentRule.instance("companyId", IdPresentRule.instance("companyId",
CorrespondentAccountNewRequest::getCompanyId, CorrespondentAccountNewRequest::getCompanyId,
IMDGDistributedNames.Map_Company, IMDGDistributedNames.Map_Company,
Company.class, Company.class,
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
AccountError.CompanyNotFound AccountError.CompanyNotFound
// company -> WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus()) ? null : AccountError.CompanyNotActive
), ),
FieldRequiredSpecificRule.instance("account", FieldRequiredSpecificRule.instance("account",
CorrespondentAccountNewRequest::getAccount, CorrespondentAccountNewRequest::getAccount,
@ -81,16 +80,12 @@ public class AccountValidationConfig {
return new EnumMessage(AccountError.AccountAlreadyExist, accounts.stream().findFirst().get().getAccount()); return new EnumMessage(AccountError.AccountAlreadyExist, accounts.stream().findFirst().get().getAccount());
}), }),
DictionaryPresentRule.instance("status", DictionaryPresentRule.instance("status",
CorrespondentAccountNewRequest::getStatus, CorrespondentAccountNewRequest::getStatus,
IMDGDistributedNames.Map_ServiceStatusDictionary, IMDGDistributedNames.Map_ServiceStatusDictionary,
ServiceStatusDictionary.class, ServiceStatusDictionary.class,
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
AccountError.DictionaryNotFound, AccountError.DictionaryNotFound,
false false
// , statusValue -> {
// if (ServiceStatus.Active.equalsByKey(statusValue.getCode())) return null;
// return AccountError.WrongFieldValue;
// }
), ),
DictionaryPresentRule.instance("accountType", DictionaryPresentRule.instance("accountType",
CorrespondentAccountNewRequest::getAccountType, CorrespondentAccountNewRequest::getAccountType,
@ -162,16 +157,12 @@ public class AccountValidationConfig {
AccountError.DictionaryNotFound, AccountError.DictionaryNotFound,
false), false),
DictionaryPresentRule.instance("accountType", DictionaryPresentRule.instance("accountType",
CorrespondentAccountUpdateRequest::getAccountType, CorrespondentAccountUpdateRequest::getAccountType,
IMDGDistributedNames.Map_AccountTypeDictionary, IMDGDistributedNames.Map_AccountTypeDictionary,
AccountTypeDictionary.class, AccountTypeDictionary.class,
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
AccountError.DictionaryNotFound, AccountError.DictionaryNotFound,
false false
// accountType -> {
// if (AccountType.Corr.equalsByKey(accountType.getCode())) return null;
// return AccountError.WrongFieldValue;
// }
) )
); );
}; };

View file

@ -106,11 +106,10 @@ public class BankAccountValidationConfig {
bankAccount -> { bankAccount -> {
Long accountId = bankAccount.getAccountId(); Long accountId = bankAccount.getAccountId();
Imdg<Account> accountImdg = context.obtainMap( Imdg<Account> accountImdg = context.obtainMap(
IMDGDistributedNames.Map_Account, Account.class IMDGDistributedNames.Map_Account, Account.class
); );
Account account = accountImdg.getSingleObjectByID(accountId); Account account = accountImdg.getSingleObjectByID(accountId);
if (account == null) return AccountError.AccountNotFound; if (account == null) return AccountError.AccountNotFound;
// if (!AccountStatus.ACTIVE.equalsByKey(account.getStatus())) return AccountError.AccountNotActive;
return null; return null;
}), }),
DictionaryPresentRule.instance("currency", DictionaryPresentRule.instance("currency",

View file

@ -48,12 +48,11 @@ public class ClearingAccountValidationConfig {
addImdg.accept(IMDGDistributedNames.Map_ServiceStatusDictionary); addImdg.accept(IMDGDistributedNames.Map_ServiceStatusDictionary);
return new ValidatorImpl<>(context, return new ValidatorImpl<>(context,
IdPresentRule.instance("companyId", IdPresentRule.instance("companyId",
ClearingAccountNewRequest::getCompanyId, ClearingAccountNewRequest::getCompanyId,
IMDGDistributedNames.Map_Company, IMDGDistributedNames.Map_Company,
Company.class, Company.class,
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
AccountError.CompanyNotFound AccountError.CompanyNotFound
// company -> !WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus()) ? AccountError.CompanyNotActive : null
), ),
FieldNotBlankRequiredRule.instance("account", FieldNotBlankRequiredRule.instance("account",
ClearingAccountNewRequest::getAccount, ClearingAccountNewRequest::getAccount,

View file

@ -42,12 +42,11 @@ public class DepoAccountValidationConfig {
addImdg.accept(IMDGDistributedNames.Map_ServiceStatusDictionary); addImdg.accept(IMDGDistributedNames.Map_ServiceStatusDictionary);
return new ValidatorImpl<>(context, return new ValidatorImpl<>(context,
IdPresentRule.instance("companyId", IdPresentRule.instance("companyId",
DepoAccountNewRequest::getCompanyId, DepoAccountNewRequest::getCompanyId,
IMDGDistributedNames.Map_Company, IMDGDistributedNames.Map_Company,
Company.class, Company.class,
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
AccountError.CompanyNotFound AccountError.CompanyNotFound
// company -> !WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus()) ? AccountError.CompanyNotActive : null
), ),
FieldNotBlankRequiredRule.instance("account", FieldNotBlankRequiredRule.instance("account",
DepoAccountNewRequest::getAccount, DepoAccountNewRequest::getAccount,

View file

@ -21,7 +21,7 @@ class SameAccountValidationRule<R> implements IValidationRule<ImdgValidationCont
final Function<R, String> accountGetter; final Function<R, String> accountGetter;
public SameAccountValidationRule(AccountType accountType, Function<R, String> accountGetter) { public SameAccountValidationRule(AccountType accountType, Function<R, String> accountGetter) {
this.accountType = accountType.getKey(); // or req.getAccountType() this.accountType = accountType.getKey();
this.accountGetter = accountGetter; this.accountGetter = accountGetter;
Objects.requireNonNull(accountGetter); Objects.requireNonNull(accountGetter);
} }
@ -32,9 +32,8 @@ class SameAccountValidationRule<R> implements IValidationRule<ImdgValidationCont
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class); Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
ImdgPredicateBuilder pb = accountImdg.predicateBuilder(); ImdgPredicateBuilder pb = accountImdg.predicateBuilder();
ImdgPredicate query = pb.and( ImdgPredicate query = pb.and(
pb.equals("account", accountGetter.apply(req)), // req.getAccount() pb.equals("account", accountGetter.apply(req)),
// pb.equals("accountType", accountType), имена всех счетов уникальны, вне зависимости от типа pb.in("status", ServiceStatus.Active.getKey(), ServiceStatus.Reopened.getKey(), ServiceStatus.Appl.getKey())
pb.in("status", ServiceStatus.Active.getKey(), ServiceStatus.Reopened.getKey(), ServiceStatus.Appl.getKey())
); );
Account existAccount = accountImdg.getFirstObjectByPredicate(query); Account existAccount = accountImdg.getFirstObjectByPredicate(query);
if (existAccount != null) { if (existAccount != null) {

View file

@ -113,7 +113,7 @@ public class TradingClearingRegistryListValidationConfig {
.map(TradingClearingRegistryList::getAccountId) .map(TradingClearingRegistryList::getAccountId)
.filter(accountId::equals) .filter(accountId::equals)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
return new EnumMessage(AccountError.AccountForTradingClearingRegistryAlreadyUsed, duplicateAccounts, "accountId"); // (5023) «Счет %s уже используется» return new EnumMessage(AccountError.AccountForTradingClearingRegistryAlreadyUsed, duplicateAccounts, "accountId");
} }
return null; return null;
}), }),
@ -189,12 +189,11 @@ public class TradingClearingRegistryListValidationConfig {
} }
if (accounts.isEmpty()) { if (accounts.isEmpty()) {
if (required) if (required)
return of(AccountError.RequiredFieldEmpty, fieldName); // обязательное поле return of(AccountError.RequiredFieldEmpty, fieldName);
else else
return Optional.empty(); return Optional.empty();
} }
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class); Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
// Проверить существование счетов
{ {
for (Long accountId : accounts) { for (Long accountId : accounts) {
Account byIdObject = accountImdg.getSingleObjectByID(accountId); Account byIdObject = accountImdg.getSingleObjectByID(accountId);
@ -202,13 +201,11 @@ public class TradingClearingRegistryListValidationConfig {
return of(AccountError.AccountNotFound, accountId, fieldName); return of(AccountError.AccountNotFound, accountId, fieldName);
if (!IEnumKey.contains(byIdObject.getAccountType(), AccountType.Clrn, AccountType.Info)) { if (!IEnumKey.contains(byIdObject.getAccountType(), AccountType.Clrn, AccountType.Info)) {
return of(AccountError.AccountIsNotACurrency, accountId, return of(AccountError.AccountIsNotACurrency, accountId,
fieldName, "expected: CLRN/INFO but is " + byIdObject.getAccountType()); // Счет %S не fieldName, "expected: CLRN/INFO but is " + byIdObject.getAccountType());
} }
if (CurrencyCode.isRub(byIdObject.getCurrency()) || StringUtils.isEmpty(byIdObject.getCurrency())) { if (CurrencyCode.isRub(byIdObject.getCurrency()) || StringUtils.isEmpty(byIdObject.getCurrency())) {
return of(AccountError.AccountIsNotACurrency, accountId, fieldName); // Счет %S не валютный return of(AccountError.AccountIsNotACurrency, accountId, fieldName);
} }
// Проверка отсутствия других TradingClearingRegistryList с этими счетами
Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg = context.obtainMap(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class); Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg = context.obtainMap(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class);
ImdgPredicateBuilder pb = tradingClearingRegistryListImdg.predicateBuilder(); ImdgPredicateBuilder pb = tradingClearingRegistryListImdg.predicateBuilder();
@ -217,8 +214,8 @@ public class TradingClearingRegistryListValidationConfig {
pb.equals("accountId", accountId), pb.equals("accountId", accountId),
pb.equals("status", WorkflowStatus.Active.getKey()) pb.equals("status", WorkflowStatus.Active.getKey())
)); ));
if (!listWithAccountId.isEmpty()){ if (!listWithAccountId.isEmpty()) {
return of(AccountError.AccountForTradingClearingRegistryAlreadyUsed, byIdObject.getAccount(), fieldName); // (5023) «Данная счет %s уже используется» return of(AccountError.AccountForTradingClearingRegistryAlreadyUsed, byIdObject.getAccount(), fieldName);
} }
Long tkrId = tkrIdGetter.apply(validatedObject); Long tkrId = tkrIdGetter.apply(validatedObject);
ImdgPredicate query = pb.and( ImdgPredicate query = pb.and(
@ -227,17 +224,13 @@ public class TradingClearingRegistryListValidationConfig {
pb.equals("currency", byIdObject.getCurrency())); pb.equals("currency", byIdObject.getCurrency()));
if (idGetter != null) { if (idGetter != null) {
Long id = idGetter.apply(validatedObject); Long id = idGetter.apply(validatedObject);
if (id == null) // never if (id == null)
return of(AccountError.RequiredFieldEmpty, "id"); return of(AccountError.RequiredFieldEmpty, "id");
query = pb.and(query, pb.not(pb.equals("id", id))); query = pb.and(query, pb.not(pb.equals("id", id)));
} }
Collection<TradingClearingRegistryList> inOtherLists = tradingClearingRegistryListImdg.getCollectionObjectsByPredicate(query); Collection<TradingClearingRegistryList> inOtherLists = tradingClearingRegistryListImdg.getCollectionObjectsByPredicate(query);
if (!inOtherLists.isEmpty()) { if (!inOtherLists.isEmpty()) {
// Collection<String> duplicateAccounts = inOtherLists.stream() return of(AccountError.CurrencyForTradingClearingRegistryListAlreadyUsed, byIdObject.getCurrency(), fieldName);
// .map(tradingClearingRegistryList ->
// accountImdg.getSingleObjectByID(tradingClearingRegistryList.getAccountId()).getAccount())
// .collect(Collectors.toSet());
return of(AccountError.CurrencyForTradingClearingRegistryListAlreadyUsed, byIdObject.getCurrency(), fieldName); // (5023) «Данная валюта %s уже используется»
} }
} }
} }

View file

@ -78,33 +78,17 @@ public class TradingClearingRegistryValidationConfig {
AccountError.RequiredFieldEmpty, AccountError.RequiredFieldEmpty,
moneyAccountId -> { moneyAccountId -> {
Imdg<Account> accountImdg = context.obtainMap( Imdg<Account> accountImdg = context.obtainMap(
IMDGDistributedNames.Map_Account, Account.class IMDGDistributedNames.Map_Account, Account.class
); );
Account account = accountImdg.getSingleObjectByID(moneyAccountId); Account account = accountImdg.getSingleObjectByID(moneyAccountId);
if (account == null) { if (account == null) {
return AccountError.AccountNotFound; return AccountError.AccountNotFound;
} else { } else {
if (AccountType.Clrn.equalsByKey(account.getAccountType()) || AccountType.Info.equalsByKey(account.getAccountType())) { if (AccountType.Clrn.equalsByKey(account.getAccountType()) || AccountType.Info.equalsByKey(account.getAccountType())) {
// ok
} else { } else {
// неправильный тип
return AccountError.AccountNotFound; return AccountError.AccountNotFound;
} }
} }
// Imdg<ClearingAccount> clearingAccountImdg = context.obtainMap(
// IMDGDistributedNames.Map_ClearingAccount, ClearingAccount.class
// );
// ClearingAccount clearingAccount = clearingAccountImdg.getSingleObjectByFieldValues(
// Map.of("accountId",moneyAccountId)
// );
// if (clearingAccount == null) {
// Imdg<InformationAccount> informationAccountImdg = context.obtainMap(
// IMDGDistributedNames.Map_InformationAccount, InformationAccount.class
// );
// InformationAccount infoAccount = informationAccountImdg.getSingleObjectByFieldValues(
// Map.of("accountId",moneyAccountId));
// if (infoAccount == null) return AccountError.AccountNotFound;
// }
return null; return null;
}), }),
FieldRequiredRule.instance("depoAccountId", FieldRequiredRule.instance("depoAccountId",
@ -165,39 +149,34 @@ public class TradingClearingRegistryValidationConfig {
public Optional<EnumMessage> validate(ImdgValidationContext<TradingClearingRegistryUpdateRequest> context) { public Optional<EnumMessage> validate(ImdgValidationContext<TradingClearingRegistryUpdateRequest> context) {
TradingClearingRegistryUpdateRequest validatedObject = context.getValidatedObject(); TradingClearingRegistryUpdateRequest validatedObject = context.getValidatedObject();
Long depoAccountId = validatedObject.getDepoAccountId(); Long depoAccountId = validatedObject.getDepoAccountId();
if (depoAccountId == null) // необязательное поле if (depoAccountId == null)
return empty(); return empty();
// Проверка типа счёта ДЕПО, что существует
Imdg<DepoAccount> depoAccountImdg = context.obtainMap(IMDGDistributedNames.Map_DepoAccount, DepoAccount.class); Imdg<DepoAccount> depoAccountImdg = context.obtainMap(IMDGDistributedNames.Map_DepoAccount, DepoAccount.class);
DepoAccount depoAccount = depoAccountImdg.getFirstObjectByFieldValues( DepoAccount depoAccount = depoAccountImdg.getFirstObjectByFieldValues(
Map.of("accountId", depoAccountId) Map.of("accountId", depoAccountId)
); );
if (depoAccount == null) if (depoAccount == null)
return of(AccountError.AccountNotFound, depoAccountId); return of(AccountError.AccountNotFound, depoAccountId);
// Проверка компании ТКР и счёта
Imdg<TradingClearingRegistry> tcrMap = context.obtainMap(IMDGDistributedNames.Map_TradingClearingRegistry, TradingClearingRegistry.class); Imdg<TradingClearingRegistry> tcrMap = context.obtainMap(IMDGDistributedNames.Map_TradingClearingRegistry, TradingClearingRegistry.class);
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class); Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
Account account = accountImdg.getSingleObjectByID(validatedObject.getMoneyAccountId()); Account account = accountImdg.getSingleObjectByID(validatedObject.getMoneyAccountId());
if (account == null) { // never if (account == null) {
return of(AccountError.AccountNotFound, depoAccountId); return of(AccountError.AccountNotFound, depoAccountId);
} }
TradingClearingRegistry updateObject = tcrMap.getSingleObjectByID(validatedObject.getId()); TradingClearingRegistry updateObject = tcrMap.getSingleObjectByID(validatedObject.getId());
if (!Objects.equals(account.getCompanyId(), updateObject.getCompanyId())) { if (!Objects.equals(account.getCompanyId(), updateObject.getCompanyId())) {
return of(AccountError.AccountNotFound, depoAccountId); // или UserVerifyDenial return of(AccountError.AccountNotFound, depoAccountId);
} }
// Проверка использования счёта в других ТКР
ImdgPredicateBuilder pb = tcrMap.predicateBuilder(); ImdgPredicateBuilder pb = tcrMap.predicateBuilder();
ImdgPredicate query = pb.and(pb.equals("depoAccountId", validatedObject.getDepoAccountId()), ImdgPredicate query = pb.and(pb.equals("depoAccountId", validatedObject.getDepoAccountId()),
pb.not(pb.equals("id", validatedObject.getId())) pb.not(pb.equals("id", validatedObject.getId()))
); );
Collection<TradingClearingRegistry> existTCR = tcrMap.getCollectionObjectsByPredicate(query); Collection<TradingClearingRegistry> existTCR = tcrMap.getCollectionObjectsByPredicate(query);
if (existTCR.isEmpty()) { if (existTCR.isEmpty()) {
return empty(); return empty();
} else { } else {
if (account == null && validatedObject.getDepoAccountId() != null) account = accountImdg.getSingleObjectByID(validatedObject.getDepoAccountId()); if (account == null && validatedObject.getDepoAccountId() != null)
account = accountImdg.getSingleObjectByID(validatedObject.getDepoAccountId());
return of(AccountError.AccountForTradingClearingRegistryAlreadyUsed, account.getAccount()); return of(AccountError.AccountForTradingClearingRegistryAlreadyUsed, account.getAccount());
} }
} }

View file

@ -54,8 +54,6 @@ public class ValidationConfig {
addImdg.accept(IMDGDistributedNames.Map_AccountSymbols, AccountSymbols.class); addImdg.accept(IMDGDistributedNames.Map_AccountSymbols, AccountSymbols.class);
addImdg.accept(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class); addImdg.accept(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class);
addImdg.accept(IMDGDistributedNames.Map_Currency, Currency.class); addImdg.accept(IMDGDistributedNames.Map_Currency, Currency.class);
//for ClientCodeValidationConfig
addImdg.accept(IMDGDistributedNames.Map_ClientCode, ClientCode.class); addImdg.accept(IMDGDistributedNames.Map_ClientCode, ClientCode.class);
return imdg; return imdg;

View file

@ -19,13 +19,12 @@ public enum AccountError implements IErrorEnumId {
DepoAccountNotFound(5017L), DepoAccountNotFound(5017L),
MoneyAccountNotFound(5018L), MoneyAccountNotFound(5018L),
ClearingCategoryNotFound(5019L), ClearingCategoryNotFound(5019L),
ClearingCompanySymbolNotFound(5022L), // Для компании %s отсутствует клиринговый код». ClearingCompanySymbolNotFound(5022L),
AccountForTradingClearingRegistryAlreadyUsed(5023L), AccountForTradingClearingRegistryAlreadyUsed(5023L),
AccountFieldNotSet(5024L), AccountFieldNotSet(5024L),
AccountDepoTypeRequired(5025L), AccountDepoTypeRequired(5025L),
AccountIsNotACurrency(5026L), // Счет %S не валютный AccountIsNotACurrency(5026L),
CompanyHasNotClearingMemberCategory(5027L), CompanyHasNotClearingMemberCategory(5027L),
//ошибки для трансляции в модуль gateway
TCR_NOT_FOUND_GTW(5028L), TCR_NOT_FOUND_GTW(5028L),
ACCOUNT_NOT_FOUND_GTW(5029L), ACCOUNT_NOT_FOUND_GTW(5029L),
COMPANY_NOT_FOUND_GTW(5030L), COMPANY_NOT_FOUND_GTW(5030L),

View file

@ -42,11 +42,6 @@ public class AccountHelper {
this.messageResolver = messageResolver; this.messageResolver = messageResolver;
} }
/**
* Заполняет поля relationId и companyId из соответствующей записи Relation
*
* @param requestId Идентификатор запроса для вывода лога
*/
public RequestInfoUpdate fillAccountFromRelation(Account account, Long requestId, boolean checkClearingMemberCategory) { public RequestInfoUpdate fillAccountFromRelation(Account account, Long requestId, boolean checkClearingMemberCategory) {
Long companyId = account.getCompanyId(); Long companyId = account.getCompanyId();
Collection<Relation> relations; Collection<Relation> relations;
@ -73,7 +68,6 @@ public class AccountHelper {
} else { } else {
log.info("ClearingCategoryNotFound with clearingCategoryValue={} not implemented. Do not search Relation.", clearingCategoryValue); log.info("ClearingCategoryNotFound with clearingCategoryValue={} not implemented. Do not search Relation.", clearingCategoryValue);
return null; return null;
//return makeError(requestId, AccountError.ClearingCategoryNotFound, companyId, clearingCategoryValue + " (case not implemented)");
} }
finalRelationPredicate = relationPredicateBuilder.and(consumerIdPredicate, servicePredicate); finalRelationPredicate = relationPredicateBuilder.and(consumerIdPredicate, servicePredicate);
relations = relationMap.getCollectionObjectsByPredicate(finalRelationPredicate); relations = relationMap.getCollectionObjectsByPredicate(finalRelationPredicate);
@ -83,7 +77,6 @@ public class AccountHelper {
} }
if (relations.isEmpty()) { if (relations.isEmpty()) {
//return makeError(requestId, AccountError.WrongFieldValue, "companyId", finalRelationPredicate.toString());
log.info("Relation not found: {}", finalRelationPredicate.toString()); log.info("Relation not found: {}", finalRelationPredicate.toString());
return null; return null;
} }

View file

@ -167,10 +167,8 @@ public class AccountService extends QueueConsumer implements InitializingBean {
Long newId = null; Long newId = null;
if (AccountType.Corr.equalsByKey(account.getAccountType())) { if (AccountType.Corr.equalsByKey(account.getAccountType())) {
// default, дополнительные таблицы не требуются
newId = accountMap.insert(account); newId = accountMap.insert(account);
} else { } else {
// Транзакцией
ImdgTransaction imdgTransaction = imdgProvider.newTransaction(); ImdgTransaction imdgTransaction = imdgProvider.newTransaction();
imdgTransaction.beginTransaction(); imdgTransaction.beginTransaction();
boolean txOk = false; boolean txOk = false;
@ -179,7 +177,6 @@ public class AccountService extends QueueConsumer implements InitializingBean {
newId = accountMap.insert(account); newId = accountMap.insert(account);
if (AccountType.Corr.equalsByKey(account.getAccountType())) { if (AccountType.Corr.equalsByKey(account.getAccountType())) {
// default, дополнительные таблицы не требуются
} else if (AccountType.Info.equalsByKey(account.getAccountType())) } else if (AccountType.Info.equalsByKey(account.getAccountType()))
makeInfoPart(imdgTransaction, account); makeInfoPart(imdgTransaction, account);
else if (AccountType.Depo.equalsByKey(account.getAccountType())) else if (AccountType.Depo.equalsByKey(account.getAccountType()))
@ -231,7 +228,6 @@ public class AccountService extends QueueConsumer implements InitializingBean {
if (account.getAccount() != null && account.getAccount().contains("BC")) { if (account.getAccount() != null && account.getAccount().contains("BC")) {
depoAcc.setDepoAccountType(DepoAccountType.C.getKey()); depoAcc.setDepoAccountType(DepoAccountType.C.getKey());
} else { } else {
//todo в реквесте нет поля depoAcc.setDepoAccountType(req.getDepoAccountType());
} }
Long depoId = depoAccountMap.insert(depoAcc); Long depoId = depoAccountMap.insert(depoAcc);
log.debug("For account id={} make DepoAccount id={}", account.getId(), depoId); log.debug("For account id={} make DepoAccount id={}", account.getId(), depoId);
@ -299,7 +295,7 @@ public class AccountService extends QueueConsumer implements InitializingBean {
log.debug("AccountTerminationRequest received, id={}", userRequest.getId()); log.debug("AccountTerminationRequest received, id={}", userRequest.getId());
RequestInfoUpdate requestInfoUpdate = userRoleVerification.validateRoleAndGetResult(userRequest); RequestInfoUpdate requestInfoUpdate = userRoleVerification.validateRoleAndGetResult(userRequest);
if (requestInfoUpdate != null) return requestInfoUpdate; // never - system if (requestInfoUpdate != null) return requestInfoUpdate;
AccountTerminationRequest req = userRequest.getRequestPayload(); AccountTerminationRequest req = userRequest.getRequestPayload();
final Long companyId = req.getCompanyId(); final Long companyId = req.getCompanyId();
@ -311,7 +307,6 @@ public class AccountService extends QueueConsumer implements InitializingBean {
try { try {
tx.beginTransaction(); tx.beginTransaction();
for (Account account : accounts) { for (Account account : accounts) {
//Account account = accountMap.getSingleObjectByID(request.getId());
if (!ServiceStatus.Blocked.equalsByKey(account.getStatus())) { if (!ServiceStatus.Blocked.equalsByKey(account.getStatus())) {
account.setStatus(ServiceStatus.Blocked.getKey()); account.setStatus(ServiceStatus.Blocked.getKey());
account.setUpdated(Instant.now()); account.setUpdated(Instant.now());

View file

@ -227,7 +227,6 @@ public class BankAccountService extends QueueConsumer implements InitializingBea
account.setUpdated(Instant.now()); account.setUpdated(Instant.now());
accountMap.update(account); accountMap.update(account);
//без изменений bankAccountMap.update(bankAccount);
log.debug("successfully block, existing bankAccount with id {}", bankAccount.getId()); log.debug("successfully block, existing bankAccount with id {}", bankAccount.getId());
return null; return null;

View file

@ -286,7 +286,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} catch (Throwable e) { } catch (Throwable e) {
AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart(); AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart();
responsePart.setSdfId(accountReq.getSdfId()); responsePart.setSdfId(accountReq.getSdfId());
responsePart.setErrorCode(AccountError.DictionaryNotFound.getId()); // see accountService.fillAccountFromRelation responsePart.setErrorCode(AccountError.DictionaryNotFound.getId());
responsePart.setErrorText("couldn't extract currency from '%s' account".formatted(accountReq.getAccount())); responsePart.setErrorText("couldn't extract currency from '%s' account".formatted(accountReq.getAccount()));
accountToStatement.add(responsePart); accountToStatement.add(responsePart);
log.info("sdf.id={} companyId={} accountType={} couldn't find currency for account {}", log.info("sdf.id={} companyId={} accountType={} couldn't find currency for account {}",
@ -307,11 +307,11 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
account.setUpdated(now); account.setUpdated(now);
RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequest.getId(), true); RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequest.getId(), true);
if (requestInfoUpdate != null) { if (requestInfoUpdate != null) {
log.warn("Error fill new account from relation. {}", /*account.getId(),*/ requestInfoUpdate.getMessage()); log.warn("Error fill new account from relation. {}", requestInfoUpdate.getMessage());
{ {
AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart(); AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart();
responsePart.setSdfId(accountReq.getSdfId()); responsePart.setSdfId(accountReq.getSdfId());
responsePart.setErrorCode(AccountError.ClearingCategoryNotFound.getId()); // see accountService.fillAccountFromRelation responsePart.setErrorCode(AccountError.ClearingCategoryNotFound.getId());
responsePart.setErrorText(requestInfoUpdate.getMessage()); responsePart.setErrorText(requestInfoUpdate.getMessage());
accountToStatement.add(responsePart); accountToStatement.add(responsePart);
continue accountsLoop; continue accountsLoop;
@ -373,22 +373,14 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
return null; return null;
} }
/**
* Логика похожа на SDF01
*
* @param accountValue account
* @param companyId
* @param userRequestId для лога
* @return
*/
private synchronized Account createSdf52Account(String accountValue, String acctType, Long companyId, Long userRequestId) { private synchronized Account createSdf52Account(String accountValue, String acctType, Long companyId, Long userRequestId) {
{ // Валидация {
boolean existClearingAccountTypeDictionary; boolean existClearingAccountTypeDictionary;
if (!StringUtils.hasText(acctType)) { if (!StringUtils.hasText(acctType)) {
existClearingAccountTypeDictionary = false; existClearingAccountTypeDictionary = false;
} else { } else {
ClearingAccountTypeDictionary catd = clearingAccountTypeDictionaryImdg.getFirstObjectByFieldValues( ClearingAccountTypeDictionary catd = clearingAccountTypeDictionaryImdg.getFirstObjectByFieldValues(
Map.of("code", acctType)); Map.of("code", acctType));
existClearingAccountTypeDictionary = catd != null; existClearingAccountTypeDictionary = catd != null;
} }
if (!existClearingAccountTypeDictionary) { if (!existClearingAccountTypeDictionary) {
@ -398,7 +390,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} }
ClearingMemberCategory companyAnyCMC = clearingMemberCategoryImdg.getFirstObjectByFieldValues(Map.of( ClearingMemberCategory companyAnyCMC = clearingMemberCategoryImdg.getFirstObjectByFieldValues(Map.of(
"companyId", companyId "companyId", companyId
)); ));
if (companyAnyCMC == null) { if (companyAnyCMC == null) {
String errMsg = messageResolver.resolve(new EnumMessage(AccountError.CompanyHasNotClearingMemberCategory, companyId)); String errMsg = messageResolver.resolve(new EnumMessage(AccountError.CompanyHasNotClearingMemberCategory, companyId));
@ -428,19 +420,19 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
account.setUpdated(now); account.setUpdated(now);
RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequestId, true); RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequestId, true);
if (requestInfoUpdate != null) { if (requestInfoUpdate != null) {
log.warn("Error fill new account from relation. {}", /*account.getId(),*/ requestInfoUpdate.getMessage()); log.warn("Error fill new account from relation. {}", requestInfoUpdate.getMessage());
return null; return null;
} }
Account existAccount = accountImdg.getFirstObjectBySQL("account = '%s' and accountType='%s'" Account existAccount = accountImdg.getFirstObjectBySQL("account = '%s' and accountType='%s'"
.formatted(accountValue, AccountType.Clrn.getKey())); .formatted(accountValue, AccountType.Clrn.getKey()));
if (existAccount != null) { if (existAccount != null) {
log.debug("Sdf52: Account {} already exists", accountValue); log.debug("Sdf52: Account {} already exists", accountValue);
if (companyId.equals(existAccount.getCompanyId())) { if (companyId.equals(existAccount.getCompanyId())) {
return existAccount; return existAccount;
} else { } else {
log.debug("Sdf52: Account {} already exists for other companyId={}, do not apply for companyId={}", log.debug("Sdf52: Account {} already exists for other companyId={}, do not apply for companyId={}",
accountValue, existAccount.getCompanyId(), companyId); accountValue, existAccount.getCompanyId(), companyId);
return null; return null;
} }
} }
@ -471,7 +463,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
Long groupId = req.getGroupId(); Long groupId = req.getGroupId();
if (SdfTable.SDF_52 != req.getTable()) { if (SdfTable.SDF_52 != req.getTable()) {
log.warn("Unsupported table {} received on accountUpdateSdf52. Expected only {}.", log.warn("Unsupported table {} received on accountUpdateSdf52. Expected only {}.",
req.getTable(), SdfTable.SDF_52); req.getTable(), SdfTable.SDF_52);
} }
Collection<SDf52> sdfs = sdfProcessService.sdfsByGroupId(groupId); Collection<SDf52> sdfs = sdfProcessService.sdfsByGroupId(groupId);
if (sdfs.isEmpty()) { if (sdfs.isEmpty()) {
@ -482,13 +474,13 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
List<Pair<SDf52, Account>> toUpdate = new ArrayList<>(); List<Pair<SDf52, Account>> toUpdate = new ArrayList<>();
List<Triple<SDf52, Account, String>> toProcessSDF53 = new ArrayList<>(); List<Triple<SDf52, Account, String>> toProcessSDF53 = new ArrayList<>();
{ // 1. Выборка данных {
for (SDf52 sDf52 : sdfs) { for (SDf52 sDf52 : sdfs) {
if (sdfProcessService.parseSdf52Status(sDf52.getStatus()) == null) { if (sdfProcessService.parseSdf52Status(sDf52.getStatus()) == null) {
String msg = messageResolver.resolve(new EnumMessage(AccountError.WrongFieldValue, "status")); String msg = messageResolver.resolve(new EnumMessage(AccountError.WrongFieldValue, "status"));
log.warn("By generationId={} s_df52[{}] error: {}", groupId, sDf52.getId(), msg); log.warn("By generationId={} s_df52[{}] error: {}", groupId, sDf52.getId(), msg);
toProcessSDF53.add(new MutableTriple<>(sDf52, null, toProcessSDF53.add(new MutableTriple<>(sDf52, null,
makeSdfErrorText(AccountError.WrongFieldValue, SDFProcessService.SDF_STATUS_ERROR))); makeSdfErrorText(AccountError.WrongFieldValue, SDFProcessService.SDF_STATUS_ERROR)));
continue; continue;
} }
Company company = sDf52.getDeal() == null ? null : companyImdg.getSingleObjectByFieldValues(Map.of("tradingCode", sDf52.getDeal())); Company company = sDf52.getDeal() == null ? null : companyImdg.getSingleObjectByFieldValues(Map.of("tradingCode", sDf52.getDeal()));
@ -496,30 +488,30 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
String msg = messageResolver.resolve(new EnumMessage(AccountError.CompanyNotFound, sDf52.getDeal())); String msg = messageResolver.resolve(new EnumMessage(AccountError.CompanyNotFound, sDf52.getDeal()));
log.warn("By generationId={} s_df52[{}] error: {}", groupId, sDf52.getId(), msg); log.warn("By generationId={} s_df52[{}] error: {}", groupId, sDf52.getId(), msg);
toProcessSDF53.add(new MutableTriple<>(sDf52, null, toProcessSDF53.add(new MutableTriple<>(sDf52, null,
makeSdfErrorText(AccountError.CompanyNotFound, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND))); makeSdfErrorText(AccountError.CompanyNotFound, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND)));
continue; continue;
} }
Map<String, Comparable<?>> accountQuery = Map.of( Map<String, Comparable<?>> accountQuery = Map.of(
"accountType", AccountType.Clrn.getKey(), "accountType", AccountType.Clrn.getKey(),
"account", sDf52.getAccount(), "account", sDf52.getAccount(),
"companyId", company.getId() "companyId", company.getId()
); );
Account account = sDf52.getAccount() == null ? null : accountImdg.getFirstObjectByFieldValues(accountQuery); Account account = sDf52.getAccount() == null ? null : accountImdg.getFirstObjectByFieldValues(accountQuery);
if (account == null) { if (account == null) {
if (SDFProcessService.SDF52_STATUS_3Open.equals(sDf52.getStatus())) { if (SDFProcessService.SDF52_STATUS_3Open.equals(sDf52.getStatus())) {
log.trace("By generationId={} s_df52[{}].status={}, account not found (query: {}). Try create new account.", log.trace("By generationId={} s_df52[{}].status={}, account not found (query: {}). Try create new account.",
groupId, sDf52.getId(), sDf52.getStatus(), accountQuery); groupId, sDf52.getId(), sDf52.getStatus(), accountQuery);
account = createSdf52Account(sDf52.getAccount(),sDf52.getAcc_type(), company.getId(), systemRequest.getId()); account = createSdf52Account(sDf52.getAccount(), sDf52.getAcc_type(), company.getId(), systemRequest.getId());
if (account == null) { if (account == null) {
log.info("Can not create account: \"{}\", companyId={}. Ignore SDF52.id={}", log.info("Can not create account: \"{}\", companyId={}. Ignore SDF52.id={}",
sDf52.getAccount(), company.getId(), sDf52.getId()); sDf52.getAccount(), company.getId(), sDf52.getId());
continue; continue;
} }
} else { } else {
String msg = messageResolver.resolve(new EnumMessage(AccountError.AccountNotFound, sDf52.getAccount())); String msg = messageResolver.resolve(new EnumMessage(AccountError.AccountNotFound, sDf52.getAccount()));
log.warn("By generationId={} s_df52[{}] (query: {}) error: {}", groupId, sDf52.getId(), accountQuery, msg); log.warn("By generationId={} s_df52[{}] (query: {}) error: {}", groupId, sDf52.getId(), accountQuery, msg);
toProcessSDF53.add(new MutableTriple<>(sDf52, null, toProcessSDF53.add(new MutableTriple<>(sDf52, null,
makeSdfErrorText(AccountError.AccountNotFound, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND))); makeSdfErrorText(AccountError.AccountNotFound, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND)));
continue; continue;
} }
} }
@ -530,27 +522,24 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} }
} }
log.debug("Selected to update {} account's", toUpdate.size()); log.debug("Selected to update {} account's", toUpdate.size());
// 4. to notification
List<Long> notificationAccountIds = new ArrayList<>(); List<Long> notificationAccountIds = new ArrayList<>();
for (Pair<SDf52, Account> item : toUpdate) { for (Pair<SDf52, Account> item : toUpdate) {
SDf52 sdf = item.getFirst(); SDf52 sdf = item.getFirst();
Account account = item.getSecond(); Account account = item.getSecond();
AccountStatus newStatus = sdfProcessService.parseSdf52Status(sdf.getStatus()); AccountStatus newStatus = sdfProcessService.parseSdf52Status(sdf.getStatus());
if (newStatus == null) { // never if (newStatus == null) {
throw new IllegalArgumentException("Can not parse sdf status " + sdf.getStatus()); throw new IllegalArgumentException("Can not parse sdf status " + sdf.getStatus());
} }
if (newStatus.equalsByKey(account.getStatus())) { if (newStatus.equalsByKey(account.getStatus())) {
// одинаковых обычно не бывает.
log.trace("In sDF_52[{}] for account [{}] status {} not changed.", sdf.getId(), account.getId(), newStatus); log.trace("In sDF_52[{}] for account [{}] status {} not changed.", sdf.getId(), account.getId(), newStatus);
continue; continue;
} }
if (AccountStatus.BLOCKED == newStatus || AccountStatus.CLOSE == newStatus) { // статус 0/2 if (AccountStatus.BLOCKED == newStatus || AccountStatus.CLOSE == newStatus) {
sendNotificationRequest(ObjectType.account_block, account, newStatus); sendNotificationRequest(ObjectType.account_block, account, newStatus);
notificationAccountIds.add(account.getId()); notificationAccountIds.add(account.getId());
putNotificationWaiting(systemRequest, item.getFirst(), item.getSecond()); putNotificationWaiting(systemRequest, item.getFirst(), item.getSecond());
} }
if (AccountStatus.ACTIVE == newStatus) { // статус 1/3 if (AccountStatus.ACTIVE == newStatus) {
sendNotificationRequest(ObjectType.account_active, account, newStatus); sendNotificationRequest(ObjectType.account_active, account, newStatus);
notificationAccountIds.add(account.getId()); notificationAccountIds.add(account.getId());
putNotificationWaiting(systemRequest, item.getFirst(), item.getSecond()); putNotificationWaiting(systemRequest, item.getFirst(), item.getSecond());
@ -561,7 +550,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
log.info("{} account's need wait accept over notification. GroupId={}", notificationAccountIds.size(), groupId); log.info("{} account's need wait accept over notification. GroupId={}", notificationAccountIds.size(), groupId);
log.debug("successfully processed, grouping id={} with {} accounts.", log.debug("successfully processed, grouping id={} with {} accounts.",
groupId, toUpdate.size()); groupId, toUpdate.size());
return null; return null;
} }
@ -589,32 +578,26 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
protected synchronized RequestInfoUpdate accountUpdateSdf52_part2(BaseRequest<StatementRequest> systemRequest1, protected synchronized RequestInfoUpdate accountUpdateSdf52_part2(BaseRequest<StatementRequest> systemRequest1,
SDf52 sdf, Account account, SDf52 sdf, Account account,
BaseRequest<NotificationFeedbackRequest> secondSystemRequest2) { BaseRequest<NotificationFeedbackRequest> secondSystemRequest2) {
// 5. from notification:
StatementRequest req = systemRequest1.getRequestPayload(); StatementRequest req = systemRequest1.getRequestPayload();
Long groupId = req.getGroupId(); Long groupId = req.getGroupId();
log.info("Continue Sdf52 groupId={}, first request id={}, second request id={}", log.info("Continue Sdf52 groupId={}, first request id={}, second request id={}",
groupId, systemRequest1 == null ? null : systemRequest1.getId(), secondSystemRequest2 == null ? null : secondSystemRequest2.getId()); groupId, systemRequest1 == null ? null : systemRequest1.getId(), secondSystemRequest2 == null ? null : secondSystemRequest2.getId());
int countOfUpdated = 0; int countOfUpdated = 0;
// 2. обновление данных
Instant now = Instant.now(); Instant now = Instant.now();
AccountStatus newStatus = sdfProcessService.parseSdf52Status(sdf.getStatus()); AccountStatus newStatus = sdfProcessService.parseSdf52Status(sdf.getStatus());
if (newStatus == null) { if (newStatus == null) {
throw new IllegalArgumentException("Can not parse sdf status " + sdf.getStatus()); throw new IllegalArgumentException("Can not parse sdf status " + sdf.getStatus());
} }
// За долгое время ожидания пользователя счёт мог быть обновлён, прочитать его ещё раз
account = accountImdg.getSingleObjectByID(account.getId()); account = accountImdg.getSingleObjectByID(account.getId());
if (!newStatus.equalsByKey(account.getStatus())) { if (!newStatus.equalsByKey(account.getStatus())) {
// Обновление счёта
String oldStatus = account.getStatus(); String oldStatus = account.getStatus();
account.setStatus(newStatus.getKey()); account.setStatus(newStatus.getKey());
account.setUpdated(now); account.setUpdated(now);
accountImdg.update(account); accountImdg.update(account);
log.trace("S_DF52[{}] do update status to {} for account[{}]", log.trace("S_DF52[{}] do update status to {} for account[{}]",
sdf.getId(), newStatus.getKey(), account.getId()); sdf.getId(), newStatus.getKey(), account.getId());
if (AccountStatus.ACTIVE.equalsByKey(oldStatus) && AccountStatus.ACTIVE != newStatus) { // счёт заблокировали - значит блокируем ТКР, наоборот не надо. if (AccountStatus.ACTIVE.equalsByKey(oldStatus) && AccountStatus.ACTIVE != newStatus) {
// Отправка в ТКР
TradingClearingRegistryUpdateRequest tcrReq = new TradingClearingRegistryUpdateRequest(); TradingClearingRegistryUpdateRequest tcrReq = new TradingClearingRegistryUpdateRequest();
tcrReq.setMoneyAccountId(account.getId()); tcrReq.setMoneyAccountId(account.getId());
tcrReq.setCompanyId(account.getCompanyId()); tcrReq.setCompanyId(account.getCompanyId());
@ -639,7 +622,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} }
log.debug("successfully processed, grouping id={}. Updated {} accounts.", log.debug("successfully processed, grouping id={}. Updated {} accounts.",
groupId, countOfUpdated); groupId, countOfUpdated);
return null; return null;
} }
@ -659,7 +642,7 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
request.setAccountCreationResults(results); request.setAccountCreationResults(results);
request.setFromAccount(true); request.setFromAccount(true);
request.setContinueSdf(true); request.setContinueSdf(true);
request.setTable(SdfTable.SDF_01); // по нему запрос получили request.setTable(SdfTable.SDF_01);
log.debug("Send message to kafka \"{}\": {}", destination, LogFormatter.toStringWrapper(request)); log.debug("Send message to kafka \"{}\": {}", destination, LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(destination, request); kafkaSender.sendRequestToQueue(destination, request);
} }
@ -683,14 +666,10 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} }
/**
* Формирование уведомления о добавлении счёта
*/
public Long sendNotificationAccountNewRequest(Account account) { public Long sendNotificationAccountNewRequest(Account account) {
String message = String.format("Добавлен новый счет %s", account.getAccount()); String message = String.format("Добавлен новый счет %s", account.getAccount());
final String destination = Consts.NOTIFICATION_NEW; final String destination = Consts.NOTIFICATION_NEW;
NotificationNewRequest request = new NotificationNewRequest(); NotificationNewRequest request = new NotificationNewRequest();
//request.setObjectId(account.getId());
request.setObjectType(ObjectType.rgst.getKey()); request.setObjectType(ObjectType.rgst.getKey());
request.setPriority(Priority.HIGH.getKey()); request.setPriority(Priority.HIGH.getKey());
request.setComment(message); request.setComment(message);
@ -701,7 +680,6 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
} }
// --------- notification apply system -----------
public static class SDF52WaitingData { public static class SDF52WaitingData {
public BaseRequest<StatementRequest> systemRequest; public BaseRequest<StatementRequest> systemRequest;
public SDf52 sdf; public SDf52 sdf;
@ -735,9 +713,6 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
return true; return true;
} }
/**
* @return triggered SDF52WaitingData or null
*/
public SDF52WaitingData onNotificationResponse(NotificationFeedbackRequest onNotification) { public SDF52WaitingData onNotificationResponse(NotificationFeedbackRequest onNotification) {
if (onNotification.getNotificationId() == null) { if (onNotification.getNotificationId() == null) {
log.trace("notificationId was empty"); log.trace("notificationId was empty");

View file

@ -80,7 +80,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
protected TradingClearingRegistryService tradingClearingRegistryService; protected TradingClearingRegistryService tradingClearingRegistryService;
protected ConfigurableApplicationContext context; protected ConfigurableApplicationContext context;
private final KafkaSender kafkaSender; private final KafkaSender kafkaSender;
//protected TradingClearingRegistryListService tradingClearingRegistryListService;
@Autowired @Autowired
public ClientCodeService(Consumer<String, Object> kafkaQueue, public ClientCodeService(Consumer<String, Object> kafkaQueue,
@ -91,7 +90,7 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
IMessageResolver messageResolver, IMessageResolver messageResolver,
RequestHelper requestHelper, RequestHelper requestHelper,
TradingClearingRegistryService tradingClearingRegistryService, TradingClearingRegistryService tradingClearingRegistryService,
ConfigurableApplicationContext context, //TradingClearingRegistryListService tradingClearingRegistryListService, ConfigurableApplicationContext context,
UserRoleVerification userRoleVerification, UserRoleVerification userRoleVerification,
@Qualifier("clientCodeNewRequestValidator") Function<ClientCodeNewRequest, IValidator> clientCodeNewRequestValidator, @Qualifier("clientCodeNewRequestValidator") Function<ClientCodeNewRequest, IValidator> clientCodeNewRequestValidator,
@Qualifier("clientCodeUpdateRequestValidator") Function<ClientCodeUpdateRequest, IValidator> clientCodeUpdateRequestValidator, @Qualifier("clientCodeUpdateRequestValidator") Function<ClientCodeUpdateRequest, IValidator> clientCodeUpdateRequestValidator,
@ -115,20 +114,12 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
this.messageResolver = messageResolver; this.messageResolver = messageResolver;
this.userRoleVerification = userRoleVerification; this.userRoleVerification = userRoleVerification;
this.tradingClearingRegistryService = tradingClearingRegistryService; this.tradingClearingRegistryService = tradingClearingRegistryService;
this.context = context; // TradingClearingRegistryListService this.context = context;
} }
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
imdgProvider.waitAvailable(); imdgProvider.waitAvailable();
// callback(ClientCodeNewRequest.class)
// .setFunction(this::clientCodeNew)
// .forDestination(Consts.DESTINATION_CLIENT_CODE_NEW, callbacks::put);
//note переехало в ClientCodeMessageListener[новая версия сервиса]
// callback(TkrAccountsGatewayRequest.class)
// .setFunction(this::clientCodeNewFromGateway)
// .forDestination(Consts.DESTINATION_CLIENT_CODE_NEW_FROM_GATEWAY, callbacks::put);
callback(ClientCodeNewRequest.class) callback(ClientCodeNewRequest.class)
.setFunction(this::clientCodeNewFromApiUmCompany) .setFunction(this::clientCodeNewFromApiUmCompany)
.forDestination(Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, callbacks::put); .forDestination(Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, callbacks::put);
@ -143,19 +134,8 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
} }
/**
* Проверки
* 3.5.1 если не была найдена запись в tradingClearingRegistry по companyId, moneyAccountId, depoAccountId и tradingClearingRegistryType=B (п 3.5.1)
* 3.5.2 если не заполнены поля moneyAccountId ИЛИ moneyAccountId и depoAccountId
*
* @param userRequest
* @param moneyAccountId req.getMoneyAccountId()
* @param depoAccountId req.getDepoAccountId()
* @param companyId req.getCompanyId()
* @return
*/
RequestInfoUpdate crossValidate(BaseRequest<?> userRequest, Long moneyAccountId, Long depoAccountId, Long companyId) { RequestInfoUpdate crossValidate(BaseRequest<?> userRequest, Long moneyAccountId, Long depoAccountId, Long companyId) {
if (moneyAccountId == null) { // Если не заполнены moneyAccountId ИЛИ moneyAccountId и depoAccountId if (moneyAccountId == null) {
EnumMessage error = null; EnumMessage error = null;
if (companyId == null) { if (companyId == null) {
error = new EnumMessage(AccountError.RequiredFieldEmpty, "companyId"); error = new EnumMessage(AccountError.RequiredFieldEmpty, "companyId");
@ -182,7 +162,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
ClientCodeNewRequest req = userRequest.getRequestPayload(); ClientCodeNewRequest req = userRequest.getRequestPayload();
// дополнительная проверка
requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId()); requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId());
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
@ -204,10 +183,9 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
ClientCode newClientCode = buildClientCode(req); ClientCode newClientCode = buildClientCode(req);
clientCodeMap.insert(newClientCode); clientCodeMap.insert(newClientCode);
log.debug("successfully processed, new clientCode id {}", newClientCode.getId()); log.debug("successfully processed, new clientCode id {}", newClientCode.getId());
} else {//fixme transaction! } else {
if (!fromTCRList) { if (!fromTCRList) {
if (req.getMoneyAccountId() != null /*&& currencyAccountId != null*/) { if (req.getMoneyAccountId() != null) {
// Для каждого счета из списка (currencyAccountList) должна быть создана отдельная запись объекте clientCode с данным счетом для данного клиента
TradingClearingRegistry tcr = selectTradingClearingRegistry(req.getCompanyId(), req.getMoneyAccountId(), req.getDepoAccountId()); TradingClearingRegistry tcr = selectTradingClearingRegistry(req.getCompanyId(), req.getMoneyAccountId(), req.getDepoAccountId());
TradingClearingRegistryListNewRequest tcrListNewR = new TradingClearingRegistryListNewRequest(); TradingClearingRegistryListNewRequest tcrListNewR = new TradingClearingRegistryListNewRequest();
@ -261,7 +239,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
ClientCodeNewRequest req = userRequest.getRequestPayload(); ClientCodeNewRequest req = userRequest.getRequestPayload();
// дополнительная проверка
requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId()); requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId());
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
@ -283,10 +260,9 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
ClientCode newClientCode = buildClientCode(req); ClientCode newClientCode = buildClientCode(req);
clientCodeMap.insert(newClientCode); clientCodeMap.insert(newClientCode);
log.debug("successfully processed, new clientCode id {}", newClientCode.getId()); log.debug("successfully processed, new clientCode id {}", newClientCode.getId());
} else {//fixme transaction! } else {
if (!fromTCRList) { if (!fromTCRList) {
if (req.getMoneyAccountId() != null /*&& currencyAccountId != null*/) { if (req.getMoneyAccountId() != null) {
// Для каждого счета из списка (currencyAccountList) должна быть создана отдельная запись объекте clientCode с данным счетом для данного клиента
TradingClearingRegistry tcr = selectTradingClearingRegistry(req.getCompanyId(), req.getMoneyAccountId(), req.getDepoAccountId()); TradingClearingRegistry tcr = selectTradingClearingRegistry(req.getCompanyId(), req.getMoneyAccountId(), req.getDepoAccountId());
TradingClearingRegistryListUpdateRequest tcrListUpdateR = new TradingClearingRegistryListUpdateRequest(); TradingClearingRegistryListUpdateRequest tcrListUpdateR = new TradingClearingRegistryListUpdateRequest();
@ -333,7 +309,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
requestInfoUpdate = validationHelper.validateTillFirstError(userRequest, clientCodeUpdateRequestValidator); requestInfoUpdate = validationHelper.validateTillFirstError(userRequest, clientCodeUpdateRequestValidator);
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
// дополнительная проверка
requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId()); requestInfoUpdate = crossValidate(userRequest, req.getMoneyAccountId(), req.getDepoAccountId(), req.getCompanyId());
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
@ -359,7 +334,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
} }
updateClientCode(clientCode, req); updateClientCode(clientCode, req);
//fixme спросить, у нас при апдейте передаётся clientCode.id которого надо изменять. А тут список currencyAccountList приходит - в нём что будет - только 1 счёт для него и его же менять?
clientCodeMap.update(clientCode); clientCodeMap.update(clientCode);
log.debug("successfully processed update, id {}", clientCode.getId()); log.debug("successfully processed update, id {}", clientCode.getId());
@ -407,7 +381,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
} }
private boolean checkNeedCreateTCR(Long companyId, Long moneyAccountId, Long depoAccountId) { private boolean checkNeedCreateTCR(Long companyId, Long moneyAccountId, Long depoAccountId) {
// moneyAccountId обязателен, depoAccountId опционален
if (moneyAccountId == null) { if (moneyAccountId == null) {
return false; return false;
} }
@ -431,11 +404,8 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
requestPayload.setCompanyId(companyId); requestPayload.setCompanyId(companyId);
requestPayload.setMoneyAccountId(moneyAccountId); requestPayload.setMoneyAccountId(moneyAccountId);
requestPayload.setDepoAccountId(depoAccountId); requestPayload.setDepoAccountId(depoAccountId);
// requestPayload.setStatus(WorkflowStatus.Active.getKey());
requestPayload.setTradingClearingRegistryType(TradingClearingRegistryType.Client_B.getKey()); requestPayload.setTradingClearingRegistryType(TradingClearingRegistryType.Client_B.getKey());
request.setRequestPayload(requestPayload); request.setRequestPayload(requestPayload);
// Следующий вызываемый метод обязательно должен быть synchronized.
RequestInfoUpdate reply = tradingClearingRegistryService.tradingClearingRegistryNew(request); RequestInfoUpdate reply = tradingClearingRegistryService.tradingClearingRegistryNew(request);
if (reply != null && Status.Error.equals(reply.getStatus())) { if (reply != null && Status.Error.equals(reply.getStatus())) {
log.warn("tradingClearingRegistryService return error: " + reply.getMessage()); log.warn("tradingClearingRegistryService return error: " + reply.getMessage());
@ -465,11 +435,6 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
} }
/**
* @param queue Consts.*
* @param message BaseRequest
* @return
*/
private Long sendMessage(String queue, BaseRequest<?> message) { private Long sendMessage(String queue, BaseRequest<?> message) {
Long sentRequestId = message.getId(); Long sentRequestId = message.getId();
if (sentRequestId == null) { if (sentRequestId == null) {
@ -493,13 +458,8 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
return null; return null;
} }
/**
* @param req требуется заполнить tradingClearingRegistryId по tradingClearingRegistry.code
* @return
*/
private ClientCode buildClientCode(ClientCodeNewRequest req) { private ClientCode buildClientCode(ClientCodeNewRequest req) {
ClientCode clientCode = new ClientCode(); ClientCode clientCode = new ClientCode();
// clientCode.setId(idSequence.newId()); add in insert
clientCode.setCreated(Instant.now()); clientCode.setCreated(Instant.now());
clientCode.setUpdated(clientCode.getCreated()); clientCode.setUpdated(clientCode.getCreated());

View file

@ -157,8 +157,6 @@ public class DepoAccountService extends QueueConsumer implements InitializingBea
accountsLoop: accountsLoop:
for (AccountSdfRequestPart accountReq : req.getAccounts()) { for (AccountSdfRequestPart accountReq : req.getAccounts()) {
// DepoAccountNewRequest req = userRequest.getRequestPayload();
Instant now = Instant.now(); Instant now = Instant.now();
Account account = new Account(); Account account = new Account();
account.setAccount(accountReq.getAccount()); account.setAccount(accountReq.getAccount());
@ -169,11 +167,11 @@ public class DepoAccountService extends QueueConsumer implements InitializingBea
account.setUpdated(now); account.setUpdated(now);
RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequest.getId(), true); RequestInfoUpdate requestInfoUpdate = accountService.fillAccountFromRelation(account, userRequest.getId(), true);
if (requestInfoUpdate != null) { if (requestInfoUpdate != null) {
log.warn("Error fill new account from relation. {}", /*account.getId(),*/ requestInfoUpdate.getMessage()); log.warn("Error fill new account from relation. {}", requestInfoUpdate.getMessage());
{ {
AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart(); AccountSdfToStatementRequestPart responsePart = new AccountSdfToStatementRequestPart();
responsePart.setSdfId(accountReq.getSdfId()); responsePart.setSdfId(accountReq.getSdfId());
responsePart.setErrorCode(AccountError.ClearingCategoryNotFound.getId()); // see accountService.fillAccountFromRelation responsePart.setErrorCode(AccountError.ClearingCategoryNotFound.getId());
responsePart.setErrorText(requestInfoUpdate.getMessage()); responsePart.setErrorText(requestInfoUpdate.getMessage());
accountToStatement.add(responsePart); accountToStatement.add(responsePart);
continue accountsLoop; continue accountsLoop;
@ -208,7 +206,6 @@ public class DepoAccountService extends QueueConsumer implements InitializingBea
depoAccountId = depoAccountImdg.insert(depoAccount); depoAccountId = depoAccountImdg.insert(depoAccount);
log.debug("New account {}, depoAccount {} was created.", accountId, depoAccountId); log.debug("New account {}, depoAccount {} was created.", accountId, depoAccountId);
{ {
@ -247,19 +244,15 @@ public class DepoAccountService extends QueueConsumer implements InitializingBea
request.setContinueSdf(true); request.setContinueSdf(true);
request.setAccountCreationResults(results); request.setAccountCreationResults(results);
request.setFromAccount(true); request.setFromAccount(true);
request.setTable(SdfTable.SDF_08); // по нему запрос получили request.setTable(SdfTable.SDF_08);
log.debug("Send message to kafka \"{}\": {}", Consts.STATEMENT_PROCESS, LogFormatter.toStringWrapper(request)); log.debug("Send message to kafka \"{}\": {}", Consts.STATEMENT_PROCESS, LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(Consts.STATEMENT_PROCESS, request); kafkaSender.sendRequestToQueue(Consts.STATEMENT_PROCESS, request);
} }
/**
* Формирование уведомления о добавлении счёта
*/
public Long sendNotificationAccountNewRequest(Account account) { public Long sendNotificationAccountNewRequest(Account account) {
String message = String.format("Добавлен новый счет %s", account.getAccount()); String message = String.format("Добавлен новый счет %s", account.getAccount());
final String destination = Consts.NOTIFICATION_NEW; final String destination = Consts.NOTIFICATION_NEW;
NotificationNewRequest request = new NotificationNewRequest(); NotificationNewRequest request = new NotificationNewRequest();
//request.setObjectId(account.getId());
request.setObjectType(ObjectType.rgst.getKey()); request.setObjectType(ObjectType.rgst.getKey());
request.setPriority(Priority.HIGH.getKey()); request.setPriority(Priority.HIGH.getKey());
request.setComment(message); request.setComment(message);

View file

@ -60,10 +60,6 @@ public class InformationAccountService extends QueueConsumer implements Initiali
private final Function<InformationAccountNewRequest, IValidator> infoAccountNewRequestValidator; private final Function<InformationAccountNewRequest, IValidator> infoAccountNewRequestValidator;
private final Imdg<InformationAccount> informationAccountImdg; private final Imdg<InformationAccount> informationAccountImdg;
private final Imdg<Account> accountImdg; private final Imdg<Account> accountImdg;
/**
* Кэш-счётчик сквозных номеров счетов.
* См. accountNextId()
*/
protected Map<String, AtomicLong> infoCounterByCurrency = new HashMap<>(); protected Map<String, AtomicLong> infoCounterByCurrency = new HashMap<>();
@Autowired @Autowired
@ -116,7 +112,7 @@ public class InformationAccountService extends QueueConsumer implements Initiali
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
InformationAccountNewRequest req = userRequest.getRequestPayload(); InformationAccountNewRequest req = userRequest.getRequestPayload();
String currency = req.getCurrency() == null ? CurrencyCode.RUB.getKey() : req.getCurrency(); //userRequest.getRequestPayload().getCurrency(); String currency = req.getCurrency() == null ? CurrencyCode.RUB.getKey() : req.getCurrency();
Long newId = informationAccountImdg.nextIDSequenceFor(); Long newId = informationAccountImdg.nextIDSequenceFor();
Long infoSequenceId = accountNextId(currency, 810L); Long infoSequenceId = accountNextId(currency, 810L);
@ -194,12 +190,10 @@ public class InformationAccountService extends QueueConsumer implements Initiali
log.debug("InformationAccountNewRequest received (system), request id={}", userRequest.getId()); log.debug("InformationAccountNewRequest received (system), request id={}", userRequest.getId());
RequestInfoUpdate requestInfoUpdate; RequestInfoUpdate requestInfoUpdate;
// RequestInfoUpdate requestInfoUpdate = validationHelper.validateTillFirstError(userRequest, infoAccountNewRequestValidator);
// if (requestInfoUpdate != null) return requestInfoUpdate;
final Long forCompanyId = userRequest.getRequestPayload().getCompanyId(); final Long forCompanyId = userRequest.getRequestPayload().getCompanyId();
ImdgPredicateBuilder pb = accountImdg.predicateBuilder(); ImdgPredicateBuilder pb = accountImdg.predicateBuilder();
{ // Проверка существования счёта {
Collection<Account> accountsAnlt = accountImdg.getCollectionObjectsByFieldValues(Map.of( Collection<Account> accountsAnlt = accountImdg.getCollectionObjectsByFieldValues(Map.of(
"companyId", forCompanyId, "companyId", forCompanyId,
"accountType", AccountType.Info.getKey() "accountType", AccountType.Info.getKey()
@ -216,7 +210,7 @@ public class InformationAccountService extends QueueConsumer implements Initiali
if (currency == null) if (currency == null)
currency = CurrencyCode.RUB.getKey(); currency = CurrencyCode.RUB.getKey();
Long newId = informationAccountImdg.nextIDSequenceFor(); Long newId = informationAccountImdg.nextIDSequenceFor();
Long infoSequenceId = accountNextId(currency, 810L); // требуется последовательность n+1 Long infoSequenceId = accountNextId(currency, 810L);
String accountValue = generateInfoAccount(810L, infoSequenceId); String accountValue = generateInfoAccount(810L, infoSequenceId);
log.trace("New info-account id={}, sequenceId={}, account={}", newId, infoSequenceId, accountValue); log.trace("New info-account id={}, sequenceId={}, account={}", newId, infoSequenceId, accountValue);
@ -283,17 +277,12 @@ public class InformationAccountService extends QueueConsumer implements Initiali
imdgTransaction.rollbackTransaction(); imdgTransaction.rollbackTransaction();
} }
} }
// send to kafka
sendNotificationToReport(informationAccount, account); sendNotificationToReport(informationAccount, account);
return null; return null;
} }
/**
* Формирование уведолмения о регистрации УК
*/
protected void sendNotificationToReport(InformationAccount informationAccount, Account account) { protected void sendNotificationToReport(InformationAccount informationAccount, Account account) {
NotificationRequest request = new NotificationRequest(); NotificationRequest request = new NotificationRequest();
request.setConsumerId(account.getCompanyId()); request.setConsumerId(account.getCompanyId());
@ -309,16 +298,10 @@ public class InformationAccountService extends QueueConsumer implements Initiali
return accountNextId(currency, 810L); return accountNextId(currency, 810L);
} }
/**
* Сквозной номер инфо-счетов
*
* @param
* @return infoCounter++
*/
public synchronized Long accountNextId(String currency, Long currencyCodeId) { public synchronized Long accountNextId(String currency, Long currencyCodeId) {
String idWithTrailingZero = String.format("%03d", currencyCodeId); String idWithTrailingZero = String.format("%03d", currencyCodeId);
if (currency == null) if (currency == null)
currency = CurrencyCode.RUB.getKey(); // default currency = CurrencyCode.RUB.getKey();
AtomicLong infoCounter = infoCounterByCurrency.get(currency); AtomicLong infoCounter = infoCounterByCurrency.get(currency);
if (infoCounter == null) synchronized (this) { if (infoCounter == null) synchronized (this) {
if (infoCounter == null) { if (infoCounter == null) {
@ -342,7 +325,7 @@ public class InformationAccountService extends QueueConsumer implements Initiali
Pattern accPattern = Pattern.compile("39911%s([0-9]{8})7000".formatted(idWithTrailingZero)); Pattern accPattern = Pattern.compile("39911%s([0-9]{8})7000".formatted(idWithTrailingZero));
int maxN = 1; int maxN = 1;
int parsedCount = 0; int parsedCount = 0;
String lastAccount = null; // for debug String lastAccount = null;
for (Account acc : allInfoAcc) { for (Account acc : allInfoAcc) {
try { try {
String number = acc.getAccount(); String number = acc.getAccount();

View file

@ -27,12 +27,12 @@ import ru.spcex.platform.imdg.api.ImdgTransaction;
@Service @Service
public class SDFProcessService { public class SDFProcessService {
public static final String SDF_STATUS_OK = "OK"; // (Операция выполнена успешно) - если account обновлена по sDf52; public static final String SDF_STATUS_OK = "OK";
public static final String SDF_STATUS_ERROR_REPEAT = "1"; // (Ошибка. Попытка повторно исполнить операцию) public static final String SDF_STATUS_ERROR_REPEAT = "1";
public static final String SDF_STATUS_ERROR_COMPANY_NOT_FOUND = "2"; // (Ошибка. Участник не найден) - если получена ошибка (5013) "Компания %s не найдена" (т.е. account НЕ обновлена по sDf52); public static final String SDF_STATUS_ERROR_COMPANY_NOT_FOUND = "2";
public static final String SDF_STATUS_ERROR_LIMIT_SUMM = "3"; // (Ошибка. Сумма списания превышает сумму средств на торговом счете участника в ТС) public static final String SDF_STATUS_ERROR_LIMIT_SUMM = "3";
public static final String SDF_STATUS_ERROR_NO_TRADE = "4"; // (Ошибка. Торги не идут) public static final String SDF_STATUS_ERROR_NO_TRADE = "4";
public static final String SDF_STATUS_ERROR = "9"; // (Другие ошибки, выявленные в КС) - если получены другие ошибки (т.е. account НЕ обновлена по sDf52). public static final String SDF_STATUS_ERROR = "9";
protected static final Long SDF52_STATUS_0Blocked = 0L; protected static final Long SDF52_STATUS_0Blocked = 0L;
protected static final Long SDF52_STATUS_1Unblocked = 1L; protected static final Long SDF52_STATUS_1Unblocked = 1L;
@ -76,7 +76,7 @@ public class SDFProcessService {
boolean txOk = false; boolean txOk = false;
imdgTransaction.beginTransaction(); imdgTransaction.beginTransaction();
HashSet<String> fileNames = new HashSet<>(); HashSet<String> fileNames = new HashSet<>();
try { // 2. обновление данных, в транзакции try {
Imdg<SDf53> sdf53Imdg = imdgTransaction.getImdg(IMDGDistributedNames.Map_SDf53, SDf53.class); Imdg<SDf53> sdf53Imdg = imdgTransaction.getImdg(IMDGDistributedNames.Map_SDf53, SDf53.class);
Instant now = Instant.now(); Instant now = Instant.now();
@ -116,9 +116,9 @@ public class SDFProcessService {
newSdf.setResult(result); newSdf.setResult(result);
newSdf.setGenerationTime(now); newSdf.setGenerationTime(now);
newSdf.setGenerationId(sdf52.getGenerationId()); newSdf.setGenerationId(sdf52.getGenerationId());
if (!Objects.equals(newGenerationId, newSdf.getGenerationId())) { // never if (!Objects.equals(newGenerationId, newSdf.getGenerationId())) {
log.warn("Different GenerationId={} for sdf53[{}] and GenerationId={} for group of sdf52", log.warn("Different GenerationId={} for sdf53[{}] and GenerationId={} for group of sdf52",
newSdf.getGenerationId(), newSdf.getId(), newGenerationId newSdf.getGenerationId(), newSdf.getId(), newGenerationId
); );
} }
newSdf.setInSDfId(sdf52.getId()); newSdf.setInSDfId(sdf52.getId());
@ -126,10 +126,6 @@ public class SDFProcessService {
} }
/**
* @param status sdf.getStatus()
* @return AccountStatus или null
*/
public AccountStatus parseSdf52Status(Long status) { public AccountStatus parseSdf52Status(Long status) {
if (SDF52_STATUS_1Unblocked.equals(status) || SDF52_STATUS_3Open.equals(status)) { if (SDF52_STATUS_1Unblocked.equals(status) || SDF52_STATUS_3Open.equals(status)) {
return AccountStatus.ACTIVE; return AccountStatus.ACTIVE;
@ -144,9 +140,9 @@ public class SDFProcessService {
void messageStatementToExport53(Long groupId, String fileName) { void messageStatementToExport53(Long groupId, String fileName) {
final String destination = Consts.EXPORT_PROCESS; // dbf-exporter final String destination = Consts.EXPORT_PROCESS;
ExportToFileRequest request = new ExportToFileRequest(); ExportToFileRequest request = new ExportToFileRequest();
request.setNameOfTable("DF-53"); // SdfTable.SDF_53 request.setNameOfTable("DF-53");
request.setSdfGroupId(groupId); request.setSdfGroupId(groupId);
request.setFileName(fileName); request.setFileName(fileName);
Long msgId = kafkaSender.sendRequestToQueue(destination, request); Long msgId = kafkaSender.sendRequestToQueue(destination, request);

View file

@ -63,7 +63,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
private final Function<TradingClearingRegistryListUpdateRequest, IValidator> tradingClearingRegistryListUpdateRequestValidator; private final Function<TradingClearingRegistryListUpdateRequest, IValidator> tradingClearingRegistryListUpdateRequestValidator;
private final RequestHelper requestHelper; private final RequestHelper requestHelper;
private final Function<TradingClearingRegistryListNewRequest, IValidator> tradingClearingRegistryListNewRequestValidator; private final Function<TradingClearingRegistryListNewRequest, IValidator> tradingClearingRegistryListNewRequestValidator;
// private final Function<CommonIdRequest, IValidator> tradingClearingRegistryListBlockRequestValidator;
private final IMessageResolver messageResolver; private final IMessageResolver messageResolver;
private final Producer<String, Object> kafkaProducer; private final Producer<String, Object> kafkaProducer;
@ -79,10 +78,10 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
IMessageResolver messageResolver, IMessageResolver messageResolver,
RequestHelper requestHelper, RequestHelper requestHelper,
@Qualifier("tradingClearingRegistryListNewRequestValidator") @Qualifier("tradingClearingRegistryListNewRequestValidator")
Function<TradingClearingRegistryListNewRequest, IValidator> tradingClearingRegistryListNewRequestValidator, Function<TradingClearingRegistryListNewRequest, IValidator> tradingClearingRegistryListNewRequestValidator,
@Qualifier("tradingClearingRegistryListUpdateRequestValidator") @Qualifier("tradingClearingRegistryListUpdateRequestValidator")
Function<TradingClearingRegistryListUpdateRequest, IValidator> tradingClearingRegistryListUpdateRequestValidator Function<TradingClearingRegistryListUpdateRequest, IValidator> tradingClearingRegistryListUpdateRequestValidator
) { ) {
super(kafkaQueue, kafkaProducer); super(kafkaQueue, kafkaProducer);
this.kafkaProducer = kafkaProducer; this.kafkaProducer = kafkaProducer;
this.kafkaSender = kafkaSender; this.kafkaSender = kafkaSender;
@ -100,7 +99,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
this.relationImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Relation, Relation.class); this.relationImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Relation, Relation.class);
this.tradingClearingRegistryListNewRequestValidator = tradingClearingRegistryListNewRequestValidator; this.tradingClearingRegistryListNewRequestValidator = tradingClearingRegistryListNewRequestValidator;
this.tradingClearingRegistryListUpdateRequestValidator = tradingClearingRegistryListUpdateRequestValidator; this.tradingClearingRegistryListUpdateRequestValidator = tradingClearingRegistryListUpdateRequestValidator;
// this.tradingClearingRegistryListBlockRequestValidator = tradingClearingRegistryListBlockRequestValidator;
this.messageResolver = messageResolver; this.messageResolver = messageResolver;
this.clientCodeService = clientCodeService; this.clientCodeService = clientCodeService;
} }
@ -109,11 +107,11 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
imdgProvider.waitAvailable(); imdgProvider.waitAvailable();
callback(TradingClearingRegistryListNewRequest.class) callback(TradingClearingRegistryListNewRequest.class)
.setFunction(this::tradingClearingRegistryListNew) .setFunction(this::tradingClearingRegistryListNew)
.forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, callbacks::put); .forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, callbacks::put);
callback(TradingClearingRegistryListUpdateRequest.class) callback(TradingClearingRegistryListUpdateRequest.class)
.setFunction(this::tradingClearingRegistryListUpdate) .setFunction(this::tradingClearingRegistryListUpdate)
.forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, callbacks::put); .forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, callbacks::put);
init(); init();
} }
@ -123,7 +121,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
@Deprecated @Deprecated
protected RequestInfoUpdate tradingClearingRegistryListNew0(BaseRequest<TradingClearingRegistryListNewRequest> userRequest, boolean innerCall) { protected RequestInfoUpdate tradingClearingRegistryListNew0(BaseRequest<TradingClearingRegistryListNewRequest> userRequest, boolean innerCall) {
// fixme объединить с путом а то лист может быть пустой. и чистить...
log.debug("TradingClearingRegistryListNewRequest received"); log.debug("TradingClearingRegistryListNewRequest received");
RequestInfoUpdate requestInfoUpdate = userRoleVerification.validateRoleAndGetResult(userRequest); RequestInfoUpdate requestInfoUpdate = userRoleVerification.validateRoleAndGetResult(userRequest);
if (requestInfoUpdate != null) { if (requestInfoUpdate != null) {
@ -143,8 +140,8 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
TradingClearingRegistryListNewRequest req = userRequest.getRequestPayload(); TradingClearingRegistryListNewRequest req = userRequest.getRequestPayload();
Instant now = Instant.now(); Instant now = Instant.now();
List<Long> newIds=new ArrayList<>(); List<Long> newIds = new ArrayList<>();
for (Long currAccId: req.getCurrencyAccountList()) { for (Long currAccId : req.getCurrencyAccountList()) {
Long id = tradingClearingRegistryListImdg.nextIDSequenceFor(); Long id = tradingClearingRegistryListImdg.nextIDSequenceFor();
TradingClearingRegistryList tradingClearingRegistryList = new TradingClearingRegistryList(); TradingClearingRegistryList tradingClearingRegistryList = new TradingClearingRegistryList();
tradingClearingRegistryList.setId(id); tradingClearingRegistryList.setId(id);
@ -167,7 +164,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
log.info("New TCRList.id={} has created.", newIds); log.info("New TCRList.id={} has created.", newIds);
if (!innerCall) { if (!innerCall) {
// Для каждого счета из списка (currencyAccountList) должна быть создана отдельная запись объекте clientCode с данным счетом для данного клиента, т.е. у одного клиента может быть несколько валютных счетов.
try { try {
ClientCodeNewRequest cCodeReq = new ClientCodeNewRequest(); ClientCodeNewRequest cCodeReq = new ClientCodeNewRequest();
cCodeReq.setTradingClearingRegistryId(req.getTradingClearingRegistryId()); cCodeReq.setTradingClearingRegistryId(req.getTradingClearingRegistryId());
@ -176,15 +172,14 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
cCodeReq.setCompanyId(tcr.getCompanyId()); cCodeReq.setCompanyId(tcr.getCompanyId());
cCodeReq.setCurrencyAccountList(req.getCurrencyAccountList()); cCodeReq.setCurrencyAccountList(req.getCurrencyAccountList());
cCodeReq.setStatus(req.getStatus()); cCodeReq.setStatus(req.getStatus());
//todo cCodeReq.setCode();
BaseRequest<ClientCodeNewRequest> request2 = new BaseRequest<>(); BaseRequest<ClientCodeNewRequest> request2 = new BaseRequest<>();
request2.setRequestPayload(cCodeReq); request2.setRequestPayload(cCodeReq);
requestInfoUpdate = clientCodeService.clientCodeNew0(request2, true); requestInfoUpdate = clientCodeService.clientCodeNew0(request2, true);
if (requestInfoUpdate != null) return requestInfoUpdate; if (requestInfoUpdate != null) return requestInfoUpdate;
} catch (Exception e) { } catch (Exception e) {
log.error("Can not wait creation of tradingClearingRegistryList. request id={}; {}", log.error("Can not wait creation of tradingClearingRegistryList. request id={}; {}",
userRequest.getId(), userRequest.getId(),
ExceptionUtils.getStackTrace(e)); ExceptionUtils.getStackTrace(e));
return requestHelper.makeErrorResponse(userRequest, AccountError.GeneralError, "Can not create TCR: " + e.getMessage()); return requestHelper.makeErrorResponse(userRequest, AccountError.GeneralError, "Can not create TCR: " + e.getMessage());
} }
@ -233,27 +228,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
log.info("New TCRList.id={} has created.", id); log.info("New TCRList.id={} has created.", id);
if (!innerCall) { if (!innerCall) {
// Для каждого счета из списка (currencyAccountList) должна быть создана отдельная запись объекте clientCode с данным счетом для данного клиента, т.е. у одного клиента может быть несколько валютных счетов.
// try {
// TradingClearingRegistry tcr = tradingClearingRegistryImdg.getSingleObjectByID(req.getTradingClearingRegistryId());
// ClientCodeNewRequest cCodeReq = new ClientCodeNewRequest();
// cCodeReq.setTradingClearingRegistryId(req.getTradingClearingRegistryId());
// cCodeReq.setDepoAccountId(tcr.getDepoAccountId());
// cCodeReq.setMoneyAccountId(tcr.getMoneyAccountId());
// cCodeReq.setCompanyId(tcr.getCompanyId());
// cCodeReq.setCurrencyAccountList(Arrays.asList(req.getAccountId())); // todo rewrite API
// cCodeReq.setStatus(tradingClearingRegistryList.getStatus());
// //todo cCodeReq.setCode();
// BaseRequest<ClientCodeNewRequest> request2 = new BaseRequest<>();
// request2.setRequestPayload(cCodeReq);
// requestInfoUpdate = clientCodeService.clientCodeNew0(request2, true);
// if (requestInfoUpdate != null) return requestInfoUpdate;
// } catch (Exception e) {
// log.error("Can not wait creation of tradingClearingRegistryList. request id={}; {}",
// userRequest.getId(),
// ExceptionUtils.getStackTrace(e));
// return requestHelper.makeErrorResponse(userRequest, AccountError.GeneralError, "Can not create TCR: " + e.getMessage());
// }
} }
@ -289,8 +263,6 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
log.debug("Nothing to update TCRList.id={}.", tradingClearingRegistryList.getId()); log.debug("Nothing to update TCRList.id={}.", tradingClearingRegistryList.getId());
} }
//todo нужно ли слать уведомления sendNotificationToClearingSvc?
log.debug("successfully processed, id {}", tradingClearingRegistryList.getId()); log.debug("successfully processed, id {}", tradingClearingRegistryList.getId());
return null; return null;
} }
@ -298,12 +270,10 @@ public class TradingClearingRegistryListService extends QueueConsumer implements
@Deprecated @Deprecated
protected void sendNotificationToClearingSvc(List<Long> tradingClearingRegistries, TradingClearingRegistry tcr) { protected void sendNotificationToClearingSvc(List<Long> tradingClearingRegistries, TradingClearingRegistry tcr) {
for (Long tradingClearingRegistryId:tradingClearingRegistries) for (Long tradingClearingRegistryId : tradingClearingRegistries)
sendNotificationToClearingSvc(tradingClearingRegistryId, tcr); sendNotificationToClearingSvc(tradingClearingRegistryId, tcr);
} }
/**
* clearing-service сообщение на открытие клиринговых регистров;
*/
protected void sendNotificationToClearingSvc(Long tradingClearingRegistryId, TradingClearingRegistry tcr) { protected void sendNotificationToClearingSvc(Long tradingClearingRegistryId, TradingClearingRegistry tcr) {
CreateRegistryRequest request = new CreateRegistryRequest(); CreateRegistryRequest request = new CreateRegistryRequest();
request.setTcrListId(tradingClearingRegistryId); request.setTcrListId(tradingClearingRegistryId);

View file

@ -124,7 +124,7 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
this.clientCodeImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class); this.clientCodeImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class);
this.companySymbolsImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_CompanySymbols, CompanySymbols.class); this.companySymbolsImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_CompanySymbols, CompanySymbols.class);
this.tradingClearingRegistryNewRequestValidator = tradingClearingRegistryNewRequestValidator; this.tradingClearingRegistryNewRequestValidator = tradingClearingRegistryNewRequestValidator;
this.tradingClearingRegistryAutoNewRequestValidator = tradingClearingRegistryNewRequestValidator; // без relation. this.tradingClearingRegistryAutoNewRequestValidator = tradingClearingRegistryNewRequestValidator;
this.tradingClearingRegistryUpdateRequestValidator = tradingClearingRegistryUpdateRequestValidator; this.tradingClearingRegistryUpdateRequestValidator = tradingClearingRegistryUpdateRequestValidator;
this.tradingClearingRegistryBlockRequestValidator = tradingClearingRegistryBlockRequestValidator; this.tradingClearingRegistryBlockRequestValidator = tradingClearingRegistryBlockRequestValidator;
this.messageResolver = messageResolver; this.messageResolver = messageResolver;
@ -133,7 +133,7 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
imdgProvider.waitAvailable(); imdgProvider.waitAvailable();
callback(TradingClearingRegistryNewRequest.class) // todo deprecated - unused. callback(TradingClearingRegistryNewRequest.class)
.setFunction(this::tradingClearingRegistryAutoNew) .setFunction(this::tradingClearingRegistryAutoNew)
.forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, callbacks::put); .forDestination(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, callbacks::put);
callback(TradingClearingRegistryNewRequest.class) callback(TradingClearingRegistryNewRequest.class)
@ -174,18 +174,13 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
Account depoAccountMain = req.getDepoAccountId() != null ? accountImdg.getSingleObjectByID(req.getDepoAccountId()) : null; Account depoAccountMain = req.getDepoAccountId() != null ? accountImdg.getSingleObjectByID(req.getDepoAccountId()) : null;
DepoAccount depoAccount = depoAccountMain != null ? depoAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", req.getDepoAccountId())) : null; DepoAccount depoAccount = depoAccountMain != null ? depoAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", req.getDepoAccountId())) : null;
// InformationAccount infoAccount = null;
ClearingAccount clearingAccount = null; ClearingAccount clearingAccount = null;
Account accountMain = null; Account accountMain = null;
if (req.getMoneyAccountId() != null) { if (req.getMoneyAccountId() != null) {
clearingAccount = clearingAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", req.getMoneyAccountId())); clearingAccount = clearingAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", req.getMoneyAccountId()));
// if (clearingAccount == null) infoAccount = informationAccountImdg.getSingleObjectByFieldValues(Map.of("accountId", req.getMoneyAccountId())); Long accountId = req.getMoneyAccountId();
Long accountId = req.getMoneyAccountId(); //clearingAccount != null ? clearingAccount.getAccountId() : infoAccount.getAccountId();
accountMain = accountImdg.getSingleObjectByID(accountId); accountMain = accountImdg.getSingleObjectByID(accountId);
} }
// кроссвалидация
if (req.getMoneyAccountId() == null && (req.getMoneyAccountId() == null || req.getDepoAccountId() == null)) { if (req.getMoneyAccountId() == null && (req.getMoneyAccountId() == null || req.getDepoAccountId() == null)) {
TradingClearingRegistry registryByCompany = tradingClearingRegistryImdg.getFirstObjectByFieldValues(Map.of("companyId", req.getCompanyId())); TradingClearingRegistry registryByCompany = tradingClearingRegistryImdg.getFirstObjectByFieldValues(Map.of("companyId", req.getCompanyId()));
if (registryByCompany == null) { if (registryByCompany == null) {
@ -225,7 +220,7 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
} }
if (accountId != null) { if (accountId != null) {
accountMain = accountImdg.getSingleObjectByID(accountId); accountMain = accountImdg.getSingleObjectByID(accountId);
if (accountMain == null) { // never, только с инконсистентными данными if (accountMain == null) {
log.warn("Account {} not exist.", accountId); log.warn("Account {} not exist.", accountId);
} else { } else {
tradingClearingRegistry.setMoneyAccountId(accountId); tradingClearingRegistry.setMoneyAccountId(accountId);
@ -283,7 +278,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType); tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType);
TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C; TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C;
//http://jira.mfd.msk:8088/browse/CLS-631#comment-60200
tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey()); tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey());
Company company = companyImdg.getSingleObjectByID(req.getCompanyId()); Company company = companyImdg.getSingleObjectByID(req.getCompanyId());
@ -298,9 +292,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
tradingClearingRegistryImdg.insert(tradingClearingRegistry); tradingClearingRegistryImdg.insert(tradingClearingRegistry);
log.debug("New TCR.id={} was created", tradingClearingRegistry.getId()); log.debug("New TCR.id={} was created", tradingClearingRegistry.getId());
// sendNotificationToCompanySvc(tradingClearingRegistry); при автосоздании ТКР в company-service не отправлять.
// sendNotificationToClearingSvc(tradingClearingRegistry);
sendNotificationToReportSvc(tradingClearingRegistry); sendNotificationToReportSvc(tradingClearingRegistry);
sendNotificationToClearingSvc(tradingClearingRegistry); sendNotificationToClearingSvc(tradingClearingRegistry);
@ -321,7 +312,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
} }
TradingClearingRegistryNewRequest req = userRequest.getRequestPayload(); TradingClearingRegistryNewRequest req = userRequest.getRequestPayload();
// Дополнительная проверка
if (req.getMoneyAccountId() == null && (req.getMoneyAccountId() == null || req.getDepoAccountId() == null)) { if (req.getMoneyAccountId() == null && (req.getMoneyAccountId() == null || req.getDepoAccountId() == null)) {
TradingClearingRegistry registryByCompany = tradingClearingRegistryImdg.getFirstObjectByFieldValues(Map.of("companyId", req.getCompanyId())); TradingClearingRegistry registryByCompany = tradingClearingRegistryImdg.getFirstObjectByFieldValues(Map.of("companyId", req.getCompanyId()));
if (registryByCompany == null) { if (registryByCompany == null) {
@ -359,8 +349,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
else tradingRegistryType = TradingClearingRegistryType.Owner_A.getKey(); else tradingRegistryType = TradingClearingRegistryType.Owner_A.getKey();
} }
tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType); tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType);
//http://jira.mfd.msk:8088/browse/CLS-631#comment-60200
TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C; TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C;
tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey()); tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey());
@ -435,15 +423,14 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
if (code.length() > 4) if (code.length() > 4)
code = code.substring(code.length() - 4); code = code.substring(code.length() - 4);
code = "%4s".formatted(code).replace(' ', '0'); code = "%4s".formatted(code).replace(' ', '0');
// code += registryPurpose.getKey(); // C / M / ... code += "C";
code += "C";//пока ставим всегда С, возможно придется откатить String trType = tradingRegistryType + "T";
String trType = tradingRegistryType + "T"; // 2 символа
code += trType; code += trType;
String sId = "%5s".formatted(id).replace(' ', '0'); String sId = "%5s".formatted(id).replace(' ', '0');
if (sId.length() > 5) if (sId.length() > 5)
sId = sId.substring(sId.length() - 5); sId = sId.substring(sId.length() - 5);
code += sId; code += sId;
return code; // 12 символов return code;
} }
public RequestInfoUpdate tradingClearingRegistryUpdate(BaseRequest<TradingClearingRegistryUpdateRequest> userRequest) { public RequestInfoUpdate tradingClearingRegistryUpdate(BaseRequest<TradingClearingRegistryUpdateRequest> userRequest) {
@ -456,16 +443,13 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
TradingClearingRegistryUpdateRequest req = userRequest.getRequestPayload(); TradingClearingRegistryUpdateRequest req = userRequest.getRequestPayload();
TradingClearingRegistry tradingClearingRegistry = tradingClearingRegistryImdg.getSingleObjectByID(req.getId()); TradingClearingRegistry tradingClearingRegistry = tradingClearingRegistryImdg.getSingleObjectByID(req.getId());
// кроссвалидация - нельзя менять эти поля:
if (req.getMoneyAccountId() != null && !req.getMoneyAccountId().equals(tradingClearingRegistry.getMoneyAccountId())) { if (req.getMoneyAccountId() != null && !req.getMoneyAccountId().equals(tradingClearingRegistry.getMoneyAccountId())) {
return requestHelper.makeErrorResponse(userRequest, AccountError.WrongFieldValue, "MoneyAccountId", req.getMoneyAccountId()); return requestHelper.makeErrorResponse(userRequest, AccountError.WrongFieldValue, "MoneyAccountId", req.getMoneyAccountId());
} }
if (tradingClearingRegistry.getDepoAccountId() != null && // но можно с null заменить if (tradingClearingRegistry.getDepoAccountId() != null &&
req.getDepoAccountId() != null && !req.getDepoAccountId().equals(tradingClearingRegistry.getDepoAccountId())) { req.getDepoAccountId() != null && !req.getDepoAccountId().equals(tradingClearingRegistry.getDepoAccountId())) {
return requestHelper.makeErrorResponse(userRequest, AccountError.WrongFieldValue, "DepoAccountId", req.getDepoAccountId()); return requestHelper.makeErrorResponse(userRequest, AccountError.WrongFieldValue, "DepoAccountId", req.getDepoAccountId());
} }
// tradingClearingRegistry.setMoneyAccountId(req.getMoneyAccountId());
if (req.getStatus() != null && !Objects.equals(req.getStatus(), tradingClearingRegistry.getStatus()) if (req.getStatus() != null && !Objects.equals(req.getStatus(), tradingClearingRegistry.getStatus())
|| req.getDepoAccountId() != null && !req.getDepoAccountId().equals(tradingClearingRegistry.getDepoAccountId()) || req.getDepoAccountId() != null && !req.getDepoAccountId().equals(tradingClearingRegistry.getDepoAccountId())
@ -630,9 +614,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
return Optional.empty(); return Optional.empty();
} }
/**
* company-service сообщение об успешном добавлении ТКР клиента с параметром tradingClearingRegistry.code
*/
protected void sendNotificationToCompanySvc(TradingClearingRegistry tradingClearingRegistry) { protected void sendNotificationToCompanySvc(TradingClearingRegistry tradingClearingRegistry) {
ClientCodeNewRequest request = new ClientCodeNewRequest(); ClientCodeNewRequest request = new ClientCodeNewRequest();
request.setTradingClearingRegistryId(tradingClearingRegistry.getId()); request.setTradingClearingRegistryId(tradingClearingRegistry.getId());
@ -644,9 +625,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
kafkaSender.sendRequestToQueue(Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, request); kafkaSender.sendRequestToQueue(Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, request);
} }
/**
* clearing-service сообщение на открытие клиринговых регистров;
*/
protected void sendNotificationToClearingSvc(TradingClearingRegistry tradingClearingRegistry) { protected void sendNotificationToClearingSvc(TradingClearingRegistry tradingClearingRegistry) {
CreateRegistryRequest request = new CreateRegistryRequest(); CreateRegistryRequest request = new CreateRegistryRequest();
request.setCompanyId(tradingClearingRegistry.getCompanyId()); request.setCompanyId(tradingClearingRegistry.getCompanyId());
@ -655,9 +633,6 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
kafkaSender.sendRequestToQueue(Consts.REGISTRY_NEW, request); kafkaSender.sendRequestToQueue(Consts.REGISTRY_NEW, request);
} }
/**
* report-service сообщение на формирование уведомления о создании нового ТКР
*/
protected void sendNotificationToReportSvc(TradingClearingRegistry tradingClearingRegistry) { protected void sendNotificationToReportSvc(TradingClearingRegistry tradingClearingRegistry) {
NotificationRequest request = new NotificationRequest(); NotificationRequest request = new NotificationRequest();
request.setConsumerId(tradingClearingRegistry.getCompanyId()); request.setConsumerId(tradingClearingRegistry.getCompanyId());

View file

@ -36,9 +36,6 @@ public class ClientCodeFacade implements IClearingFacade {
this.tradingClearingRegistryListFacade = tradingClearingRegistryListFacade; this.tradingClearingRegistryListFacade = tradingClearingRegistryListFacade;
} }
/**
* Создает clientCode, TCR и опционально TCRList, если указаны валюты.
*/
public void createClientCode(ClientCodeNewRequest request, IValidator validator) { public void createClientCode(ClientCodeNewRequest request, IValidator validator) {
log.trace("Start process creating new client code"); log.trace("Start process creating new client code");
TradingClearingRegistry tradingClearingRegistry; TradingClearingRegistry tradingClearingRegistry;
@ -75,48 +72,9 @@ public class ClientCodeFacade implements IClearingFacade {
} }
} }
// public void createClientCode(ClientCodeBusiness businessRequest) {
// log.trace("Start process creating new client code");
// TradingClearingRegistry tradingClearingRegistry;
// {
// log.debug("Trading Clearing Registry is not exist, creating...");
// TradingClearingRegistryBusiness creationTcrRequest = new TradingClearingRegistryBusiness();
// creationTcrRequest.setCompanyId(request.getCompanyId());
// creationTcrRequest.setMoneyAccountId(request.getMoneyAccountId());
// creationTcrRequest.setDepoAccountId(request.getDepoAccountId());
// creationTcrRequest.setTradingClearingRegistryType(TradingClearingRegistryType.Client_B.getKey());
// tradingClearingRegistry = tradingClearingRegistryFacade.createTradingClearingRegistry(creationTcrRequest, null);
// }
// {
// if (request.getCurrencyAccountList() != null && !request.getCurrencyAccountList().isEmpty()) {
// TradingClearingRegistryListNewRequest tcrListNew = new TradingClearingRegistryListNewRequest();
// tcrListNew.setTradingClearingRegistryId(tradingClearingRegistry.getId());
// tcrListNew.setCurrencyAccountList(request.getCurrencyAccountList());
// List<Long> tkrListIds = tradingClearingRegistryListFacade.createTradingClearingRegistryList(tcrListNew, null);
// }
// }
//
// {
// ClientCode clientCode = new ClientCode();
// clientCode.setCreated(Instant.now());
// clientCode.setUpdated(clientCode.getCreated());
//
// clientCode.setCompanyId(request.getCompanyId());
// clientCode.setCode(request.getCode());
// clientCode.setMoneyAccountId(request.getMoneyAccountId());
// clientCode.setDepoAccountId(request.getDepoAccountId());
// clientCode.setStatus(request.getStatus());
// clientCodeImdg.insert(clientCode);
// log.debug("successfully processed, new clientCode id {}", clientCode.getId());
// }
// }
public void lock() { public void lock() {
// tradingClearingRegistryFacade.lock()
// tradingClearingRegistryListFacade.lock()
} }
public void unlock() { public void unlock() {
// tradingClearingRegistryFacade.lock()
// tradingClearingRegistryListFacade.lock()
} }
} }

View file

@ -79,8 +79,6 @@ public class TradingClearingRegistryFacade {
else tradingRegistryType = TradingClearingRegistryType.Owner_A.getKey(); else tradingRegistryType = TradingClearingRegistryType.Owner_A.getKey();
} }
tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType); tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType);
//http://jira.mfd.msk:8088/browse/CLS-631#comment-60200
TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C; TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C;
tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey()); tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey());
@ -113,42 +111,15 @@ public class TradingClearingRegistryFacade {
businessRequest.getDepoAccount().ifPresent(depoAccount -> businessRequest.getDepoAccount().ifPresent(depoAccount ->
tradingClearingRegistry.setDepoAccountId(depoAccount.getId())); tradingClearingRegistry.setDepoAccountId(depoAccount.getId()));
; ;
if (businessRequest.getTradingClearingRegistryType().isEmpty()){ if (businessRequest.getTradingClearingRegistryType().isEmpty()) {
if (businessRequest.getDepoAccount().isPresent()){ if (businessRequest.getDepoAccount().isPresent()) {
} }
} }
// ClearingAccount clearingAccount = request.getMoneyAccountId() != null ?
// clearingAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", request.getMoneyAccountId())) : null;
//
// if (request.getStatus() == null) {
// tradingClearingRegistry.setStatus(ServiceStatus.Active.getKey());
// log.trace("TCR status in request not set. Use default: {}", tradingClearingRegistry.getStatus());
// } else {
// tradingClearingRegistry.setStatus(request.getStatus());
// log.trace("TCR status in request set: {}", tradingClearingRegistry.getStatus());
// }
//
// String tradingRegistryType;
// if (request.getTradingClearingRegistryType() != null) {
// tradingRegistryType = request.getTradingClearingRegistryType();
// } else if (depoAccount != null) {
// tradingRegistryType = depoAccount.getDepoAccountType();
// } else {
// if (clearingAccount != null) tradingRegistryType = clearingAccount.getClearingAccountType();
// else tradingRegistryType = TradingClearingRegistryType.Owner_A.getKey();
// }
// tradingClearingRegistry.setTradingClearingRegistryType(tradingRegistryType);
//http://jira.mfd.msk:8088/browse/CLS-631#comment-60200
TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C; TradingClearingRegistryPurpose registryPurpose = TradingClearingRegistryPurpose.C;
tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey()); tradingClearingRegistry.setTradingClearingRegistryPurpose(registryPurpose.getKey());
Company company = businessRequest.getCompany(); Company company = businessRequest.getCompany();
// Long seqId = companySequenceNextId(company.getId(), registryPurpose, tradingRegistryType);
// String code = makeCode(company.getClearingCode(), registryPurpose, tradingRegistryType, seqId);
// log.debug("For new TCR.id={} of companyId={} next sequence={}; code={}", id, company.getId(), seqId, code);
// tradingClearingRegistry.setCode(code);
Instant now = Instant.now(); Instant now = Instant.now();
tradingClearingRegistry.setCreated(now); tradingClearingRegistry.setCreated(now);
@ -217,15 +188,14 @@ public class TradingClearingRegistryFacade {
if (code.length() > 4) if (code.length() > 4)
code = code.substring(code.length() - 4); code = code.substring(code.length() - 4);
code = "%4s".formatted(code).replace(' ', '0'); code = "%4s".formatted(code).replace(' ', '0');
// code += registryPurpose.getKey(); // C / M / ... code += "C";
code += "C";//пока ставим всегда С, возможно придется откатить String trType = tradingRegistryType + "T";
String trType = tradingRegistryType + "T"; // 2 символа
code += trType; code += trType;
String sId = "%5s".formatted(id).replace(' ', '0'); String sId = "%5s".formatted(id).replace(' ', '0');
if (sId.length() > 5) if (sId.length() > 5)
sId = sId.substring(sId.length() - 5); sId = sId.substring(sId.length() - 5);
code += sId; code += sId;
return code; // 12 символов return code;
} }
private void sendNotificationToClearingSvc(TradingClearingRegistry tradingClearingRegistry) { private void sendNotificationToClearingSvc(TradingClearingRegistry tradingClearingRegistry) {
@ -236,9 +206,6 @@ public class TradingClearingRegistryFacade {
kafkaSender.sendRequestToQueue(Consts.REGISTRY_NEW, request); kafkaSender.sendRequestToQueue(Consts.REGISTRY_NEW, request);
} }
/**
* report-service сообщение на формирование уведомления о создании нового ТКР
*/
private void sendNotificationToReportSvc(TradingClearingRegistry tradingClearingRegistry) { private void sendNotificationToReportSvc(TradingClearingRegistry tradingClearingRegistry) {
NotificationRequest request = new NotificationRequest(); NotificationRequest request = new NotificationRequest();
request.setConsumerId(tradingClearingRegistry.getCompanyId()); request.setConsumerId(tradingClearingRegistry.getCompanyId());

View file

@ -67,12 +67,9 @@ public class ClientCodeMessageListener extends QueueConsumer implements Initiali
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
imdgProvider.waitAvailable(); imdgProvider.waitAvailable();
//from backend-api requests
callback(ClientCodeNewRequest.class) callback(ClientCodeNewRequest.class)
.setFunction(this::clientCodeNewFromBackend) .setFunction(this::clientCodeNewFromBackend)
.forDestination(Consts.DESTINATION_CLIENT_CODE_NEW, callbacks::put); .forDestination(Consts.DESTINATION_CLIENT_CODE_NEW, callbacks::put);
//from gateway requests
callback(TkrAccountsGatewayRequest.class) callback(TkrAccountsGatewayRequest.class)
.setFunction(this::clientCodeNewFromGateway) .setFunction(this::clientCodeNewFromGateway)
.forDestination(Consts.DESTINATION_CLIENT_CODE_NEW_FROM_GATEWAY, callbacks::put); .forDestination(Consts.DESTINATION_CLIENT_CODE_NEW_FROM_GATEWAY, callbacks::put);
@ -84,7 +81,6 @@ public class ClientCodeMessageListener extends QueueConsumer implements Initiali
private RequestInfoUpdate clientCodeNewFromGateway(BaseRequest<TkrAccountsGatewayRequest> tkrRequest) { private RequestInfoUpdate clientCodeNewFromGateway(BaseRequest<TkrAccountsGatewayRequest> tkrRequest) {
clientCodeFacade.lock(); clientCodeFacade.lock();
//валидация запроса
TkrAccountsGatewayRequest gatewayRequest = tkrRequest.getRequestPayload(); TkrAccountsGatewayRequest gatewayRequest = tkrRequest.getRequestPayload();
SendTkrRequest sendTkrRequest = new SendTkrRequest(); SendTkrRequest sendTkrRequest = new SendTkrRequest();
@ -115,8 +111,6 @@ public class ClientCodeMessageListener extends QueueConsumer implements Initiali
kafkaSender.sendRequestToQueue(Consts.ACCOUNTS_TO_GATEWAY, sendTkrRequest); kafkaSender.sendRequestToQueue(Consts.ACCOUNTS_TO_GATEWAY, sendTkrRequest);
return null; return null;
} }
//unwrap запроса
for (Map.Entry<TkrAccount, ValidationResult> entry : accountsAfterValidation.entrySet()) { for (Map.Entry<TkrAccount, ValidationResult> entry : accountsAfterValidation.entrySet()) {
ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest(); ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest();
TkrAccount tkrAccount = entry.getKey(); TkrAccount tkrAccount = entry.getKey();

View file

@ -28,7 +28,6 @@ public enum AccountValidationRule implements IValidationRule<ImdgValidationConte
if (!Status.Active.equalsByKey(company.getWorkflowStatus())) { if (!Status.Active.equalsByKey(company.getWorkflowStatus())) {
return of(AccountError.CompanyNotActive); return of(AccountError.CompanyNotActive);
} }
// context.storeObject(ValidationStored.Company, company);
return empty(); return empty();
} }
}, },

View file

@ -22,11 +22,11 @@ public enum BackendClientCodeValidationRule implements IValidationRule<ImdgValid
ClientCodeNewRequest validatedObject = context.getValidatedObject(); ClientCodeNewRequest validatedObject = context.getValidatedObject();
List<Long> ids = validatedObject.getCurrencyAccountList(); List<Long> ids = validatedObject.getCurrencyAccountList();
if (ids == null || ids.isEmpty()) { if (ids == null || ids.isEmpty()) {
return empty(); // необязательное поле return empty();
} }
Imdg<Account> imdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class); Imdg<Account> imdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
for (Long id : ids) { for (Long id : ids) {
if (id == null) { // null значения в массиве не ожидаются if (id == null) {
return of(AccountError.RequiredFieldEmpty, "accountId"); return of(AccountError.RequiredFieldEmpty, "accountId");
} }
Account byIdObject = imdg.getSingleObjectByID(id); Account byIdObject = imdg.getSingleObjectByID(id);

View file

@ -186,15 +186,11 @@ class AccountServiceTest {
String jsonString = getJsonStringForUpdate(correspondentAccountUpdateRequest, 0); String jsonString = getJsonStringForUpdate(correspondentAccountUpdateRequest, 0);
//ACT
addRecordToKafka((MockConsumer) accountService.getConsumer(), addRecordToKafka((MockConsumer) accountService.getConsumer(),
Consts.DESTINATION_CORRESPONDENT_ACCOUNT_UPDATE, Consts.DESTINATION_CORRESPONDENT_ACCOUNT_UPDATE,
PARTITION, PARTITION,
0, 0,
jsonString); jsonString);
//ASSERT
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
Account resultUpdating = accountImdg.getSingleObjectByID(accountId); Account resultUpdating = accountImdg.getSingleObjectByID(accountId);
@ -224,15 +220,11 @@ class AccountServiceTest {
commonDeleteRequest.setId(accountId); commonDeleteRequest.setId(accountId);
String jsonString = getJsonStringForDelete(commonDeleteRequest, 0); String jsonString = getJsonStringForDelete(commonDeleteRequest, 0);
//ACT
addRecordToKafka((MockConsumer) accountService.getConsumer(), addRecordToKafka((MockConsumer) accountService.getConsumer(),
Consts.DESTINATION_CORRESPONDENT_ACCOUNT_BLOCK, Consts.DESTINATION_CORRESPONDENT_ACCOUNT_BLOCK,
PARTITION, PARTITION,
0, 0,
jsonString); jsonString);
//ASSERT
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
Account resultBlock = accountImdg.getSingleObjectByID(accountId); Account resultBlock = accountImdg.getSingleObjectByID(accountId);

View file

@ -96,7 +96,6 @@ class AccountSymbolsServiceTest {
@PreDestroy @PreDestroy
private void destroyTest() { private void destroyTest() {
//clean test data
Account account = accountImdg.getSingleObjectByID(accountId); Account account = accountImdg.getSingleObjectByID(accountId);
if (account != null) if (account != null)
accountImdg.delete(account); accountImdg.delete(account);
@ -130,7 +129,7 @@ class AccountSymbolsServiceTest {
predictableAccountSymbols.setId(resultNew.getId()); predictableAccountSymbols.setId(resultNew.getId());
ACCOUNT_SYMBOL_MATCHER.assertMatch(resultNew, predictableAccountSymbols); ACCOUNT_SYMBOL_MATCHER.assertMatch(resultNew, predictableAccountSymbols);
accountSymbolsImdg.delete(resultNew); // cleanup test accountSymbolsImdg.delete(resultNew);
newRequestCnt++; newRequestCnt++;
} }
@ -146,15 +145,11 @@ class AccountSymbolsServiceTest {
accountSymbolsDeleteRequest.setId(accountSymbolId); accountSymbolsDeleteRequest.setId(accountSymbolId);
String jsonString = getJsonStringForDelete(accountSymbolsDeleteRequest, 0); String jsonString = getJsonStringForDelete(accountSymbolsDeleteRequest, 0);
//ACT
addRecordToKafka((MockConsumer) accountSymbolsService.getConsumer(), addRecordToKafka((MockConsumer) accountSymbolsService.getConsumer(),
Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_DELETE, Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_DELETE,
PARTITION, PARTITION,
0, 0,
jsonString); jsonString);
//ASSERT
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
AccountSymbols resultUpdating = accountSymbolsImdg.getSingleObjectByID(accountSymbolId); AccountSymbols resultUpdating = accountSymbolsImdg.getSingleObjectByID(accountSymbolId);

View file

@ -127,23 +127,8 @@ public class BankAccountServiceTest {
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L); new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
} }
/**
* {@link BankAccountService#bankAccountNew(BaseRequest request)}<br>
* Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka.<br>
* Входной запрос {@link BankAccountNewRequest}:<br>
* {@link BankAccountNewRequest#bankIdentificationCode} - 99999<br>
* {@link BankAccountNewRequest#bankName} - ооо тинькофф<br>
* {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598<br>
* {@link BankAccountNewRequest#correspondentAccountName} - BIK OF<br>
* {@link BankAccountNewRequest#currency} - RUB<br>
* {@link BankAccountNewRequest#destination} - OOO ROGA I KOPITA<br>
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484<br>
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886<br>
* {@link BankAccountNewRequest#account} - 123456789123<br>
*/
@Test @Test
public void bankAccountNew() { public void bankAccountNew() {
//ARRANGE
BankAccount predictableBankAccount = getBankAccount(); BankAccount predictableBankAccount = getBankAccount();
Company company = getTestCompany(); Company company = getTestCompany();
@ -168,8 +153,6 @@ public class BankAccountServiceTest {
BankAccountNewRequest bankAccountNewRequest = getBankAccountNewRequest(predictableBankAccount); BankAccountNewRequest bankAccountNewRequest = getBankAccountNewRequest(predictableBankAccount);
String jsonString = getJsonStringForNew(bankAccountNewRequest, ID); String jsonString = getJsonStringForNew(bankAccountNewRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_NEW, PARTITION, 0, jsonString); addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_NEW, PARTITION, 0, jsonString);
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
@ -178,26 +161,10 @@ public class BankAccountServiceTest {
predictableBankAccount.setAccountId(accountResult.getId()); predictableBankAccount.setAccountId(accountResult.getId());
predictableBankAccount.setId(bankAccountResult.getId()); predictableBankAccount.setId(bankAccountResult.getId());
setSameValueToField(accountResult, predictableAccount); setSameValueToField(accountResult, predictableAccount);
//ASSERT
BANK_ACCOUNT_MATCHER.assertMatch(bankAccountResult, predictableBankAccount); BANK_ACCOUNT_MATCHER.assertMatch(bankAccountResult, predictableBankAccount);
ACCOUNT_MATCHER.assertMatch(accountResult, predictableAccount); ACCOUNT_MATCHER.assertMatch(accountResult, predictableAccount);
} }
/**
* {@link BankAccountService#bankAccountNew(BaseRequest request)}<br>
* Тест проверяет валидацию.<br>
* Входной запрос {@link BankAccountNewRequest}:<br>
* {@link BankAccountNewRequest#bankIdentificationCode} - 99999<br>
* {@link BankAccountNewRequest#bankName} - ооо тинькофф<br>
* {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598<br>
* {@link BankAccountNewRequest#correspondentAccountName} - BIK OF<br>
* {@link BankAccountNewRequest#currency} - RUB<br>
* {@link BankAccountNewRequest#destination} - OOO ROGA I KOPITA<br>
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484<br>
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886<br>
* {@link BankAccountNewRequest#account} - 123456789123<br>
*/
@Test @Test
public void validatedBankAccountNew() { public void validatedBankAccountNew() {
clearImdg(accountImdg); clearImdg(accountImdg);
@ -207,8 +174,6 @@ public class BankAccountServiceTest {
BankAccountNewRequest bankAccountNewRequest = getBankAccountNewRequest(predictableBankAccount); BankAccountNewRequest bankAccountNewRequest = getBankAccountNewRequest(predictableBankAccount);
String errMsg; String errMsg;
//AccountValidationRule.RequiredFields
//WrongFieldValue
bankAccountNewRequest.setCurrency(null); bankAccountNewRequest.setCurrency(null);
errMsg = messageResolver.resolve(new EnumMessage(AccountError.RequiredFieldEmpty, "null, currency")); errMsg = messageResolver.resolve(new EnumMessage(AccountError.RequiredFieldEmpty, "null, currency"));
checkError(errMsg, bankAccountNewRequest); checkError(errMsg, bankAccountNewRequest);
@ -233,17 +198,11 @@ public class BankAccountServiceTest {
checkError(errMsg, bankAccountNewRequest); checkError(errMsg, bankAccountNewRequest);
bankAccountNewRequest.setAccount(acc); bankAccountNewRequest.setAccount(acc);
//AccountValidationRule.CompanyPresent
//CompanyNotFound
bankAccountNewRequest.setCompanyId(999924535239L); bankAccountNewRequest.setCompanyId(999924535239L);
errMsg = messageResolver.resolve(new EnumMessage(AccountError.CompanyNotFound, bankAccountNewRequest.getCompanyId()+", companyId")); errMsg = messageResolver.resolve(new EnumMessage(AccountError.CompanyNotFound, bankAccountNewRequest.getCompanyId() + ", companyId"));
checkError(errMsg, bankAccountNewRequest); checkError(errMsg, bankAccountNewRequest);
bankAccountNewRequest.setCompanyId(company.getId()); bankAccountNewRequest.setCompanyId(company.getId());
//AccountValidationRule.AccountIsNew
//AccountAlreadyExist
Account existAccount = getTestAccount(accountId, acc); Account existAccount = getTestAccount(accountId, acc);
accountImdg.insert(existAccount); accountImdg.insert(existAccount);
errMsg = messageResolver.resolve(new EnumMessage(AccountError.AccountAlreadyExist, existAccount.getAccount())); errMsg = messageResolver.resolve(new EnumMessage(AccountError.AccountAlreadyExist, existAccount.getAccount()));
@ -252,7 +211,6 @@ public class BankAccountServiceTest {
} }
private void checkError(String errorMsg, BankAccountNewRequest bankAccountNewRequest) { private void checkError(String errorMsg, BankAccountNewRequest bankAccountNewRequest) {
//ARRANGE
int currentTime = countRun.getAndIncrement(); int currentTime = countRun.getAndIncrement();
long currentOffset = currentTime; long currentOffset = currentTime;
BaseRequest<Object> predictableBaseRequest = new BaseRequest<>(); BaseRequest<Object> predictableBaseRequest = new BaseRequest<>();
@ -265,41 +223,19 @@ public class BankAccountServiceTest {
predictableBaseRequest.setRequestPayload(requestInfoUpdate); predictableBaseRequest.setRequestPayload(requestInfoUpdate);
String jsonString = getJsonStringForNew(bankAccountNewRequest, ID); String jsonString = getJsonStringForNew(bankAccountNewRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_NEW, PARTITION, currentOffset, jsonString); addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_NEW, PARTITION, currentOffset, jsonString);
ArgumentCaptor<ProducerRecord> producerRecord = getCaptor(mockProducer); ArgumentCaptor<ProducerRecord> producerRecord = getCaptor(mockProducer);
//waiting for kafka producer send message (finale event)
verify(mockProducer, timeout(30_000L).times(currentTime)) verify(mockProducer, timeout(30_000L).times(currentTime))
.send(producerRecord.capture()); .send(producerRecord.capture());
BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) producerRecord.getValue().value(); BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) producerRecord.getValue().value();
//ASSERT
assertEquals(Consts.REQUEST_INFO_UPDATE, producerRecord.getValue().topic()); assertEquals(Consts.REQUEST_INFO_UPDATE, producerRecord.getValue().topic());
BASE_REQUEST_MATCHER.assertMatch(baseRequestResult, predictableBaseRequest); BASE_REQUEST_MATCHER.assertMatch(baseRequestResult, predictableBaseRequest);
} }
/**
* {@link BankAccountService#bankAccountUpdate(BaseRequest)}<br>
* Тест проверяет обновление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka.<br>
* Входной запрос {@link BankAccountUpdateRequest}:<br>
* {@link BankAccountUpdateRequest#bankIdentificationCode} - NEW BUNK NAME<br>
* {@link BankAccountUpdateRequest#bankName} - 88888<br>
* {@link BankAccountUpdateRequest#correspondentAccount} - 894984646541316<br>
* {@link BankAccountUpdateRequest#correspondentAccountName} - BIK OF NEW BUNK<br>
* {@link BankAccountUpdateRequest#currency} - EU<br>
* {@link BankAccountUpdateRequest#destination} - OOO NEW BUNK<br>
* {@link BankAccountUpdateRequest#taxpayerIdentificationNumber} - 65468461321<br>
* {@link BankAccountUpdateRequest#taxRegistrationReasonCode} - 532137<br>
* {@link BankAccountUpdateRequest#account} - 326984656514<br>
*/
@Test @Test
void bankAccountUpdate() { void bankAccountUpdate() {
clearImdg(accountImdg); clearImdg(accountImdg);
//ARRANGE
// Company company = getTestCompany();
// companyImdg.insert(company);
Account predictableAccount = getTestAccount(accountId, acc); Account predictableAccount = getTestAccount(accountId, acc);
accountImdg.insert(predictableAccount); accountImdg.insert(predictableAccount);
@ -332,11 +268,7 @@ public class BankAccountServiceTest {
bankAccountUpdateRequest.setSwiftCode(predictableUpdateBankAccount.getSwiftCode()); bankAccountUpdateRequest.setSwiftCode(predictableUpdateBankAccount.getSwiftCode());
String jsonString = getJsonStringForUpdate(bankAccountUpdateRequest, ID); String jsonString = getJsonStringForUpdate(bankAccountUpdateRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_UPDATE, PARTITION, 0, jsonString); addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_UPDATE, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
Account accountResult = accountImdg.getSingleObjectByID(predictableAccount.getId()); Account accountResult = accountImdg.getSingleObjectByID(predictableAccount.getId());
@ -348,15 +280,8 @@ public class BankAccountServiceTest {
ACCOUNT_MATCHER.assertMatch(accountResult, predictableAccount); ACCOUNT_MATCHER.assertMatch(accountResult, predictableAccount);
} }
/**
* {@link BankAccountService#bankAccountBlock(BaseRequest)}
* Тест проверяет удаление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka.
* Входной запрос {@link CommonDeleteRequest}:
* {@link CommonDeleteRequest#id} - Идентификатор записи
*/
@Test @Test
void bankAccountBlock() { void bankAccountBlock() {
//ARRANGE
BankAccount bankAccountExists = getBankAccount(); BankAccount bankAccountExists = getBankAccount();
bankAccountImdg.insert(bankAccountExists); bankAccountImdg.insert(bankAccountExists);
Account account = new Account(); Account account = new Account();
@ -367,11 +292,7 @@ public class BankAccountServiceTest {
CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest(); CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest();
commonDeleteRequest.setId(ID); commonDeleteRequest.setId(ID);
String jsonString = getJsonStringForDelete(commonDeleteRequest, ID); String jsonString = getJsonStringForDelete(commonDeleteRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_DELETE, PARTITION, 0, jsonString); addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_DELETE, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
Account bankAccount = accountImdg.getSingleObjectByID(accountId); Account bankAccount = accountImdg.getSingleObjectByID(accountId);

View file

@ -233,19 +233,8 @@ class ClearingAccountServiceTest {
Assertions.assertEquals("2", clearingAccountService.makeSdfErrorText(null, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND)); Assertions.assertEquals("2", clearingAccountService.makeSdfErrorText(null, SDFProcessService.SDF_STATUS_ERROR_COMPANY_NOT_FOUND));
} }
/**
* {@link ClearingAccountService#accountNewSdf01(BaseRequest)}<br>
* Тест проверяет создание сущности {@link BaseRequest} в Hazelcast при передаче из Apache Kafka.<br>
* Входной запрос {@link AccountSdf01Request}:<br>
* {@link AccountSdfRequestPart#setSdfId} - текущий Id<br>
* {@link AccountSdfRequestPart#setAccount} - 123456789123<br>
* {@link AccountSdfRequestPart#setCompanyId} - текущий Id<br>
* {@link AccountSdf01Request#setGroupingSdf01Id} - текущий Id<br>
* {@link AccountSdf01Request#setAccounts} - Collections.singletonList(AccountSdfRequestPart)<br>
*/
@Test @Test
void accountSdf01New() throws InterruptedException { void accountSdf01New() throws InterruptedException {
//ARRANGE
clearImdg(accountImdg); clearImdg(accountImdg);
setMockFuture(kafkaTemplate); setMockFuture(kafkaTemplate);
Long firstID = currentID.getAndIncrement(); Long firstID = currentID.getAndIncrement();
@ -268,15 +257,10 @@ class ClearingAccountServiceTest {
predictableAccount.setRelationId(relationId); predictableAccount.setRelationId(relationId);
ClearingAccount predictableClearingAccount = new ClearingAccount(); ClearingAccount predictableClearingAccount = new ClearingAccount();
predictableClearingAccount.setCompanyId(companyId); predictableClearingAccount.setCompanyId(companyId);
// predictableClearingAccount.setClearingAccountType(CLEARING_ACCOUNT_TYPE_DICT);
//KAFKA
addRecordToKafka((MockConsumer) clearingAccountService.getConsumer(), Consts.ACCOUNT_NEW_SDF01, PARTITION, 0, jsonString); addRecordToKafka((MockConsumer) clearingAccountService.getConsumer(), Consts.ACCOUNT_NEW_SDF01, PARTITION, 0, jsonString);
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
ImdgHazelcast<Account> accountImdg = (ImdgHazelcast<Account>) hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_Account, Account.class); ImdgHazelcast<Account> accountImdg = (ImdgHazelcast<Account>) hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_Account, Account.class);
//ASSERT
Account accountResult = accountImdg.getSingleObjectBySQL(String.format("account = %s", ACCOUNT_VALUE)); Account accountResult = accountImdg.getSingleObjectBySQL(String.format("account = %s", ACCOUNT_VALUE));
ClearingAccount resultClearingAccountNew = clearingAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", accountResult.getId())); ClearingAccount resultClearingAccountNew = clearingAccountImdg.getFirstObjectByFieldValues(Map.of("accountId", accountResult.getId()));
predictableAccount.setId(accountResult.getId()); predictableAccount.setId(accountResult.getId());

View file

@ -53,20 +53,20 @@ import static ru.spcex.clearing.test.TestUtils.waitingSendAndCheckRecord;
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { @ContextConfiguration(classes = {
ClientCodeService.class, ClientCodeService.class,
ClientCodeValidationConfig.class, ClientCodeValidationConfig.class,
TradingClearingRegistryService.class, TradingClearingRegistryService.class,
TradingClearingRegistryValidationConfig.class, TradingClearingRegistryValidationConfig.class,
TradingClearingRegistryListService.class, TradingClearingRegistryListService.class,
TradingClearingRegistryListValidationConfig.class, TradingClearingRegistryListValidationConfig.class,
ValidationConfig.class, ValidationConfig.class,
BeanConfiguration.class, BeanConfiguration.class,
KafkaTestConfig.class, KafkaTestConfig.class,
ImdgTestConfig.class}) ImdgTestConfig.class})
class ClientCodeServiceTest { class ClientCodeServiceTest {
private static final int PARTITION = 0; private static final int PARTITION = 0;
@ -90,16 +90,11 @@ class ClientCodeServiceTest {
private Imdg<ClientCode> clientCodeImdg; private Imdg<ClientCode> clientCodeImdg;
private Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg; private Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg;
// ****************************-*******************
@PostConstruct @PostConstruct
private void init() { private void init() {
hazelcastServiceTest.waitAvailable(); hazelcastServiceTest.waitAvailable();
clientCodeImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class); clientCodeImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class);
tradingClearingRegistryListImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class); tradingClearingRegistryListImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class);
// Словари для теста, применяются в ValidationConfig
putToDictionary(IMDGDistributedNames.Map_WorkflowStatusDictionary, new WorkflowStatusDictionary(), "ACTV"); putToDictionary(IMDGDistributedNames.Map_WorkflowStatusDictionary, new WorkflowStatusDictionary(), "ACTV");
putToDictionary(IMDGDistributedNames.Map_ServiceStatusDictionary, new ServiceStatusDictionary(), ServiceStatus.Active.getKey()); putToDictionary(IMDGDistributedNames.Map_ServiceStatusDictionary, new ServiceStatusDictionary(), ServiceStatus.Active.getKey());
putToDictionary(IMDGDistributedNames.Map_CompanySymbolDictionary, new CompanySymbolDictionary(), "CLRC"); putToDictionary(IMDGDistributedNames.Map_CompanySymbolDictionary, new CompanySymbolDictionary(), "CLRC");
@ -141,7 +136,7 @@ class ClientCodeServiceTest {
moneyAccount.setId(131L); moneyAccount.setId(131L);
moneyAccount.setAccount("AAAA-4444"); moneyAccount.setAccount("AAAA-4444");
moneyAccount.setStatus("ACTV"); moneyAccount.setStatus("ACTV");
moneyAccount.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта moneyAccount.setCompanyId(COMPANY_ID);
accounts.insert(moneyAccount); accounts.insert(moneyAccount);
ClearingAccount clsAcc = new ClearingAccount(); ClearingAccount clsAcc = new ClearingAccount();
clsAcc.setId(moneyAccount.getId()); clsAcc.setId(moneyAccount.getId());
@ -153,7 +148,7 @@ class ClientCodeServiceTest {
depoAccount.setId(132L); depoAccount.setId(132L);
depoAccount.setAccount("AAAB-44654"); depoAccount.setAccount("AAAB-44654");
depoAccount.setStatus("ACTV"); depoAccount.setStatus("ACTV");
depoAccount.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта depoAccount.setCompanyId(COMPANY_ID);
accounts.insert(depoAccount); accounts.insert(depoAccount);
DepoAccount depoAcc = new DepoAccount(); DepoAccount depoAcc = new DepoAccount();
depoAcc.setId(depoAccount.getId()); depoAcc.setId(depoAccount.getId());
@ -165,7 +160,7 @@ class ClientCodeServiceTest {
c2Account.setId(133L); c2Account.setId(133L);
c2Account.setAccount("AAAX-44654-CURR"); c2Account.setAccount("AAAX-44654-CURR");
c2Account.setStatus("ACTV"); c2Account.setStatus("ACTV");
c2Account.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта c2Account.setCompanyId(COMPANY_ID);
c2Account.setAccountType(AccountType.Curr.getKey()); c2Account.setAccountType(AccountType.Curr.getKey());
accounts.insert(c2Account); accounts.insert(c2Account);
@ -196,14 +191,8 @@ class ClientCodeServiceTest {
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет создание {@link ClientCode} в IMDG при передаче из Apache Kafka (очередь 1).<br>
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeNewRequest}:<br>
**/
@Test @Test
void clientCodeNew1() { void clientCodeNew1() {
//ARRANGE
final String ccCode = "Lucky planet"; final String ccCode = "Lucky planet";
ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest(); ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest();
clientCodeNewRequest.setCompanyId(COMPANY_ID); clientCodeNewRequest.setCompanyId(COMPANY_ID);
@ -217,16 +206,9 @@ class ClientCodeServiceTest {
predictableClientCode.setCode(ccCode); predictableClientCode.setCode(ccCode);
predictableClientCode.setStatus("ACTV"); predictableClientCode.setStatus("ACTV");
predictableClientCode.setCompanyId(COMPANY_ID); predictableClientCode.setCompanyId(COMPANY_ID);
// predictableClientCode.setMoneyAccountId(131L);
// predictableClientCode.setDepoAccountId(132L);
// predictableClientCode.setTradingClearingRegistryId(TCR_ID);
//ACT
String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID); String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode)); ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId()); predictableClientCode.setId(resultNew.getId());
@ -234,14 +216,8 @@ class ClientCodeServiceTest {
assertNotNull(resultNew.getCreated()); assertNotNull(resultNew.getCreated());
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет создание {@link ClientCode} в IMDG при передаче из Apache Kafka (очередь 2).<br>
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeNewRequest}:<br>
**/
@Test @Test
void clientCodeNew2() { void clientCodeNew2() {
//ARRANGE
final String ccCode = "Lucky planet"; final String ccCode = "Lucky planet";
ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest(); ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest();
clientCodeNewRequest.setCompanyId(COMPANY_ID); clientCodeNewRequest.setCompanyId(COMPANY_ID);
@ -255,17 +231,10 @@ class ClientCodeServiceTest {
predictableClientCode.setCode(ccCode); predictableClientCode.setCode(ccCode);
predictableClientCode.setStatus("ACTV"); predictableClientCode.setStatus("ACTV");
predictableClientCode.setCompanyId(COMPANY_ID); predictableClientCode.setCompanyId(COMPANY_ID);
// predictableClientCode.setMoneyAccountId(131L);
// predictableClientCode.setDepoAccountId(132L);
// predictableClientCode.setTradingClearingRegistryId(TCR_ID);
//ACT
String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID); String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, PARTITION, 0, jsonString);
waitingSendAndCheckRecord(ID, mockProducer, producerRecord);
//ASSERT
TestUtils.waitingSendAndCheckRecord(ID, mockProducer, producerRecord);
ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode)); ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId()); predictableClientCode.setId(resultNew.getId());
CLIENT_CODE_MATCHER.assertMatch(resultNew, predictableClientCode); CLIENT_CODE_MATCHER.assertMatch(resultNew, predictableClientCode);
@ -273,15 +242,8 @@ class ClientCodeServiceTest {
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет создание {@link ClientCode} в IMDG при передаче из Apache Kafka (очередь 1).<br>
* NEW с заполненными MoneyAccountId(131L), DepoAccountId(132L); - от этого будет создан ТКР.
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeNewRequest}:<br>
**/
@Test @Test
void clientCodeNew3() { void clientCodeNew3() {
//ARRANGE
final String ccCode = "Lucky planet2"; final String ccCode = "Lucky planet2";
ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest(); ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest();
clientCodeNewRequest.setCompanyId(COMPANY_ID); clientCodeNewRequest.setCompanyId(COMPANY_ID);
@ -298,13 +260,9 @@ class ClientCodeServiceTest {
predictableClientCode.setMoneyAccountId(131L); predictableClientCode.setMoneyAccountId(131L);
predictableClientCode.setDepoAccountId(132L); predictableClientCode.setDepoAccountId(132L);
predictableClientCode.setTradingClearingRegistryId(TCR_ID); predictableClientCode.setTradingClearingRegistryId(TCR_ID);
//ACT
String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID); String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode)); ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId()); predictableClientCode.setId(resultNew.getId());
@ -313,15 +271,8 @@ class ClientCodeServiceTest {
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет создание {@link ClientCode} в IMDG при передаче из Apache Kafka (очередь 4).<br>
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeNewRequest}:<br>
* С дополнительным заполнением TradingClearingRegistryList id's. С одним.
**/
@Test @Test
void clientCodeNew4() { void clientCodeNew4() {
//ARRANGE
final String ccCode = "Lucky"; final String ccCode = "Lucky";
ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest(); ClientCodeNewRequest clientCodeNewRequest = new ClientCodeNewRequest();
clientCodeNewRequest.setCompanyId(COMPANY_ID); clientCodeNewRequest.setCompanyId(COMPANY_ID);
@ -340,13 +291,9 @@ class ClientCodeServiceTest {
predictableClientCode.setDepoAccountId(132L); predictableClientCode.setDepoAccountId(132L);
predictableClientCode.setCurrencyAccountId(133L); predictableClientCode.setCurrencyAccountId(133L);
predictableClientCode.setTradingClearingRegistryId(TCR_ID); predictableClientCode.setTradingClearingRegistryId(TCR_ID);
//ACT
String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID); String jsonString = TestUtils.getJsonStringForNew(clientCodeNewRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode)); ClientCode resultNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId()); predictableClientCode.setId(resultNew.getId());
@ -358,14 +305,8 @@ class ClientCodeServiceTest {
assertEquals(TCR_ID, newTCRList.getTradingClearingRegistryId()); assertEquals(TCR_ID, newTCRList.getTradingClearingRegistryId());
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет обновление сущности {@link ClientCode} в IMDG при передаче из Apache Kafka.<br>
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeUpdateRequest}:<br>
**/
@Test @Test
void clientCodeUpdate() { void clientCodeUpdate() {
//ARRANGE
ClientCode existsClientCode = new ClientCode(); ClientCode existsClientCode = new ClientCode();
existsClientCode.setId(ID); existsClientCode.setId(ID);
existsClientCode.setCompanyId(COMPANY_ID); existsClientCode.setCompanyId(COMPANY_ID);
@ -393,13 +334,9 @@ class ClientCodeServiceTest {
predictableClientCode.setMoneyAccountId(131L); predictableClientCode.setMoneyAccountId(131L);
predictableClientCode.setDepoAccountId(132L); predictableClientCode.setDepoAccountId(132L);
predictableClientCode.setStatus("ACTV"); predictableClientCode.setStatus("ACTV");
//ACT
String jsonString = TestUtils.getJsonStringForUpdate(clientCodeUpdateRequest, ID); String jsonString = TestUtils.getJsonStringForUpdate(clientCodeUpdateRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_UPDATE, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_UPDATE, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultUpdating = clientCodeImdg.getSingleObjectByID(ID); ClientCode resultUpdating = clientCodeImdg.getSingleObjectByID(ID);
@ -408,19 +345,12 @@ class ClientCodeServiceTest {
} }
/**
* {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
* Тест проверяет удаление {@link ClientCode} из IMDG при передаче из Apache Kafka.<br>
* Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest}:<br>
**/
@Test @Test
void clientCodeDelete1() { void clientCodeDelete1() {
//ARRANGE
ClientCode existsClientCode = new ClientCode(); ClientCode existsClientCode = new ClientCode();
existsClientCode.setId(ID); existsClientCode.setId(ID);
existsClientCode.setCompanyId(COMPANY_ID); existsClientCode.setCompanyId(COMPANY_ID);
existsClientCode.setCode("0000"); existsClientCode.setCode("0000");
// Если следующие поля заполнить, то дополнительно отправит сообщение в trading-clearing-registry-update:
existsClientCode.setTradingClearingRegistryId(null); existsClientCode.setTradingClearingRegistryId(null);
existsClientCode.setMoneyAccountId(null); existsClientCode.setMoneyAccountId(null);
existsClientCode.setDepoAccountId(null); existsClientCode.setDepoAccountId(null);
@ -431,56 +361,14 @@ class ClientCodeServiceTest {
CommonDeleteRequest clientCodeDeleteRequest = new CommonDeleteRequest(); CommonDeleteRequest clientCodeDeleteRequest = new CommonDeleteRequest();
clientCodeDeleteRequest.setId(ID); clientCodeDeleteRequest.setId(ID);
Assertions.assertNotNull(clientCodeImdg.getSingleObjectByID(ID)); // verify test data assertNotNull(clientCodeImdg.getSingleObjectByID(ID));
//ACT
String jsonString = TestUtils.getJsonStringForUpdate(clientCodeDeleteRequest, ID); String jsonString = TestUtils.getJsonStringForUpdate(clientCodeDeleteRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_DELETE, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_DELETE, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultUpdate = clientCodeImdg.getSingleObjectByID(ID); ClientCode resultUpdate = clientCodeImdg.getSingleObjectByID(ID);
assertEquals(WorkflowStatus.Blocked.getKey(), resultUpdate.getStatus()); assertEquals(WorkflowStatus.Blocked.getKey(), resultUpdate.getStatus());
} }
// /**
// * {@link ClientCodeService#clientCodeUpdate(BaseRequest)}<br>
// * Тест проверяет удаление {@link ClientCode} из IMDG при передаче из Apache Kafka.<br>
// * У ClientCode заполнены MoneyAccountId, DepoAccountId - по этому при удалении должно направиться дополнительное сообщение в очередь DESTINATION_TRADING_CLEARING_REGISTRY_UPDATE<br>
// * Входной запрос {@link ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest}:<br>
// **/
// @Test
// void clientCodeDelete2() {
// //ARRANGE
// ClientCode existsClientCode = new ClientCode();
// existsClientCode.setId(ID);
// existsClientCode.setCompanyId(COMPANY_ID);
// existsClientCode.setCode("0000");
// // Если следующие поля заполнить, то дополнительно отправит сообщение в trading-clearing-registry-update:
// existsClientCode.setTradingClearingRegistryId(TCR_ID);
// existsClientCode.setMoneyAccountId(131L);
// existsClientCode.setDepoAccountId(132L);
// existsClientCode.setStatus("ACTV");
//
// clientCodeImdg.insert(existsClientCode);
//
// CommonDeleteRequest clientCodeDeleteRequest = new CommonDeleteRequest();
// clientCodeDeleteRequest.setId(ID);
//
// Assertions.assertNotNull(clientCodeImdg.getSingleObjectByID(ID)); // verify test data
//
// //ACT
// String jsonString = getJsonStringForUpdate(clientCodeDeleteRequest, ID);
//
// addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_DELETE, PARTITION, 0, jsonString);
//
// //ASSERT
//
// waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
// ClientCode resultUpdate = clientCodeImdg.getSingleObjectByID(ID);
// Assertions.assertNull(resultUpdate);
// }
} }

View file

@ -174,7 +174,7 @@ class InformationAccountServiceTest {
@Test @Test
void accountIncrementSequence() { void accountIncrementSequence() {
Imdg<InformationAccount> accountInfoImdg = hazelcastServiceTest.getImdg( IMDGDistributedNames.Map_InformationAccount, InformationAccount.class ); Imdg<InformationAccount> accountInfoImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_InformationAccount, InformationAccount.class);
{ {
Account account = new Account(); Account account = new Account();
@ -192,14 +192,12 @@ class InformationAccountServiceTest {
accountInfoImdg.insert(accountInfo); accountInfoImdg.insert(accountInfo);
} }
UserRoleVerification userRoleVerification = Mockito.mock(UserRoleVerification.class); UserRoleVerification userRoleVerification = Mockito.mock(UserRoleVerification.class);
InformationAccountService infoAccSvc=new InformationAccountService(null,null,null, InformationAccountService infoAccSvc = new InformationAccountService(null, null, null,
null, userRoleVerification, hazelcastServiceTest, null, null, null, null); null, userRoleVerification, hazelcastServiceTest, null, null, null, null);
Long n = infoAccSvc.accountNextId(null); Long n = infoAccSvc.accountNextId(null);
Assertions.assertEquals(13L, n); Assertions.assertEquals(13L, n);
n = infoAccSvc.accountNextId(null); n = infoAccSvc.accountNextId(null);
Assertions.assertEquals(14L, n); Assertions.assertEquals(14L, n);
// Другие валюты
n = infoAccSvc.accountNextId(CurrencyCode.RUB.getKey()); n = infoAccSvc.accountNextId(CurrencyCode.RUB.getKey());
Assertions.assertEquals(15L, n); Assertions.assertEquals(15L, n);
n = infoAccSvc.accountNextId("CNY"); n = infoAccSvc.accountNextId("CNY");

View file

@ -55,19 +55,19 @@ import static ru.spcex.clearing.test.TestUtils.waitingSendAndCheckRecord;
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { @ContextConfiguration(classes = {
TradingClearingRegistryListService.class, TradingClearingRegistryListService.class,
TradingClearingRegistryListValidationConfig.class, TradingClearingRegistryListValidationConfig.class,
ClientCodeService.class, ClientCodeService.class,
ClientCodeValidationConfig.class, ClientCodeValidationConfig.class,
TradingClearingRegistryService.class, TradingClearingRegistryService.class,
TradingClearingRegistryValidationConfig.class, TradingClearingRegistryValidationConfig.class,
ValidationConfig.class, ValidationConfig.class,
BeanConfiguration.class, BeanConfiguration.class,
KafkaTestConfig.class, KafkaTestConfig.class,
ImdgTestConfig.class}) ImdgTestConfig.class})
class TradingClearingRegistryListServiceTest { class TradingClearingRegistryListServiceTest {
private static final int PARTITION = 0; private static final int PARTITION = 0;
private static final Long ID = 4L; private static final Long ID = 4L;
@ -91,16 +91,11 @@ class TradingClearingRegistryListServiceTest {
private Imdg<ClientCode> clientCodeImdg; private Imdg<ClientCode> clientCodeImdg;
private Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg; private Imdg<TradingClearingRegistryList> tradingClearingRegistryListImdg;
// ****************************-*******************
@PostConstruct @PostConstruct
private void init() { private void init() {
hazelcastServiceTest.waitAvailable(); hazelcastServiceTest.waitAvailable();
clientCodeImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class); clientCodeImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_ClientCode, ClientCode.class);
tradingClearingRegistryListImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class); tradingClearingRegistryListImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TradingClearingRegistryList, TradingClearingRegistryList.class);
// Словари для теста, применяются в ValidationConfig
putToDictionary(IMDGDistributedNames.Map_WorkflowStatusDictionary, new WorkflowStatusDictionary(), "ACTV"); putToDictionary(IMDGDistributedNames.Map_WorkflowStatusDictionary, new WorkflowStatusDictionary(), "ACTV");
putToDictionary(IMDGDistributedNames.Map_ServiceStatusDictionary, new ServiceStatusDictionary(), ServiceStatus.Active.getKey()); putToDictionary(IMDGDistributedNames.Map_ServiceStatusDictionary, new ServiceStatusDictionary(), ServiceStatus.Active.getKey());
putToDictionary(IMDGDistributedNames.Map_CompanySymbolDictionary, new CompanySymbolDictionary(), "CLRC"); putToDictionary(IMDGDistributedNames.Map_CompanySymbolDictionary, new CompanySymbolDictionary(), "CLRC");
@ -142,7 +137,7 @@ class TradingClearingRegistryListServiceTest {
moneyAccount.setId(131L); moneyAccount.setId(131L);
moneyAccount.setAccount("AAAA-4444"); moneyAccount.setAccount("AAAA-4444");
moneyAccount.setStatus("ACTV"); moneyAccount.setStatus("ACTV");
moneyAccount.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта moneyAccount.setCompanyId(COMPANY_ID);
accounts.insert(moneyAccount); accounts.insert(moneyAccount);
ClearingAccount clsAcc = new ClearingAccount(); ClearingAccount clsAcc = new ClearingAccount();
clsAcc.setId(moneyAccount.getId()); clsAcc.setId(moneyAccount.getId());
@ -154,7 +149,7 @@ class TradingClearingRegistryListServiceTest {
depoAccount.setId(132L); depoAccount.setId(132L);
depoAccount.setAccount("AAAB-44654"); depoAccount.setAccount("AAAB-44654");
depoAccount.setStatus("ACTV"); depoAccount.setStatus("ACTV");
depoAccount.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта depoAccount.setCompanyId(COMPANY_ID);
accounts.insert(depoAccount); accounts.insert(depoAccount);
DepoAccount depoAcc = new DepoAccount(); DepoAccount depoAcc = new DepoAccount();
depoAcc.setId(depoAccount.getId()); depoAcc.setId(depoAccount.getId());
@ -166,7 +161,7 @@ class TradingClearingRegistryListServiceTest {
c2Account.setId(133L); c2Account.setId(133L);
c2Account.setAccount("AAAX-44654-CURR"); c2Account.setAccount("AAAX-44654-CURR");
c2Account.setStatus("ACTV"); c2Account.setStatus("ACTV");
c2Account.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта c2Account.setCompanyId(COMPANY_ID);
c2Account.setAccountType(AccountType.Info.getKey()); c2Account.setAccountType(AccountType.Info.getKey());
c2Account.setCurrency("USD"); c2Account.setCurrency("USD");
accounts.insert(c2Account); accounts.insert(c2Account);
@ -175,7 +170,7 @@ class TradingClearingRegistryListServiceTest {
c3Account.setId(134L); c3Account.setId(134L);
c3Account.setAccount("AAAX-12654-CURR"); c3Account.setAccount("AAAX-12654-CURR");
c3Account.setStatus("ACTV"); c3Account.setStatus("ACTV");
c3Account.setCompanyId(COMPANY_ID); // для валидации принадлежности счёта c3Account.setCompanyId(COMPANY_ID);
c3Account.setAccountType(AccountType.Info.getKey()); c3Account.setAccountType(AccountType.Info.getKey());
c3Account.setCurrency("USD"); c3Account.setCurrency("USD");
accounts.insert(c3Account); accounts.insert(c3Account);
@ -192,14 +187,8 @@ class TradingClearingRegistryListServiceTest {
} }
/**
* {@link TradingClearingRegistryListService#tradingClearingRegistryListNew(BaseRequest)}<br>
* Тест проверяет создание {@link TradingClearingRegistryList} в IMDG при передаче из Apache Kafka (очередь 1).<br>
* Входной запрос {@link TradingClearingRegistryListNewRequest}:<br>
**/
@Test @Test
void tradingClearingRegistryListNew() { void tradingClearingRegistryListNew() {
//ARRANGE
final String ccCode = null; final String ccCode = null;
TradingClearingRegistryListNewRequest tcrlNewRequest = new TradingClearingRegistryListNewRequest(); TradingClearingRegistryListNewRequest tcrlNewRequest = new TradingClearingRegistryListNewRequest();
tcrlNewRequest.setTradingClearingRegistryId(TCR_ID); tcrlNewRequest.setTradingClearingRegistryId(TCR_ID);
@ -215,14 +204,10 @@ class TradingClearingRegistryListServiceTest {
predictableTradingClearingRegistryList.setAccountId(134L); predictableTradingClearingRegistryList.setAccountId(134L);
predictableTradingClearingRegistryList.setStatus("ACTV"); predictableTradingClearingRegistryList.setStatus("ACTV");
predictableTradingClearingRegistryList.setCurrency("USD"); predictableTradingClearingRegistryList.setCurrency("USD");
//ACT
String jsonString = TestUtils.getJsonStringForNew(tcrlNewRequest, ID); String jsonString = TestUtils.getJsonStringForNew(tcrlNewRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) tradingClearingRegistryListService.getConsumer(), Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) tradingClearingRegistryListService.getConsumer(), Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, PARTITION, 0, jsonString);
waitingSendAndCheckRecord(ID, mockProducer);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultCCNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode)); ClientCode resultCCNew = clientCodeImdg.getFirstObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultCCNew.getId()); predictableClientCode.setId(resultCCNew.getId());
CLIENT_CODE_MATCHER.assertMatch(resultCCNew, predictableClientCode); CLIENT_CODE_MATCHER.assertMatch(resultCCNew, predictableClientCode);
@ -232,19 +217,11 @@ class TradingClearingRegistryListServiceTest {
predictableClientCode.setId(resultTCRLNew.getId()); predictableClientCode.setId(resultTCRLNew.getId());
TRADING_CLEARING_REGISTRY_LIST_MATCHER.assertMatch(resultTCRLNew, predictableTradingClearingRegistryList); TRADING_CLEARING_REGISTRY_LIST_MATCHER.assertMatch(resultTCRLNew, predictableTradingClearingRegistryList);
assertNotNull(resultTCRLNew.getCreated()); assertNotNull(resultTCRLNew.getCreated());
// CLEAN UP
tradingClearingRegistryListImdg.delete(resultTCRLNew); tradingClearingRegistryListImdg.delete(resultTCRLNew);
} }
/**
* {@link TradingClearingRegistryListService#tradingClearingRegistryListUpdate(BaseRequest)}<br>
* Тест проверяет обновление сущности {@link TradingClearingRegistryList} в IMDG при передаче из Apache Kafka.<br>
* Входной запрос {@link TradingClearingRegistryListUpdateRequest}:<br>
**/
@Test @Test
void tradingClearingRegistryListUpdate() { void tradingClearingRegistryListUpdate() {
//ARRANGE
TradingClearingRegistryList existsTradingClearingRegistryList = new TradingClearingRegistryList(); TradingClearingRegistryList existsTradingClearingRegistryList = new TradingClearingRegistryList();
existsTradingClearingRegistryList.setId(ID); existsTradingClearingRegistryList.setId(ID);
existsTradingClearingRegistryList.setTradingClearingRegistryId(TCR_ID); existsTradingClearingRegistryList.setTradingClearingRegistryId(TCR_ID);
@ -264,20 +241,14 @@ class TradingClearingRegistryListServiceTest {
predictableTradingClearingRegistryList.setCurrency("BTC"); predictableTradingClearingRegistryList.setCurrency("BTC");
predictableTradingClearingRegistryList.setAccountId(133L); predictableTradingClearingRegistryList.setAccountId(133L);
predictableTradingClearingRegistryList.setStatus("ACTV"); predictableTradingClearingRegistryList.setStatus("ACTV");
//ACT
String jsonString = TestUtils.getJsonStringForUpdate(tradingClearingRegistryListUpdateRequest, ID); String jsonString = TestUtils.getJsonStringForUpdate(tradingClearingRegistryListUpdateRequest, ID);
TestUtils.addRecordToKafka((MockConsumer) tradingClearingRegistryListService.getConsumer(), Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, PARTITION, 0, jsonString); TestUtils.addRecordToKafka((MockConsumer) tradingClearingRegistryListService.getConsumer(), Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, PARTITION, 0, jsonString);
//ASSERT
waitingSendAndCheckRecord(ID, mockProducer); waitingSendAndCheckRecord(ID, mockProducer);
TradingClearingRegistryList resultUpdating = tradingClearingRegistryListImdg.getSingleObjectByID(ID); TradingClearingRegistryList resultUpdating = tradingClearingRegistryListImdg.getSingleObjectByID(ID);
TRADING_CLEARING_REGISTRY_LIST_MATCHER.assertMatch(resultUpdating, predictableTradingClearingRegistryList); TRADING_CLEARING_REGISTRY_LIST_MATCHER.assertMatch(resultUpdating, predictableTradingClearingRegistryList);
assertNotNull(resultUpdating.getUpdated()); assertNotNull(resultUpdating.getUpdated());
// CLEAN UP
tradingClearingRegistryListImdg.delete(resultUpdating); tradingClearingRegistryListImdg.delete(resultUpdating);
} }

View file

@ -283,15 +283,11 @@ class TradingClearingRegistryServiceTest {
tradingClearingRegistryUpdateRequest.setId(registryId); tradingClearingRegistryUpdateRequest.setId(registryId);
String jsonString = getJsonStringForUpdate(tradingClearingRegistryUpdateRequest, 0); String jsonString = getJsonStringForUpdate(tradingClearingRegistryUpdateRequest, 0);
//ACT
addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(), addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(),
Consts.DESTINATION_TRADING_CLEARING_REGISTRY_UPDATE, Consts.DESTINATION_TRADING_CLEARING_REGISTRY_UPDATE,
PARTITION, PARTITION,
0, 0,
jsonString); jsonString);
//ASSERT
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId); TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId);
@ -311,15 +307,11 @@ class TradingClearingRegistryServiceTest {
tradingClearingRegistryDeleteRequest.setId(registryId); tradingClearingRegistryDeleteRequest.setId(registryId);
String jsonString = getJsonStringForDelete(tradingClearingRegistryDeleteRequest, 0); String jsonString = getJsonStringForDelete(tradingClearingRegistryDeleteRequest, 0);
//ACT
addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(), addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(),
Consts.DESTINATION_TRADING_CLEARING_REGISTRY_BLOCK, Consts.DESTINATION_TRADING_CLEARING_REGISTRY_BLOCK,
PARTITION, PARTITION,
0, 0,
jsonString); jsonString);
//ASSERT
waitingSendAndCheckRecord(0L, mockProducer); waitingSendAndCheckRecord(0L, mockProducer);
TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId); TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId);

View file

@ -0,0 +1,45 @@
package ru.spcex.clearing.account.service;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import ru.clearing.classes.statics.data.account.Account;
public class UtilsTest {
@Test
public void testAccount() {
Long currencyCodeId = 1L;
String withTrailingZero = String.format("%03d", currencyCodeId);
String withTrailingZero2 = "%d%03d%08d%d".formatted(39911, currencyCodeId, 1, 7000);
List<Account> allInfoAcc = new ArrayList<>();
Account account = new Account();
account.setAccount("39911051000000027000");
allInfoAcc.add(account);
Pattern accPattern = Pattern.compile("39911%s([0-9]{8})7000".formatted(withTrailingZero));
int maxN = 1;
int parsedCount = 0;
String lastAccount = null;
for (Account acc : allInfoAcc) {
try {
String number = acc.getAccount();
if (StringUtils.isEmpty(number)) continue;
lastAccount = number;
Matcher m = accPattern.matcher(number);
if (m.find()) {
String seqNumber = m.group(1);
if (StringUtils.isNotEmpty(seqNumber)) {
int accN = Integer.parseInt(seqNumber);
if (accN > maxN) maxN = accN;
}
parsedCount++;
}
} catch (Exception errParse) {
}
}
}
}

View file

@ -26,7 +26,6 @@ public class BackendApiApplication extends SpringBootServletInitializer {
@Override @Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
setKeycloakConfigFile(); setKeycloakConfigFile();
// springApplicationBuilder.initializers(DfaConfig.get().getLoggingInitializer());
return builder.sources(BackendApiApplication.class); return builder.sources(BackendApiApplication.class);
} }
@ -35,9 +34,6 @@ public class BackendApiApplication extends SpringBootServletInitializer {
return super.run(application); return super.run(application);
} }
/**
* чтобы переместить настройки keycloak в keycloak.json вместо application.properties
*/
private static void setKeycloakConfigFile() { private static void setKeycloakConfigFile() {
System.setProperty("keycloak.configurationFile", "classpath:keycloak.json"); System.setProperty("keycloak.configurationFile", "classpath:keycloak.json");
} }

View file

@ -47,9 +47,8 @@ public class BackEndApiImdgConfig {
throw new IllegalArgumentException("Property \"backend-api.hazelcast.cluster-members\" not set"); throw new IllegalArgumentException("Property \"backend-api.hazelcast.cluster-members\" not set");
} }
ImdgProvider imdg = new HazelcastService(taskExecutorHazelcastClientInitializer, ImdgProvider imdg = new HazelcastService(taskExecutorHazelcastClientInitializer,
taskExecutorIdGeneratorAwaiter, taskExecutorIdGeneratorAwaiter,
clientSetting.getHazelcast()); clientSetting.getHazelcast());
// todo корректное ожидание готовности imdg.waitAvailable();
return imdg; return imdg;
} }
@ -62,12 +61,10 @@ public class BackEndApiImdgConfig {
) { ) {
if (clientSetting.getHazelcastSearch() == null || clientSetting.getHazelcastSearch().getClusterMembers() == null) { if (clientSetting.getHazelcastSearch() == null || clientSetting.getHazelcastSearch().getClusterMembers() == null) {
log.warn("Property \"backend-api.hazelcast-search.cluster-members\" not set!"); log.warn("Property \"backend-api.hazelcast-search.cluster-members\" not set!");
// может работать без history, но history будет недоступна
} }
ImdgProvider imdg = new HazelcastService(taskExecutorHazelcastClientInitializer, ImdgProvider imdg = new HazelcastService(taskExecutorHazelcastClientInitializer,
taskExecutorIdGeneratorAwaiter, taskExecutorIdGeneratorAwaiter,
clientSetting.getHazelcastSearch()); clientSetting.getHazelcastSearch());
// todo корректное ожидание готовности imdg.waitAvailable();
return imdg; return imdg;
} }

View file

@ -22,7 +22,6 @@ import java.util.function.Consumer;
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
//todo remove? see ClearingCorsFilter
@CrossOrigin @CrossOrigin
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
private final MappingJackson2HttpMessageConverter customJsonHttpConverter; private final MappingJackson2HttpMessageConverter customJsonHttpConverter;

View file

@ -22,9 +22,6 @@ public abstract class AbstractQueueController {
return responseToClient; return responseToClient;
} }
/**
* Для оптимизации передачи userId
*/
protected <T> CudResponse processRequest(String destination, IAction<T> iAction, Long userId) throws ExecutionException, InterruptedException { protected <T> CudResponse processRequest(String destination, IAction<T> iAction, Long userId) throws ExecutionException, InterruptedException {
CudResponse responseToClient = new CudResponse(); CudResponse responseToClient = new CudResponse();
responseToClient.setPayload(operator.sendRequestToQueue(destination, iAction, userId)); responseToClient.setPayload(operator.sendRequestToQueue(destination, iAction, userId));

View file

@ -44,20 +44,9 @@ public class InformationAccountController extends AbstractQueueController {
@ResponseBody @ResponseBody
public CommonGetAllResponse getAll() { public CommonGetAllResponse getAll() {
Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(IMDGDistributedNames.Map_InformationAccount, Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(IMDGDistributedNames.Map_InformationAccount,
InformationAccount.class); InformationAccount.class);
CommonGetAllResponse response = new CommonGetAllResponse(); CommonGetAllResponse response = new CommonGetAllResponse();
response.fromEntity(all); response.fromEntity(all);
return response; return response;
} }
// @ApiOperation(value = "Добавление информационного счета.")
// @ApiResponses(value = {@ApiResponse(code = 200, message = "OK", response = CudResponse.class), @ApiResponse(code = 400, message = "Ошибка валидации", response = BasicSpcexResponse.class)})
// @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
// @ResponseBody
// public CudResponse add(
// @ApiParam(value = "Параметры команды в JSON формате.", required = true)
// @RequestBody AccountInformationNewAction accountNewInformationAction) throws ExecutionException, InterruptedException {
// return processRequest(Consts.DESTINATION_INFORMATION_ACCOUNT_NEW, accountNewInformationAction);
// }
} }

View file

@ -66,10 +66,9 @@ public class HistController {
} }
Optional<Class<? extends SpcexObjectBase>> entityClass = responseFactory.classByDestination(destination); Optional<Class<? extends SpcexObjectBase>> entityClass = responseFactory.classByDestination(destination);
//class may be added to HistorySubscription if needed
if (entityClass.isEmpty()) { if (entityClass.isEmpty()) {
throw new ActionValidationException(new EnumMessage(BackEndError.ValidationError, throw new ActionValidationException(new EnumMessage(BackEndError.ValidationError,
"destination " + "'" + destination + "' not supported (meta class not found)")); "destination " + "'" + destination + "' not supported (meta class not found)"));
} }
HistoryRequest req = new HistoryRequest(); HistoryRequest req = new HistoryRequest();
@ -82,10 +81,10 @@ public class HistController {
conditionProvider.conditionForRequest(req).map(s -> subscr[0] = s, p -> prdct[0] = p); conditionProvider.conditionForRequest(req).map(s -> subscr[0] = s, p -> prdct[0] = p);
Collection<Map<String, Object>> searchRes = stateLoader.getAllMetaTransform( Collection<Map<String, Object>> searchRes = stateLoader.getAllMetaTransform(
subscr[0].getSearchProxyMapName(), subscr[0].getSearchProxyMapName(),
subscr[0].getFullHistoryMapName(), subscr[0].getFullHistoryMapName(),
entityClass.get(), entityClass.get(),
prdct[0] prdct[0]
); );
CommonGetAllResponse response = new CommonGetAllResponse(); CommonGetAllResponse response = new CommonGetAllResponse();

View file

@ -58,7 +58,6 @@ public class ConditionProvider {
ImdgPredicate result; ImdgPredicate result;
if (predicates.size() == 0) { if (predicates.size() == 0) {
//add boundary conditions?
log.warn("destination '{}' zero predicates found", destination); log.warn("destination '{}' zero predicates found", destination);
result = pb.alwaysTrue(); result = pb.alwaysTrue();
} else if (predicates.size() == 1) { } else if (predicates.size() == 1) {

View file

@ -9,7 +9,6 @@ public class HistorySubscription {
private List<IHistoryCondition> conditions; private List<IHistoryCondition> conditions;
private String searchProxyMapName; private String searchProxyMapName;
private String fullHistoryMapName; private String fullHistoryMapName;
//class
public List<IHistoryCondition> getConditions() { public List<IHistoryCondition> getConditions() {

View file

@ -52,25 +52,21 @@ public class RegistryController extends AbstractQueueController {
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
@ResponseBody @ResponseBody
public CommonGetAllResponse getAll() { public CommonGetAllResponse getAll() {
// long t1 = System.currentTimeMillis();
ImdgPredicate filter = predicateBuilder.or( ImdgPredicate filter = predicateBuilder.or(
predicateBuilder.equals("registryDesignation", RegistryDesignation.A.getKey()), predicateBuilder.equals("registryDesignation", RegistryDesignation.A.getKey()),
predicateBuilder.equals("registryDesignation", RegistryDesignation.D.getKey()), predicateBuilder.equals("registryDesignation", RegistryDesignation.D.getKey()),
predicateBuilder.and( predicateBuilder.and(
predicateBuilder.or( predicateBuilder.or(
predicateBuilder.equals("registryDesignation", RegistryDesignation.O.getKey()), predicateBuilder.equals("registryDesignation", RegistryDesignation.O.getKey()),
predicateBuilder.equals("registryDesignation", RegistryDesignation.T.getKey()) predicateBuilder.equals("registryDesignation", RegistryDesignation.T.getKey())
), ),
predicateBuilder.greatEqual("settlementDate", LocalDate.now()) predicateBuilder.greatEqual("settlementDate", LocalDate.now())
) )
); );
Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(IMDGDistributedNames.Map_Registry, Registry.class, Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(IMDGDistributedNames.Map_Registry, Registry.class,
filter); filter);
// long t2 = System.currentTimeMillis();
// log.info("Info select and format {} data {}", all.size(), t2 - t1);
CommonGetAllResponse response = new CommonGetAllResponse(); CommonGetAllResponse response = new CommonGetAllResponse();
response.fromEntity(all); response.fromEntity(all);
// log.info("Info select and format {} data {}", all.size(), System.currentTimeMillis() - t2);
return response; return response;
} }

View file

@ -24,7 +24,6 @@ import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
// todo unittest for TradingClearingRegistryListController
@Controller @Controller
@RequestMapping("/trading-clearing-registries-list") @RequestMapping("/trading-clearing-registries-list")
public class TradingClearingRegistryListController extends AbstractQueueController { public class TradingClearingRegistryListController extends AbstractQueueController {
@ -42,8 +41,8 @@ public class TradingClearingRegistryListController extends AbstractQueueControll
@ResponseBody @ResponseBody
public CommonGetAllResponse getAll() { public CommonGetAllResponse getAll() {
Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform( Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(
IMDGDistributedNames.Map_TradingClearingRegistryList, IMDGDistributedNames.Map_TradingClearingRegistryList,
TradingClearingRegistryList.class); TradingClearingRegistryList.class);
CommonGetAllResponse response = new CommonGetAllResponse(); CommonGetAllResponse response = new CommonGetAllResponse();
response.fromEntity(all); response.fromEntity(all);
return response; return response;
@ -54,8 +53,8 @@ public class TradingClearingRegistryListController extends AbstractQueueControll
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody @ResponseBody
public CudResponse add( public CudResponse add(
@ApiParam(value = "Параметры команды в JSON формате.", required = true) @ApiParam(value = "Параметры команды в JSON формате.", required = true)
@RequestBody TradingClearingRegistryListNewAction tradingClearingRegistryListNewAction) throws ExecutionException, InterruptedException { @RequestBody TradingClearingRegistryListNewAction tradingClearingRegistryListNewAction) throws ExecutionException, InterruptedException {
return processRequest(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, tradingClearingRegistryListNewAction); return processRequest(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_NEW, tradingClearingRegistryListNewAction);
} }
@ -64,10 +63,10 @@ public class TradingClearingRegistryListController extends AbstractQueueControll
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody @ResponseBody
public CudResponse update( public CudResponse update(
@ApiParam(value = "Идентификатор изменяемого объекта.", required = true, example = "1234") @ApiParam(value = "Идентификатор изменяемого объекта.", required = true, example = "1234")
@PathVariable("id") Long id, @PathVariable("id") Long id,
@ApiParam(value = "Новые значения полей объекта.", required = true) @ApiParam(value = "Новые значения полей объекта.", required = true)
@RequestBody TradingClearingRegistryListUpdateAction tradingClearingRegistryListUpdateAction) throws ExecutionException, InterruptedException { @RequestBody TradingClearingRegistryListUpdateAction tradingClearingRegistryListUpdateAction) throws ExecutionException, InterruptedException {
tradingClearingRegistryListUpdateAction.setId(id); tradingClearingRegistryListUpdateAction.setId(id);
return processRequest(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, tradingClearingRegistryListUpdateAction); return processRequest(Consts.DESTINATION_TRADING_CLEARING_REGISTRIES_LIST_UPDATE, tradingClearingRegistryListUpdateAction);
} }

View file

@ -86,8 +86,6 @@ public class LauncherController extends AbstractQueueController {
} }
launcherCommand.setTask(dictionaryName); launcherCommand.setTask(dictionaryName);
launcherCommand.setUserId(user.getId()); launcherCommand.setUserId(user.getId());
//топики ограничиваются наличием в taskDictionary
//подписываются на разные топики в разных модулях, см. ru.spcex.platform.enumeration.Task#topic
return processRequest(Consts.LAUNCHER_NEW, launcherCommand); return processRequest(Consts.LAUNCHER_NEW, launcherCommand);
} }
@ -106,7 +104,7 @@ public class LauncherController extends AbstractQueueController {
} }
if (!IEnumKey.contains(taskEnum.getCode(), Task.startOfClearing, Task.dbfExport_OUTV, Task.getAllBalance, Task.createRegistry_GBRR)) { if (!IEnumKey.contains(taskEnum.getCode(), Task.startOfClearing, Task.dbfExport_OUTV, Task.getAllBalance, Task.createRegistry_GBRR)) {
log.warn(String.format("Task %s not support request with body", taskEnum.getCode())); log.warn(String.format("Task %s not support request with body", taskEnum.getCode()));
} // else В мете эти модели с дополнительными параметрами (OUTV). }
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = KeycloakUtils.getUserNameFromAuthentication(authentication); String username = KeycloakUtils.getUserNameFromAuthentication(authentication);
User user = userImdg.getFirstObjectByFieldValues(Map.of("identifier", username)); User user = userImdg.getFirstObjectByFieldValues(Map.of("identifier", username));

View file

@ -20,9 +20,6 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
/**
* SecurityController и MoneyMarketSecurityController разные контроллеры, не путать.
*/
@Controller @Controller
@RequestMapping("/securities") @RequestMapping("/securities")
public class SecurityController { public class SecurityController {
@ -40,16 +37,16 @@ public class SecurityController {
public CommonGetAllResponse getAll() { public CommonGetAllResponse getAll() {
Collection<Map<String, Object>> all = new ArrayList<>(); Collection<Map<String, Object>> all = new ArrayList<>();
all.addAll(stateLoader.getAllMetaTransformSpecificClass( all.addAll(stateLoader.getAllMetaTransformSpecificClass(
IMDGDistributedNames.Map_MoneyMarketSecurity, MoneyMarketSecurity.class IMDGDistributedNames.Map_MoneyMarketSecurity, MoneyMarketSecurity.class
)); ));
all.addAll(stateLoader.getAllMetaTransformSpecificClass( all.addAll(stateLoader.getAllMetaTransformSpecificClass(
IMDGDistributedNames.Map_FixedIncomeSecurity, FixedIncomeSecurity.class IMDGDistributedNames.Map_FixedIncomeSecurity, FixedIncomeSecurity.class
)); ));
all.addAll(stateLoader.getAllMetaTransformSpecificClass( all.addAll(stateLoader.getAllMetaTransformSpecificClass(
IMDGDistributedNames.Map_EquitySecurity, EquitySecurity.class IMDGDistributedNames.Map_EquitySecurity, EquitySecurity.class
)); ));
all.addAll(stateLoader.getAllMetaTransformSpecificClass( all.addAll(stateLoader.getAllMetaTransformSpecificClass(
IMDGDistributedNames.Map_CurrencyPairSecurity, EquitySecurity.class IMDGDistributedNames.Map_CurrencyPairSecurity, EquitySecurity.class
)); ));
CommonGetAllResponse response = new CommonGetAllResponse(); CommonGetAllResponse response = new CommonGetAllResponse();
response.fromEntity(all); response.fromEntity(all);

View file

@ -90,10 +90,6 @@ public class UserController extends AbstractQueueController {
log.warn("user {} sended update request for user {}", username, userUpdateAction.getUsername()); log.warn("user {} sended update request for user {}", username, userUpdateAction.getUsername());
throw new IllegalStateException("cannot perform delete action for " + username); throw new IllegalStateException("cannot perform delete action for " + username);
} }
// User user = userImdg.getSingleObjectByFieldValues(Map.of("identifier", username));
// if (user == null) {
// log.info("update user {} authenticated, but User object was not created", username);
// }
return processRequest(Consts.USER_UPDATE, userUpdateAction); return processRequest(Consts.USER_UPDATE, userUpdateAction);
} }

View file

@ -58,8 +58,6 @@ public class StatementController extends AbstractQueueController {
Optional<Statement> statement = stateLoader.getById(id, IMDGDistributedNames.Map_Statement, Statement.class); Optional<Statement> statement = stateLoader.getById(id, IMDGDistributedNames.Map_Statement, Statement.class);
CommonGetByIdResponse response = new CommonGetByIdResponse(); CommonGetByIdResponse response = new CommonGetByIdResponse();
if (statement.isEmpty()) { if (statement.isEmpty()) {
//можно так, либо response.setCode(404); response.setMessage("blabla"); но тогда еще нужно
//отдельно HTTP статус проставлять
throw new NotFound404Exception(String.valueOf(id)); throw new NotFound404Exception(String.valueOf(id));
} }
Statement stmt = statement.get(); Statement stmt = statement.get();

View file

@ -15,16 +15,12 @@ public class TradingClearingRegistryListNewAction implements IAction<TradingClea
@ApiModelProperty(value = "Идентификатор валютного счёта", example = "123") @ApiModelProperty(value = "Идентификатор валютного счёта", example = "123")
@JsonProperty @JsonProperty
private Long accountId; private Long accountId;
// @ApiModelProperty(value = "Наименование статуса", example = "ACTV", required = false)
// @JsonProperty
// private String status;
@Override @Override
public TradingClearingRegistryListNewRequest toRequest() { public TradingClearingRegistryListNewRequest toRequest() {
var req = new TradingClearingRegistryListNewRequest(); var req = new TradingClearingRegistryListNewRequest();
req.setTradingClearingRegistryId(this.tradingClearingRegistryId); req.setTradingClearingRegistryId(this.tradingClearingRegistryId);
req.setAccountId(this.accountId); req.setAccountId(this.accountId);
// req.setStatus(this.status);
return req; return req;
} }

View file

@ -25,12 +25,6 @@ public class CurrencyPairSecurityNewAction implements IAction<CurrencyPairSecuri
@ApiModelProperty(value = "Валютная пара", example = "1234") @ApiModelProperty(value = "Валютная пара", example = "1234")
@JsonProperty @JsonProperty
public Long currencyPairId; public Long currencyPairId;
// @ApiModelProperty(value = "Размер лота", example = "12.33")
// @JsonProperty
// public BigDecimal lotSize;
// @ApiModelProperty(value = "Шаг цены", example = "12.33")
// @JsonProperty
// public BigDecimal minStep;
@ApiModelProperty(value = "Количество валюты лота", example = "12.33") @ApiModelProperty(value = "Количество валюты лота", example = "12.33")
@JsonProperty @JsonProperty
public BigDecimal baseUnitSize; public BigDecimal baseUnitSize;
@ -52,8 +46,6 @@ public class CurrencyPairSecurityNewAction implements IAction<CurrencyPairSecuri
req.setShortName(this.getShortName()); req.setShortName(this.getShortName());
req.setFullName(this.getFullName()); req.setFullName(this.getFullName());
req.setCurrencyPairId(this.getCurrencyPairId()); req.setCurrencyPairId(this.getCurrencyPairId());
// req.setLotSize(this.getLotSize());
// req.setMinStep(this.getMinStep());
req.setBaseUnitSize(this.getBaseUnitSize()); req.setBaseUnitSize(this.getBaseUnitSize());
req.setSettlementType(this.getSettlementType()); req.setSettlementType(this.getSettlementType());
req.setWorkflowStatus(this.getWorkflowStatus()); req.setWorkflowStatus(this.getWorkflowStatus());

View file

@ -29,12 +29,6 @@ public class CurrencyPairSecurityUpdateAction implements IAction<CurrencyPairSec
@ApiModelProperty(value = "Валютная пара", example = "1234") @ApiModelProperty(value = "Валютная пара", example = "1234")
@JsonProperty @JsonProperty
public Long currencyPairId; public Long currencyPairId;
// @ApiModelProperty(value = "Размер лота", example = "12.33")
// @JsonProperty
// public BigDecimal lotSize;
// @ApiModelProperty(value = "Шаг цены", example = "12.33")
// @JsonProperty
// public BigDecimal minStep;
@ApiModelProperty(value = "Количество валюты лота", example = "12.33") @ApiModelProperty(value = "Количество валюты лота", example = "12.33")
@JsonProperty @JsonProperty
public BigDecimal baseUnitSize; public BigDecimal baseUnitSize;
@ -57,8 +51,6 @@ public class CurrencyPairSecurityUpdateAction implements IAction<CurrencyPairSec
req.setShortName(this.getShortName()); req.setShortName(this.getShortName());
req.setFullName(this.getFullName()); req.setFullName(this.getFullName());
req.setCurrencyPairId(this.getCurrencyPairId()); req.setCurrencyPairId(this.getCurrencyPairId());
// req.setLotSize(this.getLotSize());
// req.setMinStep(this.getMinStep());
req.setBaseUnitSize(this.getBaseUnitSize()); req.setBaseUnitSize(this.getBaseUnitSize());
req.setSettlementType(this.getSettlementType()); req.setSettlementType(this.getSettlementType());
req.setWorkflowStatus(this.getWorkflowStatus()); req.setWorkflowStatus(this.getWorkflowStatus());

View file

@ -51,25 +51,6 @@ public class CompanyBackendGetAll extends BasicSpcexResponse {
singleItem.setFullName(company.getFullName()); singleItem.setFullName(company.getFullName());
singleItem.setCreated(company.getCreated()); singleItem.setCreated(company.getCreated());
singleItem.setUpdated(company.getUpdated()); singleItem.setUpdated(company.getUpdated());
// CompanyInfo profile = company.getProfile();
// if (profile != null) {
// singleItem.setCorporationSoleType(profile.getCorporationSoleType());
// singleItem.setCountryCode(profile.getCountryCode());
// singleItem.setDescription(profile.getDescription());
// singleItem.setProfessionalSign(profile.getProfessionalSign());
// singleItem.setLegalKind(profile.getLegalKind());
// singleItem.setOrganizationType(profile.getOrganizationType());
// singleItem.setResidence(profile.getResidence());
// singleItem.setShortNameEng(profile.getShortNameEng());
// singleItem.setFullNameEng(profile.getFullNameEng());
// }
/* todo
CompanySymbol companySymbol = ;
if (companySymbol!=null) {
singleItem.setCompanySymbol(profile.getCompanySymbol());
singleItem.setCompanySymbolValue(profile.getCompanySymbolValue());
}*/
payload.getItems().add(singleItem); payload.getItems().add(singleItem);
} }

View file

@ -6,12 +6,6 @@ import io.swagger.annotations.ApiModelProperty;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry; import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.spcex.clearing.backendapi.controller.response.BasicSpcexResponse; import ru.spcex.clearing.backendapi.controller.response.BasicSpcexResponse;
/**
* Банковские реквизиты для перечисления денежных средств
*
* @ApiModel(description = "Ответ в результате отправки операции в топик Kafka.")
* @ApiModelProperty(value = "Информация о принятом запросе")
**/
@ApiModel(description = "Ответ при получении объекта TradingClearingRegistry.") @ApiModel(description = "Ответ при получении объекта TradingClearingRegistry.")
public class TradingClearingRegistryBackendGetById extends BasicSpcexResponse { public class TradingClearingRegistryBackendGetById extends BasicSpcexResponse {

View file

@ -9,11 +9,6 @@ import ru.spcex.clearing.platform.messaging.domain.json.serialize.EnumSerializer
import ru.spcex.clearing.platform.messaging.service.Status; import ru.spcex.clearing.platform.messaging.service.Status;
/**
* Банковские реквизиты для перечисления денежных средств
* @ApiModel(description = "Ответ в результате отправки операции в топик Kafka.")
* @ApiModelProperty(value = "Информация о принятом запросе")
**/
@ApiModel(description = "Ответ при получении статуса запроса.") @ApiModel(description = "Ответ при получении статуса запроса.")
public class RequestInfoResponse extends BasicSpcexResponse { public class RequestInfoResponse extends BasicSpcexResponse {

View file

@ -19,18 +19,14 @@ import java.io.IOException;
public class ClearingCorsFilter extends OncePerRequestFilter { public class ClearingCorsFilter extends OncePerRequestFilter {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log = LoggerFactory.getLogger(getClass());
// private final AConfigurationProperties configuration; private final String[] meth = new String[]{};
//todo cors settings private final String[] orig = new String[]{};
private final String[] meth = new String[] {};//"*"
private final String[] orig = new String[] {};//"/**"
private final String[] head = new String[] {}; private final String[] head = new String[] {};
private final CorsAllowedOriginsService allowedOriginsService; private final CorsAllowedOriginsService allowedOriginsService;
public ClearingCorsFilter( public ClearingCorsFilter(
// AConfigurationProperties configuration, CorsAllowedOriginsService allowedOriginsService
CorsAllowedOriginsService allowedOriginsService
) { ) {
// this.configuration = configuration;
this.allowedOriginsService = allowedOriginsService; this.allowedOriginsService = allowedOriginsService;
} }
@ -63,21 +59,7 @@ public class ClearingCorsFilter extends OncePerRequestFilter {
log.trace("cors filter -> effectiveOrigin={}", effectiveOrigin); log.trace("cors filter -> effectiveOrigin={}", effectiveOrigin);
if (effectiveOrigin != null) { if (effectiveOrigin != null) {
setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_ORIGIN, effectiveOrigin); setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_ORIGIN, effectiveOrigin);
// String methods;
// if (meth.length > 0) {
// methods = String.join(", ", meth).toUpperCase(Locale.ROOT);
// } else {
// methods = "*";
// }
setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_METHODS, "*"); setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_METHODS, "*");
// String headers;
// if (head.length > 0) {
// headers = String.join(", ", head).toLowerCase(Locale.ROOT);
// } else {
// headers = "*";
// }
setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_HEADERS, "*"); setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_HEADERS, "*");
setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); setHeaderValue(httpServletResponse, H_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

View file

@ -12,7 +12,6 @@ public class CorsAllowedOriginsService {
private final List<Pattern> originPatterns = new ArrayList<>(); private final List<Pattern> originPatterns = new ArrayList<>();
//todo cors settings
public CorsAllowedOriginsService() { public CorsAllowedOriginsService() {
for (String originRegex : new String[]{".*"}) { for (String originRegex : new String[]{".*"}) {
originPatterns.add(Pattern.compile(originRegex)); originPatterns.add(Pattern.compile(originRegex));

View file

@ -22,8 +22,6 @@ public class ActionElement {
@JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonInclude(JsonInclude.Include.NON_EMPTY)
private Boolean isArray = null; private Boolean isArray = null;
// @JsonProperty(value = "fields", required = true)
// private List<Map<String, ActionField>> fields = new LinkedList<>();
@JsonProperty(value = "fields", required = true) @JsonProperty(value = "fields", required = true)
private List<ActionField> fields = new LinkedList<>(); private List<ActionField> fields = new LinkedList<>();

View file

@ -10,9 +10,6 @@ import ru.spcex.clearing.platform.messaging.domain.Consts;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
* todo временная заглушка: нужно добавить парсинг meta.xml и получать инфу оттуда
*/
@Service @Service
public class CudMetaService { public class CudMetaService {
private final Map<String, Class<? extends IAction<?>>> mapping; private final Map<String, Class<? extends IAction<?>>> mapping;

View file

@ -58,10 +58,6 @@ public abstract class FieldExtracted {
if (result == null) if (result == null)
break; break;
} }
//fixme somehow externalize custom serialization for type
// тут нужно вернуть список id объектов а не список самих объектов для случая
// - add(r, "addresseeId", o.getAddressee() == null ? null : o.getAddressee().stream().map(ObjectBase::getId).collect(Collectors.toSet()), fieldFilter);
if (result instanceof Set && ((Set) result).size() > 0) { if (result instanceof Set && ((Set) result).size() > 0) {
try { try {
Set t = new HashSet(); Set t = new HashSet();
@ -70,7 +66,7 @@ public abstract class FieldExtracted {
t.add(citem.getMethod(RfHelper.GETTER_NAME_ID).invoke(item)); t.add(citem.getMethod(RfHelper.GETTER_NAME_ID).invoke(item));
} }
result = t; result = t;
} catch (Throwable ignored) {// вернем сами объекты } catch (Throwable ignored) {
} }
} else if (result instanceof LocalDate) { } else if (result instanceof LocalDate) {
result = result.toString(); result = result.toString();

View file

@ -31,13 +31,10 @@ public class GetResponseFactory {
public Collection<Map<String, Object>> responseFromObjectCollection(Collection<?> o) { public Collection<Map<String, Object>> responseFromObjectCollection(Collection<?> o) {
return o.stream() return o.stream()
.map(this::responseFromObject) .map(this::responseFromObject)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/**
* dictionaryName - это имя тэга внутри <enum>
*/
public Map<String, Object> responseFromDictionary(String dictionaryName, Object o) { public Map<String, Object> responseFromDictionary(String dictionaryName, Object o) {
ObjectExtracted objectExtracted = meta.getEnumsExtractedByTagName().get(dictionaryName); ObjectExtracted objectExtracted = meta.getEnumsExtractedByTagName().get(dictionaryName);
if (objectExtracted == null) { if (objectExtracted == null) {
@ -54,16 +51,10 @@ public class GetResponseFactory {
return responseFromObjectExtracted(o, objExtr); return responseFromObjectExtracted(o, objExtr);
} }
/**
* Варианты методов с Class сделаны для сценариев, когда хотим распарсить объект,
* по мете для родительского класса объекта
* Т.е. вместо извлечение класса o.getClass, берем clazz извне. clazz - base class для o
*
*/
public <T> Collection<Map<String, Object>> responseFromObjectCollection(Collection<?> o, Class<T> clazz) { public <T> Collection<Map<String, Object>> responseFromObjectCollection(Collection<?> o, Class<T> clazz) {
return o.stream() return o.stream()
.map((Function<Object, Map<String, Object>>) o1 -> responseFromObject(o1, clazz)) .map((Function<Object, Map<String, Object>>) o1 -> responseFromObject(o1, clazz))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public <T> Map<String, Object> responseFromObject(Object o, Class<T> clazz) { public <T> Map<String, Object> responseFromObject(Object o, Class<T> clazz) {
@ -83,20 +74,18 @@ public class GetResponseFactory {
continue; continue;
} }
currentField = field; currentField = field;
// if (fieldsToAdd.contains(field.getField().getCode())) { try {
try { add(r, field, field.extractValue(o));
add(r, field, field.extractValue(o)); } catch (Throwable e) {
} catch (Throwable e) { log.trace(ExceptionUtils.getStackTrace(
log.trace(ExceptionUtils.getStackTrace( new RuntimeException(String.format("Can't extract value for field='%s' of %s(%s): %s -> %s\n%s",
new RuntimeException(String.format("Can't extract value for field='%s' of %s(%s): %s -> %s\n%s", field.getField().getCode(),
field.getField().getCode(), o.getClass().getSimpleName(), objExtr.getClassName(),
o.getClass().getSimpleName(), objExtr.getClassName(), e.getClass().getSimpleName(), e.getLocalizedMessage(),
e.getClass().getSimpleName(), e.getLocalizedMessage(), currentField.toString()
currentField.toString() )))
))) );
); }
}
// }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e)); log.error(ExceptionUtils.getStackTrace(e));
@ -145,48 +134,7 @@ public class GetResponseFactory {
} }
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss+03:00") .ofPattern("yyyy-MM-dd'T'HH:mm:ss+03:00")
.withLocale(Locale.US) .withLocale(Locale.US)
.withZone(ZoneId.of("Europe/Moscow")); .withZone(ZoneId.of("Europe/Moscow"));
// public Map<String, Object> newX(Object o, Collection<String> fieldFilter, String destination) {
// ObjectExtracted targetClazz = getTargetClazz(o, destination);
// if (targetClazz == null)
// throw new FrontendException(String.format("Unknown response class: %s", o.getClass().getName()));
// Collection<String> fieldsToAdd = getFilteredFields(targetClazz, fieldFilter);
// Map<String, Object> r = new LinkedHashMap<>();
// FieldExtracted currentField = null;
// try {
// for (FieldExtracted field : targetClazz.getFields()) {
// if (field.getField().isVirtual() != null && field.getField().isVirtual()) {
// continue;
// }
// currentField = field;
// if (fieldsToAdd.contains(field.getField().getCode())) {
// try {
// add(r, field.getField().getCode(), field.extractValue(o));
// } catch (Throwable e) {
// log.warn(ExceptionUtils.getStackTrace(
// new FrontendException(String.format("Can't extract value for field='%s' of %s(%s): %s -> %s\n%s",
// field.getField().getCode(),
// o.getClass().getSimpleName(), targetClazz.getClazz().getSimpleName(),
// e.getClass().getSimpleName(), e.getLocalizedMessage(),
// JsonHelper.writeAnyClassToLog(currentField)
// )))
// );
// }
// }
// }
// } catch (FrontendException e) {
// throw e;
// } catch (Throwable e) {
// throw new FrontendException(String.format("Can't get field of %s(%s): %s -> %s\n%s",
// o.getClass().getSimpleName(), targetClazz.getClazz().getSimpleName(),
// e.getClass().getSimpleName(), e.getLocalizedMessage(),
// JsonHelper.writeAnyClassToLog(currentField)
// ));
// }
// return r;
// }
} }

View file

@ -39,10 +39,10 @@ public class MetaServer extends MetaBase {
try { try {
Map<String, ObjectElement> objects = getObjects(); Map<String, ObjectElement> objects = getObjects();
log.info("Meta objects:\n{}", log.info("Meta objects:\n{}",
objects.values() objects.values()
.stream() .stream()
.map(ObjectElement::getName) .map(ObjectElement::getName)
.collect(Collectors.joining(";", "[", "]"))); .collect(Collectors.joining(";", "[", "]")));
for (String key : objects.keySet()) { for (String key : objects.keySet()) {
ObjectExtracted oe; ObjectExtracted oe;
ObjectElement objectElement = objects.get(key); ObjectElement objectElement = objects.get(key);
@ -85,8 +85,8 @@ public class MetaServer extends MetaBase {
log.warn("META SERVER >>> {}", e.getLocalizedMessage()); log.warn("META SERVER >>> {}", e.getLocalizedMessage());
continue; continue;
} }
String actionDestination = // обычно бывают =null о этому эффективнее по имени класса а не по: objectElement.getSubscription().destination + "/"+ actionElement.getDestination(); String actionDestination =
oe.getClassName(); oe.getClassName();
actionObjectsExtracted.put(actionDestination, oe); actionObjectsExtracted.put(actionDestination, oe);
} }
} }
@ -104,20 +104,6 @@ public class MetaServer extends MetaBase {
log.warn("{} {}", key, ExceptionUtils.getStackTrace(e)); log.warn("{} {}", key, ExceptionUtils.getStackTrace(e));
continue; continue;
} }
/**
* можно было бы хранить только для нестандартных словарей (где не только id, name, code)
*/
// List<FieldExtracted> dictFields = oe.getFields();
// boolean add = false;
// for (FieldExtracted dictField : dictFields) {
// if (!dictionaryDefaultFields.contains(dictField.getMemberName())) {
// add = true;
// break;
// }
// }
// if (add) {
// enumsExtractedByTagName.put(key, oe);
// }
enumsExtractedByTagName.put(key, oe); enumsExtractedByTagName.put(key, oe);
} }
@ -130,7 +116,6 @@ public class MetaServer extends MetaBase {
if (!RfHelper.isAbstract(o.getClazz())) { if (!RfHelper.isAbstract(o.getClazz())) {
try { try {
Object instance = newInstance(o.getClassName()); Object instance = newInstance(o.getClassName());
// создается успешно.
} catch (Throwable e) { } catch (Throwable e) {
log.warn("META SERVER >>> Не удается создать класс {} !", o.getClassName()); log.warn("META SERVER >>> Не удается создать класс {} !", o.getClassName());
} }
@ -142,32 +127,8 @@ public class MetaServer extends MetaBase {
throw new ClearingMetaServerValidationException(e.getLocalizedMessage()); throw new ClearingMetaServerValidationException(e.getLocalizedMessage());
} }
} }
//
// for (ObjectExtracted o : this.actionObjectsExtracted.values()) {
// try {
// if (!RfHelper.isAbstract(o.getClazz())) {
// try {
// Object instance = newInstance(o.getClassName());
// // создается успешно.
// } catch (Throwable e) {
// log.warn("META SERVER ACTION >>> Не удается создать класс {} !", o.getClassName());
// }
// }
// validateGetterForObject(o);
// } catch (ClrxMetaServerGetterNotFoundException e) {
// throw e;
// } catch (Throwable e) {
// throw new ClearingMetaServerValidationException(e.getLocalizedMessage());
// }
// }
} }
/**
* проверим наличие геттеров к полям
*
* @param o
* @throws ClassNotFoundException
*/
private void validateGetterForObject(ObjectExtracted o) throws ClassNotFoundException { private void validateGetterForObject(ObjectExtracted o) throws ClassNotFoundException {
for (FieldExtracted field : o.getFields()) { for (FieldExtracted field : o.getFields()) {
Class<?> c = o.getClazz(); Class<?> c = o.getClazz();

View file

@ -47,7 +47,7 @@ public class RfHelper {
Class<?> raw = Class.forName(((ParameterizedType) t).getRawType().getTypeName()); Class<?> raw = Class.forName(((ParameterizedType) t).getRawType().getTypeName());
if (BUSINESS_OBJECT_REF.equals(raw.getSimpleName())) { if (BUSINESS_OBJECT_REF.equals(raw.getSimpleName())) {
return Class.forName(((ParameterizedType) t).getActualTypeArguments()[0].getTypeName()); return Class.forName(((ParameterizedType) t).getActualTypeArguments()[0].getTypeName());
} else if ("Set".equals(raw.getSimpleName())) { // множества пока не распаковываем } else if ("Set".equals(raw.getSimpleName())) {
return Class.forName(raw.getName()); return Class.forName(raw.getName());
} }
} }

View file

@ -85,7 +85,6 @@ public class KeycloakRestTemplateAuthenticationProvider implements Authenticatio
throw new AuthenticationServiceException("keycloak direct access grant auth failed: bad token"); throw new AuthenticationServiceException("keycloak direct access grant auth failed: bad token");
} }
AccessToken accessToken = AdapterTokenVerifier.verifyToken(accessTokenString, deployment); AccessToken accessToken = AdapterTokenVerifier.verifyToken(accessTokenString, deployment);
//todo cors settings
accessToken.setAllowedOrigins(Collections.singleton("*")); accessToken.setAllowedOrigins(Collections.singleton("*"));
RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, accessTokenString, accessToken, null, null, refreshTokenString); RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, accessTokenString, accessToken, null, null, refreshTokenString);
@ -93,21 +92,21 @@ public class KeycloakRestTemplateAuthenticationProvider implements Authenticatio
final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>(principalName, skSession); final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>(principalName, skSession);
Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession); Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession);
Set<String> effectiveRoles = roles Set<String> effectiveRoles = roles
.stream() .stream()
.map(s -> { .map(s -> {
UserRole userRole = roleMapping.get(s); UserRole userRole = roleMapping.get(s);
return userRole != null ? userRole.getKey() : null; return userRole != null ? userRole.getKey() : null;
}) })
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
List<SimpleGrantedAuthority> realmRoles = effectiveRoles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); List<SimpleGrantedAuthority> realmRoles = effectiveRoles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
final KeycloakAccount account = new SimpleKeycloakAccount(principal, effectiveRoles, skSession); final KeycloakAccount account = new SimpleKeycloakAccount(principal, effectiveRoles, skSession);
KeycloakAuthenticationToken keycloakAuthenticationToken = new KeycloakAuthenticationToken(account, false, realmRoles); KeycloakAuthenticationToken keycloakAuthenticationToken = new KeycloakAuthenticationToken(account, false, realmRoles);
keycloakAuthenticationToken.setAuthenticated(true); keycloakAuthenticationToken.setAuthenticated(true);
log.debug("login successful: login {}, roles from keycloak: {}; effective roles {}", log.debug("login successful: login {}, roles from keycloak: {}; effective roles {}",
authentication.getName(), authentication.getName(),
String.join(";", roles), String.join(";", roles),
String.join(";", effectiveRoles) String.join(";", effectiveRoles)
); );
return keycloakAuthenticationToken; return keycloakAuthenticationToken;

View file

@ -10,20 +10,17 @@ import org.springframework.security.core.Authentication;
public class KeycloakUtils { public class KeycloakUtils {
static Logger log = LoggerFactory.getLogger(KeycloakUtils.class); static Logger log = LoggerFactory.getLogger(KeycloakUtils.class);
/**
* Достать username из Keycloak имплементации Authentication
*/
public static String getUserNameFromAuthentication(Authentication authentication) { public static String getUserNameFromAuthentication(Authentication authentication) {
if (authentication == null) return null; if (authentication == null) return null;
if (!(authentication instanceof KeycloakAuthenticationToken)) { // AnonymousAuthenticationToken if (!(authentication instanceof KeycloakAuthenticationToken)) {
log.trace("Authentication token class {} is not KeycloakAuthenticationToken", authentication.getClass().getName()); log.trace("Authentication token class {} is not KeycloakAuthenticationToken", authentication.getClass().getName());
return null; return null;
} }
KeycloakAuthenticationToken auth = (KeycloakAuthenticationToken) authentication; KeycloakAuthenticationToken auth = (KeycloakAuthenticationToken) authentication;
KeycloakAccount details = (KeycloakAccount) auth.getDetails(); KeycloakAccount details = (KeycloakAccount) auth.getDetails();
return ((KeycloakPrincipal) details.getPrincipal()) return ((KeycloakPrincipal) details.getPrincipal())
.getKeycloakSecurityContext() .getKeycloakSecurityContext()
.getToken() .getToken()
.getPreferredUsername(); .getPreferredUsername();
} }
} }

View file

@ -20,11 +20,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.Map; import java.util.Map;
/**
* при bearer only false
* клиент сюда не попадает
* срабатывает KeycloakAuthenticationProvider с редиректом на логин keycloak
*/
@Controller @Controller
@RequestMapping("/sso") @RequestMapping("/sso")
public class LoginController { public class LoginController {
@ -44,31 +39,31 @@ public class LoginController {
String login = httpServletRequest.getHeader("clearing-login"); String login = httpServletRequest.getHeader("clearing-login");
String password = httpServletRequest.getHeader("clearing-password"); String password = httpServletRequest.getHeader("clearing-password");
HttpEntity<MultiValueMap<String, String>> request = HttpEntity<MultiValueMap<String, String>> request =
new TokenRequest.Builder() new TokenRequest.Builder()
.username(login) .username(login)
.password(password) .password(password)
.build(); .build();
ResponseEntity<String> response = restTemplate.postForEntity( ResponseEntity<String> response = restTemplate.postForEntity(
"http://10.200.200.147:8080/realms/master/protocol/openid-connect/token", "http://10.200.200.147:8080/realms/master/protocol/openid-connect/token",
request, String.class); request, String.class);
return null; return null;
} }
@RequestMapping(value = "/login", method = RequestMethod.GET) @RequestMapping(value = "/login", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public KeycloakAuthResponse getExample(HttpServletRequest httpServletRequest, public KeycloakAuthResponse getExample(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws JsonProcessingException { HttpServletResponse httpServletResponse) throws JsonProcessingException {
RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) httpServletRequest.getSession().getAttribute(KeycloakSecurityContext.class.getName()); RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) httpServletRequest.getSession().getAttribute(KeycloakSecurityContext.class.getName());
String login = httpServletRequest.getHeader("clearing-login"); String login = httpServletRequest.getHeader("clearing-login");
String password = httpServletRequest.getHeader("clearing-password"); String password = httpServletRequest.getHeader("clearing-password");
HttpEntity<MultiValueMap<String, String>> request = HttpEntity<MultiValueMap<String, String>> request =
new TokenRequest.Builder() new TokenRequest.Builder()
.username(login) .username(login)
.password(password) .password(password)
.build(); .build();
ResponseEntity<String> response = restTemplate.postForEntity( ResponseEntity<String> response = restTemplate.postForEntity(
"http://10.200.200.147:8080/realms/master/protocol/openid-connect/token", "http://10.200.200.147:8080/realms/master/protocol/openid-connect/token",
request, String.class); request, String.class);
KeycloakAuthResponse authInfo = json.readValue(response.getBody(), KeycloakAuthResponse.class); KeycloakAuthResponse authInfo = json.readValue(response.getBody(), KeycloakAuthResponse.class);
return authInfo; return authInfo;
} }

View file

@ -17,14 +17,11 @@ public class RestTemplateConfig {
this.builder = builder; this.builder = builder;
} }
/**
* В настоящий момент используется для выгрузки AFS данных
*/
@Bean("clearing-rest") @Bean("clearing-rest")
public RestTemplate restTemplate() { public RestTemplate restTemplate() {
return builder return builder
.setConnectTimeout(Duration.ofMillis(10000)) .setConnectTimeout(Duration.ofMillis(10000))
.setReadTimeout(Duration.ofMillis(40000)) .setReadTimeout(Duration.ofMillis(40000))
.build(); .build();
} }
} }

View file

@ -5,10 +5,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class SimpleUserDetailService public class SimpleUserDetailService {
// implements UserDetailsService
{
// @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return null; return null;
} }

View file

@ -52,11 +52,7 @@ public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
super.configure(http); super.configure(http);
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl anyReq = http ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl anyReq = http
// .formLogin() .cors()
// .loginProcessingUrl("/backend-api-login/perform-login")
// .and()
//todo remove? see ClearingCorsFilter
.cors()
.and() .and()
.csrf().disable() .csrf().disable()
.authorizeRequests() .authorizeRequests()
@ -84,7 +80,6 @@ public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Bean @Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults() { public GrantedAuthorityDefaults grantedAuthorityDefaults() {
// Remove the ROLE_ prefix
return new GrantedAuthorityDefaults(""); return new GrantedAuthorityDefaults("");
} }

View file

@ -8,16 +8,5 @@ import java.util.concurrent.ExecutionException;
public interface IOperator { public interface IOperator {
QueueSuccessResponse sendRequestToQueue(String destination, IAction<?> iAction, boolean appendUserId) throws ExecutionException, InterruptedException; QueueSuccessResponse sendRequestToQueue(String destination, IAction<?> iAction, boolean appendUserId) throws ExecutionException, InterruptedException;
/**
* Для оптимизации проставления userId.
* Аналог sendRequestToQueue(String destination, IAction<?> iAction, true)
*
* @param destination
* @param iAction
* @param userId совершивший запрос
* @return
* @throws ExecutionException
* @throws InterruptedException
*/
QueueSuccessResponse sendRequestToQueue(String destination, IAction<?> iAction, Long userId) throws ExecutionException, InterruptedException; QueueSuccessResponse sendRequestToQueue(String destination, IAction<?> iAction, Long userId) throws ExecutionException, InterruptedException;
} }

View file

@ -7,19 +7,22 @@ import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
/**
* сделал чтобы не привязывать все контроллеры к Imdg API
*/
public interface IStateLoader { public interface IStateLoader {
<T extends SpcexObjectBase> Optional<T> getById(Long id, String mapName, Class<T> clazz); <T extends SpcexObjectBase> Optional<T> getById(Long id, String mapName, Class<T> clazz);
<T extends SpcexObjectBase> Collection<T> getAll(String mapName, Class<T> clazz); <T extends SpcexObjectBase> Collection<T> getAll(String mapName, Class<T> clazz);
<T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz); <T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz);
<T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransformSpecificClass(String mapName, Class<T> clazz); <T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransformSpecificClass(String mapName, Class<T> clazz);
<T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz, Map<String, ? extends Comparable<?>> conditions); <T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz, Map<String, ? extends Comparable<?>> conditions);
<T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz, ImdgPredicate conditions); <T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(String mapName, Class<T> clazz, ImdgPredicate conditions);
<T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform( <T extends SpcexObjectBase> Collection<Map<String, Object>> getAllMetaTransform(
String searchMapName, String searchMapName,
String mapName, String mapName,
Class<T> clazz, Class<T> clazz,
ImdgPredicate conditions); ImdgPredicate conditions);
} }

View file

@ -14,10 +14,6 @@ import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider; import ru.spcex.platform.imdg.api.ImdgProvider;
/**
* Сервис для сигнализирования результатов запросов клиентов. Ассинхронное обновление статуса.
* Клиент запрашивает периодически (или по событию) таблицу Map_RequestInfo и видит результат выполнения запросов.
*/
@Service @Service
public class RequestInfoAccepter extends QueueConsumer implements InitializingBean { public class RequestInfoAccepter extends QueueConsumer implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log = LoggerFactory.getLogger(getClass());
@ -33,23 +29,22 @@ public class RequestInfoAccepter extends QueueConsumer implements InitializingBe
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
callback(RequestInfoUpdate.class) callback(RequestInfoUpdate.class)
.setConsumer(this::updateRequestInfo) .setConsumer(this::updateRequestInfo)
.forDestination(Consts.REQUEST_INFO_UPDATE, callbacks::put); .forDestination(Consts.REQUEST_INFO_UPDATE, callbacks::put);
init(); init();
} }
private void updateRequestInfo(BaseRequest<RequestInfoUpdate> requestInfoUpdateBaseRequest) { private void updateRequestInfo(BaseRequest<RequestInfoUpdate> requestInfoUpdateBaseRequest) {
//will throw exception for any class other than RequestInfoUpdate
RequestInfoUpdate statusInfo = requestInfoUpdateBaseRequest.getRequestPayload(); RequestInfoUpdate statusInfo = requestInfoUpdateBaseRequest.getRequestPayload();
if (statusInfo == null || statusInfo.getId() == null) { if (statusInfo == null || statusInfo.getId() == null) {
log.warn("BaseRequest id={}, RequestPayload={}: requestInfo id was null", log.warn("BaseRequest id={}, RequestPayload={}: requestInfo id was null",
requestInfoUpdateBaseRequest.getId(), statusInfo); requestInfoUpdateBaseRequest.getId(), statusInfo);
return; return;
} }
RequestInfo requestInfo = requestInfoImdg.getSingleObjectByID(statusInfo.getId()); RequestInfo requestInfo = requestInfoImdg.getSingleObjectByID(statusInfo.getId());
if (requestInfo == null) { if (requestInfo == null) {
log.warn("unknown requestInfo id={}; statusInfo: {}", log.warn("unknown requestInfo id={}; statusInfo: {}",
statusInfo.getId(), statusInfo); statusInfo.getId(), statusInfo);
return; return;
} }
requestInfo.setStatus(statusInfo.getStatus()); requestInfo.setStatus(statusInfo.getStatus());

View file

@ -40,7 +40,7 @@ public class UserAuthProcessor {
requestData.setUsername(identifier); requestData.setUsername(identifier);
requestData.setTime(Instant.now()); requestData.setTime(Instant.now());
requestData.setRoles(new ArrayList<>(roles)); requestData.setRoles(new ArrayList<>(roles));
requestData.setServerIp(serverIp + ":" + serverPort); //getServerAddress() + ":" + serverPort requestData.setServerIp(serverIp + ":" + serverPort);
requestData.setClientIp(userIp); requestData.setClientIp(userIp);
requestData.setEmail(email); requestData.setEmail(email);
requestData.setName(name); requestData.setName(name);
@ -48,7 +48,7 @@ public class UserAuthProcessor {
requestData.setMiddleName(middleName); requestData.setMiddleName(middleName);
try { try {
operator.sendRequestToQueue(Consts.USER_AUTH_SUCCESS, authEvent, false); operator.sendRequestToQueue(Consts.USER_AUTH_SUCCESS, authEvent, false);
} catch (Throwable e) { //ExecutionException | InterruptedException } catch (Throwable e) {
log.error(ExceptionUtils.getStackTrace(e)); log.error(ExceptionUtils.getStackTrace(e));
} }
} }

View file

@ -62,10 +62,8 @@ public class OperatorImpl implements IOperator {
if (user == null) { if (user == null) {
log.warn("UserID not found by login \"{}\"", username); log.warn("UserID not found by login \"{}\"", username);
return null; return null;
//throw new IllegalStateException("cannot obtain userId from logged in user " + username);
} }
return user.getId(); return user.getId();
// todo добавить кэш, с очисткой по времени
} }
@Override @Override
@ -78,7 +76,6 @@ public class OperatorImpl implements IOperator {
if (appendUserId) { if (appendUserId) {
request.setUserId(currentUserId()); request.setUserId(currentUserId());
} }
//сохраняет данные о запросе в хранилище
saveRequestToStorage(destination, request); saveRequestToStorage(destination, request);
Future<RecordMetadata> send = kafka.send(new ProducerRecord<>(destination, request)); Future<RecordMetadata> send = kafka.send(new ProducerRecord<>(destination, request));
send.get(); send.get();
@ -98,7 +95,6 @@ public class OperatorImpl implements IOperator {
} else { } else {
request.setUserId(userId); request.setUserId(userId);
} }
//сохраняет данные о запросе в хранилище
saveRequestToStorage(destination, request); saveRequestToStorage(destination, request);
Future<RecordMetadata> send = kafka.send(new ProducerRecord<>(destination, request)); Future<RecordMetadata> send = kafka.send(new ProducerRecord<>(destination, request));
send.get(); send.get();
@ -114,12 +110,10 @@ public class OperatorImpl implements IOperator {
} }
private void throwValidate(String destination, IAction<?> iAction) { private void throwValidate(String destination, IAction<?> iAction) {
//простая валидация - которую можно запилить прямо внутри класса (наличие полей, отношения между датами etc.)
Collection<EnumMessage> validationErrors = iAction.validate(); Collection<EnumMessage> validationErrors = iAction.validate();
if (validationErrors.size() > 0) { if (validationErrors.size() > 0) {
throw new ActionValidationException(validationErrors); throw new ActionValidationException(validationErrors);
} }
// Валидация по мете (рекомендуется использовать её,а не iAction.validate();
IValidator metaValidator = actionMetaValidation.getValidator(destination, iAction); IValidator metaValidator = actionMetaValidation.getValidator(destination, iAction);
if (metaValidator != null) { if (metaValidator != null) {
metaValidator.tillFirstError().ifPresent(enumMessage -> { metaValidator.tillFirstError().ifPresent(enumMessage -> {
@ -130,8 +124,6 @@ public class OperatorImpl implements IOperator {
} }
}); });
} }
//валидация требующая IMDG поиска других сущностей и т.д.
IValidator validator = validation.getValidator(destination, iAction); IValidator validator = validation.getValidator(destination, iAction);
if (validator != null) { if (validator != null) {
validator.tillFirstError().ifPresent(enumMessage -> { validator.tillFirstError().ifPresent(enumMessage -> {

View file

@ -25,9 +25,6 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
/**
* Проверка обязательности полей для IAction по мете
*/
@Component @Component
public class ActionMetaValidation implements InitializingBean { public class ActionMetaValidation implements InitializingBean {
protected static final Logger log = LoggerFactory.getLogger(ActionMetaValidation.class); protected static final Logger log = LoggerFactory.getLogger(ActionMetaValidation.class);
@ -55,8 +52,7 @@ public class ActionMetaValidation implements InitializingBean {
public IValidator getValidator(String destination, Object action) { public IValidator getValidator(String destination, Object action) {
if (action == null) if (action == null)
return null; return null;
//if (destination == null) destination = action.getClass().getName(); String actionDestination = action.getClass().getName();
String actionDestination = action.getClass().getName(); // см. реализацию в MetaServer String actionDestination =...
Function<Object, IValidator> constructor = (Function<Object, IValidator>) validators.get(actionDestination); Function<Object, IValidator> constructor = (Function<Object, IValidator>) validators.get(actionDestination);
if (constructor != null) if (constructor != null)
return constructor.apply(action); return constructor.apply(action);
@ -64,21 +60,20 @@ public class ActionMetaValidation implements InitializingBean {
} }
static boolean isTrue(Boolean b) { static boolean isTrue(Boolean b) {
return b!=null && b; return b != null && b;
} }
private <T extends Object> Function<T, IValidator> validatorConstructor(ObjectExtracted metaAction) { private <T extends Object> Function<T, IValidator> validatorConstructor(ObjectExtracted metaAction) {
if (!metaAction.getFields().stream().anyMatch(field -> isTrue(field.getField().isRequired()))) { if (!metaAction.getFields().stream().anyMatch(field -> isTrue(field.getField().isRequired()))) {
log.debug("Action {}: no any required fields. Do not need validator.", metaAction.getClassName()); log.debug("Action {}: no any required fields. Do not need validator.", metaAction.getClassName());
// нет обязательных полей для валидации
return null; return null;
} }
// Тестирование getter
{ {
Object object; Object object;
try { try {
object = metaAction.getClazz().getDeclaredConstructor().newInstance(); object = metaAction.getClazz().getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
throw new RuntimeException("Error self-test validator on class " + metaAction.getClazz(), e); throw new RuntimeException("Error self-test validator on class " + metaAction.getClazz(), e);
} }
for (FieldExtracted field : metaAction.getFields()) { for (FieldExtracted field : metaAction.getFields()) {
@ -90,10 +85,10 @@ public class ActionMetaValidation implements InitializingBean {
String className = metaAction.getClazz().getName(); String className = metaAction.getClazz().getName();
if (className.endsWith(".MoneyMarketSecurityUpdateAction") || className.endsWith(".ChangeRefundDateActionNew")) { if (className.endsWith(".MoneyMarketSecurityUpdateAction") || className.endsWith(".ChangeRefundDateActionNew")) {
log.warn("Expected warning self-test validator on class {} and field {}: {}", log.warn("Expected warning self-test validator on class {} and field {}: {}",
className, field.getMemberName(), e.toString()); className, field.getMemberName(), e.toString());
} else { } else {
log.warn("Error self-test validator on class {} and field {}: {}", log.warn("Error self-test validator on class {} and field {}: {}",
className, field.getMemberName(), ExceptionUtils.getStackTrace(e)); className, field.getMemberName(), ExceptionUtils.getStackTrace(e));
} }
} }
} }
@ -104,7 +99,6 @@ public class ActionMetaValidation implements InitializingBean {
ctx.setValidatedObject(iAcc); ctx.setValidatedObject(iAcc);
ValidatorImpl<ImdgValidationContext<T>> iValidator = new ValidatorImpl(ctx); ValidatorImpl<ImdgValidationContext<T>> iValidator = new ValidatorImpl(ctx);
iValidator.addRule(metaValidatorRule); iValidator.addRule(metaValidatorRule);
// в дальнейшем можно улучшить и разделить валидатор по полям
return iValidator; return iValidator;
}; };
} }
@ -125,17 +119,14 @@ public class ActionMetaValidation implements InitializingBean {
Object value = field.extractValue(object); Object value = field.extractValue(object);
if (value == null) if (value == null)
return of(BackEndError.ValidationError, field.getMemberName()); return of(BackEndError.ValidationError, field.getMemberName());
// if (value instanceof String && ((String)value).isEmpty()) // пустое поле, но не null
// return of(BackEndError.ValidationError, field.getMemberName());
} }
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
if (object instanceof MoneyMarketSecurityUpdateAction) { if (object instanceof MoneyMarketSecurityUpdateAction) {
//todo в мете для moneyMarketSecurity / actions / put / для поля lotSize field="securityId" исключение - там надо оставить field, требуется для frontend
if (((MoneyMarketSecurityUpdateAction) object).getLotSize() == null) if (((MoneyMarketSecurityUpdateAction) object).getLotSize() == null)
return of(BackEndError.ValidationError, "LotSize"); return of(BackEndError.ValidationError, "LotSize");
} else { } else {
log.warn("Error apply meta-validator {} for {} : {}", log.warn("Error apply meta-validator {} for {} : {}",
metaAction, object, e.toString()); metaAction, object, e.toString());
} }
} }
} }

View file

@ -121,7 +121,7 @@
<tradingClearingRegistryType id="1" code="A" name="Владелец"/> <tradingClearingRegistryType id="1" code="A" name="Владелец"/>
<tradingClearingRegistryType id="2" code="B" name="Клиентский"/> <tradingClearingRegistryType id="2" code="B" name="Клиентский"/>
<tradingClearingRegistryType id="3" code="C" name="Клиентский"/> <!-- todo был Попечитель --> <tradingClearingRegistryType id="3" code="C" name="Клиентский"/>
<tradingClearingRegistryType id="4" code="D" name="Доверительный управляющий"/> <tradingClearingRegistryType id="4" code="D" name="Доверительный управляющий"/>
<tradingClearingRegistryType id="5" code="E" name="Эмитент"/> <tradingClearingRegistryType id="5" code="E" name="Эмитент"/>
<tradingClearingRegistryType id="6" code="Z" name="К размещению/выкупу"/> <tradingClearingRegistryType id="6" code="Z" name="К размещению/выкупу"/>

View file

@ -107,7 +107,7 @@ COMMENT ON COLUMN <xsl:value-of select="$dbTableName"/>.<xsl:call-template name=
COMMENT ON COLUMN <xsl:value-of select="$dbTableName"/>.<xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template> IS '<xsl:if test="$dbNameComment"><xsl:value-of select="$dbNameComment"/></xsl:if> <xsl:if test="@link"> (linked to <xsl:value-of select="@link"/>)</xsl:if>'; COMMENT ON COLUMN <xsl:value-of select="$dbTableName"/>.<xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template> IS '<xsl:if test="$dbNameComment"><xsl:value-of select="$dbNameComment"/></xsl:if> <xsl:if test="@link"> (linked to <xsl:value-of select="@link"/>)</xsl:if>';
</xsl:otherwise></xsl:choose></xsl:template> </xsl:otherwise></xsl:choose></xsl:template>
<xsl:template match="*" mode="comment-history-objects"><!-- todo похож на comment-objects только именем таблицы различается попробовать объединить --> <xsl:template match="*" mode="comment-history-objects">
<xsl:choose> <xsl:choose>
<!--<xsl:when test="@ "></xsl:when>--> <!--<xsl:when test="@ "></xsl:when>-->
<xsl:when test="@extends"></xsl:when> <xsl:when test="@extends"></xsl:when>

View file

@ -36,7 +36,7 @@
<xsl:variable name="dbTableName"><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='concat(name(),"Dictionary")'/></xsl:call-template></xsl:variable> <xsl:variable name="dbTableName"><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='concat(name(),"Dictionary")'/></xsl:call-template></xsl:variable>
<xsl:variable name="nameObjFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable> <xsl:variable name="nameObjFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable>
package ru.clearing.platform.dictionary;<!-- todo remove extract last class <xsl:value-of select="@class"/> - only package--> package ru.clearing.platform.dictionary; select="@class"/> - only package-->
<!-- import ru.clearing.dictionarys.ConstDictionarySerializable; --> <!-- import ru.clearing.dictionarys.ConstDictionarySerializable; -->
/** /**
@ -95,7 +95,7 @@ public class <xsl:value-of select="$nameObjFmt"/>DictionaryMapStore extends Dict
<xsl:when test="name()='code'"></xsl:when> <xsl:when test="name()='code'"></xsl:when>
<xsl:when test="name()='name'"></xsl:when> <xsl:when test="name()='name'"></xsl:when>
<xsl:otherwise> <xsl:otherwise>
!! Нестандартное поле !! <xsl:value-of select="name()"/> // FIXME Нестандартный словарь! Требуется писать код вручную. !! Нестандартное поле !! <xsl:value-of select="name()"/>
</xsl:otherwise> </xsl:otherwise>
</xsl:choose> </xsl:choose>
</xsl:template> </xsl:template>
@ -104,7 +104,7 @@ public class <xsl:value-of select="$nameObjFmt"/>DictionaryMapStore extends Dict
// ------------------ <xsl:value-of select="name()"/> - <xsl:value-of select="@name"/> // ------------------ <xsl:value-of select="name()"/> - <xsl:value-of select="@name"/>
<xsl:variable name="dbTableName"><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable> <xsl:variable name="dbTableName"><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable>
<xsl:variable name="nameObjFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable> <xsl:variable name="nameObjFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable>
package <xsl:value-of select="@class"/>;<!-- todo remove extract last class - only package--> package <xsl:value-of select="@class"/>;
import ru.clearing.classes.ConstSerializable; import ru.clearing.classes.ConstSerializable;
import ru.spcex.platform.classes.base.SpcexObjectBase; import ru.spcex.platform.classes.base.SpcexObjectBase;
@ -177,7 +177,7 @@ public class <xsl:value-of select="$nameObjFmt"/>MapStore extends TemplateMapSto
} }
<xsl:if test="@logUpdates"> <xsl:if test="@logUpdates">
// todo добавить класс <xsl:value-of select="$nameObjFmt"/>History // todo добавить класс <xsl:value-of select="$nameObjFmt"/>History
package <xsl:value-of select="@class"/>;<!-- todo remove extract last class - only package--> package <xsl:value-of select="@class"/>;
import ru.clearing.classes.ConstSerializable; import ru.clearing.classes.ConstSerializable;
import ru.clearing.classes.objects.BusinessEvent; import ru.clearing.classes.objects.BusinessEvent;
@ -234,7 +234,7 @@ public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends Templat
@Override @Override
public String[] getFields() { public String[] getFields() {
return new String[]{"ID","EVENT_TIME", "EVENT_USER_ID", "EVENT_TYPE", <!-- todo покрасивее сделать ?_ID, а то код вручную приодится править --> return new String[]{"ID","EVENT_TIME", "EVENT_USER_ID", "EVENT_TYPE",
<xsl:value-of select="$dbTableName"/>_<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getFields"/> <xsl:value-of select="$dbTableName"/>_<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getFields"/>
}; };
} }
@ -283,7 +283,7 @@ public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends Templat
</xsl:choose>", <xsl:value-of select="$javatp"/>.class))</xsl:otherwise> </xsl:choose>", <xsl:value-of select="$javatp"/>.class))</xsl:otherwise>
</xsl:choose>;</xsl:template> </xsl:choose>;</xsl:template>
<xsl:template match="*" mode="mapstore-field-getters" ><xsl:if test="position() != '1' and not(@extends)">, </xsl:if><!-- todo запятую в конце а не в начале, см. last()--> <xsl:template match="*" mode="mapstore-field-getters" ><xsl:if test="position() != '1' and not(@extends)">, </xsl:if>
<xsl:variable name="tp" select="@type"/> <xsl:variable name="tp" select="@type"/>
<xsl:variable name="javatp" select="/meta/types/*[@id=$tp]/@javatype"/> <xsl:variable name="javatp" select="/meta/types/*[@id=$tp]/@javatype"/>
<xsl:text> <!-- space &#160; 4 new line --> <xsl:text> <!-- space &#160; 4 new line -->
@ -306,10 +306,10 @@ public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends Templat
<xsl:when test="@dbfield"> // DB field: <xsl:value-of select="@dbfield"/></xsl:when> <xsl:when test="@dbfield"> // DB field: <xsl:value-of select="@dbfield"/></xsl:when>
<!-- new line --> <!-- new line -->
<xsl:otherwise> </xsl:otherwise></xsl:choose> <xsl:otherwise> </xsl:otherwise></xsl:choose>
<!-- todo pretty comment: <xsl:if test="@link"> // (linked to <xsl:value-of select="@link"/>) <!-- todo pretty comment: <xsl:if test="@link"> // (linked to <xsl:value-of select="@link"/>)
</xsl:if>--> </xsl:if>-->
<!-- fixme т.к. тут атрибуты перебираются - не работают переносы а ещё знак пробела надо пропатчить, а то NBSP -->
</xsl:template> </xsl:template>
@ -337,9 +337,9 @@ public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends Templat
<xsl:template match="*" mode="getter-setter-enums"> <xsl:template match="*" mode="getter-setter-enums">
<xsl:variable name="tp" select="@type"/> <xsl:variable name="tp" select="@type"/>
<xsl:choose> <xsl:choose>
<xsl:when test="name()='id'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary --> <xsl:when test="name()='id'"></xsl:when>
<xsl:when test="name()='code'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary --> <xsl:when test="name()='code'"></xsl:when>
<xsl:when test="name()='name'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary --> <xsl:when test="name()='name'"></xsl:when>
<xsl:otherwise><!-- нестандартное поле --> <xsl:otherwise><!-- нестандартное поле -->
<xsl:variable name="NameFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable> <xsl:variable name="NameFmt"><xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:variable>
public <xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> get<xsl:value-of select="$NameFmt"/>() { public <xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> get<xsl:value-of select="$NameFmt"/>() {
@ -451,7 +451,7 @@ public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends Templat
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
<!-- todo должен первую букву прописной сделать -->
<xsl:template name='convertFirstUC_'> <xsl:template name='convertFirstUC_'>
<xsl:param name='toconvert' /> <xsl:param name='toconvert' />
<xsl:if test="string-length($toconvert) > 0"> <xsl:if test="string-length($toconvert) > 0">

View file

@ -81,89 +81,72 @@ import static ru.spcex.clearing.test.json.MatcherFactoryWithJson.usingIgnoringFi
@ContextConfiguration(classes = { @ContextConfiguration(classes = {
//account AccountController.class,
AccountController.class, BankAccountController.class,
BankAccountController.class, ClearingAccountController.class,
ClearingAccountController.class, DepoAccountController.class,
DepoAccountController.class, ClientCodeController.class,
//account misc AccountSymbolsController.class,
ClientCodeController.class, CompanyRoleSetController.class,
AccountSymbolsController.class, CompanyController.class,
//company ClearingMemberCategoryController.class,
CompanyRoleSetController.class, CompanyInfoController.class,
CompanyController.class, CompanySymbolController.class,
ClearingMemberCategoryController.class, ContactController.class,
CompanyInfoController.class, ProfileDocumentController.class,
CompanySymbolController.class, RelationController.class,
ContactController.class, ExecutionDepositController.class,
ProfileDocumentController.class, ExecutionFondController.class,
RelationController.class, InDocumentJournalController.class,
//execution ManagementJournalController.class,
ExecutionDepositController.class, OutDocumentJournalController.class,
ExecutionFondController.class, CurrencyController.class,
//journal ErrorTextController.class,
InDocumentJournalController.class, ListingController.class,
ManagementJournalController.class, MarketController.class,
OutDocumentJournalController.class, NotificationController.class,
//liabilities SessionController.class,
//misc SCrossRateController.class,
CurrencyController.class, PaymentInstructionController.class,
ErrorTextController.class, AdmittedLiabilitiesRegisterController.class,
ListingController.class, CoveredLiabilitiesRegisterController.class,
MarketController.class, DepoBalanceRegisterController.class,
NotificationController.class, DepoPaymentInstructionRegisterController.class,
SessionController.class, ExcludeLiabilitiesRegisterController.class,
SCrossRateController.class, ExecutionRegisterController.class,
//payment LiabilitiesRegisterController.class,
PaymentInstructionController.class, MoneyBalanceRegisterController.class,
//register ContractRegisterController.class,
AdmittedLiabilitiesRegisterController.class, ReportRegisterController.class,
CoveredLiabilitiesRegisterController.class, GatewayResultController.class,
DepoBalanceRegisterController.class, PairSdfController.class,
DepoPaymentInstructionRegisterController.class, RegistryController.class,
ExcludeLiabilitiesRegisterController.class, TradingClearingRegistryController.class,
ExecutionRegisterController.class, ClearingCalendarController.class,
LiabilitiesRegisterController.class, LauncherController.class,
MoneyBalanceRegisterController.class, PlannerAllTodayController.class,
ContractRegisterController.class, PlannerController.class,
ReportRegisterController.class, PlannerTemplateController.class,
GatewayResultController.class, MoneyMarketSecurityController.class,
PairSdfController.class, CouponPeriodController.class,
//registry EquitySecurityController.class,
RegistryController.class, FixedIncomeCashFlowController.class,
TradingClearingRegistryController.class, FixedIncomeSecurityController.class,
//scheduler InformationAccountController.class,
ClearingCalendarController.class, SecurityController.class,
LauncherController.class, UserController.class,
PlannerAllTodayController.class, UserRoleSessionController.class,
PlannerController.class, StatementController.class,
PlannerTemplateController.class, UserSettingsController.class,
//securities WebTestConfig.class,
MoneyMarketSecurityController.class, IOperatorTest.class,
CouponPeriodController.class, HazelcastServiceTestConfiguration.class,
EquitySecurityController.class, StateLoaderImplTestConfig.class,
FixedIncomeCashFlowController.class, WebSecurityTestConfigurer.class,
FixedIncomeSecurityController.class, MessagesTestConfig.class,
InformationAccountController.class, Jackson2HttpConverterTestConfig.class})
SecurityController.class,
//user
UserController.class,
UserRoleSessionController.class,
//utilities
StatementController.class,
UserSettingsController.class,
//******* common configs *******
WebTestConfig.class,
IOperatorTest.class,
HazelcastServiceTestConfiguration.class,
StateLoaderImplTestConfig.class,
WebSecurityTestConfigurer.class,
MessagesTestConfig.class,
Jackson2HttpConverterTestConfig.class})
//todo может быть указать пакедж а не список контроллеров
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
@WebMvcTest @WebMvcTest
//@TestPropertySource(properties = "spring.config.location=D:/repo/mfd/clearing/clearing-parent/backend-api/src/main/resources/")
public abstract class AbstractControllerTest { public abstract class AbstractControllerTest {
protected static final MatcherFactoryWithJson.Matcher<BaseRequest> BASE_REQUEST_MATCHER = usingIgnoringFieldsComparatorForClass(BaseRequest.class,"userId"); protected static final MatcherFactoryWithJson.Matcher<BaseRequest> BASE_REQUEST_MATCHER = usingIgnoringFieldsComparatorForClass(BaseRequest.class,"userId");
protected static final MatcherFactoryWithJson.Matcher<CudResponse> CUD_RESPONSE_MATCHER = usingIgnoringFieldsComparatorForClass(CudResponse.class); protected static final MatcherFactoryWithJson.Matcher<CudResponse> CUD_RESPONSE_MATCHER = usingIgnoringFieldsComparatorForClass(CudResponse.class);
@ -202,10 +185,9 @@ public abstract class AbstractControllerTest {
@PostConstruct @PostConstruct
private void postConstruct() { private void postConstruct() {
mockMvc = MockMvcBuilders mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext) .webAppContextSetup(webApplicationContext)
.addFilter(CHARACTER_ENCODING_FILTER) .addFilter(CHARACTER_ENCODING_FILTER)
// .apply(springSecurity()) .build();
.build();
TestUtils.FutureRecordMetadata future = spy(TestUtils.FutureRecordMetadata.class); TestUtils.FutureRecordMetadata future = spy(TestUtils.FutureRecordMetadata.class);
doReturn(future).when(producer).send(producerRecord.capture()); doReturn(future).when(producer).send(producerRecord.capture());
userImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_User, User.class); userImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_User, User.class);
@ -229,16 +211,13 @@ public abstract class AbstractControllerTest {
CudResponse expected = new CudResponse(); CudResponse expected = new CudResponse();
expected.setCode(0L); expected.setCode(0L);
expected.setMessage("success"); expected.setMessage("success");
//ACT
MvcResult mvcResult = perform(MockMvcRequestBuilders.post(REST_URL) MvcResult mvcResult = perform(MockMvcRequestBuilders.post(REST_URL)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(writeValue(action))) .content(writeValue(action)))
.andDo(print())//output to the log request and response .andDo(print())
//ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andReturn();
//.andExpect(content().json(writeValue(expected)))
.andReturn();
CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class); CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class);
expected.setPayload(new QueueSuccessResponse(ActionType.NEW, cudResponseTest.getPayload().getId())); expected.setPayload(new QueueSuccessResponse(ActionType.NEW, cudResponseTest.getPayload().getId()));
CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected); CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected);
@ -249,17 +228,13 @@ public abstract class AbstractControllerTest {
expected.setCode(0L); expected.setCode(0L);
expected.setMessage("success"); expected.setMessage("success");
expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement())); expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement()));
//ACT
MvcResult mvcResult = perform(MockMvcRequestBuilders.put(REST_URL + existsId) MvcResult mvcResult = perform(MockMvcRequestBuilders.put(REST_URL + existsId)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(writeValue(action))) .content(writeValue(action)))
.andDo(print())//output to the log request and response .andDo(print())
//ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andReturn();
//.andExpect(content().json(writeValue(expected)));
.andReturn();
CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class); CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class);
expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, cudResponseTest.getPayload().getId())); expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, cudResponseTest.getPayload().getId()));
CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected); CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected);
@ -277,17 +252,13 @@ public abstract class AbstractControllerTest {
expected.setCode(0L); expected.setCode(0L);
expected.setMessage("success"); expected.setMessage("success");
expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement())); expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement()));
//ACT
MvcResult mvcResult = perform(MockMvcRequestBuilders.put(REST_URL) MvcResult mvcResult = perform(MockMvcRequestBuilders.put(REST_URL)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(writeValue(action))) .content(writeValue(action)))
.andDo(print())//output to the log request and response .andDo(print())
//ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andReturn();
//.andExpect(content().json(writeValue(expected)));
.andReturn();
CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class); CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class);
expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, cudResponseTest.getPayload().getId())); expected.setPayload(new QueueSuccessResponse(ActionType.UPDATE, cudResponseTest.getPayload().getId()));
CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected); CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected);
@ -300,15 +271,12 @@ public abstract class AbstractControllerTest {
expected.setPayload(new QueueSuccessResponse(ActionType.DELETE, existsId)); expected.setPayload(new QueueSuccessResponse(ActionType.DELETE, existsId));
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(existsId); deleteAction.setId(existsId);
//ACT
MvcResult mvcResult = perform(MockMvcRequestBuilders.delete(REST_URL + existsId) MvcResult mvcResult = perform(MockMvcRequestBuilders.delete(REST_URL + existsId)
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response .andDo(print())
//ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andReturn();
// .andExpect(content().json(writeValue(expected)));
.andReturn();
CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class); CudResponseTest cudResponseTest = readValue(mvcResult.getResponse().getContentAsString(), CudResponseTest.class);
expected.setPayload(new QueueSuccessResponse(ActionType.DELETE, cudResponseTest.getPayload().getId())); expected.setPayload(new QueueSuccessResponse(ActionType.DELETE, cudResponseTest.getPayload().getId()));
CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected); CUD_RESPONSE_MATCHER.assertMatch(cudResponseTest, expected);
@ -324,21 +292,18 @@ public abstract class AbstractControllerTest {
protected <T extends SpcexObjectBase> void checkGettingAllFromRestApi(String imdgDistributedNames, T existsObj, String restUrl) throws Exception { protected <T extends SpcexObjectBase> void checkGettingAllFromRestApi(String imdgDistributedNames, T existsObj, String restUrl) throws Exception {
Class<T> clazz = (Class<T>) existsObj.getClass(); Class<T> clazz = (Class<T>) existsObj.getClass();
Imdg<T> testingImdg = hazelcastServiceTest.getImdg(imdgDistributedNames, clazz); Imdg<T> testingImdg = hazelcastServiceTest.getImdg(imdgDistributedNames, clazz);
// ((ImdgHazelcast<T>)testingImdg).clear(); // предварительная очистка
testingImdg.insert(existsObj); testingImdg.insert(existsObj);
Collection<T> values = testingImdg.getAllValues(); Collection<T> values = testingImdg.getAllValues();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values); Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse(); CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all); expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(restUrl) perform(MockMvcRequestBuilders.get(restUrl)
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response .andDo(print())
// ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(content().json(writeValue(expected)));
.andExpect(content().json(writeValue(expected)));
} }
protected <T extends SpcexObjectBase> void clearAll(String imdgDistributedNames, Class<T> clazz) { protected <T extends SpcexObjectBase> void clearAll(String imdgDistributedNames, Class<T> clazz) {

View file

@ -12,51 +12,28 @@ import ru.spcex.clearing.platform.messaging.domain.Consts;
class AccountControllerTest extends AbstractControllerTest { class AccountControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/accounting/accounts/"; private static final String REST_URL = "/accounting/accounts/";
/**
* {@link AccountController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /accounting/accounts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Account existBankAccount = new Account(); Account existBankAccount = new Account();
existBankAccount.setAccountType("99"); existBankAccount.setAccountType("99");
existBankAccount.setAccount("123456789123"); existBankAccount.setAccount("123456789123");
existBankAccount.setId(currentId.get()); existBankAccount.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Account, existBankAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Account, existBankAccount, REST_URL);
} }
/**
* {@link AccountController#add(AccountNewAction)} <br>
* Тест проверяет получение сущности {@link AccountNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link AccountNewAction}:<br>
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
AccountNewAction accountNewAction = new AccountNewAction(); AccountNewAction accountNewAction = new AccountNewAction();
accountNewAction.setStatus("ACTV"); accountNewAction.setStatus("ACTV");
accountNewAction.setAccount("A11112222333"); accountNewAction.setAccount("A11112222333");
accountNewAction.setCompanyId(5L); accountNewAction.setCompanyId(5L);
accountNewAction.setAccountType("BANK"); accountNewAction.setAccountType("BANK");
//ACT and ASSERT
checkAddingByRestApi(REST_URL, accountNewAction); checkAddingByRestApi(REST_URL, accountNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_NEW, accountNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_NEW, accountNewAction);
} }
/**
* {@link AccountController#update(Long, AccountUpdateAction)} <br>
* Тест проверяет получение сущности {@link AccountUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link AccountUpdateAction}:<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
AccountUpdateAction accountUpdateAction = new AccountUpdateAction(); AccountUpdateAction accountUpdateAction = new AccountUpdateAction();
accountUpdateAction.setId(id); accountUpdateAction.setId(id);
@ -65,29 +42,19 @@ class AccountControllerTest extends AbstractControllerTest {
accountUpdateAction.setCompanyId(5L); accountUpdateAction.setCompanyId(5L);
accountUpdateAction.setAccountType("BANK"); accountUpdateAction.setAccountType("BANK");
Account account = getAccount(id); Account account = getAccount(id);
//ACT and ASSERT
checkUpdatingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Account, account, checkUpdatingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Account, account,
REST_URL, accountUpdateAction, id); REST_URL, accountUpdateAction, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_UPDATE, accountUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_UPDATE, accountUpdateAction);
} }
/**
* {@link AccountController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /securities/account/{@link Long}: - 0L<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
Account account = getAccount(id); Account account = getAccount(id);
//ACT and ASSERT
checkDeletingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Account, account, checkDeletingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Account, account,
REST_URL, id); REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_BLOCK, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CORRESPONDENT_ACCOUNT_BLOCK, deleteAction);
} }

View file

@ -12,54 +12,30 @@ import ru.spcex.clearing.platform.messaging.domain.Consts;
class AccountSymbolsControllerTest extends AbstractControllerTest { class AccountSymbolsControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/accounting/depo-accounts-symbols/"; private static final String REST_URL = "/accounting/depo-accounts-symbols/";
/**
* {@link AccountSymbolsController#add(AccountSymbolsNewAction)}<br>
* Тест проверяет получение сущности {@link AccountSymbolsNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link AccountSymbolsNewAction}: {111L, "VALUE-1234"}
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
AccountSymbolsNewAction accountSymbolsNewAction = new AccountSymbolsNewAction(); AccountSymbolsNewAction accountSymbolsNewAction = new AccountSymbolsNewAction();
accountSymbolsNewAction.setAccountId(111L); accountSymbolsNewAction.setAccountId(111L);
accountSymbolsNewAction.setAccountSymbolValue("VALUE-1234"); accountSymbolsNewAction.setAccountSymbolValue("VALUE-1234");
//ACT and ASSERT
checkAddingByRestApi(REST_URL, accountSymbolsNewAction); checkAddingByRestApi(REST_URL, accountSymbolsNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_NEW, accountSymbolsNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_NEW, accountSymbolsNewAction);
} }
/**
* {@link AccountSymbolsController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /accounting/depo-accounts-symbols/{@link Long}: - 0L<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
//ACT and ASSERT
checkDeletingByRestApi(REST_URL, id); checkDeletingByRestApi(REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_DELETE, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_DEPO_ACCOUNT_SYMBOLS_DELETE, deleteAction);
} }
/**
* {@link ClientCodeController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClientCode.<br>
* Входной запрос /client-codes/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
AccountSymbols existAccountSymbols = new AccountSymbols(); AccountSymbols existAccountSymbols = new AccountSymbols();
existAccountSymbols.setAccountId(111L); existAccountSymbols.setAccountId(111L);
existAccountSymbols.setAccountSymbolValue("AAABBBVVCD"); existAccountSymbols.setAccountSymbolValue("AAABBBVVCD");
existAccountSymbols.setId(currentId.get()); existAccountSymbols.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_AccountSymbols, existAccountSymbols, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_AccountSymbols, existAccountSymbols, REST_URL);
} }

View file

@ -30,53 +30,22 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class BankAccountControllerTest extends AbstractControllerTest { class BankAccountControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/accounting/bank-accounts/"; private static final String REST_URL = "/accounting/bank-accounts/";
/**
* {@link BankAccountController#add(BankAccountNewAction)}<br>
* Тест проверяет получение сущности {@link BankAccountNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link BankAccountNewRequest}:<br>
* {@link BankAccountNewRequest#bankIdentificationCode} - 044525776<br>
* {@link BankAccountNewRequest#bankName} - Beta Money Bank<br>
* {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776<br>
* {@link BankAccountNewRequest#correspondentAccountName} - correspondent<br>
* {@link BankAccountNewRequest#currency} - RUB<br>
* {@link BankAccountNewRequest#destination} - destination<br>
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397<br>
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01<br>
* {@link BankAccountNewRequest#account} - 11111222223333344444<br>
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
BankAccountNewAction bankAccountNewAction = getBankAccountNewAction( BankAccountNewAction bankAccountNewAction = getBankAccountNewAction(
0, "044525776", 0, "044525776",
"Beta Money Bank", "Beta Money Bank",
"30101111111111111776", "30101111111111111776",
"correspondent", "correspondent",
"RUB", "RUB",
"destination", "destination",
"3664011397", "3664011397",
"01", "01",
"11111222223333344444"); "11111222223333344444");
//ACT and ASSERT
checkAddingByRestApi(REST_URL, bankAccountNewAction); checkAddingByRestApi(REST_URL, bankAccountNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_NEW, bankAccountNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_NEW, bankAccountNewAction);
} }
/**
* {@link BankAccountController#add(BankAccountNewAction)}<br>
* Тест проверяет работу валидации сущности {@link BankAccountNewAction} принятой по REST API для отправку в Apache Kafka.<br>
* Входной запрос {@link BankAccountNewRequest}:<br>
* {@link BankAccountNewRequest#bankIdentificationCode} - 044525776 или ""<br>
* {@link BankAccountNewRequest#bankName} - Beta Money Bank или ""<br>
* {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776 или ""<br>
* {@link BankAccountNewRequest#correspondentAccountName} - correspondent или ""<br>
* {@link BankAccountNewRequest#currency} - RUB или ""<br>
* {@link BankAccountNewRequest#destination} - destinatio или ""n<br>
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397 или ""<br>
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01 или ""<br>
* {@link BankAccountNewRequest#account} - 11111222223333344444 или ""<br>
*/
@Test @Test
void addWithException() { void addWithException() {
assertThrowsFor(getBankAccountNewAction(0, "", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444")); assertThrowsFor(getBankAccountNewAction(0, "", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
@ -90,65 +59,35 @@ class BankAccountControllerTest extends AbstractControllerTest {
assertThrowsFor(getBankAccountNewAction(0, "044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "")); assertThrowsFor(getBankAccountNewAction(0, "044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", ""));
} }
/**
* {@link BankAccountController#update(Long, BankAccountUpdateAction)}<br>
* Тест проверяет получение сущности {@link BankAccountUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link BankAccountUpdateAction}:<br>
* {@link BankAccountUpdateAction#bankIdentificationCode} - 044525776<br>
* {@link BankAccountUpdateAction#bankName} - Beta Money Bank<br>
* {@link BankAccountUpdateAction#correspondentAccount} - 30101111111111111776<br>
* {@link BankAccountUpdateAction#correspondentAccountName} - correspondent<br>
* {@link BankAccountUpdateAction#currency} - RUB<br>
* {@link BankAccountUpdateAction#destination} - destination<br>
* {@link BankAccountUpdateAction#taxpayerIdentificationNumber} - 3664011397<br>
* {@link BankAccountUpdateAction#taxRegistrationReasonCode} - 01<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
long id = 0; long id = 0;
BankAccountUpdateAction bankAccountUpdateAction = getBankAccountUpdateAction( BankAccountUpdateAction bankAccountUpdateAction = getBankAccountUpdateAction(
id, id,
"044525776", "044525776",
"Beta Money Bank", "Beta Money Bank",
"30101111111111111776", "30101111111111111776",
"correspondent", "correspondent",
"RUB", "RUB",
"destination", "destination",
"3664011397", "3664011397",
"01", "01",
"11111222223333344444"); "11111222223333344444");
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, bankAccountUpdateAction, id); checkUpdatingByRestApi(REST_URL, bankAccountUpdateAction, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_UPDATE, bankAccountUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_UPDATE, bankAccountUpdateAction);
} }
/**
* {@link BankAccountController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /accounting/bank-accounts/{@link Long}: - 0L<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
//ACT and ASSERT
checkDeletingByRestApi(REST_URL, id); checkDeletingByRestApi(REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_BLOCK, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_BANK_ACCOUNT_BLOCK, deleteAction);
} }
/**
* {@link BankAccountController#getById(Long)} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /accounting/bank-accounts/{@link Long}: - 0L <br>
* Ответ BankAccountBackendGetById <br>
*/
@Test @Test
void getById() throws Exception { void getById() throws Exception {
//ARRANGE
BankAccount existBankAccount = new BankAccount(); BankAccount existBankAccount = new BankAccount();
existBankAccount.setBankName("ooo tinkoff"); existBankAccount.setBankName("ooo tinkoff");
existBankAccount.setBankIdentificationCode("99999"); existBankAccount.setBankIdentificationCode("99999");
@ -164,7 +103,6 @@ class BankAccountControllerTest extends AbstractControllerTest {
inDocumentJournalImdg.insert(existBankAccount); inDocumentJournalImdg.insert(existBankAccount);
CommonGetByIdResponse expected = new CommonGetByIdResponse(); CommonGetByIdResponse expected = new CommonGetByIdResponse();
//expected.getPayload().
Map<String, Object> payload = new HashMap<>(); Map<String, Object> payload = new HashMap<>();
payload.put("bankName", "ooo tinkoff"); payload.put("bankName", "ooo tinkoff");
payload.put("bankIdentificationCode", "99999"); payload.put("bankIdentificationCode", "99999");
@ -176,25 +114,16 @@ class BankAccountControllerTest extends AbstractControllerTest {
payload.put("taxRegistrationReasonCode", "886886"); payload.put("taxRegistrationReasonCode", "886886");
payload.put("id", existBankAccount.getId()); payload.put("id", existBankAccount.getId());
expected.fromEntity(payload); expected.fromEntity(payload);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL + existBankAccount.getId()) perform(MockMvcRequestBuilders.get(REST_URL + existBankAccount.getId())
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response .andDo(print())
// ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(content().json(writeValue(expected)));
.andExpect(content().json(writeValue(expected)));
} }
/**
* {@link BankAccountController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /accounting/bank-accounts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
BankAccount existBankAccount = new BankAccount(); BankAccount existBankAccount = new BankAccount();
existBankAccount.setBankName("ooo tinkoff"); existBankAccount.setBankName("ooo tinkoff");
existBankAccount.setBankIdentificationCode("99999"); existBankAccount.setBankIdentificationCode("99999");
@ -205,8 +134,6 @@ class BankAccountControllerTest extends AbstractControllerTest {
existBankAccount.setTaxpayerIdentificationNumber("848484848484"); existBankAccount.setTaxpayerIdentificationNumber("848484848484");
existBankAccount.setTaxRegistrationReasonCode("886886"); existBankAccount.setTaxRegistrationReasonCode("886886");
existBankAccount.setId(currentId.get()); existBankAccount.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_BankAccount, existBankAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_BankAccount, existBankAccount, REST_URL);
} }

View file

@ -8,22 +8,13 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
class ClearingAccountControllerTest extends AbstractControllerTest { class ClearingAccountControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/accounting/clearing-accounts/"; private static final String REST_URL = "/accounting/clearing-accounts/";
/**
* {@link ClearingAccountController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClearingAccount.<br>
* Входной запрос /securities/clearing-accounts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ClearingAccount existClearingAccount = new ClearingAccount(); ClearingAccount existClearingAccount = new ClearingAccount();
existClearingAccount.setAccountId(99L); existClearingAccount.setAccountId(99L);
existClearingAccount.setClearingAccountType("CATPE-1"); existClearingAccount.setClearingAccountType("CATPE-1");
existClearingAccount.setCompanyId(6L); existClearingAccount.setCompanyId(6L);
existClearingAccount.setId(currentId.get()); existClearingAccount.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClearingAccount, existClearingAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClearingAccount, existClearingAccount, REST_URL);
} }

View file

@ -22,42 +22,20 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class ClientCodeControllerTest extends AbstractControllerTest { class ClientCodeControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/client-codes/"; private static final String REST_URL = "/client-codes/";
/**
* {@link ClientCodeController#add(ClientCodeNewAction)}<br>
* Тест проверяет получение сущности {@link ClientCodeNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ClientCodeNewRequest}:<br>
* {@link ClientCodeNewRequest#} - 044525776<br>
* ...
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
ClientCodeNewAction clientCodeNewAction = getClientCodeNewAction( ClientCodeNewAction clientCodeNewAction = getClientCodeNewAction(
0, 0,
"044525776", "044525776",
"ACTV", "ACTV",
1000L, 1000L,
1010L, 1010L,
1020L, 1020L,
1030L); 1030L);
//ACT and ASSERT
checkAddingByRestApi(REST_URL, clientCodeNewAction); checkAddingByRestApi(REST_URL, clientCodeNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_NEW, clientCodeNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_NEW, clientCodeNewAction);
} }
/**
* {@link ClientCodeController#add(ClientCodeNewAction)}<br>
* Тест проверяет работу валидации сущности {@link ClientCodeNewAction} принятой по REST API для отправку в Apache Kafka.<br>
* Входной запрос {@link ClientCodeNewAction}:<br>
* {@link ClientCodeNewAction#id} - (generated)<br>
* {@link ClientCodeNewAction#code} - "044525776" или null или ""<br>
* {@link ClientCodeNewAction#status} - "ACTV"<br>
* {@link ClientCodeNewAction#companyId} - 1000L или null<br>
* {@link ClientCodeNewAction#depoAccountId} - 1010L<br>
* {@link ClientCodeNewAction#moneyAccountId} - 1020L<br>
* {@link ClientCodeNewAction#tradingClearingRegistryId} - 1030L<br>
*/
@Test @Test
void addWithException() { void addWithException() {
assertThrowsFor(getClientCodeNewAction(0, "", "ACTV", 1000L, 1010L, 1020L, 1030L)); assertThrowsFor(getClientCodeNewAction(0, "", "ACTV", 1000L, 1010L, 1020L, 1030L));
@ -65,61 +43,32 @@ class ClientCodeControllerTest extends AbstractControllerTest {
assertThrowsFor(getClientCodeNewAction(0, "044525776", "ACTV", null, 1010L, 1020L, 1030L)); assertThrowsFor(getClientCodeNewAction(0, "044525776", "ACTV", null, 1010L, 1020L, 1030L));
} }
/**
* {@link ClientCodeController#update(Long, ClientCodeUpdateAction)}<br>
* Тест проверяет получение сущности {@link ClientCodeUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ClientCodeUpdateAction}:<br>
* {@link ClientCodeUpdateAction#id} - (generated)<br>
* {@link ClientCodeUpdateAction#code} - "044525776"<br>
* {@link ClientCodeUpdateAction#status} - "ACTV"<br>
* {@link ClientCodeUpdateAction#companyId} - 1000L<br>
* {@link ClientCodeUpdateAction#depoAccountId} - 1010L<br>
* {@link ClientCodeUpdateAction#moneyAccountId} - 1020L<br>
* {@link ClientCodeUpdateAction#tradingClearingRegistryId} - 1030L<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
long id = 0; long id = 0;
ClientCodeUpdateAction clientCodeUpdateAction = getClientCodeUpdateAction( ClientCodeUpdateAction clientCodeUpdateAction = getClientCodeUpdateAction(
id, id,
"044525776", "044525776",
"ACTV", "ACTV",
1000L, 1000L,
1010L, 1010L,
1020L, 1020L,
1030L); 1030L);
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, clientCodeUpdateAction, id); checkUpdatingByRestApi(REST_URL, clientCodeUpdateAction, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_UPDATE, clientCodeUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_UPDATE, clientCodeUpdateAction);
} }
/**
* {@link ClientCodeController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /client-codes/{@link Long}: - 0L<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
//ACT and ASSERT
checkDeletingByRestApi(REST_URL, id); checkDeletingByRestApi(REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_DELETE, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLIENT_CODE_DELETE, deleteAction);
} }
/**
* {@link ClientCodeController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClientCode.<br>
* Входной запрос /client-codes/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ClientCode existClientCode = new ClientCode(); ClientCode existClientCode = new ClientCode();
existClientCode.setCode("ooo tinkoff"); existClientCode.setCode("ooo tinkoff");
existClientCode.setCompanyId(1000L); existClientCode.setCompanyId(1000L);
@ -130,8 +79,6 @@ class ClientCodeControllerTest extends AbstractControllerTest {
existClientCode.setCreated(Instant.now()); existClientCode.setCreated(Instant.now());
existClientCode.setUpdated(Instant.now()); existClientCode.setUpdated(Instant.now());
existClientCode.setId(currentId.get()); existClientCode.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClientCode, existClientCode, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClientCode, existClientCode, REST_URL);
} }

View file

@ -8,22 +8,13 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
class DepoAccountControllerTest extends AbstractControllerTest { class DepoAccountControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/accounting/depo-accounts/"; private static final String REST_URL = "/accounting/depo-accounts/";
/**
* {@link DepoAccountController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClearingAccount.<br>
* Входной запрос /securities/depo-accounts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
DepoAccount existDepoAccount = new DepoAccount(); DepoAccount existDepoAccount = new DepoAccount();
existDepoAccount.setAccountId(99L); existDepoAccount.setAccountId(99L);
existDepoAccount.setDepoAccountType("T1001"); existDepoAccount.setDepoAccountType("T1001");
existDepoAccount.setCompanyId(6L); existDepoAccount.setCompanyId(6L);
existDepoAccount.setId(currentId.get()); existDepoAccount.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_DepoAccount, existDepoAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_DepoAccount, existDepoAccount, REST_URL);
} }

View file

@ -9,22 +9,13 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
class InformationAccountControllerTest extends AbstractControllerTest { class InformationAccountControllerTest extends AbstractControllerTest {
public static final String REST_URL = "/accounting/information-accounts/"; public static final String REST_URL = "/accounting/information-accounts/";
/**
* {@link InformationAccountController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /accounting/information-accounts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
InformationAccount informationAccount = new InformationAccount(); InformationAccount informationAccount = new InformationAccount();
informationAccount.setId(currentId.get()); informationAccount.setId(currentId.get());
informationAccount.setCompanyId(currentId.get()); informationAccount.setCompanyId(currentId.get());
informationAccount.setClearingAccountId(currentId.get()); informationAccount.setClearingAccountId(currentId.get());
informationAccount.setAccountId(currentId.get()); informationAccount.setAccountId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_InformationAccount, informationAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_InformationAccount, informationAccount, REST_URL);
} }
} }

View file

@ -20,88 +20,44 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class ClearingMemberCategoryControllerTest extends AbstractControllerTest { class ClearingMemberCategoryControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/clearing-member-categories/"; private static final String REST_URL = "/clearing-member-categories/";
/**
* {@link ClearingMemberCategoryController#add(ClearingMemberCategoryNewAction)}<br>
* Тест проверяет получение сущности {@link ClearingMemberCategoryNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ClearingMemberCategoryNewAction}:<br>
* {@link ClearingMemberCategoryNewAction#clearingMemberCategory} - "Category"<br>
* {@link ClearingMemberCategoryNewAction#companyId} - currentId<br>
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
ClearingMemberCategoryNewAction clearingMemberCategoryNewAction = new ClearingMemberCategoryNewAction(); ClearingMemberCategoryNewAction clearingMemberCategoryNewAction = new ClearingMemberCategoryNewAction();
clearingMemberCategoryNewAction.setClearingMemberCategory("Category"); clearingMemberCategoryNewAction.setClearingMemberCategory("Category");
clearingMemberCategoryNewAction.setCompanyId(0L); clearingMemberCategoryNewAction.setCompanyId(0L);
//ACT and ASSERT
checkAddingByRestApi(REST_URL, clearingMemberCategoryNewAction); checkAddingByRestApi(REST_URL, clearingMemberCategoryNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_NEW, clearingMemberCategoryNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_NEW, clearingMemberCategoryNewAction);
} }
/**
* {@link ClearingMemberCategoryController#add(ClearingMemberCategoryNewAction)}<br>
* Тест проверяет получение сущности {@link ClearingMemberCategoryNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ClearingMemberCategoryNewAction}:<br>
* {@link ClearingMemberCategoryNewAction#clearingMemberCategory} - "Category"<br>
* {@link ClearingMemberCategoryNewAction#companyId} - currentId<br>
*/
// @Test валидации пока нет
void addWithException() { void addWithException() {
assertThrowsFor(getClearingMemberCategoryNewAction("Category", null)); assertThrowsFor(getClearingMemberCategoryNewAction("Category", null));
assertThrowsFor(getClearingMemberCategoryNewAction("", 0L)); assertThrowsFor(getClearingMemberCategoryNewAction("", 0L));
} }
/**
* {@link ClearingMemberCategoryController#update(Long, ClearingMemberCategoryUpdateAction)}<br>
* Тест проверяет получение сущности {@link ClearingMemberCategoryUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ClearingMemberCategoryUpdateAction}:<br>
* {@link ClearingMemberCategoryUpdateAction#clearingMemberCategory} - Category<br>
* {@link ClearingMemberCategoryUpdateAction#id} - currentId<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
ClearingMemberCategoryUpdateAction clearingMemberCategoryUpdateAction = new ClearingMemberCategoryUpdateAction(); ClearingMemberCategoryUpdateAction clearingMemberCategoryUpdateAction = new ClearingMemberCategoryUpdateAction();
clearingMemberCategoryUpdateAction.setClearingMemberCategory("Category"); clearingMemberCategoryUpdateAction.setClearingMemberCategory("Category");
clearingMemberCategoryUpdateAction.setId(currentId.get()); clearingMemberCategoryUpdateAction.setId(currentId.get());
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, clearingMemberCategoryUpdateAction, clearingMemberCategoryUpdateAction.getId()); checkUpdatingByRestApi(REST_URL, clearingMemberCategoryUpdateAction, clearingMemberCategoryUpdateAction.getId());
checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_UPDATE, clearingMemberCategoryUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_UPDATE, clearingMemberCategoryUpdateAction);
} }
/**
* {@link ClearingMemberCategoryController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /clearing-member-categories/{@link Long}: - currentId<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
//ACT and ASSERT
checkDeletingByRestApi(REST_URL, id); checkDeletingByRestApi(REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_DELETE, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_DELETE, deleteAction);
} }
/**
* {@link ClearingMemberCategoryController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClearingMemberCategory.<br>
* Входной запрос /clearing-member-categories/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ClearingMemberCategory clearingMemberCategory = new ClearingMemberCategory(); ClearingMemberCategory clearingMemberCategory = new ClearingMemberCategory();
clearingMemberCategory.setClearingMemberCategory("Category"); clearingMemberCategory.setClearingMemberCategory("Category");
clearingMemberCategory.setCompanyId(1000000L); clearingMemberCategory.setCompanyId(1000000L);
clearingMemberCategory.setId(currentId.get()); clearingMemberCategory.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClearingMemberCategory, clearingMemberCategory, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ClearingMemberCategory, clearingMemberCategory, REST_URL);
} }

View file

@ -14,30 +14,17 @@ import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingR
class CompanyControllerTest extends AbstractControllerTest { class CompanyControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/companies/"; private static final String REST_URL = "/companies/";
/**
* {@link CompanyController#delete(Long)} <br>
* Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.<br>
* Входной запрос /companies/{@link Long}: - 0L<br>
*/
@Test @Test
void delete() throws Exception { void delete() throws Exception {
//ARRANGE
long id = currentId.getAndIncrement(); long id = currentId.getAndIncrement();
CommonDeleteAction deleteAction = new CommonDeleteAction(); CommonDeleteAction deleteAction = new CommonDeleteAction();
deleteAction.setId(id); deleteAction.setId(id);
//ACT and ASSERT
checkDeletingByRestApi(REST_URL, id); checkDeletingByRestApi(REST_URL, id);
checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_DELETE, deleteAction); checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_DELETE, deleteAction);
} }
/**
* {@link CompanyController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Company.<br>
* Входной запрос /companies <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Company existCompany = new Company(); Company existCompany = new Company();
existCompany.setTradingCode("ooo tinkoff"); existCompany.setTradingCode("ooo tinkoff");
existCompany.setClearingCode("99999"); existCompany.setClearingCode("99999");
@ -45,26 +32,12 @@ class CompanyControllerTest extends AbstractControllerTest {
existCompany.setShortName("OOO ROGA I KOPITA"); existCompany.setShortName("OOO ROGA I KOPITA");
existCompany.setTradingCode("848484848484"); existCompany.setTradingCode("848484848484");
existCompany.setId(currentId.get()); existCompany.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Company, existCompany, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Company, existCompany, REST_URL);
} }
/**
* {@link CompanyController#add(CompanyNewAction)}<br>
* Тест проверяет создание сущности {@link CompanyNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanyNewAction}:<br>
* {@link CompanyNewAction#fullName "Full name"<br>
* {@link CompanyNewAction#companySymbol "CLRC"<br>
* {@link CompanyNewAction#companySymbolValue "NAME1"<br>
* {@link CompanyNewAction#workflowStatus "ACTV"<br>
*/
@Test @Test
void add() throws Exception { void add() throws Exception {
//ARRANGE
CompanyNewAction newAction = getCompanyNewAction(); CompanyNewAction newAction = getCompanyNewAction();
//ACT and ASSERT
checkAddingByRestApi(REST_URL, newAction); checkAddingByRestApi(REST_URL, newAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_NEW, newAction); checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_NEW, newAction);
} }

View file

@ -30,51 +30,13 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class CompanyInfoControllerTest extends AbstractControllerTest { class CompanyInfoControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/company-infos/"; private static final String REST_URL = "/company-infos/";
/**
* {@link CompanyInfoController#update(Long, CompanyInfoUpdateAction)}<br>
* Тест проверяет получение сущности {@link CompanyInfoUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanyInfoUpdateAction}:<br>
* {@link CompanyInfoUpdateAction#workflowStatus} - ACTV<br>
* {@link CompanyInfoUpdateAction#corporationSoleType} - 0000<br>
* {@link CompanyInfoUpdateAction#countryCode} - 0000<br>
* {@link CompanyInfoUpdateAction#description} - exists description<br>
* {@link CompanyInfoUpdateAction#professionalSign} - 0000<br>
* {@link CompanyInfoUpdateAction#legalKind} - 0000<br>
* {@link CompanyInfoUpdateAction#organizationType} - 0000<br>
* {@link CompanyInfoUpdateAction#residence} - 0000<br>
* {@link CompanyInfoUpdateAction#shortNameEng} - exists shortNameEng<br>
* {@link CompanyInfoUpdateAction#fullNameEng} - exists fullNameEng<br>
* {@link CompanyInfoUpdateAction#shortName} - exists shortName<br>
* {@link CompanyInfoUpdateAction#fullName} - exists fullName<br>
* {@link CompanyInfoUpdateAction#id} - currentId<br>
*/
// @Test валидации пока нет
void addWithException() { void addWithException() {
assertThrowsFor(getClearingMemberCategoryNewAction("Category", null)); assertThrowsFor(getClearingMemberCategoryNewAction("Category", null));
assertThrowsFor(getClearingMemberCategoryNewAction("", 0L)); assertThrowsFor(getClearingMemberCategoryNewAction("", 0L));
} }
/**
* {@link CompanyInfoController#update(Long, CompanyInfoUpdateAction)}<br>
* Тест проверяет получение сущности {@link CompanyInfoUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanyInfoUpdateAction}:<br>
* {@link CompanyInfoUpdateAction#workflowStatus} - ACTV<br>
* {@link CompanyInfoUpdateAction#corporationSoleType} - 0000<br>
* {@link CompanyInfoUpdateAction#countryCode} - 0000<br>
* {@link CompanyInfoUpdateAction#description} - exists description<br>
* {@link CompanyInfoUpdateAction#professionalSign} - 0000<br>
* {@link CompanyInfoUpdateAction#legalKind} - 0000<br>
* {@link CompanyInfoUpdateAction#organizationType} - 0000<br>
* {@link CompanyInfoUpdateAction#residence} - 0000<br>
* {@link CompanyInfoUpdateAction#shortNameEng} - exists shortNameEng<br>
* {@link CompanyInfoUpdateAction#fullNameEng} - exists fullNameEng<br>
* {@link CompanyInfoUpdateAction#shortName} - exists shortName<br>
* {@link CompanyInfoUpdateAction#fullName} - exists fullName<br>
* {@link CompanyInfoUpdateAction#id} - currentId<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
CompanyInfoUpdateAction companyInfoUpdateAction = new CompanyInfoUpdateAction(); CompanyInfoUpdateAction companyInfoUpdateAction = new CompanyInfoUpdateAction();
companyInfoUpdateAction.setWorkflowStatus("ACTV"); companyInfoUpdateAction.setWorkflowStatus("ACTV");
companyInfoUpdateAction.setCorporationSoleType("0000"); companyInfoUpdateAction.setCorporationSoleType("0000");
@ -89,21 +51,12 @@ class CompanyInfoControllerTest extends AbstractControllerTest {
companyInfoUpdateAction.setShortName("exists shortName"); companyInfoUpdateAction.setShortName("exists shortName");
companyInfoUpdateAction.setFullName("exists fullName"); companyInfoUpdateAction.setFullName("exists fullName");
companyInfoUpdateAction.setId(currentId.get()); companyInfoUpdateAction.setId(currentId.get());
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, companyInfoUpdateAction, companyInfoUpdateAction.getId()); checkUpdatingByRestApi(REST_URL, companyInfoUpdateAction, companyInfoUpdateAction.getId());
checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_INFO_UPDATE, companyInfoUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_INFO_UPDATE, companyInfoUpdateAction);
} }
/**
* {@link CompanyInfoController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Company.<br>
* Входной запрос /company-infos/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Long ID = 0L; Long ID = 0L;
CompanyInfo existsCompanyInfo = new CompanyInfo(); CompanyInfo existsCompanyInfo = new CompanyInfo();
existsCompanyInfo.setId(ID); existsCompanyInfo.setId(ID);
@ -122,26 +75,24 @@ class CompanyInfoControllerTest extends AbstractControllerTest {
existsCompany.setProfile(existsCompanyInfo); existsCompany.setProfile(existsCompanyInfo);
Imdg<Company> companyImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_Company, Company.class); Imdg<Company> companyImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_Company, Company.class);
((ImdgHazelcast<Company>)companyImdg).clear(); ((ImdgHazelcast<Company>) companyImdg).clear();
companyImdg.insert(existsCompany); companyImdg.insert(existsCompany);
Collection<Map<String, Object>> all = new ArrayList<>(); Collection<Map<String, Object>> all = new ArrayList<>();
Collection<Company> companies = companyImdg.getAllValues(); Collection<Company> companies = companyImdg.getAllValues();
for (Company company : companies) { for (Company company : companies) {
if (company.getProfile() != null && company.getProfile().getId() != null) { // пока возвращает "пустой" CompanyInfo если его нет для Company if (company.getProfile() != null && company.getProfile().getId() != null) {
all.add(responseFactory.responseFromObject(company.getProfile())); all.add(responseFactory.responseFromObject(company.getProfile()));
} }
} }
CommonGetAllResponse expected = new CommonGetAllResponse(); CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all); expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL) perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response .andDo(print())
//ASSERT .andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(content().json(writeValue(expected)));
.andExpect(content().json(writeValue(expected)));
} }
private void assertThrowsFor(IAction<?> iAction) { private void assertThrowsFor(IAction<?> iAction) {

View file

@ -8,22 +8,12 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
class CompanyRoleSetControllerTest extends AbstractControllerTest { class CompanyRoleSetControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/company-role-sets/"; private static final String REST_URL = "/company-role-sets/";
/**
* {@link CompanyRoleSetController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /company-role-sets/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
CompanyRoleSet existBankAccount = new CompanyRoleSet(); CompanyRoleSet existBankAccount = new CompanyRoleSet();
existBankAccount.setCompanyId(11L); existBankAccount.setCompanyId(11L);
existBankAccount.setCompanyRole("CLRM"); existBankAccount.setCompanyRole("CLRM");
existBankAccount.setId(currentId.get()); existBankAccount.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_CompanyRoleSet, existBankAccount, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_CompanyRoleSet, existBankAccount, REST_URL);
} }
} }

View file

@ -19,57 +19,28 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class CompanySymbolControllerTest extends AbstractControllerTest { class CompanySymbolControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/company-symbols/"; private static final String REST_URL = "/company-symbols/";
/**
* {@link CompanySymbolController#update(Long, CompanySymbolUpdateAction)}<br>
* Тест проверяет получение сущности {@link CompanySymbolUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanySymbolUpdateAction}:<br>
* {@link CompanySymbolUpdateAction#companyId} - 1000L<br>
* {@link CompanySymbolUpdateAction#companySymbolValue} - SymbolValue<br>
* {@link CompanySymbolUpdateAction#id} - currentId<br>
*/
// @Test валидации пока нет
void addWithException() { void addWithException() {
assertThrowsFor(getClearingMemberCategoryNewAction("Category", null)); assertThrowsFor(getClearingMemberCategoryNewAction("Category", null));
assertThrowsFor(getClearingMemberCategoryNewAction("", 0L)); assertThrowsFor(getClearingMemberCategoryNewAction("", 0L));
} }
/**
* {@link CompanySymbolController#update(Long, CompanySymbolUpdateAction)}<br>
* Тест проверяет получение сущности {@link CompanySymbolUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanySymbolUpdateAction}:<br>
* {@link CompanySymbolUpdateAction#companyId} - 1000L<br>
* {@link CompanySymbolUpdateAction#companySymbolValue} - SymbolValue<br>
* {@link CompanySymbolUpdateAction#id} - currentId<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
CompanySymbolUpdateAction companySymbolUpdateAction = new CompanySymbolUpdateAction(); CompanySymbolUpdateAction companySymbolUpdateAction = new CompanySymbolUpdateAction();
companySymbolUpdateAction.setCompanyId(1000L); companySymbolUpdateAction.setCompanyId(1000L);
companySymbolUpdateAction.setCompanySymbolValue("SymbolValue"); companySymbolUpdateAction.setCompanySymbolValue("SymbolValue");
companySymbolUpdateAction.setId(currentId.get()); companySymbolUpdateAction.setId(currentId.get());
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, companySymbolUpdateAction, companySymbolUpdateAction.getId()); checkUpdatingByRestApi(REST_URL, companySymbolUpdateAction, companySymbolUpdateAction.getId());
checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_SYMBOL_UPDATE, companySymbolUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_COMPANY_SYMBOL_UPDATE, companySymbolUpdateAction);
} }
/**
* {@link CompanySymbolController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_CompanySymbols.<br>
* Входной запрос /clearing-member-categories/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
CompanySymbols companySymbols = new CompanySymbols(); CompanySymbols companySymbols = new CompanySymbols();
companySymbols.setCompanyId(1000L); companySymbols.setCompanyId(1000L);
companySymbols.setCompanySymbol("Symbol"); companySymbols.setCompanySymbol("Symbol");
companySymbols.setCompanySymbolValue("SymbolValue"); companySymbols.setCompanySymbolValue("SymbolValue");
companySymbols.setId(currentId.get()); companySymbols.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_CompanySymbols, companySymbols, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_CompanySymbols, companySymbols, REST_URL);
} }

View file

@ -21,80 +21,39 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class ContactControllerTest extends AbstractControllerTest { class ContactControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/contacts/"; private static final String REST_URL = "/contacts/";
/**
* {@link CompanySymbolController#update(Long, CompanySymbolUpdateAction)}<br>
* Тест проверяет получение сущности {@link CompanySymbolUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link CompanySymbolUpdateAction}:<br>
* {@link CompanySymbolUpdateAction#companyId} - 1000L<br>
* {@link CompanySymbolUpdateAction#companySymbol} - Symbol<br>
* {@link CompanySymbolUpdateAction#companySymbolValue} - SymbolValue<br>
* {@link CompanySymbolUpdateAction#id} - currentId<br>
*/
// @Test валидации пока нет
void addWithException() { void addWithException() {
assertThrowsFor(getClearingMemberCategoryNewAction("Category", null)); assertThrowsFor(getClearingMemberCategoryNewAction("Category", null));
assertThrowsFor(getClearingMemberCategoryNewAction("", 0L)); assertThrowsFor(getClearingMemberCategoryNewAction("", 0L));
} }
/**
* {@link ContactController#create(Long, ContactNewAction)}<br>
* Тест проверяет получение сущности {@link ContactNewAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ContactNewAction}:<br>
* {@link ContactNewAction#contactType} - ContactType<br>
* {@link ContactNewAction#contactValue} - ContactValue<br>
* {@link ContactNewAction#id} - currentId<br>
*/
@Test @Test
void create() throws Exception { void create() throws Exception {
//ARRANGE
ContactNewAction companySymbolNewAction = new ContactNewAction(); ContactNewAction companySymbolNewAction = new ContactNewAction();
companySymbolNewAction.setContactType("ContactType"); companySymbolNewAction.setContactType("ContactType");
companySymbolNewAction.setContactValue("ContactValue"); companySymbolNewAction.setContactValue("ContactValue");
companySymbolNewAction.setCompanyId(currentId.get()); companySymbolNewAction.setCompanyId(currentId.get());
//ACT and ASSERT
checkAddingByRestApi(REST_URL, companySymbolNewAction); checkAddingByRestApi(REST_URL, companySymbolNewAction);
checkSendedMessegeFromKafka(Consts.DESTINATION_CONTACT_NEW, companySymbolNewAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CONTACT_NEW, companySymbolNewAction);
} }
/**
* {@link ContactController#update(Long, ContactUpdateAction)}<br>
* Тест проверяет получение сущности {@link ContactUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос {@link ContactUpdateAction}:<br>
* {@link ContactUpdateAction#contactType} - ContactType<br>
* {@link ContactUpdateAction#contactValue} - ContactValue<br>
* {@link ContactUpdateAction#id} - currentId<br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
ContactUpdateAction companySymbolUpdateAction = new ContactUpdateAction(); ContactUpdateAction companySymbolUpdateAction = new ContactUpdateAction();
companySymbolUpdateAction.setContactType("ContactType"); companySymbolUpdateAction.setContactType("ContactType");
companySymbolUpdateAction.setContactValue("ContactValue"); companySymbolUpdateAction.setContactValue("ContactValue");
companySymbolUpdateAction.setId(currentId.get()); companySymbolUpdateAction.setId(currentId.get());
//ACT and ASSERT
checkUpdatingByRestApi(REST_URL, companySymbolUpdateAction, companySymbolUpdateAction.getId()); checkUpdatingByRestApi(REST_URL, companySymbolUpdateAction, companySymbolUpdateAction.getId());
checkSendedMessegeFromKafka(Consts.DESTINATION_CONTACT_UPDATE, companySymbolUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_CONTACT_UPDATE, companySymbolUpdateAction);
} }
/**
* {@link ContactController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Contact.<br>
* Входной запрос /contacts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Contact companySymbolUpdateAction = new Contact(); Contact companySymbolUpdateAction = new Contact();
companySymbolUpdateAction.setCompanyId(1000L); companySymbolUpdateAction.setCompanyId(1000L);
companySymbolUpdateAction.setContactType("ContactType"); companySymbolUpdateAction.setContactType("ContactType");
companySymbolUpdateAction.setContactValue("ContactValue"); companySymbolUpdateAction.setContactValue("ContactValue");
companySymbolUpdateAction.setId(currentId.get()); companySymbolUpdateAction.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Contact, companySymbolUpdateAction, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Contact, companySymbolUpdateAction, REST_URL);
} }

View file

@ -10,15 +10,8 @@ import java.time.LocalDate;
class ProfileDocumentControllerTest extends AbstractControllerTest { class ProfileDocumentControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/profile-documents/"; private static final String REST_URL = "/profile-documents/";
/**
* {@link ProfileDocumentController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ProfileDocument.<br>
* Входной запрос /profile-documents/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ProfileDocument profileDocument = new ProfileDocument(); ProfileDocument profileDocument = new ProfileDocument();
profileDocument.setCompanyId(1000L); profileDocument.setCompanyId(1000L);
profileDocument.setDocumentType("DocumentType"); profileDocument.setDocumentType("DocumentType");
@ -33,8 +26,6 @@ class ProfileDocumentControllerTest extends AbstractControllerTest {
profileDocument.setValidToDate(LocalDate.now()); profileDocument.setValidToDate(LocalDate.now());
profileDocument.setLink("Link"); profileDocument.setLink("Link");
profileDocument.setId(currentId.get()); profileDocument.setId(currentId.get());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ProfileDocument, profileDocument, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ProfileDocument, profileDocument, REST_URL);
} }
} }

View file

@ -19,15 +19,8 @@ import static ru.spcex.clearing.test.json.JsonUtil.writeValue;
class RelationControllerTest extends AbstractControllerTest { class RelationControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/relations/"; private static final String REST_URL = "/relations/";
/**
* {@link RelationController#update(Long, RelationUpdateAction)}<br>
* Тест проверяет получение сущности {@link RelationUpdateAction} по REST API и отправку в Apache Kafka.<br>
* Входной запрос: id, {@link RelationUpdateAction}:<br>
* <br>
*/
@Test @Test
void update() throws Exception { void update() throws Exception {
//ARRANGE
Long existsId = 123L; Long existsId = 123L;
RelationUpdateAction relationUpdateAction = new RelationUpdateAction(); RelationUpdateAction relationUpdateAction = new RelationUpdateAction();
relationUpdateAction.setId(existsId); relationUpdateAction.setId(existsId);
@ -36,22 +29,13 @@ class RelationControllerTest extends AbstractControllerTest {
Relation relation = new Relation(); Relation relation = new Relation();
relation.setId(existsId); relation.setId(existsId);
//ACT and ASSERT
checkUpdatingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Relation, relation, checkUpdatingWithIdVolidationByRestApi(IMDGDistributedNames.Map_Relation, relation,
REST_URL, relationUpdateAction, existsId); REST_URL, relationUpdateAction, existsId);
checkSendedMessegeFromKafka(Consts.DESTINATION_RELATION_UPDATE, relationUpdateAction); checkSendedMessegeFromKafka(Consts.DESTINATION_RELATION_UPDATE, relationUpdateAction);
} }
/**
* {@link RelationController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /relations/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Long existsId = 123L; Long existsId = 123L;
BankAccount existBankAccount = new BankAccount(); BankAccount existBankAccount = new BankAccount();
existBankAccount.setBankName("ooo tinkoff"); existBankAccount.setBankName("ooo tinkoff");
@ -66,8 +50,6 @@ class RelationControllerTest extends AbstractControllerTest {
Relation relation = new Relation(); Relation relation = new Relation();
relation.setId(existsId); relation.setId(existsId);
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Relation, relation, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Relation, relation, REST_URL);
} }

View file

@ -12,15 +12,8 @@ import java.time.LocalDate;
class ExecutionDepositControllerTest extends AbstractControllerTest { class ExecutionDepositControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/execution-deposits/"; private static final String REST_URL = "/execution-deposits/";
/**
* {@link ExecutionDepositController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /execution-deposits/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ExecutionDeposit executionDeposit = new ExecutionDeposit(); ExecutionDeposit executionDeposit = new ExecutionDeposit();
executionDeposit.setId(currentId.get()); executionDeposit.setId(currentId.get());
executionDeposit.setExchangeExecutionId(currentId.get()); executionDeposit.setExchangeExecutionId(currentId.get());
@ -52,8 +45,6 @@ class ExecutionDepositControllerTest extends AbstractControllerTest {
executionDeposit.setCoverageStatus("cov"); executionDeposit.setCoverageStatus("cov");
executionDeposit.setSessionId(currentId.get()); executionDeposit.setSessionId(currentId.get());
executionDeposit.setClearingDate(LocalDate.now()); executionDeposit.setClearingDate(LocalDate.now());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ExecutionDeposit, executionDeposit, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ExecutionDeposit, executionDeposit, REST_URL);
} }
} }

View file

@ -12,15 +12,8 @@ import java.time.LocalDate;
class ExecutionFondControllerTest extends AbstractControllerTest { class ExecutionFondControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/execution-fonds/"; private static final String REST_URL = "/execution-fonds/";
/**
* {@link ExecutionFondController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /execution-fonds/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ExecutionFond executionFond = new ExecutionFond(); ExecutionFond executionFond = new ExecutionFond();
executionFond.setId(currentId.get()); executionFond.setId(currentId.get());
executionFond.setExchangeExecutionId(currentId.get()); executionFond.setExchangeExecutionId(currentId.get());
@ -50,8 +43,6 @@ class ExecutionFondControllerTest extends AbstractControllerTest {
executionFond.setSettlementCode("settl1"); executionFond.setSettlementCode("settl1");
executionFond.setSettlementDate(LocalDate.now()); executionFond.setSettlementDate(LocalDate.now());
executionFond.setExchangeExecutionMicroseconds(Instant.now()); executionFond.setExchangeExecutionMicroseconds(Instant.now());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ExecutionFond, executionFond, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ExecutionFond, executionFond, REST_URL);
} }
} }

View file

@ -12,15 +12,8 @@ import java.time.LocalTime;
class InDocumentJournalControllerTest extends AbstractControllerTest { class InDocumentJournalControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/in-document-journals/"; private static final String REST_URL = "/in-document-journals/";
/**
* {@link InDocumentJournalController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /in-document-journals/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
InDocumentJournal inDocumentJournal = new InDocumentJournal(); InDocumentJournal inDocumentJournal = new InDocumentJournal();
inDocumentJournal.setId(currentId.get()); inDocumentJournal.setId(currentId.get());
inDocumentJournal.setComment("Comment"); inDocumentJournal.setComment("Comment");
@ -37,8 +30,6 @@ class InDocumentJournalControllerTest extends AbstractControllerTest {
inDocumentJournal.setQuantity(0L); inDocumentJournal.setQuantity(0L);
inDocumentJournal.setClearingCode("dosser"); inDocumentJournal.setClearingCode("dosser");
inDocumentJournal.setEmailDate(LocalDate.now()); inDocumentJournal.setEmailDate(LocalDate.now());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_InDocumentJournal, inDocumentJournal, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_InDocumentJournal, inDocumentJournal, REST_URL);
} }
} }

View file

@ -10,15 +10,8 @@ import java.time.Instant;
class ManagementJournalControllerTest extends AbstractControllerTest { class ManagementJournalControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/management-journals/"; private static final String REST_URL = "/management-journals/";
/**
* {@link ManagementJournalController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /management-journals/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ManagementJournal managementJournal = new ManagementJournal(); ManagementJournal managementJournal = new ManagementJournal();
managementJournal.setId(currentId.get()); managementJournal.setId(currentId.get());
managementJournal.setCompanyId(currentId.get()); managementJournal.setCompanyId(currentId.get());
@ -30,8 +23,6 @@ class ManagementJournalControllerTest extends AbstractControllerTest {
managementJournal.setChangeAccessSign("send"); managementJournal.setChangeAccessSign("send");
managementJournal.setChangeDataSign("dos"); managementJournal.setChangeDataSign("dos");
managementJournal.setEventDate(Instant.now()); managementJournal.setEventDate(Instant.now());
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_ManagementJournal, managementJournal, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_ManagementJournal, managementJournal, REST_URL);
} }
} }

View file

@ -12,15 +12,8 @@ import java.time.LocalTime;
class OutDocumentJournalControllerTest extends AbstractControllerTest { class OutDocumentJournalControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/out-document-journals/"; private static final String REST_URL = "/out-document-journals/";
/**
* {@link OutDocumentJournalController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /out-document-journals/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
OutDocumentJournal outDocumentJournal = new OutDocumentJournal(); OutDocumentJournal outDocumentJournal = new OutDocumentJournal();
outDocumentJournal.setId(currentId.get()); outDocumentJournal.setId(currentId.get());
outDocumentJournal.setRegistrationDate(LocalDate.now()); outDocumentJournal.setRegistrationDate(LocalDate.now());
@ -36,8 +29,6 @@ class OutDocumentJournalControllerTest extends AbstractControllerTest {
outDocumentJournal.setDossierNumber("doc"); outDocumentJournal.setDossierNumber("doc");
outDocumentJournal.setPostDate(LocalDate.now()); outDocumentJournal.setPostDate(LocalDate.now());
outDocumentJournal.setResultStatus("res"); outDocumentJournal.setResultStatus("res");
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_OutDocumentJournal, outDocumentJournal, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_OutDocumentJournal, outDocumentJournal, REST_URL);
} }
} }

View file

@ -8,21 +8,12 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
class CurrencyControllerTest extends AbstractControllerTest { class CurrencyControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/currencies/"; private static final String REST_URL = "/currencies/";
/**
* {@link CurrencyController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /currencies/ <br>
* Ответ CurrencyController <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Currency currency = new Currency(); Currency currency = new Currency();
currency.setId(currentId.get()); currency.setId(currentId.get());
currency.setCountryCode("acc"); currency.setCountryCode("acc");
currency.setCurrencyCode("acc"); currency.setCurrencyCode("acc");
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Currency, currency, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Currency, currency, REST_URL);
} }
} }

View file

@ -10,15 +10,8 @@ import java.time.LocalDate;
class ErrorTextControllerTest extends AbstractControllerTest { class ErrorTextControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/error-texts/"; private static final String REST_URL = "/error-texts/";
/**
* {@link ErrorTextController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /error-texts/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
ErrorText errorText = new ErrorText(); ErrorText errorText = new ErrorText();
errorText.setId(currentId.get()); errorText.setId(currentId.get());
errorText.setText("text"); errorText.setText("text");

View file

@ -10,15 +10,8 @@ import java.math.BigDecimal;
class ListingControllerTest extends AbstractControllerTest { class ListingControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/listings/"; private static final String REST_URL = "/listings/";
/**
* {@link ListingController#getAll()} <br>
* Тест проверяет получение запроса по REST API.<br>
* Входной запрос /listings/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test @Test
void getAll() throws Exception { void getAll() throws Exception {
//ARRANGE
Listing liabilitiesClaimsAssets = new Listing(); Listing liabilitiesClaimsAssets = new Listing();
liabilitiesClaimsAssets.setId(currentId.get()); liabilitiesClaimsAssets.setId(currentId.get());
liabilitiesClaimsAssets.setSecurityId(currentId.get()); liabilitiesClaimsAssets.setSecurityId(currentId.get());
@ -28,8 +21,6 @@ class ListingControllerTest extends AbstractControllerTest {
liabilitiesClaimsAssets.setSymbolName("res"); liabilitiesClaimsAssets.setSymbolName("res");
liabilitiesClaimsAssets.setTradingCurrency("trad"); liabilitiesClaimsAssets.setTradingCurrency("trad");
liabilitiesClaimsAssets.setWorkflowStatus("work"); liabilitiesClaimsAssets.setWorkflowStatus("work");
//ACT and ASSERT
checkGettingAllFromRestApi(IMDGDistributedNames.Map_Listing, liabilitiesClaimsAssets, REST_URL); checkGettingAllFromRestApi(IMDGDistributedNames.Map_Listing, liabilitiesClaimsAssets, REST_URL);
} }
} }

Some files were not shown because too many files have changed in this diff Show more