From 55aee6fd5f6a3ca040408c018beb74bca579ccd4 Mon Sep 17 00:00:00 2001 From: winter <664946893@qq.com> Date: Sat, 4 Jan 2025 19:54:37 +0800 Subject: [PATCH] fix --- .../iformall/domain/po/WxRentContract.java | 3 + .../impl/WxRentContractServiceImpl.java | 6732 +++++++++-------- .../resources/mapper/WxRentContractMapper.xml | 3 +- 3 files changed, 3381 insertions(+), 3357 deletions(-) diff --git a/mallinkService/src/main/java/com/iformall/domain/po/WxRentContract.java b/mallinkService/src/main/java/com/iformall/domain/po/WxRentContract.java index 5015b8e0c..2bcbaa419 100644 --- a/mallinkService/src/main/java/com/iformall/domain/po/WxRentContract.java +++ b/mallinkService/src/main/java/com/iformall/domain/po/WxRentContract.java @@ -198,6 +198,9 @@ public class WxRentContract extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value = "保底营业额", name = "revenue") private String revenue; + @io.swagger.annotations.ApiModelProperty(value = "最低扣点营业额(达到此营业额才会扣点)", name = "limitRevenue") + private String limitRevenue; + @io.swagger.annotations.ApiModelProperty(value = "联营扣点租金取高租金价格是否固定", name = "revenueFixedRentPrice") private Integer revenueFixedRentPrice; @io.swagger.annotations.ApiModelProperty(value = "联营扣点租金取高租金固定价格", name = "revenueRentPrice") diff --git a/mallinkService/src/main/java/com/iformall/service/impl/WxRentContractServiceImpl.java b/mallinkService/src/main/java/com/iformall/service/impl/WxRentContractServiceImpl.java index b39b38751..46fc75c0e 100644 --- a/mallinkService/src/main/java/com/iformall/service/impl/WxRentContractServiceImpl.java +++ b/mallinkService/src/main/java/com/iformall/service/impl/WxRentContractServiceImpl.java @@ -1,3361 +1,3381 @@ -package com.iformall.service.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.common.Result; -import com.iformall.common.ResultData; -import com.iformall.common.SysConfigConstant; -import com.iformall.domain.po.MallUserInfo; -import com.iformall.domain.po.SysConfig; -import com.iformall.domain.po.WxAllBill; -import com.iformall.domain.po.WxBillAction; -import com.iformall.domain.po.WxContractCustomers; -import com.iformall.domain.po.WxContractShop; -import com.iformall.domain.po.WxEnergyFees; -import com.iformall.domain.po.WxFlowModel; -import com.iformall.domain.po.WxFlowRecord; -import com.iformall.domain.po.WxMall; -import com.iformall.domain.po.WxMerchant; -import com.iformall.domain.po.WxMerchantTradeDaily; -import com.iformall.domain.po.WxPayAccountBill; -import com.iformall.domain.po.WxPropertyContract; -import com.iformall.domain.po.WxRentContract; -import com.iformall.domain.po.WxRentContractFreePeriod; -import com.iformall.domain.po.WxRentContractRevenueJump; -import com.iformall.domain.po.WxRentContractRevenueSales; -import com.iformall.domain.po.WxShop; -import com.iformall.domain.po.WxShopUsers; -import com.iformall.domain.po.WxShopUsersInfo; -import com.iformall.domain.po.base.TenantEntity; -import com.iformall.domain.vo.BillTimeVo; -import com.iformall.domain.vo.RatioVo; -import com.iformall.domain.vo.RentContractFreePeriodVo; -import com.iformall.domain.vo.WxBillSum; -import com.iformall.domain.vo.WxRentContractRevenueSetSalesVo; -import com.iformall.domain.vo.WxRentContractYearsSumVo; -import com.iformall.domain.vo.WxRentContractYearsVo; -import com.iformall.enums.EnumBillAction; -import com.iformall.enums.EnumBillAllType; -import com.iformall.enums.EnumBillExtraCreateFrom; -import com.iformall.enums.EnumBillStatus; -import com.iformall.enums.EnumContractCustomersStatus; -import com.iformall.enums.EnumContractOperationType; -import com.iformall.enums.EnumContractReceivePeriodUnit; -import com.iformall.enums.EnumEndProperty; -import com.iformall.enums.EnumFeesStandardsCalcuteUnit; -import com.iformall.enums.EnumFlowKey; -import com.iformall.enums.EnumFlowRecordStatus; -import com.iformall.enums.EnumFromType; -import com.iformall.enums.EnumGetRatioFrom; -import com.iformall.enums.EnumIsPreview; -import com.iformall.enums.EnumMissTimeType; -import com.iformall.enums.EnumPriceUnit; -import com.iformall.enums.EnumRentAgileType; -import com.iformall.enums.EnumRentContractAdjustPeriod; -import com.iformall.enums.EnumRentContractAdjustRatioWay; -import com.iformall.enums.EnumRentContractAgileFeesType; -import com.iformall.enums.EnumRentContractAppStatus; -import com.iformall.enums.EnumRentContractManageFeeType; -import com.iformall.enums.EnumRentContractStatus; -import com.iformall.enums.EnumRentContractType; -import com.iformall.enums.EnumRentDayPriceCalcute; -import com.iformall.enums.EnumRentShopType; -import com.iformall.enums.EnumRentStartType; -import com.iformall.enums.EnumShopUsersStatus; -import com.iformall.enums.EnumShopUsersType; -import com.iformall.enums.EnumSystemUserType; -import com.iformall.enums.EnumTradeDailyDateType; -import com.iformall.enums.EnumYesOrNo; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.WxAllBillMapper; -import com.iformall.mapper.WxBusinessMapper; -import com.iformall.mapper.WxContractCustomersMapper; -import com.iformall.mapper.WxContractShopMapper; -import com.iformall.mapper.WxFlowRecordMapper; -import com.iformall.mapper.WxMerchantMapper; -import com.iformall.mapper.WxMerchantShopMapper; -import com.iformall.mapper.WxMerchantTradeDailyMapper; -import com.iformall.mapper.WxPropertyContractMapper; -import com.iformall.mapper.WxRentContractFreePeriodMapper; -import com.iformall.mapper.WxRentContractMapper; -import com.iformall.mapper.WxRentContractRevenueJumpMapper; -import com.iformall.mapper.WxRentContractRevenueSalesMapper; -import com.iformall.mapper.WxShopMapper; -import com.iformall.service.SysConfigService; -import com.iformall.service.WxAgileContractService; -import com.iformall.service.WxBillActionService; -import com.iformall.service.WxEnergyService; -import com.iformall.service.WxFlowRecordService; -import com.iformall.service.WxFlowService; -import com.iformall.service.WxMallService; -import com.iformall.service.WxMerchantService; -import com.iformall.service.WxPayAccountBillService; -import com.iformall.service.WxPropertyContractService; -import com.iformall.service.WxRentContractService; -import com.iformall.service.WxShopService; -import com.iformall.service.helper.WxBillAllHelper; -import com.iformall.service.helper.WxRentContractHelper; -import com.iformall.utils.Constant; -import com.iformall.utils.DateUtils; -import com.iformall.utils.DownFileUtil; -import com.iformall.utils.PriceUtil; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.collections.map.HashedMap; -import org.apache.commons.compress.utils.Lists; -import org.apache.commons.lang3.StringUtils; -import org.apache.shiro.SecurityUtils; -import org.flowable.engine.RuntimeService; -import org.flowable.engine.TaskService; -import org.flowable.task.api.Task; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * @author gongbiao - */ -@Service -public class WxRentContractServiceImpl implements WxRentContractService { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private String fmUploadDir; - - @Autowired - WxRentContractMapper wxRentContractMapper; - - @Autowired - WxRentContractFreePeriodMapper wxRentContractFreePeriodMapper; - - @Autowired - WxRentContractRevenueJumpMapper wxRentContractRevenueJumpMapper; - - @Autowired - WxRentContractRevenueSalesMapper wxRentContractRevenueSalesMapper; - - @Autowired - WxContractCustomersMapper wxContractCustomersMapper; - - @Autowired - WxContractShopMapper wxContractShopMapper; - - @Autowired - WxShopMapper wxShopMapper; - - @Lazy - @Autowired - WxMerchantService wxMerchantService; - - @Autowired - WxPropertyContractMapper wxPropertyContractMapper; - - @Autowired - WxMerchantMapper wxMerchantMapper; - - @Autowired - WxBusinessMapper wxBusinessMapper; - - @Lazy - @Autowired - WxMallService wxMallService; - - @Lazy - @Autowired - WxFlowRecordService wxFlowRecordService; - - @Lazy - @Autowired - RuntimeService runtimeService; - - @Lazy - @Autowired - private TaskService taskService; - - @Lazy - @Autowired - private WxFlowService wxFlowService; - - @Autowired - WxMerchantShopMapper wxMerchantShopMapper; - - @Autowired - WxFlowRecordMapper wxFlowRecordMapper; - - @Autowired - WxAllBillMapper wxAllBillMapper; - - @Lazy - @Autowired - WxPropertyContractService wxPropertyContractService; - - @Lazy - @Autowired - WxAgileContractService wxAgileContractService; - - @Lazy - @Autowired - WxPayAccountBillService wxPayAccountBillService; - - @Lazy - @Autowired - WxShopService wxShopService; - - @Autowired - WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper; - - @Lazy - @Autowired - WxBillAllHelper wxBillAllHelper; - - @Lazy - @Autowired - WxEnergyService wxEnergyService; - - @Lazy - @Autowired - SysConfigService sysConfigService; - - @Lazy - @Autowired - private WxBillActionService wxBillActionService; - - @Override - public List findList(WxRentContract record){ - return wxRentContractMapper.findList(record); - } - - @Override - public List findIdList(WxRentContract record){ - return wxRentContractMapper.findIdList(record); - } - - @Override - public Map getById(Long id,Integer noBillList) { - Map result = new HashMap<>(); - WxRentContract wxRentContract = wxRentContractMapper.selectById(id); - if (wxRentContract == null) { - throw new MallinkException(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); - } - - WxContractCustomers customers = wxContractCustomersMapper.selectById(wxRentContract.getCustomersId(),wxRentContract.getTenantId()); - wxRentContract.setCustomerType(customers.getPrincipalType()); - wxRentContract.setCustomerLinkPerson(customers.getLinkPerson()); - wxRentContract.setCustomerName(customers.getName()); - wxRentContract.setCustomerPhone(customers.getPhone()); - wxRentContract.setCustomerLegalPerson(customers.getLegalPerson()); - - //init dateDiff - if(wxRentContract.getRentalStartDate() != null && wxRentContract.getRentalEndDate() != null){ - //加1天 - Date newEndDate = DateUtils.getDaySet(wxRentContract.getRentalEndDate(),Calendar.DATE,1); - int[] array = DateUtils.getDiff(wxRentContract.getRentalStartDate(),newEndDate); - result.put("totalPeriodMonth",array[0]); - result.put("totalPeriodDay",array[1]); - } - - //init 租赁单价 - String rentInfo = wxRentContract.getRentInfo(); - if(StringUtils.isNotBlank(rentInfo)){ - JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); - int size = rentInfoArray.size(); - //查询rent_info 包括shopId - for (int i = 0; i < size; i++) { - JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); - BigDecimal rentPrice = rentInfoObject.getBigDecimal("rentPrice"); - //wxRentContract.setShopId(rentInfoObject.getLong("shopId")); - String price = wxRentContract.getPrice(); - if(rentPrice == null){ - if(StringUtils.isNotBlank(wxRentContract.getRentArea()) && !"0".equals(wxRentContract.getRentArea()) && !"0.00".equals(wxRentContract.getRentArea()) && !"0.0".equals(wxRentContract.getRentArea()) ) { - Double rentArea = Double.parseDouble(wxRentContract.getRentArea()); - rentPrice = new BigDecimal(price).divide(new BigDecimal(rentArea),wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); - rentInfoObject.put("rentPrice", rentPrice); - } - } - } - wxRentContract.setRentInfo(rentInfoArray.toJSONString()); - }else{ - if(wxRentContract.getRentPrice() == null || "0".equals(wxRentContract.getRentPrice())){ - if(StringUtils.isNotBlank(wxRentContract.getRentArea()) && !"0".equals(wxRentContract.getRentArea()) && !"0.00".equals(wxRentContract.getRentArea()) && !"0.0".equals(wxRentContract.getRentArea()) ) { - String price = wxRentContract.getPrice(); - Double rentArea = Double.parseDouble(wxRentContract.getRentArea()); - BigDecimal rentPrice = new BigDecimal(price).divide(new BigDecimal(rentArea),wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); - if(rentPrice.compareTo(new BigDecimal(0)) > 0){ - wxRentContract.setRentPrice(rentPrice.toString()); - }else{ - wxRentContract.setRentPrice("0"); - } - } - - } - } - if(wxRentContract.getPriceUnit() == null){ - wxRentContract.setPriceUnit(EnumPriceUnit.M.getCode()); - } - if(wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode())){ - wxRentContract.setAdjustPeriod(EnumRentContractAdjustPeriod.ADJUST_PERIOD_MONTH.getCode()); - wxRentContract.setPriceUnit(EnumPriceUnit.D.getCode()); - } - - //商场信息 - WxMall wxMall = new WxMall(); - wxMall.setTenantInfo(wxRentContract); - List mallList = wxMallService.findList(wxMall); - if (!mallList.isEmpty()) { - result.put("mall", mallList.get(0)); - } - wxRentContract.setPrice(StringUtils.isNotBlank(wxRentContract.getPrice()) ? wxRentContract.getPrice() : "0"); - wxRentContract.setDeposit(StringUtils.isNotBlank(wxRentContract.getDeposit()) ? wxRentContract.getDeposit() : "0"); - - //免租期 - WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); - fpq.updateTenantInfo(wxRentContract); - fpq.setRentContractId(wxRentContract.getId()); - fpq.setSortColumn("year_index asc,start_date asc"); - List freePeroids = wxRentContractFreePeriodMapper.findList(fpq); - wxRentContract.setFreeVo(freePeroids); - - //跳点设置 - WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); - jq.updateTenantInfo(wxRentContract); - jq.setRentContractId(wxRentContract.getId()); - wxRentContract.setRevenueJumps(wxRentContractRevenueJumpMapper.findList(jq)); - result.put("wxRentContract", wxRentContract); - //关联的店铺 - if (wxRentContract.shopIdsByRentInfo().size()> 0) { - WxShop record = new WxShop(); - //record.setId(wxRentContract.getShopId()); - record.setIds(wxRentContract.shopIdsByRentInfo()); - record.updateTenantInfo(wxRentContract); - PageInfo> shopPageInfo = wxShopService.findListMap(record,1,10000); - List> list = shopPageInfo.getList(); - result.put("wxShops", list); - } else { - result.put("wxShops", Collections.EMPTY_LIST); - } - //设置审批流程状态 - result.put("applyStatus", wxRentContract.getApplyStatus()); - - //发起人备注 - WxFlowRecord wxFlowRecord = new WxFlowRecord(); - wxFlowRecord.setBusinessId(String.valueOf(id)); - wxFlowRecord.setStatus(EnumFlowRecordStatus.NEW.getCode()); - List flowRecordList = wxFlowRecordService.findList(wxFlowRecord); - if(!CollectionUtils.isEmpty(flowRecordList)){ - result.put("remark",flowRecordList.get(0).getRemark()); - } - - //查询预账单用于展示 - if (null != noBillList && EnumYesOrNo.YES.getCode().intValue() == noBillList.intValue()) { - }else { - WxAllBill wxBillRent = new WxAllBill(); - wxBillRent.setRentContractId(id); - wxBillRent.updateTenantInfo(wxRentContract); - wxBillRent.setBillType(EnumBillAllType.RENT.getCode()); - List resultList = wxAllBillMapper.findContractSamePeriodSum(wxBillRent); - result.put("previewBillRentList",resultList); - } - - return result; - } - - @Override - public WxRentContract selectById(Long id) { - return wxRentContractMapper.selectById(id); - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData save(WxRentContract record,MallUserInfo user,String userName,Date oldRentStartDate) { - //保存租赁合同信息 - final IdWorker idWorker = IdWorker.get(); - record.setId(idWorker.nextId()); - int dayType = record.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; - //计租开始时间 - Calendar instance = Calendar.getInstance(); - instance.setTime(record.getRentalStartDate()); - instance.add(dayType, record.getLease()); - instance.add(Calendar.DAY_OF_MONTH, -1); - //计租结束时间 - if (!record.getStartDate().equals(record.getRentalStartDate())) { - instance.clear(); - instance.setTime(record.getRentalStartDate()); - instance.add(Calendar.DAY_OF_MONTH, -1); - record.setEndDate(instance.getTime()); - } else { - record.setEndDate(record.getStartDate()); - } - - if (StringUtils.isEmpty(record.getPrice())) { - record.setPrice("0"); - } - if (StringUtils.isEmpty(record.getDeposit())) { - record.setDeposit("0"); - } - - Date date = new Date(); - record.setCreatetime(date); - record.setCreateBy(user.getId()); - record.setCreateByName(user.getName()); - record.setUpdatetime(date); - record.setUpdateBy(user.getId()); - record.setUpdateByName(user.getName()); - - List shopList = Lists.newArrayList(); - String rentInfo = record.getRentInfo(); - JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); - int size = rentInfoArray.size(); - if (size == 0) { - return new ResultData(ErrorCode.SHOP_NOT_SELECTED); - } - //查询rent_info 包括 shopId - String shopIdStr = ""; - BigDecimal rentArea = new BigDecimal(0); - for (int i = 0; i < size; i++) { - JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); - Long shopId = rentInfoObject.getLong("id"); - rentArea = rentArea.add(new BigDecimal(rentInfoObject.getString("operationArea"))); - if (!shopList.contains(shopId)) { - shopList.add(shopId); - shopIdStr = shopIdStr +","+ shopId; - } - } - record.setRentArea(rentArea.toPlainString()); - setShops(record,shopList); - //关联客户 - setCustomers(record); - try { - record.setApplyStatus(EnumRentContractAppStatus.DEFAULT.getCode()); - record.setStatus(EnumRentContractStatus.UNWRITE.getCode()); - Date tempDate = record.getRentalStartDate(); - record.setRentalStartDate(oldRentStartDate); - record.setShopIdStr(shopIdStr); - record.setAgileType(EnumRentAgileType.STANDARDS_YEAR.getCode()); - wxRentContractMapper.insert(record); - record.setRentalStartDate(tempDate); - } catch (Exception e) { - logger.error("保存租赁合同信息失败,e:" + e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); - } - - return new ResultData(Result.SUCCESS, "保存租赁合同信息成功", record); - } - - public void setCustomers(WxRentContract record) { - WxContractCustomers cq = new WxContractCustomers(); - cq.updateTenantInfo(record); - cq.setPrincipalType(record.getCustomerType()); - cq.setNameEqal(record.getCustomerName()); - cq.setPhoneEqal(record.getCustomerPhone()); - List list = wxContractCustomersMapper.findList(cq); - WxContractCustomers cus = null; - if (null != list && list.size() > 0 ){ - cus = list.get(0); - } - if (null == cus) { - final IdWorker idWorker = IdWorker.get(); - cus = new WxContractCustomers(); - cus.updateTenantInfo(record); - cus.setId(idWorker.nextId()); - cus.setPrincipalType(record.getCustomerType()); - cus.setName(record.getCustomerName()); - cus.setPhone(record.getCustomerPhone()); - cus.setLegalPerson(record.getCustomerLegalPerson()); - cus.setLinkPerson(record.getCustomerLinkPerson()); - cus.setCreateDate(new Date()); - cus.setUpdateDate(new Date()); - cus.setStatus(EnumContractCustomersStatus.TEMP.getCode()); - wxContractCustomersMapper.insert(cus); - }else { - cus.setLinkPerson(record.getCustomerLinkPerson()); - cus.setLegalPerson(record.getCustomerLegalPerson()); - cus.setUpdateDate(new Date()); - wxContractCustomersMapper.updateById(cus); - } - record.setCustomersId(cus.getId()); - } - - public void setShops(WxRentContract record,List shopIdList) { - WxContractShop sdel = new WxContractShop(); - sdel.updateTenantInfo(record); - sdel.setContractId(record.getId()); - wxContractShopMapper.deleteByCondition(sdel); - Map shopAreaMap = record.getRentShopArea(); - if (null != shopIdList && shopIdList.size() > 0 ) { - final IdWorker idWorker = IdWorker.get(); - for ( int i = 0 ; i < shopIdList.size(); i ++) { - Long shopId = shopIdList.get(i); - WxContractShop s = new WxContractShop(); - s.updateTenantInfo(record); - s.setContractId(record.getId()); - s.setShopId(shopIdList.get(i)); - s.setRentArea(shopAreaMap.get(shopId).toPlainString()); - s.setCreateDate(new Date()); - s.setUpdateDate(new Date()); - s.setId(idWorker.nextId()); - wxContractShopMapper.insert(s); - } - } - - } - - - @Override - public List getShopIds(WxRentContract record) { - return record.shopIdsByRentInfo(); - } - - //@Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData update(WxRentContract record, MallUserInfo user,String userName,int from,Date oldRentStartDate,boolean writeComplate,boolean setRevenJumps) { - //查询预账单用于展示 - WxAllBill wxBillRent = new WxAllBill(); - wxBillRent.setRentContractId(record.getId()); - wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); - wxBillRent.updateTenantInfo(record); - List resultList = wxAllBillMapper.findList(wxBillRent); - - //更新 - ResultData resultData = getResultDataForUpdate(record, user,from,oldRentStartDate,writeComplate,setRevenJumps); - if (resultData.code != Result.SUCCESS) { - return resultData; - } - - boolean saveBill = true; - if(CollectionUtils.isEmpty(record.getPreviewBillRentList())) { - if (record.getReceivePeriod() != null && record.getLease() != null - && !record.getReceivePeriod().equals(0) && !record.getLease().equals(0)) { - deletePrewBill(record); - //联营扣点,不设置保底营业额,不生成账单 - //if (EnumRentContractType.RENT_BY_JOINT.getCode().equals(record.getType()) && record.getRevenueRatio().equals(0)) { - //do nothing - // saveBill = false; - //}else { - resultList = buildRent(user, record, EnumIsPreview.YES.getCode(),true); - //} - } - } - - WxRentContract wxRentContract = (WxRentContract)resultData.data; - wxRentContract.setPreviewBillRentList(resultList); - return new ResultData(wxRentContract); - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData updateOneStep(WxRentContract record, MallUserInfo user,String userName,int from,Date oldRentStartDate,boolean writeComplate) { - //查询预账单用于展示 - WxAllBill wxBillRent = new WxAllBill(); - wxBillRent.setRentContractId(record.getId()); - wxBillRent.setSortColumns("starttime asc"); - wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); - wxBillRent.updateTenantInfo(record); - List resultList = wxAllBillMapper.findList(wxBillRent); - - //更新 - setCustomers(record); - ResultData resultData = getResultDataForUpdate(record, user,from,oldRentStartDate,writeComplate,false); - if (resultData.code != Result.SUCCESS) { - return resultData; - } - WxRentContract wxRentContract = (WxRentContract)resultData.data; - wxRentContract.setPreviewBillRentList(resultList); - - WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); - jq.updateTenantInfo(record); - jq.setRentContractId(record.getId()); - wxRentContract.setRevenueJumps(wxRentContractRevenueJumpMapper.findList(jq)); - return new ResultData(wxRentContract); - } - - @Override - public ResultData updateRentStartTime(WxRentContract record, MallUserInfo user) { - //查询预账单用于展示 - WxAllBill wxBillRent = new WxAllBill(); - wxBillRent.setRentContractId(record.getId()); - wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); - wxBillRent.updateTenantInfo(record); - List resultList = wxAllBillMapper.findList(wxBillRent); - - //更新 - WxRentContract contractUpdate = new WxRentContract(); - contractUpdate.setId(record.getId()); - contractUpdate.updateTenantInfo(record); - contractUpdate.setRentStartType(record.getRentStartType()); - contractUpdate.setUpdatetime(new Date()); - contractUpdate.setUpdateBy(user.getId()); - contractUpdate.setUpdateByName(user.getName()); - wxRentContractMapper.updateById(record); - - - WxRentContract rentContract = wxRentContractMapper.selectById(record.getId()); - Date oldDate = record.getRentalStartDate(); - rentContract.setAdjustPeriodHandle(); - if(rentContract.getRentStartType()!=null && rentContract.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){ - rentContract.setRentalStartDate(rentContract.getStartDate()); - } - - deletePrewBill(record); - resultList = buildRent(user, rentContract, EnumIsPreview.YES.getCode(),true); - rentContract.setPreviewBillRentList(resultList); - rentContract.setRentalStartDate(oldDate); - return new ResultData(rentContract); - } - - public ResultData getResultDataForUpdate(WxRentContract record, MallUserInfo user,int from,Date oldRentStartDate,boolean writeFinal,boolean setRevenJumps) { - //更新租赁合同信息 - WxRentContract wxRentContract = wxRentContractMapper.selectById(record.getId()); - if (wxRentContract == null) { - return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); - } - wxRentContract.setPayRatio(record.getPayRatio()); - - int dayType = wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; - - Calendar instance = Calendar.getInstance(); - instance.setTime(record.getRentalStartDate()); - instance.add(dayType, record.getLease()); - instance.add(Calendar.DAY_OF_MONTH, -1); - - if(!EnumFromType.SWITCH.getCode().equals(from)){ - //如果是联营扣点,或者联营取高,需要根据保底营业额来计算 - if (record.getType() != null) { - //联营扣点 - if (record.getType().equals(EnumRentContractType.RENT_BY_JOINT.getCode())) { - String revenue = record.getRevenue(); - if (StringUtils.isBlank(revenue)) { - revenue = "0"; - } - record.setPrice(new BigDecimal(record.getPayRatio()).multiply(new BigDecimal(revenue)).divide(new BigDecimal(100),Constant.default_long_decimal_size,RoundingMode.HALF_UP).toPlainString()); - }else if (record.getType().equals(EnumRentContractType.RENT_BY_AREA_AND_JOINT.getCode())) { - BigDecimal rentPrice = null; - //联营取高,如果是固定金额的话,取固定金额. 不固定的金额,会传price. - if (null != record.getRevenueFixedRentPrice() && record.getRevenueFixedRentPrice().intValue() == EnumYesOrNo.YES.getCode()){ - rentPrice = new BigDecimal(record.getRevenueRentPrice()); - }else { - rentPrice = new BigDecimal(record.getPrice()); - } - record.setPrice(rentPrice.toPlainString()); - } - } - } - - if (StringUtils.isEmpty(record.getPrice())) { - record.setPrice("0"); - } - if (StringUtils.isEmpty(record.getDeposit())) { - record.setDeposit("0"); - } - List shopList = Lists.newArrayList(); - record.setUpdatetime(new Date()); - record.setUpdateBy(user.getId()); - record.setUpdateByName(user.getName()); - String rentInfo = record.getRentInfo(); - JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); - int size = rentInfoArray.size(); - if (size == 0) { - return new ResultData(ErrorCode.SHOP_NOT_SELECTED); - } - //查询rent_info 包括 shopId - String shopIdStr = ""; - BigDecimal rentArea = new BigDecimal(0); - for (int i = 0; i < size; i++) { - JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); - WxRentContract wxRentContractQuery = new WxRentContract(); - wxRentContractQuery.updateTenantInfo(record); - Long shopId = rentInfoObject.getLong("id"); - String shopNumber = rentInfoObject.getString("shopNumber"); - if (shopId == null) { - return new ResultData(ErrorCode.SHOP_IS_NOT_FOUND.getCode(), "店铺 " + shopNumber + " 已删除"); - } - rentArea = rentArea.add(new BigDecimal(rentInfoObject.getString("operationArea"))); - wxRentContractQuery.setId(record.getId()); - if (!shopList.contains(shopId)) { - shopList.add(shopId); - shopIdStr = shopIdStr +","+shopId; - } - } - setShops(record,shopList); - record.setRentArea(rentArea.toPlainString()); - try { - Date tempDate = record.getRentalStartDate(); - record.setRentalStartDate(oldRentStartDate); - record.setShopIdStr(shopIdStr); - if (writeFinal) { - record.setStatus(EnumRentContractStatus.DRAFT.getCode()); - }else { - record.setStatus(wxRentContract.getStatus()); - } - record.setApplyStatus(wxRentContract.getApplyStatus()); - if (StringUtils.isBlank(record.getOperatingManagementFee())){ - record.setOperatingManagementFee(null); - } - if (StringUtils.isBlank(record.getBussinessManagementFee())){ - record.setBussinessManagementFee(null); - } - wxRentContractMapper.updateById(record); - record.setRentalStartDate(tempDate); - - if (setRevenJumps) { - WxRentContractRevenueJump jumpsDel = new WxRentContractRevenueJump(); - jumpsDel.updateTenantInfo(record); - jumpsDel.setRentContractId(record.getId()); - wxRentContractRevenueJumpMapper.deleteByContract(jumpsDel); - - if (null != record.getRevenueJumps()) { - final IdWorker idWorker = IdWorker.get(); - List jlist = new ArrayList(); - for (int i = 0 ; i < record.getRevenueJumps().size(); i++) { - WxRentContractRevenueJump jp = record.getRevenueJumps().get(i); - if (StringUtils.isNotBlank(jp.getMinMoney())) { - jp.updateTenantInfo(record); - jp.setId(idWorker.nextId()); - jp.setRentContractId(record.getId()); - jp.setCreateTime(new Date()); - jp.setUpdateTime(new Date()); - jlist.add(jp); - } - } - if (jlist.size() > 0 ) { - wxRentContractRevenueJumpMapper.inertJumps(record.getTenantId(), jlist); - } - } - } - - } catch (Exception e) { - logger.error("更新租赁合同信息失败,e:" + e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); - } - //重新查一次 - wxRentContract = wxRentContractMapper.selectById(record.getId()); - return new ResultData(Result.SUCCESS, "保存租赁合同信息成功", wxRentContract); - } - - - @Transactional(rollbackFor = {Exception.class}) - @Override - public void buildDeposit( TenantEntity tenantEntity,MallUserInfo user,Long rentContractId) { - WxRentContract wxRentContract = wxRentContractMapper.selectById(rentContractId); - if (wxRentContract != null && StringUtils.isNotBlank(wxRentContract.getDeposit()) - && new BigDecimal(wxRentContract.getDeposit()).compareTo(new BigDecimal(0)) > 0 ) { - - List shopIdList = wxRentContract.shopIdsByRentInfo(); - - WxShopUsers suq = new WxShopUsers(); - suq.updateTenantInfo(wxRentContract); - suq.setShopIds(shopIdList); - suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); - Map shopUserMap = wxShopService.getShopUserMap(suq); - - WxEnergyFees fq = new WxEnergyFees(); - fq.updateTenantInfo(tenantEntity); - fq.setBillType(EnumBillAllType.RENT_DEPOSIT.getCode()); - Map typeMap = wxEnergyService.getFeesMap(fq); - - //根据不同的科目生成不同的押金账单 - Map feesMap = wxRentContract.getDepositEnergyFees(typeMap); - Map shopAreaRateMap = wxRentContract.getRentShopArea(); - if (null == shopAreaRateMap) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无店铺信息"); - } - List insertList = new ArrayList(); - - for (Iterator it = feesMap.keySet().iterator();it.hasNext();){ - Long energyFeesId = it.next(); - WxEnergyFees depositFee = feesMap.get(energyFeesId); - WxEnergyFees fees = typeMap.get(energyFeesId); - final IdWorker idWorker = IdWorker.get(); - - for (int i = 0 ; i < shopIdList.size(); i++ ) { - Long sid = shopIdList.get(i); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - String cusName = null; - if (null != shopUserMap) { - WxShopUsers su = shopUserMap.get(sid); - if (null != su) { - cusName = su.getName(); - } - } - - WxAllBill wxBillDeposit = new WxAllBill(); - wxBillDeposit.setId(idWorker.nextId()); - wxBillDeposit.setRentContractId(wxRentContract.getId()); - wxBillDeposit.setBillType(EnumBillAllType.RENT_DEPOSIT.getCode()); - wxBillDeposit.setIsPreview(EnumYesOrNo.NO.getCode()); - wxBillDeposit.setCanEdit(EnumYesOrNo.NO.getCode()); - //if (null != fees) { - // wxBillDeposit.setPriceDetail("合同押金项["+fees.getName()+"]"+depositFee.getPrice()+"元"+"/"+fees.getCalcuteUnitName()); - //} - wxBillDeposit.setPay("0"); - String needpay = depositFee.getPrice(); - - // String count = "1"; - // if (null != depositFee.getCalcuteUnit() && depositFee.getCalcuteUnit().intValue() == EnumFeesStandardsCalcuteUnit.MM.getCode().intValue()) { - // count = wxRentContract.getRentArea(); - // } - // String needpay = depositFee.calcuteTotalMoney(wxRentContract.getDecimalSize(), null, null, count, true, null, null); - wxBillDeposit.setReceivePay(new BigDecimal(needpay).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); - wxBillDeposit.setNeedPay(wxBillDeposit.getReceivePay()); - //wxBillDeposit.setOwe(needpay); - //找到计租方式 - int dayType = wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; - - Date date = new Date(); - wxBillDeposit.setStarttime(wxRentContract.getFirstBillDateStart()); - wxBillDeposit.setEndtime(wxRentContract.getFirstBillDateEnd()); - wxBillDeposit.setReceiveDate(wxRentContract.getFirstBillReceiveDate()); - wxBillDeposit.setPeriod(WxRentContractHelper.getPeriod(wxRentContract.getFirstBillReceiveDate())); - //wxBillDeposit.setExpiredDay(0L); - wxBillDeposit.updateTenantInfo(wxRentContract); - //wxBillDeposit.setIsDel(0); - wxBillDeposit.setShopNumber(wxRentContract.getRentInfoShopNumber()); - if (null != user) { - //wxBillDeposit.setUserId(user.getId()); - } - wxBillDeposit.setShopId(sid); - wxBillDeposit.setCusName(cusName); - wxBillDeposit.setRentArea(shoprentArea.toPlainString()); - wxBillDeposit.setCreatetime(date); - if (null != user) { - wxBillDeposit.setCreateBy(user.getId()); - wxBillDeposit.setCreateByName(user.getName()); - } - wxBillDeposit.setUpdatetime(date); - if (null != user) { - wxBillDeposit.setUpdateBy(user.getId()); - wxBillDeposit.setUpdateByName(user.getName()); - } - //wxBillDeposit.setIsDel(EnumDelStatus.NOT_DEL.getCode()); - String rentInfo = wxRentContract.getRentInfo(); - if (rentInfo != null) { - JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); - Map shopInfo = new HashMap<>(); - for (int j = 0, size = rentInfoArray.size(); j < size; j++) { - JSONObject rentInfoObject = rentInfoArray.getJSONObject(j); - shopInfo.put(rentInfoObject.getString("shopNumber"), rentInfoObject.get("deposit")); - } - wxBillDeposit.setShopInfo(JSONObject.toJSONString(shopInfo)); - } - wxBillDeposit.setEnergyFeesId(energyFeesId); - wxBillDeposit.setCreateBy(wxRentContract.getCreateBy()); - wxBillDeposit.setUpdateBy(wxRentContract.getCreateBy()); - wxBillDeposit.setCreateByName(wxRentContract.getCreateByName()); - wxBillDeposit.setUpdateByName(wxRentContract.getCreateByName()); - - insertList.add(wxBillDeposit); - } - } - - try { - if (insertList.size() > 0 ) { - wxAllBillMapper.insertBills(tenantEntity.getTenantId(),insertList); - } - } catch (Exception e) { - logger.error("添加押金账单失败,e:" + e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); - } - } - } - - @Override - public ResultData hasRentStatus(WxRentContract record) { - String rentInfo = record.getRentInfo(); - if (StringUtils.isEmpty(rentInfo)) { - return new ResultData(ErrorCode.SHOP_NOT_SELECTED); - } - String[] split = rentInfo.split(","); - int size = split.length; - //查询rent_info 包括 shopId - for (int i = 0; i < size; i++) { - String shopId = split[i]; - WxShop wxShop = wxShopMapper.selectById(shopId); - WxRentContract wxRentContractQuery = new WxRentContract(); - wxRentContractQuery.updateTenantInfo(record); - String shopNumber = wxShop.getShopNumber(); - if (shopId == null) { - return new ResultData(ErrorCode.SHOP_IS_NOT_FOUND.getCode(), "店铺 " + shopNumber + " 已删除"); - } - //wxRentContractQuery.setShopId(Long.valueOf(shopId)); - int count = wxRentContractMapper.selectRentContractCountByShopId(wxRentContractQuery.getTenantId(),wxRentContractQuery.getParentTenantId(),Long.valueOf(shopId),wxRentContractQuery.getId()); - if (count > 0) { - return new ResultData(ErrorCode.SHOP_IS_RENT.getCode(), "店铺 " + shopNumber + " 已出租"); - } - } - return new ResultData(Result.SUCCESS, "操作成功"); - } - - @Override - public ResultData hasContractNumber(WxRentContract wxRentContract) { - int count = wxRentContractMapper.hasContractNumber(wxRentContract); - return new ResultData(Result.SUCCESS, "操作成功", count > 0 ? true : false); - } - - public void updateInvalidStatus(WxRentContract record) { - Long id = record.getId(); - //审核流程中止 - try { - // 修改合同审核状态 - WxRentContract rentContract = record; - rentContract.setId(id); - rentContract.setApplyStatus(EnumRentContractAppStatus.CANCLE.getCode()); - updateApplyStatus(rentContract); - - //修改flowRecord - WxFlowRecord fr = new WxFlowRecord(); - fr.setBusinessId(String.valueOf(id)); - fr.setCurrStatus(EnumRentContractAppStatus.CANCLE.getCode()); - wxFlowRecordMapper.updateCurrStatus(fr); - - logger.info("合同id:{},开始停止...", id); - //结束审批流 by luozukai - WxFlowModel flowModel = wxFlowService.getModelByType(EnumFlowKey.NEW_RENT_CONTRACT.getCode().intValue(),record); - - WxFlowModel flowModel_pro = wxFlowService.getModelByType(EnumFlowKey.NEW_PRO_CONTRACT.getCode().intValue(),record); - - WxFlowModel flowModel_rent = wxFlowService.getModelByType(EnumFlowKey.NNEW_RENT_CONTRACT.getCode().intValue(),record); - - List keyList = new ArrayList<>(); - if(flowModel != null){ - keyList.add(flowModel.getFlowId()); - } - if(flowModel_pro != null){ - keyList.add(flowModel_pro.getFlowId()); - } - if(flowModel_rent != null){ - keyList.add(flowModel_rent.getFlowId()); - } - keyList.add(EnumFlowKey.CONTRACT.getMessage()); - List tasks = taskService.createTaskQuery() - .processDefinitionKeyIn(keyList) - .processVariableValueEquals("businessId", id+"").list(); - if (!CollectionUtils.isEmpty(tasks)) { - for (Task task : tasks) { - logger.info("合同id:{},taskid:{}", id, task.getId()); - runtimeService.deleteProcessInstance(task.getProcessInstanceId(), "合同作废"); - - // 保存审批历史入 - MallUserInfo mallUserInfo = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute("userSession"); - WxFlowRecord updateRecord = new WxFlowRecord(); - updateRecord.setBusinessId(String.valueOf(id)); - updateRecord.setStatus(EnumFlowRecordStatus.CANCLE.getCode()); - updateRecord.setBusinessType(1); - updateRecord.setUserId(mallUserInfo.getId()); - updateRecord.setProcessInstanceId(task.getProcessInstanceId()); - wxFlowRecordService.saveOrUpdate(updateRecord); - } - } - - } catch (Exception e) { - logger.error("deleteProcessInstance error", e); - } - } - - @Override - @Transactional(rollbackFor = {Exception.class}) - public List buildRent(MallUserInfo user,WxRentContract wxRentContract,Integer isPreview,boolean saveDb) { - List rentList = new ArrayList<>(); - if (wxRentContract != null) { - int receivePeriod = wxRentContract.getReceivePeriod().intValue(); - Integer lease = wxRentContract.getLease(); - Date rentalStartDate = wxRentContract.getRentalStartDate(); - String price = wxRentContract.getPrice(); - if(EnumContractOperationType.JINMAO.getCode().equals(wxRentContract.getOperationType())){ - Date startDate = wxRentContract.getStartDate(); - //rentList = buildRentJinmao(user, wxRentContract, receivePeriod, lease, startDate, price, isPreview,saveDb); - }else{ - rentList = buildRentMonth(user, wxRentContract, receivePeriod, lease, rentalStartDate, isPreview,saveDb); - } - } - return rentList; - } - - @Override - public List getYearList(int years,int month,Date rentalStartDate,Date endContractTime ) { - List yearList = new ArrayList(); - for (int i = 0; i < years; i++) { - Calendar instance = Calendar.getInstance(); - instance.setTime(rentalStartDate); - instance.set(Calendar.MILLISECOND, 0); - instance.add(Calendar.MONTH, month * i); - Date startDate = instance.getTime(); - if (null != endContractTime && endContractTime.before(startDate)) { - yearList.add(endContractTime); - break; - }else { - yearList.add(startDate); - } - } - return yearList; - } - - public List buildRentMonth(MallUserInfo user, WxRentContract wxRentContract, int receivePeriod, Integer lease, Date rentalStartDate,Integer isPreview, boolean saveDb) { - int years = 0; - //计算租金每年的计费基数 - String[] priceArrs = WxRentContractHelper.calcuteRentPrice(wxRentContract); - //计算商业管理费 - String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(wxRentContract); - //计算运营管理费 - String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(wxRentContract); - int month = 12; - int billcount = 0; - List resultList = new ArrayList(); - years = priceArrs.length; - List yearList = getYearList(years,month,rentalStartDate,null); - - String shopInfoStr = getShopInfoStr(wxRentContract); - Map resultMap = buildRent(receivePeriod, priceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs, yearList, wxRentContract.getReceivePeriodUnit(), wxRentContract, user, billcount, isPreview, shopInfoStr,saveDb); - List billRentList = (List)resultMap.get("billList"); - resultList.addAll(billRentList); - return resultList; - } - - public String getShopInfoStr(WxRentContract wxRentContract){ - String shopInfoStr = null; -// if (wxRentContract.getRentShopType().equals(EnumRentShopType.SHOP.getCode())) { - String rentInfo = wxRentContract.getRentInfo(); - JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); - int rentSize = rentInfoArray.size(); - Map shopInfoMap = new HashMap<>(rentSize); - for (int j = 0; j < rentSize; j++) { - JSONObject rentInfoObject = rentInfoArray.getJSONObject(j); - shopInfoMap.put(rentInfoObject.getString("shopNumber"), rentInfoObject.getString("buildArea")); - } - shopInfoStr = JSONObject.toJSONString(shopInfoMap); -// } - return shopInfoStr; - } - - private static Date getCurrentYearRentDate(Date yearEndDate,Date rentDate){ - Calendar calendar = Calendar.getInstance(); - calendar.setTime(yearEndDate); - - Calendar rentCalendar = Calendar.getInstance(); - rentCalendar.setTime(rentDate); - - calendar.set(Calendar.DAY_OF_MONTH,rentCalendar.get(Calendar.DAY_OF_MONTH)); - calendar.set(Calendar.MONTH, rentCalendar.get(Calendar.MONTH)); - return calendar.getTime(); - } - - private List getFreeDays(WxRentContract wxRentContract) { - //免租期 - WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); - fpq.updateTenantInfo(wxRentContract); - fpq.setRentContractId(wxRentContract.getId()); - fpq.setSortColumn("start_date asc"); - List freePeriods = wxRentContractFreePeriodMapper.findList(fpq); - if (null == freePeriods || freePeriods.size() <= 0 ) { - return null; - } - List allDate = new ArrayList(); - for (int i = 0 ; i < freePeriods.size() ; i ++) { - WxRentContractFreePeriod fp = freePeriods.get(i); - List dates = DateUtils.getAllDays(fp.getStartDate(), fp.getEndDate()); - if (null != dates && dates.size() > 0 ) { - allDate.removeAll(dates); - allDate.addAll(dates); - } - } - if (allDate.size() <= 0 ) { - return null; - } - return allDate; - } - - public Map buildRent(int receivePeriod, String[] priceArrs,String[] bussinessManagerPriceArrs,String[] operationManagerPriceArrs, List yearList, int dayType, WxRentContract wxRentContract, MallUserInfo user, int billcount, Integer isPreview, String shopInfoStr,boolean saveDb) { - WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantInfo(wxRentContract); - SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); - Map resultMap = new HashedMap(); - List resultList = new ArrayList(); - List manageList = new ArrayList(); - final IdWorker idWorker = IdWorker.get(); - - Date endDate = null;//每年的截止日期 - if(yearList.size() > 1){ - endDate = yearList.get(1); - } - - List billTimeVoList = new ArrayList<>(); - if(saveDb){ - billTimeVoList = initBillTimeList(yearList,wxRentContract.getRentalStartDate(),wxRentContract.getRentalEndDate(),wxRentContract.getAdjustPeriod(),dayType,receivePeriod,wxRentContract.getPayPeriodRate()); - }else{ - //预账单编辑账期,生成金额 - for (WxAllBill rent:wxRentContract.getPreviewBillRentList()) { - BillTimeVo billTimeVo = new BillTimeVo(); - billTimeVo.setStartDate(rent.getStarttime()); - billTimeVo.setEndDate(rent.getEndtime()); - billTimeVo.setReceiveDate(DateUtils.getDaySet(rent.getStarttime(),Calendar.DATE,-1)); - billTimeVoList.add(billTimeVo); - } - } - - if (null != billTimeVoList && billTimeVoList.size() > 0 ) { - BillTimeVo firstBillTime = billTimeVoList.get(0); - WxRentContract cupdate = new WxRentContract(); - cupdate.updateTenantInfo(wxRentContract); - cupdate.setId(wxRentContract.getId()); - cupdate.setFirstBillDateStart(firstBillTime.getStartDate()); - cupdate.setFirstBillDateEnd(firstBillTime.getEndDate()); - cupdate.setFirstBillReceiveDate(firstBillTime.getReceiveDate()); - cupdate.setDecimalSize(null);//去掉默认的,避免更新 - wxRentContractMapper.updateById(cupdate); - } - - List shopIdList = wxRentContract.shopIdsByRentInfo(); - Map shopAreaRateMap = wxRentContract.getRentShopArea(); - if (null == shopAreaRateMap) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无店铺信息"); - } - - //免租期 - List freePeriods = getFreeDays(wxRentContract); - - int index = 0; - for (int i = 0; i < billTimeVoList.size(); i++) { - BillTimeVo billTimeVo = billTimeVoList.get(i); - //计算金额 - String needpay = "0"; - //商业管理费 - String bussinessManageFeeNeedpay = "0"; - //营业管理费 - String operatingManageFeeNeedpay = "0"; - - boolean flag = false; - //此处逻辑处理这一年和下一年交接那一期账单。 - if(yearList.size() > 1) { - if (endDate!=null && (sd.format(billTimeVo.getStartDate()).equals(sd.format(endDate)) || billTimeVo.getStartDate().after(endDate) || billTimeVo.getEndDate().after(endDate) )) { - if(yearList.size() > 1) { - if (endDate!=null && (sd.format(billTimeVo.getStartDate()).equals(sd.format(endDate)) || billTimeVo.getStartDate().after(endDate) || billTimeVo.getEndDate().after(endDate) )) { - //logger.info("=====billTimeVo.getStartDate():"+sd.format(billTimeVo.getStartDate())+" endDate:"+sd.format(endDate)); - - index++; - //如果是计算账单金额&cross 拆分日期进行计算 - if(billTimeVo.getEndDate().after(endDate)) { - String needpayFront = "0"; - String needpayAfter = "0"; - - //商业管理费 - String bussinessManageFeeNeedpayFront = "0"; - String bussinessManageFeeNeedpayAfter = "0"; - - //营业管理费 - String operatingManageFeeNeedpayFront = "0"; - String operatingManageFeeNeedpayAfter = "0"; - - //同一天,算一天 - if(sd.format(billTimeVo.getStartDate()).equals(sd.format(billTimeVo.getEndDate()))){ - needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,priceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,bussinessManagerPriceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,operationManagerPriceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); - } - }else{ - //这一年到期和下一年开始的期间,从这一年到期时间分开来进行计算。因为涉及到年租金调整等 TODO 如何把这两块单独生成账单 - if(billTimeVo.getStartDate().before(endDate)){ - if (EnumRentContractType.RENT_BY_JOINT.getCode().equals(wxRentContract.getType()) && EnumMissTimeType.PERIOD.getCode().equals(0)) { - //设置跳点率为年周期 price不变 - needpayFront = priceArrs[index - 1]; - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = bussinessManagerPriceArrs[index - 1]; - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = operationManagerPriceArrs[index - 1]; - } - }else { - needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - needpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - bussinessManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - operatingManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - } - } - //下一年的第一天 - }else if (billTimeVo.getStartDate().equals(endDate)) { - needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - } - }else{ - //如果是按自然月,则这一年和下一年交叉部分需要重新计算 - if(wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode())) { - Date currentYearRentDate = getCurrentYearRentDate(endDate,wxRentContract.getRentalStartDate()); - needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - needpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - bussinessManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - operatingManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); - } - }else { - //按账单日 - needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { - bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); - } - } - } - } - needpay = new BigDecimal(needpayFront).add(new BigDecimal(needpayAfter)).toPlainString(); - bussinessManageFeeNeedpay = new BigDecimal(bussinessManageFeeNeedpayFront).add(new BigDecimal(bussinessManageFeeNeedpayAfter)).toPlainString(); - operatingManageFeeNeedpay = new BigDecimal(operatingManageFeeNeedpayFront).add(new BigDecimal(operatingManageFeeNeedpayAfter)).toPlainString(); - flag = true; - } - if(index >= yearList.size()-1){ - endDate = null; - }else{ - endDate = yearList.get(index+1);//price index 0开始,year.end 从第二年开始 - //logger.info("==========cross:"+sd.format(endDate)); - } - } - } - } - } - - //计算金额 - if(!flag){ - needpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0 ) { - bussinessManageFeeNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); - } - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { - operatingManageFeeNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); - } - } - - - WxAllBill wxBillRent = new WxAllBill(); - wxBillRent.setIsPreview(isPreview); - wxBillRent.setId(idWorker.nextId()); - wxBillRent.setRentContractId(wxRentContract.getId()); - wxBillRent.setBillType(EnumBillAllType.RENT.getCode()); - wxBillRent.setPay("0"); - wxBillRent.setStarttime(billTimeVo.getStartDate()); - wxBillRent.setEndtime(billTimeVo.getEndDate()); - wxBillRent.setReceiveDate(billTimeVo.getReceiveDate()); - wxBillRent.setPeriod(WxRentContractHelper.getPeriod(billTimeVo.getReceiveDate())); +package com.iformall.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.IdWorker; +import com.iformall.common.Result; +import com.iformall.common.ResultData; +import com.iformall.common.SysConfigConstant; +import com.iformall.domain.po.MallUserInfo; +import com.iformall.domain.po.SysConfig; +import com.iformall.domain.po.WxAllBill; +import com.iformall.domain.po.WxBillAction; +import com.iformall.domain.po.WxContractCustomers; +import com.iformall.domain.po.WxContractShop; +import com.iformall.domain.po.WxEnergyFees; +import com.iformall.domain.po.WxFlowModel; +import com.iformall.domain.po.WxFlowRecord; +import com.iformall.domain.po.WxMall; +import com.iformall.domain.po.WxMerchant; +import com.iformall.domain.po.WxMerchantTradeDaily; +import com.iformall.domain.po.WxPayAccountBill; +import com.iformall.domain.po.WxPropertyContract; +import com.iformall.domain.po.WxRentContract; +import com.iformall.domain.po.WxRentContractFreePeriod; +import com.iformall.domain.po.WxRentContractRevenueJump; +import com.iformall.domain.po.WxRentContractRevenueSales; +import com.iformall.domain.po.WxShop; +import com.iformall.domain.po.WxShopUsers; +import com.iformall.domain.po.WxShopUsersInfo; +import com.iformall.domain.po.base.TenantEntity; +import com.iformall.domain.vo.BillTimeVo; +import com.iformall.domain.vo.RatioVo; +import com.iformall.domain.vo.RentContractFreePeriodVo; +import com.iformall.domain.vo.WxBillSum; +import com.iformall.domain.vo.WxRentContractRevenueSetSalesVo; +import com.iformall.domain.vo.WxRentContractYearsSumVo; +import com.iformall.domain.vo.WxRentContractYearsVo; +import com.iformall.enums.EnumBillAction; +import com.iformall.enums.EnumBillAllType; +import com.iformall.enums.EnumBillExtraCreateFrom; +import com.iformall.enums.EnumBillStatus; +import com.iformall.enums.EnumContractCustomersStatus; +import com.iformall.enums.EnumContractOperationType; +import com.iformall.enums.EnumContractReceivePeriodUnit; +import com.iformall.enums.EnumEndProperty; +import com.iformall.enums.EnumFeesStandardsCalcuteUnit; +import com.iformall.enums.EnumFlowKey; +import com.iformall.enums.EnumFlowRecordStatus; +import com.iformall.enums.EnumFromType; +import com.iformall.enums.EnumGetRatioFrom; +import com.iformall.enums.EnumIsPreview; +import com.iformall.enums.EnumMissTimeType; +import com.iformall.enums.EnumPriceUnit; +import com.iformall.enums.EnumRentAgileType; +import com.iformall.enums.EnumRentContractAdjustPeriod; +import com.iformall.enums.EnumRentContractAdjustRatioWay; +import com.iformall.enums.EnumRentContractAgileFeesType; +import com.iformall.enums.EnumRentContractAppStatus; +import com.iformall.enums.EnumRentContractManageFeeType; +import com.iformall.enums.EnumRentContractStatus; +import com.iformall.enums.EnumRentContractType; +import com.iformall.enums.EnumRentDayPriceCalcute; +import com.iformall.enums.EnumRentShopType; +import com.iformall.enums.EnumRentStartType; +import com.iformall.enums.EnumShopUsersStatus; +import com.iformall.enums.EnumShopUsersType; +import com.iformall.enums.EnumSystemUserType; +import com.iformall.enums.EnumTradeDailyDateType; +import com.iformall.enums.EnumYesOrNo; +import com.iformall.exception.MallinkException; +import com.iformall.mapper.WxAllBillMapper; +import com.iformall.mapper.WxBusinessMapper; +import com.iformall.mapper.WxContractCustomersMapper; +import com.iformall.mapper.WxContractShopMapper; +import com.iformall.mapper.WxFlowRecordMapper; +import com.iformall.mapper.WxMerchantMapper; +import com.iformall.mapper.WxMerchantShopMapper; +import com.iformall.mapper.WxMerchantTradeDailyMapper; +import com.iformall.mapper.WxPropertyContractMapper; +import com.iformall.mapper.WxRentContractFreePeriodMapper; +import com.iformall.mapper.WxRentContractMapper; +import com.iformall.mapper.WxRentContractRevenueJumpMapper; +import com.iformall.mapper.WxRentContractRevenueSalesMapper; +import com.iformall.mapper.WxShopMapper; +import com.iformall.service.SysConfigService; +import com.iformall.service.WxAgileContractService; +import com.iformall.service.WxBillActionService; +import com.iformall.service.WxEnergyService; +import com.iformall.service.WxFlowRecordService; +import com.iformall.service.WxFlowService; +import com.iformall.service.WxMallService; +import com.iformall.service.WxMerchantService; +import com.iformall.service.WxPayAccountBillService; +import com.iformall.service.WxPropertyContractService; +import com.iformall.service.WxRentContractService; +import com.iformall.service.WxShopService; +import com.iformall.service.helper.WxBillAllHelper; +import com.iformall.service.helper.WxRentContractHelper; +import com.iformall.utils.Constant; +import com.iformall.utils.DateUtils; +import com.iformall.utils.DownFileUtil; +import com.iformall.utils.PriceUtil; + +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.collections.map.HashedMap; +import org.apache.commons.compress.utils.Lists; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.flowable.engine.RuntimeService; +import org.flowable.engine.TaskService; +import org.flowable.task.api.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * @author gongbiao + */ +@Service +public class WxRentContractServiceImpl implements WxRentContractService { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private String fmUploadDir; + + @Autowired + WxRentContractMapper wxRentContractMapper; + + @Autowired + WxRentContractFreePeriodMapper wxRentContractFreePeriodMapper; + + @Autowired + WxRentContractRevenueJumpMapper wxRentContractRevenueJumpMapper; + + @Autowired + WxRentContractRevenueSalesMapper wxRentContractRevenueSalesMapper; + + @Autowired + WxContractCustomersMapper wxContractCustomersMapper; + + @Autowired + WxContractShopMapper wxContractShopMapper; + + @Autowired + WxShopMapper wxShopMapper; + + @Lazy + @Autowired + WxMerchantService wxMerchantService; + + @Autowired + WxPropertyContractMapper wxPropertyContractMapper; + + @Autowired + WxMerchantMapper wxMerchantMapper; + + @Autowired + WxBusinessMapper wxBusinessMapper; + + @Lazy + @Autowired + WxMallService wxMallService; + + @Lazy + @Autowired + WxFlowRecordService wxFlowRecordService; + + @Lazy + @Autowired + RuntimeService runtimeService; + + @Lazy + @Autowired + private TaskService taskService; + + @Lazy + @Autowired + private WxFlowService wxFlowService; + + @Autowired + WxMerchantShopMapper wxMerchantShopMapper; + + @Autowired + WxFlowRecordMapper wxFlowRecordMapper; + + @Autowired + WxAllBillMapper wxAllBillMapper; + + @Lazy + @Autowired + WxPropertyContractService wxPropertyContractService; + + @Lazy + @Autowired + WxAgileContractService wxAgileContractService; + + @Lazy + @Autowired + WxPayAccountBillService wxPayAccountBillService; + + @Lazy + @Autowired + WxShopService wxShopService; + + @Autowired + WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper; + + @Lazy + @Autowired + WxBillAllHelper wxBillAllHelper; + + @Lazy + @Autowired + WxEnergyService wxEnergyService; + + @Lazy + @Autowired + SysConfigService sysConfigService; + + @Lazy + @Autowired + private WxBillActionService wxBillActionService; + + @Override + public List findList(WxRentContract record){ + return wxRentContractMapper.findList(record); + } + + @Override + public List findIdList(WxRentContract record){ + return wxRentContractMapper.findIdList(record); + } + + @Override + public Map getById(Long id,Integer noBillList) { + Map result = new HashMap<>(); + WxRentContract wxRentContract = wxRentContractMapper.selectById(id); + if (wxRentContract == null) { + throw new MallinkException(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); + } + + WxContractCustomers customers = wxContractCustomersMapper.selectById(wxRentContract.getCustomersId(),wxRentContract.getTenantId()); + wxRentContract.setCustomerType(customers.getPrincipalType()); + wxRentContract.setCustomerLinkPerson(customers.getLinkPerson()); + wxRentContract.setCustomerName(customers.getName()); + wxRentContract.setCustomerPhone(customers.getPhone()); + wxRentContract.setCustomerLegalPerson(customers.getLegalPerson()); + + //init dateDiff + if(wxRentContract.getRentalStartDate() != null && wxRentContract.getRentalEndDate() != null){ + //加1天 + Date newEndDate = DateUtils.getDaySet(wxRentContract.getRentalEndDate(),Calendar.DATE,1); + int[] array = DateUtils.getDiff(wxRentContract.getRentalStartDate(),newEndDate); + result.put("totalPeriodMonth",array[0]); + result.put("totalPeriodDay",array[1]); + } + + //init 租赁单价 + String rentInfo = wxRentContract.getRentInfo(); + if(StringUtils.isNotBlank(rentInfo)){ + JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); + int size = rentInfoArray.size(); + //查询rent_info 包括shopId + for (int i = 0; i < size; i++) { + JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); + BigDecimal rentPrice = rentInfoObject.getBigDecimal("rentPrice"); + //wxRentContract.setShopId(rentInfoObject.getLong("shopId")); + String price = wxRentContract.getPrice(); + if(rentPrice == null){ + if(StringUtils.isNotBlank(wxRentContract.getRentArea()) && !"0".equals(wxRentContract.getRentArea()) && !"0.00".equals(wxRentContract.getRentArea()) && !"0.0".equals(wxRentContract.getRentArea()) ) { + Double rentArea = Double.parseDouble(wxRentContract.getRentArea()); + rentPrice = new BigDecimal(price).divide(new BigDecimal(rentArea),wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); + rentInfoObject.put("rentPrice", rentPrice); + } + } + } + wxRentContract.setRentInfo(rentInfoArray.toJSONString()); + }else{ + if(wxRentContract.getRentPrice() == null || "0".equals(wxRentContract.getRentPrice())){ + if(StringUtils.isNotBlank(wxRentContract.getRentArea()) && !"0".equals(wxRentContract.getRentArea()) && !"0.00".equals(wxRentContract.getRentArea()) && !"0.0".equals(wxRentContract.getRentArea()) ) { + String price = wxRentContract.getPrice(); + Double rentArea = Double.parseDouble(wxRentContract.getRentArea()); + BigDecimal rentPrice = new BigDecimal(price).divide(new BigDecimal(rentArea),wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); + if(rentPrice.compareTo(new BigDecimal(0)) > 0){ + wxRentContract.setRentPrice(rentPrice.toString()); + }else{ + wxRentContract.setRentPrice("0"); + } + } + + } + } + if(wxRentContract.getPriceUnit() == null){ + wxRentContract.setPriceUnit(EnumPriceUnit.M.getCode()); + } + if(wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode())){ + wxRentContract.setAdjustPeriod(EnumRentContractAdjustPeriod.ADJUST_PERIOD_MONTH.getCode()); + wxRentContract.setPriceUnit(EnumPriceUnit.D.getCode()); + } + + //商场信息 + WxMall wxMall = new WxMall(); + wxMall.setTenantInfo(wxRentContract); + List mallList = wxMallService.findList(wxMall); + if (!mallList.isEmpty()) { + result.put("mall", mallList.get(0)); + } + wxRentContract.setPrice(StringUtils.isNotBlank(wxRentContract.getPrice()) ? wxRentContract.getPrice() : "0"); + wxRentContract.setDeposit(StringUtils.isNotBlank(wxRentContract.getDeposit()) ? wxRentContract.getDeposit() : "0"); + + //免租期 + WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); + fpq.updateTenantInfo(wxRentContract); + fpq.setRentContractId(wxRentContract.getId()); + fpq.setSortColumn("year_index asc,start_date asc"); + List freePeroids = wxRentContractFreePeriodMapper.findList(fpq); + wxRentContract.setFreeVo(freePeroids); + + //跳点设置 + WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); + jq.updateTenantInfo(wxRentContract); + jq.setRentContractId(wxRentContract.getId()); + wxRentContract.setRevenueJumps(wxRentContractRevenueJumpMapper.findList(jq)); + result.put("wxRentContract", wxRentContract); + //关联的店铺 + if (wxRentContract.shopIdsByRentInfo().size()> 0) { + WxShop record = new WxShop(); + //record.setId(wxRentContract.getShopId()); + record.setIds(wxRentContract.shopIdsByRentInfo()); + record.updateTenantInfo(wxRentContract); + PageInfo> shopPageInfo = wxShopService.findListMap(record,1,10000); + List> list = shopPageInfo.getList(); + result.put("wxShops", list); + } else { + result.put("wxShops", Collections.EMPTY_LIST); + } + //设置审批流程状态 + result.put("applyStatus", wxRentContract.getApplyStatus()); + + //发起人备注 + WxFlowRecord wxFlowRecord = new WxFlowRecord(); + wxFlowRecord.setBusinessId(String.valueOf(id)); + wxFlowRecord.setStatus(EnumFlowRecordStatus.NEW.getCode()); + List flowRecordList = wxFlowRecordService.findList(wxFlowRecord); + if(!CollectionUtils.isEmpty(flowRecordList)){ + result.put("remark",flowRecordList.get(0).getRemark()); + } + + //查询预账单用于展示 + if (null != noBillList && EnumYesOrNo.YES.getCode().intValue() == noBillList.intValue()) { + }else { + WxAllBill wxBillRent = new WxAllBill(); + wxBillRent.setRentContractId(id); + wxBillRent.updateTenantInfo(wxRentContract); + wxBillRent.setBillType(EnumBillAllType.RENT.getCode()); + List resultList = wxAllBillMapper.findContractSamePeriodSum(wxBillRent); + result.put("previewBillRentList",resultList); + } + + return result; + } + + @Override + public WxRentContract selectById(Long id) { + return wxRentContractMapper.selectById(id); + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData save(WxRentContract record,MallUserInfo user,String userName,Date oldRentStartDate) { + //保存租赁合同信息 + final IdWorker idWorker = IdWorker.get(); + record.setId(idWorker.nextId()); + int dayType = record.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; + //计租开始时间 + Calendar instance = Calendar.getInstance(); + instance.setTime(record.getRentalStartDate()); + instance.add(dayType, record.getLease()); + instance.add(Calendar.DAY_OF_MONTH, -1); + //计租结束时间 + if (!record.getStartDate().equals(record.getRentalStartDate())) { + instance.clear(); + instance.setTime(record.getRentalStartDate()); + instance.add(Calendar.DAY_OF_MONTH, -1); + record.setEndDate(instance.getTime()); + } else { + record.setEndDate(record.getStartDate()); + } + + if (StringUtils.isEmpty(record.getPrice())) { + record.setPrice("0"); + } + if (StringUtils.isEmpty(record.getDeposit())) { + record.setDeposit("0"); + } + + Date date = new Date(); + record.setCreatetime(date); + record.setCreateBy(user.getId()); + record.setCreateByName(user.getName()); + record.setUpdatetime(date); + record.setUpdateBy(user.getId()); + record.setUpdateByName(user.getName()); + + List shopList = Lists.newArrayList(); + String rentInfo = record.getRentInfo(); + JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); + int size = rentInfoArray.size(); + if (size == 0) { + return new ResultData(ErrorCode.SHOP_NOT_SELECTED); + } + //查询rent_info 包括 shopId + String shopIdStr = ""; + BigDecimal rentArea = new BigDecimal(0); + for (int i = 0; i < size; i++) { + JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); + Long shopId = rentInfoObject.getLong("id"); + rentArea = rentArea.add(new BigDecimal(rentInfoObject.getString("operationArea"))); + if (!shopList.contains(shopId)) { + shopList.add(shopId); + shopIdStr = shopIdStr +","+ shopId; + } + } + record.setRentArea(rentArea.toPlainString()); + setShops(record,shopList); + //关联客户 + setCustomers(record); + try { + record.setApplyStatus(EnumRentContractAppStatus.DEFAULT.getCode()); + record.setStatus(EnumRentContractStatus.UNWRITE.getCode()); + Date tempDate = record.getRentalStartDate(); + record.setRentalStartDate(oldRentStartDate); + record.setShopIdStr(shopIdStr); + record.setAgileType(EnumRentAgileType.STANDARDS_YEAR.getCode()); + wxRentContractMapper.insert(record); + record.setRentalStartDate(tempDate); + } catch (Exception e) { + logger.error("保存租赁合同信息失败,e:" + e.getMessage()); + throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); + } + + return new ResultData(Result.SUCCESS, "保存租赁合同信息成功", record); + } + + public void setCustomers(WxRentContract record) { + WxContractCustomers cq = new WxContractCustomers(); + cq.updateTenantInfo(record); + cq.setPrincipalType(record.getCustomerType()); + cq.setNameEqal(record.getCustomerName()); + cq.setPhoneEqal(record.getCustomerPhone()); + List list = wxContractCustomersMapper.findList(cq); + WxContractCustomers cus = null; + if (null != list && list.size() > 0 ){ + cus = list.get(0); + } + if (null == cus) { + final IdWorker idWorker = IdWorker.get(); + cus = new WxContractCustomers(); + cus.updateTenantInfo(record); + cus.setId(idWorker.nextId()); + cus.setPrincipalType(record.getCustomerType()); + cus.setName(record.getCustomerName()); + cus.setPhone(record.getCustomerPhone()); + cus.setLegalPerson(record.getCustomerLegalPerson()); + cus.setLinkPerson(record.getCustomerLinkPerson()); + cus.setCreateDate(new Date()); + cus.setUpdateDate(new Date()); + cus.setStatus(EnumContractCustomersStatus.TEMP.getCode()); + wxContractCustomersMapper.insert(cus); + }else { + cus.setLinkPerson(record.getCustomerLinkPerson()); + cus.setLegalPerson(record.getCustomerLegalPerson()); + cus.setUpdateDate(new Date()); + wxContractCustomersMapper.updateById(cus); + } + record.setCustomersId(cus.getId()); + } + + public void setShops(WxRentContract record,List shopIdList) { + WxContractShop sdel = new WxContractShop(); + sdel.updateTenantInfo(record); + sdel.setContractId(record.getId()); + wxContractShopMapper.deleteByCondition(sdel); + Map shopAreaMap = record.getRentShopArea(); + if (null != shopIdList && shopIdList.size() > 0 ) { + final IdWorker idWorker = IdWorker.get(); + for ( int i = 0 ; i < shopIdList.size(); i ++) { + Long shopId = shopIdList.get(i); + WxContractShop s = new WxContractShop(); + s.updateTenantInfo(record); + s.setContractId(record.getId()); + s.setShopId(shopIdList.get(i)); + s.setRentArea(shopAreaMap.get(shopId).toPlainString()); + s.setCreateDate(new Date()); + s.setUpdateDate(new Date()); + s.setId(idWorker.nextId()); + wxContractShopMapper.insert(s); + } + } + + } + + + @Override + public List getShopIds(WxRentContract record) { + return record.shopIdsByRentInfo(); + } + + //@Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData update(WxRentContract record, MallUserInfo user,String userName,int from,Date oldRentStartDate,boolean writeComplate,boolean setRevenJumps) { + //查询预账单用于展示 + WxAllBill wxBillRent = new WxAllBill(); + wxBillRent.setRentContractId(record.getId()); + wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); + wxBillRent.updateTenantInfo(record); + List resultList = wxAllBillMapper.findList(wxBillRent); + + //更新 + ResultData resultData = getResultDataForUpdate(record, user,from,oldRentStartDate,writeComplate,setRevenJumps); + if (resultData.code != Result.SUCCESS) { + return resultData; + } + + boolean saveBill = true; + if(CollectionUtils.isEmpty(record.getPreviewBillRentList())) { + if (record.getReceivePeriod() != null && record.getLease() != null + && !record.getReceivePeriod().equals(0) && !record.getLease().equals(0)) { + deletePrewBill(record); + //联营扣点,不设置保底营业额,不生成账单 + //if (EnumRentContractType.RENT_BY_JOINT.getCode().equals(record.getType()) && record.getRevenueRatio().equals(0)) { + //do nothing + // saveBill = false; + //}else { + resultList = buildRent(user, record, EnumIsPreview.YES.getCode(),true); + //} + } + } + + WxRentContract wxRentContract = (WxRentContract)resultData.data; + wxRentContract.setPreviewBillRentList(resultList); + return new ResultData(wxRentContract); + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData updateOneStep(WxRentContract record, MallUserInfo user,String userName,int from,Date oldRentStartDate,boolean writeComplate) { + //查询预账单用于展示 + WxAllBill wxBillRent = new WxAllBill(); + wxBillRent.setRentContractId(record.getId()); + wxBillRent.setSortColumns("starttime asc"); + wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); + wxBillRent.updateTenantInfo(record); + List resultList = wxAllBillMapper.findList(wxBillRent); + + //更新 + setCustomers(record); + ResultData resultData = getResultDataForUpdate(record, user,from,oldRentStartDate,writeComplate,false); + if (resultData.code != Result.SUCCESS) { + return resultData; + } + WxRentContract wxRentContract = (WxRentContract)resultData.data; + wxRentContract.setPreviewBillRentList(resultList); + + WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); + jq.updateTenantInfo(record); + jq.setRentContractId(record.getId()); + wxRentContract.setRevenueJumps(wxRentContractRevenueJumpMapper.findList(jq)); + return new ResultData(wxRentContract); + } + + @Override + public ResultData updateRentStartTime(WxRentContract record, MallUserInfo user) { + //查询预账单用于展示 + WxAllBill wxBillRent = new WxAllBill(); + wxBillRent.setRentContractId(record.getId()); + wxBillRent.setIsPreview(EnumIsPreview.YES.getCode()); + wxBillRent.updateTenantInfo(record); + List resultList = wxAllBillMapper.findList(wxBillRent); + + //更新 + WxRentContract contractUpdate = new WxRentContract(); + contractUpdate.setId(record.getId()); + contractUpdate.updateTenantInfo(record); + contractUpdate.setRentStartType(record.getRentStartType()); + contractUpdate.setUpdatetime(new Date()); + contractUpdate.setUpdateBy(user.getId()); + contractUpdate.setUpdateByName(user.getName()); + wxRentContractMapper.updateById(record); + + + WxRentContract rentContract = wxRentContractMapper.selectById(record.getId()); + Date oldDate = record.getRentalStartDate(); + rentContract.setAdjustPeriodHandle(); + if(rentContract.getRentStartType()!=null && rentContract.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){ + rentContract.setRentalStartDate(rentContract.getStartDate()); + } + + deletePrewBill(record); + resultList = buildRent(user, rentContract, EnumIsPreview.YES.getCode(),true); + rentContract.setPreviewBillRentList(resultList); + rentContract.setRentalStartDate(oldDate); + return new ResultData(rentContract); + } + + public ResultData getResultDataForUpdate(WxRentContract record, MallUserInfo user,int from,Date oldRentStartDate,boolean writeFinal,boolean setRevenJumps) { + //更新租赁合同信息 + WxRentContract wxRentContract = wxRentContractMapper.selectById(record.getId()); + if (wxRentContract == null) { + return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); + } + wxRentContract.setPayRatio(record.getPayRatio()); + + int dayType = wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; + + Calendar instance = Calendar.getInstance(); + instance.setTime(record.getRentalStartDate()); + instance.add(dayType, record.getLease()); + instance.add(Calendar.DAY_OF_MONTH, -1); + + if(!EnumFromType.SWITCH.getCode().equals(from)){ + //如果是联营扣点,或者联营取高,需要根据保底营业额来计算 + if (record.getType() != null) { + //联营扣点 + if (record.getType().equals(EnumRentContractType.RENT_BY_JOINT.getCode())) { + String revenue = record.getRevenue(); + if (StringUtils.isBlank(revenue)) { + revenue = "0"; + }else { + if (StringUtils.isNotBlank(record.getLimitRevenue()) && new BigDecimal(record.getLimitRevenue()).compareTo(new BigDecimal(revenue)) > 0) { + revenue = "0"; + } + } + record.setPrice(new BigDecimal(record.getPayRatio()).multiply(new BigDecimal(revenue)).divide(new BigDecimal(100),Constant.default_long_decimal_size,RoundingMode.HALF_UP).toPlainString()); + }else if (record.getType().equals(EnumRentContractType.RENT_BY_AREA_AND_JOINT.getCode())) { + BigDecimal rentPrice = null; + //联营取高,如果是固定金额的话,取固定金额. 不固定的金额,会传price. + if (null != record.getRevenueFixedRentPrice() && record.getRevenueFixedRentPrice().intValue() == EnumYesOrNo.YES.getCode()){ + rentPrice = new BigDecimal(record.getRevenueRentPrice()); + }else { + rentPrice = new BigDecimal(record.getPrice()); + } + record.setPrice(rentPrice.toPlainString()); + } + } + } + + if (StringUtils.isEmpty(record.getPrice())) { + record.setPrice("0"); + } + if (StringUtils.isEmpty(record.getDeposit())) { + record.setDeposit("0"); + } + List shopList = Lists.newArrayList(); + record.setUpdatetime(new Date()); + record.setUpdateBy(user.getId()); + record.setUpdateByName(user.getName()); + String rentInfo = record.getRentInfo(); + JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); + int size = rentInfoArray.size(); + if (size == 0) { + return new ResultData(ErrorCode.SHOP_NOT_SELECTED); + } + //查询rent_info 包括 shopId + String shopIdStr = ""; + BigDecimal rentArea = new BigDecimal(0); + for (int i = 0; i < size; i++) { + JSONObject rentInfoObject = rentInfoArray.getJSONObject(i); + WxRentContract wxRentContractQuery = new WxRentContract(); + wxRentContractQuery.updateTenantInfo(record); + Long shopId = rentInfoObject.getLong("id"); + String shopNumber = rentInfoObject.getString("shopNumber"); + if (shopId == null) { + return new ResultData(ErrorCode.SHOP_IS_NOT_FOUND.getCode(), "店铺 " + shopNumber + " 已删除"); + } + rentArea = rentArea.add(new BigDecimal(rentInfoObject.getString("operationArea"))); + wxRentContractQuery.setId(record.getId()); + if (!shopList.contains(shopId)) { + shopList.add(shopId); + shopIdStr = shopIdStr +","+shopId; + } + } + setShops(record,shopList); + record.setRentArea(rentArea.toPlainString()); + try { + Date tempDate = record.getRentalStartDate(); + record.setRentalStartDate(oldRentStartDate); + record.setShopIdStr(shopIdStr); + if (writeFinal) { + record.setStatus(EnumRentContractStatus.DRAFT.getCode()); + }else { + record.setStatus(wxRentContract.getStatus()); + } + record.setApplyStatus(wxRentContract.getApplyStatus()); + if (StringUtils.isBlank(record.getOperatingManagementFee())){ + record.setOperatingManagementFee(null); + } + if (StringUtils.isBlank(record.getBussinessManagementFee())){ + record.setBussinessManagementFee(null); + } + wxRentContractMapper.updateById(record); + record.setRentalStartDate(tempDate); + + if (setRevenJumps) { + WxRentContractRevenueJump jumpsDel = new WxRentContractRevenueJump(); + jumpsDel.updateTenantInfo(record); + jumpsDel.setRentContractId(record.getId()); + wxRentContractRevenueJumpMapper.deleteByContract(jumpsDel); + + if (null != record.getRevenueJumps()) { + final IdWorker idWorker = IdWorker.get(); + List jlist = new ArrayList(); + for (int i = 0 ; i < record.getRevenueJumps().size(); i++) { + WxRentContractRevenueJump jp = record.getRevenueJumps().get(i); + if (StringUtils.isNotBlank(jp.getMinMoney())) { + jp.updateTenantInfo(record); + jp.setId(idWorker.nextId()); + jp.setRentContractId(record.getId()); + jp.setCreateTime(new Date()); + jp.setUpdateTime(new Date()); + jlist.add(jp); + } + } + if (jlist.size() > 0 ) { + wxRentContractRevenueJumpMapper.inertJumps(record.getTenantId(), jlist); + } + } + } + + } catch (Exception e) { + logger.error("更新租赁合同信息失败,e:" + e.getMessage()); + throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); + } + //重新查一次 + wxRentContract = wxRentContractMapper.selectById(record.getId()); + return new ResultData(Result.SUCCESS, "保存租赁合同信息成功", wxRentContract); + } + + + @Transactional(rollbackFor = {Exception.class}) + @Override + public void buildDeposit( TenantEntity tenantEntity,MallUserInfo user,Long rentContractId) { + WxRentContract wxRentContract = wxRentContractMapper.selectById(rentContractId); + if (wxRentContract != null && StringUtils.isNotBlank(wxRentContract.getDeposit()) + && new BigDecimal(wxRentContract.getDeposit()).compareTo(new BigDecimal(0)) > 0 ) { + + List shopIdList = wxRentContract.shopIdsByRentInfo(); + + WxShopUsers suq = new WxShopUsers(); + suq.updateTenantInfo(wxRentContract); + suq.setShopIds(shopIdList); + suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); + Map shopUserMap = wxShopService.getShopUserMap(suq); + + WxEnergyFees fq = new WxEnergyFees(); + fq.updateTenantInfo(tenantEntity); + fq.setBillType(EnumBillAllType.RENT_DEPOSIT.getCode()); + Map typeMap = wxEnergyService.getFeesMap(fq); + + //根据不同的科目生成不同的押金账单 + Map feesMap = wxRentContract.getDepositEnergyFees(typeMap); + Map shopAreaRateMap = wxRentContract.getRentShopArea(); + if (null == shopAreaRateMap) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无店铺信息"); + } + List insertList = new ArrayList(); + + for (Iterator it = feesMap.keySet().iterator();it.hasNext();){ + Long energyFeesId = it.next(); + WxEnergyFees depositFee = feesMap.get(energyFeesId); + WxEnergyFees fees = typeMap.get(energyFeesId); + final IdWorker idWorker = IdWorker.get(); + + for (int i = 0 ; i < shopIdList.size(); i++ ) { + Long sid = shopIdList.get(i); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + String cusName = null; + if (null != shopUserMap) { + WxShopUsers su = shopUserMap.get(sid); + if (null != su) { + cusName = su.getName(); + } + } + + WxAllBill wxBillDeposit = new WxAllBill(); + wxBillDeposit.setId(idWorker.nextId()); + wxBillDeposit.setRentContractId(wxRentContract.getId()); + wxBillDeposit.setBillType(EnumBillAllType.RENT_DEPOSIT.getCode()); + wxBillDeposit.setIsPreview(EnumYesOrNo.NO.getCode()); + wxBillDeposit.setCanEdit(EnumYesOrNo.NO.getCode()); + //if (null != fees) { + // wxBillDeposit.setPriceDetail("合同押金项["+fees.getName()+"]"+depositFee.getPrice()+"元"+"/"+fees.getCalcuteUnitName()); + //} + wxBillDeposit.setPay("0"); + String needpay = depositFee.getPrice(); + + // String count = "1"; + // if (null != depositFee.getCalcuteUnit() && depositFee.getCalcuteUnit().intValue() == EnumFeesStandardsCalcuteUnit.MM.getCode().intValue()) { + // count = wxRentContract.getRentArea(); + // } + // String needpay = depositFee.calcuteTotalMoney(wxRentContract.getDecimalSize(), null, null, count, true, null, null); + wxBillDeposit.setReceivePay(new BigDecimal(needpay).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); + wxBillDeposit.setNeedPay(wxBillDeposit.getReceivePay()); + //wxBillDeposit.setOwe(needpay); + //找到计租方式 + int dayType = wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_DAY.getCode()) ? Calendar.DAY_OF_MONTH : Calendar.MONTH; + + Date date = new Date(); + wxBillDeposit.setStarttime(wxRentContract.getFirstBillDateStart()); + wxBillDeposit.setEndtime(wxRentContract.getFirstBillDateEnd()); + wxBillDeposit.setReceiveDate(wxRentContract.getFirstBillReceiveDate()); + wxBillDeposit.setPeriod(WxRentContractHelper.getPeriod(wxRentContract.getFirstBillReceiveDate())); + //wxBillDeposit.setExpiredDay(0L); + wxBillDeposit.updateTenantInfo(wxRentContract); + //wxBillDeposit.setIsDel(0); + wxBillDeposit.setShopNumber(wxRentContract.getRentInfoShopNumber()); + if (null != user) { + //wxBillDeposit.setUserId(user.getId()); + } + wxBillDeposit.setShopId(sid); + wxBillDeposit.setCusName(cusName); + wxBillDeposit.setRentArea(shoprentArea.toPlainString()); + wxBillDeposit.setCreatetime(date); + if (null != user) { + wxBillDeposit.setCreateBy(user.getId()); + wxBillDeposit.setCreateByName(user.getName()); + } + wxBillDeposit.setUpdatetime(date); + if (null != user) { + wxBillDeposit.setUpdateBy(user.getId()); + wxBillDeposit.setUpdateByName(user.getName()); + } + //wxBillDeposit.setIsDel(EnumDelStatus.NOT_DEL.getCode()); + String rentInfo = wxRentContract.getRentInfo(); + if (rentInfo != null) { + JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); + Map shopInfo = new HashMap<>(); + for (int j = 0, size = rentInfoArray.size(); j < size; j++) { + JSONObject rentInfoObject = rentInfoArray.getJSONObject(j); + shopInfo.put(rentInfoObject.getString("shopNumber"), rentInfoObject.get("deposit")); + } + wxBillDeposit.setShopInfo(JSONObject.toJSONString(shopInfo)); + } + wxBillDeposit.setEnergyFeesId(energyFeesId); + wxBillDeposit.setCreateBy(wxRentContract.getCreateBy()); + wxBillDeposit.setUpdateBy(wxRentContract.getCreateBy()); + wxBillDeposit.setCreateByName(wxRentContract.getCreateByName()); + wxBillDeposit.setUpdateByName(wxRentContract.getCreateByName()); + + insertList.add(wxBillDeposit); + } + } + + try { + if (insertList.size() > 0 ) { + wxAllBillMapper.insertBills(tenantEntity.getTenantId(),insertList); + } + } catch (Exception e) { + logger.error("添加押金账单失败,e:" + e.getMessage()); + throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); + } + } + } + + @Override + public ResultData hasRentStatus(WxRentContract record) { + String rentInfo = record.getRentInfo(); + if (StringUtils.isEmpty(rentInfo)) { + return new ResultData(ErrorCode.SHOP_NOT_SELECTED); + } + String[] split = rentInfo.split(","); + int size = split.length; + //查询rent_info 包括 shopId + for (int i = 0; i < size; i++) { + String shopId = split[i]; + WxShop wxShop = wxShopMapper.selectById(shopId); + WxRentContract wxRentContractQuery = new WxRentContract(); + wxRentContractQuery.updateTenantInfo(record); + String shopNumber = wxShop.getShopNumber(); + if (shopId == null) { + return new ResultData(ErrorCode.SHOP_IS_NOT_FOUND.getCode(), "店铺 " + shopNumber + " 已删除"); + } + //wxRentContractQuery.setShopId(Long.valueOf(shopId)); + int count = wxRentContractMapper.selectRentContractCountByShopId(wxRentContractQuery.getTenantId(),wxRentContractQuery.getParentTenantId(),Long.valueOf(shopId),wxRentContractQuery.getId()); + if (count > 0) { + return new ResultData(ErrorCode.SHOP_IS_RENT.getCode(), "店铺 " + shopNumber + " 已出租"); + } + } + return new ResultData(Result.SUCCESS, "操作成功"); + } + + @Override + public ResultData hasContractNumber(WxRentContract wxRentContract) { + int count = wxRentContractMapper.hasContractNumber(wxRentContract); + return new ResultData(Result.SUCCESS, "操作成功", count > 0 ? true : false); + } + + public void updateInvalidStatus(WxRentContract record) { + Long id = record.getId(); + //审核流程中止 + try { + // 修改合同审核状态 + WxRentContract rentContract = record; + rentContract.setId(id); + rentContract.setApplyStatus(EnumRentContractAppStatus.CANCLE.getCode()); + updateApplyStatus(rentContract); + + //修改flowRecord + WxFlowRecord fr = new WxFlowRecord(); + fr.setBusinessId(String.valueOf(id)); + fr.setCurrStatus(EnumRentContractAppStatus.CANCLE.getCode()); + wxFlowRecordMapper.updateCurrStatus(fr); + + logger.info("合同id:{},开始停止...", id); + //结束审批流 by luozukai + WxFlowModel flowModel = wxFlowService.getModelByType(EnumFlowKey.NEW_RENT_CONTRACT.getCode().intValue(),record); + + WxFlowModel flowModel_pro = wxFlowService.getModelByType(EnumFlowKey.NEW_PRO_CONTRACT.getCode().intValue(),record); + + WxFlowModel flowModel_rent = wxFlowService.getModelByType(EnumFlowKey.NNEW_RENT_CONTRACT.getCode().intValue(),record); + + List keyList = new ArrayList<>(); + if(flowModel != null){ + keyList.add(flowModel.getFlowId()); + } + if(flowModel_pro != null){ + keyList.add(flowModel_pro.getFlowId()); + } + if(flowModel_rent != null){ + keyList.add(flowModel_rent.getFlowId()); + } + keyList.add(EnumFlowKey.CONTRACT.getMessage()); + List tasks = taskService.createTaskQuery() + .processDefinitionKeyIn(keyList) + .processVariableValueEquals("businessId", id+"").list(); + if (!CollectionUtils.isEmpty(tasks)) { + for (Task task : tasks) { + logger.info("合同id:{},taskid:{}", id, task.getId()); + runtimeService.deleteProcessInstance(task.getProcessInstanceId(), "合同作废"); + + // 保存审批历史入 + MallUserInfo mallUserInfo = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute("userSession"); + WxFlowRecord updateRecord = new WxFlowRecord(); + updateRecord.setBusinessId(String.valueOf(id)); + updateRecord.setStatus(EnumFlowRecordStatus.CANCLE.getCode()); + updateRecord.setBusinessType(1); + updateRecord.setUserId(mallUserInfo.getId()); + updateRecord.setProcessInstanceId(task.getProcessInstanceId()); + wxFlowRecordService.saveOrUpdate(updateRecord); + } + } + + } catch (Exception e) { + logger.error("deleteProcessInstance error", e); + } + } + + @Override + @Transactional(rollbackFor = {Exception.class}) + public List buildRent(MallUserInfo user,WxRentContract wxRentContract,Integer isPreview,boolean saveDb) { + List rentList = new ArrayList<>(); + if (wxRentContract != null) { + int receivePeriod = wxRentContract.getReceivePeriod().intValue(); + Integer lease = wxRentContract.getLease(); + Date rentalStartDate = wxRentContract.getRentalStartDate(); + String price = wxRentContract.getPrice(); + if(EnumContractOperationType.JINMAO.getCode().equals(wxRentContract.getOperationType())){ + Date startDate = wxRentContract.getStartDate(); + //rentList = buildRentJinmao(user, wxRentContract, receivePeriod, lease, startDate, price, isPreview,saveDb); + }else{ + rentList = buildRentMonth(user, wxRentContract, receivePeriod, lease, rentalStartDate, isPreview,saveDb); + } + } + return rentList; + } + + @Override + public List getYearList(int years,int month,Date rentalStartDate,Date endContractTime ) { + List yearList = new ArrayList(); + for (int i = 0; i < years; i++) { + Calendar instance = Calendar.getInstance(); + instance.setTime(rentalStartDate); + instance.set(Calendar.MILLISECOND, 0); + instance.add(Calendar.MONTH, month * i); + Date startDate = instance.getTime(); + if (null != endContractTime && endContractTime.before(startDate)) { + yearList.add(endContractTime); + break; + }else { + yearList.add(startDate); + } + } + return yearList; + } + + public List buildRentMonth(MallUserInfo user, WxRentContract wxRentContract, int receivePeriod, Integer lease, Date rentalStartDate,Integer isPreview, boolean saveDb) { + int years = 0; + //计算租金每年的计费基数 + String[] priceArrs = WxRentContractHelper.calcuteRentPrice(wxRentContract); + //计算商业管理费 + String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(wxRentContract); + //计算运营管理费 + String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(wxRentContract); + int month = 12; + int billcount = 0; + List resultList = new ArrayList(); + years = priceArrs.length; + List yearList = getYearList(years,month,rentalStartDate,null); + + String shopInfoStr = getShopInfoStr(wxRentContract); + Map resultMap = buildRent(receivePeriod, priceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs, yearList, wxRentContract.getReceivePeriodUnit(), wxRentContract, user, billcount, isPreview, shopInfoStr,saveDb); + List billRentList = (List)resultMap.get("billList"); + resultList.addAll(billRentList); + return resultList; + } + + public String getShopInfoStr(WxRentContract wxRentContract){ + String shopInfoStr = null; +// if (wxRentContract.getRentShopType().equals(EnumRentShopType.SHOP.getCode())) { + String rentInfo = wxRentContract.getRentInfo(); + JSONArray rentInfoArray = JSONArray.parseArray(rentInfo); + int rentSize = rentInfoArray.size(); + Map shopInfoMap = new HashMap<>(rentSize); + for (int j = 0; j < rentSize; j++) { + JSONObject rentInfoObject = rentInfoArray.getJSONObject(j); + shopInfoMap.put(rentInfoObject.getString("shopNumber"), rentInfoObject.getString("buildArea")); + } + shopInfoStr = JSONObject.toJSONString(shopInfoMap); +// } + return shopInfoStr; + } + + private static Date getCurrentYearRentDate(Date yearEndDate,Date rentDate){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(yearEndDate); + + Calendar rentCalendar = Calendar.getInstance(); + rentCalendar.setTime(rentDate); + + calendar.set(Calendar.DAY_OF_MONTH,rentCalendar.get(Calendar.DAY_OF_MONTH)); + calendar.set(Calendar.MONTH, rentCalendar.get(Calendar.MONTH)); + return calendar.getTime(); + } + + private List getFreeDays(WxRentContract wxRentContract) { + //免租期 + WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); + fpq.updateTenantInfo(wxRentContract); + fpq.setRentContractId(wxRentContract.getId()); + fpq.setSortColumn("start_date asc"); + List freePeriods = wxRentContractFreePeriodMapper.findList(fpq); + if (null == freePeriods || freePeriods.size() <= 0 ) { + return null; + } + List allDate = new ArrayList(); + for (int i = 0 ; i < freePeriods.size() ; i ++) { + WxRentContractFreePeriod fp = freePeriods.get(i); + List dates = DateUtils.getAllDays(fp.getStartDate(), fp.getEndDate()); + if (null != dates && dates.size() > 0 ) { + allDate.removeAll(dates); + allDate.addAll(dates); + } + } + if (allDate.size() <= 0 ) { + return null; + } + return allDate; + } + + public Map buildRent(int receivePeriod, String[] priceArrs,String[] bussinessManagerPriceArrs,String[] operationManagerPriceArrs, List yearList, int dayType, WxRentContract wxRentContract, MallUserInfo user, int billcount, Integer isPreview, String shopInfoStr,boolean saveDb) { + WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantInfo(wxRentContract); + SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); + Map resultMap = new HashedMap(); + List resultList = new ArrayList(); + List manageList = new ArrayList(); + final IdWorker idWorker = IdWorker.get(); + + Date endDate = null;//每年的截止日期 + if(yearList.size() > 1){ + endDate = yearList.get(1); + } + + List billTimeVoList = new ArrayList<>(); + if(saveDb){ + billTimeVoList = initBillTimeList(yearList,wxRentContract.getRentalStartDate(),wxRentContract.getRentalEndDate(),wxRentContract.getAdjustPeriod(),dayType,receivePeriod,wxRentContract.getPayPeriodRate()); + }else{ + //预账单编辑账期,生成金额 + for (WxAllBill rent:wxRentContract.getPreviewBillRentList()) { + BillTimeVo billTimeVo = new BillTimeVo(); + billTimeVo.setStartDate(rent.getStarttime()); + billTimeVo.setEndDate(rent.getEndtime()); + billTimeVo.setReceiveDate(DateUtils.getDaySet(rent.getStarttime(),Calendar.DATE,-1)); + billTimeVoList.add(billTimeVo); + } + } + + if (null != billTimeVoList && billTimeVoList.size() > 0 ) { + BillTimeVo firstBillTime = billTimeVoList.get(0); + WxRentContract cupdate = new WxRentContract(); + cupdate.updateTenantInfo(wxRentContract); + cupdate.setId(wxRentContract.getId()); + cupdate.setFirstBillDateStart(firstBillTime.getStartDate()); + cupdate.setFirstBillDateEnd(firstBillTime.getEndDate()); + cupdate.setFirstBillReceiveDate(firstBillTime.getReceiveDate()); + cupdate.setDecimalSize(null);//去掉默认的,避免更新 + wxRentContractMapper.updateById(cupdate); + } + + List shopIdList = wxRentContract.shopIdsByRentInfo(); + Map shopAreaRateMap = wxRentContract.getRentShopArea(); + if (null == shopAreaRateMap) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无店铺信息"); + } + + //免租期 + List freePeriods = getFreeDays(wxRentContract); + + int index = 0; + for (int i = 0; i < billTimeVoList.size(); i++) { + BillTimeVo billTimeVo = billTimeVoList.get(i); + //计算金额 + String needpay = "0"; + //商业管理费 + String bussinessManageFeeNeedpay = "0"; + //营业管理费 + String operatingManageFeeNeedpay = "0"; + + boolean flag = false; + //此处逻辑处理这一年和下一年交接那一期账单。 + if(yearList.size() > 1) { + if (endDate!=null && (sd.format(billTimeVo.getStartDate()).equals(sd.format(endDate)) || billTimeVo.getStartDate().after(endDate) || billTimeVo.getEndDate().after(endDate) )) { + if(yearList.size() > 1) { + if (endDate!=null && (sd.format(billTimeVo.getStartDate()).equals(sd.format(endDate)) || billTimeVo.getStartDate().after(endDate) || billTimeVo.getEndDate().after(endDate) )) { + //logger.info("=====billTimeVo.getStartDate():"+sd.format(billTimeVo.getStartDate())+" endDate:"+sd.format(endDate)); + + index++; + //如果是计算账单金额&cross 拆分日期进行计算 + if(billTimeVo.getEndDate().after(endDate)) { + String needpayFront = "0"; + String needpayAfter = "0"; + + //商业管理费 + String bussinessManageFeeNeedpayFront = "0"; + String bussinessManageFeeNeedpayAfter = "0"; + + //营业管理费 + String operatingManageFeeNeedpayFront = "0"; + String operatingManageFeeNeedpayAfter = "0"; + + //同一天,算一天 + if(sd.format(billTimeVo.getStartDate()).equals(sd.format(billTimeVo.getEndDate()))){ + needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,priceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,bussinessManagerPriceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract,operationManagerPriceArrs[index-1],billTimeVo.getStartDate(),endDate,i,billTimeVoList.size(),saveDb,dayType,receivePeriod); + } + }else{ + //这一年到期和下一年开始的期间,从这一年到期时间分开来进行计算。因为涉及到年租金调整等 TODO 如何把这两块单独生成账单 + if(billTimeVo.getStartDate().before(endDate)){ + if (EnumRentContractType.RENT_BY_JOINT.getCode().equals(wxRentContract.getType()) && EnumMissTimeType.PERIOD.getCode().equals(0)) { + //设置跳点率为年周期 price不变 + needpayFront = priceArrs[index - 1]; + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = bussinessManagerPriceArrs[index - 1]; + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = operationManagerPriceArrs[index - 1]; + } + }else { + needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + needpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + bussinessManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index - 1], billTimeVo.getStartDate(), DateUtils.getDaySet(endDate, Calendar.SECOND, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + operatingManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], endDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + } + } + //下一年的第一天 + }else if (billTimeVo.getStartDate().equals(endDate)) { + needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + } + }else{ + //如果是按自然月,则这一年和下一年交叉部分需要重新计算 + if(wxRentContract.getAdjustPeriod().equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode())) { + Date currentYearRentDate = getCurrentYearRentDate(endDate,wxRentContract.getRentalStartDate()); + needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + needpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + bussinessManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index - 1],endDate, DateUtils.getDaySet(currentYearRentDate, Calendar.DATE, -1), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + operatingManageFeeNeedpayAfter = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index],currentYearRentDate, billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb, dayType, receivePeriod); + } + }else { + //按账单日 + needpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0) { + bussinessManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpayFront = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index], billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(), saveDb,dayType,receivePeriod); + } + } + } + } + needpay = new BigDecimal(needpayFront).add(new BigDecimal(needpayAfter)).toPlainString(); + bussinessManageFeeNeedpay = new BigDecimal(bussinessManageFeeNeedpayFront).add(new BigDecimal(bussinessManageFeeNeedpayAfter)).toPlainString(); + operatingManageFeeNeedpay = new BigDecimal(operatingManageFeeNeedpayFront).add(new BigDecimal(operatingManageFeeNeedpayAfter)).toPlainString(); + flag = true; + } + if(index >= yearList.size()-1){ + endDate = null; + }else{ + endDate = yearList.get(index+1);//price index 0开始,year.end 从第二年开始 + //logger.info("==========cross:"+sd.format(endDate)); + } + } + } + } + } + + //计算金额 + if(!flag){ + needpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, priceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0 ) { + bussinessManageFeeNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, bussinessManagerPriceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); + } + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0) { + operatingManageFeeNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,wxRentContract, operationManagerPriceArrs[index],billTimeVo.getStartDate(), billTimeVo.getEndDate(), i, billTimeVoList.size(),saveDb,dayType,receivePeriod); + } + } + + + WxAllBill wxBillRent = new WxAllBill(); + wxBillRent.setIsPreview(isPreview); + wxBillRent.setId(idWorker.nextId()); + wxBillRent.setRentContractId(wxRentContract.getId()); + wxBillRent.setBillType(EnumBillAllType.RENT.getCode()); + wxBillRent.setPay("0"); + wxBillRent.setStarttime(billTimeVo.getStartDate()); + wxBillRent.setEndtime(billTimeVo.getEndDate()); + wxBillRent.setReceiveDate(billTimeVo.getReceiveDate()); + wxBillRent.setPeriod(WxRentContractHelper.getPeriod(billTimeVo.getReceiveDate())); wxBillRent.setCanEdit(EnumYesOrNo.NO.getCode());; - //wxBillRent.setContractNeedPay(needpay); - //wxBillRent.setRentPriceInfo(getRentPriceInfo(wxRentContract,new BigDecimal(needpay))); - wxBillRent.setNeedPay(needpay); - //wxBillRent.setOwe(needpay); - wxBillRent.setReceivePay(needpay); - logger.debug(">>>>"+DateUtils.date2String(billTimeVo.getStartDate())+">>>>"+DateUtils.date2String(billTimeVo.getEndDate())+">>>>"+needpay); - //商业管理费 - wxBillRent.setBussinessManageFeeNeedPay(bussinessManageFeeNeedpay); - //运营管理费 - wxBillRent.setOperatingManageFeeNeedPay(operatingManageFeeNeedpay); - //截止收租日在当前时间之前 - Date date = new Date(); - //setExpiredDay(wxBillRent,dayType,receivePeriod); - //wxBillRent.setRevenue("0"); - wxBillRent.updateTenantInfo(wxRentContract); - //wxBillRent.setUserId(user.getId()); - if (null != wxRentContract.shopIdsByRentInfo() && wxRentContract.shopIdsByRentInfo().size() == 1) { - wxBillRent.setShopId(wxRentContract.shopIdsByRentInfo().get(0)); - } - wxBillRent.setShopNumber(wxRentContract.getRentInfoShopNumber()); - wxBillRent.setRentArea(wxRentContract.getRentArea()); - wxBillRent.setCreatetime(date); - wxBillRent.setCreateBy(user.getId()); - wxBillRent.setCreateByName(user.getName()); - wxBillRent.setUpdatetime(date); - wxBillRent.setUpdateBy(user.getId()); + //wxBillRent.setContractNeedPay(needpay); + //wxBillRent.setRentPriceInfo(getRentPriceInfo(wxRentContract,new BigDecimal(needpay))); + wxBillRent.setNeedPay(needpay); + //wxBillRent.setOwe(needpay); + wxBillRent.setReceivePay(needpay); + logger.debug(">>>>"+DateUtils.date2String(billTimeVo.getStartDate())+">>>>"+DateUtils.date2String(billTimeVo.getEndDate())+">>>>"+needpay); + //商业管理费 + wxBillRent.setBussinessManageFeeNeedPay(bussinessManageFeeNeedpay); + //运营管理费 + wxBillRent.setOperatingManageFeeNeedPay(operatingManageFeeNeedpay); + //截止收租日在当前时间之前 + Date date = new Date(); + //setExpiredDay(wxBillRent,dayType,receivePeriod); + //wxBillRent.setRevenue("0"); + wxBillRent.updateTenantInfo(wxRentContract); + //wxBillRent.setUserId(user.getId()); + if (null != wxRentContract.shopIdsByRentInfo() && wxRentContract.shopIdsByRentInfo().size() == 1) { + wxBillRent.setShopId(wxRentContract.shopIdsByRentInfo().get(0)); + } + wxBillRent.setShopNumber(wxRentContract.getRentInfoShopNumber()); + wxBillRent.setRentArea(wxRentContract.getRentArea()); + wxBillRent.setCreatetime(date); + wxBillRent.setCreateBy(user.getId()); + wxBillRent.setCreateByName(user.getName()); + wxBillRent.setUpdatetime(date); + wxBillRent.setUpdateBy(user.getId()); wxBillRent.setUpdateByName(user.getName());; - //wxBillRent.setIsDel(EnumDelStatus.NOT_DEL.getCode()); - //wxBillRent.setPeriod(++billcount); - wxBillRent.setShopInfo(shopInfoStr); - //wxBillRent.setLatePayRatio(0); - wxBillRent.calcuteTotalFee(wxRentContract.getDecimalSize()); - wxBillRent.setEnergyFeesId(EnumBillAllType.RENT.getEnergyFeesId()); - - //计算手续费 - //BigDecimal servicePay = new BigDecimal(wxBillRent.getReceivePay()).multiply(new BigDecimal(wxPayAccountBill.getServiceChargeRate())) - // .divide(new BigDecimal(10000), wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); - //wxBillRent.setServiceChargePay(servicePay.toPlainString()); - //wxBillRent.setOwe(new BigDecimal(wxBillRent.getReceivePay()).add(new BigDecimal(wxBillRent.getServiceChargePay())).toPlainString()); - //wxBillRent.setOwe(new BigDecimal(wxBillRent.getReceivePay()).toPlainString()); - resultList.add(wxBillRent); - - - //商业管理费账单 - if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0 && new BigDecimal(bussinessManageFeeNeedpay).compareTo(new BigDecimal(0)) > 0) { - manageList.add(setManageRent(wxRentContract.getDecimalSize(),wxBillRent,EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE,bussinessManageFeeNeedpay,wxPayAccountBill.getServiceChargeRate(),dayType,receivePeriod)); - } - //营业管理费账单 - if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0 && new BigDecimal(operatingManageFeeNeedpay).compareTo(new BigDecimal(0)) > 0 ) { - manageList.add(setManageRent(wxRentContract.getDecimalSize(),wxBillRent,EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE,operatingManageFeeNeedpay,wxPayAccountBill.getServiceChargeRate(),dayType,receivePeriod)); - } - } - - //批量插入账单 - if(saveDb) { - - WxShopUsers suq = new WxShopUsers(); - suq.updateTenantInfo(wxRentContract); - suq.setShopIds(shopIdList); - suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); - Map shopUserMap = wxShopService.getShopUserMap(suq); - - List rblist = new ArrayList(); - for (int k = 0 ; k < resultList.size(); k++) { - WxAllBill rb = resultList.get(k); - for (int g = 0 ; g < shopIdList.size(); g ++ ){ - WxAllBill rs = new WxAllBill(); - Long sid = shopIdList.get(g); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - try { - BeanUtils.copyProperties(rs, rb); - rs.setId(idWorker.nextId()); - rs.setShopId(sid); - rs.setNeedPay(new BigDecimal(rb.getNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); - rs.setReceivePay(rs.getNeedPay()); - rs.setShopId(sid); - rs.setRentArea(shoprentArea.toPlainString()); - if (StringUtils.isNotBlank(rb.getBussinessManageFeeNeedPay())) { - rs.setBussinessManageFeeNeedPay(new BigDecimal(rb.getBussinessManageFeeNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); - } - if (StringUtils.isNotBlank(rb.getOperatingManageFeeNeedPay())) { - rs.setOperatingManageFeeNeedPay(new BigDecimal(rb.getOperatingManageFeeNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); - } - if (null != shopUserMap ) { - WxShopUsers wsu = shopUserMap.get(sid); - if (null != wsu) { - rs.setCusName(wsu.getName()); - } - } - rblist.add(rs); - } catch (IllegalAccessException e) { - logger.error("savePreviewBill error.",e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); - } catch (InvocationTargetException e) { - logger.error("savePreviewBill error.",e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); - } - } - } - wxAllBillMapper.insertBills(wxRentContract.getTenantId(),rblist); - if (manageList.size() > 0 ) { - List mblist = new ArrayList(); - for (int k = 0 ; k < manageList.size(); k++) { - WxAllBill rb = manageList.get(k); - for (int g = 0 ; g < shopIdList.size(); g ++ ){ - WxAllBill rs = new WxAllBill(); - Long sid = shopIdList.get(g); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - try { - BeanUtils.copyProperties(rs, rb); - rs.setId(idWorker.nextId()); - rs.setShopId(sid); - rs.setNeedPay(new BigDecimal(rb.getNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); - rs.setReceivePay(rs.getNeedPay()); - rs.setShopId(sid); - rs.setRentArea(shoprentArea.toPlainString()); - if (null != shopUserMap ) { - WxShopUsers wsu = shopUserMap.get(sid); - if (null != wsu) { - rs.setCusName(wsu.getName()); - } - } - mblist.add(rs); - } catch (IllegalAccessException e) { - logger.error("savePreviewBill error.",e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); - } catch (InvocationTargetException e) { - logger.error("savePreviewBill error.",e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); - } - } - } - - wxAllBillMapper.insertBills(wxRentContract.getTenantId(),mblist); - } - } - resultMap.put("billcount",billcount); - resultMap.put("billList",resultList); - return resultMap; - } - - private WxAllBill setManageRent(Integer decimalSize,WxAllBill wxBillRent,EnumRentContractManageFeeType feeType,String needPay,Integer serviceChargeRate,int dayType,int receivePeriod) { - WxAllBill manage = new WxAllBill(); - manage.setRentContractId(wxBillRent.getRentContractId()); - manage.setPay(wxBillRent.getPay()); - manage.setStarttime(wxBillRent.getStarttime()); - manage.setEndtime(wxBillRent.getEndtime()); - manage.setReceiveDate(wxBillRent.getReceiveDate()); + //wxBillRent.setIsDel(EnumDelStatus.NOT_DEL.getCode()); + //wxBillRent.setPeriod(++billcount); + wxBillRent.setShopInfo(shopInfoStr); + //wxBillRent.setLatePayRatio(0); + wxBillRent.calcuteTotalFee(wxRentContract.getDecimalSize()); + wxBillRent.setEnergyFeesId(EnumBillAllType.RENT.getEnergyFeesId()); + + //计算手续费 + //BigDecimal servicePay = new BigDecimal(wxBillRent.getReceivePay()).multiply(new BigDecimal(wxPayAccountBill.getServiceChargeRate())) + // .divide(new BigDecimal(10000), wxRentContract.getDecimalSize(), BigDecimal.ROUND_HALF_UP); + //wxBillRent.setServiceChargePay(servicePay.toPlainString()); + //wxBillRent.setOwe(new BigDecimal(wxBillRent.getReceivePay()).add(new BigDecimal(wxBillRent.getServiceChargePay())).toPlainString()); + //wxBillRent.setOwe(new BigDecimal(wxBillRent.getReceivePay()).toPlainString()); + resultList.add(wxBillRent); + + + //商业管理费账单 + if (null != bussinessManagerPriceArrs && bussinessManagerPriceArrs.length > 0 && new BigDecimal(bussinessManageFeeNeedpay).compareTo(new BigDecimal(0)) > 0) { + manageList.add(setManageRent(wxRentContract.getDecimalSize(),wxBillRent,EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE,bussinessManageFeeNeedpay,wxPayAccountBill.getServiceChargeRate(),dayType,receivePeriod)); + } + //营业管理费账单 + if (null != operationManagerPriceArrs && operationManagerPriceArrs.length > 0 && new BigDecimal(operatingManageFeeNeedpay).compareTo(new BigDecimal(0)) > 0 ) { + manageList.add(setManageRent(wxRentContract.getDecimalSize(),wxBillRent,EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE,operatingManageFeeNeedpay,wxPayAccountBill.getServiceChargeRate(),dayType,receivePeriod)); + } + } + + //批量插入账单 + if(saveDb) { + + WxShopUsers suq = new WxShopUsers(); + suq.updateTenantInfo(wxRentContract); + suq.setShopIds(shopIdList); + suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); + Map shopUserMap = wxShopService.getShopUserMap(suq); + + List rblist = new ArrayList(); + for (int k = 0 ; k < resultList.size(); k++) { + WxAllBill rb = resultList.get(k); + for (int g = 0 ; g < shopIdList.size(); g ++ ){ + WxAllBill rs = new WxAllBill(); + Long sid = shopIdList.get(g); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + try { + BeanUtils.copyProperties(rs, rb); + rs.setId(idWorker.nextId()); + rs.setShopId(sid); + rs.setNeedPay(new BigDecimal(rb.getNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); + rs.setReceivePay(rs.getNeedPay()); + rs.setShopId(sid); + rs.setRentArea(shoprentArea.toPlainString()); + if (StringUtils.isNotBlank(rb.getBussinessManageFeeNeedPay())) { + rs.setBussinessManageFeeNeedPay(new BigDecimal(rb.getBussinessManageFeeNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); + } + if (StringUtils.isNotBlank(rb.getOperatingManageFeeNeedPay())) { + rs.setOperatingManageFeeNeedPay(new BigDecimal(rb.getOperatingManageFeeNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); + } + if (null != shopUserMap ) { + WxShopUsers wsu = shopUserMap.get(sid); + if (null != wsu) { + rs.setCusName(wsu.getName()); + } + } + rblist.add(rs); + } catch (IllegalAccessException e) { + logger.error("savePreviewBill error.",e); + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); + } catch (InvocationTargetException e) { + logger.error("savePreviewBill error.",e); + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); + } + } + } + wxAllBillMapper.insertBills(wxRentContract.getTenantId(),rblist); + if (manageList.size() > 0 ) { + List mblist = new ArrayList(); + for (int k = 0 ; k < manageList.size(); k++) { + WxAllBill rb = manageList.get(k); + for (int g = 0 ; g < shopIdList.size(); g ++ ){ + WxAllBill rs = new WxAllBill(); + Long sid = shopIdList.get(g); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(wxRentContract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + try { + BeanUtils.copyProperties(rs, rb); + rs.setId(idWorker.nextId()); + rs.setShopId(sid); + rs.setNeedPay(new BigDecimal(rb.getNeedPay()).multiply(shoprate).setScale(wxRentContract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()); + rs.setReceivePay(rs.getNeedPay()); + rs.setShopId(sid); + rs.setRentArea(shoprentArea.toPlainString()); + if (null != shopUserMap ) { + WxShopUsers wsu = shopUserMap.get(sid); + if (null != wsu) { + rs.setCusName(wsu.getName()); + } + } + mblist.add(rs); + } catch (IllegalAccessException e) { + logger.error("savePreviewBill error.",e); + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); + } catch (InvocationTargetException e) { + logger.error("savePreviewBill error.",e); + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"创建账单失败"); + } + } + } + + wxAllBillMapper.insertBills(wxRentContract.getTenantId(),mblist); + } + } + resultMap.put("billcount",billcount); + resultMap.put("billList",resultList); + return resultMap; + } + + private WxAllBill setManageRent(Integer decimalSize,WxAllBill wxBillRent,EnumRentContractManageFeeType feeType,String needPay,Integer serviceChargeRate,int dayType,int receivePeriod) { + WxAllBill manage = new WxAllBill(); + manage.setRentContractId(wxBillRent.getRentContractId()); + manage.setPay(wxBillRent.getPay()); + manage.setStarttime(wxBillRent.getStarttime()); + manage.setEndtime(wxBillRent.getEndtime()); + manage.setReceiveDate(wxBillRent.getReceiveDate()); manage.setPeriod(wxBillRent.getPeriod()); - manage.updateTenantInfo(wxBillRent); - manage.setIsPreview(wxBillRent.getIsPreview()); - manage.setCreatetime(wxBillRent.getCreatetime()); - manage.setCreateBy(wxBillRent.getCreateBy()); - manage.setCreateByName(wxBillRent.getCreateByName()); - manage.setUpdateBy(wxBillRent.getUpdateBy()); - manage.setUpdatetime(wxBillRent.getUpdatetime()); - manage.setUpdateByName(wxBillRent.getUpdateByName()); - manage.setRentArea(wxBillRent.getRentArea()); - manage.setShopNumber(wxBillRent.getShopNumber()); - manage.setCanEdit(EnumYesOrNo.NO.getCode()); - manage.setCusName(wxBillRent.getCusName()); - if (feeType.getCode().intValue() == EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE.getCode().intValue()){ - manage.setEnergyFeesId(EnumBillAllType.RENT_BUSSINESS_MANAGE.getEnergyFeesId()); - manage.setBillType(EnumBillAllType.RENT_BUSSINESS_MANAGE.getCode()); - }else if (feeType.getCode().intValue() == EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE.getCode().intValue()) { - manage.setEnergyFeesId(EnumBillAllType.RENT_OPERATION_MANAGE.getEnergyFeesId()); - manage.setBillType(EnumBillAllType.RENT_OPERATION_MANAGE.getCode()); - } - final IdWorker idWorker = IdWorker.get(); - wxBillRent.setId(idWorker.nextId()); - manage.setNeedPay(needPay); - manage.setReceivePay(needPay); - //计算手续费 - //BigDecimal servicePay = new BigDecimal(needPay).multiply(new BigDecimal(serviceChargeRate)).divide(new BigDecimal(10000), decimalSize, BigDecimal.ROUND_HALF_UP); - //manage.setServiceChargePay(servicePay.toPlainString()); - //manage.setOwe(new BigDecimal(needPay).add(new BigDecimal(manage.getServiceChargePay())).toPlainString()); - //manage.setOwe(new BigDecimal(needPay).toPlainString()); - return manage; - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData deleteById(String id) { - wxRentContractMapper.deleteById(id); - return new ResultData(Result.SUCCESS, "删除租赁合同信息成功"); - } - - @Override - public void download(HttpServletRequest request, HttpServletResponse response) { - String id = request.getParameter("id"); - WxRentContract wxRentContract = wxRentContractMapper.selectById(id); - String filesuffix = wxRentContract.getFilepath().substring(wxRentContract.getFilepath().lastIndexOf(".")); - String filename = UUID.randomUUID() + filesuffix; - String filepath = fmUploadDir; - String destPath = filepath + filename; - File dest = new File(destPath); - File pDest = dest.getParentFile(); - if (!pDest.exists()) { - pDest.mkdirs(); - } - try { - String exportFileName = wxRentContract.getFilename(); - DownFileUtil.downLoadFromUrl(wxRentContract.getFilepath(), filename, filepath); - DownFileUtil.downFile(destPath, exportFileName, response, request); - org.apache.commons.io.FileUtils.forceDelete(dest); - } catch (IOException e) { - logger.info("创建本地文件失败" + e.getMessage()); - } - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData endContract(WxRentContract wxRentContract,MallUserInfo userInfo) { - - WxRentContract contract = wxRentContractMapper.selectById(wxRentContract.getId()); - if (contract == null) { - return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); - } - contract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); - contract.setUpdatetime(new Date()); - contract.setUpdateBy(userInfo.getId()); - contract.setEndContractTime(wxRentContract.getEndContractTime()); - wxRentContractMapper.updateById(contract); - - //终止租赁合同,同时终止物业合同 - if(EnumEndProperty.END_RENT_AND_PROPERTY.getCode().equals(wxRentContract.getEndProperty())){ -// WxPropertyContract wxPropertyContract = new WxPropertyContract(); -// wxPropertyContract.setRentContractId(wxRentContract.getId()); -// wxPropertyContract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); -// wxPropertyContractMapper.updateStatusByRentContractId(wxPropertyContract); - WxPropertyContract wxPropertyContract = new WxPropertyContract(); - wxRentContract.updateTenantInfo(wxRentContract); - wxPropertyContract.setRentContractId(wxRentContract.getId()); - - //终止有效的合同 - wxPropertyContract.setStatuss(EnumRentContractStatus.getValidStatus()); - wxPropertyContract.setUpdatetime(new Date()); - wxPropertyContract.setUpdateBy(userInfo.getId()); - wxPropertyContract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); - wxPropertyContractMapper.endContract(wxPropertyContract); - //作废未生效的合同 - List unvalidstatuss = new ArrayList(); - unvalidstatuss.add(EnumRentContractStatus.DRAFT.getCode()); - unvalidstatuss.add(EnumRentContractStatus.PERFORMANCE.getCode()); - wxPropertyContract.setStatuss(unvalidstatuss); - wxPropertyContract.setStatus(EnumRentContractStatus.INVALID.getCode()); - wxPropertyContractMapper.endContract(wxPropertyContract); - - //物业账单失效 - WxPropertyContract pq = new WxPropertyContract(); - pq.updateTenantInfo(wxRentContract); - pq.setRentContractId(wxRentContract.getId()); - List plist = wxPropertyContractMapper.findList(pq); - if (null != plist && plist.size() > 0 ) { - WxPropertyContract pc = plist.get(0); - pc.setEndContractTime(wxRentContract.getEndContractTime()); - wxBillAllHelper.propertyContractStop(pc, userInfo); - wxPropertyContractMapper.updateById(pc); - } - - } - //租赁账单失效 - wxBillAllHelper.rentContractStop(wxRentContract,userInfo); -// WxBillRent wxBillRent = new WxBillRent(); -// wxBillRent.setRentContractId(wxRentContract.getId()); -// wxBillRent.updateTenantInfo(wxRentContract); -// wxBillRentMapper.updateInvalidStatus(wxBillRent); - return new ResultData(Result.SUCCESS,"终止成功"); - //解绑商户和商铺关系 -// WxRentContract rentContract = wxRentContractMapper.selectById(wxRentContract.getId()); -// if(rentContract != null && rentContract.getMerchantId() != null){ -// wxMerchantService.disable(rentContract.getMerchantId()); -// } - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public ResultData updateRentContract(WxRentContract wxRentContract) { -// WxRentContract record = wxRentContractMapper.selectById(wxRentContract); -// if (wxRentContract == null) { -// return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); -// } -// record.setMerchantId(wxRentContract.getMerchantId()); - try { - wxRentContractMapper.updateById(wxRentContract); - } catch (MallinkException e) { - logger.info("关联合同商户失败:" + e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); - } - return new ResultData(Result.SUCCESS, "操作成功"); - } - - @Override - public PageInfo getRentContractList(WxRentContract rentContract, Integer pageIndex, Integer pageSize) { - if (StringUtils.isNotBlank(rentContract.getFloorForRule()) || StringUtils.isNotBlank(rentContract.getQueryShopIdStr())) { - List shopIdList = null; - if (StringUtils.isNotBlank(rentContract.getQueryShopIdStr())) { - String[] qsids = rentContract.getQueryShopIdStr().split(","); - if (null != qsids && qsids.length > 0 ) { - shopIdList = new ArrayList(); - for (int i = 0 ; i < qsids.length ; i ++) { - String qsid = qsids[i]; - if (StringUtils.isNotBlank(qsid)) { - shopIdList.add(Long.parseLong(qsid)); - } - } - if (shopIdList.size() <= 0 ) { - shopIdList = null; - } - } - } - - List contractIds = wxAgileContractService.findBuildingFloorContractIds(rentContract, rentContract.getFloorForRule(), null, null, shopIdList, 0); - //List mids = wxMerchantService.getFloorBuildMerchantIds(rentContract, rentContract.getFloorForRule() , null, null,rentContract.getShopTypeForRule(), 0, 0,null); - if (null == contractIds || contractIds.size() <= 0 ) { - rentContract.setId(-1L); - } else { - rentContract.setIds(contractIds); - } - } - //根据客户名称查询 - if (StringUtils.isNotBlank(rentContract.getMerchantName())) { - WxContractCustomers ccq = new WxContractCustomers(); - ccq.updateTenantInfo(rentContract); - ccq.setName(rentContract.getMerchantName()); - List customersIdList = wxContractCustomersMapper.findIdList(ccq); - if (null != customersIdList && customersIdList.size() > 0 ) { - rentContract.setCustomersIdList(customersIdList); - }else { - rentContract.setId(-1L); - } - } - - //PageInfo pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxRentContractMapper.getRentContractList(rentContract)); - PageInfo pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxRentContractMapper.findList(rentContract)); - if (null != pageInfo && null != pageInfo.getList()) { - List customersIdList = new ArrayList(); - for (int i = 0 ; i < pageInfo.getList().size(); i ++ ){ - WxRentContract contract = pageInfo.getList().get(i); - if (null != contract.getCustomersId()) { - customersIdList.add(contract.getCustomersId()); - } - } - - Map customersMap = getContractCustomersMap(rentContract,customersIdList); - - for (int i = 0 ; i < pageInfo.getList().size(); i ++ ) { - WxRentContract contract = pageInfo.getList().get(i); - String merchantName = ""; - if (null != customersMap && null != contract.getCustomersId()) { - WxContractCustomers cc = customersMap.get(contract.getCustomersId()); - if (null != cc) { - merchantName = merchantName + cc.getName(); - } - } - contract.setMerchantName(merchantName); - } - - } - return pageInfo; - } - - private Map getContractCustomersMap(TenantEntity tenantEntity,List customerIds) { - if (null == customerIds || customerIds.size() <= 0 ) { - return null; - } - WxContractCustomers ccq = new WxContractCustomers(); - ccq.updateTenantInfo(tenantEntity); - ccq.setIds(customerIds); - List cclist = wxContractCustomersMapper.findList(ccq); - if (null != cclist && cclist.size() > 0 ){ - Map map = new HashMap(); - for (int i = 0 ; i < cclist.size() ; i ++ ) { - WxContractCustomers cc = cclist.get(i); - if (null != cc) { - map.put(cc.getId(),cc); - } - } - return map; - } - return null; - } - - @Override - @Transactional(rollbackFor = {Exception.class}) - public ResultData updateFile(WxRentContract record, MallUserInfo user,String userName,boolean writeComplate) { - - WxRentContract wxRentContract = wxRentContractMapper.selectById(record.getId()); - if (null == wxRentContract) { - return new ResultData(Result.ERROR,"id查询不到合同"); - } - WxRentContract rc = new WxRentContract(); - rc.setId(record.getId()); - rc.setDecimalSize(wxRentContract.getDecimalSize()); - if (writeComplate) { - rc.setStatus(EnumRentContractStatus.DRAFT.getCode()); - }else { - rc.setStatus(wxRentContract.getStatus()); - } - rc.setFileNames(record.getFileNames()); - rc.setRemark(record.getRemark()); - wxRentContractMapper.updateById(rc); - if (null != wxRentContract.getOperationType() && EnumContractOperationType.WHOLE.getCode().equals(wxRentContract.getOperationType())) { - WxPropertyContract pc = wxPropertyContractMapper.findOneByRentId(wxRentContract); - if (null != pc) { - wxRentContract.setPropertyContractId(pc.getId()); - } - } - return new ResultData(wxRentContract); - } - - @Override - @Transactional(rollbackFor = {Exception.class}) - public ResultData updateRentContractStatus(Long id,boolean buildProperyBill) { - logger.info(" updateRentContractStatus_:"+id); - - - if (id == null) { - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR); - } - WxRentContract record = wxRentContractMapper.selectById(id); - if (record == null) { - return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); - } - //如果合同状态为非正常状态,则不更新合同状态,并删除账单 - if(record.getStatus().intValue() == EnumRentContractStatus.INVALID.getCode().intValue() - || record.getStatus().intValue() == EnumRentContractStatus.TERMINATE.getCode().intValue()) { - return new ResultData(ErrorCode.RENT_CONTRACT_IS_TERMINATED.getCode(),"合同状态已作废或者已终止."); - } - - - //更新合同状态为签约 - WxRentContract wxRentContract = new WxRentContract(); - wxRentContract.setId(id); - if (record.getRentalStartDate().before(new Date())) { - wxRentContract.setStatus(EnumRentContractStatus.PAING.getCode()); - } else { - wxRentContract.setStatus(EnumRentContractStatus.READY_FOR_PAING.getCode()); - } - wxRentContractMapper.updateById(wxRentContract); - - //合同客户状态变更 - WxContractCustomers customers = wxContractCustomersMapper.selectById(record.getCustomersId(), record.getTenantId()); - customers.setStatus(EnumContractCustomersStatus.FORMUL.getCode()); - customers.setUpdateDate(new Date()); - wxContractCustomersMapper.updateById(customers); - - //把customers写入到wxShopUser - String cusName = castCustomersToShopUsers(customers,record.shopIdsByRentInfo()); - - //如果合同的账单cusName为空的话,则设置为customers name - handleContractBillCusName(record,cusName); - - //EventUtil.publistRentEvent(this, wxRentContract); - //建立账单 - //自定义账单无单价,为能生成账单,设置该值 - if (EnumRentContractType.RENT_BY_CUSTOMIZE.getCode() == record.getType()) { - record.setPrice("0.01"); - } - if (record != null && (record.getReceivePeriod() != null || - (null != record.getAgileType() && record.getAgileType().intValue() == EnumRentAgileType.AGILE.getCode()))) { - //预览账单改为正式,并写入商户id - WxAllBill billRent = new WxAllBill(); - billRent.setRentContractId(id); - billRent.setIsPreview(EnumIsPreview.NO.getCode()); - billRent.updateTenantInfo(record); - wxAllBillMapper.updatePreviewStatus(billRent); -// WxMerchant wxMerchant = new WxMerchant(); -// wxMerchant.setId(record.getMerchantId()); -// wxMerchant.updateTenantInfo(record); - - //商业管理费,营业管理费 - //WxAllBill billRentManage = new WxAllBill(); - //billRentManage.setRentContractId(id); - //billRentManage.setIsPreview(EnumIsPreview.NO.getCode()); - //billRentManage.updateTenantInfo(record); - //wxAllBillMapper.updatePreviewStatus(billRentManage); - - if(new BigDecimal(record.getDeposit()).compareTo(new BigDecimal(0)) > 0) { - //押金 - buildDeposit(record, null, id); - } - //一起建立物业账单 - if (buildProperyBill) { - updatePropertyPreviewBill(record); - } - - //作废合同 - //updateInvalidContract(id); - } - - return new ResultData(Result.SUCCESS, "操作成功"); - } - - public String castCustomersToShopUsers(WxContractCustomers customers,List shopIdList) { - WxShopUsersInfo suiq = new WxShopUsersInfo(); - suiq.updateTenantInfo(customers); - suiq.setPrincipalType(customers.getPrincipalType()); - suiq.setName(customers.getName()); - suiq.setPhone(customers.getPhone()); - List ids = wxShopService.getUserInfoList(suiq); - Long infoId = null; - String cusName = null; - if (null == ids || ids.size() <= 0 ) { - WxShopUsersInfo sui = new WxShopUsersInfo(); - sui.updateTenantInfo(customers); - sui.setPrincipalType(customers.getPrincipalType()); - sui.setName(customers.getName()); - sui.setPhone(customers.getPhone()); - sui.setLegalPerson(customers.getLegalPerson()); - sui.setIdNumber(customers.getIdNumber()); - sui.setSex(customers.getSex()); - sui.setLinkPerson(customers.getLinkPerson()); - sui.setCreateContractCustomerId(customers.getId()); - wxShopService.saveOrUpdateShopUsersInfo(sui); - infoId = sui.getId(); - cusName = customers.getName(); - }else { - infoId = ids.get(0).getId(); - cusName = ids.get(0).getName(); - } - - for (int i = 0 ; i < shopIdList.size(); i++) { - Long shopId = shopIdList.get(i); - //查询这个infoId是不是当前的租户 - WxShopUsers suq = new WxShopUsers(); - suq.updateTenantInfo(customers); - suq.setShopId(shopId); - suq.setInfoId(infoId); - suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); - List ulist = wxShopService.getShopUsersList(suq); - if (null != ulist && ulist.size() > 0 ) { - //WxShopUsers su = ulist.get(0); - }else { - //先把当前的租户变更掉 - wxShopService.updateRentShopUsersOld(customers,shopId); - //新增租户 - WxShopUsers su = new WxShopUsers(); - su.updateTenantInfo(customers); - su.setShopId(shopId); - su.setInfoId(infoId); - su.setType(EnumShopUsersType.RENTER.getCode()); - su.setStatus(EnumShopUsersStatus.LIVE.getCode()); - wxShopService.saveOrUpdateShopUsers(su); - } - } - return cusName; - } - - public void handleContractBillCusName(WxRentContract record,String cusName) { - WxAllBill bill = new WxAllBill(); - bill.updateTenantInfo(record); - bill.setCusName(cusName); - bill.setRentContractId(record.getId()); - wxAllBillMapper.updateContractCusName(bill); - } - - @Override - public void updatePropertyPreviewBill(WxRentContract record) { - //合并合同-更新物业账单 - if (record.getOperationType().equals(EnumContractOperationType.WHOLE.getCode())) { - //查签约 - WxPropertyContract wxPropertyContract = new WxPropertyContract(); - wxPropertyContract.setRentContractId(record.getId()); - WxPropertyContract propertyContract = wxPropertyContractMapper.selectOne(new QueryWrapper(wxPropertyContract)); - logger.info("物业合同状态及账单状态修改:{}",propertyContract); - if (propertyContract != null) { - wxPropertyContractService.updatePropertyContractStatus(propertyContract.getId()); - } - } - } - - @Override - public void updateApplyStatus(WxRentContract wxRentContract) { - wxRentContractMapper.updateApplyStatus(wxRentContract); - } - -// @Override -// public Integer getShopType(WxRentContract wxRentContract) { -// return wxRentContractMapper.getShopType(wxRentContract); -// } - - //yearList,每年的合同截止日期,到这个截止日之前之后,需要拆开时间 - public static List initBillTimeList(List yearList,Date start,Date end,Integer adjustPeriod,Integer dayType,int receivePeriod,int payPeriod){ - List list = new ArrayList<>(); - int count = 0; - List yearsEndList = new ArrayList(); - yearsEndList.addAll(yearList); - if (yearsEndList.size() > 0) { - yearsEndList.remove(0); - } - BillTimeVo receiveDate = null; - while (true) { - BillTimeVo timeVo = new BillTimeVo(); - - //账单日 - Calendar instance = Calendar.getInstance(); - instance.setTime(start); - instance.set(Calendar.MILLISECOND, 0); - //开始时间 - timeVo.setStartDate(instance.getTime()); - - //结束时间 - instance.clear(); - instance.setTime(start); - instance.set(Calendar.MILLISECOND, 0); - instance = EnumContractReceivePeriodUnit.getAfterCalendarDay(instance, receivePeriod, dayType); - //instance.add(dayType, receivePeriod); - //instance.add(Calendar.DATE, -1); - timeVo.setEndDate(instance.getTime()); - - //自然月,应该是从本月开始到本月结束 - if(adjustPeriod.equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode())){ - timeVo.setEndDate(EnumContractReceivePeriodUnit.getAfterCalendarNarDay(timeVo.getStartDate(), receivePeriod, dayType)); - } - - //如果是到了每年的截止时间,第一年忽略(是开始时间) - boolean isYearCut = false;//是不是有截断 - if (null != yearsEndList && yearsEndList.size() > 0 ) { - Date yearEndDateStart = yearsEndList.get(0); - //如果开始时间到了年的截止 - if (timeVo.getStartDate().equals(yearEndDateStart)) { - yearsEndList.remove(yearEndDateStart); - }else if (timeVo.getStartDate().after(yearEndDateStart)) { - //do nothing - }else if (timeVo.getStartDate().before(yearEndDateStart)) { - Date yearEndDateEnd = DateUtils.getDayEnd(yearEndDateStart); - if (timeVo.getEndDate().after(yearEndDateEnd)) { - timeVo.setEndDate(DateUtils.getDaySet(yearEndDateEnd,Calendar.DATE,-1)); - yearsEndList.remove(yearEndDateStart); - isYearCut = true; - }else if(timeVo.getEndDate().equals(yearEndDateEnd)) { - yearsEndList.remove(yearEndDateStart); - } - } - } - - if(timeVo.getEndDate().after(end)){ - Calendar endinstance = Calendar.getInstance(); - endinstance.setTime(end); - endinstance.set(Calendar.MILLISECOND, 0); - timeVo.setEndDate(endinstance.getTime()); - } - - list.add(timeVo); - - receiveDate = WxRentContractHelper.getReceiveDate(receiveDate,timeVo.getStartDate(), timeVo.getEndDate(), payPeriod,adjustPeriod,receivePeriod,dayType); - timeVo.setReceiveDate(receiveDate.getStartDate()); - - - //next - start = DateUtils.getDaySet(timeVo.getEndDate(),Calendar.SECOND,1); - - if(start.after(end)) { - break; - } - count ++; - - //预警 - if(count >= 1000){ - Logger logger = LoggerFactory.getLogger(WxRentContractServiceImpl.class); - logger.error("initBillTimeList() warnCount max error !!!"); - break; - } - } - return list; - } - - - @Override - public WxRentContract getByBill(WxAllBill billRent) { - return wxRentContractMapper.getByBill(billRent); - } - - - @Override - public ResultData getContractByContractNumber(WxRentContract rentContract) { - WxRentContract wxRentContract = wxRentContractMapper.selectOne(new QueryWrapper<>(rentContract)); - return new ResultData(wxRentContract); - } - - @Override - public ResultData apply(WxRentContract rentContract,MallUserInfo user) { - //如果存在审批中的合同,不允许提交审批 - WxRentContract wrq = new WxRentContract(); - wrq.updateTenantInfo(user); - List shopIds = rentContract.shopIdsByRentInfo(); - List contractIds = wxAgileContractService.findBuildingFloorContractIds(wrq, null, null, null, shopIds, 0); - if (null != contractIds && contractIds.size() > 0 ) { - wrq.setIds(contractIds); - } - wrq.setStatus(EnumRentContractStatus.PERFORMANCE.getCode()); - List clist = wxRentContractMapper.findList(wrq); - if (null != clist && clist.size() > 0 ) { - return new ResultData(Result.ERROR, "房间资源存在其他审批中的租金合同。请先作完成。"); - } - //如果该合同是租金+物业合同,则还要判断物业合同 - if(rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue()) { - WxPropertyContract wpc = new WxPropertyContract(); - wpc.updateTenantInfo(user); - if (null != contractIds && contractIds.size() > 0 ) { - wpc.setIds(contractIds); - } - wpc.setStatus(EnumRentContractStatus.PERFORMANCE.getCode()); - List plist = wxPropertyContractMapper.findList(wpc); - if (null != plist && plist.size() > 0 ) { - return new ResultData(Result.ERROR, "房间资源存在其他审批中的物业合同。请先作完成。"); - } - } -// Integer count = wxRentContractMapper.getCanApplyCount(rentContract.getId()); -// if (null != count && count.intValue()>0) { -// return new ResultData(Result.ERROR, "当前存在其他草稿状态或者履约驳回的合同。请先作废其他草稿或者审批拒绝或者撤回的合同。"); -// } - - if (CollectionUtils.isEmpty(rentContract.getFlowParams())) { - return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同没有审批流程."); - } - - if ((EnumRentContractStatus.DRAFT.getCode().intValue() == rentContract.getStatus().intValue()) - || (EnumRentContractStatus.PERFORMANCE.getCode().intValue() == rentContract.getStatus().intValue() - && (EnumRentContractAppStatus.REJECT.getCode().intValue() == rentContract.getApplyStatus().intValue() || - EnumRentContractAppStatus.SETBACK.getCode().intValue() == rentContract.getApplyStatus().intValue())) - ) { - Integer bussinessType = (Integer) rentContract.getFlowParams().get("businessType"); - if (null == bussinessType) { - return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同FlowParams错误,未找到businessType."); - } - WxFlowModel flowModle = wxFlowService.getModelByType(bussinessType, rentContract); - if (null == flowModle) { - return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同配置的流程["+String.valueOf(bussinessType)+"]未找到流程模板."); - } - //rentContract.getFlowParams().put("businessId", rentContract.getId().toString()); - wxFlowService.start(rentContract.getFlowParams(), user.getId(), user.getName(), rentContract); - return new ResultData(Result.SUCCESS,"提交审批成功",rentContract); - }else { - return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同状态不能提交审批.允许提交的状态为 [草稿],[履约中+审批驳回]"); - } - } - - @Override - @Transactional(rollbackFor = {Exception.class}) - public void renewal(WxRentContract rentContract,WxPropertyContract propertyContract,MallUserInfo user) { - final IdWorker idWorker = IdWorker.get(); - Long newContractId = idWorker.nextId(); - //拷贝 - WxContractShop csq = new WxContractShop(); - csq.updateTenantInfo(rentContract); - csq.setContractId(rentContract.getId()); - List csqlist = wxContractShopMapper.findList(csq); - if (null != csqlist && csqlist.size() > 0 ){ - for ( int i = 0 ; i< csqlist.size() ; i ++) { - WxContractShop cs = csqlist.get(i); - cs.setId(idWorker.nextId()); - cs.setContractId(newContractId); - cs.setCreateDate(new Date()); - cs.setUpdateDate(new Date()); - wxContractShopMapper.insert(cs); - } - } - - //WxContractCustomers ccq = new WxContractCustomers(); - - WxRentContractRevenueJump crjq = new WxRentContractRevenueJump(); - crjq.updateTenantInfo(rentContract); - crjq.setRentContractId(rentContract.getId()); - List jumpList = wxRentContractRevenueJumpMapper.findList(crjq); - if ( null != jumpList && jumpList.size() > 0 ) { - for (int i = 0 ; i < jumpList.size(); i++) { - WxRentContractRevenueJump rj = jumpList.get(i); - rj.setRentContractId(newContractId); - rj.setId(idWorker.nextId()); - rj.setCreateTime(new Date()); - rj.setUpdateTime(new Date()); - wxRentContractRevenueJumpMapper.insert(rj); - } - } - - //WxRentContractFreePeriod cfpq = new WxRentContractFreePeriod(); - - Long oldId = rentContract.getId(); - rentContract.setId(newContractId); - rentContract.setCreatetime(new Date()); - rentContract.setCreateBy(user.getId()); - rentContract.setCreateByName(user.getName()); - rentContract.setUpdatetime(new Date()); - rentContract.setUpdateBy(user.getId()); - rentContract.setUpdateByName(user.getName()); - rentContract.setStatus(EnumRentContractStatus.UNWRITE.getCode()); - rentContract.setApplyStatus(EnumRentContractAppStatus.DEFAULT.getCode()); - rentContract.setEndContractTime(null); - rentContract.setFirstBillDateStart(null); - rentContract.setFirstBillDateEnd(null); - rentContract.setFirstBillReceiveDate(null); - int[] array = DateUtils.getDiff(rentContract.getRentalStartDate(),rentContract.getRentalEndDate()); - rentContract.setLease(array[0]); - //rentContract.setAdjustRatio(); - //rentContract.setRevenueRatioSet(); - //rentContract.set - wxRentContractMapper.insert(rentContract); - - if (rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue() && null != propertyContract) { - propertyContract.setRentalStartDate(rentContract.getRentalStartDate()); - propertyContract.setRentalEndDate(rentContract.getRentalEndDate()); - propertyContract.setSignDate(rentContract.getSignDate()); - propertyContract.setStartDate(rentContract.getStartDate()); - propertyContract.setEndDate(rentContract.getStartDate()); - propertyContract.setRentContractId(newContractId); - wxPropertyContractService.renewal(propertyContract, user,true); - } - } - - @Transactional(rollbackFor = {Exception.class}) - @Override - public void transfer(WxRentContract rentContract,MallUserInfo user) { - this.setCustomers(rentContract); - rentContract.setUpdatetime(new Date()); - rentContract.setUpdateBy(user.getId()); - rentContract.setUpdateByName(user.getName()); - wxRentContractMapper.updateById(rentContract); - - //更新账单归属 - WxAllBill bill = new WxAllBill(); - bill.updateTenantInfo(rentContract); - bill.setRentContractId(rentContract.getId()); - bill.setCusName(rentContract.getCustomerName()); - wxAllBillMapper.transferCusName(bill); - - if (rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue()) { - WxPropertyContract pq = new WxPropertyContract(); - pq.updateTenantInfo(rentContract); - pq.setOperationType(EnumContractOperationType.WHOLE.getCode()); - pq.setRentContractId(rentContract.getId()); - List pclist = wxPropertyContractService.findList(pq); - if (null != pclist && pclist.size() > 0 ) { - WxPropertyContract propertyContract = pclist.get(0); - wxPropertyContractService.transfer(propertyContract, user); - } - } - } - - @Override - public void outDateContract(WxMall wxMall) { - try { - //查询商户下计租到期的合同,更新合同状态 - WxRentContract wrc = new WxRentContract(); - wrc.updateTenantInfo(wxMall); - wrc.setStatus(EnumRentContractStatus.PAING.getCode()); - List contractList = wxRentContractMapper.findList(wrc); - for (WxRentContract contract:contractList) { - if (contract.getRentalEndDate().before(new Date())) { - contract.setStatus(EnumRentContractStatus.OUT_DATE.getCode()); - wxRentContractMapper.updateById(contract); - } - } - }catch(Exception e) { - logger.error("outDateContract error.",e); - } - } - - @Override - public void readyToNomal(WxMall wxMall) { - WxRentContract wr = new WxRentContract(); - wr.setStatus(EnumRentContractStatus.READY_FOR_PAING.getCode()); - wr.updateTenantInfo(wxMall); - List rentList = wxRentContractMapper.findList(wr); - if (null != rentList && rentList.size() > 0 ) { - for (WxRentContract wrc : rentList) { - if (wrc.getRentalStartDate().before(new Date())) { - wrc.setStatus(EnumRentContractStatus.PAING.getCode()); - wxRentContractMapper.updateStatus(wrc); - } - } - } - } - - @Override - public WxRentContract getSimpleDeatil(Long id) { - return wxRentContractMapper.selectById(id); - } - - @Override - public long findCount(WxRentContract wxRentContract) { - TenantEntity tenantEntity = new TenantEntity(); - tenantEntity.setTenantId(wxRentContract.getTenantId()); - tenantEntity.setParentTenantId(wxRentContract.getParentTenantId()); - List tenantEntitys = wxMallService.getTenantEntitys(tenantEntity); - long count = 0l; - for (TenantEntity te:tenantEntitys) { - wxRentContract.updateTenantInfo(te); - count += wxRentContractMapper.findCount(wxRentContract); - } - wxRentContract.updateTenantInfo(tenantEntity); - return count; - } - - @Override - public void setEndContractTime(WxRentContract wxRentContract) { - wxRentContractMapper.setEndContractTime(wxRentContract); - } - - @Override - public List findToEndContractList(WxRentContract record) { - return wxRentContractMapper.findToEndContractList(record); - } - - @Override - public List findToOutDateContracts(TenantEntity tenantEntity) { - WxRentContract wrc = new WxRentContract(); - wrc.setStatus(EnumRentContractStatus.PAING.getCode()); - wrc.setOutDateNofity(1); - return wxRentContractMapper.findList(wrc); - } - - @Override - public void calcuteByTradeDaily(WxRentContract wxRentContract) { - } - - private BigDecimal sumTradeDailyBySameMonthDay(Integer decimalSize,TenantEntity tenantEntity,Long merchantId,Date begin ,Date end) { - //如果有按月的,则取按月来算 - WxMerchantTradeDaily tdq = new WxMerchantTradeDaily(); - tdq.updateTenantInfo(tenantEntity); - tdq.setMerchantId(merchantId); - tdq.setDateType(EnumTradeDailyDateType.MONTH.getCode()); - tdq.setReportDate(DateUtils.date2String(begin, DateUtils.DATE_PATTERN_MONTH)); - List monthList = wxMerchantTradeDailyMapper.findList(tdq); - if (null != monthList && monthList.size() > 0 ){ - int monthSums = monthList.get(0).getTradeAmtInteger(); - Date _fistDay = DateUtils.getDayBegin(DateUtils.getFirstDayForCurrMonth(begin)); - Date _lastDay = DateUtils.getLastDayForMonth(begin); - if (begin.equals(_fistDay) && end.equals(_lastDay)) { - //满月 - return new BigDecimal(monthSums); - }else { - //根据天数计算 - int monthDays = DateUtils.daysBetween(_fistDay, _lastDay)+1; - int _days = DateUtils.daysBetween(begin, end)+1; - if (_days == 0) { - _days = 1;//当天 - } - BigDecimal servicePay = new BigDecimal(monthSums).multiply(new BigDecimal(_days)).divide(new BigDecimal(monthDays), decimalSize, BigDecimal.ROUND_HALF_UP); - return servicePay; - } - }else { - WxMerchantTradeDaily tdq1 = new WxMerchantTradeDaily(); - tdq1.updateTenantInfo(tenantEntity); - tdq1.setMerchantId(merchantId); - tdq1.setDateType(EnumTradeDailyDateType.DAY.getCode()); - tdq1.setStartTime(DateUtils.format(begin)); - tdq1.setEndTime(DateUtils.format(end)); - String sumMoney = wxMerchantTradeDailyMapper.findSumMoney(tdq1); - return new BigDecimal(sumMoney); - } - } - - @Override - public void deletePrewBill(WxRentContract record) { - //删除预账单,重新生成 - wxAllBillMapper.deleteBillByContract(record); - //删除商业管理费账单 - //WxAllBill wxBillRentManage = new WxAllBill(); - //wxBillRentManage.setRentContractId(record.getId()); - //wxBillRentManage.setManageFeeType(EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE.getCode()); - //wxBillRentManage.updateTenantInfo(record); - //wxAllBillMapper.deletePreviewBill(wxBillRentManage); - //删除营业管理费账单 - //wxBillRentManage.setManageFeeType(EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE.getCode()); - //wxBillRentManageMapper.deletePreviewBill(wxBillRentManage); - } - - @Override - public List getFreePeriods(WxRentContract wxRentContract) { - int[] array = DateUtils.getDiff(wxRentContract.getRentalStartDate(),wxRentContract.getRentalEndDate()); - int months = array[0]; - int years = 0; - if ( months % 12 == 0) { - years = months / 12; - }else { - years = months / 12 + 1; - } - if (years == 0) { - years = 1; - } - Date start = wxRentContract.getRentalStartDate(); - List volist = new ArrayList(); - for (int i = 0 ; i < years; i ++) { - RentContractFreePeriodVo vo = new RentContractFreePeriodVo(); - vo.setYearIndex(i+1); - vo.setStart(start); - if (i == years-1) { - vo.setEnd(wxRentContract.getRentalEndDate()); - }else { - start = DateUtils.getTimeAfterDays(365*(i+1)+1,wxRentContract.getRentalStartDate()); - vo.setEnd(start); - } - WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); - fpq.updateTenantInfo(wxRentContract); - fpq.setRentContractId(wxRentContract.getId()); - fpq.setYearIndex(i+1); - fpq.setSortColumn("start_date asc"); - vo.setPeriods(wxRentContractFreePeriodMapper.findList(fpq)); - volist.add(vo); - } - return volist; - } - - @Override - public void saveFreePeriods(WxRentContract wxRentContract) { - WxRentContract rentContract = wxRentContractMapper.selectById(wxRentContract.getId()); - List yearsVo = getRentContractYears(rentContract); - if (null == yearsVo) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无缴费年限"); - } - Map yearsMap = new HashMap(); - for (int i = 0 ; i < yearsVo.size() ; i++) { - WxRentContractYearsVo vo = yearsVo.get(i); - yearsMap.put(vo.getYearIndex(), vo); - } - - WxRentContractFreePeriod del = new WxRentContractFreePeriod(); - del.updateTenantInfo(wxRentContract); + manage.updateTenantInfo(wxBillRent); + manage.setIsPreview(wxBillRent.getIsPreview()); + manage.setCreatetime(wxBillRent.getCreatetime()); + manage.setCreateBy(wxBillRent.getCreateBy()); + manage.setCreateByName(wxBillRent.getCreateByName()); + manage.setUpdateBy(wxBillRent.getUpdateBy()); + manage.setUpdatetime(wxBillRent.getUpdatetime()); + manage.setUpdateByName(wxBillRent.getUpdateByName()); + manage.setRentArea(wxBillRent.getRentArea()); + manage.setShopNumber(wxBillRent.getShopNumber()); + manage.setCanEdit(EnumYesOrNo.NO.getCode()); + manage.setCusName(wxBillRent.getCusName()); + if (feeType.getCode().intValue() == EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE.getCode().intValue()){ + manage.setEnergyFeesId(EnumBillAllType.RENT_BUSSINESS_MANAGE.getEnergyFeesId()); + manage.setBillType(EnumBillAllType.RENT_BUSSINESS_MANAGE.getCode()); + }else if (feeType.getCode().intValue() == EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE.getCode().intValue()) { + manage.setEnergyFeesId(EnumBillAllType.RENT_OPERATION_MANAGE.getEnergyFeesId()); + manage.setBillType(EnumBillAllType.RENT_OPERATION_MANAGE.getCode()); + } + final IdWorker idWorker = IdWorker.get(); + wxBillRent.setId(idWorker.nextId()); + manage.setNeedPay(needPay); + manage.setReceivePay(needPay); + //计算手续费 + //BigDecimal servicePay = new BigDecimal(needPay).multiply(new BigDecimal(serviceChargeRate)).divide(new BigDecimal(10000), decimalSize, BigDecimal.ROUND_HALF_UP); + //manage.setServiceChargePay(servicePay.toPlainString()); + //manage.setOwe(new BigDecimal(needPay).add(new BigDecimal(manage.getServiceChargePay())).toPlainString()); + //manage.setOwe(new BigDecimal(needPay).toPlainString()); + return manage; + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData deleteById(String id) { + wxRentContractMapper.deleteById(id); + return new ResultData(Result.SUCCESS, "删除租赁合同信息成功"); + } + + @Override + public void download(HttpServletRequest request, HttpServletResponse response) { + String id = request.getParameter("id"); + WxRentContract wxRentContract = wxRentContractMapper.selectById(id); + String filesuffix = wxRentContract.getFilepath().substring(wxRentContract.getFilepath().lastIndexOf(".")); + String filename = UUID.randomUUID() + filesuffix; + String filepath = fmUploadDir; + String destPath = filepath + filename; + File dest = new File(destPath); + File pDest = dest.getParentFile(); + if (!pDest.exists()) { + pDest.mkdirs(); + } + try { + String exportFileName = wxRentContract.getFilename(); + DownFileUtil.downLoadFromUrl(wxRentContract.getFilepath(), filename, filepath); + DownFileUtil.downFile(destPath, exportFileName, response, request); + org.apache.commons.io.FileUtils.forceDelete(dest); + } catch (IOException e) { + logger.info("创建本地文件失败" + e.getMessage()); + } + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData endContract(WxRentContract wxRentContract,MallUserInfo userInfo) { + + WxRentContract contract = wxRentContractMapper.selectById(wxRentContract.getId()); + if (contract == null) { + return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); + } + contract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); + contract.setUpdatetime(new Date()); + contract.setUpdateBy(userInfo.getId()); + contract.setEndContractTime(wxRentContract.getEndContractTime()); + wxRentContractMapper.updateById(contract); + + //终止租赁合同,同时终止物业合同 + if(EnumEndProperty.END_RENT_AND_PROPERTY.getCode().equals(wxRentContract.getEndProperty())){ +// WxPropertyContract wxPropertyContract = new WxPropertyContract(); +// wxPropertyContract.setRentContractId(wxRentContract.getId()); +// wxPropertyContract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); +// wxPropertyContractMapper.updateStatusByRentContractId(wxPropertyContract); + WxPropertyContract wxPropertyContract = new WxPropertyContract(); + wxRentContract.updateTenantInfo(wxRentContract); + wxPropertyContract.setRentContractId(wxRentContract.getId()); + + //终止有效的合同 + wxPropertyContract.setStatuss(EnumRentContractStatus.getValidStatus()); + wxPropertyContract.setUpdatetime(new Date()); + wxPropertyContract.setUpdateBy(userInfo.getId()); + wxPropertyContract.setStatus(EnumRentContractStatus.TERMINATE.getCode()); + wxPropertyContractMapper.endContract(wxPropertyContract); + //作废未生效的合同 + List unvalidstatuss = new ArrayList(); + unvalidstatuss.add(EnumRentContractStatus.DRAFT.getCode()); + unvalidstatuss.add(EnumRentContractStatus.PERFORMANCE.getCode()); + wxPropertyContract.setStatuss(unvalidstatuss); + wxPropertyContract.setStatus(EnumRentContractStatus.INVALID.getCode()); + wxPropertyContractMapper.endContract(wxPropertyContract); + + //物业账单失效 + WxPropertyContract pq = new WxPropertyContract(); + pq.updateTenantInfo(wxRentContract); + pq.setRentContractId(wxRentContract.getId()); + List plist = wxPropertyContractMapper.findList(pq); + if (null != plist && plist.size() > 0 ) { + WxPropertyContract pc = plist.get(0); + pc.setEndContractTime(wxRentContract.getEndContractTime()); + wxBillAllHelper.propertyContractStop(pc, userInfo); + wxPropertyContractMapper.updateById(pc); + } + + } + //租赁账单失效 + wxBillAllHelper.rentContractStop(wxRentContract,userInfo); +// WxBillRent wxBillRent = new WxBillRent(); +// wxBillRent.setRentContractId(wxRentContract.getId()); +// wxBillRent.updateTenantInfo(wxRentContract); +// wxBillRentMapper.updateInvalidStatus(wxBillRent); + return new ResultData(Result.SUCCESS,"终止成功"); + //解绑商户和商铺关系 +// WxRentContract rentContract = wxRentContractMapper.selectById(wxRentContract.getId()); +// if(rentContract != null && rentContract.getMerchantId() != null){ +// wxMerchantService.disable(rentContract.getMerchantId()); +// } + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public ResultData updateRentContract(WxRentContract wxRentContract) { +// WxRentContract record = wxRentContractMapper.selectById(wxRentContract); +// if (wxRentContract == null) { +// return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); +// } +// record.setMerchantId(wxRentContract.getMerchantId()); + try { + wxRentContractMapper.updateById(wxRentContract); + } catch (MallinkException e) { + logger.info("关联合同商户失败:" + e.getMessage()); + throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); + } + return new ResultData(Result.SUCCESS, "操作成功"); + } + + @Override + public PageInfo getRentContractList(WxRentContract rentContract, Integer pageIndex, Integer pageSize) { + if (StringUtils.isNotBlank(rentContract.getFloorForRule()) || StringUtils.isNotBlank(rentContract.getQueryShopIdStr())) { + List shopIdList = null; + if (StringUtils.isNotBlank(rentContract.getQueryShopIdStr())) { + String[] qsids = rentContract.getQueryShopIdStr().split(","); + if (null != qsids && qsids.length > 0 ) { + shopIdList = new ArrayList(); + for (int i = 0 ; i < qsids.length ; i ++) { + String qsid = qsids[i]; + if (StringUtils.isNotBlank(qsid)) { + shopIdList.add(Long.parseLong(qsid)); + } + } + if (shopIdList.size() <= 0 ) { + shopIdList = null; + } + } + } + + List contractIds = wxAgileContractService.findBuildingFloorContractIds(rentContract, rentContract.getFloorForRule(), null, null, shopIdList, 0); + //List mids = wxMerchantService.getFloorBuildMerchantIds(rentContract, rentContract.getFloorForRule() , null, null,rentContract.getShopTypeForRule(), 0, 0,null); + if (null == contractIds || contractIds.size() <= 0 ) { + rentContract.setId(-1L); + } else { + rentContract.setIds(contractIds); + } + } + //根据客户名称查询 + if (StringUtils.isNotBlank(rentContract.getMerchantName())) { + WxContractCustomers ccq = new WxContractCustomers(); + ccq.updateTenantInfo(rentContract); + ccq.setName(rentContract.getMerchantName()); + List customersIdList = wxContractCustomersMapper.findIdList(ccq); + if (null != customersIdList && customersIdList.size() > 0 ) { + rentContract.setCustomersIdList(customersIdList); + }else { + rentContract.setId(-1L); + } + } + + //PageInfo pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxRentContractMapper.getRentContractList(rentContract)); + PageInfo pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxRentContractMapper.findList(rentContract)); + if (null != pageInfo && null != pageInfo.getList()) { + List customersIdList = new ArrayList(); + for (int i = 0 ; i < pageInfo.getList().size(); i ++ ){ + WxRentContract contract = pageInfo.getList().get(i); + if (null != contract.getCustomersId()) { + customersIdList.add(contract.getCustomersId()); + } + } + + Map customersMap = getContractCustomersMap(rentContract,customersIdList); + + for (int i = 0 ; i < pageInfo.getList().size(); i ++ ) { + WxRentContract contract = pageInfo.getList().get(i); + String merchantName = ""; + if (null != customersMap && null != contract.getCustomersId()) { + WxContractCustomers cc = customersMap.get(contract.getCustomersId()); + if (null != cc) { + merchantName = merchantName + cc.getName(); + } + } + contract.setMerchantName(merchantName); + } + + } + return pageInfo; + } + + private Map getContractCustomersMap(TenantEntity tenantEntity,List customerIds) { + if (null == customerIds || customerIds.size() <= 0 ) { + return null; + } + WxContractCustomers ccq = new WxContractCustomers(); + ccq.updateTenantInfo(tenantEntity); + ccq.setIds(customerIds); + List cclist = wxContractCustomersMapper.findList(ccq); + if (null != cclist && cclist.size() > 0 ){ + Map map = new HashMap(); + for (int i = 0 ; i < cclist.size() ; i ++ ) { + WxContractCustomers cc = cclist.get(i); + if (null != cc) { + map.put(cc.getId(),cc); + } + } + return map; + } + return null; + } + + @Override + @Transactional(rollbackFor = {Exception.class}) + public ResultData updateFile(WxRentContract record, MallUserInfo user,String userName,boolean writeComplate) { + + WxRentContract wxRentContract = wxRentContractMapper.selectById(record.getId()); + if (null == wxRentContract) { + return new ResultData(Result.ERROR,"id查询不到合同"); + } + WxRentContract rc = new WxRentContract(); + rc.setId(record.getId()); + rc.setDecimalSize(wxRentContract.getDecimalSize()); + if (writeComplate) { + rc.setStatus(EnumRentContractStatus.DRAFT.getCode()); + }else { + rc.setStatus(wxRentContract.getStatus()); + } + rc.setFileNames(record.getFileNames()); + rc.setRemark(record.getRemark()); + wxRentContractMapper.updateById(rc); + if (null != wxRentContract.getOperationType() && EnumContractOperationType.WHOLE.getCode().equals(wxRentContract.getOperationType())) { + WxPropertyContract pc = wxPropertyContractMapper.findOneByRentId(wxRentContract); + if (null != pc) { + wxRentContract.setPropertyContractId(pc.getId()); + } + } + return new ResultData(wxRentContract); + } + + @Override + @Transactional(rollbackFor = {Exception.class}) + public ResultData updateRentContractStatus(Long id,boolean buildProperyBill) { + logger.info(" updateRentContractStatus_:"+id); + + + if (id == null) { + return new ResultData(ErrorCode.SYS_PARAMETER_ERROR); + } + WxRentContract record = wxRentContractMapper.selectById(id); + if (record == null) { + return new ResultData(ErrorCode.RENT_CONTRACT_IS_NOT_FOUND); + } + //如果合同状态为非正常状态,则不更新合同状态,并删除账单 + if(record.getStatus().intValue() == EnumRentContractStatus.INVALID.getCode().intValue() + || record.getStatus().intValue() == EnumRentContractStatus.TERMINATE.getCode().intValue()) { + return new ResultData(ErrorCode.RENT_CONTRACT_IS_TERMINATED.getCode(),"合同状态已作废或者已终止."); + } + + + //更新合同状态为签约 + WxRentContract wxRentContract = new WxRentContract(); + wxRentContract.setId(id); + if (record.getRentalStartDate().before(new Date())) { + wxRentContract.setStatus(EnumRentContractStatus.PAING.getCode()); + } else { + wxRentContract.setStatus(EnumRentContractStatus.READY_FOR_PAING.getCode()); + } + wxRentContractMapper.updateById(wxRentContract); + + //合同客户状态变更 + WxContractCustomers customers = wxContractCustomersMapper.selectById(record.getCustomersId(), record.getTenantId()); + customers.setStatus(EnumContractCustomersStatus.FORMUL.getCode()); + customers.setUpdateDate(new Date()); + wxContractCustomersMapper.updateById(customers); + + //把customers写入到wxShopUser + String cusName = castCustomersToShopUsers(customers,record.shopIdsByRentInfo()); + + //如果合同的账单cusName为空的话,则设置为customers name + handleContractBillCusName(record,cusName); + + //EventUtil.publistRentEvent(this, wxRentContract); + //建立账单 + //自定义账单无单价,为能生成账单,设置该值 + if (EnumRentContractType.RENT_BY_CUSTOMIZE.getCode() == record.getType()) { + record.setPrice("0.01"); + } + if (record != null && (record.getReceivePeriod() != null || + (null != record.getAgileType() && record.getAgileType().intValue() == EnumRentAgileType.AGILE.getCode()))) { + //预览账单改为正式,并写入商户id + WxAllBill billRent = new WxAllBill(); + billRent.setRentContractId(id); + billRent.setIsPreview(EnumIsPreview.NO.getCode()); + billRent.updateTenantInfo(record); + wxAllBillMapper.updatePreviewStatus(billRent); +// WxMerchant wxMerchant = new WxMerchant(); +// wxMerchant.setId(record.getMerchantId()); +// wxMerchant.updateTenantInfo(record); + + //商业管理费,营业管理费 + //WxAllBill billRentManage = new WxAllBill(); + //billRentManage.setRentContractId(id); + //billRentManage.setIsPreview(EnumIsPreview.NO.getCode()); + //billRentManage.updateTenantInfo(record); + //wxAllBillMapper.updatePreviewStatus(billRentManage); + + if(new BigDecimal(record.getDeposit()).compareTo(new BigDecimal(0)) > 0) { + //押金 + buildDeposit(record, null, id); + } + //一起建立物业账单 + if (buildProperyBill) { + updatePropertyPreviewBill(record); + } + + //作废合同 + //updateInvalidContract(id); + } + + return new ResultData(Result.SUCCESS, "操作成功"); + } + + public String castCustomersToShopUsers(WxContractCustomers customers,List shopIdList) { + WxShopUsersInfo suiq = new WxShopUsersInfo(); + suiq.updateTenantInfo(customers); + suiq.setPrincipalType(customers.getPrincipalType()); + suiq.setName(customers.getName()); + suiq.setPhone(customers.getPhone()); + List ids = wxShopService.getUserInfoList(suiq); + Long infoId = null; + String cusName = null; + if (null == ids || ids.size() <= 0 ) { + WxShopUsersInfo sui = new WxShopUsersInfo(); + sui.updateTenantInfo(customers); + sui.setPrincipalType(customers.getPrincipalType()); + sui.setName(customers.getName()); + sui.setPhone(customers.getPhone()); + sui.setLegalPerson(customers.getLegalPerson()); + sui.setIdNumber(customers.getIdNumber()); + sui.setSex(customers.getSex()); + sui.setLinkPerson(customers.getLinkPerson()); + sui.setCreateContractCustomerId(customers.getId()); + wxShopService.saveOrUpdateShopUsersInfo(sui); + infoId = sui.getId(); + cusName = customers.getName(); + }else { + infoId = ids.get(0).getId(); + cusName = ids.get(0).getName(); + } + + for (int i = 0 ; i < shopIdList.size(); i++) { + Long shopId = shopIdList.get(i); + //查询这个infoId是不是当前的租户 + WxShopUsers suq = new WxShopUsers(); + suq.updateTenantInfo(customers); + suq.setShopId(shopId); + suq.setInfoId(infoId); + suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); + List ulist = wxShopService.getShopUsersList(suq); + if (null != ulist && ulist.size() > 0 ) { + //WxShopUsers su = ulist.get(0); + }else { + //先把当前的租户变更掉 + wxShopService.updateRentShopUsersOld(customers,shopId); + //新增租户 + WxShopUsers su = new WxShopUsers(); + su.updateTenantInfo(customers); + su.setShopId(shopId); + su.setInfoId(infoId); + su.setType(EnumShopUsersType.RENTER.getCode()); + su.setStatus(EnumShopUsersStatus.LIVE.getCode()); + wxShopService.saveOrUpdateShopUsers(su); + } + } + return cusName; + } + + public void handleContractBillCusName(WxRentContract record,String cusName) { + WxAllBill bill = new WxAllBill(); + bill.updateTenantInfo(record); + bill.setCusName(cusName); + bill.setRentContractId(record.getId()); + wxAllBillMapper.updateContractCusName(bill); + } + + @Override + public void updatePropertyPreviewBill(WxRentContract record) { + //合并合同-更新物业账单 + if (record.getOperationType().equals(EnumContractOperationType.WHOLE.getCode())) { + //查签约 + WxPropertyContract wxPropertyContract = new WxPropertyContract(); + wxPropertyContract.setRentContractId(record.getId()); + WxPropertyContract propertyContract = wxPropertyContractMapper.selectOne(new QueryWrapper(wxPropertyContract)); + logger.info("物业合同状态及账单状态修改:{}",propertyContract); + if (propertyContract != null) { + wxPropertyContractService.updatePropertyContractStatus(propertyContract.getId()); + } + } + } + + @Override + public void updateApplyStatus(WxRentContract wxRentContract) { + wxRentContractMapper.updateApplyStatus(wxRentContract); + } + +// @Override +// public Integer getShopType(WxRentContract wxRentContract) { +// return wxRentContractMapper.getShopType(wxRentContract); +// } + + //yearList,每年的合同截止日期,到这个截止日之前之后,需要拆开时间 + public static List initBillTimeList(List yearList,Date start,Date end,Integer adjustPeriod,Integer dayType,int receivePeriod,int payPeriod){ + List list = new ArrayList<>(); + int count = 0; + List yearsEndList = new ArrayList(); + yearsEndList.addAll(yearList); + if (yearsEndList.size() > 0) { + yearsEndList.remove(0); + } + BillTimeVo receiveDate = null; + while (true) { + BillTimeVo timeVo = new BillTimeVo(); + + //账单日 + Calendar instance = Calendar.getInstance(); + instance.setTime(start); + instance.set(Calendar.MILLISECOND, 0); + //开始时间 + timeVo.setStartDate(instance.getTime()); + + //结束时间 + instance.clear(); + instance.setTime(start); + instance.set(Calendar.MILLISECOND, 0); + instance = EnumContractReceivePeriodUnit.getAfterCalendarDay(instance, receivePeriod, dayType); + //instance.add(dayType, receivePeriod); + //instance.add(Calendar.DATE, -1); + timeVo.setEndDate(instance.getTime()); + + //自然月,应该是从本月开始到本月结束 + if(adjustPeriod.equals(EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode())){ + timeVo.setEndDate(EnumContractReceivePeriodUnit.getAfterCalendarNarDay(timeVo.getStartDate(), receivePeriod, dayType)); + } + + //如果是到了每年的截止时间,第一年忽略(是开始时间) + boolean isYearCut = false;//是不是有截断 + if (null != yearsEndList && yearsEndList.size() > 0 ) { + Date yearEndDateStart = yearsEndList.get(0); + //如果开始时间到了年的截止 + if (timeVo.getStartDate().equals(yearEndDateStart)) { + yearsEndList.remove(yearEndDateStart); + }else if (timeVo.getStartDate().after(yearEndDateStart)) { + //do nothing + }else if (timeVo.getStartDate().before(yearEndDateStart)) { + Date yearEndDateEnd = DateUtils.getDayEnd(yearEndDateStart); + if (timeVo.getEndDate().after(yearEndDateEnd)) { + timeVo.setEndDate(DateUtils.getDaySet(yearEndDateEnd,Calendar.DATE,-1)); + yearsEndList.remove(yearEndDateStart); + isYearCut = true; + }else if(timeVo.getEndDate().equals(yearEndDateEnd)) { + yearsEndList.remove(yearEndDateStart); + } + } + } + + if(timeVo.getEndDate().after(end)){ + Calendar endinstance = Calendar.getInstance(); + endinstance.setTime(end); + endinstance.set(Calendar.MILLISECOND, 0); + timeVo.setEndDate(endinstance.getTime()); + } + + list.add(timeVo); + + receiveDate = WxRentContractHelper.getReceiveDate(receiveDate,timeVo.getStartDate(), timeVo.getEndDate(), payPeriod,adjustPeriod,receivePeriod,dayType); + timeVo.setReceiveDate(receiveDate.getStartDate()); + + + //next + start = DateUtils.getDaySet(timeVo.getEndDate(),Calendar.SECOND,1); + + if(start.after(end)) { + break; + } + count ++; + + //预警 + if(count >= 1000){ + Logger logger = LoggerFactory.getLogger(WxRentContractServiceImpl.class); + logger.error("initBillTimeList() warnCount max error !!!"); + break; + } + } + return list; + } + + + @Override + public WxRentContract getByBill(WxAllBill billRent) { + return wxRentContractMapper.getByBill(billRent); + } + + + @Override + public ResultData getContractByContractNumber(WxRentContract rentContract) { + WxRentContract wxRentContract = wxRentContractMapper.selectOne(new QueryWrapper<>(rentContract)); + return new ResultData(wxRentContract); + } + + @Override + public ResultData apply(WxRentContract rentContract,MallUserInfo user) { + //如果存在审批中的合同,不允许提交审批 + WxRentContract wrq = new WxRentContract(); + wrq.updateTenantInfo(user); + List shopIds = rentContract.shopIdsByRentInfo(); + List contractIds = wxAgileContractService.findBuildingFloorContractIds(wrq, null, null, null, shopIds, 0); + if (null != contractIds && contractIds.size() > 0 ) { + wrq.setIds(contractIds); + } + wrq.setStatus(EnumRentContractStatus.PERFORMANCE.getCode()); + List clist = wxRentContractMapper.findList(wrq); + if (null != clist && clist.size() > 0 ) { + return new ResultData(Result.ERROR, "房间资源存在其他审批中的租金合同。请先作完成。"); + } + //如果该合同是租金+物业合同,则还要判断物业合同 + if(rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue()) { + WxPropertyContract wpc = new WxPropertyContract(); + wpc.updateTenantInfo(user); + if (null != contractIds && contractIds.size() > 0 ) { + wpc.setIds(contractIds); + } + wpc.setStatus(EnumRentContractStatus.PERFORMANCE.getCode()); + List plist = wxPropertyContractMapper.findList(wpc); + if (null != plist && plist.size() > 0 ) { + return new ResultData(Result.ERROR, "房间资源存在其他审批中的物业合同。请先作完成。"); + } + } +// Integer count = wxRentContractMapper.getCanApplyCount(rentContract.getId()); +// if (null != count && count.intValue()>0) { +// return new ResultData(Result.ERROR, "当前存在其他草稿状态或者履约驳回的合同。请先作废其他草稿或者审批拒绝或者撤回的合同。"); +// } + + if (CollectionUtils.isEmpty(rentContract.getFlowParams())) { + return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同没有审批流程."); + } + + if ((EnumRentContractStatus.DRAFT.getCode().intValue() == rentContract.getStatus().intValue()) + || (EnumRentContractStatus.PERFORMANCE.getCode().intValue() == rentContract.getStatus().intValue() + && (EnumRentContractAppStatus.REJECT.getCode().intValue() == rentContract.getApplyStatus().intValue() || + EnumRentContractAppStatus.SETBACK.getCode().intValue() == rentContract.getApplyStatus().intValue())) + ) { + Integer bussinessType = (Integer) rentContract.getFlowParams().get("businessType"); + if (null == bussinessType) { + return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同FlowParams错误,未找到businessType."); + } + WxFlowModel flowModle = wxFlowService.getModelByType(bussinessType, rentContract); + if (null == flowModle) { + return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同配置的流程["+String.valueOf(bussinessType)+"]未找到流程模板."); + } + //rentContract.getFlowParams().put("businessId", rentContract.getId().toString()); + wxFlowService.start(rentContract.getFlowParams(), user.getId(), user.getName(), rentContract); + return new ResultData(Result.SUCCESS,"提交审批成功",rentContract); + }else { + return new ResultData(Result.ERROR, "编号["+rentContract.getId()+"]租金合同状态不能提交审批.允许提交的状态为 [草稿],[履约中+审批驳回]"); + } + } + + @Override + @Transactional(rollbackFor = {Exception.class}) + public void renewal(WxRentContract rentContract,WxPropertyContract propertyContract,MallUserInfo user) { + final IdWorker idWorker = IdWorker.get(); + Long newContractId = idWorker.nextId(); + //拷贝 + WxContractShop csq = new WxContractShop(); + csq.updateTenantInfo(rentContract); + csq.setContractId(rentContract.getId()); + List csqlist = wxContractShopMapper.findList(csq); + if (null != csqlist && csqlist.size() > 0 ){ + for ( int i = 0 ; i< csqlist.size() ; i ++) { + WxContractShop cs = csqlist.get(i); + cs.setId(idWorker.nextId()); + cs.setContractId(newContractId); + cs.setCreateDate(new Date()); + cs.setUpdateDate(new Date()); + wxContractShopMapper.insert(cs); + } + } + + //WxContractCustomers ccq = new WxContractCustomers(); + + WxRentContractRevenueJump crjq = new WxRentContractRevenueJump(); + crjq.updateTenantInfo(rentContract); + crjq.setRentContractId(rentContract.getId()); + List jumpList = wxRentContractRevenueJumpMapper.findList(crjq); + if ( null != jumpList && jumpList.size() > 0 ) { + for (int i = 0 ; i < jumpList.size(); i++) { + WxRentContractRevenueJump rj = jumpList.get(i); + rj.setRentContractId(newContractId); + rj.setId(idWorker.nextId()); + rj.setCreateTime(new Date()); + rj.setUpdateTime(new Date()); + wxRentContractRevenueJumpMapper.insert(rj); + } + } + + //WxRentContractFreePeriod cfpq = new WxRentContractFreePeriod(); + + Long oldId = rentContract.getId(); + rentContract.setId(newContractId); + rentContract.setCreatetime(new Date()); + rentContract.setCreateBy(user.getId()); + rentContract.setCreateByName(user.getName()); + rentContract.setUpdatetime(new Date()); + rentContract.setUpdateBy(user.getId()); + rentContract.setUpdateByName(user.getName()); + rentContract.setStatus(EnumRentContractStatus.UNWRITE.getCode()); + rentContract.setApplyStatus(EnumRentContractAppStatus.DEFAULT.getCode()); + rentContract.setEndContractTime(null); + rentContract.setFirstBillDateStart(null); + rentContract.setFirstBillDateEnd(null); + rentContract.setFirstBillReceiveDate(null); + int[] array = DateUtils.getDiff(rentContract.getRentalStartDate(),rentContract.getRentalEndDate()); + rentContract.setLease(array[0]); + //rentContract.setAdjustRatio(); + //rentContract.setRevenueRatioSet(); + //rentContract.set + wxRentContractMapper.insert(rentContract); + + if (rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue() && null != propertyContract) { + propertyContract.setRentalStartDate(rentContract.getRentalStartDate()); + propertyContract.setRentalEndDate(rentContract.getRentalEndDate()); + propertyContract.setSignDate(rentContract.getSignDate()); + propertyContract.setStartDate(rentContract.getStartDate()); + propertyContract.setEndDate(rentContract.getStartDate()); + propertyContract.setRentContractId(newContractId); + wxPropertyContractService.renewal(propertyContract, user,true); + } + } + + @Transactional(rollbackFor = {Exception.class}) + @Override + public void transfer(WxRentContract rentContract,MallUserInfo user) { + this.setCustomers(rentContract); + rentContract.setUpdatetime(new Date()); + rentContract.setUpdateBy(user.getId()); + rentContract.setUpdateByName(user.getName()); + wxRentContractMapper.updateById(rentContract); + + //更新账单归属 + WxAllBill bill = new WxAllBill(); + bill.updateTenantInfo(rentContract); + bill.setRentContractId(rentContract.getId()); + bill.setCusName(rentContract.getCustomerName()); + wxAllBillMapper.transferCusName(bill); + + if (rentContract.getOperationType().intValue() == EnumContractOperationType.WHOLE.getCode().intValue()) { + WxPropertyContract pq = new WxPropertyContract(); + pq.updateTenantInfo(rentContract); + pq.setOperationType(EnumContractOperationType.WHOLE.getCode()); + pq.setRentContractId(rentContract.getId()); + List pclist = wxPropertyContractService.findList(pq); + if (null != pclist && pclist.size() > 0 ) { + WxPropertyContract propertyContract = pclist.get(0); + wxPropertyContractService.transfer(propertyContract, user); + } + } + } + + @Override + public void outDateContract(WxMall wxMall) { + try { + //查询商户下计租到期的合同,更新合同状态 + WxRentContract wrc = new WxRentContract(); + wrc.updateTenantInfo(wxMall); + wrc.setStatus(EnumRentContractStatus.PAING.getCode()); + List contractList = wxRentContractMapper.findList(wrc); + for (WxRentContract contract:contractList) { + if (contract.getRentalEndDate().before(new Date())) { + contract.setStatus(EnumRentContractStatus.OUT_DATE.getCode()); + wxRentContractMapper.updateById(contract); + } + } + }catch(Exception e) { + logger.error("outDateContract error.",e); + } + } + + @Override + public void readyToNomal(WxMall wxMall) { + WxRentContract wr = new WxRentContract(); + wr.setStatus(EnumRentContractStatus.READY_FOR_PAING.getCode()); + wr.updateTenantInfo(wxMall); + List rentList = wxRentContractMapper.findList(wr); + if (null != rentList && rentList.size() > 0 ) { + for (WxRentContract wrc : rentList) { + if (wrc.getRentalStartDate().before(new Date())) { + wrc.setStatus(EnumRentContractStatus.PAING.getCode()); + wxRentContractMapper.updateStatus(wrc); + } + } + } + } + + @Override + public WxRentContract getSimpleDeatil(Long id) { + return wxRentContractMapper.selectById(id); + } + + @Override + public long findCount(WxRentContract wxRentContract) { + TenantEntity tenantEntity = new TenantEntity(); + tenantEntity.setTenantId(wxRentContract.getTenantId()); + tenantEntity.setParentTenantId(wxRentContract.getParentTenantId()); + List tenantEntitys = wxMallService.getTenantEntitys(tenantEntity); + long count = 0l; + for (TenantEntity te:tenantEntitys) { + wxRentContract.updateTenantInfo(te); + count += wxRentContractMapper.findCount(wxRentContract); + } + wxRentContract.updateTenantInfo(tenantEntity); + return count; + } + + @Override + public void setEndContractTime(WxRentContract wxRentContract) { + wxRentContractMapper.setEndContractTime(wxRentContract); + } + + @Override + public List findToEndContractList(WxRentContract record) { + return wxRentContractMapper.findToEndContractList(record); + } + + @Override + public List findToOutDateContracts(TenantEntity tenantEntity) { + WxRentContract wrc = new WxRentContract(); + wrc.setStatus(EnumRentContractStatus.PAING.getCode()); + wrc.setOutDateNofity(1); + return wxRentContractMapper.findList(wrc); + } + + @Override + public void calcuteByTradeDaily(WxRentContract wxRentContract) { + } + + private BigDecimal sumTradeDailyBySameMonthDay(Integer decimalSize,TenantEntity tenantEntity,Long merchantId,Date begin ,Date end) { + //如果有按月的,则取按月来算 + WxMerchantTradeDaily tdq = new WxMerchantTradeDaily(); + tdq.updateTenantInfo(tenantEntity); + tdq.setMerchantId(merchantId); + tdq.setDateType(EnumTradeDailyDateType.MONTH.getCode()); + tdq.setReportDate(DateUtils.date2String(begin, DateUtils.DATE_PATTERN_MONTH)); + List monthList = wxMerchantTradeDailyMapper.findList(tdq); + if (null != monthList && monthList.size() > 0 ){ + int monthSums = monthList.get(0).getTradeAmtInteger(); + Date _fistDay = DateUtils.getDayBegin(DateUtils.getFirstDayForCurrMonth(begin)); + Date _lastDay = DateUtils.getLastDayForMonth(begin); + if (begin.equals(_fistDay) && end.equals(_lastDay)) { + //满月 + return new BigDecimal(monthSums); + }else { + //根据天数计算 + int monthDays = DateUtils.daysBetween(_fistDay, _lastDay)+1; + int _days = DateUtils.daysBetween(begin, end)+1; + if (_days == 0) { + _days = 1;//当天 + } + BigDecimal servicePay = new BigDecimal(monthSums).multiply(new BigDecimal(_days)).divide(new BigDecimal(monthDays), decimalSize, BigDecimal.ROUND_HALF_UP); + return servicePay; + } + }else { + WxMerchantTradeDaily tdq1 = new WxMerchantTradeDaily(); + tdq1.updateTenantInfo(tenantEntity); + tdq1.setMerchantId(merchantId); + tdq1.setDateType(EnumTradeDailyDateType.DAY.getCode()); + tdq1.setStartTime(DateUtils.format(begin)); + tdq1.setEndTime(DateUtils.format(end)); + String sumMoney = wxMerchantTradeDailyMapper.findSumMoney(tdq1); + return new BigDecimal(sumMoney); + } + } + + @Override + public void deletePrewBill(WxRentContract record) { + //删除预账单,重新生成 + wxAllBillMapper.deleteBillByContract(record); + //删除商业管理费账单 + //WxAllBill wxBillRentManage = new WxAllBill(); + //wxBillRentManage.setRentContractId(record.getId()); + //wxBillRentManage.setManageFeeType(EnumRentContractManageFeeType.RENT_BUSSINESS_MANAGE_FEE.getCode()); + //wxBillRentManage.updateTenantInfo(record); + //wxAllBillMapper.deletePreviewBill(wxBillRentManage); + //删除营业管理费账单 + //wxBillRentManage.setManageFeeType(EnumRentContractManageFeeType.RENT_OPERATING_MANAGE_FEE.getCode()); + //wxBillRentManageMapper.deletePreviewBill(wxBillRentManage); + } + + @Override + public List getFreePeriods(WxRentContract wxRentContract) { + int[] array = DateUtils.getDiff(wxRentContract.getRentalStartDate(),wxRentContract.getRentalEndDate()); + int months = array[0]; + int years = 0; + if ( months % 12 == 0) { + years = months / 12; + }else { + years = months / 12 + 1; + } + if (years == 0) { + years = 1; + } + Date start = wxRentContract.getRentalStartDate(); + List volist = new ArrayList(); + for (int i = 0 ; i < years; i ++) { + RentContractFreePeriodVo vo = new RentContractFreePeriodVo(); + vo.setYearIndex(i+1); + vo.setStart(start); + if (i == years-1) { + vo.setEnd(wxRentContract.getRentalEndDate()); + }else { + start = DateUtils.getTimeAfterDays(365*(i+1)+1,wxRentContract.getRentalStartDate()); + vo.setEnd(start); + } + WxRentContractFreePeriod fpq = new WxRentContractFreePeriod(); + fpq.updateTenantInfo(wxRentContract); + fpq.setRentContractId(wxRentContract.getId()); + fpq.setYearIndex(i+1); + fpq.setSortColumn("start_date asc"); + vo.setPeriods(wxRentContractFreePeriodMapper.findList(fpq)); + volist.add(vo); + } + return volist; + } + + @Override + public void saveFreePeriods(WxRentContract wxRentContract) { + WxRentContract rentContract = wxRentContractMapper.selectById(wxRentContract.getId()); + List yearsVo = getRentContractYears(rentContract); + if (null == yearsVo) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"无缴费年限"); + } + Map yearsMap = new HashMap(); + for (int i = 0 ; i < yearsVo.size() ; i++) { + WxRentContractYearsVo vo = yearsVo.get(i); + yearsMap.put(vo.getYearIndex(), vo); + } + + WxRentContractFreePeriod del = new WxRentContractFreePeriod(); + del.updateTenantInfo(wxRentContract); del.setRentContractId(wxRentContract.getId()); - wxRentContractFreePeriodMapper.deleteByContract(del); - List volist = wxRentContract.getFreePeriods(); - if (null != volist && volist.size() > 0 ) { - List fpList = new ArrayList(); - for (int i = 0 ; i < volist.size() ; i ++) { - RentContractFreePeriodVo vo = volist.get(i); - if (null != vo.getPeriods()) { - for (int j = 0 ; j < vo.getPeriods().size(); j++ ){ - WxRentContractFreePeriod fp = vo.getPeriods().get(j); - WxRentContractYearsVo yearVo = yearsMap.get(vo.getYearIndex()); - if ((fp.getStartDate().after(yearVo.getStart()) || fp.getStartDate().equals(yearVo.getStart()) ) && - (fp.getEndDate().before(yearVo.getEnd()) || fp.getEndDate().equals(yearVo.getEnd()))) { - final IdWorker idWorker = IdWorker.get(); - fp.setId(idWorker.nextId()); - fp.updateTenantInfo(wxRentContract); - fp.setYearIndex(vo.getYearIndex()); - fp.setCreateTime(new Date()); - fp.setUpdateTime(new Date()); - fp.setRentContractId(rentContract.getId()); - fpList.add(fp); - }else { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"第"+vo.getYearIndex()+"年度有时间选择有误,不能超过该年度时间范围"); - } - } - } - } - wxRentContractFreePeriodMapper.inertPeriods(wxRentContract.getTenantId(), fpList); - } - } - - @Override - public List getRentContractYears(WxRentContract rentContract) { - //String adjustRatio = rentContract.getAdjustRatio(); - //List integers = JSONArray.parseArray(adjustRatio, String.class); - //integers.add(0, "0"); - //int years = integers.size(); - SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); - int [] diffs = DateUtils.getDiff(rentContract.getRentalStartDate(),rentContract.getRentalEndDate()); - int months = diffs[0]; - int days = diffs[1]; - int ext = months % 12; - int years = months/12; - if (ext > 0 ) { - years = years + 1; - }else { - if (days > 0 ) { - years = years + 1; - } - } - //合同以什么日期来计算开始计租日期 - if(rentContract.getRentStartType()!=null &&rentContract.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){ - rentContract.setRentalStartDate(rentContract.getStartDate()); - } - //如果有撤铺日 - Date endcontract = rentContract.getEndContractTime(); - if (null != endcontract) { - endcontract = DateUtils.getDayEnd(endcontract); - } - List yearList = this.getYearList(years, 12, rentContract.getRentalStartDate(),endcontract); - List retList = new ArrayList(); - if (null != yearList && yearList.size() > 0) { - if (yearList.size() == 1) { - WxRentContractYearsVo vo = new WxRentContractYearsVo(); - vo.setStart(yearList.get(0)); - vo.setEnd(rentContract.getRentalEndDate()); - vo.setRemark("第1年度"); - vo.setYearIndex(1); - retList.add(vo); - }else { - Date begin = null; - for (int i = 0 ; i < yearList.size()-1 ; i ++) { - int yearindex = i+1; - begin = yearList.get(i); - Date end = yearList.get(i+1); - Date realEnd = DateUtils.getDaySet(end, Calendar.SECOND, -1); - WxRentContractYearsVo vo = new WxRentContractYearsVo(); - vo.setStart(begin); - vo.setEnd(realEnd); - vo.setRemark("第"+yearindex+"年度"); - vo.setYearIndex(yearindex); - retList.add(vo); - begin = end; - } - WxRentContractYearsVo vo = new WxRentContractYearsVo(); - vo.setStart(yearList.get(yearList.size()-1)); - vo.setEnd(rentContract.getRentalEndDate()); - vo.setRemark("第"+yearList.size()+"年度"); - vo.setYearIndex(yearList.size()); - retList.add(vo); - } - } - if (retList.size() > 0 ) { - return retList; - } - return null; - } - - @Override - public List getContractSales(WxRentContract wxRentContract) { - WxRentContractRevenueSales sales = new WxRentContractRevenueSales(); - sales.updateTenantInfo(wxRentContract); - sales.setRentContractId(wxRentContract.getId()); - if (null != wxRentContract.getYearsBegin() && null != wxRentContract.getYearsEnd()) { - sales.setStarttime(wxRentContract.getYearsBegin()); - sales.setEndtime(wxRentContract.getYearsEnd()); - } - if (null != wxRentContract.getBillStartTime() && null != wxRentContract.getBillEndTime()) { - sales.setStarttimeEqual(wxRentContract.getBillStartTime()); - sales.setEndtimeEqual(wxRentContract.getBillEndTime()); - } - return wxRentContractRevenueSalesMapper.findList(sales); - } - - private BigDecimal calcuteUnitPrice(Date startDate,Date endDate,BigDecimal salesDeciaml,Integer priceUnit, - Integer dayPriceCalcute,Integer mothAverageDays,Integer adjustPeriod,Integer receivePeriodUnit) { - BigDecimal unitPrice = new BigDecimal(0); - - Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); - int[] diffs = DateUtils.getDiff(startDate, realEndStart); - if (priceUnit.equals(EnumPriceUnit.D.getCode())){ - int allDays = 0; - if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - allDays = diffs[0]*mothAverageDays + diffs[1]; - }else { - allDays = DateUtils.daysBetween(startDate, endDate)+1; - } - //每一天的单价 - unitPrice = salesDeciaml.divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else if(EnumPriceUnit.Y.getCode().equals(priceUnit)) { - //按照当前金额,当前时间区间,计算每一年的单价 - //当前时间有多少个月 - int months = diffs[0]; - int lastdays = diffs[1]; - if (lastdays > 0) { - //计算当前区间算多少年 - if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - Date lastmonthStartDate = DateUtils.getTimeAfterMonths(diffs[0], startDate); - int days = DateUtils.daysBetween(lastmonthStartDate, endDate)+1; - BigDecimal _months = new BigDecimal(days).divide(new BigDecimal(mothAverageDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).add(new BigDecimal(months)); - unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(_months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else { - BigDecimal _months = getMonthsByRealDays(months,startDate,endDate,adjustPeriod,receivePeriodUnit); - unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(_months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - }else { - unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(new BigDecimal(months),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - }else if(EnumPriceUnit.M.getCode().equals(priceUnit)) { - //每一月的单价 - BigDecimal months = new BigDecimal(diffs[0]); - int lastdays = diffs[1]; - if (lastdays > 0) { - if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - Date lastmonthStartDate = DateUtils.getTimeAfterMonths(diffs[0], startDate); - int days = DateUtils.daysBetween(lastmonthStartDate, endDate)+1; - months = months.add(new BigDecimal(days).divide(new BigDecimal(mothAverageDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - }else { - months = getMonthsByRealDays(diffs[0],startDate,endDate,adjustPeriod,receivePeriodUnit); - } - } - unitPrice = salesDeciaml.divide(months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - return unitPrice; - } - - private BigDecimal getMonthsByRealDays(int months,Date startDate,Date endDate,Integer adjustPeriod,Integer receivePeriodUnit) { - BigDecimal _months = new BigDecimal(0); - //如果是自然月或者自然季度,则是到月底 - if (adjustPeriod == EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode() || - receivePeriodUnit == EnumContractReceivePeriodUnit.QUARTER.getCode()) { - //需要查询到真实的自然月份有多少 - Date startFirstDay = DateUtils.getFirstDayForCurrMonth(startDate); - Date endLastStartDay = DateUtils.getLastDayForMonth(endDate); - int[] rdiffs = DateUtils.getDiff(startFirstDay, endLastStartDay); - int rmonths = rdiffs[0]; - if (rmonths > 0 ) { - //第一个个月是start到月底,最后一个是1号到end - Date startLastDay = DateUtils.getLastDayForMonth(startDate); - int firstdays = DateUtils.daysBetween(startDate, startLastDay)+1; - int firstmonthdays = DateUtils.daysBetween(startFirstDay, startLastDay)+1; - _months = _months.add(new BigDecimal(firstdays).divide(new BigDecimal(firstmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - if (rmonths == 1) { - Date endFirstDay = DateUtils.getDaySet(startLastDay, Calendar.SECOND, 1); - int enddays = DateUtils.daysBetween(endFirstDay, endDate)+1; - Date endlastday = DateUtils.getLastDayForMonth(endDate); - int endmonthdays = DateUtils.daysBetween(endFirstDay, endlastday)+1; - _months = _months.add(new BigDecimal(enddays).divide(new BigDecimal(endmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - }else { - _months = _months.add(new BigDecimal(rmonths-1)); - Date endFirstDay = DateUtils.getDaySet(DateUtils.getDaySet(startLastDay, Calendar.MONTH, rmonths-1), Calendar.SECOND, 1); - int enddays = DateUtils.daysBetween(endFirstDay, endDate)+1; - Date endlastday = DateUtils.getLastDayForMonth(endDate); - int endmonthdays = DateUtils.daysBetween(endFirstDay, endlastday)+1; - _months = _months.add(new BigDecimal(enddays).divide(new BigDecimal(endmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - } - }else { - //相当于在同一个月份 - int days = DateUtils.daysBetween(startDate, endDate)+1; - Date startLastDay = DateUtils.getLastDayForMonth(startDate); - int monthdays = DateUtils.daysBetween(startDate, startLastDay)+1; - _months = _months.add(new BigDecimal(days).divide(new BigDecimal(monthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - } - }else { - _months = _months.add(new BigDecimal(months)); - Date prelastMonthStartDate = DateUtils.getDaySet(startDate, Calendar.MONTH, months); - Date extraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(prelastMonthStartDate); - Date extraStartDayMonthEnd = DateUtils.getLastDayForMonth(prelastMonthStartDate); - int premonthDays = DateUtils.daysBetween(extraStartDayMonthStart, extraStartDayMonthEnd)+1; - int prelastdays = 0; - if (extraStartDayMonthEnd.after(endDate) || extraStartDayMonthEnd.equals(endDate)) { - prelastdays = DateUtils.daysBetween(prelastMonthStartDate, endDate)+1; - _months = _months.add(new BigDecimal(prelastdays).divide(new BigDecimal(premonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - }else { - prelastdays = DateUtils.daysBetween(prelastMonthStartDate, extraStartDayMonthEnd)+1; - _months = _months.add(new BigDecimal(prelastdays).divide(new BigDecimal(premonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - //跨月 - Date lastMonthStart = DateUtils.getDaySet(extraStartDayMonthEnd, Calendar.SECOND, 1); - int lastdays = DateUtils.daysBetween(lastMonthStart, endDate)+1; - Date lastextraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(lastMonthStart); - Date lastextraStartDayMonthEnd = DateUtils.getLastDayForMonth(lastMonthStart); - int lastmonthDays = DateUtils.daysBetween(lastextraStartDayMonthStart, lastextraStartDayMonthEnd)+1; - _months = _months.add(new BigDecimal(lastdays).divide(new BigDecimal(lastmonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - } - } - return _months; - } - - //根据租金合同来计算附加物业费 - private BigDecimal calcuteRentPropertyPrice(WxRentContract rentcontract,WxPropertyContract propertyContract,Date startDate,Date endDate,BigDecimal money) { - //计算物业费的单价 - BigDecimal unitPropertyPrice = calcuteUnitPrice(startDate, endDate,money, - propertyContract.getPriceUnit(),propertyContract.getDayPriceCalcute(),propertyContract.getMonthAverageDays(),propertyContract.getAdjustPeriod(),propertyContract.getReceivePeriodUnit()); - //如果租金是按天计算 - if (rentcontract.getPriceUnit().equals(EnumPriceUnit.D.getCode())){ - //物业也是按天 - if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { - return unitPropertyPrice; - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { - if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - return unitPropertyPrice.divide(new BigDecimal(12*propertyContract.getMonthAverageDays()), - Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else { - return unitPropertyPrice.divide(new BigDecimal(365),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { - if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - return unitPropertyPrice.divide(new BigDecimal(propertyContract.getMonthAverageDays()), - Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else { - int allDays = DateUtils.daysBetween(startDate, endDate)+1; - return money.divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - } - }else if (rentcontract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { - if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { - if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - return unitPropertyPrice.multiply(new BigDecimal(12*propertyContract.getMonthAverageDays())); - }else { - return unitPropertyPrice.multiply(new BigDecimal(365)); - } - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { - return unitPropertyPrice; - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { - return unitPropertyPrice.multiply(new BigDecimal(12)); - } - }else if (rentcontract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { - if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { - if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - return unitPropertyPrice.multiply(new BigDecimal(propertyContract.getMonthAverageDays())); - }else { - //此处就无法计算月了。 - //计算月份值。 - Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); - int[] diffs = DateUtils.getDiff(startDate, realEndStart); - BigDecimal months = new BigDecimal(diffs[0]); - Date preextraStartDay = DateUtils.getTimeAfterMonths(diffs[0], startDate); - Date extraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(preextraStartDay); - Date extraStartDayMonthEnd = DateUtils.getLastDayForMonth(preextraStartDay); - int monthDays = DateUtils.daysBetween(extraStartDayMonthStart, extraStartDayMonthEnd)+1; - int predays = DateUtils.daysBetween(preextraStartDay, extraStartDayMonthEnd)+1; - months = months.add(new BigDecimal(predays).divide(new BigDecimal(monthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - //有可能会跨月 - if (extraStartDayMonthEnd.before(endDate)) { - Date lastMonthStart = DateUtils.getDaySet(extraStartDayMonthEnd, Calendar.SECOND, 1); - int lastdays = DateUtils.daysBetween(lastMonthStart, endDate)+1; - Date lastextraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(lastMonthStart); - Date lastextraStartDayMonthEnd = DateUtils.getLastDayForMonth(lastMonthStart); - int lastmonthDays = DateUtils.daysBetween(lastextraStartDayMonthStart, lastextraStartDayMonthEnd)+1; - months = months.add(new BigDecimal(lastdays).divide(new BigDecimal(lastmonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); - } - return unitPropertyPrice.multiply(months); - } - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { - return unitPropertyPrice.divide(new BigDecimal(12),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { - return unitPropertyPrice; - } - } - return unitPropertyPrice; - } - - private BigDecimal[] calcuteReveneuJump(BigDecimal sales,WxRentContract rentcontract,Date startDate,Date endDate,List freePeriods) { - BigDecimal revenueDecimal = new BigDecimal(0); - BigDecimal rentDecimal = new BigDecimal(0); - //根据免租期来计算 - List validDates = WxRentContractHelper.getValidDays(startDate, endDate, freePeriods); - if (null == validDates || validDates.size() <= 0 ) { - BigDecimal[] bs = new BigDecimal[] {revenueDecimal,rentDecimal,new BigDecimal(0)}; - return bs; - } - int allDays = DateUtils.daysBetween(startDate,endDate)+1; - boolean isFull = false; - if (allDays == validDates.size()) { - isFull = true; - } - WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); - jq.updateTenantInfo(rentcontract); - jq.setRentContractId(rentcontract.getId()); - jq.setSortColumn(" minMoney asc"); - List jumpList = wxRentContractRevenueJumpMapper.findList(jq); - if (null != jumpList && jumpList.size() > 0 ) { - //不是满时间段的,要按天来计算 - if (!isFull) { - Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); - int[] diffs = DateUtils.getDiff(startDate, realEndStart); - if (diffs[0] <= 0 || (diffs[0] == 1 && diffs[1] <= 0 )) { - if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(30),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else { - sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - }else { - Date preextraStartDay = DateUtils.getTimeAfterMonths(diffs[0], startDate); - int predays = DateUtils.daysBetween(preextraStartDay, endDate)+1; - if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - BigDecimal days = new BigDecimal(diffs[0]).multiply(new BigDecimal(30)).add(new BigDecimal(predays)); - sales = sales.multiply(new BigDecimal(validDates.size())).divide(days,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - }else { - sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - } - } - } - for (int i = 0 ; i< jumpList.size() ; i ++) { - WxRentContractRevenueJump rj = jumpList.get(i); - String minMoney = rj.getMinMoney(); - String maxMoney = rj.getMaxMoney(); - if (StringUtils.isNotBlank(maxMoney)) { - if (sales.compareTo(new BigDecimal(maxMoney)) <= 0 ) { - revenueDecimal = sales.multiply(new BigDecimal(rj.getRate())).divide(new BigDecimal(100)); - if (StringUtils.isNotBlank(rj.getRentMoney())) { - rentDecimal = new BigDecimal(rj.getRentMoney()); - } - break; - } - }else { - if (sales.compareTo(new BigDecimal(minMoney)) > 0 ) { - revenueDecimal = sales.multiply(new BigDecimal(rj.getRate())).divide(new BigDecimal(100)); - if (StringUtils.isNotBlank(rj.getRentMoney())) { - rentDecimal = new BigDecimal(rj.getRentMoney()); - } - break; - } - } - } - } - //根据时间区间计算 - //固定租金需要再计算,因为跳点设置的租金是单价 - String rentNeedpay = "0"; - if (rentDecimal.compareTo(new BigDecimal(0)) > 0 ) { - rentNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,rentcontract, rentDecimal.toPlainString(),startDate, - endDate,0,0,false,rentcontract.getReceivePeriodUnit(),rentcontract.getReceivePeriod()); - } - rentDecimal = new BigDecimal(rentNeedpay); - BigDecimal[] bs = new BigDecimal[] {revenueDecimal,rentDecimal,sales}; - return bs; - } - - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - @Override - public WxRentContractRevenueSetSalesVo setRevenueSales(MallUserInfo user,WxRentContract rentcontract, String sales, Date startime, Date endtime, Long propertyContractId) { - //如果账单存在缴费,付款,减免,冲抵,等情况,则不允许。 - WxAllBill bq = wxBillAllHelper.generateRentContractQueryBill(rentcontract, rentcontract.getId(),startime,endtime); - List rentBillList = wxAllBillMapper.findList(bq); - if (null == rentBillList || rentBillList.size() <= 0 ) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"未查询到账单"); - } - for (int i = 0 ; i < rentBillList.size() ; i ++) { - WxAllBill rentBill = rentBillList.get(i); - if ((StringUtils.isNotBlank(rentBill.getPay()) && new BigDecimal(rentBill.getPay()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(rentBill.getSetOff()) && new BigDecimal(rentBill.getSetOff()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(rentBill.getReturnPay()) && new BigDecimal(rentBill.getReturnPay()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(rentBill.getUseMoney()) && new BigDecimal(rentBill.getUseMoney()).compareTo(new BigDecimal(0)) > 0 ) ) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"租金账单存在已经已经缴费或付款,扣减,减免,冲抵的情况,不允许操作"); - } - } - - BigDecimal salesDeciaml = new BigDecimal(sales); - - //删除自动创建的账单 - WxAllBill billDel = new WxAllBill(); - billDel.updateTenantInfo(rentcontract); - billDel.setRentContractId(rentcontract.getId()); - billDel.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_REVENUE_SALES.getCode()); - billDel.setStarttimeEqual(startime); - wxAllBillMapper.deleteByRentReveneuSales(billDel); - - //上面删除掉生成的账单之后,再重新查询,只剩下主账单 - rentBillList = wxAllBillMapper.findList(bq); - - //加上物业 - List propertyBillList = null; - BigDecimal propertyPrice = new BigDecimal(0); - WxPropertyContract propertyContract = null; - if (null != propertyContractId) { - WxAllBill propertyBillq = new WxAllBill(); - propertyBillq.updateTenantInfo(rentcontract); - propertyBillq.setPropertyContractId(propertyContractId); - propertyBillq.setBillType(EnumBillAllType.PROPERTY.getCode()); - propertyBillq.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); - propertyBillq.setIsPreview(EnumYesOrNo.NO.getCode()); - propertyBillq.setNoExtraCreateFrom(EnumYesOrNo.YES.getCode()); - propertyBillq.setStarttimeEqual(startime); - propertyBillq.setEndtimeEqual(endtime); - propertyBillList = wxAllBillMapper.findList(propertyBillq); - for (int i = 0 ; i < propertyBillList.size() ; i ++) { - WxAllBill propertyBill = propertyBillList.get(i); - if ((StringUtils.isNotBlank(propertyBill.getPay()) && new BigDecimal(propertyBill.getPay()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(propertyBill.getSetOff()) && new BigDecimal(propertyBill.getSetOff()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(propertyBill.getReturnPay()) && new BigDecimal(propertyBill.getReturnPay()).compareTo(new BigDecimal(0)) > 0 ) - || (StringUtils.isNotBlank(propertyBill.getUseMoney()) && new BigDecimal(propertyBill.getUseMoney()).compareTo(new BigDecimal(0)) > 0 ) ) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"物业账单存在已经已经缴费或付款,扣减,减免,冲抵的情况,不允许操作"); - } - } - } - - //根据销售额来计算平均每计费周期营业额,相当于设置联营扣点保底营业额 - BigDecimal unitRevenuePrice = calcuteUnitPrice(startime, endtime,salesDeciaml, - rentcontract.getPriceUnit(),rentcontract.getDayPriceCalcute(),rentcontract.getMonthAverageDays(),rentcontract.getAdjustPeriod(),rentcontract.getReceivePeriodUnit()); - //设置保底营业额 - rentcontract.setRevenue(unitRevenuePrice.toPlainString()); - //联营扣点 - if (rentcontract.getType().equals(EnumRentContractType.RENT_BY_JOINT.getCode())) { - rentcontract.setPrice(new BigDecimal(rentcontract.getPayRatio()).multiply(unitRevenuePrice).divide(new BigDecimal(100), - Constant.default_long_decimal_size,RoundingMode.HALF_UP).toPlainString()); - }else if (rentcontract.getType().intValue() == EnumRentContractType.RENT_BY_AREA_AND_JOINT.getCode()) { - //取高才能加上物业费 - if (null != propertyContractId && null != propertyBillList) { - propertyContract = wxPropertyContractMapper.selectById(propertyContractId); - //有可能物业的单价时间跟租金的不一致,需要根据物业的单价重新计算 - //propertyPrice = calcuteRentPropertyPrice(rentcontract, propertyContract, rentBill.getStarttime(), rentBill.getEndtime(), - //new BigDecimal(propertyBill.getNeedPay())); - } - } - //计算每一年的基数 - List priceArrs = WxRentContractHelper.calcuteRentAndRevenuePrice(rentcontract); - String[] rentPriceArrs = priceArrs.get(0); - String[] revenuePriceArrs = priceArrs.get(1); - //计算商业管理费 - String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(rentcontract); - //计算运营管理费 - String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(rentcontract); - - //物业费单价 - String[] propertyContractArrs = null; - if (null != propertyContract) { - propertyContractArrs = WxRentContractHelper.calcutePropertyPrice(propertyContract); - } - List yearList = this.getYearList(rentPriceArrs.length, 12, rentcontract.getRentalStartDate(),null); - int yearIndex = 0; - for( int i = 0 ; i < yearList.size() ; i ++) { - Date yearStartDate = yearList.get(i); - Date yearEndDate = DateUtils.getTimeAfterMonths(12, yearStartDate); - if (startime.equals(yearStartDate) || - (startime.after(yearStartDate) && (endtime.before(yearEndDate) || endtime.equals(yearEndDate)) )) { - yearIndex = i; - break; - } - } - if (yearIndex <= 0 ) { - yearIndex = 0; - } - - //租金+营业管理费+商业管理费+物业 和扣点相比取高。 - BigDecimal rentTotal = new BigDecimal(rentPriceArrs[yearIndex]); - if (null != bussinessManagerPriceArrs) { - rentTotal = rentTotal.add(new BigDecimal(bussinessManagerPriceArrs[yearIndex])); - } - if (null != operationManagerPriceArrs) { - rentTotal = rentTotal.add(new BigDecimal(operationManagerPriceArrs[yearIndex])); - } - //此处需要物业合同合租金合同的计费周期一致,严谨的需要用到上面计算的propertyPrice - if (null != propertyContractArrs) { - rentTotal = rentTotal.add(new BigDecimal(propertyContractArrs[yearIndex])); - } - - //跟扣点相比较 - BigDecimal priceDecimal = rentTotal; - if (null != revenuePriceArrs && null != revenuePriceArrs[yearIndex]) { - BigDecimal revenuePrice = new BigDecimal(revenuePriceArrs[yearIndex]); - if (revenuePrice.compareTo(rentTotal) > 0 ) { - priceDecimal = revenuePrice; - } - } - - //免租期 - List freePeriods = getFreeDays(rentcontract); - - //根据扣点规则和租赁相关费用取高来计算费用 - String needpay = WxRentContractHelper.getNeedPayMoney(freePeriods,rentcontract, priceDecimal.toPlainString(),startime, - endtime,0,0,false,rentcontract.getReceivePeriodUnit(),rentcontract.getReceivePeriod()); - - //计算跳点。 - BigDecimal[] jumppays = calcuteReveneuJump(salesDeciaml, rentcontract,startime, endtime,freePeriods); - BigDecimal jumpRevenuePay = jumppays[0]; - BigDecimal jumpRentPay = jumppays[1]; - BigDecimal saleDecimalValid = jumppays[2]; - BigDecimal jumppay = new BigDecimal(0); - if (jumpRevenuePay.compareTo(jumpRentPay) > 0 ) { - jumppay = jumppay.add(jumpRevenuePay); - }else { - jumppay = jumppay.add(jumpRentPay); - } - StringBuffer sb = new StringBuffer("有效销售额:"+saleDecimalValid.toPlainString()+","); - if (jumppay.compareTo(new BigDecimal(needpay)) > 0 ) { - sb.append("跳点规则计算金额:"+jumppay.toPlainString()+",合同租金扣点规则计算金额:"+needpay+"."); - needpay = jumppay.toPlainString(); - }else { - sb.append("跳点规则计算金额:"+jumppay.toPlainString()+",合同租金扣点规则计算金额:"+needpay+"."); - } - sb.append("取高后总金额为:["+needpay+"]."); - //保存销售额 - WxRentContractRevenueSales rs = new WxRentContractRevenueSales(); - rs.updateTenantInfo(rentcontract); - rs.setRentContractId(rentcontract.getId()); - rs.setStarttimeEqual(startime); - rs.setEndtimeEqual(endtime); - List saleList = wxRentContractRevenueSalesMapper.findList(rs); - if (null != saleList && saleList.size() > 0 ) { WxRentContractRevenueSales sale = saleList.get(0); + wxRentContractFreePeriodMapper.deleteByContract(del); + List volist = wxRentContract.getFreePeriods(); + if (null != volist && volist.size() > 0 ) { + List fpList = new ArrayList(); + for (int i = 0 ; i < volist.size() ; i ++) { + RentContractFreePeriodVo vo = volist.get(i); + if (null != vo.getPeriods()) { + for (int j = 0 ; j < vo.getPeriods().size(); j++ ){ + WxRentContractFreePeriod fp = vo.getPeriods().get(j); + WxRentContractYearsVo yearVo = yearsMap.get(vo.getYearIndex()); + if ((fp.getStartDate().after(yearVo.getStart()) || fp.getStartDate().equals(yearVo.getStart()) ) && + (fp.getEndDate().before(yearVo.getEnd()) || fp.getEndDate().equals(yearVo.getEnd()))) { + final IdWorker idWorker = IdWorker.get(); + fp.setId(idWorker.nextId()); + fp.updateTenantInfo(wxRentContract); + fp.setYearIndex(vo.getYearIndex()); + fp.setCreateTime(new Date()); + fp.setUpdateTime(new Date()); + fp.setRentContractId(rentContract.getId()); + fpList.add(fp); + }else { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"第"+vo.getYearIndex()+"年度有时间选择有误,不能超过该年度时间范围"); + } + } + } + } + wxRentContractFreePeriodMapper.inertPeriods(wxRentContract.getTenantId(), fpList); + } + } + + @Override + public List getRentContractYears(WxRentContract rentContract) { + //String adjustRatio = rentContract.getAdjustRatio(); + //List integers = JSONArray.parseArray(adjustRatio, String.class); + //integers.add(0, "0"); + //int years = integers.size(); + SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); + int [] diffs = DateUtils.getDiff(rentContract.getRentalStartDate(),rentContract.getRentalEndDate()); + int months = diffs[0]; + int days = diffs[1]; + int ext = months % 12; + int years = months/12; + if (ext > 0 ) { + years = years + 1; + }else { + if (days > 0 ) { + years = years + 1; + } + } + //合同以什么日期来计算开始计租日期 + if(rentContract.getRentStartType()!=null &&rentContract.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){ + rentContract.setRentalStartDate(rentContract.getStartDate()); + } + //如果有撤铺日 + Date endcontract = rentContract.getEndContractTime(); + if (null != endcontract) { + endcontract = DateUtils.getDayEnd(endcontract); + } + List yearList = this.getYearList(years, 12, rentContract.getRentalStartDate(),endcontract); + List retList = new ArrayList(); + if (null != yearList && yearList.size() > 0) { + if (yearList.size() == 1) { + WxRentContractYearsVo vo = new WxRentContractYearsVo(); + vo.setStart(yearList.get(0)); + vo.setEnd(rentContract.getRentalEndDate()); + vo.setRemark("第1年度"); + vo.setYearIndex(1); + retList.add(vo); + }else { + Date begin = null; + for (int i = 0 ; i < yearList.size()-1 ; i ++) { + int yearindex = i+1; + begin = yearList.get(i); + Date end = yearList.get(i+1); + Date realEnd = DateUtils.getDaySet(end, Calendar.SECOND, -1); + WxRentContractYearsVo vo = new WxRentContractYearsVo(); + vo.setStart(begin); + vo.setEnd(realEnd); + vo.setRemark("第"+yearindex+"年度"); + vo.setYearIndex(yearindex); + retList.add(vo); + begin = end; + } + WxRentContractYearsVo vo = new WxRentContractYearsVo(); + vo.setStart(yearList.get(yearList.size()-1)); + vo.setEnd(rentContract.getRentalEndDate()); + vo.setRemark("第"+yearList.size()+"年度"); + vo.setYearIndex(yearList.size()); + retList.add(vo); + } + } + if (retList.size() > 0 ) { + return retList; + } + return null; + } + + @Override + public List getContractSales(WxRentContract wxRentContract) { + WxRentContractRevenueSales sales = new WxRentContractRevenueSales(); + sales.updateTenantInfo(wxRentContract); + sales.setRentContractId(wxRentContract.getId()); + if (null != wxRentContract.getYearsBegin() && null != wxRentContract.getYearsEnd()) { + sales.setStarttime(wxRentContract.getYearsBegin()); + sales.setEndtime(wxRentContract.getYearsEnd()); + } + if (null != wxRentContract.getBillStartTime() && null != wxRentContract.getBillEndTime()) { + sales.setStarttimeEqual(wxRentContract.getBillStartTime()); + sales.setEndtimeEqual(wxRentContract.getBillEndTime()); + } + return wxRentContractRevenueSalesMapper.findList(sales); + } + + private BigDecimal calcuteUnitPrice(Date startDate,Date endDate,BigDecimal salesDeciaml,Integer priceUnit, + Integer dayPriceCalcute,Integer mothAverageDays,Integer adjustPeriod,Integer receivePeriodUnit) { + BigDecimal unitPrice = new BigDecimal(0); + + Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); + int[] diffs = DateUtils.getDiff(startDate, realEndStart); + if (priceUnit.equals(EnumPriceUnit.D.getCode())){ + int allDays = 0; + if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + allDays = diffs[0]*mothAverageDays + diffs[1]; + }else { + allDays = DateUtils.daysBetween(startDate, endDate)+1; + } + //每一天的单价 + unitPrice = salesDeciaml.divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else if(EnumPriceUnit.Y.getCode().equals(priceUnit)) { + //按照当前金额,当前时间区间,计算每一年的单价 + //当前时间有多少个月 + int months = diffs[0]; + int lastdays = diffs[1]; + if (lastdays > 0) { + //计算当前区间算多少年 + if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + Date lastmonthStartDate = DateUtils.getTimeAfterMonths(diffs[0], startDate); + int days = DateUtils.daysBetween(lastmonthStartDate, endDate)+1; + BigDecimal _months = new BigDecimal(days).divide(new BigDecimal(mothAverageDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).add(new BigDecimal(months)); + unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(_months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else { + BigDecimal _months = getMonthsByRealDays(months,startDate,endDate,adjustPeriod,receivePeriodUnit); + unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(_months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + }else { + unitPrice = salesDeciaml.multiply(new BigDecimal(12)).divide(new BigDecimal(months),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + }else if(EnumPriceUnit.M.getCode().equals(priceUnit)) { + //每一月的单价 + BigDecimal months = new BigDecimal(diffs[0]); + int lastdays = diffs[1]; + if (lastdays > 0) { + if (dayPriceCalcute.intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + Date lastmonthStartDate = DateUtils.getTimeAfterMonths(diffs[0], startDate); + int days = DateUtils.daysBetween(lastmonthStartDate, endDate)+1; + months = months.add(new BigDecimal(days).divide(new BigDecimal(mothAverageDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + }else { + months = getMonthsByRealDays(diffs[0],startDate,endDate,adjustPeriod,receivePeriodUnit); + } + } + unitPrice = salesDeciaml.divide(months,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + return unitPrice; + } + + private BigDecimal getMonthsByRealDays(int months,Date startDate,Date endDate,Integer adjustPeriod,Integer receivePeriodUnit) { + BigDecimal _months = new BigDecimal(0); + //如果是自然月或者自然季度,则是到月底 + if (adjustPeriod == EnumRentContractAdjustPeriod.ADJUST_PERIOD_NAR_MONTH.getCode() || + receivePeriodUnit == EnumContractReceivePeriodUnit.QUARTER.getCode()) { + //需要查询到真实的自然月份有多少 + Date startFirstDay = DateUtils.getFirstDayForCurrMonth(startDate); + Date endLastStartDay = DateUtils.getLastDayForMonth(endDate); + int[] rdiffs = DateUtils.getDiff(startFirstDay, endLastStartDay); + int rmonths = rdiffs[0]; + if (rmonths > 0 ) { + //第一个个月是start到月底,最后一个是1号到end + Date startLastDay = DateUtils.getLastDayForMonth(startDate); + int firstdays = DateUtils.daysBetween(startDate, startLastDay)+1; + int firstmonthdays = DateUtils.daysBetween(startFirstDay, startLastDay)+1; + _months = _months.add(new BigDecimal(firstdays).divide(new BigDecimal(firstmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + if (rmonths == 1) { + Date endFirstDay = DateUtils.getDaySet(startLastDay, Calendar.SECOND, 1); + int enddays = DateUtils.daysBetween(endFirstDay, endDate)+1; + Date endlastday = DateUtils.getLastDayForMonth(endDate); + int endmonthdays = DateUtils.daysBetween(endFirstDay, endlastday)+1; + _months = _months.add(new BigDecimal(enddays).divide(new BigDecimal(endmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + }else { + _months = _months.add(new BigDecimal(rmonths-1)); + Date endFirstDay = DateUtils.getDaySet(DateUtils.getDaySet(startLastDay, Calendar.MONTH, rmonths-1), Calendar.SECOND, 1); + int enddays = DateUtils.daysBetween(endFirstDay, endDate)+1; + Date endlastday = DateUtils.getLastDayForMonth(endDate); + int endmonthdays = DateUtils.daysBetween(endFirstDay, endlastday)+1; + _months = _months.add(new BigDecimal(enddays).divide(new BigDecimal(endmonthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + } + }else { + //相当于在同一个月份 + int days = DateUtils.daysBetween(startDate, endDate)+1; + Date startLastDay = DateUtils.getLastDayForMonth(startDate); + int monthdays = DateUtils.daysBetween(startDate, startLastDay)+1; + _months = _months.add(new BigDecimal(days).divide(new BigDecimal(monthdays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + } + }else { + _months = _months.add(new BigDecimal(months)); + Date prelastMonthStartDate = DateUtils.getDaySet(startDate, Calendar.MONTH, months); + Date extraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(prelastMonthStartDate); + Date extraStartDayMonthEnd = DateUtils.getLastDayForMonth(prelastMonthStartDate); + int premonthDays = DateUtils.daysBetween(extraStartDayMonthStart, extraStartDayMonthEnd)+1; + int prelastdays = 0; + if (extraStartDayMonthEnd.after(endDate) || extraStartDayMonthEnd.equals(endDate)) { + prelastdays = DateUtils.daysBetween(prelastMonthStartDate, endDate)+1; + _months = _months.add(new BigDecimal(prelastdays).divide(new BigDecimal(premonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + }else { + prelastdays = DateUtils.daysBetween(prelastMonthStartDate, extraStartDayMonthEnd)+1; + _months = _months.add(new BigDecimal(prelastdays).divide(new BigDecimal(premonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + //跨月 + Date lastMonthStart = DateUtils.getDaySet(extraStartDayMonthEnd, Calendar.SECOND, 1); + int lastdays = DateUtils.daysBetween(lastMonthStart, endDate)+1; + Date lastextraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(lastMonthStart); + Date lastextraStartDayMonthEnd = DateUtils.getLastDayForMonth(lastMonthStart); + int lastmonthDays = DateUtils.daysBetween(lastextraStartDayMonthStart, lastextraStartDayMonthEnd)+1; + _months = _months.add(new BigDecimal(lastdays).divide(new BigDecimal(lastmonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + } + } + return _months; + } + + //根据租金合同来计算附加物业费 + private BigDecimal calcuteRentPropertyPrice(WxRentContract rentcontract,WxPropertyContract propertyContract,Date startDate,Date endDate,BigDecimal money) { + //计算物业费的单价 + BigDecimal unitPropertyPrice = calcuteUnitPrice(startDate, endDate,money, + propertyContract.getPriceUnit(),propertyContract.getDayPriceCalcute(),propertyContract.getMonthAverageDays(),propertyContract.getAdjustPeriod(),propertyContract.getReceivePeriodUnit()); + //如果租金是按天计算 + if (rentcontract.getPriceUnit().equals(EnumPriceUnit.D.getCode())){ + //物业也是按天 + if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { + return unitPropertyPrice; + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { + if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + return unitPropertyPrice.divide(new BigDecimal(12*propertyContract.getMonthAverageDays()), + Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else { + return unitPropertyPrice.divide(new BigDecimal(365),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { + if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + return unitPropertyPrice.divide(new BigDecimal(propertyContract.getMonthAverageDays()), + Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else { + int allDays = DateUtils.daysBetween(startDate, endDate)+1; + return money.divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + } + }else if (rentcontract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { + if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { + if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + return unitPropertyPrice.multiply(new BigDecimal(12*propertyContract.getMonthAverageDays())); + }else { + return unitPropertyPrice.multiply(new BigDecimal(365)); + } + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { + return unitPropertyPrice; + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { + return unitPropertyPrice.multiply(new BigDecimal(12)); + } + }else if (rentcontract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { + if (propertyContract.getPriceUnit().equals(EnumPriceUnit.D.getCode())) { + if (propertyContract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + return unitPropertyPrice.multiply(new BigDecimal(propertyContract.getMonthAverageDays())); + }else { + //此处就无法计算月了。 + //计算月份值。 + Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); + int[] diffs = DateUtils.getDiff(startDate, realEndStart); + BigDecimal months = new BigDecimal(diffs[0]); + Date preextraStartDay = DateUtils.getTimeAfterMonths(diffs[0], startDate); + Date extraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(preextraStartDay); + Date extraStartDayMonthEnd = DateUtils.getLastDayForMonth(preextraStartDay); + int monthDays = DateUtils.daysBetween(extraStartDayMonthStart, extraStartDayMonthEnd)+1; + int predays = DateUtils.daysBetween(preextraStartDay, extraStartDayMonthEnd)+1; + months = months.add(new BigDecimal(predays).divide(new BigDecimal(monthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + //有可能会跨月 + if (extraStartDayMonthEnd.before(endDate)) { + Date lastMonthStart = DateUtils.getDaySet(extraStartDayMonthEnd, Calendar.SECOND, 1); + int lastdays = DateUtils.daysBetween(lastMonthStart, endDate)+1; + Date lastextraStartDayMonthStart = DateUtils.getFirstDayForCurrMonth(lastMonthStart); + Date lastextraStartDayMonthEnd = DateUtils.getLastDayForMonth(lastMonthStart); + int lastmonthDays = DateUtils.daysBetween(lastextraStartDayMonthStart, lastextraStartDayMonthEnd)+1; + months = months.add(new BigDecimal(lastdays).divide(new BigDecimal(lastmonthDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP)); + } + return unitPropertyPrice.multiply(months); + } + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.Y.getCode())) { + return unitPropertyPrice.divide(new BigDecimal(12),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else if (propertyContract.getPriceUnit().equals(EnumPriceUnit.M.getCode())) { + return unitPropertyPrice; + } + } + return unitPropertyPrice; + } + + private BigDecimal[] calcuteReveneuJump(BigDecimal sales,WxRentContract rentcontract,Date startDate,Date endDate,List freePeriods) { + BigDecimal revenueDecimal = new BigDecimal(0); + BigDecimal rentDecimal = new BigDecimal(0); + //根据免租期来计算 + List validDates = WxRentContractHelper.getValidDays(startDate, endDate, freePeriods); + if (null == validDates || validDates.size() <= 0 ) { + BigDecimal[] bs = new BigDecimal[] {revenueDecimal,rentDecimal,new BigDecimal(0)}; + return bs; + } + int allDays = DateUtils.daysBetween(startDate,endDate)+1; + boolean isFull = false; + if (allDays == validDates.size()) { + isFull = true; + } + WxRentContractRevenueJump jq = new WxRentContractRevenueJump(); + jq.updateTenantInfo(rentcontract); + jq.setRentContractId(rentcontract.getId()); + jq.setSortColumn(" minMoney asc"); + List jumpList = wxRentContractRevenueJumpMapper.findList(jq); + if (null != jumpList && jumpList.size() > 0 ) { + //不是满时间段的,要按天来计算 + if (!isFull) { + Date realEndStart = DateUtils.getDaySet(endDate, Calendar.SECOND, 1); + int[] diffs = DateUtils.getDiff(startDate, realEndStart); + if (diffs[0] <= 0 || (diffs[0] == 1 && diffs[1] <= 0 )) { + if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(30),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else { + sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + }else { + Date preextraStartDay = DateUtils.getTimeAfterMonths(diffs[0], startDate); + int predays = DateUtils.daysBetween(preextraStartDay, endDate)+1; + if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + BigDecimal days = new BigDecimal(diffs[0]).multiply(new BigDecimal(30)).add(new BigDecimal(predays)); + sales = sales.multiply(new BigDecimal(validDates.size())).divide(days,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + }else { + sales = sales.multiply(new BigDecimal(validDates.size())).divide(new BigDecimal(allDays),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + } + } + } + for (int i = 0 ; i< jumpList.size() ; i ++) { + WxRentContractRevenueJump rj = jumpList.get(i); + String minMoney = rj.getMinMoney(); + String maxMoney = rj.getMaxMoney(); + if (StringUtils.isNotBlank(maxMoney)) { + if (sales.compareTo(new BigDecimal(maxMoney)) <= 0 ) { + revenueDecimal = sales.multiply(new BigDecimal(rj.getRate())).divide(new BigDecimal(100)); + if (StringUtils.isNotBlank(rj.getRentMoney())) { + rentDecimal = new BigDecimal(rj.getRentMoney()); + } + break; + } + }else { + if (sales.compareTo(new BigDecimal(minMoney)) > 0 ) { + revenueDecimal = sales.multiply(new BigDecimal(rj.getRate())).divide(new BigDecimal(100)); + if (StringUtils.isNotBlank(rj.getRentMoney())) { + rentDecimal = new BigDecimal(rj.getRentMoney()); + } + break; + } + } + } + } + //根据时间区间计算 + //固定租金需要再计算,因为跳点设置的租金是单价 + String rentNeedpay = "0"; + if (rentDecimal.compareTo(new BigDecimal(0)) > 0 ) { + rentNeedpay = WxRentContractHelper.getNeedPayMoney(freePeriods,rentcontract, rentDecimal.toPlainString(),startDate, + endDate,0,0,false,rentcontract.getReceivePeriodUnit(),rentcontract.getReceivePeriod()); + } + rentDecimal = new BigDecimal(rentNeedpay); + BigDecimal[] bs = new BigDecimal[] {revenueDecimal,rentDecimal,sales}; + return bs; + } + + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + @Override + public WxRentContractRevenueSetSalesVo setRevenueSales(MallUserInfo user,WxRentContract rentcontract, String sales, Date startime, Date endtime, Long propertyContractId) { + //如果账单存在缴费,付款,减免,冲抵,等情况,则不允许。 + WxAllBill bq = wxBillAllHelper.generateRentContractQueryBill(rentcontract, rentcontract.getId(),startime,endtime); + List rentBillList = wxAllBillMapper.findList(bq); + if (null == rentBillList || rentBillList.size() <= 0 ) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"未查询到账单"); + } + for (int i = 0 ; i < rentBillList.size() ; i ++) { + WxAllBill rentBill = rentBillList.get(i); + if ((StringUtils.isNotBlank(rentBill.getPay()) && new BigDecimal(rentBill.getPay()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(rentBill.getSetOff()) && new BigDecimal(rentBill.getSetOff()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(rentBill.getReturnPay()) && new BigDecimal(rentBill.getReturnPay()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(rentBill.getUseMoney()) && new BigDecimal(rentBill.getUseMoney()).compareTo(new BigDecimal(0)) > 0 ) ) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"租金账单存在已经已经缴费或付款,扣减,减免,冲抵的情况,不允许操作"); + } + } + + BigDecimal salesDeciaml = new BigDecimal(sales); + + //删除自动创建的账单 + WxAllBill billDel = new WxAllBill(); + billDel.updateTenantInfo(rentcontract); + billDel.setRentContractId(rentcontract.getId()); + billDel.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_REVENUE_SALES.getCode()); + billDel.setStarttimeEqual(startime); + wxAllBillMapper.deleteByRentReveneuSales(billDel); + + //上面删除掉生成的账单之后,再重新查询,只剩下主账单 + rentBillList = wxAllBillMapper.findList(bq); + + //加上物业 + List propertyBillList = null; + BigDecimal propertyPrice = new BigDecimal(0); + WxPropertyContract propertyContract = null; + if (null != propertyContractId) { + WxAllBill propertyBillq = new WxAllBill(); + propertyBillq.updateTenantInfo(rentcontract); + propertyBillq.setPropertyContractId(propertyContractId); + propertyBillq.setBillType(EnumBillAllType.PROPERTY.getCode()); + propertyBillq.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); + propertyBillq.setIsPreview(EnumYesOrNo.NO.getCode()); + propertyBillq.setNoExtraCreateFrom(EnumYesOrNo.YES.getCode()); + propertyBillq.setStarttimeEqual(startime); + propertyBillq.setEndtimeEqual(endtime); + propertyBillList = wxAllBillMapper.findList(propertyBillq); + for (int i = 0 ; i < propertyBillList.size() ; i ++) { + WxAllBill propertyBill = propertyBillList.get(i); + if ((StringUtils.isNotBlank(propertyBill.getPay()) && new BigDecimal(propertyBill.getPay()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(propertyBill.getSetOff()) && new BigDecimal(propertyBill.getSetOff()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(propertyBill.getReturnPay()) && new BigDecimal(propertyBill.getReturnPay()).compareTo(new BigDecimal(0)) > 0 ) + || (StringUtils.isNotBlank(propertyBill.getUseMoney()) && new BigDecimal(propertyBill.getUseMoney()).compareTo(new BigDecimal(0)) > 0 ) ) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"物业账单存在已经已经缴费或付款,扣减,减免,冲抵的情况,不允许操作"); + } + } + } + + //根据销售额来计算平均每计费周期营业额,相当于设置联营扣点保底营业额 + BigDecimal unitRevenuePrice = new BigDecimal(0); + //如果没达到最低扣点销售额,则不重新计算 + if (StringUtils.isNotBlank(rentcontract.getLimitRevenue()) && new BigDecimal(rentcontract.getLimitRevenue()).compareTo(salesDeciaml) > 0 ){ + //保存销售额 + addRevenueSales(rentcontract,startime,endtime,"0",sales,salesDeciaml,propertyContractId); + WxRentContractRevenueSetSalesVo vo = new WxRentContractRevenueSetSalesVo(); + vo.setTotal("0"); + return vo; + }else { + unitRevenuePrice = calcuteUnitPrice(startime, endtime,salesDeciaml, + rentcontract.getPriceUnit(),rentcontract.getDayPriceCalcute(),rentcontract.getMonthAverageDays(),rentcontract.getAdjustPeriod(),rentcontract.getReceivePeriodUnit()); + //设置保底营业额 + rentcontract.setRevenue(unitRevenuePrice.toPlainString()); + //联营扣点 + if (rentcontract.getType().equals(EnumRentContractType.RENT_BY_JOINT.getCode())) { + rentcontract.setPrice(new BigDecimal(rentcontract.getPayRatio()).multiply(unitRevenuePrice).divide(new BigDecimal(100), + Constant.default_long_decimal_size,RoundingMode.HALF_UP).toPlainString()); + }else if (rentcontract.getType().intValue() == EnumRentContractType.RENT_BY_AREA_AND_JOINT.getCode()) { + //取高才能加上物业费 + if (null != propertyContractId && null != propertyBillList) { + propertyContract = wxPropertyContractMapper.selectById(propertyContractId); + //有可能物业的单价时间跟租金的不一致,需要根据物业的单价重新计算 + //propertyPrice = calcuteRentPropertyPrice(rentcontract, propertyContract, rentBill.getStarttime(), rentBill.getEndtime(), + //new BigDecimal(propertyBill.getNeedPay())); + } + } + //计算每一年的基数 + List priceArrs = WxRentContractHelper.calcuteRentAndRevenuePrice(rentcontract); + String[] rentPriceArrs = priceArrs.get(0); + String[] revenuePriceArrs = priceArrs.get(1); + //计算商业管理费 + String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(rentcontract); + //计算运营管理费 + String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(rentcontract); + + //物业费单价 + String[] propertyContractArrs = null; + if (null != propertyContract) { + propertyContractArrs = WxRentContractHelper.calcutePropertyPrice(propertyContract); + } + List yearList = this.getYearList(rentPriceArrs.length, 12, rentcontract.getRentalStartDate(),null); + int yearIndex = 0; + for( int i = 0 ; i < yearList.size() ; i ++) { + Date yearStartDate = yearList.get(i); + Date yearEndDate = DateUtils.getTimeAfterMonths(12, yearStartDate); + if (startime.equals(yearStartDate) || + (startime.after(yearStartDate) && (endtime.before(yearEndDate) || endtime.equals(yearEndDate)) )) { + yearIndex = i; + break; + } + } + if (yearIndex <= 0 ) { + yearIndex = 0; + } + + //租金+营业管理费+商业管理费+物业 和扣点相比取高。 + BigDecimal rentTotal = new BigDecimal(rentPriceArrs[yearIndex]); + if (null != bussinessManagerPriceArrs) { + rentTotal = rentTotal.add(new BigDecimal(bussinessManagerPriceArrs[yearIndex])); + } + if (null != operationManagerPriceArrs) { + rentTotal = rentTotal.add(new BigDecimal(operationManagerPriceArrs[yearIndex])); + } + //此处需要物业合同合租金合同的计费周期一致,严谨的需要用到上面计算的propertyPrice + if (null != propertyContractArrs) { + rentTotal = rentTotal.add(new BigDecimal(propertyContractArrs[yearIndex])); + } + + //跟扣点相比较 + BigDecimal priceDecimal = rentTotal; + if (null != revenuePriceArrs && null != revenuePriceArrs[yearIndex]) { + BigDecimal revenuePrice = new BigDecimal(revenuePriceArrs[yearIndex]); + if (revenuePrice.compareTo(rentTotal) > 0 ) { + priceDecimal = revenuePrice; + } + } + + //免租期 + List freePeriods = getFreeDays(rentcontract); + + //根据扣点规则和租赁相关费用取高来计算费用 + String needpay = WxRentContractHelper.getNeedPayMoney(freePeriods,rentcontract, priceDecimal.toPlainString(),startime, + endtime,0,0,false,rentcontract.getReceivePeriodUnit(),rentcontract.getReceivePeriod()); + + //计算跳点。 + BigDecimal[] jumppays = calcuteReveneuJump(salesDeciaml, rentcontract,startime, endtime,freePeriods); + BigDecimal jumpRevenuePay = jumppays[0]; + BigDecimal jumpRentPay = jumppays[1]; + BigDecimal saleDecimalValid = jumppays[2]; + BigDecimal jumppay = new BigDecimal(0); + if (jumpRevenuePay.compareTo(jumpRentPay) > 0 ) { + jumppay = jumppay.add(jumpRevenuePay); + }else { + jumppay = jumppay.add(jumpRentPay); + } + StringBuffer sb = new StringBuffer("有效销售额:"+saleDecimalValid.toPlainString()+","); + if (jumppay.compareTo(new BigDecimal(needpay)) > 0 ) { + sb.append("跳点规则计算金额:"+jumppay.toPlainString()+",合同租金扣点规则计算金额:"+needpay+"."); + needpay = jumppay.toPlainString(); + }else { + sb.append("跳点规则计算金额:"+jumppay.toPlainString()+",合同租金扣点规则计算金额:"+needpay+"."); + } + sb.append("取高后总金额为:["+needpay+"]."); + //保存销售额 + addRevenueSales(rentcontract,startime,endtime,needpay,sales,saleDecimalValid,propertyContractId); + return handleBills(user,sb,rentcontract,propertyContractId,needpay,rentBillList,startime,endtime,EnumBillExtraCreateFrom.RNET_REVENUE_SALES,propertyBillList,rentPriceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs,propertyContractArrs,yearIndex); + + } + } + + private void addRevenueSales(WxRentContract rentcontract,Date starttime,Date endtime,String needpay,String sales,BigDecimal saleDecimalValid,Long propertyContractId) { + WxRentContractRevenueSales rs = new WxRentContractRevenueSales(); + rs.updateTenantInfo(rentcontract); + rs.setRentContractId(rentcontract.getId()); + rs.setStarttimeEqual(starttime); + rs.setEndtimeEqual(endtime); + List saleList = wxRentContractRevenueSalesMapper.findList(rs); + if (null != saleList && saleList.size() > 0 ) { + WxRentContractRevenueSales sale = saleList.get(0); sale.setCalcuteMoney(needpay); - sale.setSaleMoney(sales); - sale.setSaleMoneyValid(saleDecimalValid.toPlainString()); - sale.setUpdateTime(new Date()); - wxRentContractRevenueSalesMapper.updateById(sale); - }else { - WxRentContractRevenueSales sale = new WxRentContractRevenueSales(); - final IdWorker idWorker = IdWorker.get(); - sale.setId(idWorker.nextId()); - sale.updateTenantInfo(rentcontract); - sale.setStarttime(startime); - sale.setEndtime(endtime); - sale.setRentContractId(rentcontract.getId()); - sale.setSaleMoney(sales); - sale.setSaleMoneyValid(saleDecimalValid.toPlainString()); - sale.setCalcuteMoney(needpay); - sale.setPropertyContractId(propertyContractId); - sale.setCreateTime(new Date()); - sale.setUpdateTime(new Date()); - wxRentContractRevenueSalesMapper.insert(sale); - } - return handleBills(user,sb,rentcontract,propertyContractId,needpay,rentBillList,startime,endtime,EnumBillExtraCreateFrom.RNET_REVENUE_SALES,propertyBillList,rentPriceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs,propertyContractArrs,yearIndex); - } - - private WxRentContractRevenueSetSalesVo handleBills(MallUserInfo user,StringBuffer sb,WxRentContract rentcontract,Long propertyContractId, String needpay,List rentBillList,Date startDate,Date endDate, - EnumBillExtraCreateFrom createFrom,List propertyBillList,String[] rentPriceArrs,String[] bussinessManagerPriceArrs,String[] operationManagerPriceArrs,String[] propertyContractArrs,int yearIndex) { - - //计算资金分摊的比例 租金,商业管理费,营业管理费,物业费。每个科目税点不一样,这样分摊能降低成本 - String[] moneyShareRates = new String[4]; - BigDecimal rentPriceDecimal = new BigDecimal(rentPriceArrs[yearIndex]); - BigDecimal bussinessPriceDecimal = new BigDecimal(0); - if (null != bussinessManagerPriceArrs && null != bussinessManagerPriceArrs[yearIndex]) { - bussinessPriceDecimal = new BigDecimal(bussinessManagerPriceArrs[yearIndex]); - } - BigDecimal operaterPriceDecimal = new BigDecimal(0); - if (null != operationManagerPriceArrs && null != operationManagerPriceArrs[yearIndex]) { - operaterPriceDecimal = new BigDecimal(operationManagerPriceArrs[yearIndex]); - } - if (null != rentPriceArrs && null != bussinessManagerPriceArrs && null != operationManagerPriceArrs - && rentPriceDecimal.compareTo(new BigDecimal(0)) > 0 && bussinessPriceDecimal.compareTo(new BigDecimal(0)) > 0 && operaterPriceDecimal.compareTo(new BigDecimal(0)) > 0) { - BigDecimal total = rentPriceDecimal.add(bussinessPriceDecimal).add(operaterPriceDecimal); - BigDecimal property = new BigDecimal(0); - if (null != propertyContractArrs) { - property = new BigDecimal(propertyContractArrs[yearIndex]); - } - total = total.add(property); - moneyShareRates[0] = rentPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); - moneyShareRates[1] = bussinessPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); - moneyShareRates[2] = operaterPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); - moneyShareRates[3] = property.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); - }else { - SysConfig shareConfig = sysConfigService.getByKey(SysConfigConstant.rent_share_bill_rate, rentcontract); - if (null == shareConfig || StringUtils.isBlank(shareConfig.getConfigItemValue())) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"系统配置"+SysConfigConstant.rent_share_bill_rate+"未配置。"); - } - moneyShareRates = shareConfig.getConfigItemValue().split(","); - moneyShareRates[0] = new BigDecimal(moneyShareRates[0]).divide(new BigDecimal(100)).toPlainString(); - moneyShareRates[1] = new BigDecimal(moneyShareRates[1]).divide(new BigDecimal(100)).toPlainString(); - moneyShareRates[2] = new BigDecimal(moneyShareRates[2]).divide(new BigDecimal(100)).toPlainString(); - moneyShareRates[3] = new BigDecimal(moneyShareRates[3]).divide(new BigDecimal(100)).toPlainString(); - } - - String rentRate = moneyShareRates[0]; - String bussinessRate = moneyShareRates[1]; - String operaterRate = moneyShareRates[2]; - String propertyRate = moneyShareRates[3]; - //更新账单费用 - String rentneedpay = new BigDecimal(needpay).multiply(new BigDecimal(rentRate)).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); - List shopIdList = rentcontract.shopIdsByRentInfo(); - Map shopAreaRateMap = rentcontract.getRentShopArea(); - WxShopUsers suq = new WxShopUsers(); - suq.updateTenantInfo(rentcontract); - suq.setShopIds(shopIdList); - suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); - Map shopUserMap = wxShopService.getShopUserMap(suq); - WxShop sq = new WxShop(); - sq.updateTenantInfo(sq); - sq.setIds(shopIdList); - Map shopMap = wxShopService.findShopMap(sq); - - List rentBill = generateRentBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract,rentBillList,rentneedpay,rentRate,startDate,endDate,createFrom); - - List propeBill = generatePropertyBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, propertyContractId,propertyBillList,startDate,endDate, needpay, propertyRate,createFrom); - - List bmbill = generateManageBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, startDate,endDate, needpay, bussinessRate, EnumBillAllType.RENT_BUSSINESS_MANAGE,createFrom); - - List ombill = generateManageBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, startDate,endDate, needpay, operaterRate, EnumBillAllType.RENT_OPERATION_MANAGE,createFrom); - - WxRentContractRevenueSetSalesVo vo = new WxRentContractRevenueSetSalesVo(); - vo.setTotal(needpay); - List blist = new ArrayList(); - blist.addAll(rentBill); - if (null != propeBill) { - blist.addAll(propeBill); - } - if (null != bmbill) { - blist.addAll(bmbill); - } - if (null != ombill) { - blist.addAll(ombill); - } - vo.setBillList(blist);; - return vo; - } - - - private void createBillAction(WxAllBill bill,String oldMoney,String newMoney,MallUserInfo user) { - WxBillAction wxBillAction = new WxBillAction(); - wxBillAction.setBillId(bill.getId()); - wxBillAction.setBillType(bill.getBillType()); - wxBillAction.setOldMoney(oldMoney); - wxBillAction.setNewMoney(newMoney); - wxBillAction.setDetails(EnumBillAction.UPDATE_BILL.getDescription(oldMoney, newMoney,null,null,null,null)); - wxBillAction.setAction(EnumBillAction.UPDATE_BILL.getCode()); - wxBillAction.setRemark(bill.getBillRemark()); - wxBillAction.setUserType(EnumSystemUserType.ADMIN.getCode()); - wxBillActionService.modifyBill(wxBillAction, user); - } - - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public List generateManageBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, - Date starttime, Date endtime,String total,String rate,EnumBillAllType type,EnumBillExtraCreateFrom createFrom) { - WxAllBill bussinessmanageBill = new WxAllBill(); - bussinessmanageBill.updateTenantInfo(rentcontract); - bussinessmanageBill.setBillType(type.getCode()); - bussinessmanageBill.setEnergyFeesId(type.getEnergyFeesId()); - bussinessmanageBill.setRentContractId(rentcontract.getId()); - bussinessmanageBill.setIsPreview(EnumYesOrNo.NO.getCode()); - bussinessmanageBill.setNoExtraCreateFrom(EnumYesOrNo.YES.getCode()); - bussinessmanageBill.setStarttimeEqual(starttime); - bussinessmanageBill.setEndtimeEqual(endtime); - List bmbillList = wxAllBillMapper.findList(bussinessmanageBill); - BigDecimal bussinessmoney = new BigDecimal(total).multiply(new BigDecimal(rate)).setScale(Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - if (null != bmbillList && bmbillList.size() > 0 ) { - //查询每一个铺位的 - for (int i = 0 ; i < bmbillList.size() ; i ++) { - WxAllBill b = bmbillList.get(i); - String oldMoney = b.getReceivePay(); - //把原有的账单应收金额变为0 - b.setHistoryReceivePay(oldMoney); - b.setNeedPay("0");//如不设置会影响减免统计 - b.setReceivePay("0"); - b.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); - b.setUpdatetime(new Date()); - b.setUpdateBy(user.getId()); - b.setUpdateByName(user.getName()); - wxAllBillMapper.updateById(b); - - createBillAction(b,oldMoney,"0",user); - } - } - if (bussinessmoney.compareTo(new BigDecimal(0)) > 0 ) { - List billList = new ArrayList(); - for (int i = 0 ; i < shopIds.size(); i++) { - Long sid = shopIds.get(i); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - - String newmoney = bussinessmoney.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); - WxAllBill b = new WxAllBill(); - final IdWorker idWorker = IdWorker.get(); - b.setId(idWorker.nextId()); - b.updateTenantInfo(rentcontract); - b.setBillType(type.getCode()); - b.setEnergyFeesId(type.getEnergyFeesId()); - b.setRentContractId(rentcontract.getId()); - b.setIsPreview(EnumYesOrNo.NO.getCode()); - b.setCanEdit(EnumYesOrNo.NO.getCode()); - b.setShopId(sid); - String cusName = null; - if (null != shopUserMap) { - WxShopUsers su = shopUserMap.get(sid); - if (null != su) { - cusName = su.getName(); - } - } - b.setCusName(cusName); - b.setCreatetime(new Date()); - b.setCreateBy(user.getId()); - b.setCreateByName(user.getName()); - b.setUpdatetime(new Date()); - b.setUpdateBy(user.getId()); - b.setUpdateByName(user.getName()); - b.setPriceDetail(""); - b.setNeedPay(newmoney); - b.setReceivePay(newmoney); - b.setPay("0"); - b.setStarttime(starttime); - b.setEndtime(endtime); - b.setReceiveDate(starttime); - b.setPeriod(WxRentContractHelper.getPeriod(starttime)); - b.setBillRemark(createFrom.getMessage()+"自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - b.setExtraCreateFrom(createFrom.getCode()); - b.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - wxAllBillMapper.insert(b); - if (null != shopMap) { - WxShop s = shopMap.get(sid); - if ( null != s) { - b.setShopNumber(s.getShopNumber()); - } - } - billList.add(b); - } - return billList; - } - return null; - - } - - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public List generatePropertyBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, - Long propertyContractId,List propertyBillList,Date starttime,Date endtime,String total,String rate,EnumBillExtraCreateFrom createFrom) { - BigDecimal bussinessmoney = new BigDecimal(total).multiply(new BigDecimal(rate)).setScale(Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - if (null != propertyBillList ) { - if (null != propertyBillList) { - for (int i = 0 ; i < propertyBillList.size(); i++){ - WxAllBill _rb = propertyBillList.get(i); - //把原有的账单应收金额变为0 - String oldMoney = _rb.getReceivePay(); - _rb.setHistoryReceivePay(_rb.getReceivePay()); - _rb.setNeedPay("0"); - _rb.setReceivePay("0"); - _rb.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); - _rb.setUpdatetime(new Date()); - _rb.setUpdateBy(user.getId()); - _rb.setUpdateByName(user.getName()); - wxAllBillMapper.updateById(_rb); - - createBillAction(_rb,oldMoney,"0",user); - } - } - } - if (bussinessmoney.compareTo(new BigDecimal(0)) > 0 ) { - List billList = new ArrayList(); - for (int i = 0 ; i < shopIds.size() ; i ++) { - Long sid = shopIds.get(i); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - - String newmoney = bussinessmoney.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); - WxAllBill bmbill = new WxAllBill(); - final IdWorker idWorker = IdWorker.get(); - bmbill.setId(idWorker.nextId()); - bmbill.updateTenantInfo(rentcontract); - bmbill.setBillType(EnumBillAllType.PROPERTY.getCode()); - bmbill.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); - bmbill.setRentContractId(rentcontract.getId()); - bmbill.setPropertyContractId(propertyContractId); - bmbill.setIsPreview(EnumYesOrNo.NO.getCode()); - bmbill.setCanEdit(EnumYesOrNo.NO.getCode()); - bmbill.setShopId(sid); - String cusName = null; - if (null != shopUserMap) { - WxShopUsers su = shopUserMap.get(sid); - if (null != su) { - cusName = su.getName(); - } - } - bmbill.setCusName(cusName); - bmbill.setCreatetime(new Date()); - bmbill.setCreateBy(user.getId()); - bmbill.setCreateByName(user.getName()); - bmbill.setUpdatetime(new Date()); - bmbill.setUpdateBy(user.getId()); - bmbill.setUpdateByName(user.getName()); - bmbill.setPriceDetail(""); - bmbill.setNeedPay(newmoney); - bmbill.setReceivePay(newmoney); - bmbill.setPay("0"); - bmbill.setStarttime(starttime); - bmbill.setEndtime(endtime); - bmbill.setReceiveDate(starttime); - bmbill.setPeriod(WxRentContractHelper.getPeriod(starttime)); - bmbill.setBillRemark(createFrom.getMessage()+".自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - bmbill.setExtraCreateFrom(createFrom.getCode()); - bmbill.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - wxAllBillMapper.insert(bmbill); - if (null != shopMap) { - WxShop s = shopMap.get(sid); - if ( null != s) { - bmbill.setShopNumber(s.getShopNumber()); - } - } - billList.add(bmbill); - } - return billList; - } - return null; - - } - - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public List generateRentBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, - List rentBillList,String money,String rate,Date starttime,Date endtime,EnumBillExtraCreateFrom createFrom) { - //rentBillList , 如果是多个房间,则就有几个租金账单 - if (null != rentBillList && rentBillList.size() > 0 ) { - //查询每一个铺位的 - for (int i = 0 ; i < rentBillList.size() ; i ++) { - WxAllBill b = rentBillList.get(i); - //把原有的账单应收金额变为0 - String oldMoney = b.getReceivePay(); - b.setHistoryReceivePay(oldMoney);//设置此值,供录入销售额的页面显示应收金额 - b.setNeedPay("0");//如不设置会影响减免统计 - b.setReceivePay("0"); - b.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); - b.setUpdatetime(new Date()); - b.setUpdateBy(user.getId()); - b.setUpdateByName(user.getName()); - wxAllBillMapper.updateById(b); - - createBillAction(b,oldMoney,"0",user); - } - } - BigDecimal moneyb = new BigDecimal(money); - List billList = new ArrayList(); - for (int i = 0 ; i < shopIds.size(); i++) { - Long sid = shopIds.get(i); - BigDecimal shoprentArea = shopAreaRateMap.get(sid); - BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); - - String newmoney = moneyb.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); - WxAllBill bmbill = new WxAllBill(); - final IdWorker idWorker = IdWorker.get(); - bmbill.setId(idWorker.nextId()); - bmbill.updateTenantInfo(rentcontract); - bmbill.setBillType(EnumBillAllType.RENT.getCode()); - bmbill.setEnergyFeesId(EnumBillAllType.RENT.getEnergyFeesId()); - bmbill.setRentContractId(rentcontract.getId()); - bmbill.setIsPreview(EnumYesOrNo.NO.getCode()); - bmbill.setCanEdit(EnumYesOrNo.NO.getCode()); - bmbill.setShopId(sid); - String cusName = null; - if (null != shopUserMap) { - WxShopUsers su = shopUserMap.get(sid); - if (null != su) { - cusName = su.getName(); - } - } - bmbill.setCusName(cusName); - bmbill.setCreatetime(new Date()); - bmbill.setCreateBy(user.getId()); - bmbill.setCreateByName(user.getName()); - bmbill.setUpdatetime(new Date()); - bmbill.setUpdateBy(user.getId()); - bmbill.setUpdateByName(user.getName()); - bmbill.setPriceDetail(""); - bmbill.setNeedPay(newmoney); - bmbill.setReceivePay(bmbill.getNeedPay()); - bmbill.setPay("0"); - bmbill.setStarttime(starttime); - bmbill.setEndtime(endtime); - bmbill.setReceiveDate(starttime); - bmbill.setPeriod(WxRentContractHelper.getPeriod(starttime)); - bmbill.setBillRemark(createFrom.getMessage()+".自动计算创建,科目总应收金额为:"+moneyb.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - bmbill.setExtraCreateFrom(createFrom.getCode()); - bmbill.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+moneyb.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); - wxAllBillMapper.insert(bmbill); - if (null != shopMap) { - WxShop s = shopMap.get(sid); - if ( null != s) { - bmbill.setShopNumber(s.getShopNumber()); - } - } - billList.add(bmbill); - } - return billList; - } - - @Override - public void setContractSalesConfirm(WxRentContract rentcontract) { - WxRentContractRevenueSales sales = new WxRentContractRevenueSales(); - sales.updateTenantInfo(rentcontract); - sales.setRentContractId(rentcontract.getId()); - sales.setStarttime(rentcontract.getYearsBegin()); - sales.setEndtime(rentcontract.getYearsEnd()); - wxRentContractRevenueSalesMapper.updateConfirm(sales); - } - - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - @Override - public WxRentContractYearsSumVo calcuteYearsRevenueRentUp(MallUserInfo user,WxRentContract rentcontract) { - //查询销售总数 - WxRentContractRevenueSales rsq = new WxRentContractRevenueSales(); - rsq.updateTenantInfo(rentcontract); - rsq.setRentContractId(rentcontract.getId()); - rsq.setStarttime(rentcontract.getYearsBegin()); - rsq.setEndtime(rentcontract.getYearsEnd()); - BigDecimal sum = wxRentContractRevenueSalesMapper.findSumSalesMoneyValid(rsq); - if (null == sum || sum.compareTo(new BigDecimal(0)) <= 0 ) { - WxRentContractYearsSumVo vo = new WxRentContractYearsSumVo(); - vo.setTotalSales("0"); - vo.setTotalRevenue("0"); - vo.setBillReceivePay("0"); - return vo; - } - //更新已计算 - wxRentContractRevenueSalesMapper.updateCalcute(rsq); - - //如果有账单已经缴费或者付款,扣减,减免,冲抵等,则不允许操作。 - WxAllBill billd = new WxAllBill(); - billd.updateTenantInfo(rentcontract); - billd.setRentContractId(rentcontract.getId()); - //删除这个时间的,不设置结束时间,因为可能之前有了账单。,然后撤铺,结束时间虽然不一样,开始时间是一致的。 - billd.setStarttimeEqual(rentcontract.getYearsBegin()); - billd.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_TIAODIAN_HUISUAN.getCode()); - - Integer validCount = wxAllBillMapper.countValidBillCountByRentHuiSuan(billd); - if (null != validCount && validCount > 0 ) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"存在已经已经缴费或付款,扣减,减免,冲抵的账单,则不允许操作"); - } - - //删除未支付,未冲抵,未退款的之前的账单 - wxAllBillMapper.deleteByRentHuiSuan(billd); - - //计算跳点。 - BigDecimal[] jumppays = calcuteReveneuJump(sum, rentcontract,rentcontract.getYearsBegin(), rentcontract.getYearsEnd(),null); - BigDecimal jumpRevenuePay = jumppays[0]; - //BigDecimal jumpRentPay = jumppays[1]; - - //销售收入不满足一年怎么算。 - int yearDays = DateUtils.daysBetween(rentcontract.getYearsBegin(), rentcontract.getYearsEnd())+1; - //闰年是366 - if (yearDays >= 365) { - }else { - if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { - jumpRevenuePay = jumpRevenuePay.multiply(new BigDecimal(yearDays)).divide(new BigDecimal(12*rentcontract.getMonthAverageDays()),rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP); - }else { - jumpRevenuePay = jumpRevenuePay.multiply(new BigDecimal(yearDays)).divide(new BigDecimal(365),rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP); - } - } - - BigDecimal receivepay = new BigDecimal(0); - //查询合同租金所有应收的账单 - //查询所有租金+营业管理费+商业管理费账单的信息,因为设置销售额会自动的创建或者更新对应的账单 - WxAllBill rentBillq = new WxAllBill(); - rentBillq.updateTenantInfo(rentcontract); - rentBillq.setRentContractId(rentcontract.getId()); - List feesIdList = new ArrayList(); - feesIdList.add(EnumBillAllType.RENT.getEnergyFeesId()); - feesIdList.add(EnumBillAllType.RENT_BUSSINESS_MANAGE.getEnergyFeesId()); - feesIdList.add(EnumBillAllType.RENT_OPERATION_MANAGE.getEnergyFeesId()); - rentBillq.setEnergyFeesIds(feesIdList); - rentBillq.setIsPreview(EnumYesOrNo.NO.getCode()); - rentBillq.setStarttime(rentcontract.getYearsBegin()); - rentBillq.setEndtime(rentcontract.getYearsEnd()); - WxBillSum rentBillSum = wxAllBillMapper.getBillMonthSum(rentBillq); - if (null != rentBillSum) { - receivepay = receivepay.add(rentBillSum.getNeedPayNumber()); - } - - //查询对应的物业账单,包括录入销售额自动生成的 - if (null != rentcontract.getPropertyContractId()) { - WxAllBill propertyBillq = new WxAllBill(); - propertyBillq.updateTenantInfo(rentcontract); - propertyBillq.setPropertyContractId(rentcontract.getPropertyContractId()); - propertyBillq.setBillType(EnumBillAllType.PROPERTY.getCode()); - propertyBillq.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); - propertyBillq.setIsPreview(EnumYesOrNo.NO.getCode()); - propertyBillq.setStarttime(rentcontract.getYearsBegin()); - propertyBillq.setEndtime(rentcontract.getYearsEnd()); - //prpoertyBillq.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_REVENUE_SALES.getCode()); - WxBillSum propertyBillSum = wxAllBillMapper.getBillMonthSum(propertyBillq); - if (null != propertyBillSum) { - receivepay = receivepay.add(propertyBillSum.getNeedPayNumber()); - } - } - - WxRentContractYearsSumVo vo = new WxRentContractYearsSumVo(); - vo.setTotalSales(sum.toPlainString()); - vo.setTotalRevenue(jumpRevenuePay.toPlainString()); - vo.setBillReceivePay(receivepay.toPlainString()); - - if ( new BigDecimal(vo.getOwe()).compareTo(new BigDecimal(0)) > 0) { - WxRentContractRevenueSetSalesVo svo = handelHuiSuanBills(user,rentcontract,vo.getOwe()); - vo.setBillList(svo.getBillList()); - } - - return vo; - } - - private WxRentContractRevenueSetSalesVo handelHuiSuanBills(MallUserInfo user,WxRentContract rentcontract,String owe) { - //计算每一年的基数 - List priceArrs = WxRentContractHelper.calcuteRentAndRevenuePrice(rentcontract); - String[] rentPriceArrs = priceArrs.get(0); - //String[] revenuePriceArrs = priceArrs.get(1); - //计算商业管理费 - String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(rentcontract); - //计算运营管理费 - String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(rentcontract); - - //物业费单价 - String[] propertyContractArrs = null; - List yearList = this.getYearList(rentPriceArrs.length, 12, rentcontract.getRentalStartDate(),null); - int yearIndex = 0; - for( int i = 0 ; i < yearList.size() ; i ++) { - Date yearEndDate = yearList.get(i); - if (rentcontract.getYearsBegin().before(yearEndDate) || rentcontract.getYearsEnd().equals(yearEndDate)) { - yearIndex = i-1; - break; - } - } - if (yearIndex <= 0 ) { - yearIndex = 0; - } - StringBuffer sb = new StringBuffer(""); - return handleBills(user,sb,rentcontract,null,owe,null,rentcontract.getYearsBegin(),rentcontract.getYearsEnd(),EnumBillExtraCreateFrom.RNET_TIAODIAN_HUISUAN,null,rentPriceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs,propertyContractArrs,yearIndex); - } - - - @Override - public List findJumpList(WxRentContractRevenueJump jump) { - return wxRentContractRevenueJumpMapper.findList(jump); - } - - @Override - public BigDecimal calcuteContractUsedShopArea(WxRentContract wxRentContract,Long shopId) { - //根据合同区间查询已使用合同的总面积 - return null; - } - -} + sale.setSaleMoney(sales); + sale.setSaleMoneyValid(saleDecimalValid.toPlainString()); + sale.setUpdateTime(new Date()); + wxRentContractRevenueSalesMapper.updateById(sale); + }else { + WxRentContractRevenueSales sale = new WxRentContractRevenueSales(); + final IdWorker idWorker = IdWorker.get(); + sale.setId(idWorker.nextId()); + sale.updateTenantInfo(rentcontract); + sale.setStarttime(starttime); + sale.setEndtime(endtime); + sale.setRentContractId(rentcontract.getId()); + sale.setSaleMoney(sales); + sale.setSaleMoneyValid(saleDecimalValid.toPlainString()); + sale.setCalcuteMoney(needpay); + sale.setPropertyContractId(propertyContractId); + sale.setCreateTime(new Date()); + sale.setUpdateTime(new Date()); + wxRentContractRevenueSalesMapper.insert(sale); + } + } + + private WxRentContractRevenueSetSalesVo handleBills(MallUserInfo user,StringBuffer sb,WxRentContract rentcontract,Long propertyContractId, String needpay,List rentBillList,Date startDate,Date endDate, + EnumBillExtraCreateFrom createFrom,List propertyBillList,String[] rentPriceArrs,String[] bussinessManagerPriceArrs,String[] operationManagerPriceArrs,String[] propertyContractArrs,int yearIndex) { + + //计算资金分摊的比例 租金,商业管理费,营业管理费,物业费。每个科目税点不一样,这样分摊能降低成本 + String[] moneyShareRates = new String[4]; + BigDecimal rentPriceDecimal = new BigDecimal(rentPriceArrs[yearIndex]); + BigDecimal bussinessPriceDecimal = new BigDecimal(0); + if (null != bussinessManagerPriceArrs && null != bussinessManagerPriceArrs[yearIndex]) { + bussinessPriceDecimal = new BigDecimal(bussinessManagerPriceArrs[yearIndex]); + } + BigDecimal operaterPriceDecimal = new BigDecimal(0); + if (null != operationManagerPriceArrs && null != operationManagerPriceArrs[yearIndex]) { + operaterPriceDecimal = new BigDecimal(operationManagerPriceArrs[yearIndex]); + } + if (null != rentPriceArrs && null != bussinessManagerPriceArrs && null != operationManagerPriceArrs + && rentPriceDecimal.compareTo(new BigDecimal(0)) > 0 && bussinessPriceDecimal.compareTo(new BigDecimal(0)) > 0 && operaterPriceDecimal.compareTo(new BigDecimal(0)) > 0) { + BigDecimal total = rentPriceDecimal.add(bussinessPriceDecimal).add(operaterPriceDecimal); + BigDecimal property = new BigDecimal(0); + if (null != propertyContractArrs) { + property = new BigDecimal(propertyContractArrs[yearIndex]); + } + total = total.add(property); + moneyShareRates[0] = rentPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); + moneyShareRates[1] = bussinessPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); + moneyShareRates[2] = operaterPriceDecimal.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); + moneyShareRates[3] = property.divide(total,Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP).toPlainString(); + }else { + SysConfig shareConfig = sysConfigService.getByKey(SysConfigConstant.rent_share_bill_rate, rentcontract); + if (null == shareConfig || StringUtils.isBlank(shareConfig.getConfigItemValue())) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"系统配置"+SysConfigConstant.rent_share_bill_rate+"未配置。"); + } + moneyShareRates = shareConfig.getConfigItemValue().split(","); + moneyShareRates[0] = new BigDecimal(moneyShareRates[0]).divide(new BigDecimal(100)).toPlainString(); + moneyShareRates[1] = new BigDecimal(moneyShareRates[1]).divide(new BigDecimal(100)).toPlainString(); + moneyShareRates[2] = new BigDecimal(moneyShareRates[2]).divide(new BigDecimal(100)).toPlainString(); + moneyShareRates[3] = new BigDecimal(moneyShareRates[3]).divide(new BigDecimal(100)).toPlainString(); + } + + String rentRate = moneyShareRates[0]; + String bussinessRate = moneyShareRates[1]; + String operaterRate = moneyShareRates[2]; + String propertyRate = moneyShareRates[3]; + //更新账单费用 + String rentneedpay = new BigDecimal(needpay).multiply(new BigDecimal(rentRate)).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); + List shopIdList = rentcontract.shopIdsByRentInfo(); + Map shopAreaRateMap = rentcontract.getRentShopArea(); + WxShopUsers suq = new WxShopUsers(); + suq.updateTenantInfo(rentcontract); + suq.setShopIds(shopIdList); + suq.setStatus(EnumShopUsersStatus.LIVE.getCode()); + Map shopUserMap = wxShopService.getShopUserMap(suq); + WxShop sq = new WxShop(); + sq.updateTenantInfo(sq); + sq.setIds(shopIdList); + Map shopMap = wxShopService.findShopMap(sq); + + List rentBill = generateRentBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract,rentBillList,rentneedpay,rentRate,startDate,endDate,createFrom); + + List propeBill = generatePropertyBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, propertyContractId,propertyBillList,startDate,endDate, needpay, propertyRate,createFrom); + + List bmbill = generateManageBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, startDate,endDate, needpay, bussinessRate, EnumBillAllType.RENT_BUSSINESS_MANAGE,createFrom); + + List ombill = generateManageBill(user,shopIdList,shopMap,shopUserMap,shopAreaRateMap,rentcontract, startDate,endDate, needpay, operaterRate, EnumBillAllType.RENT_OPERATION_MANAGE,createFrom); + + WxRentContractRevenueSetSalesVo vo = new WxRentContractRevenueSetSalesVo(); + vo.setTotal(needpay); + List blist = new ArrayList(); + blist.addAll(rentBill); + if (null != propeBill) { + blist.addAll(propeBill); + } + if (null != bmbill) { + blist.addAll(bmbill); + } + if (null != ombill) { + blist.addAll(ombill); + } + vo.setBillList(blist);; + return vo; + } + + + private void createBillAction(WxAllBill bill,String oldMoney,String newMoney,MallUserInfo user) { + WxBillAction wxBillAction = new WxBillAction(); + wxBillAction.setBillId(bill.getId()); + wxBillAction.setBillType(bill.getBillType()); + wxBillAction.setOldMoney(oldMoney); + wxBillAction.setNewMoney(newMoney); + wxBillAction.setDetails(EnumBillAction.UPDATE_BILL.getDescription(oldMoney, newMoney,null,null,null,null)); + wxBillAction.setAction(EnumBillAction.UPDATE_BILL.getCode()); + wxBillAction.setRemark(bill.getBillRemark()); + wxBillAction.setUserType(EnumSystemUserType.ADMIN.getCode()); + wxBillActionService.modifyBill(wxBillAction, user); + } + + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + public List generateManageBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, + Date starttime, Date endtime,String total,String rate,EnumBillAllType type,EnumBillExtraCreateFrom createFrom) { + WxAllBill bussinessmanageBill = new WxAllBill(); + bussinessmanageBill.updateTenantInfo(rentcontract); + bussinessmanageBill.setBillType(type.getCode()); + bussinessmanageBill.setEnergyFeesId(type.getEnergyFeesId()); + bussinessmanageBill.setRentContractId(rentcontract.getId()); + bussinessmanageBill.setIsPreview(EnumYesOrNo.NO.getCode()); + bussinessmanageBill.setNoExtraCreateFrom(EnumYesOrNo.YES.getCode()); + bussinessmanageBill.setStarttimeEqual(starttime); + bussinessmanageBill.setEndtimeEqual(endtime); + List bmbillList = wxAllBillMapper.findList(bussinessmanageBill); + BigDecimal bussinessmoney = new BigDecimal(total).multiply(new BigDecimal(rate)).setScale(Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + if (null != bmbillList && bmbillList.size() > 0 ) { + //查询每一个铺位的 + for (int i = 0 ; i < bmbillList.size() ; i ++) { + WxAllBill b = bmbillList.get(i); + String oldMoney = b.getReceivePay(); + //把原有的账单应收金额变为0 + b.setHistoryReceivePay(oldMoney); + b.setNeedPay("0");//如不设置会影响减免统计 + b.setReceivePay("0"); + b.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); + b.setUpdatetime(new Date()); + b.setUpdateBy(user.getId()); + b.setUpdateByName(user.getName()); + wxAllBillMapper.updateById(b); + + createBillAction(b,oldMoney,"0",user); + } + } + if (bussinessmoney.compareTo(new BigDecimal(0)) > 0 ) { + List billList = new ArrayList(); + for (int i = 0 ; i < shopIds.size(); i++) { + Long sid = shopIds.get(i); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + + String newmoney = bussinessmoney.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); + WxAllBill b = new WxAllBill(); + final IdWorker idWorker = IdWorker.get(); + b.setId(idWorker.nextId()); + b.updateTenantInfo(rentcontract); + b.setBillType(type.getCode()); + b.setEnergyFeesId(type.getEnergyFeesId()); + b.setRentContractId(rentcontract.getId()); + b.setIsPreview(EnumYesOrNo.NO.getCode()); + b.setCanEdit(EnumYesOrNo.NO.getCode()); + b.setShopId(sid); + String cusName = null; + if (null != shopUserMap) { + WxShopUsers su = shopUserMap.get(sid); + if (null != su) { + cusName = su.getName(); + } + } + b.setCusName(cusName); + b.setCreatetime(new Date()); + b.setCreateBy(user.getId()); + b.setCreateByName(user.getName()); + b.setUpdatetime(new Date()); + b.setUpdateBy(user.getId()); + b.setUpdateByName(user.getName()); + b.setPriceDetail(""); + b.setNeedPay(newmoney); + b.setReceivePay(newmoney); + b.setPay("0"); + b.setStarttime(starttime); + b.setEndtime(endtime); + b.setReceiveDate(starttime); + b.setPeriod(WxRentContractHelper.getPeriod(starttime)); + b.setBillRemark(createFrom.getMessage()+"自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + b.setExtraCreateFrom(createFrom.getCode()); + b.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + wxAllBillMapper.insert(b); + if (null != shopMap) { + WxShop s = shopMap.get(sid); + if ( null != s) { + b.setShopNumber(s.getShopNumber()); + } + } + billList.add(b); + } + return billList; + } + return null; + + } + + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + public List generatePropertyBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, + Long propertyContractId,List propertyBillList,Date starttime,Date endtime,String total,String rate,EnumBillExtraCreateFrom createFrom) { + BigDecimal bussinessmoney = new BigDecimal(total).multiply(new BigDecimal(rate)).setScale(Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + if (null != propertyBillList ) { + if (null != propertyBillList) { + for (int i = 0 ; i < propertyBillList.size(); i++){ + WxAllBill _rb = propertyBillList.get(i); + //把原有的账单应收金额变为0 + String oldMoney = _rb.getReceivePay(); + _rb.setHistoryReceivePay(_rb.getReceivePay()); + _rb.setNeedPay("0"); + _rb.setReceivePay("0"); + _rb.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); + _rb.setUpdatetime(new Date()); + _rb.setUpdateBy(user.getId()); + _rb.setUpdateByName(user.getName()); + wxAllBillMapper.updateById(_rb); + + createBillAction(_rb,oldMoney,"0",user); + } + } + } + if (bussinessmoney.compareTo(new BigDecimal(0)) > 0 ) { + List billList = new ArrayList(); + for (int i = 0 ; i < shopIds.size() ; i ++) { + Long sid = shopIds.get(i); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + + String newmoney = bussinessmoney.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); + WxAllBill bmbill = new WxAllBill(); + final IdWorker idWorker = IdWorker.get(); + bmbill.setId(idWorker.nextId()); + bmbill.updateTenantInfo(rentcontract); + bmbill.setBillType(EnumBillAllType.PROPERTY.getCode()); + bmbill.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); + bmbill.setRentContractId(rentcontract.getId()); + bmbill.setPropertyContractId(propertyContractId); + bmbill.setIsPreview(EnumYesOrNo.NO.getCode()); + bmbill.setCanEdit(EnumYesOrNo.NO.getCode()); + bmbill.setShopId(sid); + String cusName = null; + if (null != shopUserMap) { + WxShopUsers su = shopUserMap.get(sid); + if (null != su) { + cusName = su.getName(); + } + } + bmbill.setCusName(cusName); + bmbill.setCreatetime(new Date()); + bmbill.setCreateBy(user.getId()); + bmbill.setCreateByName(user.getName()); + bmbill.setUpdatetime(new Date()); + bmbill.setUpdateBy(user.getId()); + bmbill.setUpdateByName(user.getName()); + bmbill.setPriceDetail(""); + bmbill.setNeedPay(newmoney); + bmbill.setReceivePay(newmoney); + bmbill.setPay("0"); + bmbill.setStarttime(starttime); + bmbill.setEndtime(endtime); + bmbill.setReceiveDate(starttime); + bmbill.setPeriod(WxRentContractHelper.getPeriod(starttime)); + bmbill.setBillRemark(createFrom.getMessage()+".自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + bmbill.setExtraCreateFrom(createFrom.getCode()); + bmbill.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+bussinessmoney.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + wxAllBillMapper.insert(bmbill); + if (null != shopMap) { + WxShop s = shopMap.get(sid); + if ( null != s) { + bmbill.setShopNumber(s.getShopNumber()); + } + } + billList.add(bmbill); + } + return billList; + } + return null; + + } + + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + public List generateRentBill(MallUserInfo user,List shopIds,Map shopMap,Map shopUserMap,Map shopAreaRateMap,WxRentContract rentcontract, + List rentBillList,String money,String rate,Date starttime,Date endtime,EnumBillExtraCreateFrom createFrom) { + //rentBillList , 如果是多个房间,则就有几个租金账单 + if (null != rentBillList && rentBillList.size() > 0 ) { + //查询每一个铺位的 + for (int i = 0 ; i < rentBillList.size() ; i ++) { + WxAllBill b = rentBillList.get(i); + //把原有的账单应收金额变为0 + String oldMoney = b.getReceivePay(); + b.setHistoryReceivePay(oldMoney);//设置此值,供录入销售额的页面显示应收金额 + b.setNeedPay("0");//如不设置会影响减免统计 + b.setReceivePay("0"); + b.setBillRemark("账单金额重新计算生成新账单,原账单金额变为0"); + b.setUpdatetime(new Date()); + b.setUpdateBy(user.getId()); + b.setUpdateByName(user.getName()); + wxAllBillMapper.updateById(b); + + createBillAction(b,oldMoney,"0",user); + } + } + BigDecimal moneyb = new BigDecimal(money); + List billList = new ArrayList(); + for (int i = 0 ; i < shopIds.size(); i++) { + Long sid = shopIds.get(i); + BigDecimal shoprentArea = shopAreaRateMap.get(sid); + BigDecimal shoprate = shoprentArea.divide(new BigDecimal(rentcontract.getRentArea()),Constant.default_long_decimal_size,BigDecimal.ROUND_HALF_UP); + + String newmoney = moneyb.multiply(shoprate).setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString(); + WxAllBill bmbill = new WxAllBill(); + final IdWorker idWorker = IdWorker.get(); + bmbill.setId(idWorker.nextId()); + bmbill.updateTenantInfo(rentcontract); + bmbill.setBillType(EnumBillAllType.RENT.getCode()); + bmbill.setEnergyFeesId(EnumBillAllType.RENT.getEnergyFeesId()); + bmbill.setRentContractId(rentcontract.getId()); + bmbill.setIsPreview(EnumYesOrNo.NO.getCode()); + bmbill.setCanEdit(EnumYesOrNo.NO.getCode()); + bmbill.setShopId(sid); + String cusName = null; + if (null != shopUserMap) { + WxShopUsers su = shopUserMap.get(sid); + if (null != su) { + cusName = su.getName(); + } + } + bmbill.setCusName(cusName); + bmbill.setCreatetime(new Date()); + bmbill.setCreateBy(user.getId()); + bmbill.setCreateByName(user.getName()); + bmbill.setUpdatetime(new Date()); + bmbill.setUpdateBy(user.getId()); + bmbill.setUpdateByName(user.getName()); + bmbill.setPriceDetail(""); + bmbill.setNeedPay(newmoney); + bmbill.setReceivePay(bmbill.getNeedPay()); + bmbill.setPay("0"); + bmbill.setStarttime(starttime); + bmbill.setEndtime(endtime); + bmbill.setReceiveDate(starttime); + bmbill.setPeriod(WxRentContractHelper.getPeriod(starttime)); + bmbill.setBillRemark(createFrom.getMessage()+".自动计算创建,科目总应收金额为:"+moneyb.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + bmbill.setExtraCreateFrom(createFrom.getCode()); + bmbill.setMoneyChangeDetail("自动计算创建,科目总应收金额为:"+moneyb.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toPlainString()+"元[科目分摊比率为:"+rate+"]。"+"本铺分担比例"+shoprate.setScale(rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP).toEngineeringString()); + wxAllBillMapper.insert(bmbill); + if (null != shopMap) { + WxShop s = shopMap.get(sid); + if ( null != s) { + bmbill.setShopNumber(s.getShopNumber()); + } + } + billList.add(bmbill); + } + return billList; + } + + @Override + public void setContractSalesConfirm(WxRentContract rentcontract) { + WxRentContractRevenueSales sales = new WxRentContractRevenueSales(); + sales.updateTenantInfo(rentcontract); + sales.setRentContractId(rentcontract.getId()); + sales.setStarttime(rentcontract.getYearsBegin()); + sales.setEndtime(rentcontract.getYearsEnd()); + wxRentContractRevenueSalesMapper.updateConfirm(sales); + } + + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + @Override + public WxRentContractYearsSumVo calcuteYearsRevenueRentUp(MallUserInfo user,WxRentContract rentcontract) { + //查询销售总数 + WxRentContractRevenueSales rsq = new WxRentContractRevenueSales(); + rsq.updateTenantInfo(rentcontract); + rsq.setRentContractId(rentcontract.getId()); + rsq.setStarttime(rentcontract.getYearsBegin()); + rsq.setEndtime(rentcontract.getYearsEnd()); + BigDecimal sum = wxRentContractRevenueSalesMapper.findSumSalesMoneyValid(rsq); + if (null == sum || sum.compareTo(new BigDecimal(0)) <= 0 ) { + WxRentContractYearsSumVo vo = new WxRentContractYearsSumVo(); + vo.setTotalSales("0"); + vo.setTotalRevenue("0"); + vo.setBillReceivePay("0"); + return vo; + } + //更新已计算 + wxRentContractRevenueSalesMapper.updateCalcute(rsq); + + //如果有账单已经缴费或者付款,扣减,减免,冲抵等,则不允许操作。 + WxAllBill billd = new WxAllBill(); + billd.updateTenantInfo(rentcontract); + billd.setRentContractId(rentcontract.getId()); + //删除这个时间的,不设置结束时间,因为可能之前有了账单。,然后撤铺,结束时间虽然不一样,开始时间是一致的。 + billd.setStarttimeEqual(rentcontract.getYearsBegin()); + billd.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_TIAODIAN_HUISUAN.getCode()); + + Integer validCount = wxAllBillMapper.countValidBillCountByRentHuiSuan(billd); + if (null != validCount && validCount > 0 ) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"存在已经已经缴费或付款,扣减,减免,冲抵的账单,则不允许操作"); + } + + //删除未支付,未冲抵,未退款的之前的账单 + wxAllBillMapper.deleteByRentHuiSuan(billd); + + //计算跳点。 + BigDecimal[] jumppays = calcuteReveneuJump(sum, rentcontract,rentcontract.getYearsBegin(), rentcontract.getYearsEnd(),null); + BigDecimal jumpRevenuePay = jumppays[0]; + //BigDecimal jumpRentPay = jumppays[1]; + + //销售收入不满足一年怎么算。 + int yearDays = DateUtils.daysBetween(rentcontract.getYearsBegin(), rentcontract.getYearsEnd())+1; + //闰年是366 + if (yearDays >= 365) { + }else { + if (rentcontract.getDayPriceCalcute().intValue() == EnumRentDayPriceCalcute.AVERAGE_DAYS.getCode()) { + jumpRevenuePay = jumpRevenuePay.multiply(new BigDecimal(yearDays)).divide(new BigDecimal(12*rentcontract.getMonthAverageDays()),rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP); + }else { + jumpRevenuePay = jumpRevenuePay.multiply(new BigDecimal(yearDays)).divide(new BigDecimal(365),rentcontract.getDecimalSize(),BigDecimal.ROUND_HALF_UP); + } + } + + BigDecimal receivepay = new BigDecimal(0); + //查询合同租金所有应收的账单 + //查询所有租金+营业管理费+商业管理费账单的信息,因为设置销售额会自动的创建或者更新对应的账单 + WxAllBill rentBillq = new WxAllBill(); + rentBillq.updateTenantInfo(rentcontract); + rentBillq.setRentContractId(rentcontract.getId()); + List feesIdList = new ArrayList(); + feesIdList.add(EnumBillAllType.RENT.getEnergyFeesId()); + feesIdList.add(EnumBillAllType.RENT_BUSSINESS_MANAGE.getEnergyFeesId()); + feesIdList.add(EnumBillAllType.RENT_OPERATION_MANAGE.getEnergyFeesId()); + rentBillq.setEnergyFeesIds(feesIdList); + rentBillq.setIsPreview(EnumYesOrNo.NO.getCode()); + rentBillq.setStarttime(rentcontract.getYearsBegin()); + rentBillq.setEndtime(rentcontract.getYearsEnd()); + WxBillSum rentBillSum = wxAllBillMapper.getBillMonthSum(rentBillq); + if (null != rentBillSum) { + receivepay = receivepay.add(rentBillSum.getNeedPayNumber()); + } + + //查询对应的物业账单,包括录入销售额自动生成的 + if (null != rentcontract.getPropertyContractId()) { + WxAllBill propertyBillq = new WxAllBill(); + propertyBillq.updateTenantInfo(rentcontract); + propertyBillq.setPropertyContractId(rentcontract.getPropertyContractId()); + propertyBillq.setBillType(EnumBillAllType.PROPERTY.getCode()); + propertyBillq.setEnergyFeesId(EnumBillAllType.PROPERTY.getEnergyFeesId()); + propertyBillq.setIsPreview(EnumYesOrNo.NO.getCode()); + propertyBillq.setStarttime(rentcontract.getYearsBegin()); + propertyBillq.setEndtime(rentcontract.getYearsEnd()); + //prpoertyBillq.setExtraCreateFrom(EnumBillExtraCreateFrom.RNET_REVENUE_SALES.getCode()); + WxBillSum propertyBillSum = wxAllBillMapper.getBillMonthSum(propertyBillq); + if (null != propertyBillSum) { + receivepay = receivepay.add(propertyBillSum.getNeedPayNumber()); + } + } + + WxRentContractYearsSumVo vo = new WxRentContractYearsSumVo(); + vo.setTotalSales(sum.toPlainString()); + vo.setTotalRevenue(jumpRevenuePay.toPlainString()); + vo.setBillReceivePay(receivepay.toPlainString()); + + if ( new BigDecimal(vo.getOwe()).compareTo(new BigDecimal(0)) > 0) { + WxRentContractRevenueSetSalesVo svo = handelHuiSuanBills(user,rentcontract,vo.getOwe()); + vo.setBillList(svo.getBillList()); + } + + return vo; + } + + private WxRentContractRevenueSetSalesVo handelHuiSuanBills(MallUserInfo user,WxRentContract rentcontract,String owe) { + //计算每一年的基数 + List priceArrs = WxRentContractHelper.calcuteRentAndRevenuePrice(rentcontract); + String[] rentPriceArrs = priceArrs.get(0); + //String[] revenuePriceArrs = priceArrs.get(1); + //计算商业管理费 + String[] bussinessManagerPriceArrs = WxRentContractHelper.calcuteBussinessManagementFee(rentcontract); + //计算运营管理费 + String[] operationManagerPriceArrs = WxRentContractHelper.calcuteOperatingManagementFee(rentcontract); + + //物业费单价 + String[] propertyContractArrs = null; + List yearList = this.getYearList(rentPriceArrs.length, 12, rentcontract.getRentalStartDate(),null); + int yearIndex = 0; + for( int i = 0 ; i < yearList.size() ; i ++) { + Date yearEndDate = yearList.get(i); + if (rentcontract.getYearsBegin().before(yearEndDate) || rentcontract.getYearsEnd().equals(yearEndDate)) { + yearIndex = i-1; + break; + } + } + if (yearIndex <= 0 ) { + yearIndex = 0; + } + StringBuffer sb = new StringBuffer(""); + return handleBills(user,sb,rentcontract,null,owe,null,rentcontract.getYearsBegin(),rentcontract.getYearsEnd(),EnumBillExtraCreateFrom.RNET_TIAODIAN_HUISUAN,null,rentPriceArrs,bussinessManagerPriceArrs,operationManagerPriceArrs,propertyContractArrs,yearIndex); + } + + + @Override + public List findJumpList(WxRentContractRevenueJump jump) { + return wxRentContractRevenueJumpMapper.findList(jump); + } + + @Override + public BigDecimal calcuteContractUsedShopArea(WxRentContract wxRentContract,Long shopId) { + //根据合同区间查询已使用合同的总面积 + return null; + } + +} diff --git a/mallinkService/src/main/resources/mapper/WxRentContractMapper.xml b/mallinkService/src/main/resources/mapper/WxRentContractMapper.xml index 9835eb13f..b3d9e46af 100644 --- a/mallinkService/src/main/resources/mapper/WxRentContractMapper.xml +++ b/mallinkService/src/main/resources/mapper/WxRentContractMapper.xml @@ -36,6 +36,7 @@ + @@ -94,7 +95,7 @@ `day_price_calcute`,`first_bill_date_start`,`first_bill_date_end`,`month_average_days`,`free_period_remark`, `deposit`,cashtype_content_lsit,cashtype_lsit,`is_del`,`revenue_jumps_remark`, `updatetime`,`createtime`,`link_person`,`link_phone`,`link_address`, - `pay_account`,`filename`,`lease`,`type`,`revenue`,`revenue_ratio`,`revenue_ratio_way`,`revenue_ratio_set`,`adjust_ratio`,`adjust_period`,`pay_ratio`, + `pay_account`,`filename`,`lease`,`type`,`revenue`,`limit_revenue`,`revenue_ratio`,`revenue_ratio_way`,`revenue_ratio_set`,`adjust_ratio`,`adjust_period`,`pay_ratio`, `start_date`,`end_date`,`from_id`,`end_contract_time`,`revenue_fixed_rent_price`,`revenue_rent_price`, `apply_status`,`bank_name`,`fix_start_date`,`fix_end_date`,`pay_period_rate`,`create_by_name`,`update_by_name`, `business_type`,`rent_info`, `file_names`,price_unit,rent_price,other_rent_price_info,`subject_name`,rent_start_type,