Merge branch 'dev' into cls-301

This commit is contained in:
akulikov 2023-05-24 13:00:04 +03:00
commit 0e4b425645
162 changed files with 7518 additions and 3774 deletions

View file

@ -32,6 +32,14 @@
<groupId>ru.spcex.clearing</groupId>
<artifactId>classes</artifactId>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>security-util</artifactId>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>clearing-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
@ -41,6 +49,11 @@
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- TEST -->
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>test-clearing</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -65,14 +78,6 @@
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>security-util</artifactId>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>clearing-validation</artifactId>
</dependency>
</dependencies>

View file

@ -106,6 +106,7 @@ public class AccountValidationConfig {
Consumer<String> addImdg = (s) -> context.addImdg(s, imdgForValidation.get(s));
addImdg.accept(IMDGDistributedNames.Map_Company);
addImdg.accept(IMDGDistributedNames.Map_Account);
addImdg.accept(IMDGDistributedNames.Map_ServiceStatusDictionary);
addImdg.accept(IMDGDistributedNames.Map_AccountTypeDictionary);
return new ValidatorImpl<>(context,
IdPresentRule.instance("id",
@ -141,7 +142,7 @@ public class AccountValidationConfig {
DictionaryPresentRule.instance("accountType",
CorrespondentAccountUpdateRequest::getAccountType,
IMDGDistributedNames.Map_AccountTypeDictionary,
ServiceStatusDictionary.class,
AccountTypeDictionary.class,
AccountError.RequiredFieldEmpty,
AccountError.WrongFieldValue,
accountType -> {

View file

@ -22,6 +22,7 @@ import ru.spcex.clearing.platform.messaging.domain.cud.account.sdf01.AccountSdfR
import ru.spcex.clearing.platform.messaging.domain.cud.balance.AccountSdfToStatementRequestPart;
import ru.spcex.clearing.platform.messaging.domain.cud.balance.StatementRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonIdRequest;
import ru.spcex.clearing.platform.messaging.serialization.LogFormatter;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.Status;
@ -215,10 +216,12 @@ public class AccountService extends QueueConsumer implements InitializingBean {
return responsePart;
}
@Deprecated
public void sendStatementRequestBack(Long groupingSdf01Id, List<AccountSdfToStatementRequestPart> results) {
StatementRequest request = new StatementRequest();
request.setGroupId(groupingSdf01Id);
request.setAccountCreationResults(results);
log.debug("Send message to kafka \"{}\": {}", Consts.STATEMENT_PROCESS, LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(Consts.STATEMENT_PROCESS, request);
}

View file

@ -17,6 +17,7 @@ import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClearingAccountNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClearingAccountUpdateRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryNewRequest;
import ru.spcex.clearing.platform.messaging.serialization.LogFormatter;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
@ -78,13 +79,13 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
@Override
public void afterPropertiesSet() throws Exception {
init();
callback(ClearingAccountNewRequest.class)
.setFunction(this::clearingAccountNew)
.forDestination(Consts.DESTINATION_CLEARING_ACCOUNT_NEW, callbacks::put);
callback(ClearingAccountUpdateRequest.class)
.setFunction(this::clearingAccountUpdate)
.forDestination(Consts.DESTINATION_CLEARING_ACCOUNT_UPDATE, callbacks::put);
init();
}
public RequestInfoUpdate clearingAccountNew(BaseRequest<ClearingAccountNewRequest> userRequest) {
@ -127,6 +128,8 @@ public class ClearingAccountService extends QueueConsumer implements Initializin
TradingClearingRegistryNewRequest request = new TradingClearingRegistryNewRequest();
request.setMoneyAccountId(accountId);
request.setCompanyId(clearingAccount.getCompanyId());
log.debug("Send message to kafka \"{}\": {}", Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW,
LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, request);
log.debug("successfully processed, new clearing account id {}, account id {}", clearingAccountId, accountId);
} else {

View file

@ -6,13 +6,11 @@ import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.account.ClientCode;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.spcex.clearing.account.errors.AccountError;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
@ -24,28 +22,24 @@ import ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeUpdateR
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryUpdateRequest;
import ru.spcex.clearing.platform.messaging.serialization.LogFormatter;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.Status;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.util.security.UserRoleVerification;
import ru.spcex.clearing.util.services.RequestHelper;
import ru.spcex.clearing.util.services.exchangers.BiDirectionQueueExchanger;
import ru.spcex.clearing.validation.common.ValidationHelper;
import ru.spcex.platform.enumeration.TradingClearingRegistryType;
import ru.spcex.platform.enumeration.WorkflowStatus;
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.iml.hazelcast.adapter.ImdgIdGeneratorHazelcast;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.error.ClearingBaseException;
import ru.spcex.platform.utils.log.ExceptionUtils;
import ru.spcex.platform.utils.validation.IValidator;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@ -310,6 +304,7 @@ public class ClientCodeService extends QueueConsumer implements InitializingBean
requestPayload.setStatus(WorkflowStatus.Blocked.getKey());
request.setRequestPayload(requestPayload);
log.debug("Send message to kafka \"{}\": {}", Consts.DESTINATION_TRADING_CLEARING_REGISTRY_UPDATE, LogFormatter.toStringWrapper(request));
try {
sendMessage(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_UPDATE, request);
} catch (Exception e) {

View file

@ -14,6 +14,7 @@ import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.DepoAccountNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryNewRequest;
import ru.spcex.clearing.platform.messaging.serialization.LogFormatter;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
@ -107,6 +108,7 @@ public class DepoAccountService extends QueueConsumer implements InitializingBea
TradingClearingRegistryNewRequest request = new TradingClearingRegistryNewRequest();
request.setDepoAccountId(accountId);
request.setCompanyId(depoAccount.getCompanyId());
log.debug("Send message to kafka \"{}\": {}", Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, request);
log.debug("successfully processed, new depo account id {}, account id {}", depoAccountId, accountId);
} else {

View file

@ -16,6 +16,7 @@ import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.InformationAccountNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryNewRequest;
import ru.spcex.clearing.platform.messaging.serialization.LogFormatter;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
@ -137,6 +138,7 @@ public class InformationAccountService extends QueueConsumer implements Initiali
TradingClearingRegistryNewRequest request = new TradingClearingRegistryNewRequest();
request.setMoneyAccountId(informationAccountId);
request.setCompanyId(informationAccount.getCompanyId());
log.debug("Send message to kafka \"{}\": {}", Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, LogFormatter.toStringWrapper(request));
kafkaSender.sendRequestToQueue(Consts.DESTINATION_TRADING_CLEARING_REGISTRY_AUTO_NEW, request);
log.debug("successfully processed, new information account id {}, new account id {}",
informationAccountId,

View file

@ -27,8 +27,6 @@ import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingR
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryUpdateRequest;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.platform.messaging.service.Status;
import ru.spcex.clearing.platform.messaging.service.sender.CorrelationHeader;
import ru.spcex.clearing.util.security.UserRoleVerification;
import ru.spcex.clearing.util.services.RequestHelper;
import ru.spcex.clearing.validation.common.ValidationHelper;
@ -41,7 +39,6 @@ import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicate;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicateBuilder;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.log.ExceptionUtils;
import ru.spcex.platform.utils.validation.IValidator;
import java.time.Instant;
@ -49,7 +46,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.function.Function;
@Service
@ -276,13 +272,11 @@ public class TradingClearingRegistryService extends QueueConsumer implements Ini
log.debug("TradingClearingRegistryNewRequest received");
RequestInfoUpdate requestInfoUpdate = userRoleVerification.validateRoleAndGetResult(userRequest);
if (requestInfoUpdate != null) {
sendResponse(userRequest, requestInfoUpdate, null);
return requestInfoUpdate;
}
requestInfoUpdate = validationHelper.validateTillFirstError(userRequest, tradingClearingRegistryNewRequestValidator);
if (requestInfoUpdate != null) {
sendResponse(userRequest, requestInfoUpdate, null);
return requestInfoUpdate;
}

View file

@ -1,70 +0,0 @@
package ru.spcex.clearing.account.config;
import com.hazelcast.config.*;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
import ru.spcex.platform.imdg.iml.hazelcast.util.HazelcastHelper;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
@Configuration
public class HazelcastServiceTestConfiguration {
public static final AtomicLong currentID = new AtomicLong(0L);
private HazelcastInstance hazelcastInstance;
private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
if (maxPoolSz > 2) {
pool.setKeepAliveSeconds(60);
pool.setAllowCoreThreadTimeOut(true);
}
pool.setCorePoolSize(maxPoolSz);
pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion);
return pool;
}
@Bean(name = "hazelcastServiceTest")
public HazelcastService hazelcastService(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer, @Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter, HazelcastClientParams params) {
Config cfg = new Config();
cfg.setInstanceName("localhost");
NetworkConfig networkConfig = new NetworkConfig();
JoinConfig joinConfig = new JoinConfig();
joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false));
joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1")));
networkConfig.setJoin(joinConfig);
cfg.setNetworkConfig(networkConfig);
hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(cfg);
HazelcastHelper.imdgSystem_setStorageState(true, hazelcastInstance);
return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params);
}
@Bean(name = "taskExecutorHazelcastClientInitializer")
public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() {
return createThreadPoolTaskExecutor(1, true);
}
@Bean(name = "taskExecutorIdGeneratorAwaiter")
public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() {
return createThreadPoolTaskExecutor(1, false);
}
@Bean(name = "hazelcastClientParams")
public HazelcastClientParams getHazelcastClientParams() {
HazelcastClientParams params = new HazelcastClientParams();
params.setLogin("dev");
params.setPassword("dev-pass");
params.setClusterMembers("127.0.0.1");
params.setInstanceName("hzTestClient" + new Random().nextInt());
params.setNearCacheConfig(new NearCacheConfig());
return params;
}
}

View file

@ -1,44 +0,0 @@
package ru.spcex.clearing.account.config;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.clients.producer.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.service.RequestInfo;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgId;
import ru.spcex.platform.imdg.api.ImdgProvider;
@Configuration
public class KafkaConfigTest {
@Autowired
@Bean(name = "kafkaSenderTest")
public KafkaSender kafkaSender(Producer<String, Object> kafkaProducer, @Qualifier("hazelcastServiceTest") ImdgProvider imdgProvider) {
ImdgId imdgIdGenerator = imdgProvider.getImdgIdGenerator();
return KafkaSender
.setup()
.producer(kafkaProducer)
.idGenerator(imdgIdGenerator::nextId)
.imdgProvider(s -> {
Imdg<RequestInfo> imdg = imdgProvider.getImdg(IMDGDistributedNames.Map_RequestInfo, RequestInfo.class);
return imdg::insert;
})
.build();
}
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Bean(name = "mockConsumerTest")
public MockConsumer<String, Object> createConsumer() {
return new MockConsumer<>(OffsetResetStrategy.EARLIEST);
}
}

View file

@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -21,8 +22,6 @@ import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.platform.dictionary.AccountTypeDictionary;
import ru.clearing.platform.dictionary.ServiceStatusDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.AccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
import ru.spcex.clearing.account.utils.MatcherFactory;
@ -39,6 +38,9 @@ import ru.spcex.clearing.platform.messaging.domain.cud.balance.StatementRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest;
import ru.spcex.clearing.platform.messaging.service.RequestInfo;
import ru.spcex.clearing.platform.messaging.service.Status;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.adapter.ImdgHazelcast;
@ -52,9 +54,9 @@ import java.util.UUID;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration.currentID;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.*;
import static ru.spcex.clearing.test.TestUtils.*;
import static ru.spcex.clearing.test.config.ImdgTestConfig.currentID;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -62,8 +64,8 @@ import static ru.spcex.clearing.account.utils.TestUtils.*;
ValidationConfig.class,
AccountValidationConfig.class,
AccountService.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
class AccountServiceTest {
public static final MatcherFactory.Matcher<Account> ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
public static final MatcherFactory.Matcher<RequestInfo> REQUEST_INFO_MATCHER_MATCHER = usingIgnoringFieldsComparator("created");
@ -82,6 +84,9 @@ class AccountServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
private Imdg<Account> accountImdg;
private Imdg<Company> companyImdg;
@ -136,6 +141,8 @@ class AccountServiceTest {
relation.setConsumerId(companyId);
relation.setService(Service.MKR.getKey());
relationImdg.insert(relation);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
@Test
@ -163,7 +170,7 @@ class AccountServiceTest {
0,
jsonString);
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, mockProducer);
Account resultNew = accountImdg.getCollectionObjectsByFieldValues(Map.of("account", uniqueAccount)).iterator().next();
predictableAccount.setId(resultNew.getId());
@ -190,7 +197,7 @@ class AccountServiceTest {
correspondentAccountUpdateRequest.setId(accountId);
String jsonString = getJsonStringForUPDATE(correspondentAccountUpdateRequest, 0);
String jsonString = getJsonStringForUpdate(correspondentAccountUpdateRequest, 0);
//ACT
addRecordToKafka((MockConsumer) accountService.getConsumer(),
@ -200,7 +207,7 @@ class AccountServiceTest {
jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, mockProducer);
Account resultUpdating = accountImdg.getSingleObjectByID(accountId);
existAccount.setUpdated(resultUpdating.getUpdated());
@ -220,7 +227,7 @@ class AccountServiceTest {
CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest();
commonDeleteRequest.setId(accountId);
String jsonString = getJsonStringForDELETE(commonDeleteRequest, 0);
String jsonString = getJsonStringForDelete(commonDeleteRequest, 0);
//ACT
addRecordToKafka((MockConsumer) accountService.getConsumer(),
@ -230,7 +237,7 @@ class AccountServiceTest {
jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, mockProducer);
Account resultBlock = accountImdg.getSingleObjectByID(accountId);
existAccount.setStatus(ServiceStatus.Blocked.getKey());
@ -302,6 +309,7 @@ class AccountServiceTest {
//waiting for kafka producer send message (finale event)
verify(producer, timeout(30_000L).times(2))
.send(producerRecord.capture());
//todo переписать валидацию ожидания на новые waitingSendAndCheckRecord / waitingWhenTryAddRecordAndCheckError
ImdgHazelcast<Account> accountImdg = (ImdgHazelcast<Account>) hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_Account, Account.class);

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -20,8 +21,6 @@ import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.platform.dictionary.CurrencyCodeDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.AccountValidationConfig;
import ru.spcex.clearing.account.config.validation.BankAccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
@ -35,6 +34,9 @@ import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewReq
import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountUpdateRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@ -48,8 +50,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.*;
import static ru.spcex.clearing.platform.messaging.service.Status.Error;
import static ru.spcex.clearing.test.TestUtils.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -59,8 +61,8 @@ import static ru.spcex.clearing.platform.messaging.service.Status.Error;
BankAccountValidationConfig.class,
AccountValidationConfig.class,
BeanConfiguration.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
public class BankAccountServiceTest {
public static final Matcher<BankAccount> BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
public static final Matcher<Account> ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
@ -104,6 +106,9 @@ public class BankAccountServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
@PostConstruct
private void init() {
@ -124,6 +129,8 @@ public class BankAccountServiceTest {
currencyCodeDictionary.setCode("RUB");
currencyCodeDictionary.setName("RUB");
currencyCodeDictionaryImdg.insert(currencyCodeDictionary);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
/**
@ -170,7 +177,7 @@ public class BankAccountServiceTest {
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_NEW, PARTITION, 0, jsonString);
waitingWhenAddedRecordAndCheckIt(ID, producer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
Account accountResult = accountImdg.getSingleObjectBySQL(String.format("account = %s", acc));
BankAccount bankAccountResult = bankAccountImdg.getSingleObjectBySQL(String.format("account = %s or companyId = %s", acc, addresseeIdNew));
@ -343,13 +350,13 @@ public class BankAccountServiceTest {
bankAccountUpdateRequest.setTaxRegistrationReasonCode(predictableUpdateBankAccount.getTaxRegistrationReasonCode());
bankAccountUpdateRequest.setAccount(predictableUpdateBankAccount.getAccount());
String jsonString = getJsonStringForUPDATE(bankAccountUpdateRequest, ID);
String jsonString = getJsonStringForUpdate(bankAccountUpdateRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_UPDATE, PARTITION, 0, jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(ID, producer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
Account accountResult = accountImdg.getSingleObjectByID(predictableAccount.getId());
BankAccount resultUpdating = bankAccountImdg.getSingleObjectByID(predictableUpdateBankAccount.getId());
@ -378,13 +385,13 @@ public class BankAccountServiceTest {
CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest();
commonDeleteRequest.setId(ID);
String jsonString = getJsonStringForDELETE(commonDeleteRequest, ID);
String jsonString = getJsonStringForDelete(commonDeleteRequest, ID);
//ACT
addRecordToKafka((MockConsumer) bankAccountService.getConsumer(), TOPIC_ACCOUNT_DELETE, PARTITION, 0, jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(ID, producer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
BankAccount bankAccount = bankAccountImdg.getSingleObjectByID(ID);
Assertions.assertNull(bankAccount);

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -20,8 +21,6 @@ import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.platform.dictionary.AccountTypeDictionary;
import ru.clearing.platform.dictionary.ClearingAccountTypeDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.AccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ClearingAccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
@ -30,6 +29,9 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClearingAccountNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClearingAccountUpdateRequest;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@ -40,7 +42,7 @@ import java.util.Map;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.*;
import static ru.spcex.clearing.test.TestUtils.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -50,8 +52,8 @@ import static ru.spcex.clearing.account.utils.TestUtils.*;
AccountValidationConfig.class,
AccountService.class,
ClearingAccountService.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
class ClearingAccountServiceTest {
public static final MatcherFactory.Matcher<ClearingAccount> CLEARING_ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
public static final MatcherFactory.Matcher<Account> ACCOUNT_MATCHER = usingIgnoringFieldsComparator("created", "updated");
@ -73,6 +75,9 @@ class ClearingAccountServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
private Imdg<ClearingAccount> clearingAccountImdg;
private Imdg<Account> accountImdg;
@ -136,6 +141,7 @@ class ClearingAccountServiceTest {
relation.setService(Service.MKR.getKey());
relationImdg.insert(relation);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
@Test
@ -206,10 +212,10 @@ class ClearingAccountServiceTest {
clearingAccountUpdateRequest.setStatus(0);
clearingAccountUpdateRequest.setDeal(TRADING_CODE);
String jsonString = getJsonStringForUPDATE(clearingAccountUpdateRequest, 0L);
String jsonString = getJsonStringForUpdate(clearingAccountUpdateRequest, 0L);
addRecordToKafka((MockConsumer) clearingAccountService.getConsumer(), Consts.DESTINATION_CLEARING_ACCOUNT_UPDATE, PARTITION, 0, jsonString);
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, mockProducer);
Account accountResult = accountImdg.getSingleObjectByID(accountId);
predictableAccount.setId(accountResult.getId());

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -23,19 +24,20 @@ import ru.clearing.classes.statics.data.profile.CompanyInfo;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.clearing.platform.dictionary.*;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.ClientCodeValidationConfig;
import ru.spcex.clearing.account.config.validation.TradingClearingRegistryValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
import ru.spcex.clearing.account.utils.MatcherFactory;
import ru.spcex.clearing.account.utils.TestUtils;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.account.ClientCodeUpdateRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.TestUtils;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.TradingClearingRegistryType;
import ru.spcex.platform.enumeration.WorkflowStatus;
import ru.spcex.platform.imdg.api.Imdg;
@ -44,6 +46,7 @@ import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
import javax.annotation.PostConstruct;
import static org.junit.jupiter.api.Assertions.*;
import static ru.spcex.clearing.test.TestUtils.waitingSendAndCheckRecord;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -56,9 +59,8 @@ import static org.junit.jupiter.api.Assertions.*;
ValidationConfig.class,
BeanConfiguration.class,
KafkaConfigTest.class,
HazelcastServiceTestConfiguration.class,})
KafkaTestConfig.class,
ImdgTestConfig.class})
class ClientCodeServiceTest {
private static final int PARTITION = 0;
@ -75,7 +77,7 @@ class ClientCodeServiceTest {
private HazelcastService hazelcastServiceTest;
@Captor
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
@Qualifier("mockProducer")
private MockProducer<String, Object> mockProducer;
private Imdg<ClientCode> clientCodeImdg;
@ -149,8 +151,7 @@ class ClientCodeServiceTest {
depoAcc.setAccountId(depoAccount.getId());
depoAccounts.insert(depoAcc);
TestUtils.FutureRecordMetadata future = Mockito.spy(TestUtils.FutureRecordMetadata.class);
Mockito.doReturn(future).when(mockProducer).send(producerRecord.capture());
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
private <D extends AbstractDictionary> void putToDictionary(String mapName, D object, String code) {
@ -208,7 +209,7 @@ class ClientCodeServiceTest {
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString);
//ASSERT
TestUtils.waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultNew = clientCodeImdg.getSingleObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId());
CLIENT_CODE_MATCHER.assertMatch(resultNew, predictableClientCode);
@ -246,7 +247,7 @@ class ClientCodeServiceTest {
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW_UM_COMPANY, PARTITION, 0, jsonString);
//ASSERT
TestUtils.waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
TestUtils.waitingSendAndCheckRecord(ID, mockProducer, producerRecord);
ClientCode resultNew = clientCodeImdg.getSingleObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId());
CLIENT_CODE_MATCHER.assertMatch(resultNew, predictableClientCode);
@ -286,7 +287,7 @@ class ClientCodeServiceTest {
TestUtils.addRecordToKafka((MockConsumer) clientCodeService.getConsumer(), Consts.DESTINATION_CLIENT_CODE_NEW, PARTITION, 0, jsonString);
//ASSERT
TestUtils.waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultNew = clientCodeImdg.getSingleObjectBySQL(String.format("code = '%s'", ccCode));
predictableClientCode.setId(resultNew.getId());
CLIENT_CODE_MATCHER.assertMatch(resultNew, predictableClientCode);
@ -330,12 +331,12 @@ class ClientCodeServiceTest {
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);
//ASSERT
TestUtils.waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultUpdating = clientCodeImdg.getSingleObjectByID(ID);
CLIENT_CODE_MATCHER.assertMatch(resultUpdating, predictableClientCode);
@ -369,13 +370,13 @@ class ClientCodeServiceTest {
Assertions.assertNotNull(clientCodeImdg.getSingleObjectByID(ID)); // verify test data
//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);
//ASSERT
TestUtils.waitingWhenAddedRecordAndCheckIt(ID, mockProducer, producerRecord);
waitingSendAndCheckRecord(ID, mockProducer);
ClientCode resultUpdate = clientCodeImdg.getSingleObjectByID(ID);
Assertions.assertNull(resultUpdate);
}

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -20,8 +21,6 @@ import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.platform.dictionary.AccountTypeDictionary;
import ru.clearing.platform.dictionary.DepoAccountTypeDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.AccountValidationConfig;
import ru.spcex.clearing.account.config.validation.DepoAccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
@ -29,6 +28,9 @@ import ru.spcex.clearing.account.utils.MatcherFactory;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.DepoAccountNewRequest;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@ -39,8 +41,8 @@ import java.util.Map;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.account.utils.TestUtils.getJsonStringForNew;
import static ru.spcex.clearing.test.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.test.TestUtils.getJsonStringForNew;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -50,8 +52,8 @@ import static ru.spcex.clearing.account.utils.TestUtils.getJsonStringForNew;
AccountValidationConfig.class,
AccountService.class,
DepoAccountService.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
class DepoAccountServiceTest {
public static final MatcherFactory.Matcher<DepoAccount> CLEARING_ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
public static final MatcherFactory.Matcher<Account> ACCOUNT_MATCHER = usingIgnoringFieldsComparator("created", "updated");
@ -73,6 +75,9 @@ class DepoAccountServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
private Imdg<DepoAccount> depoAccountImdg;
private Imdg<Account> accountImdg;
@ -136,6 +141,7 @@ class DepoAccountServiceTest {
relation.setService(Service.MKR.getKey());
relationImdg.insert(relation);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
@Test

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -19,8 +20,6 @@ import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.platform.dictionary.AccountTypeDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.AccountValidationConfig;
import ru.spcex.clearing.account.config.validation.InformationAccountValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
@ -28,6 +27,9 @@ import ru.spcex.clearing.account.utils.MatcherFactory;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.account.InformationAccountNewRequest;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@ -38,8 +40,8 @@ import java.util.Map;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.account.utils.TestUtils.getJsonStringForNew;
import static ru.spcex.clearing.test.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.test.TestUtils.getJsonStringForNew;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -49,8 +51,8 @@ import static ru.spcex.clearing.account.utils.TestUtils.getJsonStringForNew;
AccountValidationConfig.class,
AccountService.class,
InformationAccountService.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
class InformationAccountServiceTest {
public static final MatcherFactory.Matcher<InformationAccount> INFORMATION_ACCOUNT_MATCHER = usingIgnoringFieldsComparator();
public static final MatcherFactory.Matcher<Account> ACCOUNT_MATCHER = usingIgnoringFieldsComparator("created", "updated");
@ -71,6 +73,9 @@ class InformationAccountServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
private Imdg<InformationAccount> informationAccountImdg;
private Imdg<Account> accountImdg;
@ -128,6 +133,8 @@ class InformationAccountServiceTest {
accountAnlt.setAccountType(AccountType.Anlt.getKey());
accountAnlt.setCompanyId(1L);
anltAccountId = accountImdg.insert(accountAnlt);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
@Test

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.account.service;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -20,8 +21,6 @@ import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.clearing.platform.dictionary.ServiceStatusDictionary;
import ru.spcex.clearing.account.config.BeanConfiguration;
import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration;
import ru.spcex.clearing.account.config.KafkaConfigTest;
import ru.spcex.clearing.account.config.validation.TradingClearingRegistryValidationConfig;
import ru.spcex.clearing.account.config.validation.ValidationConfig;
import ru.spcex.clearing.account.utils.MatcherFactory;
@ -30,6 +29,9 @@ import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryNewRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.registry.TradingClearingRegistryUpdateRequest;
import ru.spcex.clearing.test.TestObjectCreator;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.enumeration.ServiceStatus;
import ru.spcex.platform.enumeration.TradingClearingRegistryPurpose;
import ru.spcex.platform.enumeration.TradingClearingRegistryType;
@ -40,7 +42,7 @@ import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
import javax.annotation.PostConstruct;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.account.utils.TestUtils.*;
import static ru.spcex.clearing.test.TestUtils.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
@ -48,8 +50,8 @@ import static ru.spcex.clearing.account.utils.TestUtils.*;
ValidationConfig.class,
TradingClearingRegistryValidationConfig.class,
TradingClearingRegistryService.class,
HazelcastServiceTestConfiguration.class,
KafkaConfigTest.class})
ImdgTestConfig.class,
KafkaTestConfig.class})
class TradingClearingRegistryServiceTest {
public static final MatcherFactory.Matcher<TradingClearingRegistry> TRADING_CLEARING_REGISTRY_MATCHER = usingIgnoringFieldsComparator();
private static final int PARTITION = 0;
@ -67,6 +69,9 @@ class TradingClearingRegistryServiceTest {
private ArgumentCaptor<ProducerRecord> producerRecord;
@SpyBean
private MockProducer<String, Object> producer;
@Autowired
@Qualifier("mockProducer")
protected Producer<String, Object> mockProducer;
private Imdg<TradingClearingRegistry> tradingClearingRegistryImdg;
private Imdg<Company> companyImdg;
@ -142,6 +147,8 @@ class TradingClearingRegistryServiceTest {
InformationAccount informationAccount = new InformationAccount();
informationAccount.setAccountId(account2Id);
infoAccountId = informationAccountImdg.insert(informationAccount);
new TestObjectCreator(hazelcastServiceTest).createUserAdmin(1000L);
}
@Test
@ -166,7 +173,7 @@ class TradingClearingRegistryServiceTest {
0,
jsonString);
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, mockProducer);
TradingClearingRegistry resultNew = tradingClearingRegistryImdg.getAllValues().iterator().next();
predictableTradingClearingRegistry.setId(resultNew.getId());
@ -202,7 +209,7 @@ class TradingClearingRegistryServiceTest {
0,
jsonString);
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, producer, producerRecord);
TradingClearingRegistry resultNew = tradingClearingRegistryImdg.getAllValues().iterator().next();
predictableTradingClearingRegistry.setId(resultNew.getId());
@ -241,7 +248,7 @@ class TradingClearingRegistryServiceTest {
0,
jsonString);
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, producer, producerRecord);
TradingClearingRegistry resultNew = tradingClearingRegistryImdg.getAllValues().iterator().next();
predictableTradingClearingRegistry.setId(resultNew.getId());
@ -265,7 +272,7 @@ class TradingClearingRegistryServiceTest {
tradingClearingRegistryUpdateRequest.setStatus(ServiceStatus.Active.getKey());
tradingClearingRegistryUpdateRequest.setId(registryId);
String jsonString = getJsonStringForUPDATE(tradingClearingRegistryUpdateRequest, 0);
String jsonString = getJsonStringForUpdate(tradingClearingRegistryUpdateRequest, 0);
//ACT
addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(),
@ -275,7 +282,7 @@ class TradingClearingRegistryServiceTest {
jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, producer, producerRecord);
TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId);
existTradingClearingRegistry.setUpdated(resultUpdating.getUpdated());
@ -293,7 +300,7 @@ class TradingClearingRegistryServiceTest {
CommonDeleteRequest tradingClearingRegistryDeleteRequest = new CommonDeleteRequest();
tradingClearingRegistryDeleteRequest.setId(registryId);
String jsonString = getJsonStringForDELETE(tradingClearingRegistryDeleteRequest, 0);
String jsonString = getJsonStringForDelete(tradingClearingRegistryDeleteRequest, 0);
//ACT
addRecordToKafka((MockConsumer) tradingClearingRegistryService.getConsumer(),
@ -303,7 +310,7 @@ class TradingClearingRegistryServiceTest {
jsonString);
//ASSERT
waitingWhenAddedRecordAndCheckIt(0L, producer, producerRecord);
waitingSendAndCheckRecord(0L, producer, producerRecord);
TradingClearingRegistry resultUpdating = tradingClearingRegistryImdg.getSingleObjectByID(registryId);
existTradingClearingRegistry.setUpdated(resultUpdating.getUpdated());

View file

@ -1,125 +0,0 @@
package ru.spcex.clearing.account.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
import org.mockito.ArgumentCaptor;
import ru.spcex.clearing.platform.messaging.domain.ActionType;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.service.RequestInfoUpdate;
import ru.spcex.platform.classes.base.SpcexObjectBase;
import ru.spcex.platform.imdg.api.Imdg;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator;
import static ru.spcex.clearing.platform.messaging.service.Status.Success;
public class TestUtils {
public static final MatcherFactory.Matcher<BaseRequest<Object>> BASE_REQUEST_MATCHER = usingIgnoringFieldsComparator();
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void waitingWhenAddedRecordAndCheckIt(Long id, MockProducer mockProducer, ArgumentCaptor<ProducerRecord> producerRecord) {
BaseRequest<Object> predictableBaseRequest = new BaseRequest<>();
predictableBaseRequest.setId(id);
predictableBaseRequest.setActionType(ActionType.SYSTEM);
RequestInfoUpdate requestInfoUpdate = new RequestInfoUpdate();
requestInfoUpdate.setId(id);
requestInfoUpdate.setStatus(Success);
predictableBaseRequest.setRequestPayload(requestInfoUpdate);
//waiting for kafka producer send message (finale event)
verify(mockProducer, timeout(30_000L).times(1))
.send(producerRecord.capture());
BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) producerRecord.getValue().value();
assertEquals(Consts.REQUEST_INFO_UPDATE, producerRecord.getValue().topic());
BASE_REQUEST_MATCHER.assertMatch(baseRequestResult, predictableBaseRequest);
}
public static void addRecordToKafka(MockConsumer mockConsumer, String topic, int partition, long offset, String jsonValue) {
TopicPartition tp = new TopicPartition(topic, partition);
HashMap<TopicPartition, Long> startOffsets = new HashMap<>();
startOffsets.put(tp, 0L);
mockConsumer.updateBeginningOffsets(startOffsets);
mockConsumer.schedulePollTask(() -> {
mockConsumer.rebalance(Collections.singletonList(tp));
mockConsumer.addRecord(new ConsumerRecord<>(topic, partition, offset, "key", jsonValue));
});
}
public static <T> String getJsonStringForNew(T accountRequest, long id) {
return getJsonBaseRequest(accountRequest, id, ActionType.NEW);
}
public static <T> String getJsonStringForUPDATE(T accountRequest, long id) {
return getJsonBaseRequest(accountRequest, id, ActionType.UPDATE);
}
public static <T> String getJsonStringForDELETE(T accountRequest, long id) {
return getJsonBaseRequest(accountRequest, id, ActionType.DELETE);
}
private static <T> String getJsonBaseRequest(T accountRequest, long id, ActionType actionType) {
BaseRequest<T> baseRequest = new BaseRequest<>();
baseRequest.setRequestPayload(accountRequest);
baseRequest.setId(id);
baseRequest.setActionType(actionType);
String jsonBaseRequest;
try {
jsonBaseRequest = objectMapper.writeValueAsString(baseRequest);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return jsonBaseRequest;
}
public static <T extends SpcexObjectBase> void clearImdg(Imdg<T> imdg) {
Collection<T> values = imdg.getAllValues();
for (T val : values) {
imdg.delete(val);
}
}
public static class FutureRecordMetadata implements Future<RecordMetadata> {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public RecordMetadata get() throws InterruptedException, ExecutionException {
return null;
}
@Override
public RecordMetadata get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
}
}

View file

@ -323,6 +323,31 @@
</transformationSets>
</configuration>
</execution>
<execution>
<!-- Generate java_classes.java from META file
command: mvn xml:transform@java -->
<id>java</id>
<goals>
<goal>transform</goal>
</goals>
<configuration>
<transformationSets>
<transformationSet>
<dir>src/main/resources/meta</dir>
<includes>
<include>meta.xml</include>
</includes>
<stylesheet>src/main/resources/meta/xsl/java.xsl</stylesheet>
<fileMappers>
<fileMapper
implementation="org.codehaus.plexus.components.io.filemappers.FileExtensionMapper">
<targetExtension>java_classes.java</targetExtension>
</fileMapper>
</fileMappers>
</transformationSet>
</transformationSets>
</configuration>
</execution>
</executions>
</plugin>
<plugin>

View file

@ -77,8 +77,7 @@ public class MoneyMarketSecurityController extends AbstractQueueController {
@ResponseBody
public CommonGetAllResponse getAll() {
Collection<Map<String, Object>> all = stateLoader.getAllMetaTransform(IMDGDistributedNames.Map_MoneyMarketSecurity,
MoneyMarketSecurity.class,
Map.of("workflowStatus", Status.Active.getKey()));
MoneyMarketSecurity.class);
CommonGetAllResponse response = new CommonGetAllResponse();
response.fromEntity(all);
return response;

View file

@ -2,6 +2,7 @@ package ru.spcex.clearing.backendapi.controller.request.cud.registry;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import ru.spcex.clearing.backendapi.domain.actions.IAction;
import ru.spcex.clearing.backendapi.errors.BackEndError;
import ru.spcex.clearing.platform.messaging.domain.ActionType;
@ -18,7 +19,19 @@ public class TradingClearingRegistryUpdateAction implements IAction<TradingClear
@ApiModelProperty(hidden = true)
@JsonProperty
public Long id;
@ApiModelProperty(value = "Наименование компании", example = "123")
@JsonProperty
public Long companyId;
@ApiModelProperty(value = "Код торгово-клирингового регистра", example = "123")
@JsonProperty
public String code;
@ApiModelProperty(value = "Номер денежного счета", example = "123")
@JsonProperty
public Long moneyAccountId;
@ApiModelProperty(value = "Номер депозитарного счета", example = "123")
@JsonProperty
public Long depoAccountId;
@ApiModelProperty(value = "Наименование статуса", example = "ACTV")
@JsonProperty
private String status;
@ -27,6 +40,8 @@ public class TradingClearingRegistryUpdateAction implements IAction<TradingClear
List<EnumMessage> errors = new ArrayList<>();
if (this.id == null)
errors.add(new EnumMessage(BackEndError.ValidationError, "id"));
if (StringUtils.isEmpty(this.status))
errors.add(new EnumMessage(BackEndError.ValidationError, "status"));
return errors.isEmpty() ? Collections.emptyList() : errors;
}
@ -34,6 +49,10 @@ public class TradingClearingRegistryUpdateAction implements IAction<TradingClear
public TradingClearingRegistryUpdateRequest toRequest() {
var req = new TradingClearingRegistryUpdateRequest();
req.setId(this.id);
req.setCompanyId(this.companyId);
req.setCode(this.code);
req.setMoneyAccountId(this.moneyAccountId);
req.setDepoAccountId(this.depoAccountId);
req.setStatus(this.status);
return req;
}
@ -52,6 +71,38 @@ public class TradingClearingRegistryUpdateAction implements IAction<TradingClear
this.id = id;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getMoneyAccountId() {
return moneyAccountId;
}
public void setMoneyAccountId(Long moneyAccountId) {
this.moneyAccountId = moneyAccountId;
}
public Long getDepoAccountId() {
return depoAccountId;
}
public void setDepoAccountId(Long depoAccountId) {
this.depoAccountId = depoAccountId;
}
public String getStatus() {
return status;
}

View file

@ -1,6 +1,6 @@
{
"version": "3.5.0.22",
"version": "3.5.0.24",
"enums": {
@ -1726,7 +1726,7 @@
}
,
{"code": "corporationSoleType",
"type": 12,"dbname": "Код единоличного исполнительного органа","name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","searchable": true,"sortable": true,"visible": true,"link": "corporationSoleType"
"type": 12,"dbname": "Код единоличного исполнительного органа","name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","searchable": true,"sortable": true,"visible": true,"link": "corporationSoleType","ignore": true
}
,
{"code": "countryCode",
@ -1734,7 +1734,7 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "professionalSign",
@ -1812,7 +1812,7 @@
}
,
{"code": "corporationSoleType",
"type": 12,"name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","link": "corporationSoleType"
"type": 12,"name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","link": "corporationSoleType","visible": false
}
,
{"code": "legalKind",
@ -1840,7 +1840,7 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание компании"
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание компании","visible": false
}
,
{"code": "workflowStatus",
@ -2025,7 +2025,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "issuer",
@ -2033,11 +2033,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "number",
@ -2045,11 +2045,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Место","shortname": "Место","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","searchable": true,"sortable": true
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "validToDate",
@ -2085,7 +2085,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","required": true
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","visible": false
}
,
{"code": "issuer",
@ -2093,11 +2093,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","required": true
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","visible": false
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","required": true
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","visible": false
}
,
{"code": "number",
@ -2105,11 +2105,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место","required": true
"type": 2,"length": 255,"name": "Место","shortname": "Место","visible": false
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","required": true
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","visible": false
}
,
{"code": "validToDate",
@ -2146,7 +2146,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи"
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","visible": false
}
,
{"code": "issuer",
@ -2154,11 +2154,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган"
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","visible": false
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ"
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","visible": false
}
,
{"code": "number",
@ -2166,11 +2166,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место"
"type": 2,"length": 255,"name": "Место","shortname": "Место","visible": false
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало"
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","visible": false
}
,
{"code": "validToDate",
@ -2391,7 +2391,7 @@
"fields": [
{"code": "countryCode",
"type": 12,"dbname": "Код страны","name": "Наименование страны","shortname": "Страна","searchable": true,"sortable": true,"visible": true,"link": "countryCode"
"type": 12,"dbname": "Код страны","name": "Наименование страны","shortname": "Страна","searchable": true,"sortable": true,"visible": true,"link": "countryCode","ignore": true
}
,
{"code": "currencyCode",
@ -2423,15 +2423,15 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","searchable": true,"sortable": false
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","searchable": true,"sortable": false,"ignore": true
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","searchable": true,"sortable": true
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","searchable": true,"sortable": true
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "nominalValue",
@ -2463,7 +2463,7 @@
}
,
{"code": "termType",
"type": 12,"dbname": "Код вида инструмента","name": "Наименование вида инструмента","shortname": "Вид инструмента","searchable": true,"sortable": true,"visible": false,"link": "termType"
"type": 12,"dbname": "Код вида инструмента","name": "Наименование вида инструмента","shortname": "Вид инструмента","searchable": true,"sortable": true,"visible": false,"link": "termType","ignore": true
}
,
{"code": "lotSize",
@ -2499,7 +2499,7 @@
"name": "Добавление инструмента Денежного рынка",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency,startDate,endDate,termType",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency",
"fields": [
{"code": "securitySymbol",
@ -2531,19 +2531,19 @@
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","required": true
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","visible": false
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","required": true
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","visible": false
}
,
{"code": "termType",
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","required": true
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","visible": false
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание"
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","visible": false
}
,
{"code": "issuerId",
@ -2576,7 +2576,7 @@
"name": "Изменение инструмента Денежного рынка",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency,startDate,endDate,termType",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency",
"fields": [
{"code": "id",
@ -2600,7 +2600,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "nominalValue",
@ -2612,19 +2612,19 @@
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","enabled": false
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","enabled": false,"visible": false
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания"
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","visible": false
}
,
{"code": "termType",
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType"
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","visible": false
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание"
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","visible": false
}
,
{"code": "issuerId",
@ -2849,7 +2849,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "issuerId",
@ -3080,7 +3080,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "nominalValue",
@ -3531,7 +3531,7 @@
}
,
{"code": "code",
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "Код ТКР","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "ТКР","searchable": true,"sortable": true,"visible": true
}
,
{"code": "moneyAccountId",
@ -3596,15 +3596,31 @@
"name": "Изменение ТКР",
"confirmation": "companyId,moneyAccountId,depoAccountId,status",
"confirmation": "companyId,code,moneyAccountId,depoAccountId,status",
"fields": [
{"code": "id",
"type": 1,"name": "Идентификатор записи","shortname": "ID","link": "clientCode","linkCode": "id","required": true
}
,
{"code": "companyId",
"type": 1,"name": "Наименование компании","shortname": "Компания","link": "company","linkCode": "shortName","enabled": false
}
,
{"code": "code",
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "ТКР","enabled": false
}
,
{"code": "moneyAccountId",
"type": 1,"name": "Номер денежного счета","shortname": "Денежный счет","link": "account","linkCode": "account","enabled": false
}
,
{"code": "depoAccountId",
"type": 1,"name": "Номер депозитарного счета","shortname": "Депозитарный счет","link": "account","linkCode": "account","enabled": false
}
,
{"code": "status",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "workflowStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "workflowStatus","required": true
}
]
}
@ -4439,11 +4455,11 @@
}
,
{"code": "task",
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task"
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task","required": true
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи"
"type": 5,"name": "Время задачи","shortname": "Время задачи","required": true
}
,
{"code": "section",
@ -4455,7 +4471,7 @@
}
,
{"code": "taskStatus",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus","required": true
}
,
{"code": "companyId",
@ -4548,11 +4564,11 @@
}
,
{"code": "clearingDate",
"type": 6,"name": "Дата","shortname": "Дата"
"type": 6,"name": "Дата","shortname": "Дата","required": true
}
,
{"code": "dayStatus",
"type": 12,"name": "Статус","shortname": "Статус","link": "dayStatus"
"type": 12,"name": "Статус","shortname": "Статус","link": "dayStatus","required": true
}
,
{"code": "companyId",
@ -4685,15 +4701,15 @@
}
,
{"code": "task",
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task"
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи"
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task","required": true
}
,
{"code": "clearingDate",
"type": 6,"name": "Дата задачи","shortname": "Дата задачи"
"type": 6,"name": "Дата задачи","shortname": "Дата задачи","required": true
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи","required": true
}
,
{"code": "section",
@ -4705,7 +4721,7 @@
}
,
{"code": "taskStatus",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus","required": true
}
,
{"code": "companyId",
@ -5190,6 +5206,28 @@
"name": "Формирование реестра распоряжений, направленных расчетному депозитарию",
"fields": []
}
,
{"method":"post",
"destination": "LOSC",
"group": "Клиринг",
"name": "Загрузить инструменты",
"fields": []
}
,
{"method":"post",
"destination": "LOCM",
"group": "Клиринг",
"name": "Загрузить участников",
"fields": []
}
]

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,467 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output version="1.0" method="text" indent="no" encoding="UTF-8"/>
<xsl:variable name="lcletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
<xsl:variable name="ucletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
<xsl:variable name="avoidletters">_0123456789</xsl:variable>
<xsl:template match="/"><xsl:apply-templates select="*"/></xsl:template>
<xsl:template match="meta">// JAVA classes for DB version: <xsl:value-of select="@version"/><xsl:apply-templates select="*"/></xsl:template>
<xsl:template match="enums">
/* Dictionaries */
<xsl:apply-templates select="*" mode="enums"/>
</xsl:template>
<xsl:template match="objects">
/* Business objects */
<xsl:apply-templates select="*" mode="objects"/>
</xsl:template>
<xsl:template match="types">
// Data types
<xsl:apply-templates select="*" mode="types"/>
</xsl:template>
<xsl:template match="type" mode="types">
// <xsl:value-of select="@id"/>. <xsl:value-of select="name()"/> : <xsl:value-of select="@type"/> - <xsl:value-of select="@name"/>
<xsl:if test="position() != last()">,</xsl:if>
</xsl:template>
<xsl:template match="*" mode="enums">
// ----------------- <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='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>
package ru.clearing.platform.dictionary;<!-- todo remove extract last class <xsl:value-of select="@class"/> - only package-->
<!-- import ru.clearing.dictionarys.ConstDictionarySerializable; -->
/**
* <xsl:value-of select="@name"/>
*
* Dictionary DB table: <xsl:value-of select="$dbTableName"/>
**/
public class <xsl:value-of select="$nameObjFmt"/>Dictionary extends AbstractDictionary {
private static final long serialVersionUID = ConstDictionarySerializable.serialVersionUID;
<xsl:apply-templates select="*" mode="field-enums"/> <!-- ignore default AbstractDictionary field -->
<xsl:apply-templates select="*" mode="getter-setter-enums"/>
}
// -- mapstore --
package ru.spcex.clearing.imdg.dictionary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import ru.clearing.platform.dictionary.<xsl:value-of select="$nameObjFmt"/>Dictionary; <!-- or <xsl:value-of select="@class"/> -->
import ru.spcex.clearing.imdg.base.DictionaryTMapStore;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
@Component
public class <xsl:value-of select="$nameObjFmt"/>DictionaryMapStore extends DictionaryTMapStore&lt;<xsl:value-of select="$nameObjFmt"/>Dictionary&gt; {
public <xsl:value-of select="$nameObjFmt"/>DictionaryMapStore(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public String getMapName() {
return IMDGDistributedNames.Map_<xsl:value-of select="$nameObjFmt"/>Dictionary;
}
@Override
public String getTableName() {
return "<xsl:value-of select="$dbTableName"/>";
}
@Override
public <xsl:value-of select="$nameObjFmt"/>Dictionary getDictionaryObject() {
return new <xsl:value-of select="$nameObjFmt"/>Dictionary();
}
<xsl:apply-templates select="*" mode="mapstore-field-enums"/> <!-- защита от нестандартного Dictionary -->
}
</xsl:template>
<xsl:template match="*" mode="mapstore-field-enums" >
<xsl:choose>
<xsl:when test="name()='id'"></xsl:when>
<xsl:when test="name()='code'"></xsl:when>
<xsl:when test="name()='name'"></xsl:when>
<xsl:otherwise>
!! Нестандартное поле !! <xsl:value-of select="name()"/> // FIXME Нестандартный словарь! Требуется писать код вручную.
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*" mode="objects">
// ------------------ <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="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-->
import ru.clearing.classes.ConstSerializable;
import ru.spcex.platform.classes.base.SpcexObjectBase;
/**
* <xsl:value-of select="@name"/>
*
* DB table: <xsl:value-of select="$dbTableName"/>
**/
public class <xsl:value-of select="$nameObjFmt"/> extends SpcexObjectBase {
private static final long serialVersionUID = ConstSerializable.serialVersionUID;
<xsl:apply-templates select="*[@name or @dbname or @type]" mode="field"/>
<xsl:apply-templates select="*[@name or @dbname or @type]" mode="getter-setter-objects"/>
}
//mapstore
// -- mapstore --
package ru.spcex.clearing.imdg.object;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import <xsl:value-of select="@class"/>; <!-- or ...<xsl:value-of select="$nameObjFmt"/> -->
import ru.spcex.clearing.imdg.base.TemplateMapStore;<!-- ObjectBaseMapStore; -->
import ru.spcex.platform.utils.time.TimeUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
@Component
public class <xsl:value-of select="$nameObjFmt"/>MapStore extends TemplateMapStore&lt;<xsl:value-of select="$nameObjFmt"/>&gt; {
public <xsl:value-of select="$nameObjFmt"/>MapStore(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public String getMapName() {
return IMDGDistributedNames.Map_<xsl:value-of select="$nameObjFmt"/>;
}
@Override
public String getTableName() {
return "<xsl:value-of select="$dbTableName"/>";
}
@Override
public String[] getFields() {
return new String[]{
<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getFields"/>
};
}
@Override
public <xsl:value-of select="$nameObjFmt"/> objectReader(ResultSet resultSet) throws SQLException {
<xsl:value-of select="$nameObjFmt"/> object = new <xsl:value-of select="$nameObjFmt"/>(); <xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-setters"/>
return object;
}
@Override
public Object[] objectToField(<xsl:value-of select="$nameObjFmt"/> object) {
Object[] args = new Object[]{<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getters"/>
};
return args;
}
}
<xsl:if test="@logUpdates">
// todo добавить класс <xsl:value-of select="$nameObjFmt"/>History
package <xsl:value-of select="@class"/>;<!-- todo remove extract last class - only package-->
import ru.clearing.classes.ConstSerializable;
import ru.clearing.classes.objects.BusinessEvent;
import java.io.Serial;
/**
* Изменение состояния объекта <xsl:value-of select="@name"/>
*
* DB table: <xsl:value-of select="$dbTableName"/>_HISTORY
**/
public class <xsl:value-of select="$nameObjFmt"/>History extends BusinessEvent&lt;<xsl:value-of select="$nameObjFmt"/>&gt; {
@Serial
private static final long serialVersionUID = ConstSerializable.serialVersionUID;
private <xsl:value-of select="$nameObjFmt"/> object;
@Override
public <xsl:value-of select="$nameObjFmt"/> getObject() {
return object;
}
@Override
public void setObject(<xsl:value-of select="$nameObjFmt"/> object) {
this.object = object;
}
}
// -- History mapstore для журналирования --
package ru.spcex.clearing.imdg.businessevent;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import <xsl:value-of select="@class"/>;
import <xsl:value-of select="@class"/>History; <!-- or ...<xsl:value-of select="$nameObjFmt"/> -->
import ru.spcex.clearing.imdg.base.TemplateEventMapStore;<!-- ObjectBaseMapStore; -->
import ru.spcex.platform.utils.time.TimeUtil;
@Component
public class <xsl:value-of select="$nameObjFmt"/>HistoryMapStore extends TemplateEventMapStore&lt;<xsl:value-of select="$nameObjFmt"/>History&gt; {
public <xsl:value-of select="$nameObjFmt"/>HistoryMapStore(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public String getMapName() {
return IMDGDistributedNames.Map_<xsl:value-of select="$nameObjFmt"/>History;
}
@Override
public String getTableName() {
return "<xsl:value-of select="$dbTableName"/>_HISTORY";
}
@Override
public String[] getFields() {
return new String[]{"ID","EVENT_TIME", "EVENT_USER_ID", "EVENT_TYPE", <!-- todo покрасивее сделать ?_ID, а то код вручную приодится править -->
<xsl:value-of select="$dbTableName"/>_<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getFields"/>
};
}
@Override
public Object[] objectToField(<xsl:value-of select="$nameObjFmt"/>History historyLog) {
<xsl:value-of select="$nameObjFmt"/> object=historyLog.getObject();
Object[] args = new Object[]{
historyLog.getId(),
TimeUtil.toDateFromInstant(historyLog.getEventTime()),
historyLog.getUserId(),
historyLog.getEventType(),
<xsl:apply-templates select="*[@name or @dbname or @type]" mode="mapstore-field-getters"/>
};
return args;
}
}
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="mapstore-field-getFields" ><xsl:if test="position() != '1'">, </xsl:if> "<xsl:choose>
<xsl:when test="@dbfield"><xsl:value-of select="@dbfield"/></xsl:when>
<xsl:otherwise><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:otherwise>
</xsl:choose>"</xsl:template>
<xsl:template match="*" mode="mapstore-field-setters" >
<xsl:variable name="tp" select="@type"/>
<xsl:variable name="javatp" select="/meta/types/*[@id=$tp]/@javatype"/> <xsl:choose>
<xsl:when test="$javatp='Instant'">
object.set<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>(getInstantFromTimestamp(resultSet, "<xsl:choose>
<xsl:when test="@dbfield"><xsl:value-of select="@dbfield"/></xsl:when>
<xsl:otherwise><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:otherwise>
</xsl:choose>"))</xsl:when>
<xsl:when test="$javatp='LocalDate'">
object.set<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>(getLocalDateFromSqlDate(resultSet, "<xsl:choose>
<xsl:when test="@dbfield"><xsl:value-of select="@dbfield"/></xsl:when>
<xsl:otherwise><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:otherwise>
</xsl:choose>"))</xsl:when>
<xsl:when test="$javatp='LocalTime'">
object.set<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>(getLocalTimeFromSqlTime(resultSet, "<xsl:choose>
<xsl:when test="@dbfield"><xsl:value-of select="@dbfield"/></xsl:when>
<xsl:otherwise><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:otherwise>
</xsl:choose>"))</xsl:when>
<xsl:otherwise>
object.set<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>(resultSet.getObject("<xsl:choose>
<xsl:when test="@dbfield"><xsl:value-of select="@dbfield"/></xsl:when>
<xsl:otherwise><xsl:call-template name='convertDbStyle'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template></xsl:otherwise>
</xsl:choose>", <xsl:value-of select="$javatp"/>.class))</xsl:otherwise>
</xsl:choose>;</xsl:template>
<xsl:template match="*" mode="mapstore-field-getters" ><xsl:if test="position() != '1'">, </xsl:if><!-- todo запятую в конце а не в начале, см. last()-->
<xsl:variable name="tp" select="@type"/>
<xsl:variable name="javatp" select="/meta/types/*[@id=$tp]/@javatype"/>
<xsl:choose>
<xsl:when test="$javatp='Instant'">
TimeUtil.toDateFromInstant(object.get<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>())</xsl:when>
<xsl:when test="$javatp='LocalDate'">
TimeUtil.toDateFromLocalDate(object.get<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>())</xsl:when>
<xsl:when test="$javatp='LocalTime'">
TimeUtil.toDateFromLocalTime(object.get<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>())</xsl:when>
<xsl:otherwise>
object.get<xsl:call-template name='convertFirstUC_'><xsl:with-param name='toconvert' select='name()'/></xsl:call-template>()</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*" mode="field" >
<xsl:variable name="tp" select="@type"/>
<xsl:if test="name()='id'"> // (in parent) </xsl:if> private <xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> <xsl:text> <!-- space &#160; --></xsl:text><xsl:value-of select="name()"/>;
<xsl:choose>
<xsl:when test="@dbfield"> // DB field: <xsl:value-of select="@dbfield"/></xsl:when>
<!-- new line -->
<xsl:otherwise> </xsl:otherwise></xsl:choose>
<!-- todo pretty comment: <xsl:if test="@link"> // (linked to <xsl:value-of select="@link"/>)
</xsl:if>-->
<!-- fixme т.к. тут атрибуты перебираются - не работают переносы а ещё знак пробела надо пропатчить, а то NBSP -->
</xsl:template>
<xsl:template match="*" mode="field-enums" >
<xsl:variable name="tp" select="@type"/>
<xsl:choose>
<xsl:when test="name()='id'"></xsl:when><!-- определено в родительском классе AbstractDictionary -->
<xsl:when test="name()='code'"></xsl:when><!-- определено в родительском классе AbstractDictionary -->
<xsl:when test="name()='name'"></xsl:when><!-- определено в родительском классе AbstractDictionary -->
<xsl:otherwise><!-- нестандартное поле -->
private <xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> <xsl:text> <!-- space &#160; --> </xsl:text><xsl:value-of select="name()"/>;
<xsl:choose>
<xsl:when test="@dbfield"> // DB field: <xsl:value-of select="@dbfield"/></xsl:when>
<!-- new line -->
<xsl:otherwise> </xsl:otherwise>
</xsl:choose><xsl:if test="@link"> // (linked to <xsl:value-of select="@link"/>)
<!--new line--></xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*" mode="getter-setter-enums">
<xsl:variable name="tp" select="@type"/>
<xsl:choose>
<xsl:when test="name()='id'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary -->
<xsl:when test="name()='code'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary -->
<xsl:when test="name()='name'"></xsl:when><!-- todo other restrictions of parent AbstractDictionary -->
<xsl:otherwise><!-- нестандартное поле -->
<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"/>() {
return <xsl:value-of select="name()"/>;
}
public void set<xsl:value-of select="$NameFmt"/>(<xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> value) {
this.<xsl:value-of select="name()"/>=value;
}
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*" mode="getter-setter-objects">
<xsl:variable name="tp" select="@type"/>
<xsl:choose>
<xsl:when test="name()='id'"></xsl:when>
<xsl:otherwise>
<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"/>() {
return <xsl:value-of select="name()"/>;
}
public void set<xsl:value-of select="$NameFmt"/>(<xsl:value-of select="/meta/types/*[@id=$tp]/@javatype"/> value) {
this.<xsl:value-of select="name()"/>=value;
}
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name='convertDbStyle'>
<xsl:param name='toconvert' />
<xsl:variable name="added_">
<xsl:call-template name='add_'>
<xsl:with-param name='toconvert' select='$toconvert' />
</xsl:call-template>
</xsl:variable>
<xsl:call-template name='convertcase'>
<xsl:with-param name='toconvert' select='$added_' />
<xsl:with-param name='conversion' select="'upper'" />
</xsl:call-template>
</xsl:template>
<xsl:template name='convertcase'>
<xsl:param name='toconvert' />
<xsl:param name='conversion' />
<xsl:choose>
<xsl:when test='$conversion="lower"'>
<xsl:value-of select="translate($toconvert,$ucletters,$lcletters)"/>
</xsl:when>
<xsl:when test='$conversion="upper"'>
<xsl:value-of select="translate($toconvert,$lcletters,$ucletters)"/>
</xsl:when>
<xsl:when test='$conversion="proper"'>
<xsl:call-template name='convertpropercase'>
<xsl:with-param name='toconvert'>
<xsl:value-of select="translate($toconvert,$ucletters,$lcletters)"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='$toconvert' />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name='convertpropercase'>
<xsl:param name='toconvert' />
<xsl:if test="string-length($toconvert) > 0">
<xsl:variable name='f' select='substring($toconvert, 1, 1)' />
<xsl:variable name='s' select='substring($toconvert, 2)' />
<xsl:call-template name='convertcase'>
<xsl:with-param name='toconvert' select='$f' />
<xsl:with-param name='conversion'>upper</xsl:with-param>
</xsl:call-template>
<xsl:choose>
<xsl:when test="contains($s,' ')">
<xsl:value-of select='substring-before($s," ")'/>
<xsl:call-template name='convertpropercase'>
<xsl:with-param name='toconvert' select='substring-after($s," ")' />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='$s'/>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<xsl:template name='add_'>
<xsl:param name='toconvert' />
<xsl:if test="string-length($toconvert) > 0">
<xsl:variable name='f' select='substring($toconvert, 1, 1)' />
<xsl:variable name='s' select='substring($toconvert, 2)' />
<xsl:choose>
<xsl:when test="$f = translate($f, $lcletters,$ucletters)"><xsl:if test="translate($f, $avoidletters,'')">_</xsl:if><xsl:value-of select='$f'/></xsl:when>
<xsl:otherwise><xsl:value-of select='$f'/></xsl:otherwise>
</xsl:choose>
<xsl:if test="string-length($toconvert) > 1">
<xsl:call-template name='add_'>
<xsl:with-param name='toconvert' select='$s'/>
</xsl:call-template>
</xsl:if>
</xsl:if>
</xsl:template>
<!-- todo должен первую букву прописной сделать -->
<xsl:template name='convertFirstUC_'>
<xsl:param name='toconvert' />
<xsl:if test="string-length($toconvert) > 0">
<xsl:variable name='f' select='translate(substring($toconvert, 1, 1),$lcletters,$ucletters)' />
<xsl:variable name='s' select='substring($toconvert, 2)' />
<xsl:value-of select='$f'/><xsl:value-of select='$s'/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

View file

@ -26,7 +26,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.user.User;
import ru.spcex.clearing.backendapi.controller.config.*;
import ru.spcex.clearing.backendapi.controller.queue.account.*;
@ -60,7 +59,6 @@ import ru.spcex.clearing.test.TestUtils;
import ru.spcex.clearing.test.json.MatcherFactoryWithJson;
import ru.spcex.platform.classes.base.SpcexObjectBase;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.iml.hazelcast.adapter.ImdgHazelcast;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
@ -158,6 +156,7 @@ import static ru.spcex.clearing.test.json.MatcherFactoryWithJson.usingIgnoringFi
WebSecurityTestConfigurer.class,
MessagesTestConfig.class,
Jackson2HttpConverterTestConfig.class})
//todo может быть указать пакедж а не список контроллеров
@ExtendWith(SpringExtension.class)
@WebMvcTest
//@TestPropertySource(properties = "spring.config.location=D:/repo/mfd/clearing/clearing-parent/backend-api/src/main/resources/")

View file

@ -1,6 +1,6 @@
{
"version": "3.5.0.22",
"version": "3.5.0.24",
"enums": {
@ -1726,7 +1726,7 @@
}
,
{"code": "corporationSoleType",
"type": 12,"dbname": "Код единоличного исполнительного органа","name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","searchable": true,"sortable": true,"visible": true,"link": "corporationSoleType"
"type": 12,"dbname": "Код единоличного исполнительного органа","name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","searchable": true,"sortable": true,"visible": true,"link": "corporationSoleType","ignore": true
}
,
{"code": "countryCode",
@ -1734,7 +1734,7 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "professionalSign",
@ -1812,7 +1812,7 @@
}
,
{"code": "corporationSoleType",
"type": 12,"name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","link": "corporationSoleType"
"type": 12,"name": "Единоличный исполнительный орган","shortname": "Исполнительный орган","link": "corporationSoleType","visible": false
}
,
{"code": "legalKind",
@ -1840,7 +1840,7 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание компании"
"type": 2,"length": 255,"name": "Описание компании","shortname": "Описание компании","visible": false
}
,
{"code": "workflowStatus",
@ -2025,7 +2025,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "issuer",
@ -2033,11 +2033,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "number",
@ -2045,11 +2045,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Место","shortname": "Место","searchable": true,"sortable": true,"visible": true,"ignore": true
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","searchable": true,"sortable": true
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "validToDate",
@ -2085,7 +2085,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","required": true
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","visible": false
}
,
{"code": "issuer",
@ -2093,11 +2093,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","required": true
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","visible": false
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","required": true
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","visible": false
}
,
{"code": "number",
@ -2105,11 +2105,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место","required": true
"type": 2,"length": 255,"name": "Место","shortname": "Место","visible": false
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","required": true
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","visible": false
}
,
{"code": "validToDate",
@ -2146,7 +2146,7 @@
}
,
{"code": "issuePlace",
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи"
"type": 2,"length": 255,"name": "Место выдачи","shortname": "Место выдачи","visible": false
}
,
{"code": "issuer",
@ -2154,11 +2154,11 @@
}
,
{"code": "issuerCode",
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган"
"type": 2,"length": 255,"name": "Код выдавшего органа","shortname": "Выдавший орган","visible": false
}
,
{"code": "name",
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ"
"type": 2,"length": 255,"name": "Наименование документа","shortname": "Документ","visible": false
}
,
{"code": "number",
@ -2166,11 +2166,11 @@
}
,
{"code": "place",
"type": 2,"length": 255,"name": "Место","shortname": "Место"
"type": 2,"length": 255,"name": "Место","shortname": "Место","visible": false
}
,
{"code": "validFromDate",
"type": 6,"name": "Дата начала срока действия","shortname": "Начало"
"type": 6,"name": "Дата начала срока действия","shortname": "Начало","visible": false
}
,
{"code": "validToDate",
@ -2391,7 +2391,7 @@
"fields": [
{"code": "countryCode",
"type": 12,"dbname": "Код страны","name": "Наименование страны","shortname": "Страна","searchable": true,"sortable": true,"visible": true,"link": "countryCode"
"type": 12,"dbname": "Код страны","name": "Наименование страны","shortname": "Страна","searchable": true,"sortable": true,"visible": true,"link": "countryCode","ignore": true
}
,
{"code": "currencyCode",
@ -2423,15 +2423,15 @@
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","searchable": true,"sortable": false
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","searchable": true,"sortable": false,"ignore": true
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","searchable": true,"sortable": true
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","searchable": true,"sortable": true
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","searchable": true,"sortable": true,"ignore": true
}
,
{"code": "nominalValue",
@ -2463,7 +2463,7 @@
}
,
{"code": "termType",
"type": 12,"dbname": "Код вида инструмента","name": "Наименование вида инструмента","shortname": "Вид инструмента","searchable": true,"sortable": true,"visible": false,"link": "termType"
"type": 12,"dbname": "Код вида инструмента","name": "Наименование вида инструмента","shortname": "Вид инструмента","searchable": true,"sortable": true,"visible": false,"link": "termType","ignore": true
}
,
{"code": "lotSize",
@ -2499,7 +2499,7 @@
"name": "Добавление инструмента Денежного рынка",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency,startDate,endDate,termType",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency",
"fields": [
{"code": "securitySymbol",
@ -2531,19 +2531,19 @@
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","required": true
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","visible": false
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","required": true
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","visible": false
}
,
{"code": "termType",
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","required": true
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","visible": false
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание"
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","visible": false
}
,
{"code": "issuerId",
@ -2576,7 +2576,7 @@
"name": "Изменение инструмента Денежного рынка",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency,startDate,endDate,termType",
"confirmation": "securitySymbol,shortName,fullName,lotSize,nominalValue,nominalCurrency",
"fields": [
{"code": "id",
@ -2600,7 +2600,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "nominalValue",
@ -2612,19 +2612,19 @@
}
,
{"code": "startDate",
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","enabled": false
"type": 6,"name": "Дата начала действия","shortname": "Дата начала","enabled": false,"visible": false
}
,
{"code": "endDate",
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания"
"type": 6,"name": "Дата окончания действия","shortname": "Дата окончания","visible": false
}
,
{"code": "termType",
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType"
"type": 12,"name": "Наименование вида инструмента","shortname": "Вид инструмента","link": "termType","visible": false
}
,
{"code": "description",
"type": 2,"length": 255,"name": "Описание","shortname": "Описание"
"type": 2,"length": 255,"name": "Описание","shortname": "Описание","visible": false
}
,
{"code": "issuerId",
@ -2849,7 +2849,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "issuerId",
@ -3080,7 +3080,7 @@
}
,
{"code": "lotSize",
"type": 11,"name": "Размер лота","shortname": "Лот"
"field": "securityId","type": 11,"name": "Размер лота","shortname": "Лот","linkKeyCode": "securityId","linkCode": "lotSize","link": "listing"
}
,
{"code": "nominalValue",
@ -3531,7 +3531,7 @@
}
,
{"code": "code",
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "Код ТКР","searchable": true,"sortable": true,"visible": true
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "ТКР","searchable": true,"sortable": true,"visible": true
}
,
{"code": "moneyAccountId",
@ -3596,15 +3596,31 @@
"name": "Изменение ТКР",
"confirmation": "companyId,moneyAccountId,depoAccountId,status",
"confirmation": "companyId,code,moneyAccountId,depoAccountId,status",
"fields": [
{"code": "id",
"type": 1,"name": "Идентификатор записи","shortname": "ID","link": "clientCode","linkCode": "id","required": true
}
,
{"code": "companyId",
"type": 1,"name": "Наименование компании","shortname": "Компания","link": "company","linkCode": "shortName","enabled": false
}
,
{"code": "code",
"type": 2,"length": 255,"name": "Код торгово-клирингового регистра","shortname": "ТКР","enabled": false
}
,
{"code": "moneyAccountId",
"type": 1,"name": "Номер денежного счета","shortname": "Денежный счет","link": "account","linkCode": "account","enabled": false
}
,
{"code": "depoAccountId",
"type": 1,"name": "Номер депозитарного счета","shortname": "Депозитарный счет","link": "account","linkCode": "account","enabled": false
}
,
{"code": "status",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "workflowStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "workflowStatus","required": true
}
]
}
@ -4439,11 +4455,11 @@
}
,
{"code": "task",
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task"
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task","required": true
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи"
"type": 5,"name": "Время задачи","shortname": "Время задачи","required": true
}
,
{"code": "section",
@ -4455,7 +4471,7 @@
}
,
{"code": "taskStatus",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus","required": true
}
,
{"code": "companyId",
@ -4548,11 +4564,11 @@
}
,
{"code": "clearingDate",
"type": 6,"name": "Дата","shortname": "Дата"
"type": 6,"name": "Дата","shortname": "Дата","required": true
}
,
{"code": "dayStatus",
"type": 12,"name": "Статус","shortname": "Статус","link": "dayStatus"
"type": 12,"name": "Статус","shortname": "Статус","link": "dayStatus","required": true
}
,
{"code": "companyId",
@ -4685,15 +4701,15 @@
}
,
{"code": "task",
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task"
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи"
"type": 12,"name": "Наименование задачи","shortname": "Задача","link": "task","required": true
}
,
{"code": "clearingDate",
"type": 6,"name": "Дата задачи","shortname": "Дата задачи"
"type": 6,"name": "Дата задачи","shortname": "Дата задачи","required": true
}
,
{"code": "taskTime",
"type": 5,"name": "Время задачи","shortname": "Время задачи","required": true
}
,
{"code": "section",
@ -4705,7 +4721,7 @@
}
,
{"code": "taskStatus",
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus"
"type": 12,"name": "Наименование статуса","shortname": "Статус","link": "taskStatus","required": true
}
,
{"code": "companyId",
@ -5190,6 +5206,28 @@
"name": "Формирование реестра распоряжений, направленных расчетному депозитарию",
"fields": []
}
,
{"method":"post",
"destination": "LOSC",
"group": "Клиринг",
"name": "Загрузить инструменты",
"fields": []
}
,
{"method":"post",
"destination": "LOCM",
"group": "Клиринг",
"name": "Загрузить участников",
"fields": []
}
]

View file

@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
import ru.spcex.clearing.balance.service.AbstractExecutor;
import ru.spcex.clearing.balance.service.Sdf01Executor;
import ru.spcex.clearing.balance.service.Sdf16Executor;
import ru.spcex.platform.classes.base.interfaces.WithAccount;
import ru.spcex.clearing.balance.service.Sdf57Executor;
import ru.spcex.platform.enumeration.SdfTable;
import java.util.HashMap;
@ -15,13 +15,15 @@ import java.util.Map;
public class SdfExecutorsConfig {
@Bean("sdfExecutors")
public Map<SdfTable, AbstractExecutor<? extends WithAccount>> executorsMap(Sdf01Executor sdf01Executor,
public Map<SdfTable, AbstractExecutor<?>> executorsMap(Sdf01Executor sdf01Executor,
//Sdf09Executor sdf09Executor,
Sdf16Executor sdf16Executor) {
Map<SdfTable, AbstractExecutor<? extends WithAccount>> executors = new HashMap<>();
Sdf16Executor sdf16Executor,
Sdf57Executor sdf57Executor) {
Map<SdfTable, AbstractExecutor<?>> executors = new HashMap<>();
executors.put(SdfTable.SDF_01, sdf01Executor);
// todo возможно удалят или переделают: executors.put(SdfTable.SDF_09, sdf09Executor);
executors.put(SdfTable.SDF_16, sdf16Executor);
executors.put(SdfTable.SDF_57, sdf57Executor);
return executors;
}
}

View file

@ -10,6 +10,7 @@ import ru.clearing.classes.statics.data.company.CompanySymbols;
import ru.clearing.classes.statics.data.sdf.SDf01;
import ru.clearing.classes.statics.data.sdf.SDf09;
import ru.clearing.classes.statics.data.sdf.SDf16;
import ru.clearing.classes.statics.data.sdf.SDf57;
import ru.spcex.clearing.balance.validation.*;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.platform.classes.base.SpcexObjectBase;
@ -63,6 +64,23 @@ public class ValidationConfig {
};
}
@Bean("sdf57Validator")
public Function<SDf57, IValidator> sdf57Validator() {
return sDf57 -> {
ImdgValidationContext<SDf57> context = new ImdgValidationContext<>();
context.setValidatedObject(sDf57);
Consumer<String> addImdg = (s) -> context.addImdg(s, getImdg(s));
addImdg.accept(IMDGDistributedNames.Map_Account);
addImdg.accept(IMDGDistributedNames.Map_Company);
return new ValidatorImpl<>(context,
Sdf57ValidationRule.CompanyDebPresent,
Sdf57ValidationRule.CompanyCredPresent,
Sdf57ValidationRule.AccountDebPresent,
Sdf57ValidationRule.CurrencyCode
);
};
}
@Bean("sdf16Validator")
public Function<SDf16, IValidator> sdf16Validator() {
return sDf16 -> {

View file

@ -11,6 +11,7 @@ public enum BalanceError implements IErrorEnumId {
AccountNotPresent(5217L),
AccountNotActive(5218L),
BalanceNotEnough(5222L),
CompanyNotActive(5411L),
;
private final Long id;

View file

@ -1,11 +1,10 @@
package ru.spcex.clearing.balance.service;
import ru.spcex.clearing.platform.messaging.domain.cud.balance.StatementRequest;
import ru.spcex.platform.classes.base.interfaces.WithAccount;
import java.util.Collection;
public abstract class AbstractExecutor<T extends WithAccount> {
public abstract class AbstractExecutor<T> {
abstract Result execute(Collection<T> sdf, StatementRequest statementRequest);
abstract String exportTableName();
}

View file

@ -0,0 +1,215 @@
package ru.spcex.clearing.balance.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.account.Account;
import ru.clearing.classes.statics.data.account.AccountBalance;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.sdf.SDf02;
import ru.clearing.classes.statics.data.sdf.SDf57;
import ru.clearing.classes.statics.data.statement.Statement;
import ru.spcex.clearing.balance.errors.BalanceError;
import ru.spcex.clearing.balance.validation.ValidationStored;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.cud.balance.StatementRequest;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.text.TextUtil;
import ru.spcex.platform.utils.validation.IValidator;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
@Service
public class Sdf57Executor extends AbstractExecutor<SDf57> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final static DateTimeFormatter datFormatter = DateTimeFormatter.ofPattern("dd.MM.yy");
private final Imdg<Statement> statementImdg;
private final Imdg<Registry> registryImdg;
private final Function<SDf57, IValidator> sDf57Validator;
private final LoggingService errorLogger;
private final Imdg<SDf02> sdf02Imdg;
private final ImdgProvider imdgProvider;
private final AccountBalanceService accountBalanceService;
private final IMessageResolver errorResolver;
private final Imdg<AccountBalance> accountBalanceImdg;
private final IMessageResolver messageResolver;
public Sdf57Executor(@Qualifier("sdf57Validator") Function<SDf57, IValidator> sDf57Validator,
LoggingService errorLogger,
ImdgProvider imdgProvider,
AccountBalanceService accountBalanceService,
IMessageResolver errorResolver, IMessageResolver messageResolver) {
this.statementImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Statement, Statement.class);
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.sdf02Imdg = imdgProvider.getImdg(IMDGDistributedNames.Map_SDf02, SDf02.class);
this.accountBalanceImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_AccountBalance, AccountBalance.class);
this.sDf57Validator = sDf57Validator;
this.errorLogger = errorLogger;
this.imdgProvider = imdgProvider;
this.accountBalanceService = accountBalanceService;
this.errorResolver = errorResolver;
this.messageResolver = messageResolver;
}
@Override
String exportTableName() {
return "DF-57";
} //no need...
//V - Изменение statement по sDf57
//
//1. Перед изменением statement необходимо выполнить ряд проверок:
// 1.1. Найти в company запись, у которой company.tradingCode=sDf57.deal_deb. Если такой записи нет, записать в лог ошибку (5211) "Компания %s не найдена".
// 1.2. Найти в company запись, у которой company.tradingCode=sDf57.deal_cred. Если такой записи нет, записать в лог ошибку (5211) "Компания %s не найдена".
// 1.3. Проверить, есть ли в таблице account счет, у которого account.account=sDf57.c_acc_deb. Если такой записи нет, записать в лог ошибку (5217) "Счет %s не найден".
// 1.4. Проверить, есть ли в таблице account счет, у которого account.account=sDf57.c_acc_cred. Если такой записи нет, записать в лог ошибку (5217) "Счет %s не найден".
// 1.5. Проверить, что sDf57.pay_val=RUR. Иначе записать в лог ошибку (5213) "Валюта %s не найдена".
//2. В зависимости от результата прохождения проверок в п.1 раздела Изменение statement по sDf57:
// 2.1. Если все проверки пройдены, необходимо сформировать 2 новые записи согласно описанию с соответствующим тэгом,
// где первая запись будет содержать информацию о плательщике (по sDf57.deal_deb),
// а вторая о получателе (по sDf57.deal_cred) и связаны по одному inSDfId (= sDf57.id).
// 2.2. Иначе запись в statement не добавляется.
//3. По итогу добавления statement:
// Если в п.1 раздела Изменение statement по sDf57 ошибок не обнаружено, то инициировать изменение таблицы registry согласно описанию с соответствующим тэгом.
// По итогу изменения registry должны быть обновлены значения полей в statement:
// - operationStatus;
// - errorCode в случае выявления ошибки;
// - errorText в случае выявления ошибки.
public Result execute(Collection<SDf57> sdf, StatementRequest statementRequest) {
Result result = new Result();
Long generationIdForGroup = imdgProvider.getImdgIdGenerator().nextId();
result.setGenerationId(generationIdForGroup);
for (SDf57 sdf57 : sdf) {
IValidator validator = sDf57Validator.apply(sdf57);
Optional<EnumMessage> error = validator.tillFirstError();
if (error.isPresent()) {
log.error("error while validating sdf57.id={} - {}", sdf57.getId(), messageResolver.resolve(error.get()));
continue;
}
//create by companyDeb
Company companyDeb = validator.getStored(ValidationStored.Sdf57CompanyDeb);
Account accountDeb = validator.getStored(ValidationStored.Sdf57AccountDeb);
Statement statementDeb = create(sdf57, companyDeb, accountDeb);
statementImdg.insert(statementDeb);
//create by companyCred
Company companyCred = validator.getStored(ValidationStored.Sdf57CompanyCred);
Account accountCred = validator.getStored(ValidationStored.Sdf57AccountCred);
Statement statementCred = create(sdf57, companyCred, accountCred);
statementImdg.insert(statementCred);
Consumer<StmtCmpAcc> createRegistryIfNeeded = stmtCmpAcc -> {
Statement stmt = stmtCmpAcc.statement();
Optional<EnumMessage> err = validateActiveness(stmtCmpAcc.company(), stmtCmpAcc.account(), stmt);
if (err.isEmpty()) {
Consumer<Registry> update = rgs -> {
updateReg(stmt, rgs);
registryImdg.update(rgs);
};
Runnable create = () -> {
Registry registry = createRegistryByStatement(stmt);
registryImdg.insert(registry);
};
findReg(stmt, RegistryDesignation.A).ifPresentOrElse(update, create);
findReg(stmt, RegistryDesignation.D).ifPresentOrElse(update, create);
stmt.setOperationStatus(OperationStatus.Executed.getKey());
} else {
stmt.setErrorCodeId(err.get().getSubject().getId()); // fixme ErrorText insert
stmt.setOperationStatus(OperationStatus.Rejected.getKey());
statementImdg.update(stmt);
}
};
createRegistryIfNeeded.accept(new StmtCmpAcc(statementDeb, companyDeb, accountDeb));
createRegistryIfNeeded.accept(new StmtCmpAcc(statementCred, companyCred, accountCred));
}
return result;
}
private static record StmtCmpAcc(Statement statement, Company company, Account account) {
}
private Optional<EnumMessage> validateActiveness(Company company, Account account, Statement statement) {
if (!WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
return Optional.of(new EnumMessage(BalanceError.CompanyNotActive, company.getId()));
}
if (!WorkflowStatus.Active.equalsByKey(account.getStatus())) {
return Optional.of(new EnumMessage(BalanceError.AccountNotActive, account.getId()));
}
return Optional.empty();
}
private Statement create(SDf57 sdf57, Company companyDeb, Account accountDeb) {
Statement statement = new Statement();
statement.setAddresseeId(companyDeb.getId());
statement.setSenderId(Sender.Prc.getId());
statement.setStatementType(StatementType.full.getKey());
statement.setContract(getContractFromSpecif(sdf57.getSpecif()));
statement.setAccountId(accountDeb.getId());
statement.setAccount(accountDeb.getAccount());
statement.setInOutDirection(InOutDirection.out.getKey());
statement.setSettlementDate(payDate(sdf57.getPay_date())); //fixme pay_date format
statement.setAmount(TextUtil.isEmpty(sdf57.getSum_deb()) ? null : new BigDecimal(sdf57.getSum_deb()));
statement.setOperationStatus(OperationStatus.Pending.getKey());
statement.setInSDfId(sdf57.getId());
statement.setInOutSDfType(InOutSDfType.type57.getKey());
return statement;
}
private Registry createRegistryByStatement(Statement statement) {
//todo
return new Registry();
}
private void updateReg(Statement s, Registry r) {
//todo
}
private Optional<Registry> findReg(Statement s, RegistryDesignation des) {
//todo add dependency on Registry search
// RegistryTradingParams p = new RegistryTradingParams(
// des, RegistryInstrumentType.M, RegistryCapacity.A, RegistryUnit.T
// );
// String sql = RegistryCodeSqlBuilder.getInstance(p).build();
// ImdgPredicateBuilder pb = registryImdg.predicateBuilder();
// ImdgPredicate rgstrPredicate = pb.and(pb.sql(sql),
// pb.sql(sql),
// pb.equals("companyId", s.getAddresseeId()) //fixme companyId?
// );
// if (des.equals(RegistryDesignation.D) && !TextUtil.isEmpty(s.getContract())) {
// rgstrPredicate = pb.and(rgstrPredicate, pb.equals("contract", s.getContract()));
// }
// return Optional.ofNullable(registryImdg.getSingleObjectByPredicate(rgstrPredicate));
return null;
}
DateTimeFormatter payDateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
private LocalDate payDate(String payDate) {
if (TextUtil.isEmpty(payDate)) {
return null;
}
return LocalDate.parse(payDate, payDateFormatter);
}
private String getContractFromSpecif(String specif) {
if (specif == null) {
return null;
}
int index = specif.indexOf("");
if (index == -1) {
return null;
}
return specif.substring(index + 1);
}
}

View file

@ -8,7 +8,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf01;
import ru.clearing.classes.statics.data.sdf.SDf09;
import ru.clearing.classes.statics.data.sdf.SDf16;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
@ -39,14 +38,14 @@ public class StatementService extends QueueConsumer implements InitializingBean
private final ImdgProvider imdgProvider;
private final KafkaSender kafkaReqProducer;
private final Map<SdfTable, Imdg<? extends WithAccount>> sdfImdgs;
private final Map<SdfTable, AbstractExecutor<? extends WithAccount>> executorsMap;
private final Map<SdfTable, AbstractExecutor<?>> executorsMap;
private final AccountBalanceService accountBalanceService;
@Autowired
public StatementService(Consumer<String, Object> kafkaQueue,
ImdgProvider imdgProvider,
KafkaSender kafkaReqProducer,
@Qualifier("sdfExecutors") Map<SdfTable, AbstractExecutor<? extends WithAccount>> executorsMap, AccountBalanceService accountBalanceService) {
@Qualifier("sdfExecutors") Map<SdfTable, AbstractExecutor<?>> executorsMap, AccountBalanceService accountBalanceService) {
super(kafkaQueue);
this.imdgProvider = imdgProvider;
this.accountBalanceService = accountBalanceService;
@ -76,7 +75,7 @@ public class StatementService extends QueueConsumer implements InitializingBean
accountBalanceService.updateAccountBalanceByClearing(payload);
CommonIdRequest commonIdRequest = new CommonIdRequest();
commonIdRequest.setId(updateAccBalanceReq.getId());
kafkaReqProducer.sendRequestToQueue(Consts.CONTINUE_CLEARING, commonIdRequest);
kafkaReqProducer.sendRequestToQueue(Consts.CONTINUE_CLEARING, commonIdRequest, updateAccBalanceReq.getCorrelationId());
}
private void process(BaseRequest<StatementRequest> systemRequest) {

View file

@ -0,0 +1,94 @@
package ru.spcex.clearing.balance.validation;
import ru.clearing.classes.statics.data.account.Account;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.sdf.SDf57;
import ru.spcex.clearing.balance.errors.BalanceError;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.validation.ImdgValidationContext;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.text.TextUtil;
import ru.spcex.platform.utils.validation.IValidationRule;
import java.util.Optional;
public enum Sdf57ValidationRule implements IValidationRule<ImdgValidationContext<SDf57>> {
CompanyDebPresent() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<SDf57> context) {
SDf57 sdf57 = context.getValidatedObject();
if (TextUtil.isEmpty(sdf57.getDeal_deb())) {
return of(BalanceError.CompanyNotFound, sdf57.getDeal_deb());
}
Imdg<Company> companyImdg = context.obtainMap(IMDGDistributedNames.Map_Company, Company.class);
Company found = companyImdg.getSingleObjectBySQL("tradingCode = '" + sdf57.getDeal_deb() + "'");
if (found == null) {
return of(BalanceError.CompanyNotFound, sdf57.getDeal_deb());
}
context.storeObject(ValidationStored.Sdf57CompanyDeb, found);
return empty();
}
}, CompanyCredPresent() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<SDf57> context) {
SDf57 sdf57 = context.getValidatedObject();
if (TextUtil.isEmpty(sdf57.getDeal_cred())) {
return of(BalanceError.CompanyNotFound, sdf57.getDeal_deb());
}
Imdg<Company> companyImdg = context.obtainMap(IMDGDistributedNames.Map_Company, Company.class);
Company found = companyImdg.getSingleObjectBySQL("tradingCode = '" + sdf57.getDeal_cred() + "'");
if (found == null) {
return of(BalanceError.CompanyNotFound, sdf57.getDeal_deb());
}
context.storeObject(ValidationStored.Sdf57CompanyCred, found);
return empty();
}
}, AccountDebPresent() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<SDf57> context) {
SDf57 sdf57 = context.getValidatedObject();
if (TextUtil.isEmpty(sdf57.getC_acc_deb())) {
return of(BalanceError.AccountNotPresent, sdf57.getDeal_deb());
}
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
Account found = accountImdg.getSingleObjectBySQL("account = '" + sdf57.getC_acc_deb() + "'");
if (found == null) {
return of(BalanceError.AccountNotPresent, sdf57.getDeal_deb());
}
context.storeObject(ValidationStored.Sdf57AccountDeb, found);
return empty();
}
}, AccountCredPresent() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<SDf57> context) {
SDf57 sdf57 = context.getValidatedObject();
if (TextUtil.isEmpty(sdf57.getC_acc_cred())) {
return of(BalanceError.AccountNotPresent, sdf57.getDeal_deb());
}
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
Account found = accountImdg.getSingleObjectBySQL("account = '" + sdf57.getC_acc_cred() + "'");
if (found == null) {
return of(BalanceError.AccountNotPresent, sdf57.getDeal_deb());
}
context.storeObject(ValidationStored.Sdf57AccountCred, found);
return empty();
}
}, CurrencyCode() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<SDf57> context) {
SDf57 sdf57 = context.getValidatedObject();
if (!ru.spcex.platform.enumeration.CurrencyCode.RUR.equalsByKey(sdf57.getPay_val())) {
return of(BalanceError.CurrencyNotFound, sdf57.getPay_val());
}
return empty();
}
};
@Override
public String ruleName() {
return "Sdf57ValidationRule." + name();
}
}

View file

@ -1,5 +1,9 @@
package ru.spcex.clearing.balance.validation;
public enum ValidationStored {
Account, Company;
Account, Company,
Sdf57CompanyDeb, Sdf57CompanyCred, Sdf57AccountDeb, Sdf57AccountCred
;
}

View file

@ -7,7 +7,7 @@ import java.math.BigDecimal;
/**
* Реестр остатков денежных средств
*
* <p>
* DB table: MONEY_BALANCE_REGISTER
**/
public class MoneyBalanceRegister extends BusinessObject {
@ -24,74 +24,108 @@ public class MoneyBalanceRegister extends BusinessObject {
private String companyFullName;
private Long companyId;
public static MoneyBalanceRegister makeMoneyBalanceRegister(String setHouseName,
String account,
String infoAccount,
BigDecimal remainderSum,
BigDecimal blockedSum,
BigDecimal unblockedSum,
String inn,
Long sessionId,
String companyFullName,
Long companyId) {
MoneyBalanceRegister moneyBalanceRegister = new MoneyBalanceRegister();
moneyBalanceRegister.setSetHouseName(setHouseName);
moneyBalanceRegister.setAccount(account);
moneyBalanceRegister.setInfoAccount(infoAccount);
moneyBalanceRegister.setRemainderSum(remainderSum);
moneyBalanceRegister.setBlockedSum(blockedSum);
moneyBalanceRegister.setUnblockedSum(unblockedSum);
moneyBalanceRegister.setInn(inn);
moneyBalanceRegister.setSessionId(sessionId);
moneyBalanceRegister.setCompanyFullName(companyFullName);
moneyBalanceRegister.setCompanyId(companyId);
return moneyBalanceRegister;
}
public String getSetHouseName() {
return setHouseName;
}
public void setSetHouseName(String value) {
this.setHouseName=value;
this.setHouseName = value;
}
public String getAccount() {
return account;
}
public void setAccount(String value) {
this.account=value;
this.account = value;
}
public String getInfoAccount() {
return infoAccount;
}
public void setInfoAccount(String value) {
this.infoAccount=value;
this.infoAccount = value;
}
public BigDecimal getRemainderSum() {
return remainderSum;
}
public void setRemainderSum(BigDecimal value) {
this.remainderSum=value;
this.remainderSum = value;
}
public BigDecimal getBlockedSum() {
return blockedSum;
}
public void setBlockedSum(BigDecimal value) {
this.blockedSum=value;
this.blockedSum = value;
}
public BigDecimal getUnblockedSum() {
return unblockedSum;
}
public void setUnblockedSum(BigDecimal value) {
this.unblockedSum=value;
this.unblockedSum = value;
}
public String getInn() {
return inn;
}
public void setInn(String value) {
this.inn=value;
this.inn = value;
}
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long value) {
this.sessionId=value;
this.sessionId = value;
}
public String getCompanyFullName() {
return companyFullName;
}
public void setCompanyFullName(String value) {
this.companyFullName=value;
this.companyFullName = value;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long value) {
this.companyId=value;
this.companyId = value;
}
}

View file

@ -8,11 +8,13 @@ import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.classes.statics.data.execution.ExecutionDeposit;
import ru.clearing.classes.statics.data.misc.STrades;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.clearing.classes.statics.data.security.Security;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.service.validation.ClrngValidationStored;
import ru.spcex.clearing.service.validation.ExecutionDepositValidationRule;
import ru.spcex.clearing.service.validation.RegistryStep3ValidationRule;
import ru.spcex.clearing.service.validation.STradesValidationRule;
import ru.spcex.platform.classes.base.SpcexObjectBase;
import ru.spcex.platform.enumeration.ClearingCategory;
@ -86,4 +88,23 @@ public class ValidationConfig {
STradesValidationRule.TradingClearingRegistryPresent);
};
}
@Bean("obligationAndRequirementsAdmissionValidator")
public Function<Registry, IValidator> registryValidator() {
return rgs -> {
ImdgValidationContext<Registry> context = new ImdgValidationContext<>();
context.setValidatedObject(rgs);
addImdg.accept(context, IMDGDistributedNames.Map_Relation);
addImdg.accept(context, IMDGDistributedNames.Map_Session);
addImdg.accept(context, IMDGDistributedNames.Map_SectionDictionary);
addImdg.accept(context, IMDGDistributedNames.Map_Account);
addImdg.accept(context, IMDGDistributedNames.Map_Company);
addImdg.accept(context, IMDGDistributedNames.Map_TradingClearingRegistry);
return new ValidatorImpl<>(context,
RegistryStep3ValidationRule.ClearingAvailable,
RegistryStep3ValidationRule.AccountActive,
RegistryStep3ValidationRule.CompanyActive,
RegistryStep3ValidationRule.TradingClearingRegistryActive);
};
}
}

View file

@ -5,12 +5,15 @@ import ru.spcex.platform.utils.enumeration.IErrorEnumId;
public enum ClearingError implements IErrorEnumId {
GeneralError(5400L),
RecordNotFound(5406L),
CompanyNotActive(5411L),
CompanyCreditCheck(5412L),
CompanyDebitCheck(5413L),
CompanyNotFound(5410L),
AccountNotActive(5415L),
SecurityNotFound(5416L),
TradingClearingRegistryNotFound(5418L),
TradingClearingRegistryNotActive(5419L),
ClearingUnavailableForCompany(5421L),
InsecurityObligation(5422L),
NewDealsNotFound(5423L),
;

View file

@ -1,16 +0,0 @@
package ru.spcex.clearing.models;
import ru.spcex.platform.enumeration.RegistryCapacity;
import ru.spcex.platform.enumeration.RegistryDesignation;
import ru.spcex.platform.enumeration.RegistryInstrumentType;
import ru.spcex.platform.enumeration.RegistryUnit;
public record RegistryInfo(RegistryDesignation registryDesignation,
RegistryInstrumentType registryInstrumentType,
RegistryCapacity registryCapacity,
RegistryUnit registryUnit) {
public String buildSqlCondition(){
return "";
}
}

View file

@ -9,19 +9,23 @@ import ru.spcex.clearing.platform.messaging.domain.cud.clearing.Sdf04Request;
import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonIdRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.schedule.LauncherCommandRequest;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
import ru.spcex.clearing.session.stage.PrimaryAuctionBnSession;
import ru.spcex.platform.enumeration.Task;
@Service
public class EventsReceiver extends QueueConsumer implements InitializingBean {
private final ClearingService clearingService;
private final RegistryService registryService;
private final PrimaryAuctionBnSession primaryAuctionBnSession;
public EventsReceiver(Consumer<String, Object> kafkaQueue,
ClearingService clearingService,
RegistryService registryService) {
RegistryService registryService,
PrimaryAuctionBnSession primaryAuctionBnSession) {
super(kafkaQueue);
this.clearingService = clearingService;
this.registryService = registryService;
this.primaryAuctionBnSession = primaryAuctionBnSession;
}
@Override
@ -38,12 +42,15 @@ public class EventsReceiver extends QueueConsumer implements InitializingBean {
callback(LauncherCommandRequest.class)
.setConsumer(event -> clearingService.executeVerification())
.forDestination(Task.getVerification.topic(), callbacks::put);
callback(Object.class) //todo check Object suitable
.setConsumer(event -> clearingService.executeClearing())
callback(Object.class)
.setConsumer(primaryAuctionBnSession::runSession)
.forDestination(Task.startOfClearing.topic(), callbacks::put);
callback(CommonIdRequest.class)
.setConsumer(clearingService::continueClearing)
.forDestination(Consts.CONTINUE_CLEARING, callbacks::put);
callback(Object.class)
.setConsumer(primaryAuctionBnSession::continueSession)
.forDestination(Consts.SDF57_PROCESS, callbacks::put);
callback(Object.class)
.setConsumer(event -> clearingService.executeSTrade())
.forDestination(Task.getOfTrades.topic(), callbacks::put);

View file

@ -54,7 +54,7 @@ public class ExecutionDepositComponent {
//fixme ждать ТЗ
Long tradeNum;
Instant tradingDay;
private final IMessageResolver msgResolver = new SimpleMessageResolver();
private final IMessageResolver msgResolver;
private final Function<STrades, IValidator> stradesValidator;
private final KafkaSender kafkaSender;
@ -62,12 +62,14 @@ public class ExecutionDepositComponent {
@Autowired
public ExecutionDepositComponent(ImdgProvider imdgProvider, Producer<String, Object> kafka,
@Qualifier("sTradesValidator") Function<STrades, IValidator> stradesValidator,
@Qualifier("kafkaSenderWithoutRequestInfo") KafkaSender kafkaSender) {
@Qualifier("kafkaSenderWithoutRequestInfo") KafkaSender kafkaSender,
IMessageResolver msgResolver) {
this.sTradeImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_STrades, STrades.class);
this.executionDepositImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_ExecutionDeposit, ExecutionDeposit.class);
this.listingImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Listing, Listing.class);
this.stradesValidator = stradesValidator;
this.kafkaSender = kafkaSender;
this.msgResolver = msgResolver;
resetTradingDay();
}
@ -127,7 +129,7 @@ public class ExecutionDepositComponent {
}
ExecutionDeposit newED;
try {
newED = createExecutionDeposit(sTrd, validator);
newED = createExecutionDeposit(sTrd, validator);
executionDepositImdg.insert(newED);
sendNotification(newED);
log.debug("New executionDeposit.id={} was created.", newED.getId());

View file

@ -6,7 +6,6 @@ import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.models.RegistryInfo;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.CreateRegistryRequest;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
@ -42,7 +41,7 @@ public class RegistryService {
log.trace("Found tradingClearingRegistry with id: {}", tcrByCompanyId.getId());
Registry registry = new Registry();
tcrByCompanyId.getTradingClearingRegistryType();
RegistryInfo registryInfo = createRegistryInfoByType(tcrByCompanyId.getTradingClearingRegistryType());
RegistryTradingParams registryInfo = createRegistryInfoByType(tcrByCompanyId.getTradingClearingRegistryType());
registry.setRegistryDesignation(registryInfo.registryDesignation().getKey());
registry.setRegistryInstrumentType(registryInfo.registryInstrumentType().getKey());
registry.setRegistryCapacity(registryInfo.registryCapacity().getKey());
@ -55,20 +54,20 @@ public class RegistryService {
}
private RegistryInfo createRegistryInfoByType(String type){
private RegistryTradingParams createRegistryInfoByType(String type){
TradingClearingRegistryType registryType = IEnumKey.getEnumByKey(TradingClearingRegistryType.class, type);
RegistryInfo registryInfo = null;
RegistryTradingParams registryInfo = null;
//todo спросить про дубль C и T
switch (registryType){
case Owner_A -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.M, RegistryCapacity.A, RegistryUnit.T);
case Client_B -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.T);
case Trustee_C, DepoOfShares_T -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.T);
case TrusteeManager_D -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.A);
case Issuer_E -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.E, RegistryUnit.R);
case ToThePlacementOrRedeem_Z -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.Z, RegistryUnit.R);
case DepoBond_H -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.R);
case DepoOfTrustedBond_N -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.C, RegistryUnit.R);
case DepoOfTrustedShares_S -> registryInfo = new RegistryInfo(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.C, RegistryUnit.T);
case Owner_A -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.M, RegistryCapacity.A, RegistryUnit.T);
case Client_B -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.T);
case Trustee_C, DepoOfShares_T -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.T);
case TrusteeManager_D -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.A);
case Issuer_E -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.E, RegistryUnit.R);
case ToThePlacementOrRedeem_Z -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.Z, RegistryUnit.R);
case DepoBond_H -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.R);
case DepoOfTrustedBond_N -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.C, RegistryUnit.R);
case DepoOfTrustedShares_S -> registryInfo = new RegistryTradingParams(RegistryDesignation.A, RegistryInstrumentType.S, RegistryCapacity.C, RegistryUnit.T);
}
return registryInfo;
}

View file

@ -0,0 +1,104 @@
package ru.spcex.clearing.service.validation;
import ru.clearing.classes.statics.data.account.Account;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.company.relation.Relation;
import ru.clearing.classes.statics.data.misc.Session;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.clearing.platform.dictionary.SectionDictionary;
import ru.spcex.clearing.error.ClearingError;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.platform.enumeration.ServiceStatus;
import ru.spcex.platform.enumeration.WorkflowStatus;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.validation.ImdgValidationContext;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IEnumKey;
import ru.spcex.platform.utils.validation.IValidationRule;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
public enum RegistryStep3ValidationRule implements IValidationRule<ImdgValidationContext<Registry>> {
ClearingAvailable() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<Registry> context) {
Registry validatedObject = context.getValidatedObject();
Supplier<String> sectionFind = () -> {
Imdg<Session> sessionImdg = context.obtainMap(IMDGDistributedNames.Map_Session, Session.class);
Imdg<SectionDictionary> sectionDictionaryImdg = context.obtainMap(IMDGDistributedNames.Map_SectionDictionary, SectionDictionary.class);
Session session = sessionImdg.getSingleObjectByID(validatedObject.getSessionId());
if (session == null) {
return "null";
} else {
SectionDictionary section = sectionDictionaryImdg.getSingleObjectBySQL("code ='" + session.getSection() + "'");
if (section == null) {
return "null";
} else {
return section.getName();
}
}
};
if (validatedObject.getCompanyId() == null) {
return of(ClearingError.ClearingUnavailableForCompany, sectionFind.get());
}
Imdg<Relation> relationImdg = context.obtainMap(IMDGDistributedNames.Map_Relation, Relation.class);
Relation relation = relationImdg.getSingleObjectByFieldValues(Map.of("consumerId", validatedObject.getCompanyId()));
if (relation == null || (!ServiceStatus.Active.equalsByKey(relation.getServiceStatus()) && !ServiceStatus.Reopened.equalsByKey(relation.getServiceStatus()))) {
return of(ClearingError.ClearingUnavailableForCompany, sectionFind.get(), validatedObject.getCompanyId());
}
context.storeObject(RegistryValidationStored.Relation, relation);
return empty();
}
},
AccountActive() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<Registry> context) {
Registry validatedObject = context.getValidatedObject();
Relation relation = context.getStoredObject(RegistryValidationStored.Relation);
Imdg<Account> accountImdg = context.obtainMap(IMDGDistributedNames.Map_Account, Account.class);
Account account = accountImdg.getSingleObjectBySQL("id = %d and relationId = %d".formatted(validatedObject.getAccountId(), relation.getId()));
if (account == null || (!IEnumKey.contains(account.getStatus(), ServiceStatus.Active, ServiceStatus.Reopened))) {
return of(ClearingError.AccountNotActive, validatedObject.getAccountId());
}
return empty();
}
},
CompanyActive() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<Registry> context) {
Registry validatedObject = context.getValidatedObject();
Imdg<Company> companyImdg = context.obtainMap(IMDGDistributedNames.Map_Company, Company.class);
if (validatedObject.getCompanyId() == null) {
return of(ClearingError.CompanyNotActive, validatedObject.getCompanyId());
}
Company company = companyImdg.getSingleObjectBySQL("id = %d".formatted(validatedObject.getCompanyId()));
if (company == null || !WorkflowStatus.Active.equalsByKey(company.getWorkflowStatus())) {
return of(ClearingError.CompanyNotActive, validatedObject.getCompanyId());
}
return empty();
}
},
TradingClearingRegistryActive() {
@Override
public Optional<EnumMessage> validate(ImdgValidationContext<Registry> context) {
Registry validatedObject = context.getValidatedObject();
if (validatedObject.getTradingClearingRegistryId() == null) {
return of(ClearingError.TradingClearingRegistryNotActive, validatedObject.getTradingClearingRegistryId());
}
Imdg<TradingClearingRegistry> tradingClearingRegistryImdg = context.obtainMap(IMDGDistributedNames.Map_TradingClearingRegistry, TradingClearingRegistry.class);
TradingClearingRegistry tcr = tradingClearingRegistryImdg.getSingleObjectBySQL("id = " + validatedObject.getTradingClearingRegistryId());
if (tcr == null || (ServiceStatus.Active.equalsByKey(tcr.getStatus()) || ServiceStatus.Reopened.equalsByKey(tcr.getStatus())))
return of(ClearingError.TradingClearingRegistryNotActive, validatedObject.getTradingClearingRegistryId());
return empty();
}
},
;
@Override
public String ruleName() {
return "STradesValidationRule." + name();
}
}

View file

@ -0,0 +1,5 @@
package ru.spcex.clearing.service.validation;
public enum RegistryValidationStored {
Relation
}

View file

@ -0,0 +1,200 @@
package ru.spcex.clearing.session.stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.execution.ExecutionCommon;
import ru.clearing.classes.statics.data.misc.Session;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.session.stage.impl.*;
import ru.spcex.clearing.session.stage.task.*;
import ru.spcex.platform.enumeration.Section;
import ru.spcex.platform.enumeration.SessionStatus;
import ru.spcex.platform.enumeration.SessionType;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
@Service
public class PrimaryAuctionBnSession {
private final Logger log = LoggerFactory.getLogger(getClass());
private final BalanceRevise balanceRevise;
private final DealsPrepare dealsPrepare;
private final RequirementsAndObligationCreation requirementsAndObligationCreation;
private final ObligationAdmission obligationsAdmission;
private final InclusionObligations inclusionObligations;
private final FormingRegistersOnOS formingRegistersOnOS;
private final FormingPaymentInstruction formingPaymentInstruction;
private final UnlockResources unlockResources;
private final FinishingSession finishingSession;
private final EndStageNotification endStageNotification;
private Imdg<Session> sessionImdg;
private final IMessageResolver messageResolver;
private final AtomicReference<TaskType> currStage = new AtomicReference<>();
private Session currSession;
public PrimaryAuctionBnSession(
ImdgProvider imdgProvider,
BalanceRevise balanceRevise,
DealsPrepare dealsPrepare,
RequirementsAndObligationCreation requirementsAndObligationCreation,
ObligationAdmission obligationsAdmission,
InclusionObligations inclusionObligations,
FormingRegistersOnOS formingRegistersOnOS,
FormingPaymentInstruction formingPaymentInstruction,
UnlockResources unlockResources,
FinishingSession finishingSession, EndStageNotification endStageNotification, IMessageResolver messageResolver) {
this.balanceRevise = balanceRevise;
this.dealsPrepare = dealsPrepare;
this.requirementsAndObligationCreation = requirementsAndObligationCreation;
this.obligationsAdmission = obligationsAdmission;
this.inclusionObligations = inclusionObligations;
this.formingRegistersOnOS = formingRegistersOnOS;
this.formingPaymentInstruction = formingPaymentInstruction;
this.unlockResources = unlockResources;
this.finishingSession = finishingSession;
this.endStageNotification = endStageNotification;
this.sessionImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Session, Session.class);
this.messageResolver = messageResolver;
}
public void runSession(BaseRequest<?> req) {
if (!startSession()) {
return;
}
StageResult<?> submit = balanceRevise.submit(new Task<>(TaskType.StartRevise, null));
if (!submit.success) {
log.error("stage {} error={}", balanceRevise.getClass().getSimpleName(), messageResolver.resolve(submit.error));
endSession();
} else {
log.info("stage BalanceRevise success, waiting for a response from kafka");
}
}
public void continueSession(BaseRequest<?> req) {
try {
if (!checkStage(TaskType.StartRevise)) {
log.error("cannot continue session, current stage is {}", currStage.get());
throw new StageException();
}
//stage 0
runStage(TaskType.ContinueRevise, balanceRevise);
//stage 1
StageResult<List<ExecutionCommon>> dealsPreparationResult;
{
DealsPreparePayload payload = new DealsPreparePayload();
payload.setSessionId(currSession.getId());
dealsPreparationResult = runStage(TaskType.DealsPrepare , payload, dealsPrepare);
}
//stage 2
runStage(TaskType.RequirementsAndObligationsCreate, dealsPreparationResult.getStageResult(), requirementsAndObligationCreation);
//stage 3
runStage(TaskType.ObligationsAdmission, currSession.getId(), obligationsAdmission);
//stage 4
{
InclusionToPoolPayload inclusionToPoolPayload = new InclusionToPoolPayload();
inclusionToPoolPayload.setSessionType(currSession.getSessionType());
runStage(TaskType.InclusionToPool, inclusionToPoolPayload, inclusionObligations);
}
//stage 5
{
InspectionPoolPayload companyIdPayload = new InspectionPoolPayload();
companyIdPayload.setProcessedCompanyId(currSession.getCompanyId());
runStage(TaskType.InspectionObligations, companyIdPayload, inclusionObligations);
}
//stage 6
runStage(TaskType.FormingRegistersOnOS, formingRegistersOnOS); //returns Collection<Registry>
//stage 7
runStage(TaskType.FormingPaymentInstruction, formingPaymentInstruction);
//stage 8
{
UnlockResourcesPayload unlockResourcesPayload = new UnlockResourcesPayload();
//todo set arguments
runStage(TaskType.UnlockResources, unlockResourcesPayload, unlockResources); //returns Collection<Registry>
}
//stage 9
{
FinishingSessionPayload payload = new FinishingSessionPayload();
payload.setSessionId(currSession.getId());
runStage(TaskType.FinishingSession, payload, finishingSession);
}
{
EndStageNotificationPayload payload = new EndStageNotificationPayload();
payload.setSection(currSession.getSection());
runStage(TaskType.EndStageNotification, payload, endStageNotification);
}
} catch (StageException e) {
//already logged
}
}
private <T, R> StageResult<R> runStage(TaskType type, ISessionStage stage) {
return runStage(type, null, stage);
}
@SuppressWarnings("unchecked")
private <T, R> StageResult<R> runStage(TaskType type, T payload, ISessionStage stage) {
continueRunning(type);
log.info("session.id={} step {} started", currSession.getId(), currStage.get());
Task<T> t = new Task<>(type, payload);
StageResult<?> stgRes = stage.submit(t);
log.info("session.id={} step {} result: {} ",
currSession.getId(),
currStage.get(),
stgRes.success ? "success" : messageResolver.resolve(stgRes.error));
if (!stgRes.success) {
endSession();
throw new StageException();
}
return (StageResult<R>) stgRes;
}
private boolean startSession() {
synchronized (this.currStage) {
if (this.currStage.get() != null) {
log.info("already running session.id={}", this.currSession.getId());
return false;
} else {
Session newSession = new Session();
newSession.setSection(Section.FOND.getKey());
newSession.setSessionType(SessionType.IPOB.getKey());
newSession.setSessionStatus(SessionStatus.CLRN.getKey());
//todo companyId/securityId/userId передается из сообщения очереди
sessionImdg.insert(newSession);
currSession = newSession;
log.info("started new session.id={}", this.currSession.getId());
currStage.set(TaskType.StartRevise);
return true;
}
}
}
private void endSession() {
synchronized (this.currStage) {
this.currStage.set(null);
this.currSession = null;
}
}
private void continueRunning(TaskType t) {
synchronized (this.currStage) {
this.currStage.set(t);
}
}
private boolean checkStage(TaskType t) {
synchronized (this.currStage) {
return this.currStage.get().equals(t);
}
}
private static class StageException extends RuntimeException {
}
}

View file

@ -15,19 +15,42 @@ public enum TaskType {
* step 2
*/
RequirementsAndObligationsCreate,
/**
* step 3
*/
ObligationsAdmission,
/**
* step 4
*/
InclusionToPool,
/**
* step 5
*/
InspectionObligations,
/**
* Step 6: forming Registry on Obligations and Settlement requirements
*/
FormingRegistersOnOS,
/**
* step 7
*/
FormingPaymentInstruction,
/**
* step 8
*/
UnlockResources,
/**
* Step 10
*/
FinishingSession,
/**
* Step 11
*/
EndStageNotification;
}

View file

@ -3,13 +3,14 @@ package ru.spcex.clearing.session.stage.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.misc.Currency;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.sdf.SDf56;
import ru.clearing.classes.statics.data.statement.Statement;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.Sdf56And51Request;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
@ -19,19 +20,15 @@ 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.predicate.specific.StatementRevisePredicate;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IEnumKey;
import ru.spcex.platform.utils.time.TimeUtil;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import static ru.spcex.clearing.error.ClearingErrorInternal.SessionGeneralError;
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BalanceRevise implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
//todo remove (set all in single method setImdg(provider -> setImdg1();setIdGenerator();...)
@ -40,15 +37,18 @@ public class BalanceRevise implements ISessionStage {
private Imdg<Statement> statementImdg;
private Imdg<Registry> registryImdg;
private Imdg<Currency> currencyImdg;
private Imdg<SDf56> sDf56Imdg;
private KafkaSender kafkaSender;
@Autowired
public BalanceRevise(ImdgProvider imdgProvider) {
public BalanceRevise(ImdgProvider imdgProvider, KafkaSender kafkaSender) {
this.imdgProvider = imdgProvider;
this.idGenerator = imdgProvider.getImdgIdGenerator();
this.statementImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Statement, Statement.class);
this.currencyImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Currency, Currency.class);
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.sDf56Imdg = imdgProvider.getImdg(IMDGDistributedNames.Map_SDf56, SDf56.class);
this.kafkaSender = kafkaSender;
}
@Override
@ -61,28 +61,29 @@ public class BalanceRevise implements ISessionStage {
cashFlow(); //((SdfClearingRequest) task.getData()).getGroupId() if needed
return revise();
}
default -> throw new IllegalStateException("unknown task " + task.getTaskType());
}
return null;
}
private StageResult<?> sendSdfs() {
Collection<Long> currencies = currencyImdg.projectSingleAttribute("id");
Statement statement = statementImdg.aggregateByMax("created", StatementRevisePredicate.get(statementImdg, currencies));
Instant now = Instant.now();
Sdf56And51Request sdf56Request = new Sdf56And51Request();
sdf56Request.setDf56Number(idGenerator.nextId()); //fixme day scope id generator
sdf56Request.setsDateTime(statement != null ?
statement.getCreated() : TimeUtil.localDateToInstant(LocalDate.of(2023, Month.JANUARY, 1))); //fixme default sDate
sdf56Request.seteDateTime(now);
sdf56Request.setDf51Number(idGenerator.nextId()); //fixme day scope id generator
sdf56Request.setDateTime(now);
Long msgKey = kafkaSender.sendRequestToQueue(Consts.SDF56_PROCESS, sdf56Request);
if (msgKey == null) {
log.error("failed to put SDF56 request to kafka queue");
return new StageResult<>(new EnumMessage(SessionGeneralError), false);
}
newSDf56(statement);
//fixme теперь не отправляем команду в модуль dbf-export, он получит ее из другого места
// Instant now = Instant.now();
// Sdf56And51Request sdf56Request = new Sdf56And51Request();
// sdf56Request.setDf56Number(idGenerator.nextId()); //fixme day scope id generator
// sdf56Request.setsDateTime(statement != null ?
// statement.getCreated() : TimeUtil.localDateToInstant(LocalDate.of(2023, Month.JANUARY, 1))); //fixme default sDate
// sdf56Request.seteDateTime(now);
// sdf56Request.setDf51Number(idGenerator.nextId()); //fixme day scope id generator
// sdf56Request.setDateTime(now);
// Long msgKey = kafkaSender.sendRequestToQueue(Consts.REVISE_PROCESS, sdf56Request);
// if (msgKey == null) {
// log.error("failed to put SDF56 request to kafka queue");
// return new StageResult<>(new EnumMessage(SessionGeneralError), false);
// }
return new StageResult<>(null, true);
}
@ -132,7 +133,9 @@ public class BalanceRevise implements ISessionStage {
rgsAMT.setBalance(safeBD(rgsAMT.getBalance()).add(safeBD(stmt.getAmount())));
rgsAMT.setCredit(safeBD(rgsAMT.getCredit()).add(safeBD(stmt.getAmount())));
}
default -> {throw new IllegalStateException("null direction");}
default -> {
throw new IllegalStateException("null direction");
}
}
rgsAMF.setBalance(safeBD(rgsAMT.getBalance()).subtract(safeBD(rgsAMB.getBalance())));
registryImdg.update(rgsAMT);
@ -170,4 +173,21 @@ public class BalanceRevise implements ISessionStage {
private BigDecimal safeBD(BigDecimal value) {
return value != null ? value : BigDecimal.ZERO;
}
private void newSDf56(Statement statement) {
log.debug("GALB request received; creating sdf56");
SDf56 sDf56 = new SDf56();
sDf56.setNumber(idGenerator.nextId().toString());
Instant now = Instant.now();
String startTime = String.valueOf(statement != null ?
statement.getCreated().toEpochMilli() : now.minus(1, ChronoUnit.DAYS).toEpochMilli());
sDf56.setStart_datetime(startTime);
sDf56.setEnd_datetime(String.valueOf(now.toEpochMilli()));
sDf56.setAccount("ТБС");
sDf56.setDeal("КОДУ");
sDf56.setGenerationTime(now);
sDf56.setGenerationId(idGenerator.nextId());
sDf56Imdg.insert(sDf56);
log.debug("successfully processed, new id {}", sDf56.getId());
}
}

View file

@ -4,6 +4,7 @@ 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.execution.ExecutionCommon;
import ru.clearing.classes.statics.data.execution.ExecutionDeposit;
import ru.clearing.classes.statics.data.execution.ExecutionFond;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
@ -11,7 +12,6 @@ import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.task.DealsPreparePayload;
import ru.spcex.platform.classes.base.interfaces.IExecution;
import ru.spcex.platform.classes.base.interfaces.WithExchangeExecutionId;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
@ -74,11 +74,11 @@ public class DealsPrepare implements ISessionStage {
ImdgPredicate excFondPrct = prdComposer.apply(execFondPredicates, executionFondImdg);
Collection<ExecutionDeposit> excDpsts = executionDepositImdg.getCollectionObjectsByPredicate(excDepPrct);
Collection<ExecutionFond> excFonds = executionFondImdg.getCollectionObjectsByPredicate(excFondPrct);
List<IExecution> excs = Stream.concat(excDpsts.stream().map(execToInterface()),
List<ExecutionCommon> excs = Stream.concat(excDpsts.stream().map(execToInterface()),
excFonds.stream().map(execToInterface()))
.sorted(Comparator.comparing(WithExchangeExecutionId::getExchangeExecutionId))
.toList();
for (IExecution exc : excs) {
for (ExecutionCommon exc : excs) {
exc.setSessionId(sessionId);
if (exc instanceof ExecutionDeposit) {
executionDepositImdg.update((ExecutionDeposit) exc);
@ -86,7 +86,7 @@ public class DealsPrepare implements ISessionStage {
executionFondImdg.update((ExecutionFond) exc);
}
}
StageResult<List<IExecution>> res = new StageResult<>(null, true);
StageResult<List<ExecutionCommon>> res = new StageResult<>(null, true);
res.setStageResult(excs);
return res;
}
@ -103,7 +103,7 @@ public class DealsPrepare implements ISessionStage {
private static <E extends IExecution> Function<E, IExecution> execToInterface() {
private static <E extends ExecutionCommon> Function<E, ExecutionCommon> execToInterface() {
return (e) -> e;
}
}

View file

@ -0,0 +1,112 @@
package ru.spcex.clearing.session.stage.impl;
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.registry.Registry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.SdfClearingRequest;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.task.EndStageNotificationPayload;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;
import static ru.spcex.clearing.error.ClearingErrorInternal.SessionGeneralError;
@Service
public class EndStageNotification implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Imdg<Registry> registryImdg;
private final KafkaSender kafkaSender;
private final IMessageResolver msgResolver;
@Autowired
public EndStageNotification(ImdgProvider imdgProvider, KafkaSender kafkaSender, IMessageResolver msgResolver) {
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.kafkaSender = kafkaSender;
this.msgResolver = msgResolver;
}
@Override
public StageResult<?> submit(Task<?> task) {
EndStageNotificationPayload payload = (EndStageNotificationPayload) task.getData();
switch (task.getTaskType()) {
case EndStageNotification -> {
return endStageNotification(payload.getSection());
}
default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
}
}
protected Collection<Registry> selectRegistry() {
String registrySQL = "registryStatus='" + RegistryStatus.OK.getKey() + "'";
Collection<Registry> result = registryImdg.getCollectionObjectsBySQL(registrySQL);
log.trace("Selected {} registry's by sql: {}", result.size(), registrySQL);
return result;
}
protected StageResult<?> endStageNotification(String section) {
Collection<Registry> forRegistries = selectRegistry();
Collection<Long> groups = forRegistries.stream()
.map(Registry::getGroupId)
.filter(Objects::nonNull)
.distinct().collect(Collectors.toList());
log.debug("Sending notifications for {} groups ({} registers) on section {}",
groups, forRegistries.size(), section);
for (Long groupId : groups) {
log.trace("For registry group {} send notification",
groupId);
StageResult sResult;
if (Section.FOND.equalsByKey(section)) {
sResult = notificationDF14(groupId);
} else if (Section.MKR.equalsByKey(section)) {
sResult = notificationDF05(groupId);
} else {
throw new IllegalArgumentException("Unsupported section " + section);
}
if (sResult.getError() != null) {
log.warn("When sending groupId={} has error: {}", groupId, msgResolver.resolve(sResult.getError()));
}
}
StageResult<Collection<Registry>> res = new StageResult<>(null, true);
return res;
}
protected StageResult notificationDF14(Long groupId) {
SdfClearingRequest sdf14Request = new SdfClearingRequest();
sdf14Request.setGroupId(groupId);
Long msgKey = kafkaSender.sendRequestToQueue(Consts.SDF14_PROCESS, sdf14Request);
if (msgKey == null) {
log.error("failed to put SDF14 request to kafka queue");
return new StageResult<>(new EnumMessage(SessionGeneralError), false);
}
return new StageResult<>(null, true);
}
protected StageResult notificationDF05(Long groupId) {
SdfClearingRequest sdf05Request = new SdfClearingRequest();
sdf05Request.setGroupId(groupId);
Long msgKey = kafkaSender.sendRequestToQueue(Consts.SDF05_PROCESS, sdf05Request);
if (msgKey == null) {
log.error("failed to put SDF05 request to kafka queue");
return new StageResult<>(new EnumMessage(SessionGeneralError), false);
}
return new StageResult<>(null, true);
}
}

View file

@ -0,0 +1,142 @@
package ru.spcex.clearing.session.stage.impl;
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.misc.Session;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.reports.ReportRequestWithRegistryId;
import ru.spcex.clearing.platform.messaging.domain.cud.reports.ReportRequestWithSessionId;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.task.FinishingSessionPayload;
import ru.spcex.platform.enumeration.RegistryDesignation;
import ru.spcex.platform.enumeration.RegistryTradingParams;
import ru.spcex.platform.enumeration.SessionStatus;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicate;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicateBuilder;
import ru.spcex.platform.imdg.api.predicate.specific.RegistryCodeSqlBuilder;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import java.time.Instant;
import java.util.Collection;
import static ru.spcex.clearing.error.ClearingErrorInternal.SessionGeneralError;
@Service
public class FinishingSession implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Imdg<Registry> registryImdg;
private final Imdg<Session> sessionImdg;
private final KafkaSender kafkaSender;
private final IMessageResolver msgResolver;
@Autowired
public FinishingSession(ImdgProvider imdgProvider, KafkaSender kafkaSender, IMessageResolver msgResolver) {
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.sessionImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Session, Session.class);
this.kafkaSender = kafkaSender;
this.msgResolver = msgResolver;
}
@Override
public StageResult<?> submit(Task<?> task) {
FinishingSessionPayload payload = (FinishingSessionPayload) task.getData();
switch (task.getTaskType()) {
case FinishingSession -> {
return finishingSession(payload.getSessionId());
}
default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
}
}
protected Collection<Registry> selectRegistry(Long sessionId) {
RegistryCodeSqlBuilder registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(
new RegistryTradingParams(RegistryDesignation.A, null, null, null)
);
ImdgPredicateBuilder pb = registryImdg.predicateBuilder();
ImdgPredicate condition = registryCodeSqlBuilder.buildPredicate(pb);
condition = pb.and(condition, pb.equals("sessionId", sessionId));
Collection<Registry> result = registryImdg.getCollectionObjectsByPredicate(condition);
log.trace("Selected {} registry's by sql: {}", result.size(), condition);
return result;
}
protected StageResult<?> finishingSession(Long sessionId) {
// 1. Изменить статус
Session theSession = sessionImdg.getSingleObjectByID(sessionId);
if (theSession == null) {
log.warn("Session {} not found", sessionId);
} else {
log.info("Finish status for session {}", sessionId);
theSession.setUpdated(Instant.now());
theSession.setSessionStatus(SessionStatus.CLOS.getKey());
sessionImdg.update(theSession);
log.trace("Session {} was updated", theSession.getId());
}
// 2. Отправка сообщений
Collection<Registry> forRegistries = selectRegistry(sessionId);
log.debug("Found {} registries for sessionId={}", forRegistries.size(), sessionId);
StageResult sResult = toReportSession(sessionId);
if (sResult.getError() != null) {
log.error("When sending sessionId={} has error: {}", sessionId, msgResolver.resolve(sResult.getError()));
return sResult;
}
for (Registry registryA : forRegistries) {
if (!RegistryDesignation.A.equalsByKey(registryA.getRegistryUnit())) {
log.warn("For registry {}.RegistryDesignation is not A.", registryA.getId());
continue;
}
sResult = toReportMoney(sessionId, registryA);
if (sResult.getError() != null) {
log.warn("When sending sessionId={}, registry.id={} has error: {}", sessionId, registryA.getId(), msgResolver.resolve(sResult.getError()));
return sResult;
}
}
StageResult<Collection<Registry>> res = new StageResult<>(null, true);
return res;
}
/**
* формирование операционного отчета об обязательствах
**/
protected StageResult toReportSession(Long sessionId) {
ReportRequestWithSessionId reportSessionRequest = new ReportRequestWithSessionId();
reportSessionRequest.setSessionId(sessionId);
Long msgKey = kafkaSender.sendRequestToQueue(Consts.CREATE_REPORT_FOR_SESSION_ID, reportSessionRequest);
if (msgKey == null) {
log.error("failed to put Report Session request to kafka queue");
return new StageResult<>(new EnumMessage(SessionGeneralError), false);
}
return new StageResult<>(null, true);
}
/**
* формирование операционного отчета о денежных средствах
**/
protected StageResult toReportMoney(Long sessionId, Registry registry) {
ReportRequestWithRegistryId reportMoneyRequest = new ReportRequestWithRegistryId();
reportMoneyRequest.setSessionId(sessionId);
reportMoneyRequest.setRegistryId(registry.getId());
Long msgKey = kafkaSender.sendRequestToQueue(Consts.CREATE_REPORT_FOR_REGISTRY, reportMoneyRequest);
if (msgKey == null) {
log.error("failed to put Report Registry request to kafka queue");
return new StageResult<>(new EnumMessage(SessionGeneralError), false);
}
return new StageResult<>(null, true);
}
}

View file

@ -0,0 +1,232 @@
package ru.spcex.clearing.session.stage.impl;
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.payment.PaymentInstruction;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
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.predicate.specific.RegistryCodeSqlBuilder;
import ru.spcex.platform.utils.enumeration.IEnumKey;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.enumeration.SimpleMessageResolver;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
@Service
public class FormingPaymentInstruction implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
//todo remove (set all in single method setImdg(provider -> setImdg1();setIdGenerator();...)
private ImdgProvider imdgProvider;
private ImdgId idGenerator;
private Imdg<Registry> registryImdg;
private Imdg<PaymentInstruction> paymentInstructionImdg;
private KafkaSender kafkaSender;
private final IMessageResolver msgResolver = new SimpleMessageResolver();
@Autowired
public FormingPaymentInstruction(ImdgProvider imdgProvider) {
this.imdgProvider = imdgProvider;
this.idGenerator = imdgProvider.getImdgIdGenerator();
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.paymentInstructionImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_PaymentInstruction, PaymentInstruction.class);
}
@Override
public StageResult submit(Task<?> task) {
switch (task.getTaskType()) {
case FormingPaymentInstruction -> {
return formingPaymentInstruction();
}
default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
}
}
private StageResult formingPaymentInstruction() {
RegistryTradingParams registryTradingParamsL = new RegistryTradingParams(RegistryDesignation.L,
RegistryInstrumentType.S, null, RegistryUnit.T);
RegistryTradingParams registryTradingParamsC = new RegistryTradingParams(RegistryDesignation.C,
RegistryInstrumentType.M, null, null);
RegistryCodeSqlBuilder registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParamsL, registryTradingParamsC);
String registryCodeCondition = registryCodeSqlBuilder.build();
Collection<Registry> obligations = registryImdg.getCollectionObjectsBySQL(registryCodeCondition);
List<Registry> obligationsByMoney = obligations.stream().filter(registry ->
new RegistryTradingParams(RegistryDesignation.L, RegistryInstrumentType.M, null, RegistryUnit.T).equalByRegistry(
IEnumKey.getEnumByKey(RegistryDesignation.class, registry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, registry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, registry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, registry.getRegistryUnit())))
.toList();
for (Registry obligationByMoney : obligationsByMoney) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
obligationByMoney.getTradingClearingRegistryId(), obligationByMoney.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
RegistryTradingParams registryTradingParamsF = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.M, null, RegistryUnit.F);
RegistryTradingParams registryTradingParamsT = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.M, null, RegistryUnit.T);
RegistryTradingParams registryTradingParamsB = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.M, null, RegistryUnit.B);
for (Registry relatedRegistry : relatedRegistries) {
if (registryTradingParamsF.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setBalance(relatedRegistry.getBalance().subtract(obligationByMoney.getBalance()));
} else if (registryTradingParamsT.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setSettledDebit(relatedRegistry.getSettledDebit().add(obligationByMoney.getBalance()));
} else if (registryTradingParamsB.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setBalance(relatedRegistry.getBalance().add(obligationByMoney.getBalance()));
}
registryImdg.update(relatedRegistry);
}
}
List<Registry> requirementsByIssue = obligations.stream().filter(registry ->
new RegistryTradingParams(RegistryDesignation.C, RegistryInstrumentType.S, null, RegistryUnit.T).equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, registry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, registry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, registry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, registry.getRegistryUnit())))
.toList();
for (Registry requirementByIssue : requirementsByIssue) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
requirementByIssue.getTradingClearingRegistryId(), requirementByIssue.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
RegistryTradingParams registryTradingParamsA = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.S, null, RegistryUnit.T);
for (Registry relatedRegistry : relatedRegistries) {
if (registryTradingParamsA.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setSettledDebit(relatedRegistry.getSettledDebit().add(requirementByIssue.getBalance()));
}
registryImdg.update(relatedRegistry);
}
}
List<Registry> requirementsByMoney = obligations.stream().filter(registry ->
new RegistryTradingParams(RegistryDesignation.C, RegistryInstrumentType.M, null, RegistryUnit.T).equalByRegistry(
IEnumKey.getEnumByKey(RegistryDesignation.class, registry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, registry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, registry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, registry.getRegistryUnit())))
.toList();
for (Registry requirementByMoney : requirementsByMoney) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
requirementByMoney.getTradingClearingRegistryId(), requirementByMoney.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
RegistryTradingParams registryTradingParamsA = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.M, null, RegistryUnit.T);
for (Registry relatedRegistry : relatedRegistries) {
if (registryTradingParamsA.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setSettledDebit(relatedRegistry.getSettledDebit().add(requirementByMoney.getBalance()));
}
registryImdg.update(relatedRegistry);
}
}
List<Registry> obligationsByIssue = obligations.stream().filter(registry ->
new RegistryTradingParams(RegistryDesignation.L, RegistryInstrumentType.S, null, RegistryUnit.T).equalByRegistry(
IEnumKey.getEnumByKey(RegistryDesignation.class, registry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, registry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, registry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, registry.getRegistryUnit())))
.toList();
for (Registry obligationByIssue : obligationsByIssue) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
obligationByIssue.getTradingClearingRegistryId(), obligationByIssue.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
RegistryTradingParams registryTradingParamsF = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.S, null, RegistryUnit.F);
RegistryTradingParams registryTradingParamsT = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.S, null, RegistryUnit.T);
RegistryTradingParams registryTradingParamsB = new RegistryTradingParams(RegistryDesignation.A,
RegistryInstrumentType.S, null, RegistryUnit.B);
for (Registry relatedRegistry : relatedRegistries) {
if (registryTradingParamsF.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setBalance(relatedRegistry.getBalance().subtract(obligationByIssue.getBalance()));
} else if (registryTradingParamsT.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setSettledDebit(relatedRegistry.getSettledDebit().add(obligationByIssue.getBalance()));
} else if (registryTradingParamsB.equalByRegistry(IEnumKey.getEnumByKey(RegistryDesignation.class, relatedRegistry.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, relatedRegistry.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, relatedRegistry.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, relatedRegistry.getRegistryUnit()))) {
relatedRegistry.setBalance(relatedRegistry.getBalance().add(obligationByIssue.getBalance()));
}
registryImdg.update(relatedRegistry);
}
}
for (Registry obligation : obligations) {
RegistryTradingParams registryTradingParamsLT = new RegistryTradingParams(RegistryDesignation.L,
null, null, RegistryUnit.T);
registryCodeCondition = RegistryCodeSqlBuilder.getInstance(registryTradingParamsLT).build();
String sqlCondition = String.format("(%s) and securityId = %s and tradingClearingRegistryId = %s and companyId = %s and counterPartyId = %s",
registryCodeCondition, obligation.getSecurityId(), obligation.getTradingClearingRegistryId(), obligation.getCompanyId(), obligation.getCounterPartyId());
Collection<Registry> registries = registryImdg.getCollectionObjectsBySQL(sqlCondition);
BigDecimal sumBalance = registries.stream().map(Registry::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
PaymentInstruction paymentInstruction = createPaymentInstruction(obligation, sumBalance);
paymentInstructionImdg.insert(paymentInstruction);
obligation.setPaymentId(paymentInstruction.getId());
registryImdg.update(obligation);
}
//todo send message to queue for forming sDf03 and sDf12?
return new StageResult(null, true);
}
private PaymentInstruction createPaymentInstruction(Registry registry, BigDecimal balance) {
PaymentInstruction paymentInstruction = new PaymentInstruction();
paymentInstruction.setSenderId(registry.getCompanyId());
paymentInstruction.setAddresseeId(registry.getCounterPartyId());
//todo add builder for paymentInstruction
return paymentInstruction;
}
}

View file

@ -9,7 +9,7 @@ import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.task.RegistryOnObligationsAndSettlementRequirementsPayload;
import ru.spcex.clearing.session.stage.task.FormingRegistersOnOSPayload;
import ru.spcex.clearing.session.stage.util.RegistryUtil;
import ru.spcex.platform.enumeration.RegistryDesignation;
import ru.spcex.platform.enumeration.RegistryInstrumentType;
@ -39,10 +39,10 @@ public class FormingRegistersOnOS implements ISessionStage {
@Override
public StageResult<?> submit(Task<?> task) {
RegistryOnObligationsAndSettlementRequirementsPayload payload = (RegistryOnObligationsAndSettlementRequirementsPayload) task.getData();
FormingRegistersOnOSPayload payload = (FormingRegistersOnOSPayload) task.getData();
switch (task.getTaskType()) {
case FormingRegistersOnOS -> {
return createRegistryOnObligationsAndSettlementRequirements(payload.getSessionId());
return createRegistryOnObligationsAndSettlementRequirements();
}
default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
@ -53,12 +53,10 @@ public class FormingRegistersOnOS implements ISessionStage {
/**
* Select Registry by: registryCode = [O/T][S/M][*][T] & registryStatus=OK
*
* @param sessionId
* @return
*/
protected Collection<Registry> selectRegistry(Long sessionId) {
String registrySQL = "sessionId = " + sessionId;
registrySQL += " and (registryDesignation=" + RegistryDesignation.O.getKey() + " or registryDesignation=" + RegistryDesignation.T.getKey() + ")";
protected Collection<Registry> selectRegistry() {
String registrySQL = "(registryDesignation=" + RegistryDesignation.O.getKey() + " or registryDesignation=" + RegistryDesignation.T.getKey() + ")";
registrySQL += " and (registryInstrumentType=" + RegistryInstrumentType.S.getKey() + " or registryInstrumentType=" + RegistryInstrumentType.M.getKey() + ")";
registrySQL += " and (registryUnit=" + RegistryUnit.T.getKey() + ")";
registrySQL += " and registryStatus=" + RegistryStatus.OK.getKey() + ")";
@ -67,8 +65,8 @@ public class FormingRegistersOnOS implements ISessionStage {
return result;
}
protected StageResult<?> createRegistryOnObligationsAndSettlementRequirements(Long sessionId) {
Collection<Registry> forRegistries = selectRegistry(sessionId);
protected StageResult<?> createRegistryOnObligationsAndSettlementRequirements() {
Collection<Registry> forRegistries = selectRegistry();
ArrayList<Registry> newRegistries = new ArrayList<>();
//todo oreder by обрабатываться группами по полю registry.groupId

View file

@ -67,7 +67,6 @@ public class InclusionObligations implements ISessionStage {
sessionType);
Collection<Registry> obligations = registryImdg.getCollectionObjectsBySQL(sqlCondition);
Map<Long, List<Registry>> registryByGroupId = obligations.stream().
filter(registry -> registry.getCompanyId().equals(counterPartyId)).
collect(Collectors.groupingBy(Registry::getGroupId));
for (Map.Entry<Long, List<Registry>> entrySet : registryByGroupId.entrySet()) {

View file

@ -51,7 +51,7 @@ public class InspectionObligations implements ISessionStage {
public StageResult submit(Task<?> task) {
InspectionPoolPayload payload = (InspectionPoolPayload) task.getData();
switch (task.getTaskType()) {
case InclusionToPool -> {
case InspectionObligations -> {
return inspectionPool(payload.getProcessedCompanyId());
}
default -> {

View file

@ -0,0 +1,79 @@
package ru.spcex.clearing.session.stage.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.TaskType;
import ru.spcex.platform.enumeration.RegistryStatus;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.utils.enumeration.EnumMessage;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.validation.IValidator;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class ObligationAdmission implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Imdg<Registry> registryImdg;
private final ImdgProvider imdgProvider;
private final Function<Registry, IValidator> validatorFactory;
private final IMessageResolver messageResolver;
@Autowired
public ObligationAdmission(ImdgProvider imdgProvider,
@Qualifier("obligationAndRequirementsAdmissionValidator") Function<Registry, IValidator> validatorFactory,
IMessageResolver messageResolver) {
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.imdgProvider = imdgProvider;
this.validatorFactory = validatorFactory;
this.messageResolver = messageResolver;
}
@SuppressWarnings("unchecked")
@Override
public StageResult<?> submit(Task<?> task) {
if (task.getTaskType() == TaskType.ObligationsAdmission) {
return obligationAdmission((Long) task.getData());
}
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
private StageResult<?> obligationAdmission(Long sessionId) {
Collection<Registry> registries = registryImdg.getCollectionObjectsBySQL("sessionId = " + sessionId);
Map<Long, List<Registry>> byGroups = registries.stream().collect(Collectors.groupingBy(Registry::getGroupId));
for (Map.Entry<Long, List<Registry>> grpEntry : byGroups.entrySet()) {
EnumMessage groupError = null;
List<Registry> rgsGroup = grpEntry.getValue();
for (Registry rgs : rgsGroup) {
IValidator validator = validatorFactory.apply(rgs);
Optional<EnumMessage> error = validator.tillFirstError();
if (error.isPresent()) {
groupError = error.get();
break;
}
}
if (groupError != null) {
log.warn("error {} for registries groupId = {}", messageResolver.resolve(groupError), grpEntry.getKey());
for (Registry rgs : rgsGroup) {
rgs.setRegistryStatus(RegistryStatus.NACK.getKey());
registryImdg.update(rgs);
}
}
}
return new StageResult<>(null, true);
}
}

View file

@ -0,0 +1,151 @@
package ru.spcex.clearing.session.stage.impl;
import ru.clearing.classes.statics.data.account.Account;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.execution.ExecutionCommon;
import ru.clearing.classes.statics.data.execution.ExecutionDeposit;
import ru.clearing.classes.statics.data.execution.ExecutionFond;
import ru.clearing.classes.statics.data.misc.Market;
import ru.clearing.classes.statics.data.misc.Session;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.registry.TradingClearingRegistry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.session.stage.util.RegistryUtil;
import ru.spcex.platform.classes.base.interfaces.ExecutionType;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class RegistryBuilder {
private Imdg<Company> companyImdg;
private Imdg<TradingClearingRegistry> tradingClearingRegistryImdg;
private Imdg<Account> accountImdg;
private Imdg<Market> marketImdg;
private Imdg<Session> sessionImdg;
private ExecutionCommon exec;
private RegistryDesignation regDsgn;
private RegistryBuilder() {
}
public static RegistryBuilder builder() {
return new RegistryBuilder();
}
public RegistryBuilder imdg(ImdgProvider imdgProvider) {
this.companyImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Company, Company.class);
this.tradingClearingRegistryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_TradingClearingRegistry, TradingClearingRegistry.class);
this.accountImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Account, Account.class);
this.marketImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Market, Market.class);
this.sessionImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Session, Session.class);
return this;
}
public RegistryBuilder exec(ExecutionCommon exec) {
this.exec = exec;
return this;
}
public RegistryBuilder registryDesignation(RegistryDesignation registryDesignation) {
this.regDsgn = registryDesignation;
return this;
}
public Registry build() {
ISide side = getSide(exec);
Registry reg = new Registry();
reg.setCompanyId(exec.getCompanyId());
Company company = searchCompany();
reg.setTradingCode(company.getTradingCode());
reg.setClearingCode(company.getClearingCode());
reg.setShortName(company.getShortName());
reg.setFullName(company.getFullName());
TradingClearingRegistry tcr = searchTradingClearingRegistry();
if ((regDsgn.equals(RegistryDesignation.O) && side.isBuy()) || (regDsgn.equals(RegistryDesignation.T) && side.isSell())) {
reg.setAccountId(tcr.getMoneyAccountId());
reg.setRegistryInstrumentType(RegistryInstrumentType.M.getKey());
reg.setBalanceDimension(BalanceDimension.MONY.getKey()); //fixme add second leg code branch
} else if ((regDsgn.equals(RegistryDesignation.T) && side.isBuy()) || (regDsgn.equals(RegistryDesignation.O) && side.isSell())) {
reg.setAccountId(tcr.getDepoAccountId());
reg.setRegistryInstrumentType(RegistryInstrumentType.S.getKey());
reg.setBalanceDimension(BalanceDimension.PICS.getKey()); //fixme add second leg code branch
}
Account account = accountImdg.getSingleObjectByID(reg.getAccountId());
reg.setAccountType(account.getAccountType());
reg.setAccount(account.getAccount());
reg.setRegistryDesignation(regDsgn.getKey());
reg.setRegistryCapacity(account.getAccountType());
reg.setRegistryUnit(RegistryUnit.T.getKey());
reg.setRegistryCode(RegistryUtil.clearingCode(reg));
reg.setTradingClearingRegistryId(exec.getTradingClearingRegistryId());
reg.setTradingClearingRegistry(tcr.getCode());
reg.setRegistryStatus(RegistryStatus.PROC.getKey());
reg.setSecurityId(exec.getSecurityId());
reg.setSecuritySymbol(exec.getSecuritySymbol());
switch (exec.type()) {
case ExecutionDeposit -> {
ExecutionDeposit execDep = (ExecutionDeposit) this.exec;
reg.setBalance((execDep).getFirstLegAmount());
if (regDsgn.equals(RegistryDesignation.T)) {
reg.setSettledCredit((execDep).getFirstLegAmount());
} else if (regDsgn.equals(RegistryDesignation.O)) {
reg.setSettledDebit((execDep).getFirstLegAmount());
}
reg.setSettlementDate(execDep.getFirstLegSettlementDate()); //fixme add second leg code branch
reg.setSettlementCode(execDep.getFirstLegSettlementCode()); //fixme add second leg code branch
reg.setRefundDate(execDep.getSecondLegSettlementDate()); //fixme add second leg code branch??
reg.setValueDate(execDep.getFirstLegSettlementDate());
reg.setContract(execDep.getContract());
}
case ExecutionFond -> {
ExecutionFond execFond = (ExecutionFond) this.exec;
reg.setBalance(execFond.getSettlementAmount());
reg.setSettlementDate(execFond.getSettlementDate());
reg.setSettlementCode(execFond.getSettlementCode());
}
}
reg.setTradingDate(exec.getTradingDate());
reg.setClearingDate(LocalDate.now());
reg.setPrice(exec.getPrice());
reg.setCounterPartyId(exec.getCounterPartyId());
reg.setGroupId(groupId());
reg.setSessionId(exec.getSessionId());
reg.setSessionType(sessionType());
return reg;
}
private static DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyyMMdd");
private Long groupId() {
LocalDate now = LocalDate.now();
Market market = marketImdg.getSingleObjectBySQL("code = '" + exec.getMarket() + "'");
return Long.valueOf(now.format(yyyyMMdd) + exec.getExchangeExecutionId() + market.getId());
}
//можно передать из стейджа
private String sessionType() {
Session session = sessionImdg.getSingleObjectByID(exec.getSessionId());
return session.getSessionType();
}
private Company searchCompany() {
return companyImdg.getSingleObjectBySQL("id = " + exec.getCompanyId());
}
private TradingClearingRegistry searchTradingClearingRegistry() {
return tradingClearingRegistryImdg.getSingleObjectBySQL("tradingClearingRegistryId = " + exec.getTradingClearingRegistryId());
}
private static ISide getSide(ExecutionCommon exec) {
if (exec.type().equals(ExecutionType.ExecutionDeposit)) {
return ISide.parse(MoneyFlowSide.class, exec.getSide());
} else if (exec.type().equals(ExecutionType.ExecutionFond)) {
return ISide.parse(Side.class, exec.getSide());
} else {
throw new RuntimeException("Unknown Execution type: " + exec.type());
}
}
}

View file

@ -0,0 +1,55 @@
package ru.spcex.clearing.session.stage.impl;
import ru.clearing.classes.statics.data.execution.ExecutionCommon;
import ru.clearing.classes.statics.data.execution.ExecutionDeposit;
import ru.clearing.classes.statics.data.execution.ExecutionFond;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.spcex.platform.classes.base.interfaces.ExecutionType;
import ru.spcex.platform.enumeration.RegistryDesignation;
import java.math.BigDecimal;
import java.time.Instant;
public class RegistryUpdater {
public static RegistryUpdater updater() {
return new RegistryUpdater();
}
private RegistryUpdater() {
}
private ExecutionCommon exec;
private Registry rgs;
public RegistryUpdater registry(Registry rgs) {
this.rgs = rgs;
return this;
}
public RegistryUpdater exec(ExecutionCommon exec) {
this.exec = exec;
return this;
}
public void update() {
if (exec.type().equals(ExecutionType.ExecutionDeposit)) {
rgs.setBalance(safe(rgs.getBalance()).add(safe(((ExecutionDeposit) exec).getFirstLegAmount())));
if (rgs.getRegistryDesignation().equals(RegistryDesignation.T.getKey())) {
rgs.setSettledCredit(safe(rgs.getSettledCredit()).add(safe(((ExecutionDeposit) exec).getFirstLegAmount())));
}
if (rgs.getRegistryDesignation().equals(RegistryDesignation.O.getKey())) {
rgs.setSettledDebit(safe(rgs.getSettledDebit()).add(safe(((ExecutionDeposit) exec).getFirstLegAmount())));
}
rgs.setValueDate(((ExecutionDeposit) exec).getFirstLegSettlementDate());
} else if (exec.type().equals(ExecutionType.ExecutionFond)) {
rgs.setBalance(safe(rgs.getBalance()).add(safe(((ExecutionFond) exec).getSettlementAmount())));
}
rgs.setUpdated(Instant.now());
}
private BigDecimal safe(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
}

View file

@ -0,0 +1,223 @@
package ru.spcex.clearing.session.stage.impl;
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.execution.ExecutionCommon;
import ru.clearing.classes.statics.data.execution.ExecutionDeposit;
import ru.clearing.classes.statics.data.execution.ExecutionFond;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.TaskType;
import ru.spcex.platform.classes.base.interfaces.ExecutionType;
import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicate;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicateBuilder;
import ru.spcex.platform.imdg.api.predicate.specific.RegistryCodeSqlBuilder;
import ru.spcex.platform.utils.collection.Pair;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
@Service
public class RequirementsAndObligationCreation implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Imdg<Registry> registryImdg;
private final ImdgProvider imdgProvider;
@Autowired
public RequirementsAndObligationCreation(ImdgProvider imdgProvider) {
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.imdgProvider = imdgProvider;
}
@SuppressWarnings("unchecked")
@Override
public StageResult<?> submit(Task<?> task) {
if (task.getTaskType() == TaskType.RequirementsAndObligationsCreate) {
return createRegisters((List<ExecutionCommon>) task.getData());
}
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
private StageResult<?> createRegisters(List<ExecutionCommon> data) {
if (data.size() % 2 != 0) {
throw new IllegalStateException("Data size must be even (executions must match)");
}
//см. описание к #matchExecutions
for (int i = 0; i < data.size(); ) {
Pair<ExecutionCommon, ExecutionCommon> matched = matchExecutions(data, i);
if (matched == null) {
log.error("couldn't find match execution for id = {}", data.get(i).getId());
i += 1;
continue;
}
i += 2;
ExecutionCommon partyExec = matched.getFirst();
ExecutionCommon counterExec = matched.getSecond();
//бывает поиск обычный, бывает по ExecutionDeposit.secondLegSettlementDt
AtomicReference<BiFunction<ExecutionCommon, RegistryDesignation, Optional<Registry>>> regSearchMethod = new AtomicReference<>();
//обычный поиск
regSearchMethod.set(this::findReg);
BiConsumer<ExecutionCommon, RegistryDesignation> findAndUpdateOrCreate = (exec, regDsgn) ->
regSearchMethod.get().apply(exec, regDsgn)
.ifPresentOrElse(registry -> {
RegistryUpdater.updater()
.exec(partyExec)
.registry(registry)
.update();
registryImdg.update(registry);
}, () -> {
Registry newRegister = RegistryBuilder.builder()
.imdg(imdgProvider)
.exec(partyExec)
.registryDesignation(regDsgn)
.build();
registryImdg.insert(newRegister);
});
findAndUpdateOrCreate.accept(partyExec, RegistryDesignation.O);
findAndUpdateOrCreate.accept(partyExec, RegistryDesignation.T);
findAndUpdateOrCreate.accept(counterExec, RegistryDesignation.O);
findAndUpdateOrCreate.accept(counterExec, RegistryDesignation.T);
if (partyExec.type().equals(ExecutionType.ExecutionDeposit) && ((ExecutionDeposit) partyExec).getSecondLegSettlementDate() != null) {
//поиск по дате расчетов ExecutionDeposit.secondLegSettlementDt
regSearchMethod.set(this::findRegBySettlementDt);
findAndUpdateOrCreate.accept(partyExec, RegistryDesignation.T);
findAndUpdateOrCreate.accept(partyExec, RegistryDesignation.O);
findAndUpdateOrCreate.accept(counterExec, RegistryDesignation.T);
findAndUpdateOrCreate.accept(counterExec, RegistryDesignation.O);
}
}
return new StageResult<>(null, true);
}
private Optional<Registry> findReg(ExecutionCommon exec, RegistryDesignation des) {
ISide side = getSide(exec);
RegistryTradingParams p;
if (side.isBuy() && des.equals(RegistryDesignation.O)) {
p = new RegistryTradingParams(
RegistryDesignation.O, RegistryInstrumentType.M, null, RegistryUnit.T
);
} else if (side.isBuy() && des.equals(RegistryDesignation.T)) {
p = new RegistryTradingParams(
RegistryDesignation.T, RegistryInstrumentType.S, null, RegistryUnit.T
);
} else if (side.isSell() && des.equals(RegistryDesignation.O)) {
p = new RegistryTradingParams(
RegistryDesignation.O, RegistryInstrumentType.S, null, RegistryUnit.T
);
} else if (side.isSell() && des.equals(RegistryDesignation.T)) {
p = new RegistryTradingParams(
RegistryDesignation.T, RegistryInstrumentType.M, null, RegistryUnit.T
);
} else {
throw new IllegalStateException("cannot construct for " + des + " " + side);
}
return imdgRegSearch(p, exec.getTradingClearingRegistryId(), exec.getCompanyId(), settlementDt(exec));
}
private Optional<Registry> findRegBySettlementDt(ExecutionCommon exec, RegistryDesignation des) {
if (!exec.type().equals(ExecutionType.ExecutionDeposit) || ((ExecutionDeposit) exec).getSecondLegSettlementDate() == null)
throw new IllegalStateException("cannot searchSettlementDt for " + exec.type());
ISide side = getSide(exec);
RegistryTradingParams p;
if (side.isBuy() && des.equals(RegistryDesignation.T)) {
p = new RegistryTradingParams(
RegistryDesignation.T, RegistryInstrumentType.M, RegistryCapacity.A, RegistryUnit.T
);
} else if (side.isBuy() && des.equals(RegistryDesignation.O)) {
p = new RegistryTradingParams(
RegistryDesignation.O, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.T
);
} else if (side.isSell() && des.equals(RegistryDesignation.O)) {
p = new RegistryTradingParams(
RegistryDesignation.O, RegistryInstrumentType.M, RegistryCapacity.A, RegistryUnit.T
);
} else if (side.isSell() && des.equals(RegistryDesignation.T)) {
p = new RegistryTradingParams(
RegistryDesignation.T, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.T
);
} else {
throw new IllegalStateException("cannot construct by settleDt for " + des + " " + side);
}
return imdgRegSearch(p, exec.getTradingClearingRegistryId(), exec.getCompanyId(), ((ExecutionDeposit) exec).getSecondLegSettlementDate());
}
public Optional<Registry> imdgRegSearch(RegistryTradingParams p, Long tcrId, Long companyId, LocalDate settlementDt) {
String sql = RegistryCodeSqlBuilder.getInstance(p).build();
ImdgPredicateBuilder pb = registryImdg.predicateBuilder();
ImdgPredicate rgstrPredicate = pb.and(pb.sql(sql),
pb.equals("tradingClearingRegistryId", tcrId),
pb.equals("companyId", companyId),
pb.equals("settlementDate", settlementDt)
);
return Optional.ofNullable(registryImdg.getSingleObjectByPredicate(rgstrPredicate));
}
private LocalDate settlementDt(ExecutionCommon exec) {
if (exec.type().equals(ExecutionType.ExecutionDeposit)) {
return ((ExecutionDeposit) exec).getFirstLegSettlementDate();
} else if (exec.type().equals(ExecutionType.ExecutionFond)) {
return ((ExecutionFond) exec).getSettlementDate();
} else {
throw new RuntimeException("Unknown Execution type: " + exec.type());
}
}
/**
* входные данные отсортированы по exchangeExecutionId.
* сортировка выполнена на предыдущем шаге. (такое описание шагов в ТЗ)
* по идее, Execution с одинаковым exchangeExecutionId должно быть всего два.
* если это не так, передалать на коллекцию Long executionId в правильном порядке
* и для каждого искать мэтч отдельно в Imdg, с сохранением уже обработанных для избежания дублирования
*/
private Pair<ExecutionCommon, ExecutionCommon> matchExecutions(List<ExecutionCommon> data, int i) {
//if the last execution, then no match
if (i >= data.size() - 1) {
return null;
}
ExecutionCommon exec1 = data.get(i);
ExecutionCommon exec2 = data.get(i + 1);
//Встречная сделка контрагента выбирается из executionDeposit/Fond по условию:
//exchangeExecutionId=currentExecutionDeposit/Fond.exchangeExecutionId
//и [side=SELL (если currentExecutionDeposit/Fond.side=BUY) или side=BUY (если currentExecutionDeposit/Fond.side=SELL) по справочнику moneyFlowSide или справочнику side в зависимости от секции обрабатываемой сделки]
//и companyId=currentExecutionDeposit/Fond.counterPartyId
boolean valid = true;
if (!Objects.equals(exec1.getExchangeExecutionId(), exec2.getExchangeExecutionId())) {
valid = false;
} else if (Objects.equals(getSide(exec1), getSide(exec2))) {
valid = false;
} else if (!Objects.equals(exec1.getCounterPartyId(), exec2.getCounterPartyId())) {
valid = false;
}
if (!valid) {
log.error("FATAL skipping ExchangeExecutionId: {}", exec1.getId());
}
return new Pair<>(exec1, exec2);
}
private static ISide getSide(ExecutionCommon exec) {
if (exec.type().equals(ExecutionType.ExecutionDeposit)) {
return ISide.parse(MoneyFlowSide.class, exec.getSide());
} else if (exec.type().equals(ExecutionType.ExecutionFond)) {
return ISide.parse(Side.class, exec.getSide());
} else {
throw new RuntimeException("Unknown Execution type: " + exec.type());
}
}
}

View file

@ -15,6 +15,7 @@ import ru.spcex.platform.enumeration.RegistryInstrumentType;
import ru.spcex.platform.enumeration.RegistryUnit;
import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.api.ImdgTransaction;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicate;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicateBuilder;
@ -26,10 +27,12 @@ import java.util.Collection;
public class UnlockResources implements ISessionStage {
private final Logger log = LoggerFactory.getLogger(getClass());
protected final ImdgProvider imdgProvider;
private final Imdg<Registry> registryImdg;
@Autowired
public UnlockResources(ImdgProvider imdgProvider) {
this.imdgProvider = imdgProvider;
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
}
@ -39,7 +42,7 @@ public class UnlockResources implements ISessionStage {
switch (task.getTaskType()) {
case UnlockResources -> {
UnlockResourcesPayload payload = (UnlockResourcesPayload) task.getData();
return unlockResources(payload.getSdfMode(), payload.getSessionId(),
return unlockResources(payload.getSdfMode(),
payload.getAccount(),
payload.getSecurityId(),
payload.getFullNames(),
@ -52,26 +55,18 @@ public class UnlockResources implements ISessionStage {
}
}
/**
* Select Registry by: account; fullName* / securityId
*/
protected Collection<Registry> selectRegistry(Long sessionId, String account, Long securityId, Collection<String> fullNames) {
protected Collection<Registry> selectRegistryForSDF04(String account, Collection<String> fullNames) {
ImdgPredicateBuilder pb = registryImdg.predicateBuilder();
ImdgPredicate queryPart;
if (securityId != null) {
queryPart = pb.in("securityId", securityId);
} else if (fullNames != null && !fullNames.isEmpty()) {
queryPart = pb.in("fullName", fullNames.toArray(new String[fullNames.size()]));
} else {
throw new IllegalArgumentException("Required securityId or fullNames");
}
ImdgPredicate query = pb.and(
pb.and(
pb.equals("sessionId", sessionId),
pb.equals("registryDesignation", RegistryDesignation.A.getKey()) // не все нужны, только с этим кодом отфильтруем.
pb.equals("registryDesignation", RegistryDesignation.A.getKey()),
pb.equals("registryInstrumentType", RegistryInstrumentType.M.getKey()),
// pb.equals("registryCapacity", *),
pb.or(pb.equals("registryUnit", RegistryUnit.F.getKey()),
pb.equals("registryUnit", RegistryUnit.B.getKey()))
),
pb.equals("account", account),
queryPart
pb.in("fullName", fullNames.toArray(new String[fullNames.size()]))
);
Collection<Registry> result = registryImdg.getCollectionObjectsByPredicate(query);
@ -79,50 +74,74 @@ public class UnlockResources implements ISessionStage {
return result;
}
/**
* Select Registry by: account; fullName* / securityId
*/
protected Collection<Registry> selectRegistryForSDF12(String account, Long securityId) {
ImdgPredicateBuilder pb = registryImdg.predicateBuilder();
ImdgPredicate query = pb.and(
pb.and(
pb.equals("registryDesignation", RegistryDesignation.A.getKey()),
pb.equals("registryInstrumentType", RegistryInstrumentType.S.getKey()),
// pb.equals("registryCapacity", *),
pb.or(pb.equals("registryUnit", RegistryUnit.F.getKey()),
pb.equals("registryUnit", RegistryUnit.B.getKey()))
),
pb.equals("account", account),
pb.in("securityId", securityId)
);
Collection<Registry> result = registryImdg.getCollectionObjectsByPredicate(query);
log.trace("Selected {} registry's by sql: {}", result.size(), query);
return result;
}
/**
* @param sdfMode UnlockResourcesPayload.sdfMode
* @param sessionId
* @param account
* @param securityId
* @param fullNames
* @return
*/
protected StageResult<?> unlockResources(String sdfMode, Long sessionId, String account, Long securityId, Collection<String> fullNames, BigDecimal value) {
Collection<Registry> forRegistries = selectRegistry(sessionId, account, securityId, fullNames);
protected StageResult<?> unlockResources(String sdfMode, String account, Long securityId, Collection<String> fullNames, BigDecimal value) {
Collection<Registry> forRegistries;
//todo при перезапуске после незапланированного завершения стадии: надо ли проверять уже созданные регистры и не создавать дубликаты?
if (UnlockResourcesPayload.MODE_SDF04.equals(sdfMode)) {
forRegistries = forRegistries.stream().filter(
(Registry r) ->
RegistryDesignation.A.equalsByKey(r.getRegistryDesignation())
&&
RegistryInstrumentType.M.equalsByKey(r.getRegistryInstrumentType())
&&
(RegistryUnit.F.equalsByKey(r.getRegistryUnit()) || RegistryUnit.B.equalsByKey(r.getRegistryUnit()))
).toList();
forRegistries = selectRegistryForSDF04(account, fullNames);
} else if (UnlockResourcesPayload.MODE_SDF12.equals(sdfMode)) {
forRegistries = forRegistries.stream().filter(
(Registry r) ->
RegistryDesignation.A.equalsByKey(r.getRegistryDesignation())
&&
RegistryInstrumentType.S.equalsByKey(r.getRegistryInstrumentType())
&&
(RegistryUnit.F.equalsByKey(r.getRegistryUnit()) || RegistryUnit.B.equalsByKey(r.getRegistryUnit()))
).toList();
forRegistries = selectRegistryForSDF12(account, securityId);
} else {
throw new IllegalArgumentException("Mode not support: " + sdfMode);
}
for (Registry registry : forRegistries) {
boolean modified = unlockRegistry(registry, value);
if (modified) {
registry.setUpdated(Instant.now());
registryImdg.update(registry);
log.trace("Registry {} changed; value +- registry",
registry.getId(), registry.getRegistryCode(), value);
ImdgTransaction tx = imdgProvider.newTransaction();
boolean txOk = false;
try {
log.debug("Processing transaction {}, input {} registers.", tx, forRegistries.size());
Imdg<Registry> registryTxImdg = tx.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
int nUpdates = 0;
for (Registry registry : forRegistries) {
boolean modified = unlockRegistry(registry, value);
if (modified) {
registry.setUpdated(Instant.now());
registryTxImdg.update(registry);
nUpdates++;
log.trace("Registry {} (registryCode={}) changed; value +- {}",
registry.getId(), registry.getRegistryCode(), value);
}
}
log.info("Updated {} registry's (under transaction {}", nUpdates, tx);
txOk = true;
} finally {
if (txOk) {
log.debug("Commit transaction {}.", tx);
tx.commitTransaction();
} else {
log.info("Rollback transaction {}", tx);
tx.rollbackTransaction();
}
}
//todo рекомендуется делать транзакцией.
StageResult<Collection<Registry>> res = new StageResult<>(null, true);
res.setStageResult(forRegistries);

View file

@ -0,0 +1,13 @@
package ru.spcex.clearing.session.stage.task;
public class EndStageNotificationPayload {
private String section;
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}

View file

@ -0,0 +1,13 @@
package ru.spcex.clearing.session.stage.task;
public class FinishingSessionPayload {
private Long sessionId;
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
}

View file

@ -0,0 +1,5 @@
package ru.spcex.clearing.session.stage.task;
public class FormingRegistersOnOSPayload {
}

View file

@ -1,31 +0,0 @@
package ru.spcex.clearing.session.stage.task;
public class RegistryOnObligationsAndSettlementRequirementsPayload {
private Long sessionId;
// private Long companyId;
// private Long securityId;
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
// public Long getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(Long companyId) {
// this.companyId = companyId;
// }
//
// public Long getSecurityId() {
// return securityId;
// }
//
// public void setSecurityId(Long securityId) {
// this.securityId = securityId;
// }
}

View file

@ -12,8 +12,6 @@ public class UnlockResourcesPayload {
*/
private String sdfMode;
private Long sessionId;
/**
* sDf04.c_acc_cred
* sDf12.depoCodeSender
@ -46,13 +44,6 @@ public class UnlockResourcesPayload {
}
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
public String getAccount() {
return account;

View file

@ -0,0 +1,54 @@
package ru.spcex.clearing.service.builder.sql;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import ru.spcex.clearing.models.RegistryTradingParams;
import ru.spcex.platform.enumeration.RegistryCapacity;
import ru.spcex.platform.enumeration.RegistryDesignation;
import ru.spcex.platform.enumeration.RegistryInstrumentType;
import ru.spcex.platform.enumeration.RegistryUnit;
public class RegistryCodeSqlBuilderTest {
@Test
public void testBuildByOneObject() {
RegistryTradingParams registryTradingParams = new RegistryTradingParams(RegistryDesignation.C, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.R);
RegistryCodeSqlBuilder registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams);
String sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryDesignation = 'C' and registryInstrumentType = 'M' and registryCapacity = 'B' and registryUnit = 'R')", sql);
registryTradingParams = new RegistryTradingParams(null, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.R);
registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams);
sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryInstrumentType = 'M' and registryCapacity = 'B' and registryUnit = 'R')", sql);
registryTradingParams = new RegistryTradingParams(RegistryDesignation.C, null, null, RegistryUnit.R);
registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams);
sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryDesignation = 'C' and registryUnit = 'R')", sql);
}
@Test
public void testBuildByFewObjects() {
RegistryTradingParams registryTradingParams_first = new RegistryTradingParams(RegistryDesignation.C, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.R);
RegistryTradingParams registryTradingParams_second = new RegistryTradingParams(RegistryDesignation.O, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.F);
RegistryCodeSqlBuilder registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams_first, registryTradingParams_second);
String sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryDesignation = 'C' and registryInstrumentType = 'M' and registryCapacity = 'B' and registryUnit = 'R')" +
" or (registryDesignation = 'O' and registryInstrumentType = 'S' and registryCapacity = 'A' and registryUnit = 'F')", sql);
registryTradingParams_first = new RegistryTradingParams(null, RegistryInstrumentType.M, RegistryCapacity.B, RegistryUnit.R);
registryTradingParams_second = new RegistryTradingParams(null, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.F);
registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams_first, registryTradingParams_second);
sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryInstrumentType = 'M' and registryCapacity = 'B' and registryUnit = 'R') or " +
"(registryInstrumentType = 'S' and registryCapacity = 'A' and registryUnit = 'F')", sql);
registryTradingParams_first = new RegistryTradingParams(RegistryDesignation.C, null, null, RegistryUnit.R);
registryTradingParams_second = new RegistryTradingParams(null, RegistryInstrumentType.S, RegistryCapacity.A, RegistryUnit.F);
registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(registryTradingParams_first, registryTradingParams_second);
sql = registryCodeSqlBuilder.build();
Assertions.assertEquals("(registryDesignation = 'C' and registryUnit = 'R') or " +
"(registryInstrumentType = 'S' and registryCapacity = 'A' and registryUnit = 'F')", sql);
}
}

View file

@ -65,6 +65,7 @@ public record FieldRequiredRule<R, V>(
}
@Override
// todo replace for error fieldName to fieldValue
public Optional<EnumMessage> validate(ImdgValidationContext<R> context) {
R validatedObject = context.getValidatedObject();
V value = getter.apply(validatedObject);

View file

@ -23,11 +23,15 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-sftp</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- DBF files -->
@ -49,6 +53,21 @@
<groupId>ru.spcex.clearing</groupId>
<artifactId>classes</artifactId>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>classes</artifactId>
</dependency>
<!-- TEST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ru.spcex.clearing</groupId>
<artifactId>test-clearing</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View file

@ -1,80 +1,11 @@
package ru.spcex.clearing.dbf.exporter.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import ru.spcex.clearing.dbf.exporter.logic.stages.ExportFromHazelcast;
import ru.spcex.clearing.dbf.exporter.logic.stages.PrepareDBFFile;
import ru.spcex.clearing.dbf.exporter.logic.stages.Stage;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
import java.util.LinkedList;
import java.util.List;
@Configuration
@EnableConfigurationProperties
@ComponentScan(basePackages = {"ru.spcex.clearing.dbf.exporter"})
public class DBFExporterConfig {
@Bean("taskExecutorHazelcastClientInitializer")
public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() {
return createThreadPoolTaskExecutor(1, true);
}
@Bean("taskExecutorIdGeneratorAwaiter")
public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() {
return createThreadPoolTaskExecutor(1, false);
}
@Bean("imdgProvider")
public ImdgProvider imdgProvider(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer,
@Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter,
ExportDBFServiceSettings settings) {
HazelcastClientParams params = new HazelcastClientParams();
params.setClusterMembers(settings.getHazelcast().getClusterMembers());
params.setLogin(settings.getHazelcast().getLogin());
params.setPassword(settings.getHazelcast().getPassword());
return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params);
}
@Bean("pipeline")
public List<Stage> pipeline(ApplicationContext context) {
List<Stage> pipeline = new LinkedList<>();
pipeline.add(context.getBean(PrepareDBFFile.class));
pipeline.add(context.getBean(ExportFromHazelcast.class));
return pipeline;
}
@Bean("executor")
public ThreadPoolTaskExecutor executor(ExportDBFServiceSettings settings) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(settings.getCommon().getThreadsCount());
executor.setCorePoolSize(settings.getCommon().getThreadsCount());
executor.setThreadNamePrefix("dbf-exporter");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(300);
executor.initialize();
return executor;
}
private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
if (maxPoolSz > 2) {
pool.setKeepAliveSeconds(60);
pool.setAllowCoreThreadTimeOut(true);
}
pool.setCorePoolSize(maxPoolSz);
pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion);
return pool;
}
}

View file

@ -0,0 +1,63 @@
package ru.spcex.clearing.dbf.exporter.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import ru.spcex.platform.imdg.api.ImdgProvider;
import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@Configuration
@EnableConfigurationProperties
@ComponentScan(basePackages = {"ru.spcex.clearing.dbf.exporter"})
public class ImdgConfig {
@Bean("taskExecutorHazelcastClientInitializer")
public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() {
return createThreadPoolTaskExecutor(1, true);
}
@Bean("taskExecutorIdGeneratorAwaiter")
public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() {
return createThreadPoolTaskExecutor(1, false);
}
@Bean("imdgProvider")
public ImdgProvider imdgProvider(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer,
@Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter,
ExportDBFServiceSettings settings) {
HazelcastClientParams params = new HazelcastClientParams();
params.setClusterMembers(settings.getHazelcast().getClusterMembers());
params.setLogin(settings.getHazelcast().getLogin());
params.setPassword(settings.getHazelcast().getPassword());
return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params);
}
@Bean("executor")
public ThreadPoolTaskExecutor executor(ExportDBFServiceSettings settings) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(settings.getCommon().getThreadsCount());
executor.setCorePoolSize(settings.getCommon().getThreadsCount());
executor.setThreadNamePrefix("dbf-exporter");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(300);
executor.initialize();
return executor;
}
private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
if (maxPoolSz > 2) {
pool.setKeepAliveSeconds(60);
pool.setAllowCoreThreadTimeOut(true);
}
pool.setCorePoolSize(maxPoolSz);
pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion);
return pool;
}
}

View file

@ -17,6 +17,8 @@ import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgId;
import ru.spcex.platform.imdg.api.ImdgProvider;
import java.util.function.Supplier;
//отдельный конфиг для sender чтобы сделать required false
@Configuration
public class KafkaSenderConfig {
@ -38,7 +40,6 @@ public class KafkaSenderConfig {
return KafkaProducerFactory.producerFactory(kafkaSettings);
}
@Autowired(required = false)
@Bean("kafkaTemplate")
public KafkaTemplate<String, Object> kafkaTemplate(ProducerFactory<String, Object> pf) {
if (pf == null) {
@ -47,16 +48,11 @@ public class KafkaSenderConfig {
return new KafkaTemplate<>(pf);
}
@Autowired(required = false)
@Bean
public KafkaSender kafkaSender(KafkaTemplate<String, Object> kafkaTemplate,
ImdgProvider imdgProvider) {
if (kafkaTemplate == null) {
log.info("Can not create KafkaSender: no kafka-producer settings");
return null;
}
public Supplier<KafkaSender> kafkaSenderSupplier(KafkaTemplate<String, Object> kafkaTemplate,
ImdgProvider imdgProvider) {
ImdgId imdgIdGenerator = imdgProvider.getImdgIdGenerator();
return KafkaSender
return () -> KafkaSender
.setup()
.setKafkaTemplate(kafkaTemplate)
.idGenerator(imdgIdGenerator::nextId)

View file

@ -0,0 +1,26 @@
package ru.spcex.clearing.dbf.exporter.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.spcex.clearing.dbf.exporter.logic.stages.ExportFromHazelcast;
import ru.spcex.clearing.dbf.exporter.logic.stages.Journal;
import ru.spcex.clearing.dbf.exporter.logic.stages.PrepareDBFFile;
import ru.spcex.clearing.dbf.exporter.logic.stages.Stage;
import java.util.LinkedList;
import java.util.List;
@Configuration
public class PipelineConfig {
@Bean("pipeline")
public List<Stage> pipeline(ApplicationContext context) {
List<Stage> pipeline = new LinkedList<>();
pipeline.add(context.getBean(PrepareDBFFile.class));
pipeline.add(context.getBean(ExportFromHazelcast.class));
pipeline.add(context.getBean(Journal.class));
return pipeline;
}
}

View file

@ -0,0 +1,95 @@
package ru.spcex.clearing.dbf.exporter.config;
import com.jcraft.jsch.ChannelSftp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.sftp.gateway.SftpOutboundGateway;
import org.springframework.integration.sftp.outbound.SftpMessageHandler;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.integration.sftp.session.SftpFileInfo;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import java.io.File;
import java.util.List;
import static org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.Command.LS;
@Configuration
public class SFTPConfig {
@Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory(ExportDBFServiceSettings settings) {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost(settings.getStore().getServerIp());
factory.setPort(settings.getStore().getServerPort());
factory.setUser(settings.getStore().getUser());
factory.setPassword(settings.getStore().getPassword());
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<>(factory);
}
@Bean
@ServiceActivator(inputChannel = "toSftpChannel")
public MessageHandler handler(SessionFactory<ChannelSftp.LsEntry> sessionFactory, ExportDBFServiceSettings settings) {
SftpMessageHandler handler = new SftpMessageHandler(sessionFactory);
handler.setRemoteDirectoryExpression(new LiteralExpression(settings.getStore().getOutDir()));
handler.setAutoCreateDirectory(true);
handler.setFileNameGenerator(message -> {
if (message.getPayload() instanceof File) {
return ((File) message.getPayload()).getName();
}else {
throw new IllegalArgumentException("File must expected as payload.");
}
});
return handler;
}
@MessagingGateway
public interface DbfGateway {
@Gateway(requestChannel = "toSftpChannel")
void sendToSftp(File file);
@Gateway(requestChannel = "listSftpChannel")
List<SftpFileInfo> listFiles(String dir);
}
@Bean
public MessageChannel listSftpChannel(SessionFactory<ChannelSftp.LsEntry> sessionFactory, ExportDBFServiceSettings settings) {
DirectChannel dc = new DirectChannel();
dc.subscribe(handlerList(sessionFactory, settings));
return dc;
}
@Bean
public MessageChannel toSftpChannel(SessionFactory<ChannelSftp.LsEntry> sessionFactory, ExportDBFServiceSettings settings) {
DirectChannel dc = new DirectChannel();
dc.subscribe(handler(sessionFactory, settings));
return dc;
}
@Bean
@ServiceActivator(inputChannel = "listSftpChannel")
public MessageHandler handlerList(SessionFactory<ChannelSftp.LsEntry> sessionFactory, ExportDBFServiceSettings settings) {
String expression = "'/%s'".formatted(settings.getStore().getOutDir());
SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(sessionFactory, LS.getCommand(), expression);
return sftpOutboundGateway;
}
@Bean
public IntegrationFlow sftpOutboundListFlow(SessionFactory<ChannelSftp.LsEntry> sessionFactory, ExportDBFServiceSettings settings) {
return IntegrationFlows.from("listSftpChannel")
.handle(new SftpOutboundGateway(sessionFactory, "ls", "payload")
).get();
}
}

View file

@ -3,6 +3,43 @@ package ru.spcex.clearing.dbf.exporter.config.settings;
public class Store {
private String outDir;
private String localTempDir;
private String user;
private String password;
private String serverIp;
private int serverPort;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
public String getOutDir() {
return outDir;
@ -11,4 +48,12 @@ public class Store {
public void setOutDir(String outDir) {
this.outDir = outDir;
}
public String getLocalTempDir() {
return localTempDir;
}
public void setLocalTempDir(String localTempDir) {
this.localTempDir = localTempDir;
}
}

View file

@ -1,37 +0,0 @@
package ru.spcex.clearing.dbf.exporter.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import ru.spcex.clearing.dbf.exporter.services.DBFExportService;
@Controller("/")
public class ExporterController implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(getClass());
private final DBFExportService dbfExportService;
public ExporterController(@Qualifier("dbfExportService") DBFExportService dbfExportService) {
this.dbfExportService = dbfExportService;
}
@RequestMapping(method = RequestMethod.GET, path = "/export", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String exportTables() {
log.info("Call export method for exporter controller");
dbfExportService.run();
return "export done";
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("controller started");
}
}

View file

@ -4,6 +4,7 @@ import ru.spcex.clearing.dbf.exporter.logic.data.enums.StageResult;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import java.io.File;
import java.time.LocalDateTime;
import java.util.UUID;
/**
@ -15,6 +16,8 @@ public class ResultContainer {
private File fileForExport;
private Long groupId;
private StageResult lastStageResult;
private LocalDateTime registrationDateTime;
private String memberCode;
protected ResultContainer() {}
@ -64,4 +67,20 @@ public class ResultContainer {
public void setLastStageResult(StageResult lastStageResult) {
this.lastStageResult = lastStageResult;
}
public LocalDateTime getRegistrationDateTime() {
return registrationDateTime;
}
public void setRegistrationDateTime(LocalDateTime registrationDateTime) {
this.registrationDateTime = registrationDateTime;
}
public String getMemberCode() {
return memberCode;
}
public void setMemberCode(String memberCode) {
this.memberCode = memberCode;
}
}

View file

@ -0,0 +1,108 @@
package ru.spcex.clearing.dbf.exporter.logic.data.enums;
import org.springframework.integration.sftp.session.SftpFileInfo;
import ru.spcex.clearing.dbf.exporter.logic.data.ResultContainer;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import static ru.spcex.clearing.dbf.exporter.logic.stages.PrepareDBFFile.SECTION;
import static ru.spcex.clearing.dbf.exporter.logic.stages.PrepareDBFFile.outDir;
public enum FilenameTemplate {
df_section_dateTime {
@Override
public String getFileName(ResultContainer resultContainer, List<SftpFileInfo> files) {
return appendSection(resultContainer)
.append(dateTime(resultContainer))
.append(".DBF").toString();
}
},
df_section_dateTime_counter {
@Override
public String getFileName(ResultContainer resultContainer, List<SftpFileInfo> files) {
return appendSection(resultContainer)
.append(dateTime(resultContainer))
.append(counter(resultContainer, files))
.append(".DBF").toString();
}
},
df_section_dateTime_counter_mamberCode {
@Override
public String getFileName(ResultContainer resultContainer, List<SftpFileInfo> files) {
return appendSection(resultContainer)
.append(dateTime(resultContainer))
.append(counter(resultContainer, files))
.append(memberCode(resultContainer))
.append(".DBF").toString();
}
};
protected StringBuilder appendSection(ResultContainer resultContainer) {
StringBuilder result = new StringBuilder();
result.append(outDir);
result.append(File.separator);
result.append(resultContainer.getTableForExport().getFilePrefix().toUpperCase(Locale.ROOT));
result.append('_');
result.append(SECTION);
return result;
}
protected StringBuilder dateTime(ResultContainer resultContainer) {
StringBuilder result = new StringBuilder();
result.append('_');
result.append("PRC");
result.append(tsFormatter.format(resultContainer.getRegistrationDateTime()));
return result;
}
protected StringBuilder counter(ResultContainer resultContainer, List<SftpFileInfo> files) {
StringBuilder result = new StringBuilder();
result.append('_');
result.append(countSameFilesInDir(resultContainer.getTableForExport().getFilePrefix(), files) + 1);
return result;
}
protected StringBuilder memberCode(ResultContainer resultContainer) {
StringBuilder result = new StringBuilder();
result.append('_');
result.append(resultContainer.getMemberCode());
return result;
}
protected Integer countSameFilesInDir(String prefixOfTable, List<SftpFileInfo> files) {
int res = 0;
String timestampNow = utilFormatter.format(LocalDateTime.now());
for (SftpFileInfo file : files) {
if (file.isDirectory()) continue;
String name = file.getFilename();
String[] splitName = name.split("_");
if (splitName.length < 3)
throw new IllegalArgumentException("Filename did not contains 3 or 4 separator \"_\": " + name);
String prefix = splitName[0];
String timestamp = splitName[2];
if (prefix.equalsIgnoreCase(prefixOfTable) && timestamp.contains(timestampNow)) {
if (splitName.length < 4)
throw new IllegalArgumentException("Filename did not contains 4 separator \"_\": " + name);
String counter = splitName[3];
int positionOfDot = counter.indexOf('.');
if (positionOfDot != -1) {
counter = counter.substring(0, positionOfDot);
}
res = Integer.max(res, Integer.parseInt(counter));
}
}
return res;
}
private static final DateTimeFormatter tsFormatter = DateTimeFormatter.ofPattern("yyMMddHHmm");
private static final DateTimeFormatter utilFormatter = DateTimeFormatter.ofPattern("yyMMdd");
public String getFileName(ResultContainer resultContainer, List<SftpFileInfo> files) {
return null;
}
}

View file

@ -7,11 +7,13 @@ import ru.spcex.platform.classes.base.SpcexObjectBase;
public enum Table {
S_DF02("DF-02", IMDGDistributedNames.Map_SDf02, SDf02.class),
S_DF03("DF-03", IMDGDistributedNames.Map_SDf03, SDf03.class),
S_DF08("DF-08", IMDGDistributedNames.Map_SDf08, SDf08.class),
S_DF11("DF-11", IMDGDistributedNames.Map_SDf11, SDf11.class),
S_DF18("DF-18", IMDGDistributedNames.Map_SDf18, SDf18.class),
S_DF10("DF-10", IMDGDistributedNames.Map_SDf10, SDf10.class),
S_DF17("DF-17", IMDGDistributedNames.Map_SDf17, SDf17.class);
S_DF05("DF-05", IMDGDistributedNames.Map_SDf05, SDf05.class),
S_DF07("DF-07", IMDGDistributedNames.Map_SDf07, SDf07.class),
S_DF51("DF-51", IMDGDistributedNames.Map_SDf51, SDf51.class),
S_DF53("DF-53", IMDGDistributedNames.Map_SDf53, SDf53.class),
S_DF54("DF-54", IMDGDistributedNames.Map_SDf54, SDf54.class),
S_DF56("DF-56", IMDGDistributedNames.Map_SDf56, SDf56.class);
/**
* Префикс имени файла для экспорта

View file

@ -3,9 +3,9 @@ package ru.spcex.clearing.dbf.exporter.logic.stages;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFWriter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import ru.clearing.classes.statics.data.sdf.*;
import ru.spcex.clearing.dbf.exporter.config.SFTPConfig;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import ru.spcex.clearing.dbf.exporter.exceptions.ConfigException;
import ru.spcex.clearing.dbf.exporter.logic.data.ResultContainer;
@ -30,36 +30,42 @@ import java.util.Objects;
public class ExportFromHazelcast extends Stage implements InitializingBean {
private final ExportDBFServiceSettings settings;
private final ImdgProvider imdgProvider;
private final SFTPConfig.DbfGateway gateway;
private final S_DF02_Converter s_df02_converter;
private final S_DF03_Converter s_df03_converter;
private final S_DF08_Converter s_df08_converter;
private final S_DF11_Converter s_df11_converter;
private final S_DF18_Converter s_df18_converter;
private final S_DF10_Converter s_df10_converter;
private final S_DF17_Converter s_df17_converter;
private final S_DF05_Converter s_df05_converter;
private final S_DF07_Converter s_df07_converter;
private final S_DF51_Converter s_df51_converter;
private final S_DF53_Converter s_df53_converter;
private final S_DF54_Converter s_df54_converter;
private final S_DF56_Converter s_df56_converter;
private final Map<Table, DBFField[]> dbfFieldsForTable = new HashMap<>();
private Charset dbfCharset;
public ExportFromHazelcast(ExportDBFServiceSettings settings,
@Qualifier("imdgProvider") ImdgProvider imdgProvider,
ImdgProvider imdgProvider,
SFTPConfig.DbfGateway gateway,
S_DF02_Converter s_df02_converter,
S_DF03_Converter s_df03_converter,
S_DF08_Converter s_df08_converter,
S_DF11_Converter s_df11_converter,
S_DF18_Converter s_df18_converter,
S_DF10_Converter s_df10_converter,
S_DF17_Converter s_df17_converter) {
S_DF07_Converter s_df07_converter,
S_DF05_Converter s_df05_converter,
S_DF51_Converter s_df51_converter,
S_DF54_Converter s_df54_converter,
S_DF53_Converter s_df53_converter,
S_DF56_Converter s_df56_converter) {
this.settings = settings;
this.imdgProvider = imdgProvider;
this.gateway = gateway;
this.s_df02_converter = s_df02_converter;
this.s_df03_converter = s_df03_converter;
this.s_df08_converter = s_df08_converter;
this.s_df11_converter = s_df11_converter;
this.s_df18_converter = s_df18_converter;
this.s_df10_converter = s_df10_converter;
this.s_df17_converter = s_df17_converter;
this.s_df07_converter = s_df07_converter;
this.s_df05_converter = s_df05_converter;
this.s_df51_converter = s_df51_converter;
this.s_df54_converter = s_df54_converter;
this.s_df53_converter = s_df53_converter;
this.s_df56_converter = s_df56_converter;
}
@Override
@ -89,13 +95,15 @@ public class ExportFromHazelcast extends Stage implements InitializingBean {
Object[] values;
if (value instanceof SDf02 sDf02Value) values = s_df02_converter.toObjectArray(sDf02Value);
else if (value instanceof SDf03 sDf03Value) values = s_df03_converter.toObjectArray(sDf03Value);
else if (value instanceof SDf08 sDf08Value) values = s_df08_converter.toObjectArray(sDf08Value);
else if (value instanceof SDf11 sDf11Value) values = s_df11_converter.toObjectArray(sDf11Value);
else if (value instanceof SDf18 sDf18Value) values = s_df18_converter.toObjectArray(sDf18Value);
else if (value instanceof SDf10 sDf10Value) values = s_df10_converter.toObjectArray(sDf10Value);
else if (value instanceof SDf17 sDf17Value) values = s_df17_converter.toObjectArray(sDf17Value);
else if (value instanceof SDf05 sDf05Value) values = s_df05_converter.toObjectArray(sDf05Value);
else if (value instanceof SDf07 sDf07Value) values = s_df07_converter.toObjectArray(sDf07Value);
else if (value instanceof SDf51 sDf51Value) values = s_df51_converter.toObjectArray(sDf51Value);
else if (value instanceof SDf53 sDf53Value) values = s_df53_converter.toObjectArray(sDf53Value);
else if (value instanceof SDf54 sDf54Value) values = s_df54_converter.toObjectArray(sDf54Value);
else if (value instanceof SDf56 sDf56Value) values = s_df56_converter.toObjectArray(sDf56Value);
else throw new Exception("Get unknown object from imdg. Class: " + value.getClass().getSimpleName());
dbfWriter.addRecord(values);
gateway.sendToSftp(dbfFile);
}
writeOk = true;
emptyMap = tableRows.isEmpty();
@ -131,11 +139,12 @@ public class ExportFromHazelcast extends Stage implements InitializingBean {
private void initExportFileStructure() {
dbfFieldsForTable.put(Table.S_DF02, s_df02_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF03, s_df03_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF08, s_df08_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF18, s_df18_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF10, s_df10_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF11, s_df11_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF17, s_df17_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF05, s_df05_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF07, s_df07_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF51, s_df51_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF53, s_df53_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF54, s_df54_converter.getDBFHeaders());
dbfFieldsForTable.put(Table.S_DF56, s_df56_converter.getDBFHeaders());
}
private void initDBFCharset() {

View file

@ -11,25 +11,25 @@ import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import ru.spcex.clearing.platform.messaging.domain.cud.system.JournalSdf;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import java.time.LocalDate;
import java.time.LocalTime;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Supplier;
import static ru.spcex.clearing.platform.messaging.domain.Consts.EXPORT_COMPLETED;
@Component
public class Journal extends Stage implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(getClass());
private final KafkaSender kafkaSender;
private final Supplier<KafkaSender> kafkaSender;
@Autowired(required = false)
public Journal(KafkaSender kafkaSender) {
@Autowired
public Journal(Supplier<KafkaSender> kafkaSender) {
this.kafkaSender = kafkaSender;
}
public Journal() {
this.kafkaSender = null;
}
@Override
public boolean skipCompleted() {
return false;
@ -43,13 +43,21 @@ public class Journal extends Stage implements InitializingBean {
}
JournalSdf journalSdf = new JournalSdf();
//todo read file attibutes
journalSdf.setRegistrationDate(LocalDate.now());
journalSdf.setRegistrationTime(LocalTime.now());
journalSdf.setRegistrationDate(resultContainer.getRegistrationDateTime().toLocalDate());
journalSdf.setRegistrationTime(resultContainer.getRegistrationDateTime().toLocalTime());
journalSdf.setRegistrationNumber(resultContainer.getGroupId());
journalSdf.setDocumentName(documentNames.get(resultContainer.getTableForExport()));
journalSdf.setDossierNumber(dossierNumber.get(resultContainer.getTableForExport()));
journalSdf.setResultStatus(StageResult.ERROR.equals(resultContainer.getLastStageResult()) ? "NACK" : "ACK");
// kafkaSender.sendRequestToQueue();
kafkaSender.get().sendRequestToQueue(EXPORT_COMPLETED, journalSdf);
//удалим временный файл
File dbfFile = resultContainer.getFileForExport();
try {
Files.deleteIfExists(dbfFile.toPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
return StageResult.COMPLETE;
}
@ -61,23 +69,23 @@ public class Journal extends Stage implements InitializingBean {
static {
documentNames.put(Table.S_DF02, "Уведомлений об исполнении операции загрузки денежных средств или уведомление об ошибке");
documentNames.put(Table.S_DF03, "Сводное платёжное поручение по итогу проведения расчетов, направляемое в РО");
//documentNames.put(Table.S_DF05, "Уведомление о завершении расчетов в секции");
documentNames.put(Table.S_DF08, "Запрос остатков по всем счетам, направляемый в РО");
documentNames.put(Table.S_DF10, "Подтверждение о загрузке по поступлению на клиринговый счет");
documentNames.put(Table.S_DF11, "Распоряжение на списание с ТБС УК на Клиринговый счет (по итогам проведения расчетов по возврату депозита) / Распоряжение на списание с ТБС УК на Корреспонденский счет УК");
//documentNames.put(Table.S_DF13, "Распоряжение на списание денежных средств УК категории В (с клирингового счета)");
documentNames.put(Table.S_DF17, "Подтверждение о загрузке Уведомления о возврате ден.ср. по договору депозита");
documentNames.put(Table.S_DF05, "Уведомление о завершении расчетов в секции");
documentNames.put(Table.S_DF07, "Подтверждение о загрузке Уведомления о возврате ден.ср. по договору депозита");
documentNames.put(Table.S_DF51, "Запрос остатков по всем счетам, направляемый в РО");
documentNames.put(Table.S_DF53, "");
documentNames.put(Table.S_DF54, "Распоряжение на списание денежных средств УК категории В (с клирингового счета)");
documentNames.put(Table.S_DF56, "");
}
private static final Map<Table, String> dossierNumber = new EnumMap<>(Table.class);
static {
dossierNumber.put(Table.S_DF02, "07-50");
dossierNumber.put(Table.S_DF03, "07-51");
//dossierNumber.put(Table.S_DF05, "07-53");
dossierNumber.put(Table.S_DF08, "07-55");
dossierNumber.put(Table.S_DF10, "07-56");
dossierNumber.put(Table.S_DF11, "07-36");
//dossierNumber.put(Table.S_DF13, "07-48");
dossierNumber.put(Table.S_DF17, "07-58");
dossierNumber.put(Table.S_DF05, "07-53");
dossierNumber.put(Table.S_DF07, "07-58");
dossierNumber.put(Table.S_DF51, "07-55");
dossierNumber.put(Table.S_DF53, "");
dossierNumber.put(Table.S_DF54, "07-48");
dossierNumber.put(Table.S_DF56, "");
}
}

View file

@ -1,9 +1,12 @@
package ru.spcex.clearing.dbf.exporter.logic.stages;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.sftp.session.SftpFileInfo;
import org.springframework.stereotype.Component;
import ru.spcex.clearing.dbf.exporter.config.SFTPConfig;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import ru.spcex.clearing.dbf.exporter.logic.data.ResultContainer;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.FilenameTemplate;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.StageResult;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
@ -12,8 +15,9 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
@ -21,23 +25,25 @@ import java.util.Objects;
*/
@Component
public class PrepareDBFFile extends Stage implements InitializingBean {
private static final String SECTION = "U";
private static final String CODE_OF_MEMBER = null;
private static final DateTimeFormatter tsFormatter = DateTimeFormatter.ofPattern("yyMMddHHmm");
private static final DateTimeFormatter utilFormatter = DateTimeFormatter.ofPattern("yyMMdd");
public static final String SECTION = "S";
private final ExportDBFServiceSettings settings;
private String outDir;
public static String outDir;
private final SFTPConfig.DbfGateway gateway;
public PrepareDBFFile(ExportDBFServiceSettings settings) {
public PrepareDBFFile(ExportDBFServiceSettings settings, SFTPConfig.DbfGateway gateway) {
this.settings = settings;
this.gateway = gateway;
}
@Override
public StageResult process(ResultContainer resultContainer) {
Objects.requireNonNull(resultContainer.getTableForExport());
List<SftpFileInfo> files = gateway.listFiles(settings.getStore().getOutDir());
log.debug("From sFTP dir \"{}\" list {} file names.", settings.getStore().getOutDir(), files.size());
Table table = resultContainer.getTableForExport();
File dbfFile = new File(prepareFilename(table, SECTION, CODE_OF_MEMBER, outDir));
LocalDateTime currentDateTime = LocalDateTime.now();
resultContainer.setRegistrationDateTime(currentDateTime);
File dbfFile = new File(nameTemplates.get(table).getFileName(resultContainer, files));
try {
Path dbfFilePath = dbfFile.toPath();
Files.deleteIfExists(dbfFilePath);
@ -53,58 +59,25 @@ public class PrepareDBFFile extends Stage implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
String outDirPath = settings.getStore().getOutDir();
String outDirPath = settings.getStore().getLocalTempDir();
File outDirFile = new File(outDirPath);
if (outDirFile.exists() && !outDirFile.isDirectory())
throw new IOException("Output directory " + outDirPath + " is file.");
if (!outDirFile.exists()) Files.createDirectories(outDirFile.toPath());
this.outDir = outDirPath;
log.info("Output directory: {}", outDirFile.getAbsolutePath());
}
private String prepareFilename(Table table, String section, String codeOfMember, String outDir) {
StringBuilder result = new StringBuilder();
String prefixOfTable = table.getFilePrefix();
String time = "PRC" + tsFormatter.format(LocalDateTime.now());
private static final Map<Table, FilenameTemplate> nameTemplates = new EnumMap<>(Table.class);
result.append(outDir);
result.append(File.separator);
result.append(prefixOfTable.toUpperCase(Locale.ROOT));
result.append('_');
result.append(section);
result.append('_');
result.append(time);
result.append('_');
result.append(countSameFilesInDir(prefixOfTable, outDir) + 1);
if (codeOfMember != null) {
result.append('_');
result.append(codeOfMember);
}
result.append(".DBF");
return result.toString();
}
private Integer countSameFilesInDir(String prefixOfTable, String outDir) {
int res = 0;
File directory = new File(outDir);
if (directory.exists()) {
for (File file : Objects.requireNonNull(directory.listFiles())) {
String name = file.getName();
String[] splitName = name.split("_");
String prefix = splitName[0];
String timestamp = splitName[2];
String timestampNow = utilFormatter.format(LocalDateTime.now());
if (prefix.equalsIgnoreCase(prefixOfTable) && timestamp.contains(timestampNow)) {
String counter = splitName[3];
int positionOfDot = counter.indexOf('.');
if (positionOfDot != -1) {
counter = counter.substring(0, positionOfDot);
}
res = Integer.max(res, Integer.parseInt(counter));
}
}
}
return res;
static {
nameTemplates.put(Table.S_DF02, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF03, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF05, FilenameTemplate.df_section_dateTime);
nameTemplates.put(Table.S_DF07, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF51, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF53, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF54, FilenameTemplate.df_section_dateTime_counter);
nameTemplates.put(Table.S_DF56, FilenameTemplate.df_section_dateTime_counter);
}
}

View file

@ -1,6 +1,8 @@
package ru.spcex.clearing.dbf.exporter.services;
import org.apache.kafka.clients.consumer.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import ru.spcex.clearing.dbf.exporter.logic.Processor;
@ -18,6 +20,7 @@ import java.util.Optional;
@Service
public class CommandService extends QueueConsumer implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ImdgProvider imdgProvider;
private final Processor processor;
@ -35,12 +38,30 @@ public class CommandService extends QueueConsumer implements InitializingBean {
callback(ExportToFileRequest.class)
.setConsumer(this::process)
.forDestination(Consts.EXPORT_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF02, r))
.forDestination(Consts.SDF02_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF03, r)) // todo необходимо в отдельную папку: "в отдельную директорию SettlementHouse_Fail (чтобы не отдавать такие файлы в ПРЦ"
.forDestination(Consts.SDF03_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF11, r))
.forDestination(Consts.SDF11_PROCESS, callbacks::put);
.setConsumer(r -> processSpecial(Table.S_DF05, r))
.forDestination(Consts.SDF05_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF07, r))
.forDestination(Consts.SDF07_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF51, r))
.forDestination(Consts.SDF51_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF53, r))
.forDestination(Consts.SDF53_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF54, r))
.forDestination(Consts.SDF54_PROCESS, callbacks::put);
callback(SdfClearingRequest.class)
.setConsumer(r -> processSpecial(Table.S_DF56, r))
.forDestination(Consts.SDF56_PROCESS, callbacks::put);
init();
}

View file

@ -1,40 +0,0 @@
package ru.spcex.clearing.dbf.exporter.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import ru.spcex.clearing.dbf.exporter.logic.Processor;
import ru.spcex.clearing.dbf.exporter.logic.data.ResultContainer;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import ru.spcex.platform.imdg.api.ImdgProvider;
import java.util.Arrays;
@Service("dbfExportService")
public class DBFExportService {
Logger log = LoggerFactory.getLogger(getClass());
private final ThreadPoolTaskExecutor executor;
private final Processor processor;
protected final ImdgProvider imdgProvider;
public DBFExportService(@Qualifier("executor") ThreadPoolTaskExecutor executor,
@Qualifier("processor") Processor processor,
ImdgProvider imdgProvider) {
this.executor = executor;
this.processor = processor;
this.imdgProvider = imdgProvider;
log.debug("Check IMDG...");
imdgProvider.waitAvailable();
log.debug("IMDG ready...");
}
public void run() {
log.debug("Do export for all: {}", Arrays.toString(Table.values()));
for (Table tableForExport : Table.values()) {
executor.submit(() -> processor.process(ResultContainer.createNewTask(tableForExport)));
}
}
}

View file

@ -3,6 +3,7 @@ package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFField;
import ru.spcex.platform.classes.base.SpcexObjectBase;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
@ -25,4 +26,14 @@ public abstract class DFConverter<T extends SpcexObjectBase> {
if (src instanceof LocalTime srcLocalTime) return Time.valueOf(srcLocalTime);
return src;
}
protected Long convertStrToLong(String s) {
if (s == null) return null;
return Long.valueOf(s);
}
protected BigDecimal convertStrToBigDecimal(String s) {
if (s == null) return null;
return new BigDecimal(s).setScale(0);
}
}

View file

@ -43,7 +43,7 @@ public class S_DF02_Converter extends DFConverter<SDf02> {
dbfFields.add(new DBFField("ACC_TYPE", DBFDataType.CHARACTER, 2));
dbfFields.add(new DBFField("SUMENGAGE", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("SUMUNBLOCK", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("FILE_TYPE", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("FILE_TYPE", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("RESULT", DBFDataType.CHARACTER, 3));
return dbfFields.toArray(DBFField[]::new);
}

View file

@ -17,15 +17,12 @@ public class S_DF03_Converter extends DFConverter<SDf03> {
values.add(typeMatch(entity.getDoc_type()));
values.add(typeMatch(entity.getDocnm_ref()));
values.add(typeMatch(entity.getDocnmprev()));
// values.add(typeMatch(entity.getPriority()));
// values.add(typeMatch(entity.getSbankcode()));
values.add(typeMatch(entity.getC_acc_deb()));
values.add(typeMatch(entity.getSbanknam1()));
values.add(typeMatch(entity.getSbanknam2()));
values.add(typeMatch(entity.getSbanknam3()));
values.add(typeMatch(entity.getSbanknam4()));
values.add(typeMatch(entity.getSbanknam5()));
// values.add(typeMatch(entity.getRbankcode()));
values.add(typeMatch(entity.getC_acc_cred()));
values.add(typeMatch(entity.getRbanknam1()));
values.add(typeMatch(entity.getRbanknam2()));
@ -33,31 +30,9 @@ public class S_DF03_Converter extends DFConverter<SDf03> {
values.add(typeMatch(entity.getRbanknam4()));
values.add(typeMatch(entity.getRbanknam5()));
values.add(typeMatch(entity.getPay_date()));
// values.add(typeMatch(entity.getExt_date()));
values.add(typeMatch(entity.getPay_val()));
values.add(typeMatch(entity.getSum_deb()));
// values.add(typeMatch(entity.getSclientn1()));
// values.add(typeMatch(entity.getSclientn2()));
// values.add(typeMatch(entity.getSclientn3()));
// values.add(typeMatch(entity.getSclientn4()));
// values.add(typeMatch(entity.getSc_code()));
// values.add(typeMatch(entity.getAcc_deb()));
// values.add(typeMatch(entity.getRclientn1()));
// values.add(typeMatch(entity.getRclientn2()));
// values.add(typeMatch(entity.getRclientn3()));
// values.add(typeMatch(entity.getRclientn4()));
// values.add(typeMatch(entity.getAcc_kr_1()));
// values.add(typeMatch(entity.getAcc_kr_2()));
// values.add(typeMatch(entity.getSp_code()));
values.add(typeMatch(entity.getSpecif_1()));
// values.add(typeMatch(entity.getSpecif_2()));
// values.add(typeMatch(entity.getSpecif_3()));
// values.add(typeMatch(entity.getSpecif_4()));
// values.add(typeMatch(entity.getSpecif_5()));
// values.add(typeMatch(entity.getSpecif_6()));
// values.add(typeMatch(entity.getSend_type()));
// values.add(typeMatch(entity.getServdate()));
// values.add(typeMatch(entity.getDoc_result()));
values.add(typeMatch(entity.getImp_result()));
return values.toArray(Object[]::new);
}
@ -69,15 +44,12 @@ public class S_DF03_Converter extends DFConverter<SDf03> {
dbfFields.add(new DBFField("DOC_TYPE", DBFDataType.CHARACTER, 4));
dbfFields.add(new DBFField("DOCNM_REF", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("DOCNMPREV", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("PRIORITY", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("SBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_CRED", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM2", DBFDataType.CHARACTER, 35));
@ -85,31 +57,9 @@ public class S_DF03_Converter extends DFConverter<SDf03> {
dbfFields.add(new DBFField("RBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("PAY_DATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("EXT_DATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("PAY_VAL", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("SUM_DEB", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("SCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SC_CODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("ACC_KR_1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("ACC_KR_2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SP_CODE", DBFDataType.CHARACTER, 2));
dbfFields.add(new DBFField("SPECIF_1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_6", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SEND_TYPE", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("SERVDATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("DOC_RESULT", DBFDataType.CHARACTER, 2));
dbfFields.add(new DBFField("SPECIF_1", DBFDataType.CHARACTER, 254));
dbfFields.add(new DBFField("IMP_RESULT", DBFDataType.CHARACTER, 3));
return dbfFields.toArray(DBFField[]::new);
}

View file

@ -0,0 +1,35 @@
package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf05;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF05_Converter extends DFConverter<SDf05> {
@Override
public Object[] toObjectArray(SDf05 entity) {
List<Object> values = new LinkedList<>();
values.add(typeMatch(entity.getTp()));
values.add(typeMatch(entity.getDt()));
values.add(typeMatch(entity.getTm()));
values.add(typeMatch(entity.getPr()));
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
Date date = new Date();
dbfFields.add(new DBFField("TP", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("DT", DBFDataType.DATE));
dbfFields.add(new DBFField("TM", DBFDataType.DATE));
dbfFields.add(new DBFField("PR", DBFDataType.CHARACTER, 1));
return dbfFields.toArray(DBFField[]::new);
}
}

View file

@ -3,20 +3,22 @@ package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf17;
import ru.clearing.classes.statics.data.sdf.SDf07;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF17_Converter extends DFConverter<SDf17> {
public class S_DF07_Converter extends DFConverter<SDf07> {
@Override
public Object[] toObjectArray(SDf17 entity) {
public Object[] toObjectArray(SDf07 entity) {
List<Object> values = new LinkedList<>();
values.add(typeMatch(entity.getAccount()));
values.add(typeMatch(entity.getSum()));
values.add(typeMatch(entity.getMarket()));
values.add(typeMatch(entity.getType()));
values.add(typeMatch(entity.getDeal()));
values.add(typeMatch(entity.getClientN()));
values.add(typeMatch(entity.getInn()));
values.add(typeMatch(entity.getBic()));
values.add(typeMatch(entity.getSpec()));
@ -32,11 +34,13 @@ public class S_DF17_Converter extends DFConverter<SDf17> {
dbfFields.add(new DBFField("SUM", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("MARKET", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("TYPE", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("DEAL", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("CLIENT_N", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("_I_N_N", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("_B_I_C", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("_S_P_E_C", DBFDataType.CHARACTER, 254));
dbfFields.add(new DBFField("NUMBER", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("RESULT", DBFDataType.NUMERIC, 1));
dbfFields.add(new DBFField("RESULT", DBFDataType.NUMERIC, 32, 18));
return dbfFields.toArray(DBFField[]::new);
}

View file

@ -1,39 +0,0 @@
package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf10;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF10_Converter extends DFConverter<SDf10> {
@Override
public Object[] toObjectArray(SDf10 entity) {
List<Object> values = new LinkedList<>();
// values.add(typeMatch(entity.getAccount()));
// values.add(typeMatch(entity.getSum()));
// values.add(typeMatch(entity.getMarket()));
// values.add(typeMatch(entity.getType()));
// values.add(typeMatch(entity.getNumber()));
// values.add(typeMatch(entity.getInn()));
// values.add(typeMatch(entity.getResult()));
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
dbfFields.add(new DBFField("ACCOUNT", DBFDataType.CHARACTER, 20));
dbfFields.add(new DBFField("SUM", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("MARKET", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("TYPE", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("NUMBER", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("_I_N_N", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("RESULT", DBFDataType.CHARACTER, 3));
return dbfFields.toArray(DBFField[]::new);
}
}

View file

@ -1,115 +0,0 @@
package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf11;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF11_Converter extends DFConverter<SDf11> {
@Override
public Object[] toObjectArray(SDf11 entity) {
List<Object> values = new LinkedList<>();
// values.add(typeMatch(entity.getSeg_type()));
// values.add(typeMatch(entity.getDoc_type()));
// values.add(typeMatch(entity.getDocnm_ref()));
// values.add(typeMatch(entity.getDocnmprev()));
// values.add(typeMatch(entity.getPriority()));
// values.add(typeMatch(entity.getSbankcode()));
// values.add(typeMatch(entity.getC_acc_deb()));
// values.add(typeMatch(entity.getSbanknam1()));
// values.add(typeMatch(entity.getSbanknam2()));
// values.add(typeMatch(entity.getSbanknam3()));
// values.add(typeMatch(entity.getSbanknam4()));
// values.add(typeMatch(entity.getSbanknam5()));
// values.add(typeMatch(entity.getRbankcode()));
// values.add(typeMatch(entity.getC_acc_cred()));
// values.add(typeMatch(entity.getRbanknam1()));
// values.add(typeMatch(entity.getRbanknam2()));
// values.add(typeMatch(entity.getRbanknam3()));
// values.add(typeMatch(entity.getRbanknam4()));
// values.add(typeMatch(entity.getRbanknam5()));
// values.add(typeMatch(entity.getPay_date()));
// values.add(typeMatch(entity.getExt_date()));
// values.add(typeMatch(entity.getPay_val()));
// values.add(typeMatch(entity.getSum_deb()));
// values.add(typeMatch(entity.getSclientn1()));
// values.add(typeMatch(entity.getSclientn2()));
// values.add(typeMatch(entity.getSclientn3()));
// values.add(typeMatch(entity.getSclientn4()));
// values.add(typeMatch(entity.getSc_code()));
// values.add(typeMatch(entity.getAcc_deb()));
// values.add(typeMatch(entity.getRclientn1()));
// values.add(typeMatch(entity.getRclientn2()));
// values.add(typeMatch(entity.getRclientn3()));
// values.add(typeMatch(entity.getRclientn4()));
// values.add(typeMatch(entity.getAcc_kr_1()));
// values.add(typeMatch(entity.getAcc_kr_2()));
// values.add(typeMatch(entity.getSp_code()));
// values.add(typeMatch(entity.getSpecif_1()));
// values.add(typeMatch(entity.getSpecif_2()));
// values.add(typeMatch(entity.getSpecif_3()));
// values.add(typeMatch(entity.getSpecif_4()));
// values.add(typeMatch(entity.getSpecif_5()));
// values.add(typeMatch(entity.getSpecif_6()));
// values.add(typeMatch(entity.getSend_type()));
// values.add(typeMatch(entity.getServdate()));
// values.add(typeMatch(entity.getDoc_result()));
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
dbfFields.add(new DBFField("SEG_TYPE", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("DOC_TYPE", DBFDataType.CHARACTER, 4));
dbfFields.add(new DBFField("DOCNM_REF", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("DOCNMPREV", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("PRIORITY", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("SBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_CRED", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("PAY_DATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("EXT_DATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("PAY_VAL", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("SUM_DEB", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("SCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SC_CODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("ACC_KR_1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("ACC_KR_2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SP_CODE", DBFDataType.CHARACTER, 2));
dbfFields.add(new DBFField("SPECIF_1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF_6", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SEND_TYPE", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("SERVDATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("DOC_RESULT", DBFDataType.CHARACTER, 2));
return dbfFields.toArray(DBFField[]::new);
}
}

View file

@ -3,35 +3,30 @@ package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf08;
import ru.clearing.classes.statics.data.sdf.SDf51;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF08_Converter extends DFConverter<SDf08> {
public class S_DF51_Converter extends DFConverter<SDf51> {
@Override
public Object[] toObjectArray(SDf08 entity) {
public Object[] toObjectArray(SDf51 entity) {
List<Object> values = new LinkedList<>();
// values.add(convertStrToLong(entity.getNumber()));
// values.add(typeMatch(convertStrToLong(entity.getDatetime()))); // UNIX TIME
values.add(typeMatch(entity.getNumber()));
values.add(typeMatch(convertStrToLong(entity.getDatetime()))); // UNIX TIME
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
dbfFields.add(new DBFField("NUMBER", DBFDataType.NUMERIC, 10));
dbfFields.add(new DBFField("NUMBER", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("DATETIME", DBFDataType.NUMERIC, 13)); // UNIX TIME
return dbfFields.toArray(DBFField[]::new);
}
Long convertStrToLong(String s) {
if (s == null) return null;
return Long.valueOf(s);
}
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("dd.MM.yyyy");
private static final DateTimeFormatter DATE_TIME_FMT = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");

View file

@ -3,22 +3,20 @@ package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf18;
import ru.clearing.classes.statics.data.sdf.SDf53;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF18_Converter extends DFConverter<SDf18> {
public class S_DF53_Converter extends DFConverter<SDf53> {
@Override
public Object[] toObjectArray(SDf18 entity) {
public Object[] toObjectArray(SDf53 entity) {
List<Object> values = new LinkedList<>();
values.add(typeMatch(entity.getAccount()));
values.add(typeMatch(entity.getDeal()));
values.add(typeMatch(entity.getStatus()));
values.add(typeMatch(entity.getResult()));
values.add(typeMatch(entity.getGenerationTime()));
values.add(typeMatch(entity.getGenerationId()));
return values.toArray(Object[]::new);
}
@ -29,8 +27,6 @@ public class S_DF18_Converter extends DFConverter<SDf18> {
dbfFields.add(new DBFField("DEAL", DBFDataType.CHARACTER, 4));
dbfFields.add(new DBFField("STATUS", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("RESULT", DBFDataType.NUMERIC, 32, 18));
dbfFields.add(new DBFField("GEN_TIME", DBFDataType.DATE));
dbfFields.add(new DBFField("GEN_ID", DBFDataType.NUMERIC));
return dbfFields.toArray(DBFField[]::new);
}

View file

@ -0,0 +1,105 @@
package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf54;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF54_Converter extends DFConverter<SDf54> {
@Override
public Object[] toObjectArray(SDf54 entity) {
List<Object> values = new LinkedList<>();
values.add(typeMatch(entity.getSeg_type()));
values.add(typeMatch(entity.getDoc_type()));
values.add(typeMatch(entity.getDocnm_ref()));
values.add(typeMatch(entity.getDocnmprev()));
values.add(typeMatch(entity.getSbankcode()));
values.add(typeMatch(entity.getC_acc_deb()));
values.add(typeMatch(entity.getSbanknam1()));
values.add(typeMatch(entity.getSbanknam2()));
values.add(typeMatch(entity.getSbanknam3()));
values.add(typeMatch(entity.getSbanknam4()));
values.add(typeMatch(entity.getSbanknam5()));
values.add(typeMatch(entity.getRbankcode()));
values.add(typeMatch(entity.getC_acc_cred()));
values.add(typeMatch(entity.getRbanknam1()));
values.add(typeMatch(entity.getRbanknam2()));
values.add(typeMatch(entity.getRbanknam3()));
values.add(typeMatch(entity.getRbanknam4()));
values.add(typeMatch(entity.getRbanknam5()));
values.add(typeMatch(entity.getOp_type()));
values.add(typeMatch(entity.getOp_order()));
values.add(typeMatch(entity.getPay_date()));
values.add(typeMatch(entity.getPay_val()));
values.add(typeMatch(entity.getSum_deb()));
values.add(typeMatch(entity.getSclientn1()));
values.add(typeMatch(entity.getSclientn2()));
values.add(typeMatch(entity.getSclientn3()));
values.add(typeMatch(entity.getSclientn4()));
values.add(typeMatch(entity.getInn_deb()));
values.add(typeMatch(entity.getKpp_deb()));
values.add(typeMatch(entity.getAcc_deb()));
values.add(typeMatch(entity.getRclientn1()));
values.add(typeMatch(entity.getRclientn2()));
values.add(typeMatch(entity.getRclientn3()));
values.add(typeMatch(entity.getRclientn4()));
values.add(typeMatch(entity.getInn_cred()));
values.add(typeMatch(entity.getKpp_cred()));
values.add(typeMatch(entity.getAcc_kr_1()));
values.add(typeMatch(entity.getSpecif_1()));
values.add(typeMatch(entity.getSend_type()));
values.add(typeMatch(entity.getDoc_result()));
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
dbfFields.add(new DBFField("SEG_TYPE", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("DOC_TYPE", DBFDataType.CHARACTER, 13));
dbfFields.add(new DBFField("DOCNM_REF", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("DOCNMPREV", DBFDataType.CHARACTER, 16));
dbfFields.add(new DBFField("SBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKCODE", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("C_ACC_CRED", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RBANKNAM5", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("OP_TYPE", DBFDataType.CHARACTER, 2));
dbfFields.add(new DBFField("OP_ORDER", DBFDataType.CHARACTER, 1));
dbfFields.add(new DBFField("PAY_DATE", DBFDataType.CHARACTER, 8));
dbfFields.add(new DBFField("PAY_VAL", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("SUM_DEB", DBFDataType.CHARACTER, 22));
dbfFields.add(new DBFField("SCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("INN_DEB", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("KPP_DEB", DBFDataType.CHARACTER, 9));
dbfFields.add(new DBFField("ACC_DEB", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN2", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN3", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("RCLIENTN4", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("INN_CRED", DBFDataType.CHARACTER, 12));
dbfFields.add(new DBFField("KPP_CRED", DBFDataType.CHARACTER, 9));
dbfFields.add(new DBFField("ACC_KR1", DBFDataType.CHARACTER, 35));
dbfFields.add(new DBFField("SPECIF1", DBFDataType.CHARACTER, 254));
dbfFields.add(new DBFField("SEND_TYPE", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("DOC_RESULT", DBFDataType.CHARACTER, 2));
return dbfFields.toArray(DBFField[]::new);
}
}

View file

@ -0,0 +1,35 @@
package ru.spcex.clearing.dbf.exporter.services.converters;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import org.springframework.stereotype.Service;
import ru.clearing.classes.statics.data.sdf.SDf56;
import java.util.LinkedList;
import java.util.List;
@Service
public class S_DF56_Converter extends DFConverter<SDf56> {
@Override
public Object[] toObjectArray(SDf56 entity) {
List<Object> values = new LinkedList<>();
values.add(typeMatch(entity.getNumber()));
values.add(convertStrToBigDecimal(entity.getStart_datetime())); // UNIX DATE TIME
values.add(convertStrToBigDecimal(entity.getEnd_datetime())); // UNIX DATE TIME
values.add(typeMatch(entity.getAccount()));
values.add(typeMatch(entity.getDeal()));
return values.toArray(Object[]::new);
}
@Override
public DBFField[] getDBFHeaders() {
List<DBFField> dbfFields = new LinkedList<>();
dbfFields.add(new DBFField("NUMBER", DBFDataType.CHARACTER, 10));
dbfFields.add(new DBFField("SDATETIME", DBFDataType.NUMERIC, 10));
dbfFields.add(new DBFField("EDATETIME", DBFDataType.NUMERIC, 10));
dbfFields.add(new DBFField("ACCOUNT", DBFDataType.CHARACTER, 25));
dbfFields.add(new DBFField("DEAL", DBFDataType.CHARACTER, 4));
return dbfFields.toArray(DBFField[]::new);
}
}

View file

@ -1,6 +1,4 @@
server.port=8080
server.servlet.context-path=/exporter
spring.main.web-application-type=servlet
spring.main.web-application-type=none
export-dbf-service.hazelcast.cluster-members=10.200.200.181:5701
export-dbf-service.hazelcast.login=dev
@ -9,7 +7,12 @@ export-dbf-service.hazelcast.password=dev-pass
export-dbf-service.common.encoding=cp866
export-dbf-service.common.threads-count=10
export-dbf-service.store.out-dir=d:\\trash\\clearing\\exporter\\out\\
export-dbf-service.store.local-temp-dir=D:\\docs and T3\\clearing\\dbf\\
export-dbf-service.store.out-dir=DocOut
export-dbf-service.store.user:tester
export-dbf-service.store.password=password
export-dbf-service.store.server-ip=10.230.238.53
export-dbf-service.store.server-port=2222
export-dbf-service.kafka-consumer.bootstrap-servers=localhost:9092
export-dbf-service.kafka-consumer.group-id=dev-group-balance-service
@ -18,3 +21,10 @@ export-dbf-service.kafka-consumer.session-timeout-ms=30000
export-dbf-service.kafka-consumer.auto-offset-reset=latest
export-dbf-service.kafka-consumer.linger-ms=1
export-dbf-service.kafka-consumer.buffer-memory=33554432
export-dbf-service.kafka-producer.bootstrap-servers=localhost:9092
export-dbf-service.kafka-producer.acks=all
export-dbf-service.kafka-producer.retries=0
export-dbf-service.kafka-producer.batch-size=16384
export-dbf-service.kafka-producer.linger-ms=1
export-dbf-service.kafka-producer.buffer-memory=33554432

View file

@ -0,0 +1,73 @@
package ru.spcex.clearing.dbf.exporter;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import ru.spcex.clearing.dbf.exporter.config.ExportDBFServiceSettingsTest;
import ru.spcex.clearing.dbf.exporter.config.PipelineConfig;
import ru.spcex.clearing.dbf.exporter.config.SFTPTestConfig;
import ru.spcex.clearing.dbf.exporter.logic.Processor;
import ru.spcex.clearing.dbf.exporter.logic.stages.ExportFromHazelcast;
import ru.spcex.clearing.dbf.exporter.logic.stages.Journal;
import ru.spcex.clearing.dbf.exporter.logic.stages.PrepareDBFFile;
import ru.spcex.clearing.dbf.exporter.services.CommandService;
import ru.spcex.clearing.dbf.exporter.services.converters.*;
import ru.spcex.clearing.test.config.ImdgTestConfig;
import ru.spcex.clearing.test.config.KafkaTestConfig;
import ru.spcex.platform.imdg.api.ImdgProvider;
import java.nio.file.Path;
import java.nio.file.Paths;
import static ru.spcex.clearing.test.config.ImdgTestConfig.waitAvailableImdgProviderAndAddAdminWithDefaultId;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
ExportDBFServiceSettingsTest.class,
SFTPTestConfig.class,
PipelineConfig.class,
ExportFromHazelcast.class,
Journal.class,
PrepareDBFFile.class,
Processor.class,
CommandService.class,
S_DF02_Converter.class,
S_DF03_Converter.class,
S_DF05_Converter.class,
S_DF07_Converter.class,
S_DF51_Converter.class,
S_DF53_Converter.class,
S_DF54_Converter.class,
S_DF56_Converter.class,
ImdgTestConfig.class,
KafkaTestConfig.class})
public abstract class AbstractServiceTest {
protected static final long generationId = 21L;
@Autowired
@Qualifier("kafkaTestTemplate")
protected KafkaTemplate<String, Object> kafkaTemplate;
@Autowired
@Qualifier("hazelcastServiceTest")
protected ImdgProvider imdgProvider;
@Autowired
protected CommandService commandService;
@BeforeAll
static void setProperty() {
Path path = Paths.get("src", "main", "resources");
String currentPath = path.toAbsolutePath().toString();
System.setProperty("spring.config.location", currentPath);
// Hazelcast.shutdownAll();
}
protected void init() {
waitAvailableImdgProviderAndAddAdminWithDefaultId();
}
}

View file

@ -0,0 +1,24 @@
package ru.spcex.clearing.dbf.exporter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.spcex.clearing.dbf.exporter.config.settings.Common;
import ru.spcex.clearing.dbf.exporter.config.settings.ExportDBFServiceSettings;
import ru.spcex.clearing.dbf.exporter.config.settings.Store;
@Configuration
public class ExportDBFServiceSettingsTest {
@Bean
public ExportDBFServiceSettings settings(){
ExportDBFServiceSettings settings = new ExportDBFServiceSettings();
Common common = new Common();
common.setEncoding("cp866");
settings.setCommon(common);
Store store = new Store();
store.setOutDir("DocOut");
store.setLocalTempDir("D:\\docs and T3\\clearing\\dbf");
settings.setStore(store);
return settings;
}
}

View file

@ -0,0 +1,31 @@
package ru.spcex.clearing.dbf.exporter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.sftp.session.SftpFileInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class SFTPTestConfig {
@Bean
public SFTPConfig.DbfGateway dbfGateway(){
return new DGateway();
}
public static class DGateway implements SFTPConfig.DbfGateway{
@Override
public void sendToSftp(File file) {
}
@Override
public List<SftpFileInfo> listFiles(String dir) {
return new ArrayList<>();
}
}
}

View file

@ -0,0 +1,28 @@
package ru.spcex.clearing.dbf.exporter.logic.data.enums;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.junit.jupiter.api.Test;
import org.springframework.integration.sftp.session.SftpFileInfo;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class FilenameTemplateTest {
@Test
void countSameFilesInDir() {
LsEntry lsEntry = mock(LsEntry.class);
doReturn("DF-02_S_PRC2305191321_1.DBF").when(lsEntry).getFilename();
SftpFileInfo sftpFileInfo = spy(new SftpFileInfo(lsEntry));
doReturn(false).when(sftpFileInfo).isDirectory();
List<SftpFileInfo> files = List.of(sftpFileInfo);
int count = FilenameTemplate.df_section_dateTime.countSameFilesInDir("DF-02", files);
assertEquals(1, count);
// doReturn("DF-02_S_PRC230").when(lsEntry).getFilename();
// count = FilenameTemplate.df_section_dateTime.countSameFilesInDir("DF-02", files);
// assertEquals(0, count);
}
}

View file

@ -0,0 +1,69 @@
package ru.spcex.clearing.dbf.exporter.services;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import ru.clearing.classes.statics.data.sdf.SDf02;
import ru.spcex.clearing.dbf.exporter.AbstractServiceTest;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.SdfClearingRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.system.JournalSdf;
import ru.spcex.platform.imdg.api.Imdg;
import javax.annotation.PostConstruct;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.test.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.test.TestUtils.getJsonStringForNew;
import static ru.spcex.clearing.test.config.KafkaTestConfig.getCaptor;
class S_DF02_Test extends AbstractServiceTest {
@PostConstruct
public void init() {
super.init();
}
/**
* Тест проверяет создание строк документа DBF .<br>
*/
@Test
void cdeateSdf() {
Table table = Table.S_DF02;
Imdg<SDf02> map = imdgProvider.getImdg(table.getHazelcastMapName(), SDf02.class);
SDf02 sDf02 = new SDf02();
sDf02.setGenerationId(generationId);
sDf02.setCurr_code("curr_code");
sDf02.setAccount("account");
sDf02.setRemainder("remainder");
sDf02.setDeal("deal");
sDf02.setAcc_code("acc_code");
sDf02.setDat("dat");
sDf02.setMarket("market");
sDf02.setAcc_name("acc_name");
sDf02.setAcc_type("acc_type");
sDf02.setSumengage("sumengage");
sDf02.setSumunblock("sumunblock");
sDf02.setFile_type("file_type");
sDf02.setResult("result");
map.insert(sDf02);
SdfClearingRequest sdfClearingRequest = new SdfClearingRequest();
sdfClearingRequest.setGroupId(generationId);
String request = getJsonStringForNew(sdfClearingRequest, generationId);
addRecordToKafka((MockConsumer) commandService.getConsumer(), Consts.SDF02_PROCESS, 0, 0, request);
//waiting for kafka send message (finale event)
ArgumentCaptor<ProducerRecord> captor = getCaptor(kafkaTemplate);
verify(kafkaTemplate, timeout(30_000L).times(1))
.send(captor.capture());
BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) captor.getValue().value();
JournalSdf journalSdf = (JournalSdf) baseRequestResult.getRequestPayload();
assertEquals(generationId, journalSdf.getRegistrationNumber());
}
}

View file

@ -0,0 +1,77 @@
package ru.spcex.clearing.dbf.exporter.services;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import ru.clearing.classes.statics.data.sdf.SDf03;
import ru.spcex.clearing.dbf.exporter.AbstractServiceTest;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.SdfClearingRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.system.JournalSdf;
import ru.spcex.platform.imdg.api.Imdg;
import javax.annotation.PostConstruct;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.test.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.test.TestUtils.getJsonStringForNew;
import static ru.spcex.clearing.test.config.KafkaTestConfig.getCaptor;
class S_DF03_Test extends AbstractServiceTest {
@PostConstruct
public void init() {
super.init();
}
/**
* Тест проверяет создание строк документа DBF .<br>
*/
@Test
void cdeateSdf() {
Table table = Table.S_DF03;
Imdg<SDf03> map = imdgProvider.getImdg(table.getHazelcastMapName(), SDf03.class);
SDf03 sDf03 = new SDf03();
sDf03.setGenerationId(generationId);
sDf03.setSeg_type("seg_type");
sDf03.setDoc_type("doc_type");
sDf03.setDocnm_ref("docnm_ref");
sDf03.setDocnmprev("docnmprev");
sDf03.setC_acc_deb("c_acc_deb");
sDf03.setSbanknam1("sbanknam1");
sDf03.setSbanknam2("sbanknam2");
sDf03.setSbanknam3("sbanknam3");
sDf03.setSbanknam4("sbanknam4");
sDf03.setSbanknam5("sbanknam5");
sDf03.setC_acc_cred("c_acc_cred");
sDf03.setRbanknam1("rbanknam1");
sDf03.setRbanknam2("rbanknam2");
sDf03.setRbanknam3("rbanknam3");
sDf03.setRbanknam4("rbanknam4");
sDf03.setRbanknam5("rbanknam5");
sDf03.setPay_date("pay_date");
sDf03.setPay_val("pay_val");
sDf03.setSum_deb("sum_deb");
sDf03.setSpecif_1("specif_1");
sDf03.setImp_result("imp_result");
map.insert(sDf03);
SdfClearingRequest sdfClearingRequest = new SdfClearingRequest();
sdfClearingRequest.setGroupId(generationId);
String request = getJsonStringForNew(sdfClearingRequest, generationId);
addRecordToKafka((MockConsumer) commandService.getConsumer(), Consts.SDF03_PROCESS, 0, 0, request);
//waiting for kafka send message (finale event)
ArgumentCaptor<ProducerRecord> captor = getCaptor(kafkaTemplate);
verify(kafkaTemplate, timeout(30_000L).times(1))
.send(captor.capture());
BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) captor.getValue().value();
JournalSdf journalSdf = (JournalSdf) baseRequestResult.getRequestPayload();
assertEquals(generationId, journalSdf.getRegistrationNumber());
}
}

View file

@ -0,0 +1,63 @@
package ru.spcex.clearing.dbf.exporter.services;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import ru.clearing.classes.statics.data.sdf.SDf05;
import ru.spcex.clearing.dbf.exporter.AbstractServiceTest;
import ru.spcex.clearing.dbf.exporter.logic.data.enums.Table;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.clearing.SdfClearingRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.system.JournalSdf;
import ru.spcex.platform.imdg.api.Imdg;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static ru.spcex.clearing.test.TestUtils.addRecordToKafka;
import static ru.spcex.clearing.test.TestUtils.getJsonStringForNew;
import static ru.spcex.clearing.test.config.KafkaTestConfig.getCaptor;
class S_DF05_Test extends AbstractServiceTest {
@PostConstruct
public void init() {
super.init();
}
/**
* Тест проверяет создание строк документа DBF .<br>
*/
@Test
void cdeateSdf() {
Table table = Table.S_DF05;
Imdg<SDf05> map = imdgProvider.getImdg(table.getHazelcastMapName(), SDf05.class);
SDf05 sDf05 = new SDf05();
sDf05.setGenerationId(generationId);
sDf05.setTp(new BigDecimal(32));
sDf05.setDt(LocalDate.now());
sDf05.setTm(LocalTime.now());
sDf05.setPr("deal");
map.insert(sDf05);
SdfClearingRequest sdfClearingRequest = new SdfClearingRequest();
sdfClearingRequest.setGroupId(generationId);
String request = getJsonStringForNew(sdfClearingRequest, generationId);
addRecordToKafka((MockConsumer) commandService.getConsumer(), Consts.SDF05_PROCESS, 0, 0, request);
//waiting for kafka send message (finale event)
ArgumentCaptor<ProducerRecord> captor = getCaptor(kafkaTemplate);
verify(kafkaTemplate, timeout(30_000L).times(1))
.send(captor.capture());
BaseRequest<Object> baseRequestResult = (BaseRequest<Object>) captor.getValue().value();
JournalSdf journalSdf = (JournalSdf) baseRequestResult.getRequestPayload();
assertEquals(generationId, journalSdf.getRegistrationNumber());
}
}

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