MyTetra Share
Делитесь знаниями!
Рефакторинг доп с историей
Время создания: 05.02.2020 09:06
Раздел: INFO - JOB - rtneo - Работа над задачами - Отчеты
Запись: wwwlir/Tetra/master/base/1578032507vqtcgrxfq0/text.html на raw.githubusercontent.com

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 com.haulmont.cuba.core.app.*;

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


import java.text.DateFormat;

import java.text.SimpleDateFormat;


ViewRepository vRep = AppBeans.get(ViewRepository.NAME)


//def contract = dataManager.reload(params['contract'],'contract-print')

def r1 = "c16b8f04-d5fc-4c97-400b-82b5a4078218"

def r2 = "3200f50c-0e8e-b6af-9327-1fb5ce2dc0b9"

def params = [:]

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


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

def (String startFrom, String endBefore) = getStartEndDate(contract, df)


Contragent contragent = contract.getContragent()


LinkedHashMap<String, Object> props = getRequisites(contract, params, df, startFrom, contragent)


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

def units = [];

def realEstates = [];

def calculations = [];

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

def containers = [];

def historyContainers = [:];

def containersUnique = [];

//

def accrualsGroup = new TreeMap<>();


//a.kotvinskiy /--

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

def rentersGroup = new TreeMap<>();


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

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

creView.addProperty("ownType");

//a.kotvinskiy --/


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

def n = 0

int startCount = 1

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

log.debug(">>NEW POSITION")

//a.kotvinskiy /--

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

def isPayLandlord = false;

def isOwner = false;

def isCnC = false;

def isFact = false

//////////////////////


(isFact, isCnC, isPayLandlord, isOwner) = setPositionMark(position, creView, contragent)


//a.kotvinskiy --/

if (CollectionUtils.isEmpty(position.getAccruals()) && !isFact) {

continue

}


realEstateNums = ""

realEstatePos = [:]

calculation = [:]


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

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+=getNN(accrual.getAmountBase())

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


createAccrualsGroup(accrualsGroup, accrual, isCnC, isPayLandlord)


if(isCnC && isPayLandlord){

fillRentersGroup(accrual, rentersGroup)

}


}


// (n, realEstateNums) = fillRealEstatesWP(position, n, realEstateNums, isCnC, realEstates, containersUnique, isFact, containers, startFrom, endBefore)


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

++n

List<ContractPositionContainerYard> cpcyHistory = getHistoryCY(contragent, position)


/*

/Body

/03012020

/

*/

List<ContractPosition> cpList = getHistoryCP(contragent, position)


cpList = checkCPPeriod(cpList)

if(cpList.size()>0){

List itemsCP = getItemsCP(cpList)

List itemsRE = getItemsRE(itemsCP, startCount++, contract)

for(def item : itemsRE){

// log.debug(item)

realEstates.push(item)

}

List itemsContainer = getItemsContainers(itemsCP, itemsRE, startCount, contract, historyContainers)

}

/*

/

/

/

*/


if(cpcyHistory.size()==0){

def pos = createContainerItem(position, startCount++, df.format(position.getContract().getFrom()), df.format(position.getContract().getBefore()))

realEstates.push(pos)


for(def item : position.getContainerYards()){

def containerYard = item.getContainerYard()

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

containersUnique.push(containerYard.getId())

getContainers(containerYard, isFact, containers, startFrom, endBefore, n)

// private void getContainers(containerYard, isFact, List containers, String startFrom, String endBefore, def n) {

}

}

}else{

//Временно скрыл

// List<HashMap<String, Object>> itemsCY = getHistoryPrintItemsCY(cpcyHistory, startCount++, isFact, containers, contract)

//

// for(def item : itemsCY){

// realEstates.push(item)

// }


}


////////////////////////////////////////////////////////////

//Добавляем в список объектов через запятую realEstates

//??

if (realEstateNums.length()>0){

realEstateNums+=','

}

realEstateNums+=n

}

(n, realEstateNums) = fillRealEstatesWP(position, n, realEstateNums, isCnC, realEstates, containersUnique, isFact, containers, startFrom, endBefore)


// List itemsCP

if(!isCnC){

if(isFactCalculationContract(position.getContract())){

def calculationHistory = getCalculationHistory(contragent, position, df, accrualsGroup, contract, realEstateNums, isFact, n)

for(def item : calculationHistory){

calculations.push(item)

}

}else{

getCalculation(position, calculation, df, totalVolumePosition, accrualsGroup, contract, realEstateNums, isFact)

calculations.push(calculation)

}

}

}


def prevN = 0

def remNum = 0

def prevCode = 0

ArrayList remArr = []

def first = true

for(def item : containers){

if(item['n'] == prevN+0.1 && item['code'] != prevCode){

if(item['code'] != prevCode){

// first?remNum--:

// remNum--

// remArr.add(remNum)

}else{

remNum--

remArr.add(remNum)

}

}

remNum++

prevN = item['n']

prevCode = item['code']

first = false

}


for(def rem : remArr){

if(rem < 0)rem = 0

containers.get(rem+1)["startFrom"] = containers.get(rem)["startFrom"]

containers.remove(rem)

}


List renters = getRenters(rentersGroup)



def factAmount = []


List<ContainerYard> cyList = dataManager.load(ContainerYard.class)

.query('select distinct c.containerYard from rtneo$ContractPositionContainerYard c where c.contractPosition.contract.id = :contract and c.contractPosition.isFactCalculation = 20')

.parameter("contract", contract.getId())

.view("_local")

.list();


def totalFactAmount = 0

for(ContainerYard cy : cyList){

totalFactAmount += cy.getMaxWasteExportVol()

def fact = [:]

for(i=0; i<=12; i++){

if(i == 0){

fact = [

"n": cy.getCode()

]

}else{

// fact.push(["${i}":cy.getMaxWasteExportVol()])

fact["${i}"] = cy.getMaxWasteExportVol()

}

}

factAmount.add(fact)

}


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

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)

totalSumBaseNoNds = totalSumBaseNoNds + item.getValue()['totalSumBase']/120*100

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

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

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


LinkedHashMap<String, Object> accrual = createAccrual(item)

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

'totalFactAmount' : getNumber(totalFactAmount)

]


log.debug(historyContainers)

log.debug(realEstates)


return [['props':props,'realEstates': realEstates, 'calculations': calculations, 'totals':totals, 'containers': containers, 'accruals': accruals, 'renters': renters, 'factAmount': factAmount]]


/*

/Functions

/03012020

/

*/

private Boolean isFactCalculationContract(Contract contract){

if(contract.getIsFactCalculation() != null && contract.getIsFactCalculation())return true

if(contract.getIsRefactCalculation() != null && contract.getIsRefactCalculation())return true

}

private List checkCPPeriod(List cpList){

def sortCPList = []

def prevDate = null

def prevContract = null


for(def item : cpList.reverse()){

if(prevDate != item.getPeriod() && prevContract != item.getContract().getNumber())sortCPList.add(item)


prevDate = item.getPeriod()

prevContract = item.getContract().getNumber()

}

return sortCPList

}


private List cleanCPList(List cpList){


def changeCPList = []


ContractPosition prevCP = null;


for(def item : cpList.reverse()){

def changeMap = [:]

def changeCY = changeCY(item, prevCP)

def changeRE = changeRE(item, prevCP)


changeMap = [

"cp":item,

"changeCY":changeCY,

"changeRE":changeRE

]

//Для теста пока не фильтрую

if(changeCY || changeRE)changeCPList.add(changeMap)

// changeCPList.add(changeMap)

prevCP = item

}

return changeCPList

}


private Boolean changeCY(ContractPosition cp, ContractPosition prevCP){

if(prevCP == null) return true


def strCode = ""

def prevStrCode = ""

//Нужно отсортировать КП по номеру, перед конкатенацией

for(def item : cp.getContainerYards()){

strCode = strCode+item.getContainerYard().getCode()

}

for(def item : prevCP.getContainerYards()){

prevStrCode = prevStrCode+item.getContainerYard().getCode()

}

if(!strCode.equals(prevStrCode))return true


//Другие проверки


return false

}

private Boolean changeRE(ContractPosition cp, ContractPosition prevCP){

if(prevCP == null) return true


//Сравниваем кол-во р/е

if(prevCP.getContragentRealEstate().getCalculationAmount() != cp.getContragentRealEstate().getCalculationAmount())return true


//Сравниваем объемы по начислениям

BigDecimal totalVolumePosition = null

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

totalVolumePosition=getNN(accrual.getAmountBase())

}

BigDecimal prevTotalVolumePosition = null

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

prevTotalVolumePosition=getNN(accrual.getAmountBase())

}

if(!prevTotalVolumePosition.equals(totalVolumePosition))return true


//Другие проверки


return false

}


List<HashMap<String, Object>> getItemsCP(List<ContractPosition> cpList){


def changeCPList = cleanCPList(cpList)


return changeCPList

}

private List getItemsContainers(List itemsCP, List itemsRE, Integer startCount, Contract contract, def historyContainers){

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

//Итоговый список

def listContainers = []

// def tmpContainers = historyContainers

char nChar = 'А'

BigDecimal nInt = BigDecimal.valueOf(startCount)

def n = nInt


//Предыдущие значения

def prev = [

"nChar":null,

"nInt":null

]

for(def item : itemsRE){

// log.debug(item)

}

for(def item : itemsCP){

// log.debug(item)

// log.debug("c: ${item['cp'].getContract().getNumber()}; period ${item['cp'].getContract().getFrom()} - ${item['cp'].getContract().getBefore()}; containers = ${item['cp'].getContainerYards().size()}")

for(def container : item['cp'].getContainerYards()){

def str = getItemRENum(itemsRE, df.format(item['cp'].getContract().getFrom()), container.getContainerYard().getCode())

historyContainers.putIfAbsent(container.getContainerYard().getCode(), [:]);

if(historyContainers[container.getContainerYard().getCode()][item['cp'].getContract().getFrom().toString()] == null){

historyContainers[container.getContainerYard().getCode()][item['cp'].getContract().getFrom().toString()] = str

}else{

historyContainers[container.getContainerYard().getCode()][item['cp'].getContract().getFrom().toString()] += "/"+str

}

}

}

// log.debug(tmpContainers)

// for(def item : tmpContainers){

// historyContainers.putAll(tmpContainers)

// }

// historyContainers = tmpContainers

// log.debug(historyContainers)

}

private void getContainersNew(containerYard, isFact, List containers, String startFrom, String endBefore, def n) {

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)

volume = volume.replaceAll(',', '.')

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


String typeVal = type + volume

String key = containerYard.getCode()



String typeExport = isFact ? 'Исходя из количества и объема контейнеров' : 'Исходя из нормативов накопления'

def current = []

Map previous = containerWasteBuff[key]

// if (previous == null) {

current = [

'n' : n,

'code' : containerYard.getCode(),

'startFrom' : startFrom,

'endBefore' : endBefore,

'address' : containerYard.getAddress(),

'longitude' : containerYard.getLongitude(),

'latitude' : containerYard.getLatitude(),

'typeExport': typeExport,

'owner' : containerYard.getOwner(),

'type' : type,

'volume' : volume,

'count' : count,

'typeWaste' : ((volume != '') && (new BigDecimal(volume) < 5.0)) ? 'ТКО' : 'КГО'

]

if (containerWasteBuff[key] != null) {

// if(current['n'] == )

current['n'] = ''

current['code'] = ''

current['startFrom'] = ''

current['endBefore'] = ''

current['address'] = ''

current['longitude'] = ''

current['latitude'] = ''

current['owner'] = ''

}

containers.push(current)

containerWasteBuff[key] = current

}

}

private String getItemRENum(List itemsRE, String date, String cpCode){

def str = ""

for(def item : itemsRE){

if(item["containerYardNumber"].toString().equals(cpCode)){

if(item["startFrom"].equals(date)){

str += item["n"].toString()+"/"

}

}

}

if(str.length()>0){

str = str.substring(0, str.length() - 1)

}

return str

}


private List getItemsRE(List itemsCP, Integer startCount, Contract contract){

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

//Итоговый список

def listRE = []



char nChar = 'А'

BigDecimal nInt = BigDecimal.valueOf(startCount)

def n = nInt


//Предыдущие значения

def prev = [

"nChar":null,

"nInt":null

]


for(def item : itemsCP){


//Определяем код КП

def strCodeCP = ""


if(item["cp"].getContainerYards().size()>1){

for(def cpcy : item["cp"].getContainerYards()){

strCodeCP = strCodeCP+cpcy.getContainerYard().getCode()+"/"

}

strCodeCP = strCodeCP.substring(0, strCodeCP.length() - 1)

}else{

strCodeCP = item["cp"].getContainerYards()[0].getContainerYard().getCode()

}


//Устанавливаем период

Calendar cal = Calendar.getInstance()

cal.setTime(item["cp"].getContract().getFrom())

cal.add(Calendar.DATE, -1)

if(listRE.size()>0)listRE.get(listRE.size()-1)["endBefore"] = df.format(cal.getTime())


//Определим номер

if(item["changeCY"] && !item["changeRE"]){


if(nChar == 'А'){

def tmpCyItem = listRE.get(listRE.size()-1).clone()

listRE.get(listRE.size()-1)['startFrom'] = "--"

listRE.get(listRE.size()-1)['endBefore'] = "--"

listRE.get(listRE.size()-1)['containerYardNumber'] = "--"


tmpCyItem['n'] = tmpCyItem['n'].toString()+nChar++

listRE.push(tmpCyItem)

}

n = (prev["nInt"].toString())+(nChar++)

}


if(item["changeRE"]){

nChar = 'А'

if(contract.getIsFactCalculation() != null && contract.getIsFactCalculation()) nInt +=0.1

n=nInt

}


//Создаем позицию

def pos = createREItem(item["cp"], strCodeCP, n, item["cp"].getContract().getFrom(), item["cp"].getContract().getBefore())

listRE.push(pos)


//Устанавливаем предыдущие значения

prev["nInt"] = nInt

prev["nChar"] = nChar


//Прибавляем счетчики

// nInt += 0.1

// log.debug("Prev ${prev}")

// log.debug("Проверка ${nInt}, ${nChar}")

}


return listRE

}

def createREItem(ContractPosition cp, String code, Object n, Date from, Date before){

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


// def kgo = false

//

// for(def container : cpcy.getContainerYard().getContainers()){

// BigDecimal volume = container.getType()?.getVolume() == null ? BigDecimal.ZERO : container.getType().getVolume()

// if(volume >= BigDecimal.valueOf(5.0))kgo = true;

// }


def isNull = false

isNull = cp.getContragentRealEstate() == null?true:false

def pos = [

realEstateName:isNull?'':cp.getContragentRealEstate().getRealEstate().getName(),

cadastralNumber:isNull?'':cp.getContragentRealEstate().getRealEstate().getCadastralNumber(),

address:isNull?'':cp.getContragentRealEstate().getRealEstate().getAddress(),

startFrom:df.format(from),

endBefore:df.format(before),

containerYardNumber:code,

// containerYardKGONumber: kgo?cpcy.getContainerYard().getCode():'',

n:n

]

return pos

}

/*

/

/

/

*/

private List getStartEndDate(contract, SimpleDateFormat df) {

Calendar cal = Calendar.getInstance();


cal.setTime(contract.getFrom());

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));

def startFrom = df.format(cal.getTime())


cal.setTime(contract.getBefore());

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

def endBefore = df.format(cal.getTime())

[startFrom, endBefore]

}


private List fillRealEstatesWP(ContractPosition position, int n, String realEstateNums, boolean isCnC, List realEstates, List containersUnique, boolean isFact, List containers, String startFrom, String endBefore) {

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['cadastralNumber'] = contractPositionContainerYard.getContragentRealEstate().getRealEstate().getCadastralNumber()

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

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

realEstateP['n'] = ++n

if (realEstateNums.length() > 0) {

realEstateNums += ','

}


realEstateNums += realEstateP['n']

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

if (!isCnC) realEstates.push(realEstateP)

}


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

// containersUnique.push(containerYard.getId())

// getContainers(containerYard, isFact, containers, startFrom, endBefore)

// }

}

}


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

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

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

cre = dataManager.reload(cre, "contragentRealEstate-categorization")


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

continue;

}


realEstateP = [:]

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

realEstateP['cadastralNumber'] = cre.getRealEstate().getCadastralNumber()

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

realEstateP['n'] = ++n


if (realEstateNums.length() > 0) {

realEstateNums += ','

}


realEstateNums += realEstateP['n']

realEstates.push(realEstateP)

}

}

[n, realEstateNums]

}


private List setPositionMark(ContractPosition position, View creView, Contragent contragent) {

def isPayLandlord = false;

def isOwner = false;

def isCnC = false;

def isFact = false

//Проверяем на null

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

def rentCre = position.getContragentRealEstate();

rentCre = dataManager.reload(rentCre, creView);


//Арендатор или собственник

if (rentCre.getOwnType().equals(TypeOwnership.RENT)) {

isOwner = true;

}

//Если за объект оплачивает арендодатель

if (isOwner & isPayLandLord(position.getContragentRealEstate())) {

isPayLandlord = true;

}

//Если позиция создалась с объектом арендодателя

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

isCnC = true;

}

}


isFact = dataManager.loadValue('select cp.isFactCalculation from rtneo$ContractPosition cp where cp.id = :id', Boolean.class).parameter("id", position.getId()).optional().orElse(false);

[isFact, isCnC, isPayLandlord, isOwner]

}


private LinkedHashMap<String, Object> createAccrual(Map.Entry<Object, Object> item) {

return [

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

]

}


private void getCalculation(ContractPosition position, LinkedHashMap<Object, Object> calculation, SimpleDateFormat df, BigDecimal totalVolumePosition, TreeMap<Object, Object> accrualsGroup, contract, String realEstateNums, isFact) {


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

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

}

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

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

}

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

calculation['unitName'] = "ПНООЛР с ${position.getWasteProject().getValidityFrom() == null ? '--' : df.format(position.getWasteProject().getValidityFrom())} по ${position.getWasteProject().getValidityTo() == null ? '--' : df.format(position.getWasteProject().getValidityTo())}"

}


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


//Нужен среднее кол-во р/е по позиции, или объем деленый на норматив

//Вычисляем актуальное начисление на в зависимости от даты договора

// def nMouth = accrualsGroup.size() == 12 ? contract.getDate().getMonth()-1 : 0

def nMouth = accrualsGroup.size() - (12 - contract.getDate().getMonth())

// if(accrualsGroup.values()[nMouth]) calculation['calculationAmount'] = getFormatNum(accrualsGroup.values()[nMouth]['calculationAmount'], 5)

def calculationAmount = 0


if (position.getCalculationAmount() == null || position.getCalculationAmount() == 0) {

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

calculationAmount = "--"

} else {

calculationAmount = getFormatNum(dataManager.reload(position.getContragentRealEstate(), "_local").getCalculationAmount(), 5)

}

} else {

calculationAmount = getFormatNum(position.getCalculationAmount(), 5)

}


calculation['calculationAmount'] = calculationAmount

if (position.getNorm() == null)

calculation['calculationAmountPay'] = getFormatNum(accrualsGroup.values()[nMouth]['calculationAmount'], 5);

else

calculation['calculationAmountPay'] = position.getNorm() == 0 ? BigDecimal.ZERO : getFormatNum(totalVolumePosition / new BigDecimal(position.getNorm()), 3);


if (position.getContragentRealEstate() == null) calculation['calculationAmountPay'] = "--"

//a.kotvinskiy --/

calculation['n'] = realEstateNums

if (isFact) {

calculation['unitName'] = '--'

calculation['norm'] = '--'

calculation['amount'] = 'расчет по факту'

calculation['calculationAmount'] = '--'

}

}


private def getCalculationHistory(Contragent contragent, ContractPosition cp, SimpleDateFormat df, TreeMap<Object, Object> accrualsGroup, Contract contract, String realEstateNums, isFact, num){

List<ContractPosition> cpHistoryList = getHistoryCP(contragent, cp);

num +=0.1

def calculationList = []


def prevAmount = 0.0

def prevN = null

def prevFrom = null

for(ContractPosition position : cpHistoryList){

def calculation = [:]


BigDecimal endVolume = 0.0

BigDecimal totalVolumePosition = 0.0

if(position.getAccruals().size()>0){

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

// totalVolumePosition += getNN(accrual.getAmountBase())

if(!contract.getFrom().after(accrual.getPeriod()))totalVolumePosition += getNN(accrual.getAmountBase())

endVolume = getNN(accrual.getAmountBase())

}

}

if(prevFrom.equals(position.getContract().getFrom())){

if(calculationList.size()>0)num = calculationList.get(calculationList.size()-1)["n"]

calculationList.remove(calculationList.size()-1)

prevAmount = null

}


if(prevAmount.equals(endVolume)){

continue

}else{

prevAmount = endVolume

}




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

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

}

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

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

}

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

calculation['unitName'] = "ПНООЛР с ${position.getWasteProject().getValidityFrom() == null ? '--' : df.format(position.getWasteProject().getValidityFrom())} по ${position.getWasteProject().getValidityTo() == null ? '--' : df.format(position.getWasteProject().getValidityTo())}"

}


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


//Нужен среднее кол-во р/е по позиции, или объем деленый на норматив

//Вычисляем актуальное начисление на в зависимости от даты договора

// def nMouth = accrualsGroup.size() == 12 ? contract.getDate().getMonth()-1 : 0

def nMouth = accrualsGroup.size() - (12 - contract.getDate().getMonth())

// if(accrualsGroup.values()[nMouth]) calculation['calculationAmount'] = getFormatNum(accrualsGroup.values()[nMouth]['calculationAmount'], 5)

def calculationAmount = 0


if (position.getCalculationAmount() == null || position.getCalculationAmount() == 0) {

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

calculationAmount = "--"

} else {

calculationAmount = getFormatNum(dataManager.reload(position.getContragentRealEstate(), "_local").getCalculationAmount(), 5)

}

} else {

calculationAmount = getFormatNum(position.getCalculationAmount(), 5)

}


calculation['calculationAmount'] = calculationAmount

if (position.getNorm() == null)

calculation['calculationAmountPay'] = getFormatNum(accrualsGroup.values()[nMouth]['calculationAmount'], 5);

else

calculation['calculationAmountPay'] = position.getNorm() == 0 ? BigDecimal.ZERO : getFormatNum(totalVolumePosition / new BigDecimal(position.getNorm()), 3);


if (position.getContragentRealEstate() == null) calculation['calculationAmountPay'] = "--"

//a.kotvinskiy --/

calculation['n'] = num

num +=+0.1


if (position.getIsFactCalculation()) {

calculation['unitName'] = '--'

calculation['norm'] = '--'

calculation['amount'] = '--'

calculation['calculationAmount'] = 'расчет по факту'

}


calculationList.push(calculation);

prevN = num

prevFrom = position.getContract().getFrom()

}

return calculationList

}


private void fillRentersGroup(Accrual accrual, TreeMap<Object, Object> rentersGroup) {

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

}

}


private LinkedHashMap<String, Object> getRequisites(Contract contract, HashMap<Object, Object> params, SimpleDateFormat df, String startFrom, Contragent contragent) {

def companyService = AppBeans.get(CompanyService.NAME)

def bankDataService = AppBeans.get(BankDataSupplierService.NAME)

//Получаем реквизиты компании, действующие на момент даты договора

def company = contract.getCompany()

def companyRequisites = companyService.getCompanyRequisites(company, contract.getDate())

def companyManagerNameR = companyRequisites.getManagerName()

try {

companyManagerNameR = new RussianName(companyManagerNameR).fullName(RussianNameProcessor.gcaseRod)

} catch (e) {


}

//заполняем шапку


//документ-основание

contragentPersonReasonText = ', действующего на основании '

if (contragent.getType() == ContragentType.PERSONAL) {

contragentPersonReasonText = ''

}

contragentPersonReasonDoc = params['personReason']

if (contragentPersonReasonDoc == null) {

contragentPersonReasonDoc = contragent.getHeadPersonReasonDoc()

}

contragentPersonReasonDocR = contragentPersonReasonDoc

try {

contragentPersonReasonDocR = new RussianName(contragentPersonReasonDoc).fullName(RussianNameProcessor.gcaseRod)

} catch (e) {


}

if (contragentPersonReasonDocR == null) {

if (getContragentType(contragent) == ContragentType.ORGANISATION) {

contragentPersonReasonDocR = "устава"

} else if (getContragentType(contragent) == ContragentType.INDIVIDUAL) {

contragentPersonReasonDocR = "свидетельства / выписки о государственной регистрации в качестве индивидуального предпринимателя"

}

}

//подписант

contragentPersonName = params['personName']

if (contragentPersonName == null) {

contragentPersonName = contragent.getHeadPersonName()

if (contragent.getType() == ContragentType.PERSONAL) {

contragentPersonName = contragent.getName()

}

}

contragentPersonNameR = contragentPersonName

try {

contragentPersonNameR = new RussianName(contragentPersonName).fullName(RussianNameProcessor.gcaseRod)

} catch (e) {


}

//должность подписанта

contragentPersonPost = params['personPost']

if (contragentPersonPost == null) {

contragentPersonPost = contragent.getHeadPersonPost()

}

contragentPersonPostR = contragentPersonPost

try {

contragentPersonPostR = new RussianName(contragentPersonPost).fullName(RussianNameProcessor.gcaseRod)

} catch (e) {


}


//массив шапочных параметров

def props = [

'number' : contract.getNumber(),

'date' : getTextDate(contract.getDate()),

//a.kotvinskiy /--

'dateFromTKO' : df.format(contract.getFrom()),

'dateBeforeTKO' : df.format(contract.getBefore()),

//a.kotvinskiy --/

'contragentName' : contragent.getName(),

'contragentNameShort' : contragent.getShortName(),

'contragentPersonName' : contragentPersonName,

'contragentPersonNameR' : contragentPersonNameR,

'contragentPersonNameShort' : getShortFio(contragentPersonName),

'contragentPersonPost' : contragentPersonPost,

'contragentPersonPostR' : contragentPersonPostR,

'contragentPersonReasonDoc' : contragentPersonReasonDoc,

'contragentPersonReasonDocR' : contragentPersonReasonDocR,

'contragentPersonReasonText' : contragentPersonReasonText,

'contragentShortName' : contragent.getShortName(),

'legalAddress' : contragent.getLegalAddress(),

'actualAddress' : contragent.getActualAddress(),

'mailingAddress' : contragent.getMailingAddress(),

'registrationAddrees' : contragent.getRegistrationAddress(),

'passportSeries' : contragent.getPassportSeries(),

'passportNumber' : contragent.getPassportNumber(),

'passportGivenDate' : contragent.getPassportGivenDate(),

'inn' : contragent.getInn(),

'kpp' : contragent.getKpp(),

'ogrn' : contragent.getOgrn(),

'checkingAccount' : contragent.getCheckingAccount(),

'bankName' : contragent.getBankName(),

'correspondentAccount' : contragent.getCorrespondentAccount(),

'bik' : contragent.getBik()

, 'companyShortName' : company.shortName

, 'companyFullName' : company.fullName

, 'companyInn' : company.inn

, 'companyEmail' : company.email

, 'companyOgrn' : company.ogrn

, 'companyPhone' : company.phone

, 'companyLegalAddress' : companyRequisites.legalAddress

, 'companyActualAddress' : companyRequisites.actualAddress

, 'companyPostalAddress' : companyRequisites.postalAddress

, 'companyKpp' : companyRequisites.kpp

, 'companyBankName' : companyRequisites.bankName

, 'companyBankAccount' : companyRequisites.bankAccount

, 'companyCorrespondentAccount': companyRequisites.correspondentAccount

, 'companyRcbic' : companyRequisites.rcbic

, 'companyManagerTitle' : companyRequisites.managerTitle

, 'companyManagerTitleR' : companyRequisites.managerTitleR

, 'companyManagerName' : companyRequisites.managerName

, 'companyManagerNameR' : companyManagerNameR

, 'companyManagerNameShort' : getShortFio(companyRequisites.managerName)

, 'companyManagerDocumentR' : getShortFio(companyRequisites.managerDocumentR),

'startFrom' : startFrom

]


if (!StringUtils.isBlank(props['bik']) && (StringUtils.isBlank(props['bankName']) || StringUtils.isBlank(props['correspondentAccount']))) {

BankData bank = bankDataService.getSuggestionBankDetails(props['bik'])

if (bank != null) {

if (StringUtils.isBlank(props['bankName'])) {

props['bankName'] = bank.getName()

}

if (StringUtils.isBlank(props['correspondentAccount'])) {

props['correspondentAccount'] = bank.getCorrespondentAccount()

}

}

}


//телефон + почта

def phone = ''

if (contragent.getHeadPersonPhone() != null) {

phone = contragent.getHeadPersonPhone()

} else if (contragent.getContactPersonPhone() != null) {

phone = contragent.getContactPersonPhone()

}

def email = ''

if (contragent.getHeadPersonEmail() != null) {

email = contragent.getHeadPersonEmail()

} else if (contragent.getContactPersonEmail() != null) {

email = contragent.getContactPersonEmail()

}

props['phone'] = phone

props['email'] = email

//a.kotvinskiy 19-07-19/--

//В пункте 3 доп соглашения, указываем начало действия доп соглашения

props['dateFrom'] = getTextDate(contract.getFrom())

//a.kotvinskiy 19-07-19--/

//получаем номер и дату головного договора

if (contract.getMainContract() != null) {

props['mainContractNumber'] = contract.getMainContract().getNumber()

props['mainContractDate'] = getTextDate(contract.getMainContract().getDate())

}

//вычисляем подписантов и юридический адрес

def defaultDate = new Date().copyWith(year: 2019, month: Calendar.JANUARY, dayOfMonth: 17, hourOfDay: 0, minute: 0, second: 0);

def addressChangeDate = new Date().copyWith(year: 2019, month: Calendar.APRIL, dayOfMonth: 26, hourOfDay: 0, minute: 0, second: 0);

def contractDate = contract.getDate()

props['ourPersonPost'] = "Заместитель генерального директора по коммерческой работе"

props['ourPersonPostR'] = "Заместителя генерального директора по коммерческой работе"

props['ourPersonName'] = "Степанова Татьяна Анатольевна"

props['ourPersonNameR'] = "Степановой Татьяны Анатольевны"

props['ourPersonReasonDoc'] = "доверенность № РТ-05 от 11.01.2019 г"

props['ourPersonReasonDocR'] = "доверенности № РТ-05 от 11.01.2019 г"

props['ourPersonNameShort'] = "Степанова Т.А."

if (contractDate < addressChangeDate) {

props['ourLegalAddress'] = '308000, Белгородская область, город Белгород, проспект Б. Хмельницкого, дом 131, помещение 15'

props['ourKpp'] = '312301001'

} else {

props['ourLegalAddress'] = '664033, Иркутская область, город Иркутск, улица Лермонтова, дом 337Б, помещение 8'

props['ourKpp'] = '381201001'

}

return props

}


private void createAccrualsGroup(TreeMap<Object, Object> accrualsGroup, Accrual accrual, boolean isCnC, boolean isPayLandlord) {

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

accrualsGroup[accrual.getPeriod()] = [

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

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

'amountBase' : !isCnC && isPayLandlord ? BigDecimal.ZERO : getNN(accrual.getAmountBase()),

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

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

//a.kotvinskiy /--

'totalSumBaseNoNds': getNN(accrual.getTotalSumBase())/120*100,

//'totalSumBaseNoNds': getNN(accrual.getNdsSumBase()),

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

//a.kotvinskiy --/

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

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

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

'calculationAmount': getNN(accrual.getCalculationAmount())]

} else {

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

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

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

//a.kotvinskiy /--

accrualsGroup[accrual.getPeriod()]['totalSumBaseNoNds'] += getNN(accrual.getTotalSumBase())/120*100

//accrualsGroup[accrual.getPeriod()]['totalSumBaseNoNds'] += getNN(accrual.getNdsSumBase())

//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());

accrualsGroup[accrual.getPeriod()]['calculationAmount'] = getNN(accrual.getCalculationAmount());

}

}


private void getContainers(containerYard, isFact, List containers, String startFrom, String endBefore, def n) {

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)

volume = volume.replaceAll(',', '.')

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


String typeVal = type + volume

String key = containerYard.getCode()



String typeExport = isFact ? 'Исходя из количества и объема контейнеров' : 'Исходя из нормативов накопления'

def current = []

Map previous = containerWasteBuff[key]

// if (previous == null) {

current = [

'n' : n,

'code' : containerYard.getCode(),

'startFrom' : startFrom,

'endBefore' : endBefore,

'address' : containerYard.getAddress(),

'longitude' : containerYard.getLongitude(),

'latitude' : containerYard.getLatitude(),

'typeExport': typeExport,

'owner' : containerYard.getOwner(),

'type' : type,

'volume' : volume,

'count' : count,

'typeWaste' : ((volume != '') && (new BigDecimal(volume) < 5.0)) ? 'ТКО' : 'КГО'

]

if (containerWasteBuff[key] != null) {

// if(current['n'] == )

current['n'] = ''

current['code'] = ''

current['startFrom'] = ''

current['endBefore'] = ''

current['address'] = ''

current['longitude'] = ''

current['latitude'] = ''

current['owner'] = ''

}

containers.push(current)

containerWasteBuff[key] = current

}

}


private void getContainersHistory(containerYard, isFact, List containers, String startFrom, String endBefore) {

List<ContractPosition> cpHistoryList = getHistoryCP(contragent, cp);


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)

volume = volume.replaceAll(',', '.')

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


String typeVal = type + volume

String key = containerYard.getCode()



String typeExport = isFact ? 'Исходя из количества и объема контейнеров' : 'Исходя из нормативов накопления'

def current = []

Map previous = containerWasteBuff[key]

// if (previous == null) {

current = [

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

'code' : containerYard.getCode(),

'startFrom' : startFrom,

'endBefore' : endBefore,

'address' : containerYard.getAddress(),

'longitude' : containerYard.getLongitude(),

'latitude' : containerYard.getLatitude(),

'typeExport': typeExport,

'owner' : containerYard.getOwner(),

'type' : type,

'volume' : volume,

'count' : count,

'typeWaste' : ((volume != '') && (new BigDecimal(volume) < 5.0)) ? 'ТКО' : 'КГО'

]

if (containerWasteBuff[key] != null) {

// if(current['n'] == )

current['n'] = ''

current['code'] = ''

current['startFrom'] = ''

current['endBefore'] = ''

current['address'] = ''

current['longitude'] = ''

current['latitude'] = ''

current['owner'] = ''

}

containers.push(current)

containerWasteBuff[key] = current

}

}


private List getRenters(TreeMap<Object, Object> rentersGroup) {

def renters = []

for (item in rentersGroup) {

def renter = [

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

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

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

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

]

renters.push(renter)

}

renters

}


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

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_DOWN);

}


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;

}

def isPayLandLord(ContragentRealEstate cre){

List<RealEstateRenter> rr = dataManager.load(RealEstateRenter)

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

.parameter("id", cre.getId())

.view("_local")

.list();

if(rr.size()>0)return true else return false;

}


//**************************************************************

//Получить КП для печати

//Нужно разделить(на 3. логика выбор! создание)

//**************************************************************


List<HashMap<String, Object>> getHistoryPrintItemsCY(List<ContractPositionContainerYard> cpcyHistory, Integer startCount, Boolean isFact, List containers, Contract contract){

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

HashMap<String, Object> cyHash = [:]

List<HashMap<String, Object>> cyItemList = []

def containersUnique = [];

def countCY = 0

char nChar = 'А'

BigDecimal nInt = BigDecimal.valueOf(startCount)

def n = null


def prevCode = null

def prevFrom = null

def prevBefore = null

def prevCre = null

def prevCP = null


def prevN = null

char prevNChar = nChar

BigDecimal prevNInt = nInt


def prevTotalVolumePosition = 0.0


if(cpcyHistory.size()==0){

def pos = createContainerItem(cpcy, n, df.format(cpcy.getContractPosition().getContract().getFrom()), df.format(cpcy.getContractPosition().getContract().getBefore()))

cyItemList.push(pos)

}

for(ContractPositionContainerYard cpcy : cpcyHistory){

def changeCY = false

def changeCre = false


//Логика выбора

if(!prevCode.equals(cpcy.getContainerYard().getCode())){

changeCY = true

}


if(prevCre != null && (prevCre.getCalculationAmount() != cpcy.getContractPosition().getContragentRealEstate().getCalculationAmount())){

changeCre = true

}


BigDecimal totalVolumePosition = null

for(Accrual accrual : cpcy.getContractPosition().getAccruals()){

totalVolumePosition=getNN(accrual.getAmountBase())

}

if(!prevTotalVolumePosition.equals(totalVolumePosition)){

changeCre = true

}


if(!prevCre.equals(cpcy.getContractPosition().getContragentRealEstate())){

changeCre = true

}

if(!changeCre && !changeCY)continue



if(prevFrom.equals(cpcy.getContractPosition().getContract().getFrom())){

cyItemList.remove(cyItemList.size()-1)

n = prevN

}else{

//Получение номера вынести в отдельный метод

Calendar cal = Calendar.getInstance()

cal.setTime(cpcy.getContractPosition().getContract().getFrom())

cal.add(Calendar.DATE, -1)

if(cyItemList.size()>0)cyItemList.get(cyItemList.size()-1)["endBefore"] = df.format(cal.getTime())

if(changeCY & !changeCre){

if(nChar == 'А'){

def tmpCyItem = cyItemList.get(cyItemList.size()-1).clone()


cyItemList.get(cyItemList.size()-1)['startFrom'] = "--"

cyItemList.get(cyItemList.size()-1)['endBefore'] = "--"

cyItemList.get(cyItemList.size()-1)['containerYardNumber'] = "--"


tmpCyItem['n'] = tmpCyItem['n'].toString()+nChar++

cyItemList.push(tmpCyItem)

}

n = (prevNInt.toString())+(nChar++)

}


if(changeCre){

nChar = 'А'

if(contract.getIsFactCalculation() != null && contract.getIsFactCalculation()) nInt +=0.1

n=nInt

}

}


def pos = createContainerItem(cpcy, n, df.format(cpcy.getContractPosition().getContract().getFrom()), df.format(cpcy.getContractPosition().getContract().getBefore()))

cyItemList.push(pos)


// if(n instanceof Character){

// if(prevNInt.remainder(1) == 0.0){

// nContainer = (prevNInt.setScale(0, BigDecimal.ROUND_DOWN)).toString()+n

// }else{

// def tmpNContainer = prevNInt.setScale(1, BigDecimal.ROUND_DOWN)-0.1

// if(tmpNContainer.remainder(1) == 0.0){

// tmpNContainer = tmpNContainer.setScale(0, BigDecimal.ROUND_DOWN)

// }

// nContainer = tmpNContainer.toString()+n

// }

// }else{

// nContainer = prevNInt

// }


if(prevFrom.equals(cpcy.getContractPosition().getContract().getFrom())){

containers.remove(containers.size()-1)

// n = prevN

countCY--

}

if(containers.size()>0 && containers.get(containers.size()-1)["code"] == pos["containerYardNumber"]){

if(cyItemList.size()>1){

// containers.remove(containers.size()-1)

}

}

// if (changeCY || cyItemList.size()==1) {

if(containers.size()>0){

// if(containers.get(containers.size()-1)["code"] == pos["containerYardNumber"])continue

if(n.toString().endsWith('Б')){

if(!containers.get(containers.size()-1)["n"].toString().endsWith('А')){

containers.get(containers.size()-1)["n"] = containers.get(containers.size()-1)["n"].toString()+"А"

}

}

}

if(cyItemList.size()>0 && countCY>0){

Calendar cal = Calendar.getInstance()

cal.setTime(cpcy.getContractPosition().getContract().getFrom())

cal.add(Calendar.DATE, -1)


containers.get(containers.size()-1)["endBefore"] = df.format(cal.getTime())

}

getContainers(cpcy.getContainerYard(), isFact, containers, df.format(cpcy.getContractPosition().getContract().getFrom()), df.format(cpcy.getContractPosition().getContract().getBefore()), n)

countCY++

// }


//Устанавливаем предыдущие значения

prevCode = cpcy.getContainerYard().getCode()

prevFrom = cpcy.getContractPosition().getContract().getFrom()

prevBefore = cpcy.getContractPosition().getContract().getBefore()

prevCre = cpcy.getContractPosition().getContragentRealEstate()

// if(!isPrevN)prevN = n

prevN = n

prevNChar = nChar

prevNInt = nInt

prevTotalVolumePosition = totalVolumePosition

//Конец выбора


}


return cyItemList

}


//**************************************************************

//Получить историю КП для объекта

//**************************************************************

List<ContractPositionContainerYard> getHistoryCY(Contragent contragent, ContractPosition contractPosition){

List<ContractPosition> cpList = getHistoryCP(contragent, contractPosition)

List<ContractPositionContainerYard> cpcyList = []


for(ContractPosition cp : cpList){

for(ContractPositionContainerYard cpcy : cp.getContainerYards()){

cpcyList.push(cpcy)

}

}

return cpcyList

}


//**************************************************************

//Получить историю позиции договора

//**************************************************************

List<ContractPosition> getHistoryCP(Contragent contragent, ContractPosition cp){

DataManager dataManager = AppBeans.get(DataManager.NAME);

EntitySnapshotService entitySnapshotService = AppBeans.get(EntitySnapshotService.NAME);


List<SnapshotHistory> listSnapshotHistory = null


if(cp.getContract().getIsFactCalculation() != null && cp.getContract().getIsFactCalculation()){

//if(true){

listSnapshotHistory = dataManager.load(SnapshotHistory.class)

.query('select s from rtneo$SnapshotHistory s where s.contragent.id = :contragent and s.contract.accepted = true or s.contract.id = :contractId order by s.contract.createTs asc')

.parameter("contragent", contragent.getId())

.parameter("contractId", cp.getContract().getId())

.view("_local")

.list();

}else{

listSnapshotHistory = dataManager.load(SnapshotHistory.class)

.query('select s from rtneo$SnapshotHistory s where s.contract.id = :contractId')

.parameter("contractId", cp.getContract().getId())

.view("_local")

.list();

}


List<ContractPosition> cpList = []

for(def snapshotHistory : listSnapshotHistory){


def entitySnapshot = dataManager.load(EntitySnapshot.class).id(snapshotHistory.getSnapshot()).optional().orElse(null)

Contract entity = entitySnapshotService.extractEntity(entitySnapshot)


for(ContractPosition cpItem : entity.getPositions()){

if(cp.getWasteProject() != null && cp.getWasteProject() == cpItem.getWasteProject()){

cpList.push(cpItem)

}

if((cp.getContragentRealEstate() != null && cpItem.getContragentRealEstate() != null) && (cp.getContragentRealEstate().getId() == cpItem.getContragentRealEstate().getId()))

cpList.push(cpItem)

}


}

return cpList;

}


def createContainerItem(ContractPositionContainerYard cpcy, Object n, String from, String before){

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

def kgo = false


for(def container : cpcy.getContainerYard().getContainers()){

BigDecimal volume = container.getType()?.getVolume() == null ? BigDecimal.ZERO : container.getType().getVolume()

if(volume >= BigDecimal.valueOf(5.0))kgo = true;

}


def pos = [

realEstateName:cpcy.getContractPosition().getContragentRealEstate().getRealEstate().getName(),

cadastralNumber:cpcy.getContractPosition().getContragentRealEstate().getRealEstate().getCadastralNumber(),

address:cpcy.getContractPosition().getContragentRealEstate().getRealEstate().getAddress(),

startFrom:from,

endBefore:before,

containerYardNumber:cpcy.getContainerYard().getCode(),

containerYardKGONumber: kgo?cpcy.getContainerYard().getCode():'',

n:n

]

return pos

}

def createContainerItem(ContractPosition cp, Object n, String from, String before){

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


// def kgo = false

//

// for(def container : cpcy.getContainerYard().getContainers()){

// BigDecimal volume = container.getType()?.getVolume() == null ? BigDecimal.ZERO : container.getType().getVolume()

// if(volume >= BigDecimal.valueOf(5.0))kgo = true;

// }


def isNull = false

isNull = cp.getContragentRealEstate() == null?true:false

def pos = [

realEstateName:isNull?'':cp.getContragentRealEstate().getRealEstate().getName(),

cadastralNumber:isNull?'':cp.getContragentRealEstate().getRealEstate().getCadastralNumber(),

address:isNull?'':cp.getContragentRealEstate().getRealEstate().getAddress(),

startFrom:from,

endBefore:before,

containerYardNumber:'',

// containerYardKGONumber: kgo?cpcy.getContainerYard().getCode():'',

n:n

]

return pos

}

 
MyTetra Share v.0.65
Яндекс индекс цитирования