MyTetra Share
Делитесь знаниями!
Попытка создания допа
Время создания: 27.11.2019 11:27
Раздел: INFO - JOB - CUBA - GroovyScripts
Запись: wwwlir/Tetra/master/base/1574825277ixap86gzj4/text.html на raw.githubusercontent.com

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

import com.groupstp.rtneo.entity.*

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

import java.text.SimpleDateFormat

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

import java.util.*

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

log.debug("createSupplementaryAggrements.START")


//a.kotvinskiy /--

//Программное создание view

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)


View contractView = vRep.getView(Contract.class, "_minimal");

contractView.addProperty("number");

contractView.addProperty("contragent", vRep.getView(Contragent.class, "_minimal"));

contractView.addProperty("positions", vRep.getView(ContractPosition.class, "_minimal"));

contractView.addProperty("supplementaryAgreements", vRep.getView(Contract.class, "_minimal"));


View contractPositionView = vRep.getView(ContractPosition.class, "_minimal");

contractPositionView.addProperty("relevance");

contractPositionView.addProperty("volumeYear");

contractPositionView.addProperty("accruals", vRep.getView(Accrual.class, "_minimal"));

//a.kotvinskiy --/


//здесь, в переменную price нужно указать тариф, тестовое значение = 500

BigDecimal price = 464.8

//Если contractId "", то доп генерируется для всех

String contractId = "00004ca1-c944-7191-82b5-ef60d40a84e2"

String contragentId = "00004ca1-c944-7191-82b5-ef60d40a84e2"

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

Date fromDate = format.parse("01.01.2019")

Date beforeDate = format.parse("31.12.2019")

Date contract_date = format.parse("01.01.2019")


DataManager dataManager = AppBeans.get(DataManager.NAME)

Metadata metadata = AppBeans.get(Metadata.NAME)


String tableNameCompany = metadata.getClassNN(Company.class).getName()

String tableNameContract = metadata.getClassNN(Contract.class).getName()


CommitContext commitContext = new CommitContext()


List<Company> listCompany = dataManager.load(Company.class)

.query("select comp from " + tableNameCompany + " comp")

.view("_minimal")

.list()

Company company = listCompany.size() == 1 ? listCompany.get(0) : null


//List<Contract> list = dataManager.load(Contract.class)

// .query("select c from " + tableNameContract + " c where (c.loadedFromBigTrio = false or c.loadedFromBigTrio is null)" + new StringBuilder(contractId != "" ? " and c.id = '${contractId}'" : "").toString())

// .view(contractView)

// .list()

//List<Contract> list = dataManager.load(Contract.class)

// .query('select c from rtneo$Contract c where (c.loadedFromBigTrio = false or c.loadedFromBigTrio is null) and c.id = :contractId')

// .parameter("contractId", UUID.fromString(contractId))

// .view(contractView)

// .list()


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

// .query('select c from rtneo$Contragent c where c.id in :contragents')

// .parameter("contragents", UUID.fromString(contragentIds))

// .view("_local")

// .list()


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

.query('select c from rtneo$Contragent c where c.id = :contragent')

.parameter("contragent", UUID.fromString(contragentId))

.view("_local")

.list()


//log.debug("Будет обработано " + list.size() + " договоров, загруженных из BigTrio")


def numContract = 0

def numContractPosition = 0

def numAccrual = 0

//for(Contragent contragent : contragents){

// def baseContract = dataManager.load(Contract.class)

// .query("select c from rtneo$Contract c where c.contragent.id = :id and c.mainContract is null")

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

// .view("_local")

// .one()

//}

//for (Contract baseContract : list) {

// //if (numContract == 1)

// // break

// log.debug((numContract + 1) + ") Договор № " + baseContract.getNumber())

// Contragent contragent = baseContract.getContragent()

for(Contragent contragent : contragents){

def baseContract = dataManager.load(Contract.class)

.query('select c from rtneo$Contract c where c.contragent.id = :id and c.mainContract is null')

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

.view(contractView)

.one()

Contract contract = new Contract()

contract.setDate(new Date())

contract.setFrom(fromDate)

contract.setBefore(beforeDate)

//a.kotvinskiy

contract.setNumber("${baseContract.getSupplementaryAgreements().size()+1}")

contract.setCompany(company)

contract.setContragent(contragent)

contract.setMainContract(baseContract)

contract.setPositions(new ArrayList<>())

commitContext.addInstanceToCommit(contract)

log.debug("Доп. соглашение $contract.id добавлено в CommitContext")

numContract = numContract + 1


//для каждой позиции в base-договоре

for (ContractPosition baseContractPosition : baseContract.getPositions()) {

baseContractPosition = dataManager.reload(baseContractPosition, contractPositionView)

ContractPosition contractPosition = new ContractPosition()

contractPosition.setVolumeYear(baseContractPosition.getVolumeYear())

contractPosition.setPeriod(contract_date)

contractPosition.setContract(contract)

contractPosition.setRelevance(baseContractPosition.getRelevance())

contractPosition.setContragent(contragent)

contractPosition.setAccruals(new ArrayList<>())

commitContext.addInstanceToCommit(contractPosition)

log.debug("ContractPosition $contractPosition.id добавлена в CommitContext")

numContractPosition = numContractPosition + 1

contract.getPositions().add(contractPosition)


//расчет начислений

List<Accrual> listAccruals = calculateAccruals(fromDate,

beforeDate,

new Date(),

contractPosition,

price)

for (Accrual accrual:listAccruals)

{

commitContext.addInstanceToCommit(accrual)

log.debug("Accrual $accrual.id добавлена в CommitContext")

numAccrual = numAccrual + 1

contractPosition.getAccruals().add(accrual)

}

}

//делаем неактивным допик

//makeContractObsolete(contract, false);

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

//makeContractObsolete(lastContract, true);

}

log.debug("Запись изменений в БД...")

dataManager.commit(commitContext)

log.debug("Всего создано:\nДоп.соглашений: " + numContract + "\nContractPosition: " + numContractPosition + "\nAccruals: " + numAccrual)

log.debug("createSupplementaryAggrements.FINISH")



//возвращает список начислений по переданной позици договора и указанной цене

List<Accrual> calculateAccruals(Date from, Date to, Date billDate, ContractPosition position, BigDecimal price) {

DatePeriodTools datePeriodTools = AppBeans.get(DatePeriodTools.class)

CalculationWorkerHelper helper = AppBeans.get(CalculationWorkerHelper.class)

from = from == null ? new Date() : from

to = to == null ? from : to

billDate = billDate == null ? new Date() : billDate


List<Accrual> result = new ArrayList<>()


try {


Calendar calendarFrom = datePeriodTools.getFirstDayOfMonth(from)

Calendar calendarTo = datePeriodTools.getFirstDayOfMonth(to)


while ((calendarFrom.get(Calendar.YEAR) == calendarTo.get(Calendar.YEAR) &&

calendarFrom.get(Calendar.MONTH) <= calendarTo.get(Calendar.MONTH)) ||

(calendarFrom.get(Calendar.YEAR) < calendarTo.get(Calendar.YEAR))) {

int documentNumber = helper.getNextAccrualNumber()

Date period = calendarFrom.getTime()

price = helper.getTariff(period);

Accrual accrual

try {

accrual = calculateAverage(position, period, documentNumber, billDate, price)

if (accrual != null)

result.add(accrual)

} catch (Exception e) {

log.error('не удалось создать начисление для ContractPosition: ' + position.getId())

}

calendarFrom.add(Calendar.MONTH, 1)

}

}

finally {

log.debug('Расчет начислений окончен')

}

return result

}


//расчет по-среднему

Accrual calculateAverage(ContractPosition position, Date period, int documentNumber, Date billDate, BigDecimal price) {

CalculationWorkerHelper helper = AppBeans.get(CalculationWorkerHelper.class)


BigDecimal norm

if (position.getVolumeYear() != null && position.getVolumeYear() != BigDecimal.ZERO)

norm = helper.divide(position.getVolumeYear(), BigDecimal.valueOf(12))


BigDecimal tariff = price

tariff = helper.addNdsTo(tariff)


BigDecimal sum = helper.multiply(norm, tariff)

BigDecimal totalSum = sum

BigDecimal ndsSum = helper.getNdsFrom(sum)

//a.kotvinskiy Объем ТКО в месяц

BigDecimal amountBase = position.getVolumeYear()/12


Accrual accrual = new Accrual()

accrual.setContractPosition(position)

accrual.setPeriod(period)

accrual.setContragent(position.getContragent())

accrual.setAmount(norm)

//a.kotvinskiy /--

// Недостающие атрибуты

accrual.setAmountBase(amountBase)

accrual.setTotalSumBase(totalSum)

accrual.setNdsSumBase(totalSum-price.multiply(amountBase))

//a.kotvinskiy --/

accrual.setPrice(tariff)

accrual.setReductionFactor(BigDecimal.ONE)

accrual.setZoneRatio(BigDecimal.ONE)

accrual.setNds(BigDecimal.valueOf(20))

accrual.setSum(sum)

accrual.setTotalSum(totalSum)

accrual.setNdsSum(ndsSum)

accrual.setComment('По-среднему')

accrual.setDebugComment('')

accrual.setDocumentNumber(documentNumber)

accrual.setDocumentDate(billDate)


return accrual

}

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