import com.haulmont.cuba.core.entity.KeyValueEntity;
import com.haulmont.cuba.core.global.*;
import com.groupstp.rtneo.entity.*;
import com.groupstp.rtneo.service.*;
import com.groupstp.rtneo.core.bean.tools.DatePeriodTools
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.global.ViewRepository;
import com.haulmont.cuba.core.global.View;
isAdjustmentT(2164833)
private boolean isAdjustmentT(int number) {
ViewRepository vRep = AppBeans.get(ViewRepository.NAME)
DatePeriodTools datePeriodTools = AppBeans.get(DatePeriodTools.class)
CalculationService calculationService = AppBeans.get(CalculationService.NAME)
KeyValueEntity value = dataManager.loadValues('select a.contragent.id, a.contragent.inn, a.contragent.kpp, max(a.period) from rtneo$Accrual a where a.documentNumber = :number group by a.contragent.id')
.properties('id','inn', 'kpp', 'period')
.parameter('number', number)
.optional()
.orElse(null);
UUID contragentId = value.getValue('id');
String inn = value.getValue('inn');
String kpp = value.getValue('kpp');
_(inn)
Date accrualPeriod = value.getValue('period');
KeyValueEntity adjNumber = dataManager.loadValues('select a.number from rtneo$Acts a where a.inn = :inn and a.kpp = :kpp and a.period = :period and a.adjustments is not null')
.properties('number')
.parameter('period', accrualPeriod)
.parameter('inn', inn)
.parameter('kpp', kpp)
.optional().orElse(null);
//Возможно что если есть корректировки, печатать не корректировки?
if(adjNumber != null)return true;
BigDecimal sumAccrual = dataManager.loadValue('select sum(a.sum) from rtneo$Accrual a where a.documentNumber = :number', BigDecimal.class)
.parameter('number', number)
.optional()
.orElse(null);
if (sumAccrual == null) return false;
BigDecimal finalSumAccrual = sumAccrual.setScale(3, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_UP);
//При принятии допа создаем акты на перерасчет(вынести это)
//Почему при принятии
Calendar start2019 = Calendar.getInstance();
start2019.set(2019, 0, 01, 0, 0, 0);
calculationService.getActs(inn, kpp, start2019.getTime(), datePeriodTools.getEndOfCurrentYear());
View actView = vRep.getView(Acts.class, "_local").addProperty("createTs");
//Проверяем, есть ли акты
List<Acts> acts = dataManager.load(Acts.class)
.query('select a from rtneo$Acts a where a.inn = :inn and a.kpp = :kpp and a.period = :period')
.parameter('inn', inn)
.parameter('kpp', kpp)
.parameter('period', accrualPeriod)
.view(actView)
.list();
_(acts.size())
_("${finalSumAccrual}")
acts.each{_(it, "json").toString()+_(" = ${it.getSum().add(it.getSum_nds()).subtract(finalSumAccrual)}").toString()}
// acts.each{_("id- ${it.getId()}; createTs - ${it.getCreateTs()} - sumRes - ${it.getSum().add(it.getSum_nds()).subtract(finalSumAccrual)}")}
// _(acts.stream().sorted{o1, o2 -> -1*o1.getCreateTs().compareTo(o2.getCreateTs())}.forEach{e -> _("${e.getId()} - ${e.getCreateTs()}")})
_("=============================")
_(acts.stream().filter{e -> (e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(0.05)) <= 0
|| e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(-0.05)) >= 0)}
.sorted{o1, o2 -> -1*o1.getCreateTs().compareTo(o2.getCreateTs())}.forEach{e -> _("${e.getId()} - ${e.getCreateTs()}")})
_(acts.stream().filter{e -> (e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(0.05)) <= 0
|| e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(-0.05)) >= 0)}
.sorted{o1, o2 -> -1*o1.getCreateTs().compareTo(o2.getCreateTs())}.findFirst().orElse(null))
//// if (acts.size() == 0) return false;
// if (acts.size() <= 1){
// _(contragentId)
// _(accrualPeriod)
// List<KeyValueEntity> totalSumContractsForPeriod = dataManager.loadValues('select a.contractPosition.contract.id, a.contractPosition.contract.number, sum(a.totalSum) ' +
// 'from rtneo$Accrual a ' +
// 'where a.contragent.id = :contragent ' +
// 'and a.contractPosition.contract.accepted = true ' +
// 'and a.period = :period ' +
// 'group by a.contractPosition.contract.id order by a.contractPosition.contract.createTs')
// .properties('contractId', 'contractNumber', 'totalSum')
// .parameter('contragent', contragentId)
// .parameter('period', accrualPeriod)
// .list();
// //Уточнить логику. Если идут подряд 2 договора с одной суммой, а третий с другой. Какая корректировка должна быть?
//// BigDecimal maxTotalSum = totalSumContractsForPeriod.stream().map{e->e.getValue('totalSum')}.max{a,b -> a.compareTo(b)}.orElse(BigDecimal.ZERO);
//// _(maxTotalSum)
//// BigDecimal minTotalSum = totalSumContractsForPeriod.stream().map{e->e.getValue('totalSum')}.min{a,b -> a.compareTo(b)}.orElse(BigDecimal.ZERO);
//// _(minTotalSum)
//// if(maxTotalSum.compareTo(minTotalSum) != 0){
//// return true;
//// }
//
//
// }
//Если все акты по сумме равны сумме начисления, возвращаем ложь
// if(!acts.stream().anyMatch(e->!e.getSum().add(e.getSum_nds()).setScale(2, BigDecimal.ROUND_UP).equals(sumAccrual)))return false;
/*
BigDecimal tst = BigDecimal.valueOf(0.03);
tst.compareTo(BigDecimal.valueOf(0.02)) <=0 && tst.compareTo(BigDecimal.valueOf(-0.02)) >=0
*/
_("Return ...")
if (acts.stream().anyMatch{e -> (e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(0.05)) <= 0
|| e.getSum().add(e.getSum_nds()).subtract(finalSumAccrual).compareTo(BigDecimal.valueOf(-0.05)) >= 0)}
)return true;
_("Return OK!")
//Учитывать погрешность 2 коп
// if(!acts.stream().anyMatch(e->!e.getSum().add(e.getSum_nds()).setScale(2, BigDecimal.ROUND_UP) == sumAccrual))return false;
//Если суммы равны печатаем УПД с номером из 1С
return false;
}
/**
* Логирование
*/
import com.haulmont.cuba.core.app.serialization.EntitySerializationAPI;
import com.groupstp.rtneo.util.JsonUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private _(Object obj, String... options){
if(obj == null){log("LOG.ERROR: Object is null!!!");return}
if(options.size() == 0){log(obj)}
for(def option : options){
if(option.equals("str")){log(obj)}
if(option.equals("for")){obj.each({_(it)})}
if(option.equals("json")){
EntitySerializationAPI entitySerializationAPI = AppBeans.get(EntitySerializationAPI.NAME)
try{log(entitySerializationAPI.toJson(obj))}
catch(Exception e){log("LOG.ERROR: JSON entity serialization failed")}
}
if(option.equals("objJson")){
JsonUtil jsonUtil = AppBeans.get(JsonUtil.NAME)
try{log.(jsonUtil.toJson(obj))}
catch(Exception e){log("LOG.ERROR: JSON object serialization failed")}
}
if(option.equals("date")){
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
try{log(df.format(obj))}
catch(Exception e){log("LOG.ERROR: Failed date format")}
}
}
}
private log(Object obj){log.debug(obj)}