MyTetra Share
Делитесь знаниями!
Рефакторинг допа
Время создания: 02.09.2020 08:52
Раздел: INFO - JOB - rtneo - Работа над задачами - Отчет договоров
Запись: wwwlir/Tetra/master/base/1599007929h0vdmxgnxc/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.groupstp.rtneo.util.JsonUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

def helper = AppBeans.get(CalculationWorkerHelper.NAME)
def service = AppBeans.get(AccrualService.NAME)
def containerYardWorker = AppBeans.get(ContainerYardWorker.NAME)

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

View contractView = vRep.getView(Contract.
class, "contract-print")
.addProperty(
"positions", vRep.getView(Contract.class, "contract-print")
.getProperty(
"positions").getView()
.addProperty(
"contragentRealEstate", vRep.getView(ContragentRealEstate.class, "_local")
.addProperty(
"contragent", vRep.getView(Contragent.class, "_local"))
.addProperty(
"ownType")));

//def contract = dataManager.reload(params['contract'], contractView)
def r1 = "51b20afc-4ae5-c88c-0240-5e79ca022383"
def params = [:]
def contract = dataManager.load(Contract.class).id(UUID.fromString(r1)).view(contractView).optional().orElse(null)
def root = [:]
//Проблема с ПНООЛР
//def rootContractData = loadContractData(contract)
//if(rootContractData != null){
// return rootContractData
//}

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

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

//Устанавливаем реквизиты
LinkedHashMap<String, Object> props = setRequesites(contract, params, startFrom)

//позиции по договору
def units = [];
def realEstates = [];
def calculations = [];

//контейнерные площадки
def containers = [];
def containersUnique = [];

def accrualsGroup = new TreeMap<>();

//Объемы арендаторов за которые оплачивает арендодатель
def rentersGroup = new TreeMap<>();

//заполняем позиции
for (ContractPosition position: contract.getPositions()){
//a.kotvinskiy /--
//Оплата арендодателем
def isPayLandlord = false;
def isOwner = false;
def isCnC = false;
def isFact = false;

if(position.getContragentRealEstate()!=null && !position.getContragentRealEstate().isDeleted()){
(isCnC, isOwner, isPayLandlord, isFact) = setOwnerProperties(position, contract.getContragent())
}

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

realEstateNums =
""
realEstatePos = [:]
calculation = [:]

if (position.getCategory()!=null){
calculation[
'unitName'] = position.getUnit().getName()
}
if (position.getWasteProject()!=null){
calculation[
'unitName'] = "ПНООЛР с ${position.getWasteProject().getValidityFrom() == null? '--':df.format(position.getWasteProject().getValidityFrom())} по ${position.getWasteProject().getValidityTo() == null? '--':df.format(position.getWasteProject().getValidityTo())}"
}
if (position.getNorm()!=null){
calculation[
'norm'] = getFormatNum(position.getNorm(), 4)
}

//бегаем по начислениям
BigDecimal totalVolumePosition = 0
BigDecimal tariff = 0
BigDecimal amountBaseRent = 0;
BigDecimal amountBaseRentPay =
0;

totalVolumePosition = getAccrualGroup(position, totalVolumePosition, isCnC, isPayLandlord, accrualsGroup)

if(isCnC)getRenterGroup(position, rentersGroup)

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)
if(position.getContragentRealEstate() == null){
calculation[
'calculationAmountPay'] = "--"
}else{
if(position.getWasteProject()==null){
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);
}
}
//a.kotvinskiy --/

if (position.getContragentRealEstate()!=null && position.getContragentRealEstate().getRealEstate()){
RealEstate realEstate = position.getContragentRealEstate().getRealEstate()
realEstatePos[
'realEstateName'] = realEstate.getName()
realEstatePos[
'cadastralNumber'] = realEstate.getCadastralNumber()
realEstatePos[
'address'] = realEstate.getAddress()
realEstatePos[
'startFrom'] = startFrom
realEstatePos[
'endBefore'] = 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'] = realEstates.size()+1
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())

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
// }
// }
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':getFormatNum(containerYard.getLongitude(), 5),
'latitude':getFormatNum(containerYard.getLatitude(), 5),
'typeExport':typeExport,
'owner': containerYard.getOwner(),
'type': type,
'volume': volume,
'count': count,
'typeWaste': ((volume != '') && (new BigDecimal(volume) < 5.0))?'ТКО':'КГО'
]
// log.debug(previous['code'])
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
// log.debug(containerWasteBuff)
// } else {
// previous['count'] += count
// current['code'] = '--'
// containers.push(current)
// containerWasteBuff[key] = current
// }
}
}
}
}
//добираем объекты недвижимости из ПЛООНР, для которых не найдены КП
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'] = realEstates.size()+1
if (realEstateNums.length()>0){
realEstateNums+=
','
}
realEstateNums+=realEstateP[
'n']
realEstates.push(realEstateP)
}
}
if (!isCnC && realEstatePos!=[:] && position.getWasteProject() == null){
realEstatePos[
'n'] = realEstates.size()+1
realEstates.push(realEstatePos)
if (realEstateNums.length()>0){
realEstateNums+=
','
}
realEstateNums+=realEstatePos[
'n']
}
calculation[
'n'] = realEstateNums
if(isFact){
calculation[
'unitName'] = 'Вывоз по факту'
calculation['norm'] = '--'
calculation['amount'] = '--'
calculation['calculationAmount'] = '--'
// calculation['n'] = calculations.size()+1
// calculations.push(calculation)
}
if(!isCnC) calculations.push(calculation)
}




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

//рассчет итогов
BigDecimal amountBaseAll = 0
//for (ContractPosition position: contract.getPositions()){
// amountBaseAll += position.getVolumeYear()
//}
BigDecimal amountBase = 0
BigDecimal amountBaseNoRent = 0
BigDecimal amountBaseRent = 0
BigDecimal amountBaseRentPay = 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']
amountBaseRentPay+=item.getValue()[
'amountBaseRentPay']
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_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),
'amountBaseRentPay': getFormatNum(item.getValue()['amountBaseRentPay'], 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),
'amountBaseRentPay' : getFormatNum(amountBaseRentPay, 5),
//a.kotvinskiy --/
'totalSumBaseNoNds' : getNumber(totalSumBaseNoNds),
'totalSumBase' : getNumber(totalSumBase),
'discount' : getNumber(discount),
'totalSum' : getNumber(totalSum)
]

root = [[
'props':props,'realEstates': realEstates, 'calculations': calculations, 'totals':totals, 'containers': containers, 'accruals': accruals, 'renters': renters]]
//Сохраняем полученные данные
//saveContractData(root, contract)
return root

/**/
private void saveContractData(def data, Contract contract){
ContractData cdata = metadata.create(ContractData.
class)
JsonUtil jsonUtil = AppBeans.get(JsonUtil.NAME)
String json;

try{
json = jsonUtil.toJson(data)
}
catch(Exception e){log("LOG.ERROR: JSON object serialization failed")}

cdata.setJsonData(json)
cdata.setContract(contract)
dataManager.commit(cdata)

contract.setContractData(cdata)
dataManager.commit(contract)
}

private def loadContractData(Contract contract){
JsonUtil jsonUtil = AppBeans.get(JsonUtil.NAME)
ContractData cdata = dataManager.load(ContractData.
class)
.query(
'select c from rtneo$ContractData c where c.contract.id = :contract')
.parameter(
"contract", contract.getId())
.view(
"_local")
.optional()
.orElse(
null);
if(cdata == null)return null
String json;
try{
json = cdata.getJsonData();
}
catch(Exception e){}

def arr = jsonUtil.fromJson(json, ArrayList.class)

return arr;
}

//получить дату словами
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){
// _("***")
// _(number)
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);
// _(result)
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;
}
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;
}
/**
* Вынесенные методы
*/
private LinkedHashMap<String, Object> setRequesites(contract, def params, String startFrom) {
def bankDataService = AppBeans.get(BankDataSupplierService.NAME)
def companyService = AppBeans.get(CompanyService.NAME)

DateFormat df =
new SimpleDateFormat("dd.MM.yyyy");
//Получаем реквизиты компании, действующие на момент даты договора
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) {

}
//заполняем шапку
def contragent = contract.getContragent()
//документ-основание
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' : 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 Number getAccrualGroup(ContractPosition position, BigDecimal totalVolumePosition, boolean isCnC, boolean isPayLandlord, TreeMap<Object, Object> accrualsGroup) {
BigDecimal amountBaseRentPay =
0;
BigDecimal amountBaseRent =
0;
def helper = AppBeans.get(CalculationWorkerHelper.NAME)
for (Accrual accrual : position.getAccruals()) {
if (accrual.getPeriod().after(position.getContract().getBefore())) continue

def
tariffNoNDS = getNN(accrual.getPrice()) / 120 * 100;
totalVolumePosition += getNN(accrual.getAmountBase())

if (position.getContragentRealEstate() != null) isPayLandlord = helper.isPayLandlord(position.getContragentRealEstate(), accrual.getPeriod())

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

BigDecimal totalSumBaseNoNds = getNN(accrual.getAmountBase()) * tariffNoNDS;
if (accrualsGroup[accrual.getPeriod()] == null) {
accrualsGroup[accrual.getPeriod()] = [
'period' : getTextPeriod(accrual.getPeriod()),
'tariff' : round(tariffNoNDS),
'amountBase' : !isCnC && isPayLandlord ? BigDecimal.ZERO : getNN(accrual.getAmountBase()),
'amountBaseNoRent' : !isCnC ? getNN(accrual.getAmountBase()) : BigDecimal.ZERO,
'amountBaseRent' : isCnC && isPayLandlord ? getNN(accrual.getAmountBase()) : BigDecimal.ZERO,
'amountBaseRentPay': isCnC ? getNN(accrual.getAmountBase()) : BigDecimal.ZERO,
//a.kotvinskiy /--
'totalSumBaseNoNds': totalSumBaseNoNds,
// 'totalSumBaseNoNds': (getNN(accrual.getTotalSumBase().setScale(2, RoundingMode.HALF_UP))/120*100),
//'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;
accrualsGroup[accrual.getPeriod()][
'amountBaseRentPay'] += isCnC ? getNN(accrual.getAmountBase()) : BigDecimal.ZERO;
//a.kotvinskiy /--
accrualsGroup[accrual.getPeriod()]['totalSumBaseNoNds'] += totalSumBaseNoNds;
//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());
}
}
totalVolumePosition
}

private void getRenterGroup(ContractPosition position, TreeMap<Object, Object> rentersGroup) {
for (Accrual accrual : position.getAccruals()) {
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 List setOwnerProperties(ContractPosition position, Contragent contragent) {
ContragentRealEstate rentCre = position.getContragentRealEstate();
def isPayLandlord = false;
def isOwner = false;
def isCnC = false;
def isFact = false;

//Арендатор или собственник
if (rentCre.getOwnType().equals(TypeOwnership.RENT))isOwner = true;
//Если за объект оплачивает арендодатель
if (isOwner & isPayLandLord(rentCre))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);

[isCnC, isOwner, isPayLandlord, isFact]
}
/**
* Логирование
*/
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
Яндекс индекс цитирования