MyTetra Share
Делитесь знаниями!
Выгрузка УПД с paymentLimit = '2020-03-31'
Время создания: 06.07.2020 12:22
Раздел: INFO - JOB - rtneo - Выгрузки - УПД
Запись: wwwlir/Tetra/master/base/159400935777kx9ylfhl/text.html на raw.githubusercontent.com

import com.groupstp.rtneo.entity.*

import java.util.*

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

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



DataManager dataManager = AppBeans.get(DataManager.NAME)

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

BillService billService = AppBeans.get(BillService.NAME)



//String id='6129c48c-fda9-7225-e770-4e6e9d76037b'

//

//

//FileDescriptor fd = dataManager.load(FileDescriptor.class)

// .id(UuidProvider.fromString(id))

// .view(View.MINIMAL)

// .optional()

// .orElse(null);

// if (fd == null) {

// throw new RuntimeException(getMessage("BigTrioContractImporterBean.fileNotFound"));

// }

//InputStream inputStream=fileStorageAPI.openStream(fd)

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

//List<String> listInn = [];

//for(row in reader)

//{

// listInn.add(row[0])

//}


def period1 = '2019-01-01'

def period2 = '2019-12-01'

def paymentLimit = '2020-03-31'


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

//period = df1.parse(period1)

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

Calendar periodEnd = Calendar.getInstance();

//periodStart.setTime(df1.parse(period1));

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

Calendar periodStart = Calendar.getInstance();

periodStart.setTime(df1.parse(period1));


def i = 0;



def contragents = dataManager.loadValues('select distinct c.id, c.inn, c.kpp from rtneo$Payment e join rtneo$Contragent c on e.inn = c.inn where not c.type = 3 and not e.inn is null and not c.personalAccount is null order by c.inn')

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

.firstResult(i*10)

.maxResults(10)

.list();


//def contragents = dataManager.loadValues('select c.id, c.inn, c.kpp from rtneo$Contragent c where c.inn = \'3808105761\' order by c.id')

// .properties("id", "inn", "kpp")

// .list();


//List<Accrual> accruals = null

def accrualsGroup = new TreeMap<>();

def contragentsGroup = new TreeMap<>();


Date paymentLimitDate = df1.parse(paymentLimit)

for(def contragent : contragents){


def payments = dataManager.load(Payment.class)

.query('select p from rtneo$Payment p where p.inn = :inn and p.createTs <= :paymentLimitDate')

.parameter('inn', contragent.getValue('inn'))

.parameter("paymentLimitDate", paymentLimitDate)

.view('_local')

.list();

if(payments.size() == 0) continue;

List<Accrual> rentAccruals = null

def isPayRent = false;

def res = dataManager.load(RealEstateRenter.class)

.query('select r from rtneo$RealEstateRenter r where r.contragentRealEstate.contragent.id = :id and r.payOwner = true')

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

.view("realEstateRenter-changeQueryControl")

.list();

if(res.size() != 0){

isPayRent = true

// log.debug("Contragent[${contragent.getValue('id')}] rent is ${res.size()}")

}

if(isPayRent){

rentAccruals = initBillsRentersTab(res)

}

if(contragentsGroup[contragent.getValue('inn')] == null){

contragentsGroup[contragent.getValue('inn')] =[

'inn' : contragent.getValue('inn'),

'kpp' : contragent.getValue('kpp'),

]

}

contragentsGroup[contragent.getValue('inn')]['payments'] = [:];

for(def payment : payments){

if(contragentsGroup[contragent.getValue('inn')]['payments'][dateView.format(payment.getDate())] == null){

contragentsGroup[contragent.getValue('inn')]['payments'][dateView.format(payment.getDate())] = [

'purpose' : payment.getPurpose(),

'sum' : payment.getSum()

]

}else{

contragentsGroup[contragent.getValue('inn')]['payments'][dateView.format(payment.getDate())]['sum'] += payment.getSum();

}

}

contragentsGroup[contragent.getValue('inn')]['accruals'] = [:];

accrualsGroup = [:];

periodStart.set(Calendar.MONTH, 0);

periodStart.set(Calendar.YEAR, 2019);

while(!periodStart.after(periodEnd)){

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


if(rentAccruals != null){

// log.debug("Before rent ${accruals}")

for(Accrual rentAccrual : rentAccruals){

// log.debug("rentAccrual.getPeriod() - ${rentAccrual.getPeriod()}, periodStart - ${periodStart.getTime()}")

if(rentAccrual.getPeriod() == periodStart.getTime()){

accruals.add(rentAccrual)

}

}

// log.debug("After rent ${accruals}")

}


for(def accrual : accruals){

tariffNoNDS = accrual.getPrice()*5/6;

if(accrualsGroup[dateView.format(accrual.getPeriod())]==null){

accrualsGroup[dateView.format(accrual.getPeriod())] = [

'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()),

'done' : false

]

}else{

accrualsGroup[dateView.format(accrual.getPeriod())]['amountBase'] += getNN(accrual.getAmountBase())

accrualsGroup[dateView.format(accrual.getPeriod())]['totalSumBaseNoNds'] += getNN(accrual.getAmountBase())*tariffNoNDS

accrualsGroup[dateView.format(accrual.getPeriod())]['totalSumBase'] += getNN(accrual.getTotalSumBase())

accrualsGroup[dateView.format(accrual.getPeriod())]['totalSum'] += getNN(accrual.getTotalSum())

}

}

periodStart.add(Calendar.MONTH, 1)

}

contragentsGroup[contragent.getValue('inn')]['accruals'] = accrualsGroup;

}


def res = [:]

for(def contr : contragentsGroup){

def sumPay = 0

contr.getValue()['payments'].each{p -> sumPay += p.getValue()['sum']}

res[contr.getValue()['inn']] = [

'inn' : contr.getValue()['inn'],

'kpp' : contr.getValue()['kpp'],

'sumPayments' : sumPay,

'accruals': [:]

]

// def accrual = []

for(def accrualFor : contr.getValue()['accruals']){

sumPay -= accrualFor.getValue()['totalSum']

if(!(sumPay<0))accrualFor.getValue()['done'] = true else accrualFor.getValue()['done'] = false


res[contr.getValue()['inn']]['accruals'][accrualFor.getValue()['period']]=accrualFor

}


}

Calendar endMonth = Calendar.getInstance();

endMonth.setTime(df1.parse(period1));

for(def itemRes : res){

for(def item : itemRes.getValue()['accruals']){

// log.debug(item.getValue().getValue())

def total = item.getValue().getValue()

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']))

log.debug("!Услуга Регионального оператора по обращению с ТКО за ${month}!${total['number']}!${dateView.format(endMonth.getTime())}!${itemRes.getValue()['inn']}!${itemRes.getValue()['kpp']}!${total['amountBase']}!${total['tariff']}!${total['totalSumBaseNoNds']}!${total['totalSum']-total['totalSumBaseNoNds']}!${total['totalSum']}!${total['done']==true?'да':'нет'}")

}

}

return res;


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

}

def getNN(BigDecimal value) {

return value == null ? BigDecimal.ZERO : value;

}


def initBillsRentersTab(List<RealEstateRenter> rentersRE) {

//Формируем запрос в accrualDs для получения начислений арендаторов для которых арендотатель выбрал оплату арендотаделем

String fullSql = '';

int actual = 0;

// List<RealEstateRenter> rentersRE = getRentersRE();

if (rentersRE.size() > 0) {

for (RealEstateRenter renterRE : rentersRE) {

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", renterRE.getContragent().getId())

.view("_local")

.list();

if (contracts.size() > 0) {

Contract lastContract = null;

String sqlQuery = '';

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

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String date = sdf.format(lastContract.getFrom());

sqlQuery = sqlQuery + ' or (cast(a.contractPosition.contract.id text)=\'' + contract.getId().toString() + '\' and a.period < \'' + date + '\' )';

lastContract = contract;

}

}

}

if (sqlQuery != '') {

sqlQuery = '(cast(a.contragent.id text) = \'' + renterRE.getContragent().getId().toString() + '\' and cast(a.contractPosition.contragentRealEstate.id text)=\'' + renterRE.getRenterRecord().getId().toString() + '\' and (' + sqlQuery + ')) ';

if (actual == 0) {

fullSql = sqlQuery;

actual = 1;

} else fullSql = fullSql + ' or ' + sqlQuery;

}

}

}

}

if (actual == 0) {

fullSql = 'select e from rtneo$Accrual e where 1 = 0';

} else {

fullSql = 'select a from rtneo$Accrual a where ' + fullSql + 'order by a.period';

}

List<Accrual> accruals = dataManager.load(Accrual.class)

.query(fullSql)

.view("accrual-edit")

.list();

// for (int l = 0; l < accruals.size(); l++) {

// log.debug(accruals.get(l));

// }

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

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