MyTetra Share
Делитесь знаниями!
Анализ тарифов
Время создания: 06.07.2020 12:22
Раздел: INFO - JOB - rtneo - Выгрузки - УПД
Запись: wwwlir/Tetra/master/base/1594009357fgd5kv5qfp/text.html на raw.githubusercontent.com

import java.util.*

import com.haulmont.cuba.core.global.*

import com.haulmont.cuba.core.entity.*;

import com.groupstp.rtneo.entity.*

import com.haulmont.cuba.core.entity.FileDescriptor

import com.haulmont.cuba.core.app.FileStorageAPI

import java.io.InputStream

import java.io.InputStreamReader

import java.io.ByteArrayOutputStream

import org.apache.commons.io.IOUtils

import java.nio.charset.StandardCharsets;

import com.opencsv.CSVReader;

import com.groupstp.rtneo.service.BillService

import java.text.SimpleDateFormat

import org.apache.commons.collections.CollectionUtils

import java.util.stream.Collectors;

import com.groupstp.rtneo.core.bean.tools.*

import com.google.common.collect.HashBasedTable;

import com.google.common.collect.Table;


def period1 = '2019-01-01'

def period2 = '2019-12-01'

def paymentLimit = '2020-06-13'

def contractLimit = '2020-06-13'


DatePeriodTools datePeriodTools = AppBeans.get(DatePeriodTools.class)

FileStorageAPI fileStorageAPI=AppBeans.get(FileStorageAPI.NAME);

BillService billService = AppBeans.get(BillService.NAME)


//Контрагенты для исключения из файла

String id='8f57878f-2c2e-66fd-dd0e-e8158367da5f'

FileDescriptor fd = dataManager.load(FileDescriptor.class)

.id(UuidProvider.fromString(id))

.view(View.MINIMAL)

.optional().orElse(null);

if(fd == null){throw new RuntimeException("fileNotFound")}


InputStream inputStream=fileStorageAPI.openStream(fd)

CSVReader reader = new CSVReader(new InputStreamReader(inputStream, "UTF-8"));


List<String> listInn = reader.readAll().stream()

.map{e->e[0]}.collect(Collectors.toList())


def df1 = new SimpleDateFormat("yyyy-MM-dd")

def dateView = new SimpleDateFormat("dd-MM-yyyy")


Calendar periodEnd = Calendar.getInstance();

periodEnd.setTime(df1.parse(period2));


Date paymentLimitDate = df1.parse(paymentLimit)


Calendar beginYear = Calendar.getInstance();

beginYear.setTime(df1.parse("2019-01-01"));




Table<String, String, Object> report = HashBasedTable.create();


def 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()



def i = 0;

def contragents = dataManager.loadValues('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) from rtneo$Payment e join rtneo$Contragent c on e.inn = c.inn where not e.inn is null and e.createTs <= :paymentLimitDate and not c.personalAccount is null and size(c.contracts) > 0 order by c.inn')

.properties("id", "inn", "kpp", "pa", "countContracts")

// .parameter("exclude", listInn)

.parameter("paymentLimitDate", paymentLimitDate)

// .firstResult(i*100)

// .maxResults(100)

.list();


def accrualsGroup = new TreeMap<>();

def contragentsGroup = new TreeMap<>();

//Коллекция исключенных объектов

Map<String, String> excluded = new HashMap<>()

HashSet<String> filedTariff = new HashSet<String>()

//Формируем структуру данных

for(def contragent : contragents){

//Исключаем контрагентов с филиалами

if(contragents.stream().filter{e->e.getValue('inn') == contragent.getValue('inn')}.count() > 1){

excluded.putIfAbsent(contragent.getValue('inn'), "Fil")

// continue;

}

//Исключаем контрагентов у кого есть арендаторы за которых он платит, не из БТ и нет перерасчета по факту за 2019 год

// def isRent = dataManager.loadValue('select count(r) from rtneo$RealEstateRenter r where r.contragentRealEstate.contragent.id = :contragent and r.payOwner = true and (select count(c) from rtneo$Contract c where c.contragent.id = r.contragentRealEstate.contragent.id and (c.loadedFromBigTrio = true or (c.accepted = true and c.isFactRecalculation = true))) = 0', Integer.class)

// .parameter("contragent", contragent.getValue('id'))

// .optional().orElse(0)

// if(isRent > 0){

// excluded.putIfAbsent(contragent.getValue('inn'), "Rent")

//// continue

// }

beginYear.setTime(df1.parse("2019-01-01"));

while(!beginYear.after(periodEnd)){

List<Accrual> accruals = billService.getBillsOnPeriod(UUID.fromString(contragent.getValue('id').toString()), beginYear.getTime())

def tariff = tariffs.stream().filter{e-> datePeriodTools.isPeriodIncluded(beginYear.getTime(), e.getValue('from'), e.getValue('to'))}.findFirst().orElse(null)

BigDecimal roundingTarif = new BigDecimal(tariff.getValue('tariff')).setScale(5, BigDecimal.ROUND_HALF_UP)

for(def accrual : accruals){

if(!accrual.getPrice().equals(roundingTarif)){

report.put(contragent.getValue('pa'), dateView.format(beginYear.getTime()), roundingTarif)

report.put(contragent.getValue('pa'), "contracts", contragent.getValue('countContracts'))

// _("${contragent.getValue('pa')}: period - ${dateView.format(beginYear.getTime())} (tariff = ${roundingTarif}, price = ${accrual.getPrice()})")

}

}

beginYear.add(Calendar.MONTH, 1)

}

}

//Выводим исключенные

//_("-----------Excluded------------")

//excluded.each{_(it)}

//_("--------------End--------------")

_(report.rowKeySet().size())

_(report)

/**

* Логирование

*/

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)}

Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования