MyTetra Share
Делитесь знаниями!
Категория Лицевой счет Наименование ИНН Адрес юр. Адрес факт. Телефон Электронный адрес Договор/Доп. соглашение Дата принятия Годовой объем в куб.м. Сумма платежей в руб.
Время создания: 06.07.2020 12:22
Раздел: INFO - JOB - rtneo - Выгрузки
Запись: wwwlir/Tetra/master/base/1594009357p2h3y5owxt/text.html на raw.githubusercontent.com


import java.util.*

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

import com.groupstp.rtneo.entity.*

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import com.groupstp.datasupplier.data.BankData

import com.groupstp.datasupplier.service.BankDataSupplierService

import com.groupstp.rtneo.entity.*

import org.apache.commons.collections4.CollectionUtils

import java.math.RoundingMode;

import java.text.DecimalFormat;

import java.text.DecimalFormatSymbols;

import com.github.declinationofnames.*

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

import com.groupstp.rtneo.core.bean.calculation.CalculationWorkerHelper

import com.groupstp.rtneo.service.AccrualService

import com.groupstp.rtneo.data.ContainerYardSearchData

import com.groupstp.rtneo.core.bean.ContainerYardWorker

import org.apache.commons.lang.StringUtils

import com.groupstp.rtneo.service.CompanyService

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import com.haulmont.cuba.core.global.ViewRepository;

import com.haulmont.cuba.core.global.View;

def helper = AppBeans.get(CalculationWorkerHelper.NAME)

def service = AppBeans.get(AccrualService.NAME)

def containerYardWorker = AppBeans.get(ContainerYardWorker.NAME)

def bankDataService = AppBeans.get(BankDataSupplierService.NAME)

def companyService = AppBeans.get(CompanyService.NAME)

DataManager dataManager = AppBeans.get(DataManager.NAME)

DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)


View creView = vRep.getView(ContragentRealEstate.class, "contragentRealEstate-edit");

creView.addProperty("category", vRep.getView(RealEstateCategory.class, "realEstateCategory-export"));


List<Contragent> contragents = dataManager.load(Contragent.class)

//.query('select e from rtneo$Contragent e where e.category.name=\'B\' order by e.id ')

.query('select e from rtneo$Contragent e WHERE e.legalAddress LIKE \'%%Бодай%%\' or e.legalAddress LIKE \'%%бодай%%\' or e.legalAddress LIKE \'%%БОДАЙ%%\' or e.actualAddress LIKE \'%%БОДАЙ%%\' or e.actualAddress LIKE \'%%бодай%%\' or e.actualAddress LIKE \'%%Бодай%%\' ')

.firstResult(0)

.maxResults(3000)

.view("contragent-edit")

.list();



for(contragent in contragents)

{

category="не установлена"

if(contragent.getCategory()!=null) category=contragent.getCategory().getName();

contractNumber="нет данных"

contractAcceptance="нет данных"

beginFrom="нет данных"

contractVolume="нет данных"+'$'+"нет данных"

contracts=getActualContract(contragent.getId())

manager=""

if(contragent.getManager()!=null) manager=contragent.getManager().getName()

if(contracts.size()>0)

{

Contract contract=contracts.get(0);

acceptance=contract.getAcceptanceDate()

beginFrom=contract.getFrom()

contractNumber=contract.getNumber()

contractVolume=getTotalVolume(contract.getId());

if(acceptance!=null) contractAcceptance=df.format(acceptance)


}

strRes=category+'$'+contragent.getPersonalAccount()+'$'+contragent.getName()+'$'+contragent.getInn()+'$' +contragent.getLegalAddress()+'$'+contragent.getActualAddress()+'$'+contragent.getPhone()+'$'+contragent.getContactPersonEmail()+","+contragent.getHeadPersonEmail()+'$'+contractNumber+'$'+contractAcceptance+'$'+beginFrom+'$'+contractVolume.toString().replaceAll("\\.",",")+'$'+getTotalPay(contragent.getInn()).toString().replaceAll("\\.",",")+'$'+manager

log.debug(strRes.replaceAll("\\p{Cntrl}", ""));

}



def List<Contract> getActualContract(UUID contragentID)

{

List<Contract> contracts = dataManager.load(Contract.class)

.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.accepted=true and e.mainContract is not null order by e.createTs desc')

.parameter('contragent', contragentID)

.view("contract-edit")

.list();

if(contracts.size()==0)

{

contracts = dataManager.load(Contract.class)

.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.mainContract is null order by e.createTs desc')

.parameter('contragent', contragentID)

.view('contract-edit')

.list();

}

return contracts;

}

def getTotalPay(inn)

{

totalSum=0;

List<Payment> payments = dataManager.load(Payment.class)

.query('select e from rtneo$Payment e where e.inn=:inn')

.parameter("inn", inn)

.view("_local")

.list();


for(payment in payments)

{

totalSum=totalSum+payment.getSum();

}

return totalSum;

}

def getTotalVolume(contractId)

{

def params = [:]

def contract = dataManager.load(Contract.class).id(contractId).view('contract-print').optional().orElse(null)

def contragent = contract.getContragent()

DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

DateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");



//позиции по договору

def units = [];

def realEstates = [];

def calculations = [];

//контейнерные площадки

def containers = [];

def containersUnique = [];

def accrualsGroup = new TreeMap<>();


//a.kotvinskiy /--

//Объемы арендаторов за которые оплачивает арендодатель

def rentersGroup = new TreeMap<>();

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

View creView = vRep.getView(ContragentRealEstate.class, "_local");

creView.addProperty("contragent", vRep.getView(Contragent.class, "_local"));

creView.addProperty("category", vRep.getView(RealEstateCategory.class, "_local"));

//a.kotvinskiy --/

//заполняем позиции

for (ContractPosition position: contract.getPositions()){

//a.kotvinskiy /--

//Оплата арендодателем

def isPayLandlord = false;

if(position.getContragentRealEstate()!=null){

def rentCre = position.getContragentRealEstate();

try{

rentCre = dataManager.reload(rentCre, creView);

if(!contragent.getId().equals(rentCre.getContragent().getId())){

isPayLandlord = true;

}

}catch(e){}

}

//a.kotvinskiy --/

if (CollectionUtils.isEmpty(position.getAccruals())) {

continue

}


realEstateNums = ""

realEstatePos = [:]

calculation = [:]

if (position.getCategory()!=null){

calculation['unitName'] = position.getUnit().getName()

}

if (position.getNorm()!=null){

//a.kotvinskiy /--

//calculation['norm'] = getNumber(position.getNorm(), false, true)

calculation['norm'] = getFormatNum(position.getNorm(), 4)

//a.kotvinskiy --/

}

if (position.getWasteProject()!=null){

calculation['unitName'] = 'ПНООЛР'

}

//бегаем по начислениям

BigDecimal totalVolumePosition = 0

//a.kotvinskiy /--

BigDecimal tariff = 0

BigDecimal amountBaseRent = 0;

//a.kotvinskiy --/

for (Accrual accrual: position.getAccruals()){

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

totalVolumePosition+=isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase())

amountBaseRent +=!isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase())

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

accrualsGroup[accrual.getPeriod()] = [

'period' : getTextPeriod(accrual.getPeriod()),

'tariff': round(getNN(accrual.getPrice())*5/6),

'amountBase': getNN(accrual.getAmountBase()),

'amountBaseNoRent': isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase()),

'amountBaseRent': !isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase()),

//a.kotvinskiy /--

//'totalSumBaseNoNds': (getNN(accrual.getTotalSumBase().setScale(2, RoundingMode.HALF_UP))-getNN(accrual.getNdsSumBase().setScale(2, RoundingMode.HALF_UP))),

'totalSumBaseNoNds': (getNN(accrual.getAmountBase())*getNN(tariffNoNDS)),

//a.kotvinskiy --/

'totalSumBase': getNN(accrual.getTotalSumBase()),

'discount': getNN(accrual.getTotalSumBase())-getNN(accrual.getTotalSum()),

'totalSum': getNN(accrual.getTotalSum())]

} else {

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

accrualsGroup[accrual.getPeriod()]['amountBaseNoRent']+=isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase());

accrualsGroup[accrual.getPeriod()]['amountBaseRent']+=!isPayLandlord?BigDecimal.ZERO:getNN(accrual.getAmountBase());

//a.kotvinskiy /--

//accrualsGroup[accrual.getPeriod()]['totalSumBaseNoNds']+=(getNN(accrual.getTotalSumBase().setScale(2, RoundingMode.HALF_UP))-getNN(accrual.getNdsSumBase().setScale(2, RoundingMode.HALF_UP)));

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

//a.kotvinskiy --/

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

accrualsGroup[accrual.getPeriod()]['discount']+=(getNN(accrual.getTotalSumBase())-getNN(accrual.getTotalSum()));

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

}

if(isPayLandlord){

def rentCategory = dataManager.load(RealEstateCategory.class)

.query('select a.category from rtneo$Accrual a where a.id=:id')

.parameter('id', accrual.getId())

.view('_local')

.optional()

.orElse(null);

if(rentersGroup[rentCategory.getName()] == null){

rentersGroup[rentCategory.getName()]=[

'rentCategory': rentCategory.getName(),

'rentArea':accrual.getCalculationAmount(),

'rentNorm':rentCategory.getNorm(),

'rentAmount':accrual.getAmountBase()];

}else{

//rentersGroup[rentCategory.getName()]['rentArea']+=accrual.getCalculationAmount();

rentersGroup[rentCategory.getName()]['rentAmount'] += accrual.getAmountBase();

}

}

}

//a.kotvinskiy /--

//calculation['amount'] = getNumber(totalVolumePosition, false)

//calculation['calculationAmount'] = getNumber(position.getAccruals().get(0).getCalculationAmount(), false)

calculation['amount'] = getFormatNum(totalVolumePosition, 5);

calculation['calculationAmount'] = getFormatNum(position.getAccruals().get(0).getCalculationAmount(), 5);

//a.kotvinskiy --/



if (position.getContragentRealEstate()!=null && position.getContragentRealEstate().getRealEstate()){

RealEstate realEstate = position.getContragentRealEstate().getRealEstate()

realEstatePos['realEstateName'] = realEstate.getName()

realEstatePos['address'] = realEstate.getAddress()

}


def realEstatesWasteProject = [];

//бегаем по площадкам

if (position.getContainerYards()!=null){

//заполняем массив КП

for (ContractPositionContainerYard contractPositionContainerYard: position.getContainerYards()){

containerYard = contractPositionContainerYard.getContainerYard()

realEstatePos['containerYardNumber'] = containerYard.getCode();

//выдираем из проекта лимитов ОН

if (position.getWasteProject()!=null){

realEstateP = [:]

realEstateP['realEstateName'] = contractPositionContainerYard.getContragentRealEstate().getRealEstate().getName()

realEstateP['address'] = contractPositionContainerYard.getContragentRealEstate().getRealEstate().getAddress()

realEstateP['containerYardNumber'] = containerYard.getCode();

realEstateP['n'] = realEstates.size()+1

if (realEstateNums.length()>0){

realEstateNums+=','

}

realEstateNums+=realEstateP['n']

realEstatesWasteProject.add(contractPositionContainerYard.getContragentRealEstate().getId())

if(!isPayLandlord) realEstates.push(realEstateP)

}


if (containersUnique.indexOf(containerYard.getId())<0){

containersUnique.push(containerYard.getId())


def containerWasteBuff = [:]

for (ContainerWaste container: containerYard.getContainers()){

String type = container.getType()?.getName() == null ? '' : container.getType().getName()

String volume = container.getType()?.getVolume() == null ? '' : getNumber(container.getType().getVolume(),false)

Integer count = container.getCount() == null ? 0 : container.getCount();


String key = type + volume


Map previous = containerWasteBuff[key]

if (previous == null) {

def current = [

'n': containers.size()+1,

'code':containerYard.getCode(),

'address':containerYard.getAddress(),

'longitude':containerYard.getLongitude(),

'latitude':containerYard.getLatitude(),

'owner': containerYard.getOwner(),

'type': type,

'volume': volume,

'count': count

]

containers.push(current)

containerWasteBuff[key] = current

} else {

previous['count'] += count

}

}

}

}

}

//добираем объекты недвижимости из ПЛООНР, для которых не найдены КП

if (position.getWasteProject() != null){

for (ContragentRealEstate cre: position.getWasteProject().getRealEstates()){

if (realEstatesWasteProject.indexOf(cre.getId())>=0){

continue;

}

realEstateP = [:]

realEstateP['realEstateName'] = cre.getRealEstate().getName()

realEstateP['address'] = cre.getRealEstate().getAddress()

realEstateP['n'] = realEstates.size()+1

if (realEstateNums.length()>0){

realEstateNums+=','

}

realEstateNums+=realEstateP['n']

realEstates.push(realEstateP)

}

}

if (!isPayLandlord && realEstatePos!=[:] && position.getWasteProject() == null){

realEstatePos['n'] = realEstates.size()+1

realEstates.push(realEstatePos)

if (realEstateNums.length()>0){

realEstateNums+=','

}

realEstateNums+=realEstatePos['n']

}

calculation['n'] = realEstateNums

if(!isPayLandlord) calculations.push(calculation)

}

def renters = []

for(item in rentersGroup){

def renter = [

'rentCategory':item.getValue()['rentCategory'],

'rentArea':item.getValue()['rentArea'],

'rentNorm':item.getValue()['rentNorm'],

'rentAmount':item.getValue()['rentAmount'],

]

renters.push(renter)

}


//рассчет итогов

BigDecimal amountBaseAll = 0

//for (ContractPosition position: contract.getPositions()){

// amountBaseAll += position.getVolumeYear()

//}

BigDecimal amountBase = 0

BigDecimal amountBaseNoRent = 0

BigDecimal amountBaseRent = 0

BigDecimal totalSumBaseNoNds = 0

BigDecimal totalSumBase = 0

BigDecimal discount = 0

BigDecimal totalSum = 0


def accruals = []

for (item in accrualsGroup){

amountBase+=item.getValue()['amountBase']

amountBaseNoRent+=item.getValue()['amountBaseNoRent']

amountBaseRent+=item.getValue()['amountBaseRent']

totalSumBaseNoNds = totalSumBaseNoNds + item.getValue()['totalSumBaseNoNds'].setScale(2, RoundingMode.HALF_UP)

totalSumBase = totalSumBase + item.getValue()['totalSumBase'].setScale(2, RoundingMode.HALF_UP)

discount = discount + item.getValue()['discount'].setScale(2, RoundingMode.HALF_UP)

totalSum = totalSum + item.getValue()['totalSum'].setScale(2, RoundingMode.HALF_UP)


def accrual =[

'period' : item.getValue()['period'],

'tariff': getNumber(item.getValue()['tariff']),

//a.kotvinskiy /--

//'amountBase': getNumber(item.getValue()['amountBase'], false),

'amountBase': getFormatNum(item.getValue()['amountBase'], 5),

'amountBaseNoRent': getFormatNum(item.getValue()['amountBaseNoRent'], 5),

'amountBaseRent': getFormatNum(item.getValue()['amountBaseRent'], 5),

//a.kotvinskiy --/

'totalSumBaseNoNds': getNumber(item.getValue()['totalSumBaseNoNds']),

'totalSumBase': getNumber(item.getValue()['totalSumBase']),

'discount': getNumber(item.getValue()['discount']),

'totalSum': getNumber(item.getValue()['totalSum'])

]

accruals.push(accrual)

}


//массив итогов

def totals = [

//a.kotvinskiy /--

//'amountBaseAll' : getNumber(amountBaseAll, false),

//'amountBase' : getNumber(amountBase, false),

'amountBase' : getFormatNum(amountBase, 5),

'amountBaseNoRent' : getFormatNum(amountBaseNoRent, 5),

'amountBaseRent' : getFormatNum(amountBaseRent, 5),

//a.kotvinskiy --/

'totalSumBaseNoNds' : getNumber(totalSumBaseNoNds),

'totalSumBase' : getNumber(totalSumBase),

'discount' : getNumber(discount),

'totalSum' : getNumber(totalSum)

]


return amountBaseNoRent+'$'+ amountBaseRent;


}


//получить дату словами

def getTextDate(Date date) {

def result=''

def monthesRP = ['января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря']

Calendar cal = Calendar.getInstance()

cal.setTime(date);

result = cal.get(Calendar.DAY_OF_MONTH).toString()

result+=" "+monthesRP[cal.get(Calendar.MONTH)]

result+=" "+cal.get(Calendar.YEAR).toString()+" г."

return result

}


//получить период словами

def getTextPeriod(Date date) {

def result=''

def monthesRP = ['январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь']

Calendar cal = Calendar.getInstance()

cal.setTime(date);

result+=monthesRP[cal.get(Calendar.MONTH)]

result+=" "+cal.get(Calendar.YEAR).toString()+" г."

return result

}


//форматирование чисел

def getNumber(BigDecimal number, boolean money = true, boolean scale = false) {

if (number == null) {

return "-"

}

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance()

symbols.setGroupingSeparator((char) ' ')

symbols.setDecimalSeparator((char) ',')

if (money){

DecimalFormat formatter = new DecimalFormat('###,###.00', symbols)

String result = formatter.format(number);

return result.startsWith(",") ? "0" + result : result;

} else {

//Временное решение чтобы, вывести норматив. 4 знака после запятой

if(scale){

DecimalFormat formatter = new DecimalFormat('###,###.####', symbols)

return formatter.format(number);

}else{

DecimalFormat formatter = new DecimalFormat('###,###.###', symbols)

return formatter.format(number);

}


}

}

//a.kotvinskiy /--

//Временное решение, по формату отображения нулей после запятой

def getFormatNum(BigDecimal number, int s, boolean money = false){

if (number == null) {

return "-"

}

String formatString = '';


DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance()

symbols.setGroupingSeparator((char) ' ')

symbols.setDecimalSeparator((char) ',')


switch(s){

case 1:

formatString = '###,###,###.#';

break;

case 2:

formatString = '###,###,###.##';

break;

case 3:

formatString = '###,###,###.###';

break;

case 4:

formatString = '###,###,###.####';

break;

case 5:

formatString = '###,###,###.######';

break;

}

DecimalFormat formatter = new DecimalFormat(formatString, symbols);

String result = formatter.format(number);

return result.startsWith(",") ? "0" + result : result;

}

//a.kotvinskiy --/


def getShortFio(String fio) {

if (fio == null) return ""

String pattern = '(\\S+\\s)(\\S{1})\\S+\\s(\\S{1})\\S+'

String str = fio.replaceAll(pattern, '$1$2.$3.')

return str

}


def round(BigDecimal sum){

return sum == null ? BigDecimal.ZERO : sum.setScale(2, RoundingMode.HALF_UP);

}


def getContragentType(Contragent contragent) {

String name = contragent.getName();

if (name == null){

name = contragent.getShortName();

}

String inn = contragent.getInn();

ContragentType type = contragent.getType();


if (!StringUtils.isEmpty(name)) {

name = name.toLowerCase().trim();

if (name.startsWith("ип ") || name.endsWith(" ип") ||

name.contains(" ип ") ||

name.contains("инд.предп.") ||

name.contains("индивидуальный предприниматель")) {

type = ContragentType.INDIVIDUAL;

}

}


return type;

}


def getNN(BigDecimal value) {

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

}

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