import com.groupstp.rtneo.core.bean.tools.DatePeriodTools
import com.groupstp.rtneo.entity.Accrual
import com.groupstp.rtneo.entity.Contract
import com.groupstp.rtneo.entity.ContractPosition
import com.groupstp.rtneo.entity.Contragent
import com.groupstp.rtneo.entity.ContragentRealEstate
import com.groupstp.rtneo.entity.Payment
import com.haulmont.cuba.core.app.FileStorageAPI
import com.haulmont.cuba.core.entity.FileDescriptor
import com.haulmont.cuba.core.entity.KeyValueEntity
import com.haulmont.cuba.core.global.AppBeans
import com.haulmont.cuba.core.global.DataManager
import com.haulmont.cuba.core.global.FluentLoader
import com.haulmont.cuba.core.global.UuidProvider
import com.haulmont.cuba.core.global.ViewRepository;
import com.haulmont.cuba.core.global.View
import com.opencsv.CSVReader
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.diedavids.cuba.runtimediagnose.groovy.*
import groovy.transform.InheritConstructors;
import java.text.SimpleDateFormat
import java.util.function.BiPredicate
import java.util.function.Predicate
import java.util.stream.Collectors;
long st = System.currentTimeMillis();
dataManager = AppBeans.get(DataManager.class)
//dateView = new SimpleDateFormat("dd-MM-yyyy")
dateView = new SimpleDateFormat("yyyy-MM-dd")
datePeriodTools = AppBeans.get(DatePeriodTools.class)
Date reportStart = dateView.parse("2020-07-01")
Date reportStop = to = dateView.parse("2020-09-30")
Date paymentLimitDate = dateView.parse('2020-10-23')
contractLimit = dateView.parse("2020-12-31")
Date from = dateView.parse("2019-01-01")
Date to = dateView.parse("2020-12-31")
tariffs = dataManager.loadValues('select t.tariff*1.2, t.dateSince, t.dateTill from rtneo$Tariff t where t.name = 1')
.properties("tariff", "from", "to")
.list()
//Коллекция исключенных объектов
Map<String, String> excluded = new HashMap<>()
long pr = System.currentTimeMillis();
_("Pre start ${pr-st}");
//ContragentsSupplier supplier = new ContragentById(log)
//supplier.setContragent_id('fabf3200-0a3f-3185-31c3-5137da056284')
ContragentsSupplier supplier = new ContragentsNoFact(log)
supplier.setFirstResult(0)
supplier.setMaxResults(100)
supplier.setFilter(true)
//supplier.setPredicates(getPredicators())
//FileDescriptor excludeFile = dataManager.load(FileDescriptor.class)
// .id(UuidProvider.fromString('308e6069-5d3a-aee2-01b5-e3d6761ce573'))
// .view(View.MINIMAL)
// .optional().orElse(null);
//supplier.setExcludeFileId(excludeFile)
List<Contragent> contragents = supplier.getContragents()
long ft = System.currentTimeMillis();
_("Get contragents ${ft-pr}");
TreeMap<String, Object> contragentsGroup = getContragentsGroup(contragents, paymentLimitDate, from, to)
long pa = System.currentTimeMillis();
_("Payments & Accruals ${pa-ft}");
//Форматируем данные для вывода
HashMap<String, Object> res = getFormatData(contragentsGroup)
long mr = System.currentTimeMillis();
_("More ${mr-pa}");
printUPD(from, res, excluded, contractLimit, reportStart, reportStop)
printSummary(res, excluded)
private void printUPD(Date from, HashMap<String, Object> res, HashMap<String, String> excluded, Date contractLimit, Date reportStart, Date reportStop) {
Calendar endMonth = Calendar.getInstance();
endMonth.setTime(from);
List<String> totalsNullAccrualContract = new ArrayList<>()
HashMap<String, List<Object>> zeroMap = new HashMap<>()
List<Object> zeroList = new ArrayList<>()
List<Object> excledeOutList = new ArrayList<>()
_("!Наименование услуги!Дата договора!Основной договор!Номер УПД!Дата УПД!Дата корр.!ИНН!КПП!ЛС!Объем!Цена без НДС!Сумма без НДС!НДС!Цена с НДС!Оплачен период!Остаток на начало периода")
for (def itemRes : res) {
if (excluded.keySet().stream().anyMatch { e -> e.equals(itemRes.getValue()['inn']) }) continue
List<Contract> contractList = dataManager.load(Contract.class)
.query('select c from rtneo$Contract c where c.contragent.id = :contragent and c.accepted is not null and c.accepted = true and not (c.createTs > :contractLimit and c.createdBy = \'a.kotvinskiy@groupstp.ru\') order by c.createTs')
.parameter("contragent", itemRes.getValue()['id'])
.parameter("contractLimit", contractLimit)
.view("contract-browse")
.list()
Boolean keyOutput = false
def excledeOut = false
HashMap<String, Object> excludeMap = new HashMap<>()
for (def item : itemRes.getValue()['accruals']) {
def total = item.getValue().getValue()
//Если период начислени я меньше даты начала, пропускаем
if (dateView.parse(item.getKey()).compareTo(reportStart) < 0) continue
if (dateView.parse(item.getKey()).compareTo(reportStop) > 0) continue
//Выводим один не оплаченный месяц
if (total['done'] != true && !keyOutput) {
keyOutput = true
} else if (total['done'] != true && keyOutput) {
continue
}
//Условие чтобы, за 2020 год не выводилоась запись, если оплаты кончились раньше. Переделать
if (from != reportStart) {
if (dateView.parse(total['period'].toString()).compareTo(reportStart) == 0 && total['residue'] <= 0 && !total['residue']) excledeOut = true
}
//Дата текстом и числом для вывода
endMonth.setTime(dateView.parse(total['period'].toString()));
endMonth.set(Calendar.DAY_OF_MONTH, endMonth.getActualMaximum(Calendar.DAY_OF_MONTH))
def month = getTextPeriod(dateView.parse(total['period']))
if (excledeOut) {
excludeMap.put("inn", itemRes.getValue()['inn'])
excludeMap.put("kpp", itemRes.getValue()['kpp'])
} else {
log.debug("!Услуга Регионального оператора по обращению с ТКО за ${month}!!!!${dateView.format(endMonth.getTime())}!!${itemRes.getValue()['inn']}!${itemRes.getValue()['kpp']}!${itemRes.getValue()['pa']}!!!!!!${total['done'] == true ? 'да' : 'нет'}!${total['residue']}")
}
List<HashMap> itemsList = getFormatFields(contractList, total, endMonth)
if (itemsList.isEmpty()) {
//Вынести сообщения
// _("${itemRes.getValue()['id']} itemList empty")
continue
}
//Порядок вывода реализации и исправления
//реализация
Boolean print1Contract = false
//Исправление
Boolean print2Contract = false
(print1Contract, print2Contract) = setRuleOutAccrual(itemsList)
if (excledeOut) {
if (print1Contract) {
excludeMap.put("number", itemsList.get(0).get("number"))
excledeOutList.add(excludeMap)
}
if (print2Contract) {
def excludeMapC = new HashMap<>(excludeMap)
excludeMapC.put("number", itemsList.get(itemsList.size() - 1).get("number"))
excledeOutList.add(excludeMapC)
}
} else {
if (print1Contract) printItemFromResultMap(itemsList.get(0))
if (print2Contract) printItemFromResultMap(itemsList.get(itemsList.size() - 1))
}
}
}
// excledeOutList.each{
// if(it instanceof HashMap){
// _("|${it.get('inn')}|${it.get('kpp')}|${it.get('number')}")
// }else{
// _(it)
// }
// }
}
private void printSummary(LinkedHashMap<Object, Object> res, HashMap<String, String> excluded) {
_("|Наименование|ЛС|ИНН|КПП|Объем|Сумма всего|Сумма 2019|Сумма 2020|Остаток|Последний оплаченный период")
for (def item : res) {
def rAmount = BigDecimal.ZERO
def rTotalSum = BigDecimal.ZERO
def payTotalSum = BigDecimal.ZERO
def period
def lastPeriod = false
def isHide = false
def totalSum19 = BigDecimal.ZERO
def totalSum20 = BigDecimal.ZERO
HashMap<String, Object> mapResults = new HashMap<>()
for (def accrual : item.getValue()['accruals']) {
// _(accrual)
if (lastPeriod) continue
if (!accrual.getValue().getValue()['done']) lastPeriod = true
if (!lastPeriod) {
period = accrual.getValue().getValue()['period']
payTotalSum += accrual.getValue().getValue()['totalSum']
}
def currPeriod = dateView.parse(accrual.getValue().getValue()['period'])
if (currPeriod.compareTo(dateView.parse('2020-01-01')) < 0) {
totalSum19 += accrual.getValue().getValue()['totalSum']
} else {
totalSum20 += accrual.getValue().getValue()['totalSum']
}
rAmount += accrual.getValue().getValue()['amountBase']
rTotalSum += accrual.getValue().getValue()['totalSum']
}
// if(totalSum20 == 0)isHide = true
rTotalSum = rTotalSum.setScale(2, BigDecimal.ROUND_HALF_DOWN)
mapResults.put("name", item.getValue()['name'])
mapResults.put("pa", item.getValue()['pa'])
mapResults.put("inn", item.getValue()['inn'])
mapResults.put("kpp", item.getValue()['kpp'])
mapResults.put("amount", rAmount.setScale(5, BigDecimal.ROUND_HALF_DOWN))
mapResults.put("totalSum", rTotalSum.setScale(2, BigDecimal.ROUND_HALF_DOWN))
mapResults.put("totalSum19", totalSum19.setScale(2, BigDecimal.ROUND_HALF_DOWN))
mapResults.put("totalSum20", totalSum20.setScale(2, BigDecimal.ROUND_HALF_DOWN))
mapResults.put("payments", (item.getValue()['sumPayments'] as BigDecimal).setScale(2, BigDecimal.ROUND_HALF_DOWN))
// def balance = item.getValue()['sumPayments'].compareTo(rTotalSum) < 0 ? item.getValue()['sumPayments'] : item.getValue()['sumPayments'] - rTotalSum
def balance = item.getValue()['sumPayments'] - payTotalSum
mapResults.put("balance", balance.setScale(2, BigDecimal.ROUND_HALF_DOWN))
mapResults.put("period", period)
// _(mapResults)
if (excluded.keySet().stream().anyMatch { e -> e.equals(item.getValue()['inn']) }) continue
if (!isHide) printItemFromResultMapMin(mapResults)
}
}
_('****************************************************************************')
//HashSet(totalsNullAccrualContract).each{_(it)}
return true;
void printItemFromResultMapMin(HashMap<String, Object> current){
_("|${current.get('name')}|${current.get('pa')}|${current.get('inn')}|${current.get('kpp')}|${current.get('amount')}|${current.get('totalSum')}|${current.get('totalSum19')}|${current.get('totalSum20')}|${current.get('balance')}|${current.get('period')}".replaceAll("\\p{Cntrl}", ""))
}
abstract class ContragentsSupplier{
DataManager dataManager = AppBeans.get(DataManager.class)
List<Predicate<Contragent>> predicates = new ArrayList<>();
Boolean filter = false
FileDescriptor excludeFileId;
GroovyConsoleLogger log;
ContragentsSupplier(){
}
ContragentsSupplier(GroovyConsoleLogger log){
this.log = log
}
abstract List<Contragent> contragentsLoad()
List<Contragent> getContragents(){
List<Contragent> contragents;
contragents = contragentsLoad()
this.predicates = getPredicators(contragents)
if(filter){
contragents = filterContragent(contragents)
}
if(excludeFileId != null){
contragents = excludeFromFile()
}
return contragents;
}
View createView(){
ViewRepository vRep = AppBeans.get(ViewRepository.NAME)
return vRep.getView(Contragent.class, "_minimal")
.addProperty("inn")
.addProperty("kpp")
.addProperty("name")
.addProperty("personalAccount")
}
List<Contragent> filterContragent(List<Contragent> contragents){
return contragents.stream()
.filter{c -> predicates.stream().map{p->p as Predicate<Contragent>}.allMatch{p -> p.test(c)}}
.collect(Collectors.toList())
// .filter{allPredicates.stream().reduce{a,b -> a.and(b)}.get()}
// .filter{e -> allPredicates.inject(true, {a,b -> it.and})}
}
List<Contragent> excludeFromFile(List<Contragent> contragents){
List<String> exclude = inToFile(excludeFileId)
return contragents.stream().filter{e -> !exclude.contains(e.getInn())}.collect()
}
List<String> inToFile(FileDescriptor fd){
if(fd == null){throw new RuntimeException("fileNotFound")}
FileStorageAPI fileStorageAPI=AppBeans.get(FileStorageAPI.NAME);
InputStream inputStream=fileStorageAPI.openStream(fd)
CSVReader reader = new CSVReader(new InputStreamReader(inputStream, "UTF-8"));
return reader.readAll().stream()
.map{e->e[0]}.collect(Collectors.toList())
}
List<Predicate<Contragent>> getPredicators(List<Contragent> contragents){
List<Predicate<Contragent>> allPredicates = new ArrayList<>()
allPredicates.add({c->
if(contragents.stream().filter{e->e.getInn() == c.getInn()}.count() == 1){
return true
}else{
log.debug("Is filial ${c.getInn()}")
return false
}
})
return allPredicates
}
}
@InheritConstructors
class ContragentsNoFact extends ContragentsSupplier{
def firstResult = 0
def maxResults = 0
@Override
List<Contragent> contragentsLoad(){
String query = 'select distinct c ' +
'from rtneo$Payment e ' +
' join rtneo$Contragent c on e.inn = c.inn ' +
' where not e.inn is null and not c.type = 4 ' +
'order by c.inn ' +
'except ' +
'select distinct ct.contragent ' +
'from rtneo$Contragent c ' +
' join rtneo$Contract ct on c.id = ct.contragent.id ' +
'where ' +
' ct.isFactCalculation = true and ct.accepted = true ' +
'order by c.inn'
FluentLoader.ByQuery load = dataManager.load(Contragent.class)
.query(query)
.view(createView())
if(firstResult != 0)load.firstResult(firstResult)
if(maxResults != 0)load.maxResults(maxResults)
return load.list()
}
}
@InheritConstructors
class ContragentsImplOld extends ContragentsSupplier{
@Override
List<Contragent> contragentsLoad(){
String oldQuery = 'select ' +
'distinct c.id, c.inn, c.kpp, c.personalAccount, (select count(ct) from rtneo$Contract ct where ct.contragent.id = c.id and ct.accepted = true and ct.isFactCalculation = true) ' +
'from rtneo$Payment e join rtneo$Contragent c on e.inn = c.inn ' +
'where not e.inn is null and e.createTs <= :paymentLimitDate order by c.inn'
List<Contragent> contragents = dataManager.load(Contragent.class)
.query(query)
// .parameter("paymentLimitDate", paymentLimitDate)
.firstResult(0)
.maxResults(10)
.view(createView())
.list()
return contragents
}
}
@InheritConstructors
class ContragentById extends ContragentsSupplier{
String contragent_id;
@Override
List<Contragent> contragentsLoad() {
String query = 'select c from rtneo$Contragent c where c.id = :contragent_id'
List<Contragent> contragents = dataManager.load(Contragent.class)
.query(query)
.parameter("contragent_id", UUID.fromString(contragent_id))
.view(createView())
.list()
return contragents
}
}
def setRuleOutAccrual(List<HashMap> itemsList){
//реализация
Boolean print1Contract = false
//Исправление
Boolean print2Contract = false
if(itemsList.size()>=1){
//mapResults.put("cdate", contract.getMainContract() == null ? dateView.format(contract.getDate()) : '')
//Если это доп и он один, или это основной договор, выводим
if(itemsList.get(0).get('cdate').equals('')){
if(itemsList.size() == 1)print1Contract = true
}else{
print1Contract = true
}
if(itemsList.size()>1){
//Если начисление не по допу, и дата контракта меньше 20-го, реализацию по нему не выводим
//Только 20го года Сделать условие!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if(!itemsList.get(0).get('cdate').equals('') && dateView.parse(itemsList.get(0).get('cdate')).compareTo(dateView.parse('01-01-2020')) < 0)print1Contract = false
//Если первое начисление не по допу и последнее не по допу, скрываем реализацию?? Странное условие
if(!itemsList.get(0).get('cdate').equals('') && !itemsList.get(itemsList.size()-1).get('cdate').equals('')){
print1Contract = false
}
// if(itemsList.get(0).get('cdate').equals('') && itemsList.get(itemsList.size()-1).get('cdate').equals(''))itemsList.get(itemsList.size()-1)['dateCor'] = ''
//Если сумма реализации(первое начисление) совпадает с исправлением, реализацию не выводим
if(itemsList.get(0).get('totalSum').equals(itemsList.get(itemsList.size()-1).get('totalSum')))print1Contract = false
//Исправление выводим всегда
print2Contract = true
}
return [print1Contract, print2Contract]
}
}
private List<HashMap> getFormatFields(List<Contract> contractList, total, Calendar endMonth) {
List<HashMap> itemsList = new ArrayList<>()
for (Contract contract : contractList) {
KeyValueEntity totalAccrualContract = dataManager.loadValues('select a.documentNumber, max(a.period), sum(a.amountBase), sum(a.amountBase)*max(a.price), max(a.price), sum(a.ndsSum), sum(a.totalSum), sum(a.totalSumBase) from rtneo$Accrual a where a.contractPosition.contract.id = :contract and a.period = :period group by a.documentNumber')
.properties("number", "period", "amount", "totalSumWithNDS", "price", "totalNDS", "totalSum", "totalSumBase")
.parameter("contract", contract.getId())
.parameter("period", dateView.parse(total['period']))
.optional()
.orElse(null)
// if(totalAccrualContract == null){
// totalsNullAccrualContract.add(itemRes.getValue()['inn'])
// continue
// }
String mainContractNumber = contract.getMainContract() != null ? contract.getMainContract().getNumber() : ''
HashMap<String, Object> mapResults = new HashMap<>()
if (totalAccrualContract == null) {
// _("!${contract.getNumber()}!No accruals in to period")
} else {
mapResults.put("cnumber", contract.getNumber())
mapResults.put("cdate", contract.getMainContract() == null ? dateView.format(contract.getDate()) : '')
mapResults.put("cmnumber", mainContractNumber)
mapResults.put("number", totalAccrualContract.getValue('number'))
mapResults.put("period", dateView.format(endMonth.getTime()))
mapResults.put("dateCor", contract.getMainContract() != null ? dateView.format(contract.getDate()) : '')
mapResults.put("amount", totalAccrualContract.getValue('amount'))
mapResults.put("price", totalAccrualContract.getValue('price') * 5 / 6)
def totalNDS = totalAccrualContract.getValue('totalNDS') == null ? BigDecimal.ZERO : totalAccrualContract.getValue('totalNDS')
mapResults.put("totalSumNoNDS", totalAccrualContract.getValue('totalSum') - totalNDS)
mapResults.put("totalNDS", totalNDS)
mapResults.put("totalSum", totalAccrualContract.getValue('totalSum'))
if (!(totalAccrualContract.getValue('totalSum').compareTo(totalAccrualContract.getValue('totalSumBase')) == 0)) {
mapResults.put('amount', totalAccrualContract.getValue('totalSum') / totalAccrualContract.getValue('price'))
}
// accrualsGroup.each{
// if(!(it.getValue()['totalSum'].compareTo(it.getValue()['totalSumBase']) == 0)){
// BigDecimal noNdsSum = it.getValue()['totalSum']/(100+it.getValue()['nds'])*100
// it.getValue().put('amountBase', noNdsSum/it.getValue()['tariff'])
// // excluded.putIfAbsent(contragent.getValue('inn'), "discount")
// }
// }
itemsList.add(mapResults)
}
}
return itemsList
}
void printItemFromResultMap(HashMap<String, Object> current){
_("!${current.get('cnumber')}!${current.get('cdate')}!${current.get('cmnumber')}!${current.get('number')}!${current.get('period')}!${current.get('dateCor')}!!!!${current.get('amount')}!${current.get('price')}!${current.get('totalSumNoNDS')}!${current.get('totalNDS')}!${current.get('totalSum')}")
}
def getTextPeriod(Date date) {
def result=''
if (date != null) {
def monthesRP = ['январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь']
Calendar cal = Calendar.getInstance()
cal.setTime(date);
result+=monthesRP[cal.get(Calendar.MONTH)]
result+=" "+cal.get(Calendar.YEAR).toString()+" г."
}
return result
}
HashMap<String, Object> getFormatData(TreeMap<String, Object> contragentsGroup){
HashMap<String, Object> res = [:]
for(def contr : contragentsGroup){
def sumPay = 0
def residue = 0
contr.getValue()['payments'].each{p -> sumPay += p.getValue()['sum']}
res[contr.getValue()['inn']] = [
'id' : contr.getValue()['id'],
'inn' : contr.getValue()['inn'],
'kpp' : contr.getValue()['kpp'],
'name' : contr.getValue()['name'],
'pa' : contr.getValue()['pa'],
'sumPayments' : sumPay,
'accruals': [:]
]
// def accrual = []
//Проставляем признак оплаты за период
for(def accrualFor : contr.getValue()['accruals']){
if(sumPay > accrualFor.getValue()['totalSum']){
accrualFor.getValue()['done'] = true
}else{
accrualFor.getValue()['done'] = false
}
if(sumPay >= 0){
residue = sumPay
accrualFor.getValue()['residue'] = residue
}
sumPay -= accrualFor.getValue()['totalSum']
res[contr.getValue()['inn']]['accruals'][accrualFor.getValue()['period']]=accrualFor
}
}
return res
}
private TreeMap<String, Object> getContragentsGroup(List<Contragent> contragents, Date paymentLimitDate, Date from, Date to) {
TreeMap<String, Object> contragentsGroup = new TreeMap<>();
for (Contragent contragent : contragents) {
contragentsGroup.putIfAbsent(contragent.inn, [
'id' : contragent.id,
'inn' : contragent.inn,
'kpp' : contragent.kpp,
'name' : contragent.name,
'pa' : contragent.personalAccount,
'payments': [:],
'accruals': [:]
])
contragentsGroup[contragent.inn]['payments'] = getPayments(contragent, paymentLimitDate)
contragentsGroup[contragent.inn]['accruals'] = getAccruals(contragent, from, to)
contragentsGroup[contragent.inn]['accruals'].each {
if (!(it.getValue()['totalSum'].compareTo(it.getValue()['totalSumBase']) == 0)) {
BigDecimal noNdsSum = it.getValue()['totalSum'] / (100 + it.getValue()['nds']) * 100
it.getValue().put('amountBase', noNdsSum / it.getValue()['tariff'])
}
}
}
return contragentsGroup
}
HashMap<String, Object> getPayments(Contragent contragent, Date paymentLimitDate){
HashMap<String, Object> paymentsMap = new HashMap<>()
List<Payment> payments = getPaymentsContragent(contragent, paymentLimitDate)
for(def payment : payments){
String period = dateView.format(payment.getDate())
if(paymentsMap.get(period) == null){
paymentsMap[period] = ['purpose' : payment.purpose, 'sum' : payment.sum]
}else{
paymentsMap[period]['sum'] += payment.getSum()
}
}
return paymentsMap
}
HashMap<String, Object> getAccruals(Contragent contragent, Date dateFrom, Date dateTo){
Calendar from = dateFrom.toCalendar()
Calendar to = dateTo.toCalendar()
HashMap<String, Object> accrualsGroup = [:]
while(!from.after(to)){
List<Accrual> accruals = getBillsOnPeriod(UUID.fromString(contragent.id.toString()), from.getTime())
def roundingTarif = tariffs.stream()
.filter{e-> datePeriodTools.isPeriodIncluded(from.getTime(), e.getValue('from'), e.getValue('to'))}
.map{e-> e.getValue('tariff') as BigDecimal}.map{e-> e.setScale(5, BigDecimal.ROUND_HALF_UP)}
.findFirst().orElse(BigDecimal.ZERO)
for(def accrual : accruals){
if(accrual.getComment().equals("По факту")){
factAccrual = true
continue
}
if(accrual.getPrice() == null){
log.debug("${contragent.id} accrual.getPrice() is null !!!")
continue
}
def tariffNoNDS = NDStools.getSumWithoutNDS(accrual.getPrice())
String period = dateView.format(accrual.getPeriod())
if(accrualsGroup[period]==null){
accrualsGroup[period] = [
'period' : dateView.format(accrual.getPeriod()),
'number' : accrual.getDocumentNumber(),
'tariff' : tariffNoNDS,
'amountBase' : getNN(accrual.getAmountBase()),
'totalSumBaseNoNds' : getNN(accrual.getAmountBase())*tariffNoNDS,
'totalSumBase' : getNN(accrual.getTotalSumBase()),
'totalSum' : getNN(accrual.getTotalSum()),
'nds' : getNN(accrual.getNds()),
'residue' : 0,
'done' : false
]
}else{
accrualsGroup[period]['amountBase'] += getNN(accrual.getAmountBase())
accrualsGroup[period]['totalSumBaseNoNds'] += getNN(accrual.getAmountBase())*tariffNoNDS
accrualsGroup[period]['totalSumBase'] += getNN(accrual.getTotalSumBase())
accrualsGroup[period]['totalSum'] += getNN(accrual.getTotalSum())
}
}
from.add(Calendar.MONTH, 1)
}
return accrualsGroup
}
class NDStools{
static BigDecimal setNDS(BigDecimal sum){
return sum
}
static BigDecimal getNDS(BigDecimal sum){
return sum
}
static BigDecimal getSumWithoutNDS(BigDecimal sum){
return sum*5/6
}
}
List<Payment> getPaymentsContragent(Contragent contragent, Date paymentLimitDate){
//Нужно стандартизировать инн
return dataManager.load(Payment.class)
.query('select p from rtneo$Payment p where p.inn like :inn and p.createTs <= :paymentLimitDate')
.parameter('inn', "%%"+contragent.getValue('inn'))
.parameter("paymentLimitDate", paymentLimitDate)
.view('_local')
.list();
}
def getNN(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
List<Accrual> getBillsOnPeriod(UUID contragentID, Date period) {
ViewRepository viewRepository = AppBeans.get(ViewRepository.NAME)
View acView = viewRepository.getView(Accrual.class, "_local");
acView.addProperty("contractPosition", viewRepository.getView(ContractPosition.class, "_local")
.addProperty("contragentRealEstate", viewRepository.getView(ContragentRealEstate.class, "_local")))
.addProperty("createTs")
.addProperty("createdBy");
List<Contract> contracts = dataManager.load(Contract.class)
.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.accepted=true and not (e.createTs > :contractLimit and e.createdBy = \'a.kotvinskiy@groupstp.ru\') order by e.createTs desc')
.parameter("contragent", contragentID)
.parameter("contractLimit", contractLimit)
.view("_local")
.list();
if (contracts.size() == 0) {
contracts = dataManager.load(Contract.class)
.query('select e from rtneo$Contract e where e.contragent.id = :contragent and not (e.createTs > :contractLimit and e.createdBy = \'a.kotvinskiy@groupstp.ru\') order by e.createTs')
.parameter("contragent", contragentID)
.parameter("contractLimit", contractLimit)
.view("_local")
.list();
}
if (contracts.size() > 0) {
int i = 0;
Contract contract = contracts.get(i);
if (contract.getFrom() == null) return null;
while (contract.getFrom() != null & period.before(contract.getFrom())) {
i = i + 1;
if (i == contracts.size()) break;
contract = contracts.get(i);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (contract.getFrom() != null) {
List<Accrual> accruals = dataManager.load(Accrual.class)
.query('select e from rtneo$Accrual e where e.contractPosition.contract.id=:contractId and e.period=:period')
.parameter("contractId", contract.getId())
.parameter("period", period)
.view(acView)
.list();
return accruals;
}
}
return null;
}
public List<Accrual> getContragentBills(UUID contragentID) {
ViewRepository vRep = AppBeans.get(ViewRepository.NAME)
View viewAccrual = vRep.getView(Accrual.class, "_local")
.addProperty("category", vRep.getView(RealEstateCategory.class, "_local")
.addProperty("unit", vRep.getView(Unit.class, "_local"))
)
.addProperty("realEstate", vRep.getView(RealEstate.class, "_local")
)
String sqlQuery = 'select e from rtneo$Accrual e where 1=0';
List<Accrual> accruals = new ArrayList<Accrual>();
List<Contract> contracts = dataManager.load(Contract.class)
.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.accepted =true order by e.createTs desc')
.parameter("contragent", contragentID)
.view("contract-edit")
.list();
if (contracts.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Contract lastContract = null;
for (Contract contract : contracts) {
if (lastContract == null) {
lastContract = contract;
sqlQuery = 'cast(a.contractPosition.contract.id text)=\'' + contract.getId().toString() + '\' ';
} else {
if (contract.getFrom().before(lastContract.getFrom())) {
sqlQuery = sqlQuery + ' or (cast(a.contractPosition.contract.id text)=\'' + contract.getId().toString() + '\' and a.period < \'' + sdf.format(lastContract.getFrom()) + '\' )';
lastContract = contract;
}
}
}
sqlQuery = 'select a from rtneo$Accrual a where a.contragent.id = :contragentID and (' + sqlQuery + ') order by a.period';
accruals = dataManager.load(Accrual.class)
.query(sqlQuery)
.parameter("contragentID", contragentID)
.view(viewAccrual)
.list();
}
return accruals;
}
public List<Accrual> getContragentBills(UUID contragentID, Date from, Date to) {
ViewRepository vRep = AppBeans.get(ViewRepository.NAME)
DataManager dataManager = AppBeans.get(DataManager.NAME)
View viewAccrual = vRep.getView(Accrual.class, "_local")
.addProperty("category", vRep.getView(RealEstateCategory.class, "_local")
.addProperty("unit", vRep.getView(Unit.class, "_local"))
)
.addProperty("realEstate", vRep.getView(RealEstate.class, "_local")
)
String sqlQuery = 'select e from rtneo$Accrual e where 1=0';
List<Accrual> accruals = new ArrayList<Accrual>();
List<Contract> contracts = dataManager.load(Contract.class)
.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.accepted =true order by e.createTs desc')
.parameter("contragent", contragentID)
.view("contract-edit")
.list();
if (contracts.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Contract lastContract = null;
for (Contract contract : contracts) {
if (lastContract == null) {
lastContract = contract;
sqlQuery = 'cast(a.contractPosition.contract.id text)=\'' + contract.getId().toString() + '\' ';
} else {
if (from.before(lastContract.getFrom())) {
sqlQuery = sqlQuery + ' or (cast(a.contractPosition.contract.id text)=\'' + contract.getId().toString() + '\' and a.period < \'' + sdf.format(to) + '\' )';
lastContract = contract;
}
}
}
sqlQuery = 'select a from rtneo$Accrual a where a.contragent.id = :contragentID and (' + sqlQuery + ') order by a.period';
accruals = dataManager.load(Accrual.class)
.query(sqlQuery)
.parameter("contragentID", contragentID)
.view(viewAccrual)
.list();
}
return accruals;
}
/**
* Логирование
*/
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)}