company-service: refactoring CompanyService + transaction

This commit is contained in:
AKurakin 2023-04-05 20:58:17 +03:00
parent edff45ebae
commit 1adc5db487
6 changed files with 314 additions and 145 deletions

View file

@ -19,7 +19,7 @@ public enum CompanyErrors implements IErrorEnumId {
ContactNotFound(3015L), // Контакт компании %s не найден.
CategoryNotFound(3016L), // Категория компании %s не найдена.
CategoryAlreadySet(3017L), // Компании %s уже присвоена категория %s.
CompanyAlreadyHas_(3018L), // У компании %s присутствуют обязательства.
CompanyAlreadyHasLiabilities(3018L), // У компании %s присутствуют обязательства.
EditCompanySymbols(3020L), // Тип реквизита компании %s не может быть изменен.
EditContactType(3021L) // Тип контакта компании %s не может быть изменен.
;

View file

@ -0,0 +1,64 @@
package ru.spcex.clearing.company.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.account.Account;
import ru.clearing.classes.statics.data.liabilities.LiabilitiesClaimsAssets;
import ru.spcex.clearing.company.error.CompanyErrors;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.sdf01.AccountTerminationRequest;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import java.math.BigDecimal;
import java.util.Collection;
@Service
public class AccountNotificationHelper {
private final Logger log = LoggerFactory.getLogger(getClass());
KafkaSender kafkaSender;
Imdg<LiabilitiesClaimsAssets> liabilitiesClaimsAssetsMap;
Imdg<Account> accountMap;
@Autowired
public AccountNotificationHelper(
KafkaSender kafkaSender,
ImdgProvider imdgProvider) {
this.kafkaSender = kafkaSender;
this.liabilitiesClaimsAssetsMap = imdgProvider.getImdg(IMDGDistributedNames.Map_LiabilitiesClaimsAssets, LiabilitiesClaimsAssets.class);
this.accountMap = imdgProvider.getImdg(IMDGDistributedNames.Map_Account, Account.class);
}
public CompanyErrors accountTerminationNotification(Long companyId) {
Collection<Account> accounts = accountMap.getCollectionObjectsBySQL("companyId=" + companyId);
log.trace("Found {} accounts by company {}", accounts.size(), companyId);
for (Account account : accounts) {
Collection<LiabilitiesClaimsAssets> liabilities = liabilitiesClaimsAssetsMap.getCollectionObjectsBySQL("accountId=" + account.getId());
for (LiabilitiesClaimsAssets liability : liabilities) {
if (liability.getLiabilitiesQuantity() != null && BigDecimal.ZERO.compareTo(liability.getLiabilitiesQuantity()) == 0) {
return CompanyErrors.CompanyAlreadyHasLiabilities;
}
}
}
log.debug("Sending messages to account-service for {} account", accounts.size());
for (Account account : accounts) {
Long reqId = kafkaSender.sendRequestToQueue(Consts.ACCOUNT_TERMINATION, createAccountsRequest(companyId, account));
log.debug("For account[{}] sended termination request id={}", account.getId(), reqId);
}
return null;
}
private AccountTerminationRequest createAccountsRequest(Long companyId, Account account) {
AccountTerminationRequest r = new AccountTerminationRequest();
r.setCompanyId(companyId);
r.setAccount(account.getAccount());
r.setAccountId(account.getId());
return r;
}
}

View file

@ -26,6 +26,7 @@ import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgId;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.ImdgTransaction;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.error.ValidationException;
import ru.spcex.platform.utils.validation.IValidator;
@ -36,15 +37,16 @@ import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
// todo добавить транзакции! Это важно из-за AccountNotification
@Service
public class CompanyService extends QueueConsumer implements InitializingBean {
protected static final Long SPVB_ID = 1L; // СПВБ
private final Logger log = LoggerFactory.getLogger(getClass());
private final RequestHelper requestHelper;
private final Imdg<Company> companyMap;
private final ImdgProvider imdgProvider;
// private final Imdg<Company> companyMap;
private final Imdg<CompanySymbols> companySymnbolsMap;
private final Imdg<Relation> relationMap;
// private final Imdg<Relation> relationMap;
private final ImdgId idSequence;
protected UserRoleVerification userRoleVerification;
protected IMessageResolver messageResolver;
@ -55,6 +57,8 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
private Function<CommonDeleteRequest, IValidator> companyDeleteRequestValidator;
protected CompanySymbolService companySymbolService;
protected AccountNotificationHelper accountNotification;
protected RelationHelper relationHelper;
@Autowired
public CompanyService(Consumer<String, Object> kafkaQueue, Producer<String, Object> kafkaProducer,
@ -69,13 +73,18 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
@Qualifier("CompanyDeleteRequestValidator")
Function<CommonDeleteRequest, IValidator> companyDeleteRequestValidator,
CompanySymbolService companySymbolService
CompanySymbolService companySymbolService,
AccountNotificationHelper accountNotification,
RelationHelper relationHelper
) {
super(kafkaQueue, kafkaProducer);
this.imdgProvider = imdgProvider;
this.messageResolver = messageResolver;
this.requestHelper = new RequestHelper(log, messageResolver);
this.companyMap = imdgProvider.getImdg(IMDGDistributedNames.Map_Company, Company.class);
this.relationMap = imdgProvider.getImdg(IMDGDistributedNames.Map_Relation, Relation.class);
// this.companyMap = imdgProvider.getImdg(IMDGDistributedNames.Map_Company, Company.class);
// this.relationMap = imdgProvider.getImdg(IMDGDistributedNames.Map_Relation, Relation.class);
this.companySymnbolsMap = imdgProvider.getImdg(IMDGDistributedNames.Map_CompanySymbols, CompanySymbols.class);
this.idSequence = imdgProvider.getImdgIdGenerator();
this.userRoleVerification = userRoleVerification;
@ -84,6 +93,8 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
this.companyUpdateRequestValidator = companyUpdateRequestValidator;
this.companyDeleteRequestValidator = companyDeleteRequestValidator;
this.companySymbolService = companySymbolService;
this.accountNotification = accountNotification;
this.relationHelper = relationHelper;
}
@Override
@ -128,19 +139,31 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
company.setShortName(req.getShortName());
company.setFullName(req.getFullName());
if (req.getCompanySymbol() != null) {
CompanySymbols newSymbol = companySymbolService.createCompanySymbol(company.getId(), req.getCompanySymbol(), req.getCompanySymbolValue());
updateCompanyBySymbol(company, newSymbol);
}
ImdgTransaction transaction = imdgProvider.newTransaction();
transaction.beginTransaction();
boolean txOk = false;
try {
if (req.getCompanySymbol() != null) {
CompanySymbols newSymbol = companySymbolService.createCompanySymbol(transaction, company.getId(), req.getCompanySymbol(), req.getCompanySymbolValue());
updateCompanyBySymbol(company, newSymbol);
}
company.setWorkflowStatus(req.getWorkflowStatus());
company.setWorkflowStatus(req.getWorkflowStatus());
companyMap.insert(company);
log.debug("company-new request processed, BaseRequest.id = {}, company.id={}",
companyNewRequestBaseRequest.getId(), company.getId());
createNewRelation(company);
if (!(WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus()))) { // Block
onChangeWorkflowStatus(company, null, company.getWorkflowStatus());
Imdg<Company> companyMap = transaction.getImdg(IMDGDistributedNames.Map_Company, Company.class);
companyMap.insert(company);
log.debug("company-new request processed, BaseRequest.id = {}, company.id={}",
companyNewRequestBaseRequest.getId(), company.getId());
relationHelper.createNewRelation(transaction, company);
if (!(WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus()))) { // Block
relationHelper.onChangeWorkflowStatus(transaction, company, null, company.getWorkflowStatus());
}
txOk = true;
} finally {
if (txOk)
transaction.commitTransaction();
else
transaction.rollbackTransaction();
}
return null;
}
@ -153,36 +176,49 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
RequestInfoUpdate requestInfoUpdate = validationHelper.validateTillFirstError(companyUpdateRequestBaseRequest, companyUpdateRequestValidator);
if (requestInfoUpdate != null) return requestInfoUpdate;
}
Company company = companyMap.getSingleObjectByID(updateRequest.getId()); // todo use validationContext.
if (company == null) {
log.trace("Company {} not found", updateRequest.getId());
return requestHelper.makeErrorResponse(companyUpdateRequestBaseRequest, CompanyErrors.CompanyNotFound, updateRequest.getId());
}
if (!WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
log.trace("Company {} not active: {}", company.getId(), company.getWorkflowStatus());
return requestHelper.makeErrorResponse(companyUpdateRequestBaseRequest, CompanyErrors.CompanyDisabled, updateRequest.getId());
}
ImdgTransaction transaction = imdgProvider.newTransaction();
transaction.beginTransaction();
boolean txOk = false;
try {
Imdg<Company> companyMap = transaction.getImdg(IMDGDistributedNames.Map_Company, Company.class);
company.setUpdated(Instant.now());
company.setShortName(updateRequest.getShortName());
company.setFullName(updateRequest.getFullName());
Company company = companyMap.getSingleObjectByID(updateRequest.getId());
if (company == null) {
log.trace("Company {} not found", updateRequest.getId());
return requestHelper.makeErrorResponse(companyUpdateRequestBaseRequest, CompanyErrors.CompanyNotFound, updateRequest.getId());
}
if (!WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
log.trace("Company {} not active: {}", company.getId(), company.getWorkflowStatus());
return requestHelper.makeErrorResponse(companyUpdateRequestBaseRequest, CompanyErrors.CompanyDisabled, updateRequest.getId());
}
if (updateRequest.getCompanySymbol() != null || updateRequest.getCompanySymbolValue() != null) {
log.trace("Request field CompanySymbol, CompanySymbolValue ignore for update company request.");
}
company.setUpdated(Instant.now());
company.setShortName(updateRequest.getShortName());
company.setFullName(updateRequest.getFullName());
if (updateRequest.getCompanySymbol() != null || updateRequest.getCompanySymbolValue() != null) {
log.trace("Request field CompanySymbol, CompanySymbolValue ignore for update company request.");
}
// CompanySymbols не обновляем
String prevStatus = company.getWorkflowStatus();
if (updateRequest.getWorkflowStatus() != null) {
company.setWorkflowStatus(updateRequest.getWorkflowStatus());
if (!Objects.equals(prevStatus, company.getWorkflowStatus())) {
onChangeWorkflowStatus(company, prevStatus, company.getWorkflowStatus());
String prevStatus = company.getWorkflowStatus();
if (updateRequest.getWorkflowStatus() != null) {
company.setWorkflowStatus(updateRequest.getWorkflowStatus());
if (!Objects.equals(prevStatus, company.getWorkflowStatus())) {
relationHelper.onChangeWorkflowStatus(transaction, company, prevStatus, company.getWorkflowStatus());
} else {
log.trace("Status was not changed");
}
} else {
log.trace("Status was not changed");
log.trace("Null new WorkflowStatus");
}
} else {
log.trace("Null new WorkflowStatus");
txOk = true;
} finally {
if (txOk)
transaction.commitTransaction();
else
transaction.rollbackTransaction();
}
return null;
}
@ -206,65 +242,6 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
}
}
protected void kafkaSentAccountNotification(Company aboutBlockCompany) {
log.debug("Send message to kafka...");
//todo message to queue
}
protected void createNewRelation(Company company) {
Relation relation = new Relation();
relation.setId(idSequence.nextId());
relation.setCreated(Instant.now());
relation.setUpdated(relation.getCreated());
relation.setConsumerId(company.getId());
relation.setSupplierId(SPVB_ID); // 1 СПВБ
relation.setServiceStatus(WorkflowStatus.Active.getKey());
relation.setService(ru.spcex.platform.enumeration.Service.MKR.getKey()); // MKR
relation.setServiceProduct(ServiceProduct.ZERO.getKey());
log.debug("New Relation[{}] created.", relation.getId());
relationMap.insert(relation);
}
/**
* @param company
* @param oldStatus
* @param newStatus WorkflowStatus.Active - при возобналвении; WorkflowStatus.Blocked - при блокировки/расторжении
*/
private void onChangeWorkflowStatus(Company company, String oldStatus, String newStatus) {
log.debug("Company id={} status changed from {} to {}",
company.getId(), oldStatus, company.getWorkflowStatus());
assert Objects.equals(newStatus, company.getWorkflowStatus());
String query = String.format("consumerId=%s", company.getId());
Collection<Relation> relations = relationMap.getCollectionObjectsBySQL(query);
log.trace("Selected {} Relation by query: {}", relations.size(), query);
Instant now = Instant.now();
for (Relation relation : relations) {
boolean modified = false;
if (WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
if (!ServiceStatus.Reopened.equalsByKey(relation.getServiceStatus())) {
relation.setServiceStatus(ServiceStatus.Reopened.getKey());
modified = true;
}
} else if (WorkflowStatus.Blocked.equalsByKey(company.getWorkflowStatus())) {
if (!ServiceStatus.Closed.equalsByKey(relation.getServiceStatus())) {
relation.setServiceStatus(ServiceStatus.Closed.getKey());
modified = true;
}
}
if (modified) {
relation.setUpdated(now);
log.debug("Relation id={} updated", relation.getId());
relationMap.update(relation);
}
}
if (WorkflowStatus.Blocked.equalsByKey(newStatus)) {
kafkaSentAccountNotification(company);
}
}
/**
* Блокировка компании
*
@ -279,54 +256,45 @@ public class CompanyService extends QueueConsumer implements InitializingBean {
RequestInfoUpdate requestInfoUpdate = validationHelper.validateTillFirstError(companyBlockRequestBaseRequest, companyDeleteRequestValidator);
if (requestInfoUpdate != null) return requestInfoUpdate;
}
Company company = companyMap.getSingleObjectByID(request.getId());
if (company == null) {
log.warn("Company {} not found", request.getId());
return requestHelper.makeErrorResponse(companyBlockRequestBaseRequest, CompanyErrors.CompanyNotFound, request.getId());
ImdgTransaction transaction = imdgProvider.newTransaction();
transaction.beginTransaction();
boolean txOk = false;
try {
Imdg<Company> companyMap = transaction.getImdg(IMDGDistributedNames.Map_Company, Company.class);
Company company = companyMap.getSingleObjectByID(request.getId());
if (company == null) {
log.warn("Company {} not found", request.getId());
return requestHelper.makeErrorResponse(companyBlockRequestBaseRequest, CompanyErrors.CompanyNotFound, request.getId());
}
company.setUpdated(Instant.now());
CompanySymbols companySymbol = companySymnbolsMap.getSingleObjectByFieldValues(Map.of("companyId", company.getId()));
if (companySymbol == null) {
log.warn("CompanySymbols not found for companyId={}", company.getId());
} else {
log.trace("Found CompanySymbols.id={} for companyId={}", companySymbol.getId(), company.getId());
updateCompanyBySymbol(company, companySymbol);
}
String prevStatus = company.getWorkflowStatus();
company.setWorkflowStatus(WorkflowStatus.Blocked.getKey());
log.debug("Update company.id={}", company.getId());
companyMap.update(company);
relationHelper.onChangeWorkflowStatus(transaction, company, prevStatus, company.getWorkflowStatus());
txOk = true;
} finally {
if (txOk)
transaction.commitTransaction();
else
transaction.rollbackTransaction();
}
company.setUpdated(Instant.now());
CompanySymbols companySymbol = companySymnbolsMap.getSingleObjectByFieldValues(Map.of("companyId", company.getId()));
if (companySymbol == null) {
log.warn("CompanySymbols not found for companyId={}", company.getId());
} else {
log.trace("Found CompanySymbols.id={} for companyId={}", companySymbol.getId(), company.getId());
updateCompanyBySymbol(company, companySymbol);
}
String prevStatus = company.getWorkflowStatus();
company.setWorkflowStatus(WorkflowStatus.Blocked.getKey());
log.debug("Update company.id={}", company.getId());
companyMap.update(company);
onChangeWorkflowStatus(company, prevStatus, company.getWorkflowStatus());
return null;
// Company company = companyMap.getSingleObjectByID(req.getId());
// companyMap.delete(company);
}
/**
* IV - сообщения на добавления документа расторжения договора
*
* @param companyId
*/
public synchronized void onRastorjeniye(Long companyId) {
Company company = companyMap.getSingleObjectByID(companyId);
if (company == null) {
log.warn("Company {} not found", companyId);
return;
}
if (!WorkflowStatus.Blocked.equalsByKey(company.getWorkflowStatus())) {
log.debug("Update company.id={}", company.getId());
company.setWorkflowStatus(WorkflowStatus.Blocked.getKey());
company.setUpdated(Instant.now());
companyMap.update(company);
} else {
log.trace("Company {} already has blocked.", companyId);
}
}
}

View file

@ -17,6 +17,7 @@ import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgId;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.ImdgTransaction;
import java.util.Objects;
@ -53,7 +54,8 @@ public class CompanySymbolService extends QueueConsumer implements InitializingB
log.debug("successfully processed, id {}", companySymbols.getId());
}
public CompanySymbols createCompanySymbol(Long companyId, String companySymbol, String companySymbolValue) {
public CompanySymbols createCompanySymbol(ImdgTransaction transaction, Long companyId, String companySymbol, String companySymbolValue) {
Objects.requireNonNull(companyId);
CompanySymbols newSymbol = new CompanySymbols();
newSymbol.setId(idSequence.nextId());
@ -61,7 +63,12 @@ public class CompanySymbolService extends QueueConsumer implements InitializingB
newSymbol.setCompanySymbol(companySymbol);
newSymbol.setCompanySymbolValue(companySymbolValue);
log.debug("Created new companySymbols.id={} for company {}", newSymbol.getId(), companyId);
companySymbolsMap.insert(newSymbol);
if (transaction == null) {
companySymbolsMap.insert(newSymbol);
} else {
Imdg<CompanySymbols> tMap = transaction.getImdg(IMDGDistributedNames.Map_CompanySymbols, CompanySymbols.class);
tMap.insert(newSymbol);
}
return newSymbol;
}
}

View file

@ -0,0 +1,94 @@
package ru.spcex.clearing.company.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.spcex.clearing.company.error.CompanyErrors;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.platform.enumeration.ServiceProduct;
import ru.spcex.platform.enumeration.ServiceStatus;
import ru.spcex.platform.enumeration.WorkflowStatus;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgTransaction;
import ru.spcex.platform.utils.error.ValidationException;
import java.time.Instant;
import java.util.Collection;
import java.util.Objects;
@Service
public class RelationHelper {
protected static final Long SPVB_ID = 1L; // СПВБ
protected final Logger log = LoggerFactory.getLogger(getClass());
protected AccountNotificationHelper accountNotification;
@Autowired
public RelationHelper(AccountNotificationHelper accountNotification) {
this.accountNotification = accountNotification;
}
protected void createNewRelation(ImdgTransaction transaction, Company company) {
Relation relation = new Relation();
// relation.setId(idSequence.nextId());
relation.setCreated(Instant.now());
relation.setUpdated(relation.getCreated());
relation.setConsumerId(company.getId());
relation.setSupplierId(SPVB_ID); // 1 СПВБ
relation.setServiceStatus(WorkflowStatus.Active.getKey());
relation.setService(ru.spcex.platform.enumeration.Service.MKR.getKey()); // MKR
relation.setServiceProduct(ServiceProduct.ZERO.getKey());
log.debug("New Relation[{}] created.", relation.getId());
Imdg<Relation> relationMap = transaction.getImdg(IMDGDistributedNames.Map_Relation, Relation.class);
relationMap.insert(relation);
}
/**
* @param company
* @param oldStatus
* @param newStatus WorkflowStatus.Active - при возобналвении; WorkflowStatus.Blocked - при блокировки/расторжении
*/
public void onChangeWorkflowStatus(ImdgTransaction transaction, Company company, String oldStatus, String newStatus) throws ValidationException {
log.debug("Company id={} status changed from {} to {}",
company.getId(), oldStatus, company.getWorkflowStatus());
assert Objects.equals(newStatus, company.getWorkflowStatus());
String query = String.format("consumerId=%s", company.getId());
Imdg<Relation> relationMap = transaction.getImdg(IMDGDistributedNames.Map_Relation, Relation.class);
Collection<Relation> relations = relationMap.getCollectionObjectsBySQL(query);
log.trace("Selected {} Relation by query: {}", relations.size(), query);
Instant now = Instant.now();
for (Relation relation : relations) {
boolean modified = false;
if (WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
if (!ServiceStatus.Reopened.equalsByKey(relation.getServiceStatus())) {
relation.setServiceStatus(ServiceStatus.Reopened.getKey());
modified = true;
}
} else if (WorkflowStatus.Blocked.equalsByKey(company.getWorkflowStatus())) {
if (!ServiceStatus.Closed.equalsByKey(relation.getServiceStatus())) {
relation.setServiceStatus(ServiceStatus.Closed.getKey());
modified = true;
}
}
if (modified) {
relation.setUpdated(now);
log.debug("Relation id={} updated", relation.getId());
relationMap.update(relation);
}
}
if (WorkflowStatus.Blocked.equalsByKey(newStatus)) {
// IV - сообщения на добавления документа расторжения договора
CompanyErrors hasError = accountNotification.accountTerminationNotification(company.getId());
if (hasError != null) {
log.warn("Can not block company, cause error {}", hasError);
throw new ValidationException(hasError);
}
}
}
}

View file

@ -0,0 +1,36 @@
package ru.spcex.clearing.platform.messaging.domain.cud.account.sdf01;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AccountTerminationRequest {
@JsonProperty
private String account;
@JsonProperty
private Long accountId;
@JsonProperty
private Long companyId;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
}