package com.ruoyi.web.controller.api;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.aizuda.bpm.engine.entity.FlwTask;
import com.aizuda.bpm.mybatisplus.mapper.FlwTaskMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.constant.DictConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.ProcessCategoryEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WebUtils;
import com.ruoyi.system.bo.ProcessStartBO;
import com.ruoyi.system.dto.RevokeDTO;
import com.ruoyi.system.dto.SetContractDto;
import com.ruoyi.system.dto.TContractDTO;
import com.ruoyi.system.dto.TerminateContractDTO;
import com.ruoyi.system.export.ContractExport;
import com.ruoyi.system.model.*;
import com.ruoyi.system.query.TContractBillQuery;
import com.ruoyi.system.query.TContractQuery;
import com.ruoyi.system.service.*;
import com.ruoyi.system.task.base.QuartzManager;
import com.ruoyi.system.task.base.TimeJobType;
import com.ruoyi.system.task.jobs.StateProcessJob;
import com.ruoyi.system.vo.BillVO;
import com.ruoyi.system.vo.CheckAcceptRecordVO;
import com.ruoyi.system.vo.TContractVO;
import com.ruoyi.web.controller.tool.NumberToChineseUtils;
import com.ruoyi.web.controller.tool.WordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
*
* 合同管理 前端控制器
*
*
* @author xiaochen
* @since 2025-01-17
*/
@Api(tags = "合同管理")
@RestController
@RequestMapping("/t-contract")
public class TContractController {
@Autowired
private TContractService contractService;
@Autowired
private TContractRentTypeService contractRentTypeService;
@Autowired
private THouseService houseService;
@Autowired
private TBillService billService;
@Autowired
private TCheckAcceptRecordService checkAcceptRecordService;
@Autowired
private StateProcessTemplateService stateProcessTemplateService;
@Autowired
private FlwTaskMapper flwTaskMapper;
@ApiOperation(value = "测试生成账单")
@PostMapping(value = "/testBill")
public R testBill(String id) {
TContract contract = contractService.getById(id);
// 查询所有已签订的合同并且未生成第一笔账单的
List bills = new ArrayList<>();
List contractRentTypes = contractRentTypeService.list();
contract.setFirstPayTime(contract.getStartTime().plusDays(10));
// 第一次应缴费日期
LocalDateTime firstPayTime = contract.getStartTime().plusDays(10).withHour(0).withMinute(0).withSecond(0);
TBill rentBill = new TBill();
rentBill.setContractId(contract.getId());
rentBill.setContractNumber(contract.getContractNumber());
rentBill.setPayableFeesTime(firstPayTime.toLocalDate());
rentBill.setPayFeesStatus("1");
rentBill.setBillType("1");
rentBill.setStartTime(contract.getStartPayTime());
TContractRentType tContractRentType = contractRentTypes.stream().filter(e -> e.getContractId().equals(contract.getId())).findFirst().orElse(null);
if (tContractRentType!=null && contract.getStartPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12).isAfter(tContractRentType.getChangeTime())){
// 计算租金变动的天数
long moneyDays = ChronoUnit.DAYS.between(tContractRentType.getChangeTime(), contract.getStartPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12))+1L;
contract.setChangeTime(LocalDateTime.now());
// 递增递减的租金
BigDecimal contractRentTypeMoney = new BigDecimal("0");
// 不递增递减的租金
BigDecimal originalMoney = new BigDecimal("0");
// 原租金
switch (tContractRentType.getIncreasingDecreasingType()){
case 1:
switch (tContractRentType.getIncreasingDecreasing()){
case 1:
contractRentTypeMoney =contractRentTypeMoney.add(contract.getChangeRent().multiply(new BigDecimal(100).add(tContractRentType.getNumericalValue())).divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN).divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(moneyDays)));
contract.setChangeRent(contractRentTypeMoney);
break;
case 2:
contractRentTypeMoney = contractRentTypeMoney.add(contract.getChangeRent().multiply((new BigDecimal(100).subtract(tContractRentType.getNumericalValue()))).divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN).divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(moneyDays)).divide(new BigDecimal(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12),2,BigDecimal.ROUND_DOWN));
contract.setChangeRent(contractRentTypeMoney);
break;
}
break;
case 2:
switch (tContractRentType.getIncreasingDecreasing()){
case 1:
contractRentTypeMoney =contractRentTypeMoney.add(contract.getChangeRent().add(tContractRentType.getNumericalValue())).divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(moneyDays));
contract.setChangeRent(contractRentTypeMoney);
break;
case 2:
contractRentTypeMoney = contractRentTypeMoney.add(contract.getChangeRent().subtract(tContractRentType.getNumericalValue())).divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(moneyDays));
contract.setChangeRent(contractRentTypeMoney);
break;
}
break;
}
// 不需要涨租金的时间段
if (contract.getFirstPayTime().isBefore(tContractRentType.getChangeTime())){
long originalDays = ChronoUnit.DAYS.between(contract.getFirstPayTime(), tContractRentType.getChangeTime());
originalMoney=originalMoney.add(contract.getMonthRent().divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN))
.multiply(new BigDecimal(originalDays));
rentBill.setPayableFeesMoney(contractRentTypeMoney.add(originalMoney));
rentBill.setOutstandingMoney(rentBill.getPayableFeesMoney());
}else{
rentBill.setPayableFeesMoney(contractRentTypeMoney);
rentBill.setOutstandingMoney(rentBill.getPayableFeesMoney());
}
if (contract.getFirstPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12).isAfter(contract.getEndTime())){
rentBill.setEndTime(contract.getFirstPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12));
}else{
rentBill.setEndTime(contract.getEndTime());
}
}else{
if (contract.getFirstPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12).isAfter(contract.getEndTime())){
rentBill.setEndTime(contract.getFirstPayTime().plusMonths(contract.getPayType().equals("1")? 1:contract.getPayType().equals("2")? 3:12));
}else{
rentBill.setEndTime(contract.getEndTime());
}
// 不走递增递减
long allDays = ChronoUnit.DAYS.between(contract.getFirstPayTime(), rentBill.getEndTime());
rentBill.setPayableFeesMoney(contract.getMonthRent().divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(allDays)));
rentBill.setOutstandingMoney(rentBill.getPayableFeesMoney());
}
// 租金账单
bills.add(rentBill);
// 押金账单
TBill depositBill = new TBill();
depositBill.setContractId(contract.getId());
depositBill.setContractNumber(contract.getContractNumber());
depositBill.setPayableFeesMoney(contract.getDeposit());
depositBill.setOutstandingMoney(depositBill.getPayableFeesMoney());
depositBill.setPayableFeesTime(firstPayTime.toLocalDate());
depositBill.setPayFeesStatus("1");
depositBill.setBillType("2");
contractService.updateById(contract);
billService.save(rentBill);
billService.save(depositBill);
return R.ok();
}
@ApiOperation(value = "获取合同分页列表")
@PostMapping(value = "/contractList")
@PreAuthorize("@ss.hasPermi('system:contract:list')")
public R> contractList(@RequestBody TContractQuery query) {
return R.ok(contractService.contractList(query));
}
@Log(title = "合同管理-新增合同", businessType = BusinessType.INSERT)
@ApiOperation(value = "新增合同")
@PostMapping(value = "/addContract")
@PreAuthorize("@ss.hasPermi('system:contract:add')")
public R addContract(@Validated @RequestBody TContractDTO dto) {
long count = contractService.count(new LambdaQueryWrapper().eq(TContract::getContractNumber, dto.getContractNumber()));
if (count!=0){
return R.fail("合同编号不可重复");
}
dto.setChangeRent(dto.getMonthRent());
contractService.save(dto);
if (dto.getStatus().equals("2")){
//发起合同新增审批
ProcessStartBO processStartBO = new ProcessStartBO();
processStartBO.setCategory(ProcessCategoryEnum.CATEGORY1.getValue().toString());
processStartBO.setModuleName("合同新增审批");
processStartBO.setName(dto.getContractName());
//需要显示发起申请人所在单位
// String cedName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
// String remark = String.format("【镇/街】:%s,【征收实施单位】:%s,【申请金额】:%s万元", stateProject.getStreet(), cedName, stateApplyRecord.getAmount());
processStartBO.setRemark("");
Map variable = new HashMap<>();
variable.put("projectId", dto.getId());
processStartBO.setVariable(variable);
//开启工作流程
Boolean start = stateProcessTemplateService.start(processStartBO);
if(start){
FlwTask flwTask = flwTaskMapper.selectOne(Wrappers.lambdaQuery(FlwTask.class)
.like(FlwTask::getVariable, dto.getId())
.orderByDesc(FlwTask::getCreateTime)
.last("LIMIT 1"));
if(Objects.nonNull(flwTask)){
// 添加定时任务
Map maps =
new ImmutableMap.Builder().
put("id", flwTask.getId())
.build();
QuartzManager.addJob(StateProcessJob.class, (StateProcessJob.name+flwTask.getId()).toUpperCase(), TimeJobType.AUTO_AUDIT,new Date(new Date().getTime()+10*1000L), maps);
}
}
}
if (dto.getIsIncreasing()){
TContractRentType tContractRentType = new TContractRentType();
tContractRentType.setContractId(dto.getId());
tContractRentType.setIncreasingDecreasing(dto.getIncreasingDecreasing());
tContractRentType.setIncreasingDecreasingType(dto.getIncreasingDecreasingType());
tContractRentType.setNumericalValue(dto.getNumericalValue());
tContractRentType.setChangeTime(dto.getChangeTime());
tContractRentType.setCycleTime(dto.getCycleTime());
contractRentTypeService.save(tContractRentType);
}
return R.ok();
}
@Log(title = "合同管理-编辑合同", businessType = BusinessType.UPDATE)
@ApiOperation(value = "编辑合同")
@PostMapping(value = "/updateContract")
@PreAuthorize("@ss.hasPermi('system:contract:update')")
public R updateContract(@Validated @RequestBody TContractDTO dto) {
contractService.updateById(dto);
contractRentTypeService.remove(new LambdaQueryWrapper()
.eq(TContractRentType::getContractId,dto.getId()));
if (dto.getIsIncreasing()){
TContractRentType tContractRentType = new TContractRentType();
tContractRentType.setContractId(dto.getId());
tContractRentType.setIncreasingDecreasing(dto.getIncreasingDecreasing());
tContractRentType.setIncreasingDecreasingType(dto.getIncreasingDecreasingType());
tContractRentType.setNumericalValue(dto.getNumericalValue());
tContractRentType.setChangeTime(dto.getChangeTime());
tContractRentType.setCycleTime(dto.getCycleTime());
contractRentTypeService.save(tContractRentType);
}
return R.ok();
}
@Log(title = "合同管理-批量删除合同", businessType = BusinessType.DELETE)
@ApiOperation(value = "批量删除合同")
@PreAuthorize("@ss.hasPermi('system:contract:delete')")
@DeleteMapping(value = "/deleteContractByIds")
public R deleteContractByIds(@RequestParam String ids) {
if (StringUtils.isNotEmpty(ids)){
contractService.removeBatchByIds(Arrays.asList(ids.split(",")));
}
return R.ok();
}
@ApiOperation(value = "查询合同信息信息")
@GetMapping(value = "/getContractById")
@PreAuthorize("@ss.hasPermi('system:contract:detail')")
public R getContractById(@RequestParam String id) {
TContractVO res = new TContractVO();
TContract contract = contractService.getById(id);
BeanUtils.copyProperties(contract,res);
res.setPayType(DictUtils.getDictLabel(DictConstants.DICT_TYPE_CONTRACT_PAY_TYPE,res.getPayType()));
res.setStatus(DictUtils.getDictLabel(DictConstants.DICT_TYPE_CONTRACT_STATUS,res.getStatus()));
TContractRentType contractRentType = contractRentTypeService.lambdaQuery().eq(TContractRentType::getContractId, id).one();
if (contractRentType!=null){
BeanUtils.copyProperties(contractRentType,res);
}
TContract oldContract = contractService.getOne(new LambdaQueryWrapper()
.eq(TContract::getHouseId,contract.getHouseId())
.eq(TContract::getStatus, 4)
.le(TContract::getStartTime, LocalDateTime.now())
.ge(TContract::getEndTime, LocalDateTime.now()));
THouse house = houseService.getById(contract.getHouseId());
if (oldContract!=null){
house.setTenantType(oldContract.getPayType());
}
res.setHouse(house);
List list = billService.lambdaQuery()
.eq(TBill::getContractId, id)
.in(TBill::getPayFeesStatus, Arrays.asList("1,4"))
.list();
BigDecimal payMoney = new BigDecimal("0");
for (TBill tBill : list) {
payMoney = payMoney.add(tBill.getPayFeesMoney()).add(tBill.getPayableFeesPenalty());
}
TCheckAcceptRecord tCheckAcceptRecord = checkAcceptRecordService.lambdaQuery().eq(TCheckAcceptRecord::getContractId, id).one();
res.setCheckResult(Objects.nonNull(tCheckAcceptRecord)?tCheckAcceptRecord.getCheckResult():false);
res.setPayMoney(payMoney);
return R.ok(res);
}
@Log(title = "合同管理-撤销审批", businessType = BusinessType.UPDATE)
@ApiOperation(value = "撤销审批")
@PreAuthorize("@ss.hasPermi('system:contract:revoke')")
@PostMapping(value = "/updateContractStatus")
public R updateContractStatus(@RequestBody RevokeDTO dto) {
TContract contract = contractService.getById(dto.getContractId());
contract.setStatus("1");
contractService.updateById(contract);
// 撤销审批实例
stateProcessTemplateService.revoke(dto.getInstanceId());
return R.ok();
}
@PreAuthorize("@ss.hasPermi('system:contract:confirm')")
@Log(title = "合同管理-确认结算", businessType = BusinessType.UPDATE)
@ApiOperation(value = "确认结算")
@PostMapping(value = "/confirmSettlement")
public R confirmSettlement(String id) {
TContract contract = contractService.getById(id);
contract.setStatus("8");
contractService.updateById(contract);
return R.ok();
}
@ApiOperation(value = "终止合同剩余未缴费账单列表")
@PostMapping(value = "/contractBillList")
@PreAuthorize("@ss.hasPermi('system:contract:billList')")
public R> contractBillList(@RequestBody TContractBillQuery query) {
return R.ok(contractService.contractBillList(query));
}
@ApiOperation(value = "终止合同")
@PostMapping(value = "/terminateContract")
@PreAuthorize("@ss.hasPermi('system:contract:terminate')")
public R terminateContract(@RequestBody TerminateContractDTO dto) {
contractService.terminateContract(dto);
return R.ok();
}
@ApiOperation(value = "根据合同id查看验收记录")
@GetMapping(value = "/getCheckByContractId")
@PreAuthorize("@ss.hasPermi('system:contract:checkDetail')")
public R getCheckByContractId(String id) {
return R.ok(contractService.getCheckByContractId(id));
}
@Autowired
private WordUtil wordUtil;
@ApiOperation(value = "生成合同附件")
@PostMapping("/set")
@Log(title = "生成合同附件", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:contract:set')")
public R> set(@RequestBody SetContractDto dto,HttpServletResponse response){
List list = contractService.lambdaQuery().in(TContract::getId, dto.getIds()).list();
List res = new ArrayList<>();
for (TContract contract : list) {
THouse tHouse = houseService.getById(contract.getHouseId());
Map templateParam = new HashMap<>(5);
templateParam.put("partyOneName", contract.getPartyOneName());
templateParam.put("partyTwoName", contract.getPartyTwoName());
templateParam.put("houseAddress", tHouse.getHouseAddress());
templateParam.put("houseArea", tHouse.getHouseArea()+"m²");
templateParam.put("startTime", DateUtils.localDateTimeToStringYear(contract.getStartTime()));
templateParam.put("endTime", DateUtils.localDateTimeToStringYear(contract.getEndTime()));
templateParam.put("monthRent", "¥¥"+contract.getMonthRent()+"元");
templateParam.put("monthRentString", "人民币"+NumberToChineseUtils.numberToChinese(contract.getMonthRent().setScale(2, BigDecimal.ROUND_DOWN).doubleValue()));
String totalYear = Objects.nonNull(contract.getTotalYear())?contract.getTotalYear().toString():"";
templateParam.put("totalYear", "¥¥"+totalYear+"元");
String totalYearString = StringUtils.isNotEmpty(totalYear)?NumberToChineseUtils.numberToChinese(contract.getTotalYear().setScale(2, BigDecimal.ROUND_DOWN).doubleValue()):"";
templateParam.put("totalYearString", "人民币"+totalYearString);
templateParam.put("payType", contract.getPayType().equals("1")?"月":contract.getPayType().equals("2")?"季":"年");
templateParam.put("firstRent", "¥"+(contract.getPayType().equals("1")?contract.getMonthRent():contract.getPayType().equals("2")?contract.getMonthRent().multiply(new BigDecimal("3")):contract.getMonthRent().multiply(new BigDecimal("12"))).setScale(2,BigDecimal.ROUND_DOWN)+"元");
templateParam.put("firstRentString", "人民币"+NumberToChineseUtils.numberToChinese((contract.getPayType().equals("1")?contract.getMonthRent():contract.getPayType().equals("2")?contract.getMonthRent().multiply(new BigDecimal("3")):contract.getMonthRent().multiply(new BigDecimal("12")).setScale(2,BigDecimal.ROUND_DOWN)).doubleValue()));
templateParam.put("nextPayTime", contract.getPayType().equals("1")?"月":contract.getPayType().equals("2")?"季":"年");
templateParam.put("deposit", "¥"+contract.getDeposit()+"元");
templateParam.put("depositString", NumberToChineseUtils.numberToChinese(contract.getDeposit().setScale(2, BigDecimal.ROUND_DOWN).doubleValue()));
templateParam.put("partyOnePerson", contract.getPartyOnePerson());
templateParam.put("partyOnePhone", contract.getPartyOnePhone());
templateParam.put("partyTwoPerson", contract.getPartyTwoPerson());
templateParam.put("partyTwoPhone", contract.getPartyTwoPhone());
String url = wordUtil.generatePdf("/template", "1_yzj_租赁合同.xml", templateParam, "租赁合同", "E:\\");
res.add(url);
}
return R.ok(res);
}
/**
* 导出
*/
@ApiOperation(value = "导出")
@PreAuthorize("@ss.hasPermi('system:contract:export')")
@Log(title = "导出", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void exportOpticalInspection(@RequestBody TContractQuery query)
{
List contractExports = new ArrayList<>();
List exportList = contractService.contractExportList(query);
for (TContract contract : exportList) {
ContractExport contractExport = new ContractExport();
contractExport.setContractNumber(contract.getContractNumber());
contractExport.setContractName(contract.getContractName());
contractExport.setPartyOneName(contract.getPartyOneName());
contractExport.setPartyTwoName(contract.getPartyTwoName());
contractExport.setCreateTime(DateUtils.localDateTimeToStringYear(contract.getCreateTime()));
contractExport.setStartTime(DateUtils.localDateTimeToStringYear(contract.getStartTime()));
contractExport.setEndTime(DateUtils.localDateTimeToStringYear(contract.getEndTime()));
contractExport.setPayType(DictUtils.getDictLabel(DictConstants.DICT_TYPE_CONTRACT_PAY_TYPE,contract.getPayType()));
contractExport.setDeposit(contract.getDeposit()+"");
contractExport.setStatus(DictUtils.getDictLabel(DictConstants.DICT_TYPE_CONTRACT_STATUS,contract.getStatus()));
contractExports.add(contractExport);
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ContractExport.class, contractExports);
HttpServletResponse response = WebUtils.response();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
ServletOutputStream outputStream = null;
try {
String fileName = URLEncoder.encode("合同列表.xls", "utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}