итоговая МКР добавил создание PaymentInstruction по возврату

поправил отправку SDF03
This commit is contained in:
ialbert 2023-06-08 13:32:49 +03:00
parent 14c4dc58f2
commit ef17c60c58
5 changed files with 397 additions and 44 deletions

View file

@ -22,6 +22,9 @@ import java.time.format.DateTimeFormatter;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/**
* Builder для кейса итоговой сессии МКР, 7 шаг, кейс - по сделкам
*/
public class PaymentInstructionBuilderFinalMkr { public class PaymentInstructionBuilderFinalMkr {
private final static Logger log = LoggerFactory.getLogger(PaymentInstructionBuilderFinalMkr.class); private final static Logger log = LoggerFactory.getLogger(PaymentInstructionBuilderFinalMkr.class);

View file

@ -40,7 +40,8 @@ public class FinalMkrSession extends AbstractSession implements InitializingBean
private final InclusionObligations inclusionObligations; private final InclusionObligations inclusionObligations;
private final InspectionObligations inspectionObligations; private final InspectionObligations inspectionObligations;
private final FormingRegistersOnOS formingRegistersOnOS; private final FormingRegistersOnOS formingRegistersOnOS;
private final FormingPaymentInstructionDealsFinalMkr formingPaymentInstruction; private final FormingPaymentInstructionReturnMkr formingPaymentInstructionReturn;
private final FormingPaymentInstructionDealsFinalMkr formingPaymentInstructionDeals;
private final UnlockResources unlockResources; private final UnlockResources unlockResources;
private final FinishingSession finishingSession; private final FinishingSession finishingSession;
private final EndStageNotification endStageNotification; private final EndStageNotification endStageNotification;
@ -58,7 +59,7 @@ public class FinalMkrSession extends AbstractSession implements InitializingBean
ObligationAdmission obligationsAdmission, ObligationAdmission obligationsAdmission,
InclusionObligations inclusionObligations, InclusionObligations inclusionObligations,
FormingRegistersOnOS formingRegistersOnOS, FormingRegistersOnOS formingRegistersOnOS,
FormingPaymentInstructionDealsFinalMkr formingPaymentInstruction, FormingPaymentInstructionReturnMkr formingPaymentInstructionReturn, FormingPaymentInstructionDealsFinalMkr formingPaymentInstructionDeals,
UnlockResources unlockResources, UnlockResources unlockResources,
FinishingSession finishingSession, FinishingSession finishingSession,
EndStageNotification endStageNotification, EndStageNotification endStageNotification,
@ -72,7 +73,8 @@ public class FinalMkrSession extends AbstractSession implements InitializingBean
this.obligationsAdmission = obligationsAdmission; this.obligationsAdmission = obligationsAdmission;
this.inclusionObligations = inclusionObligations; this.inclusionObligations = inclusionObligations;
this.formingRegistersOnOS = formingRegistersOnOS; this.formingRegistersOnOS = formingRegistersOnOS;
this.formingPaymentInstruction = formingPaymentInstruction; this.formingPaymentInstructionReturn = formingPaymentInstructionReturn;
this.formingPaymentInstructionDeals = formingPaymentInstructionDeals;
this.unlockResources = unlockResources; this.unlockResources = unlockResources;
this.finishingSession = finishingSession; this.finishingSession = finishingSession;
this.endStageNotification = endStageNotification; this.endStageNotification = endStageNotification;
@ -170,12 +172,22 @@ public class FinalMkrSession extends AbstractSession implements InitializingBean
//stage 6 //stage 6
runStage(TaskType.FormingRegistersOnOS, formingRegistersOnOS); //returns Collection<Registry> runStage(TaskType.FormingRegistersOnOS, formingRegistersOnOS); //returns Collection<Registry>
//stage 7 //stage 7
StageResult<Collection<PaymentInstruction>> paymentResult = null;
StageResult<Collection<PaymentInstruction>> returnsPayment = null;
{ {
FormingPaymentInstructionPayload payload = new FormingPaymentInstructionPayload(); FormingPaymentInstructionPayload payload = new FormingPaymentInstructionPayload();
payload.setSessionId(currSession.getId()); payload.setSessionId(currSession.getId());
//stage 7 //stage 7
paymentResult = runStage(TaskType.FormingPaymentInstruction, payload, formingPaymentInstruction); returnsPayment = runStage(TaskType.FormingPaymentInstruction, payload, formingPaymentInstructionReturn);
}
StageResult<Collection<PaymentInstruction>> paymentResult = null;
{
FormingPaymentInstructionDealsMkrPayload payload = new FormingPaymentInstructionDealsMkrPayload();
payload.setSessionId(currSession.getId());
payload.setPaymentInstructionReturns(returnsPayment.getStageResult());
//stage 7
paymentResult = runStage(TaskType.FormingPaymentInstruction, payload, formingPaymentInstructionDeals);
} }
if (paymentResult != null && paymentResult.getStageResult().isEmpty()) { if (paymentResult != null && paymentResult.getStageResult().isEmpty()) {
runStage(TaskType.FormingPaymentInstruction, balanceRevise); runStage(TaskType.FormingPaymentInstruction, balanceRevise);

View file

@ -17,13 +17,12 @@ import ru.spcex.clearing.error.ClearingError;
import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts; import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.balance.ExportToFileRequest; import ru.spcex.clearing.platform.messaging.domain.cud.balance.ExportToFileRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.importexport.SwtExporterRequest;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender; import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.service.builder.PaymentInstructionBuilderFinalMkr; import ru.spcex.clearing.service.builder.PaymentInstructionBuilderFinalMkr;
import ru.spcex.clearing.session.stage.ISessionStage; import ru.spcex.clearing.session.stage.ISessionStage;
import ru.spcex.clearing.session.stage.StageResult; import ru.spcex.clearing.session.stage.StageResult;
import ru.spcex.clearing.session.stage.Task; import ru.spcex.clearing.session.stage.Task;
import ru.spcex.clearing.session.stage.task.FormingPaymentInstructionPayload; import ru.spcex.clearing.session.stage.task.FormingPaymentInstructionDealsMkrPayload;
import ru.spcex.platform.enumeration.*; import ru.spcex.platform.enumeration.*;
import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.api.Imdg;
import ru.spcex.platform.imdg.api.ImdgId; import ru.spcex.platform.imdg.api.ImdgId;
@ -43,6 +42,7 @@ import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import static ru.spcex.platform.enumeration.RegistryTradingParams.CM_T; import static ru.spcex.platform.enumeration.RegistryTradingParams.CM_T;
import static ru.spcex.platform.enumeration.RegistryTradingParams.LM_T; import static ru.spcex.platform.enumeration.RegistryTradingParams.LM_T;
@ -81,10 +81,10 @@ public class FormingPaymentInstructionDealsFinalMkr implements ISessionStage {
@Override @Override
public StageResult<?> submit(Task<?> task) { public StageResult<?> submit(Task<?> task) {
FormingPaymentInstructionPayload payload = (FormingPaymentInstructionPayload) task.getData(); FormingPaymentInstructionDealsMkrPayload payload = (FormingPaymentInstructionDealsMkrPayload) task.getData();
switch (task.getTaskType()) { switch (task.getTaskType()) {
case FormingPaymentInstruction -> { case FormingPaymentInstruction -> {
return formingPaymentInstructions(payload.getSessionId()); return formingPaymentInstructions(payload.getSessionId(), payload.getPaymentInstructionReturns());
} }
default -> { default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType()); throw new IllegalStateException("Unknown task type: " + task.getTaskType());
@ -112,7 +112,7 @@ public class FormingPaymentInstructionDealsFinalMkr implements ISessionStage {
* регистр LMAT кто переводит деньги (registry.account)<br> * регистр LMAT кто переводит деньги (registry.account)<br>
* в итоге создается 2 PaymentInstruction: LMAT -> TRAN счет -> CMAT счет * в итоге создается 2 PaymentInstruction: LMAT -> TRAN счет -> CMAT счет
*/ */
private StageResult<?> formingPaymentInstructions(Long sessionId) { private StageResult<?> formingPaymentInstructions(Long sessionId, Collection<PaymentInstruction> paymentInstructionReturns) {
Collection<Registry> registries = selectRegistries(); Collection<Registry> registries = selectRegistries();
log.debug("found registries.size() = {}", registries.size()); log.debug("found registries.size() = {}", registries.size());
Account tranAcc = accountImdg.getSingleObjectBySQL("accountType = '%s' and status = '%s' and processingSign = '%s'" Account tranAcc = accountImdg.getSingleObjectBySQL("accountType = '%s' and status = '%s' and processingSign = '%s'"
@ -161,24 +161,20 @@ public class FormingPaymentInstructionDealsFinalMkr implements ISessionStage {
pmtInstrs.getFirst().getId(), pmtInstrs.getFirst().getId(),
pmtInstrs.getSecond().getId()); pmtInstrs.getSecond().getId());
} }
sendSdfs(allPaymentInstructions);
List<PaymentInstruction> returnsAndDeals = Stream.concat(paymentInstructionReturns.stream(), allPaymentInstructions.stream()).toList();
sendSdfs(returnsAndDeals);
StageResult<Collection<PaymentInstruction>> stageResult = new StageResult<>(null, true); StageResult<Collection<PaymentInstruction>> stageResult = new StageResult<>(null, true);
stageResult.setStageResult(allPaymentInstructions); stageResult.setStageResult(returnsAndDeals);
return stageResult; return stageResult;
} }
private void sendSdfs(List<PaymentInstruction> formedPaymentInstructions) { private void sendSdfs(List<PaymentInstruction> formedPaymentInstructions) {
List<SDf03> sDf03Created = new ArrayList<>(); List<SDf03> sDf03Created = new ArrayList<>();
List<SDf12> sDf12Created = new ArrayList<>();
for (PaymentInstruction paymentInstruction : formedPaymentInstructions) { for (PaymentInstruction paymentInstruction : formedPaymentInstructions) {
Security security = securityImdg.getSingleObjectByID(paymentInstruction.getCreditLeg_securityId());
Account account = accountImdg.getSingleObjectByID(paymentInstruction.getCreditLeg_accountId()); Account account = accountImdg.getSingleObjectByID(paymentInstruction.getCreditLeg_accountId());
if (InstrumentType.CRNC.equalsByKey(security.getInstrumentType()) && if (List.of(AccountType.Corr, AccountType.Clrn).contains(IEnumKey.getEnumByKey(AccountType.class, account.getAccountType()))) {
List.of(AccountType.Corr, AccountType.Clrn).contains(IEnumKey.getEnumByKey(AccountType.class, account.getAccountType()))) {
sDf03Created.add(newSDf03(paymentInstruction)); sDf03Created.add(newSDf03(paymentInstruction));
} else if (!InstrumentType.CRNC.equalsByKey(security.getInstrumentType()) &&
AccountType.Depo.equalsByKey(account.getAccountType())) {
sDf12Created.add(newSDf12(paymentInstruction));
} }
} }
@ -194,31 +190,6 @@ public class FormingPaymentInstructionDealsFinalMkr implements ISessionStage {
exportToFileRequest.setSdfGroupId(sdf03GroupId); exportToFileRequest.setSdfGroupId(sdf03GroupId);
kafkaSender.sendRequestToQueue(Consts.EXPORT_PROCESS, exportToFileRequest); kafkaSender.sendRequestToQueue(Consts.EXPORT_PROCESS, exportToFileRequest);
} }
Long sdf12GroupId = null;
Long maxTxNumber = 1L;
if (!sDf12Created.isEmpty()) {
sdf12GroupId = imdgProvider.getImdgIdGenerator().nextId();
ImdgPredicateBuilder predicateBuilder = sDf12Imdg.predicateBuilder();
ImdgPredicate notEmptyTransactionNum = predicateBuilder.not(predicateBuilder.equals("transaction_number", ""));
Long maxId = sDf12Imdg.aggregateLongMax("id", notEmptyTransactionNum);
if (maxId != null) {
SDf12 sDf12 = sDf12Imdg.getSingleObjectByID(maxId);
maxTxNumber = Long.parseLong(sDf12.getTransactionNumber()) + 1;
}
}
for (SDf12 sDf12 : sDf12Created) {
sDf12.setGenerationId(sdf03GroupId);
sDf12.setTransactionNumber(maxTxNumber.toString());
sDf12.setTransactionQuantity(String.valueOf(sDf12Created.size()));
sDf12Imdg.insert(sDf12);
}
if (sdf12GroupId != null) {
SwtExporterRequest swtExporterRequest = new SwtExporterRequest();
swtExporterRequest.setType("SDF_12");
kafkaSender.sendRequestToQueue(Consts.SWT_EXPORTER, swtExporterRequest);
}
} }
private SDf03 newSDf03(PaymentInstruction paymentInstruction) { private SDf03 newSDf03(PaymentInstruction paymentInstruction) {

View file

@ -0,0 +1,338 @@
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.account.Account;
import ru.clearing.classes.statics.data.company.Company;
import ru.clearing.classes.statics.data.payment.PaymentInstruction;
import ru.clearing.classes.statics.data.registry.Registry;
import ru.clearing.classes.statics.data.sdf.SDf03;
import ru.clearing.classes.statics.data.sdf.SDf12;
import ru.clearing.classes.statics.data.security.Security;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.Consts;
import ru.spcex.clearing.platform.messaging.domain.cud.balance.ExportToFileRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.importexport.SwtExporterRequest;
import ru.spcex.clearing.platform.messaging.service.sender.KafkaSender;
import ru.spcex.clearing.service.builder.PaymentInstructionBuilder;
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.FormingPaymentInstructionPayload;
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.ImdgPredicate;
import ru.spcex.platform.imdg.api.predicate.ImdgPredicateBuilder;
import ru.spcex.platform.imdg.api.predicate.specific.RegistryCodeSqlBuilder;
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.format.DateTimeFormatter;
import java.util.*;
import static ru.spcex.platform.enumeration.RegistryTradingParams.*;
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FormingPaymentInstructionReturnMkr 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 Imdg<Security> securityImdg;
private Imdg<Account> accountImdg;
private Imdg<Company> companyImdg;
private Imdg<SDf03> sDf03Imdg;
private Imdg<SDf12> sDf12Imdg;
private KafkaSender kafkaSender;
@Autowired
public FormingPaymentInstructionReturnMkr(ImdgProvider imdgProvider,
KafkaSender kafkaSender) {
this.kafkaSender = kafkaSender;
this.imdgProvider = imdgProvider;
this.idGenerator = imdgProvider.getImdgIdGenerator();
this.registryImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Registry, Registry.class);
this.securityImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Security, Security.class);
this.accountImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Account, Account.class);
this.companyImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_Company, Company.class);
this.sDf03Imdg = imdgProvider.getImdg(IMDGDistributedNames.Map_SDf03, SDf03.class);
this.sDf12Imdg = imdgProvider.getImdg(IMDGDistributedNames.Map_SDf12, SDf12.class);
this.paymentInstructionImdg = imdgProvider.getImdg(IMDGDistributedNames.Map_PaymentInstruction, PaymentInstruction.class);
}
@Override
public StageResult submit(Task<?> task) {
FormingPaymentInstructionPayload payload = (FormingPaymentInstructionPayload) task.getData();
switch (task.getTaskType()) {
case FormingPaymentInstruction -> {
return formingPaymentInstruction(payload.getSessionId());
}
default -> {
throw new IllegalStateException("Unknown task type: " + task.getTaskType());
}
}
}
private StageResult formingPaymentInstruction(Long sessionId) {
RegistryCodeSqlBuilder registryCodeSqlBuilder = RegistryCodeSqlBuilder.getInstance(LM_T, CM_T);
String registryCodeCondition = registryCodeSqlBuilder.build();
Collection<Registry> rgsAll = registryImdg.getCollectionObjectsBySQL(registryCodeCondition);
log.debug("LM*T and CM*T size = {}", rgsAll.size());
List<Registry> obligationsByMoney = rgsAll.stream()
.filter(registry -> equalsByRegistry(LM_T, registry))
.toList();
log.debug("changing assets by LM*T");
//изменяем активы по обязательствам по деньгам (LM_T)
for (Registry obligationByMoney : obligationsByMoney) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
obligationByMoney.getTradingClearingRegistryId(), obligationByMoney.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
for (Registry relatedRegistry : relatedRegistries) {
if (equalsByRegistry(AM_F, relatedRegistry)) {
relatedRegistry.setBalance(safeBD(relatedRegistry.getBalance()).subtract(safeBD(obligationByMoney.getBalance())));
} else if (equalsByRegistry(AM_T, relatedRegistry)) {
relatedRegistry.setSettledDebit(safeBD(relatedRegistry.getSettledDebit()).add(safeBD(obligationByMoney.getBalance())));
} else if (equalsByRegistry(AM_B, relatedRegistry)) {
relatedRegistry.setBalance(safeBD(relatedRegistry.getBalance()).add(safeBD(obligationByMoney.getBalance())));
}
registryImdg.update(relatedRegistry);
}
}
log.debug("changing assets by CM*T");
List<Registry> requirementsByMoney = rgsAll.stream()
.filter(registry -> equalsByRegistry(CM_T, registry))
.toList();
//изменяем активы по требованиям по деньгам CM_T
for (Registry requirementByMoney : requirementsByMoney) {
String sql = String.format("tradingClearingRegistryId = %s and companyId = %s",
requirementByMoney.getTradingClearingRegistryId(), requirementByMoney.getCompanyId());
Collection<Registry> relatedRegistries = registryImdg.getCollectionObjectsBySQL(sql);
for (Registry relatedRegistry : relatedRegistries) {
if (equalsByRegistry(AM_T, relatedRegistry)) {
relatedRegistry.setSettledDebit(safeBD(relatedRegistry.getSettledDebit()).add(safeBD(requirementByMoney.getBalance())));
}
registryImdg.update(relatedRegistry);
}
}
List<PaymentInstruction> formedPaymentInstructions = new ArrayList<>();
List<Registry> allLiabilities = rgsAll
.stream()
.filter(registry -> RegistryDesignation.L.equalsByKey(registry.getRegistryDesignation()))
.toList();
//todo сортировка if needed
for (int i = 0; i < allLiabilities.size(); i++) {
Registry lm_t = allLiabilities.get(i);
if (lm_t == null) continue;
LinkedList<Registry> relatedRegistries = new LinkedList<>();
relatedRegistries.add(lm_t);
for (int j = i + 1; j < allLiabilities.size(); j++) {
Registry related = allLiabilities.get(j);
if (related == null) continue;
if (registriesOfTheSameAgents(lm_t, related)) {
relatedRegistries.add(related);
allLiabilities.set(j, null);
}
}
log.trace("LM*T.id={} return group size {}", lm_t.getId(), relatedRegistries.size());
BigDecimal sumBalance = relatedRegistries.stream().map(Registry::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
log.trace("LM*T.id={} sumBalance={}", lm_t.getId(), sumBalance);
List<Registry> builderList = new ArrayList<>();
builderList.add(lm_t);
rgsAll.stream()
.filter(rgs -> rgs.getGroupId().equals(lm_t.getGroupId()))
.filter(rgs -> RegistryDesignation.C.equalsByKey(rgs.getRegistryDesignation()))
.findFirst()
.ifPresent(builderList::add);
PaymentInstruction paymentInstruction = createPaymentInstruction(builderList, sumBalance, sessionId);
formedPaymentInstructions.add(paymentInstruction);
paymentInstructionImdg.insert(paymentInstruction);
log.trace("LM*T.id={} created paymentInstruction.id={}", lm_t.getId(), paymentInstruction.getId());
builderList.forEach(registry -> {
registry.setPaymentId(paymentInstruction.getId());
registry.setUpdated(Instant.now());
registryImdg.update(registry);
});
}
//sdf отправляют
//sendSdfs(formedPaymentInstructions);
StageResult<Collection<PaymentInstruction>> stageResult = new StageResult(null, true);
stageResult.setStageResult(formedPaymentInstructions);
return stageResult;
}
private void sendSdfs(List<PaymentInstruction> formedPaymentInstructions) {
List<SDf03> sDf03Created = new ArrayList<>();
List<SDf12> sDf12Created = new ArrayList<>();
for (PaymentInstruction paymentInstruction : formedPaymentInstructions) {
Security security = securityImdg.getSingleObjectByID(paymentInstruction.getCreditLeg_securityId());
Account account = accountImdg.getSingleObjectByID(paymentInstruction.getCreditLeg_accountId());
if (InstrumentType.CRNC.equalsByKey(security.getInstrumentType()) &&
List.of(AccountType.Corr, AccountType.Clrn).contains(IEnumKey.getEnumByKey(AccountType.class, account.getAccountType()))) {
sDf03Created.add(newSDf03(paymentInstruction));
} else if (!InstrumentType.CRNC.equalsByKey(security.getInstrumentType()) &&
AccountType.Depo.equalsByKey(account.getAccountType())) {
sDf12Created.add(newSDf12(paymentInstruction));
}
}
Long sdf03GroupId = !sDf03Created.isEmpty() ? imdgProvider.getImdgIdGenerator().nextId() : null;
for (SDf03 sDf03 : sDf03Created) {
sDf03.setGenerationId(sdf03GroupId);
sDf03Imdg.insert(sDf03);
}
if (sdf03GroupId != null) {
ExportToFileRequest exportToFileRequest = new ExportToFileRequest();
exportToFileRequest.setNameOfTable("DF-03");
exportToFileRequest.setSdfGroupId(sdf03GroupId);
kafkaSender.sendRequestToQueue(Consts.EXPORT_PROCESS, exportToFileRequest);
}
Long sdf12GroupId = null;
Long maxTxNumber = 1L;
if (!sDf12Created.isEmpty()) {
sdf12GroupId = imdgProvider.getImdgIdGenerator().nextId();
ImdgPredicateBuilder predicateBuilder = sDf12Imdg.predicateBuilder();
ImdgPredicate notEmptyTransactionNum = predicateBuilder.not(predicateBuilder.equals("transaction_number", ""));
Long maxId = sDf12Imdg.aggregateLongMax("id", notEmptyTransactionNum);
if (maxId != null) {
SDf12 sDf12 = sDf12Imdg.getSingleObjectByID(maxId);
maxTxNumber = Long.parseLong(sDf12.getTransactionNumber()) + 1;
}
}
for (SDf12 sDf12 : sDf12Created) {
sDf12.setGenerationId(sdf03GroupId);
sDf12.setTransactionNumber(maxTxNumber.toString());
sDf12.setTransactionQuantity(String.valueOf(sDf12Created.size()));
sDf12Imdg.insert(sDf12);
}
if (sdf12GroupId != null) {
SwtExporterRequest swtExporterRequest = new SwtExporterRequest();
swtExporterRequest.setType("SDF_12");
kafkaSender.sendRequestToQueue(Consts.SWT_EXPORTER, swtExporterRequest);
}
}
private PaymentInstruction createPaymentInstruction(List<Registry> registries, BigDecimal balance, Long sessionId) {
PaymentInstructionBuilder paymentInstructionBuilder = PaymentInstructionBuilder.builder(imdgProvider, registries)
.sessionId(sessionId)
.amount(balance);
return paymentInstructionBuilder.build();
}
private SDf03 newSDf03(PaymentInstruction paymentInstruction) {
log.debug("creating sdf03");
SDf03 sDf03 = new SDf03();
sDf03.setId(idGenerator.nextId());
sDf03.setSeg_type("S");
sDf03.setDoc_type("002");
String strId = paymentInstruction.getId().toString();
String strIdCut = strId.length() > 16 ? strId.substring(strId.length() - 16) : strId;
sDf03.setDocnm_ref(strIdCut);
sDf03.setC_acc_deb(paymentInstruction.getCreditLeg_account());
String senderSbankName = "";
if (paymentInstruction.getSenderId().equals(1L)) {
senderSbankName = paymentInstruction.getPayeeBankName();
} else {
Company company = companyImdg.getSingleObjectByID(paymentInstruction.getSenderId());
if (company != null) {
senderSbankName = company.getShortName();
}
}
sDf03.setSbanknam1(senderSbankName);
sDf03.setSbanknam2(senderSbankName);
sDf03.setSbanknam3(senderSbankName);
sDf03.setSbanknam4(senderSbankName);
sDf03.setSbanknam5(senderSbankName);
sDf03.setC_acc_cred(paymentInstruction.getDebitLeg_account());
String addresseeSbankName = "";
if (paymentInstruction.getAddresseeId().equals(1L)) {
addresseeSbankName = paymentInstruction.getAddresseeBankName();
} else {
Company company = companyImdg.getSingleObjectByID(paymentInstruction.getAddresseeId());
if (company != null) {
addresseeSbankName = company.getShortName();
}
}
sDf03.setRbanknam1(addresseeSbankName);
sDf03.setRbanknam2(addresseeSbankName);
sDf03.setRbanknam3(addresseeSbankName);
sDf03.setRbanknam4(addresseeSbankName);
sDf03.setRbanknam5(addresseeSbankName);
sDf03.setPay_date(payDateFormatter.format(TimeUtil.toLocalDate(paymentInstruction.getPaymentDate())));
sDf03.setPay_val("RUR");
sDf03.setSum_deb(paymentInstruction.getDebitLeg_amount() != null ? paymentInstruction.getDebitLeg_amount().toString() : "");
sDf03.setSpecif_1(paymentInstruction.getPaymentPurpose());
sDf03.setGenerationTime(Instant.now());
sDf03.setPaymentInstructionId(paymentInstruction.getId());
log.debug("successfully processed, new id {}", sDf03.getId());
return sDf03;
}
private SDf12 newSDf12(PaymentInstruction paymentInstruction) {
log.debug("creating sdf12");
SDf12 sDf12 = new SDf12();
sDf12.setId(idGenerator.nextId());
sDf12.setOutDocument(sDf12.getId().toString());
sDf12.setDirection("DELFREE");
sDf12.setQuantity(paymentInstruction.getCreditLeg_amount().toString());
sDf12.setSecurityCode(paymentInstruction.getCreditLeg_securityId().toString());
sDf12.setDepoCodeSender(paymentInstruction.getCreditLeg_account());
sDf12.setDepoCodeAdressee(paymentInstruction.getDebitLeg_account());
// sDf12.setTransactionNumber();
sDf12.setGenerationTime(Instant.now());
return sDf12;
}
private BigDecimal safeBD(BigDecimal value) {
return value != null ? value : BigDecimal.ZERO;
}
DateTimeFormatter payDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yy");
private boolean registriesOfTheSameAgents(Registry rgs1, Registry rgs2) {
return Objects.equals(rgs1.getSecurityId(), rgs2.getSecurityId())
&& Objects.equals(rgs1.getTradingClearingRegistryId(), rgs2.getTradingClearingRegistryId())
&& Objects.equals(rgs1.getCompanyId(), rgs2.getCompanyId())
&& Objects.equals(rgs1.getCounterPartyId(), rgs2.getCounterPartyId());
}
private static boolean equalsByRegistry(RegistryTradingParams code, Registry rgs) {
return code.equalByRegistry(
IEnumKey.getEnumByKey(RegistryDesignation.class, rgs.getRegistryDesignation()),
IEnumKey.getEnumByKey(RegistryInstrumentType.class, rgs.getRegistryInstrumentType()),
IEnumKey.getEnumByKey(RegistryCapacity.class, rgs.getRegistryCapacity()),
IEnumKey.getEnumByKey(RegistryUnit.class, rgs.getRegistryUnit())
);
}
}

View file

@ -0,0 +1,29 @@
package ru.spcex.clearing.session.stage.task;
import ru.clearing.classes.statics.data.payment.PaymentInstruction;
import java.util.Collection;
public class FormingPaymentInstructionDealsMkrPayload {
private Long sessionId;
/**
* для МКР итоговой сессии SDF будет отправляться по 1. возвратам 2. сделкам
* соотв. поле нужно чтобы передать сделанные пейменты из пункта 1 в 2
*/
private Collection<PaymentInstruction> paymentInstructionReturns;
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
public Collection<PaymentInstruction> getPaymentInstructionReturns() {
return paymentInstructionReturns;
}
public void setPaymentInstructionReturns(Collection<PaymentInstruction> paymentInstructionReturns) {
this.paymentInstructionReturns = paymentInstructionReturns;
}
}