package com.tenwa.reckon.executor; import java.io.InputStream; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import jbo.app.tenwa.calc.LC_CALC_CONDITION; import jbo.app.tenwa.calc.LC_CALC_CONDITION_TEMP; import jbo.app.tenwa.calc.LC_CALC_RULES_TEMP; import jbo.app.tenwa.calc.LC_CASH_FLOW; import jbo.app.tenwa.calc.LC_CASH_FLOW_TEMP; import jbo.app.tenwa.calc.LC_FUND_PLAN; import jbo.app.tenwa.calc.LC_FUND_PLAN_TEMP; import jbo.app.tenwa.calc.LC_FUND_RENT_ADJUST_TEMP; import jbo.app.tenwa.calc.LC_RENT_PLAN; import jbo.app.tenwa.calc.LC_RENT_PLAN_TEMP; import jbo.com.tenwa.entity.comm.flow.FLOW_BUSSINESS_OBJECT; import jbo.com.tenwa.lease.comm.LC_PAY_CONDTION_TEMP; import jbo.sys.CODE_LIBRARY; import com.amarsoft.app.util.ProductParamUtil; import com.amarsoft.are.jbo.BizObject; import com.amarsoft.are.jbo.BizObjectManager; import com.amarsoft.are.jbo.JBOException; import com.amarsoft.are.jbo.JBOFactory; import com.amarsoft.are.jbo.JBOTransaction; import com.amarsoft.are.util.json.JSONEncoder; import com.amarsoft.are.util.json.JSONObject; import com.amarsoft.awe.util.SqlObject; import com.tenwa.comm.exception.BusinessException; import com.tenwa.comm.util.jboutil.DataOperatorUtil; import com.tenwa.officetempalte.util.ExcelVersionEnum; import com.tenwa.quartz.StringUtil; import com.tenwa.reckon.bean.AdjustBean; import com.tenwa.reckon.bean.ConditionBean; import com.tenwa.reckon.bean.FundRentPlanBean; import com.tenwa.reckon.bean.FundRentPlanIrr; import com.tenwa.reckon.bean.KnowingTableBean; import com.tenwa.reckon.bean.TabCalBean; import com.tenwa.reckon.executor.rentChange.RentChangeExe; import com.tenwa.reckon.executor.rentTerminate.RentTerminateExe; import com.tenwa.reckon.help.CalYearRateFromRent; import com.tenwa.reckon.help.ConditionHelper; import com.tenwa.reckon.help.RentPlanContrCalDAOImpl; import com.tenwa.reckon.util.DateUtil; import com.tenwa.reckon.util.DictTools; import com.tenwa.reckon.util.ExcelReader; import com.tenwa.reckon.util.MoneyUtils; import com.tenwa.reckon.util.ObjectConvertUtils; import com.tenwa.reckon.util.TbBeanTools; /** * * @author chuang 租金测算主入口 */ public class CreateTransactionExecutor implements Transaction { private String calType; private String flowunid; private String rentOrRate; private String cleanLeasemoney; private String equipEndValue; private String contractId; private String paydayAdjust; private String plannumber; private String productId; private String planCName; private String startDate; public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } /** * 正常测算 */ @Override public String run() { JSONObject jsonObject = JSONObject.createObject(); String irr = ""; JBOTransaction tx=null; try { tx=JBOFactory.createJBOTransaction(); TabCalBean bean = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); this.deletePayCondition(this.getFlowunid(),bean.getPlanCName(), bean.getPlanCValue(), tx); DictTools.setYearRate(bean); this.preHandle(bean.getCb(),bean); if(bean.getCb().getRentOrRate().equals("rent")&&new BigDecimal(bean.getCb().getIncomeNumber()).multiply(new BigDecimal(bean.getCb().getRentValue())).compareTo(new BigDecimal(bean.getCb().getCleanLeaseMoney()))<0){ throw new BusinessException("按租金算年利率租金总和必须大于融资额"); } jsonObject.appendElement("year_rate", bean.getCb().getYearRate()); FundRentPlanBean rentPlan = this.createRentPlan(bean,tx); this.createFundPlan(rentPlan, bean,tx); irr = this.createCashFlow(bean,tx); jsonObject.appendElement("result", "true"); this.callBack(jsonObject, bean.getCb(), bean,rentPlan,false,tx); // 返回参数上做处理 return JSONEncoder.encode(jsonObject); }catch(BusinessException e){ try { tx.rollback(); } catch (JBOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } jsonObject.appendElement("message",e.getMessage()); return JSONEncoder.encode(jsonObject); }catch (Exception e) { try { tx.rollback(); } catch (JBOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); return irr; }finally{ if(tx!=null){ try { tx.commit(); } catch (JBOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 起租测算 */ @Override public String runOnhire() { JSONObject jsonObject = JSONObject.createObject(); String irr = ""; JBOTransaction tx=null; try { tx=JBOFactory.createJBOTransaction(); TabCalBean bean = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); FundRentPlanBean rentPlan = this.createRentPlan(bean,tx); this.createFundPlan(rentPlan, bean,tx); irr = this.createCashFlow(bean,tx); jsonObject.appendElement("result", "true"); this.callBack(jsonObject, bean.getCb(), bean,rentPlan,false,tx); // 返回参数上做处理 return JSONEncoder.encode(jsonObject); } catch (Exception e) { try { tx.rollback(); } catch (JBOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); return irr; }finally{ if(tx!=null){ try { tx.commit(); } catch (JBOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 车贷起租测算 * @param Sqlca * @return * @throws Exception */ public String carRunOnhire(com.amarsoft.awe.util.Transaction Sqlca) throws Exception { BizObjectManager Bm=JBOFactory.getBizObjectManager(LC_CALC_CONDITION.CLASS_NAME, Sqlca); BizObject boLCC = Bm.createQuery("contract_id='" + contractId + "'").getSingleResult(true); //获取期次 if(boLCC!=null){ int incomeNumber = boLCC.getAttribute("INCOME_NUMBER").getInt(); String periodType = boLCC.getAttribute("PERIOD_TYPE").getString(); String incomeIntervalMonth = boLCC.getAttribute("INCOME_INTERVAL_MONTH").getInt() + ""; List planDateList = getPlanDateList(incomeNumber, periodType, incomeIntervalMonth, startDate); String insertSql="insert into lc_rent_plan(id,quot_id,cust_id, project_id, project_plan_number,contract_id,contract_plan_number,payment_number,plan_list,plan_date,plan_status,rent,corpus,interest,penalty,corpus_business,interest_business,rent_adjust,all_remain_corpus,settle_method,coin,year_rate,memo,flowunid,inputuserid,inputorgid,inputtime,updateuserid,updateorgid,updatetime,interest_date) select id,quot_id,cust_id, project_id, project_plan_number,contract_id,contract_plan_number,payment_number,plan_list,plan_date,plan_status,rent,corpus,interest,penalty,corpus_business,interest_business,rent_adjust,all_remain_corpus,settle_method,coin,year_rate,memo,flowunid,inputuserid,inputorgid,inputtime,updateuserid,updateorgid,updatetime,interest_date from lc_pay_rent_plan where payment_number = '" + this.plannumber + "'"; Sqlca.executeSQL(new SqlObject(insertSql)); Connection conn = Sqlca.getConnection(Sqlca); PreparedStatement ps = conn.prepareStatement("update lc_rent_plan set plan_date = ? where payment_number = '" + this.plannumber + "' and plan_list = ?"); for(int i = 0; i < planDateList.size(); i ++) { ps.setString(1, planDateList.get(i)); ps.setString(2, (i + 1) + ""); ps.addBatch(); } ps.executeBatch(); boLCC.setAttributeValue("start_date", startDate); boLCC.setAttributeValue("lease_amt_date", startDate); if(planDateList.size()>0)boLCC.setAttributeValue("first_plan_date", planDateList.get(0)); if(planDateList.size()>1)boLCC.setAttributeValue("second_plan_date", planDateList.get(1)); Bm.saveObject(boLCC); Sqlca.executeSQL(new SqlObject("update lc_fund_plan set plan_date = '" + planDateList.get(planDateList.size() - 1) + "' where payment_number = '" + this.plannumber + "' and pay_type = 'pay_type_out' and fee_type != 'feetype10'")); Sqlca.executeSQL(new SqlObject("update lc_fund_plan set plan_date = '" + startDate + "' where payment_number = '" + this.plannumber + "' and pay_type = 'pay_type_in' and fee_type != 'feetype4' and fee_type != 'feetype12'")); Sqlca.executeSQL(new SqlObject("update lc_fund_plan set plan_date = '" + startDate + "' where payment_number = '" + this.plannumber + "' and fee_type = 'feetype10'")); this.setCashFlow(this.plannumber, this.productId, Sqlca); } return "success"; } public void setCashFlow(String paymentNumber, String productId, com.amarsoft.awe.util.Transaction Sqlca) throws Exception { String sql = ""; sql += "INSERT INTO LC_CASH_FLOW (id,project_id,project_plan_number,contract_id,contract_plan_number,payment_number"; sql += ",plan_date"; sql += ",fund_in"; sql += ",fund_in_details"; sql += ",fund_out"; sql += ",fund_out_details"; sql += ",net_flow"; //sql += ",flowunid";//create_date,creator_ "+DateUtil.getSystemDate()+"' create_date ,'"+SecurityUtil.getPrincipal().getId()+"' creator_" sql += " )"; sql +=" select replace(uuid(),'-','') id,max(t.project_id),max(t.project_plan_number),max(t.contract_id),max(t.contract_plan_number),max(t.payment_number),t.plan_date,sum(t.flowin) fundin,ifnull(group_concat(if(t.flowindetail='',null,t.flowindetail)),'-') fundindetails, "; sql +=" sum(t.flowout) fundout ,ifnull(group_concat(if(t.flowoutdetail='',null,t.flowoutdetail)),'-')fundoutdetails ,sum(t.cleanfow)netflow " ; sql +=" from (" ; sql +=" select cfrp.project_id,cfrp.project_plan_number,cfrp.contract_id,cfrp.contract_plan_number,cfrp.payment_number,cfrp.plan_date,cfrp.rent flowin,concat('第',cfrp.plan_list,'期租金:',format(cfrp.rent,2)) flowindetail,0 flowout,'' flowoutdetail,cfrp.rent-0 cleanfow " ; sql +=" from lc_rent_plan cfrp" ; sql +=" where cfrp.payment_number='" + paymentNumber + "'" ; sql +=" union all " ; sql +=" select fundplan.project_id,fundplan.project_plan_number,fundplan.contract_id,fundplan.contract_plan_number,fundplan.payment_number,fundplan.plan_date,if(fundplan.pay_type='pay_type_in',fundplan.plan_money,0)flowin, "; sql +=" if(fundplan.pay_type='pay_type_in',concat(tdd.itemname,':',format(fundplan.plan_money,2)),''), " ; sql +=" if(fundplan.pay_type='pay_type_out',fundplan.plan_money,0)flowout, " ; sql +=" if(fundplan.pay_type='pay_type_out',concat(tdd.itemname,':',format(fundplan.plan_money,2)),'')flowoutdetail, " ; sql +=" if(fundplan.pay_type='pay_type_in',fundplan.plan_money,-fundplan.plan_money) cleanfow " ; sql +=" from lc_fund_plan fundplan " ; sql +=" left join code_library tdd on fundplan.fee_type = tdd.itemno " ; sql +=" where fundplan.payment_number='" + paymentNumber + "'"; if(productId != null){ Map> productCashInIRRList = ProductParamUtil.getProductComponentType(productId, "PRD0315"); Set>> entry = productCashInIRRList.entrySet(); for(Entry> e : entry){ Map parameMap = e.getValue(); boolean flag = false; if("N".equals(parameMap.get("CostType10"))){ flag = true; } if(flag){ sql +=" and tdd.relativecode<>'"+e.getKey()+"' "; } } } sql +=" )t group by t.plan_date "; Sqlca.executeSQL(new SqlObject(sql)); } public static List getPlanDateList(int incomeNumber, String periodType, String incomeIntervalMonth, String startDate) throws ParseException { List planDate = new ArrayList(); Calendar calendar = Calendar.getInstance(); calendar.setTime(com.amarsoft.app.als.sys.tools.DateUtil.parseStringToDate(startDate, "yyyy/MM/dd")); int day = calendar.get(Calendar.DAY_OF_MONTH); int addMonth = Integer.parseInt(incomeIntervalMonth); for(int i = 0; i < incomeNumber; i ++) { if(!("period_type_1".equals(periodType) && i == 0)) {//期末加上还款间隔 calendar.add(Calendar.MONTH, addMonth); if(day != calendar.get(Calendar.DAY_OF_MONTH)) { if(day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); } else { calendar.set(Calendar.DAY_OF_MONTH, day); } } } planDate.add(com.amarsoft.app.als.sys.tools.DateUtil.formatDateToString(calendar.getTime(), "yyyy/MM/dd")); } return planDate; } /** * 中途中止 */ @Override public String runTerminate() throws Exception { JSONObject jsonObject = JSONObject.createObject(); JBOTransaction tx=null; try { tx=JBOFactory.createJBOTransaction(); //组装实体bean TabCalBean bean = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); BizObject bo = JBOFactory.getFactory().getManager(LC_FUND_RENT_ADJUST_TEMP.CLASS_NAME).createQuery("flowunid =:flowunid").setParameter("flowunid", flowunid).getSingleResult(true); //AdjustBean ab = ObjectConvertUtils.converBizObjectToBean(AdjustBean.class, bo); RentTerminateExe exe = new RentTerminateExe(tx); FundRentPlanBean rentPlan = exe.create(bean.getCb(), bo, bean); this.createFundPlan(rentPlan, bean,tx); this.createCashFlow(bean,tx); jsonObject.appendElement("result", "true"); this.callBack(jsonObject, bean.getCb(), bean,rentPlan,false,tx); // 返回参数上做处理 } catch (Exception e) { tx.rollback(); e.printStackTrace(); jsonObject.appendElement("result", "false"); }finally{ if(tx!=null){ tx.commit(); } } return JSONEncoder.encode(jsonObject); } /** * 删除方案 * @param tx * @return */ public String deletePlan(JBOTransaction tx){ Map condtion=new HashMap(); condtion.put("flowunid", flowunid); condtion.put(this.planCName, plannumber); try{ DataOperatorUtil.deleteJBOByCondtion(LC_CALC_CONDITION_TEMP.CLASS_NAME, condtion, tx); DataOperatorUtil.deleteJBOByCondtion(LC_CALC_RULES_TEMP.CLASS_NAME, condtion, tx); DataOperatorUtil.deleteJBOByCondtion(LC_CASH_FLOW_TEMP.CLASS_NAME, condtion, tx); DataOperatorUtil.deleteJBOByCondtion(LC_FUND_PLAN_TEMP.CLASS_NAME, condtion, tx); DataOperatorUtil.deleteJBOByCondtion(LC_RENT_PLAN_TEMP.CLASS_NAME, condtion, tx); }catch(Exception e){ e.printStackTrace(); return "删除失败!"; } return "删除成功!"; } /** * 删除付款前提 * @param flowunid * @param planCName * @param planCValue * @param tx * @throws JBOException */ public void deletePayCondition(String flowunid,String planCName,String planCValue,JBOTransaction tx) throws JBOException{ String sql=""; if(planCName.equals("PAYMENT_NUMBER")){ sql="delete from O where flowunid=:flowunid and PAYMENT_NUMBER=:plannumber"; }else{ sql="delete from O where flowunid=:flowunid and PLAN_NUMBER=:plannumber"; } JBOFactory.getBizObjectManager(LC_PAY_CONDTION_TEMP.CLASS_NAME, tx).createQuery(sql).setParameter("flowunid", flowunid).setParameter("plannumber", planCValue).executeUpdate(); } @Override public FundRentPlanBean createRentPlan(TabCalBean bean,JBOTransaction tx) throws Exception { ConditionBean cb = bean.getCb(); bean.setCb(cb); DictTools.getReversDict(cb); String settleMethod = cb.getSettleMethod(); FundRentPlanExecutor executor; FundRentPlanBean planBean = new FundRentPlanBean(); if (settleMethod.equals("even_interest")) { executor = new EvenInterestExecutor(tx); } else if (settleMethod.equals("even_corpus")||settleMethod.equals("even_corpus_rate")) { executor = new EvenCorpusExecutor(tx); }else if(settleMethod.equals("even_rent_day")){ executor=new EvenRentDayExecutor(tx); }else if(settleMethod.equals("even_subsection")){ executor=new EvenSubsectionExecutor(tx); }else if(settleMethod.equals("car_even_interest")){ executor=new CarEvenInterestExecutor(tx,bean.getProductId());//车贷均息入口 }else if(settleMethod.equals("car_even_rent")){ executor=new CarEvenRentExecutor(tx,bean.getProductId());//车贷等租入口 } else { executor = new EvenRentExecutor(tx); } if(bean.getCalType().equals("onHire_process")){ planBean = executor.createOnhire(bean); }else{ planBean= executor.create(bean,1); } if (planBean.getPlanDateList() != null&& planBean.getPlanDateList().size() > 0) { cb.setLastPlanDate(planBean.getPlanDateList().get(planBean.getPlanDateList().size() - 1));//末期租金还款日期 String endDate=DateUtil.addDate(cb.getStartDate(),DateUtil.TIME_MONTH,cb.getLeaseTerm()); cb.setEndDate(endDate); if(cb.getPeriodType().equals("0")){ cb.setEndPlanDate(endDate); }else{ cb.setEndPlanDate(DateUtil.addDate(cb.getLastPlanDate(),DateUtil.TIME_MONTH,cb.getIncomeIntervalMonth())); } } return planBean; } @Override public void createFundPlan(FundRentPlanBean planBean, TabCalBean bean,JBOTransaction tx) throws Exception { FundFundPlanExecutor fundFundExecutor = new FundFundPlanExecutor(); fundFundExecutor.run(bean.getCb(), bean, planBean,tx); } @Override public String createCashFlow(TabCalBean bean,JBOTransaction tx) throws Exception { CashFlowExecutor executor = new CashFlowExecutor(tx); return executor.run(bean.getCb(), bean); } /** * 已知租金测算 等额租金 均息法 根据租金算年利率 */ @Override public void preHandle(ConditionBean cb,TabCalBean bean) throws Exception { CalYearRateFromRent calYearRate = CalYearRateFromRent.getInstance(); calYearRate.calDo(cb,bean); } /** * 返写商务条件 租赁期限 IRR 项目粗利 还款次数 净授信额 */ @Override public void callBack(JSONObject jsonObject,ConditionBean cb,TabCalBean bean,FundRentPlanBean rentPlan,Boolean flag,JBOTransaction tx) throws Exception { ConditionHelper helper = ConditionHelper.getInstance(tx); helper.run(jsonObject, cb, bean, rentPlan,flag); } /** * 删除已知规则 */ @Override public String runDelteKnowing() throws Exception{ TabCalBean tcb=TbBeanTools.getTabInfo(this.calType); BizObjectManager bm=JBOFactory.getBizObjectManager(tcb.getRuleTb()); bm.createQuery("delete from O where flowunid=:flowunid and "+this.planCName+"=:plannumber").setParameter("flowunid",this.flowunid).setParameter("plannumber",this.plannumber).executeUpdate(); BizObjectManager bm2=JBOFactory.getBizObjectManager(tcb.getPeriodTb()); bm2.createQuery("delete from O where flowunid=:flowunid and "+this.planCName+"=:plannumber").setParameter("flowunid",this.flowunid).setParameter("plannumber",this.plannumber).executeUpdate(); return null; } /** * 删除 * @return * @throws Exception */ public String runDeleSubsection() throws Exception{ TabCalBean tcb=TbBeanTools.getTabInfo(this.calType); BizObjectManager bm=JBOFactory.getBizObjectManager(tcb.getSubsectionTb()); bm.createQuery("delete from O where flowunid=:flowunid and "+this.planCName+"=:plannumber").setParameter("flowunid",this.flowunid).setParameter("plannumber",this.plannumber).executeUpdate(); return null; } /** * 已知规则 * @throws Exception */ @SuppressWarnings("unchecked") @Override public String checkKnowingConfig() throws Exception { try { TabCalBean tcb=TbBeanTools.getTabInfo(this.calType); BizObjectManager manager = JBOFactory.getBizObjectManager(tcb.getRuleTb()); BigDecimal corpusTotal = new BigDecimal(MoneyUtils.getZeroStr(this.cleanLeasemoney)).subtract(new BigDecimal(MoneyUtils.getZeroStr(this.equipEndValue))); List libX =manager.createQuery("flowunid=:flowunid and "+this.planCName+"=:plannumber").setParameter("plannumber",this.plannumber).setParameter("flowunid", this.flowunid).getResultList(false); BigDecimal planMoneyTotal = BigDecimal.ZERO; for(BizObject obj : libX){ int startList = obj.getAttribute("start_list").getInt(); int endList = obj.getAttribute("end_list").getInt(); for(int i = startList ; i<=endList ; i++){ planMoneyTotal = planMoneyTotal.add(new BigDecimal(obj.getAttribute("plan_money").getDouble())); } } if(this.rentOrRate.equals("knowing_rent")){ if(planMoneyTotal.compareTo(corpusTotal) > 0){ return ""; }else{ return "租金总额需大于融资额!"; } }else if(this.rentOrRate.equals("knowing_corpus")){ if(planMoneyTotal.compareTo(corpusTotal) == 0){ return ""; }else{ return "本金规则本金总额需等于融资额!"; } } BizObjectManager bm=JBOFactory.getBizObjectManager(tcb.getPeriodTb()); List periodList=bm.createQuery("flowunid=:flowunid and "+this.planCName+"=:plannumber").setParameter("plannumber",this.plannumber).setParameter("flowunid", this.flowunid).getResultList(false); planMoneyTotal=BigDecimal.ZERO; for(BizObject bo:periodList){ planMoneyTotal=planMoneyTotal.add(new BigDecimal(bo.getAttribute("PLAN_MONEY").getString())); } if(this.rentOrRate.equals("rent_period")){ if(planMoneyTotal.compareTo(corpusTotal) > 0){ return ""; }else{ return "租金总额需大于融资额!"; } }else if(this.rentOrRate.equals("corpus_period")){ if(planMoneyTotal.compareTo(corpusTotal) == 0){ return ""; }else{ return "本金规则本金总额需等于融资额!"; } } return ""; } catch (JBOException e) { e.printStackTrace(); return "服务器繁忙,请稍后再试!"; } } /** * 租金计划变更 */ @Override public String runRentChange() throws Exception{ JSONObject jsonObject = JSONObject.createObject(); JBOTransaction tx=null; try { tx=JBOFactory.createJBOTransaction(); //组装实体bean TabCalBean bean = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); BizObject bo = JBOFactory.getFactory().getManager(LC_FUND_RENT_ADJUST_TEMP.CLASS_NAME).createQuery("flowunid =:flowunid and payment_number=:plannumber").setParameter("flowunid", flowunid).setParameter("plannumber", plannumber).getSingleResult(true); AdjustBean ab = ObjectConvertUtils.converBizObjectToBean(AdjustBean.class, bo); RentChangeExe exe = new RentChangeExe(tx); ConditionBean csOld=bean.getCb().clone(); csOld.setOldIncomeNumber(csOld.getIncomeNumber()); FundRentPlanBean rentPlan = exe.create(bean.getCb(), ab, bean); //设置新的 csOld.setIncomeNumber(ab.getAdjustList()); csOld.setLeaseTerm(bean.getCb().getLeaseTerm()); csOld.setYearRate(ab.getYearRate().toString()); bean.setCb(csOld); //this.createFundPlan(rentPlan, bean,tx); this.createCashFlow(bean,tx); jsonObject.appendElement("result", "true"); this.callBack(jsonObject, bean.getCb(), bean,rentPlan,true,tx); // 返回参数上做处理 } catch (Exception e) { tx.rollback(); e.printStackTrace(); jsonObject.appendElement("result", "false"); }finally{ if(tx!=null){ tx.commit(); } } return JSONEncoder.encode(jsonObject); } /** * 取消变更 */ @Override public String cancelRentChange(JBOTransaction tx) throws Exception { BizObjectManager manager = JBOFactory.getFactory().getManager(LC_FUND_RENT_ADJUST_TEMP.CLASS_NAME); //删除变更记录 BizObject bo = manager.createQuery("flowunid =:flowunid and payment_number=:plannumber").setParameter("flowunid", flowunid).setParameter("plannumber", plannumber).getSingleResult(true); if(bo != null ){ manager.deleteObject(bo); } //重新复制正式表租金计划到临时表 Map fromCondition = new HashMap(); Map toCondition=new HashMap(); toCondition.put("flowunid", this.getFlowunid()); toCondition.put("payment_number", this.getPlannumber()); Map otherProperty = new HashMap(); fromCondition.put("payment_number",this.getPlannumber()); otherProperty.put("flowunid", flowunid); DataOperatorUtil.copyJBOSet(LC_RENT_PLAN.CLASS_NAME, fromCondition,LC_RENT_PLAN_TEMP.CLASS_NAME ,toCondition, otherProperty,null, tx); DataOperatorUtil.copyJBOSet(LC_CALC_CONDITION.CLASS_NAME, fromCondition,LC_CALC_CONDITION_TEMP.CLASS_NAME ,toCondition, otherProperty,null, tx); DataOperatorUtil.copyJBOSet(LC_FUND_PLAN.CLASS_NAME, fromCondition,LC_FUND_PLAN_TEMP.CLASS_NAME ,toCondition, otherProperty,null, tx); DataOperatorUtil.copyJBOSet(LC_CASH_FLOW.CLASS_NAME, fromCondition,LC_CASH_FLOW_TEMP.CLASS_NAME ,toCondition, otherProperty,null, tx); return "true"; } /** * 判断租金变更信息是否存在 */ @Override public String checkIsRentChange() throws Exception { try{ BizObject bo = JBOFactory.getFactory().getManager(LC_FUND_RENT_ADJUST_TEMP.CLASS_NAME).createQuery("flowunid =:flowunid and PAYMENT_NUMBER=:plannumber").setParameter("flowunid", flowunid).setParameter("plannumber", plannumber).getSingleResult(true); if(bo == null){ return "true"; }else{ return "false"; } }catch(Exception e){ return "false"; } } /** * 判断商务条件是否保存 */ @Override public String checkIsSaveCondition() throws Exception { try{ TabCalBean tcb=TbBeanTools.getTabInfo(this.calType); BizObject bo = JBOFactory.getFactory().getManager(tcb.getCondition_tb()).createQuery("flowunid =:flowunid and "+this.planCName+"='"+this.plannumber+"'").setParameter("flowunid", flowunid).getSingleResult(true); if(bo == null){ return "false"; }else{ return "true"; } }catch(Exception e){ return "false"; } } @SuppressWarnings("unchecked") public String updateConditionFund() throws Exception{ List funds=JBOFactory.createBizObjectQuery(LC_FUND_PLAN_TEMP.CLASS_NAME,"flowunid=:flowunid and payment_number=:paymentnumber").setParameter("flowunid",this.flowunid).setParameter("paymentnumber",this.plannumber).getResultList(false); BizObjectManager bm=JBOFactory.getBizObjectManager(LC_CALC_CONDITION_TEMP.CLASS_NAME); BizObject condition=bm.createQuery("flowunid=:flowunid and payment_number=:paymentnumber").setParameter("flowunid",this.flowunid).setParameter("paymentnumber",this.plannumber).getSingleResult(true); Map map=new HashMap(); List fundConfig=JBOFactory.createBizObjectQuery(CODE_LIBRARY.CLASS_NAME,"codeno='FeeType'").getResultList(false); Map fundCol=new HashMap(); for(BizObject config:fundConfig){ map.put(config.getAttribute("itemno").getString(),BigDecimal.ZERO); fundCol.put(config.getAttribute("itemno").getString(),config.getAttribute("relativecode").getString()); if(config.getAttribute("itemno").getString().equals("feetype16")){//抵扣保证金 fundCol.put(config.getAttribute("itemno").getString(),"CAUTION_DEDUCTION_MONEY"); } if(config.getAttribute("itemno").getString().equals("feetype17")){//退还保证金 fundCol.put(config.getAttribute("itemno").getString(),"CAUTION_MONEY_REMAIN"); } if(config.getAttribute("itemno").getString().equals("feetype12")){//期末余值 fundCol.remove(config.getAttribute("itemno").getString()); map.remove(config.getAttribute("itemno").getString()); } } for(BizObject fund:funds){ map.put(fund.getAttribute("FEE_TYPE").getString(), map.get(fund.getAttribute("FEE_TYPE").getString()).add(new BigDecimal(fund.getAttribute("PLAN_MONEY").getString()))); } if(map.get("feetype2").compareTo(map.get("feetype16").add(map.get("feetype17")))!=0){ return "保证金不等于保证金抵扣加保证金退还,请检查"; } Map fundColMoney=new HashMap(); for(String key:map.keySet()){ fundColMoney.put(fundCol.get(key), map.get(key).toString()); } Map> fundmap=ProductParamUtil.getProductComponentType(productId, "PRD0315"); Map fundColMoneyRatio=new HashMap(); fundColMoneyRatio.putAll(fundColMoney); for(Map.Entry entry:fundColMoney.entrySet()){ String key=entry.getKey(); if(fundmap.containsKey(key)&&!key.equals("EQUIP_AMT")){ String q= StringUtil.nullToString(fundmap.get(key).get("CostType07")); if(q.equals("EquipAmt")){ fundColMoneyRatio.put(key+"_RATIO",new BigDecimal(fundColMoney.get(key)).multiply(new BigDecimal(100)).divide(new BigDecimal(condition.getAttribute("EQUIP_AMT").getString()),6,BigDecimal.ROUND_HALF_UP).toString() ); }else if(q.equals("EquipEndAmt")){ fundColMoneyRatio.put(key+"_RATIO",new BigDecimal(fundColMoney.get(key)).multiply(new BigDecimal(100)).divide(new BigDecimal(condition.getAttribute("CLEAN_LEASE_MONEY").getString()),6,BigDecimal.ROUND_HALF_UP).toString() ); } } } condition.setAttributesValue(fundColMoneyRatio); bm.saveObject(condition); return "true"; } /** * 更新现金流 * @return * @throws Exception */ @Override public String updateCashFlow() throws Exception { JSONObject jsonObject = JSONObject.createObject(); JBOTransaction tx=null; try { tx=JBOFactory.createJBOTransaction(); BizObject flow=JBOFactory.createBizObjectQuery(FLOW_BUSSINESS_OBJECT.CLASS_NAME,"flow_unid=:flowunid").setParameter("flowunid", this.flowunid).getSingleResult(false); String productId; if(flow!=null){ productId=flow.getAttribute("productId").getString(); }else{ productId=this.productId; } TabCalBean tcb = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); RentPlanContrCalDAOImpl rpccdi = new RentPlanContrCalDAOImpl(); FundRentPlanBean frpb = rpccdi.getRentAndDateByTcb(tcb, 1,tx); this.createCashFlow(tcb,tx); jsonObject.appendElement("result", "true"); jsonObject.appendElement("IRR",tcb.getCb().getIrr()); this.callBack(jsonObject, tcb.getCb(), tcb,frpb,false,tx); } catch (Exception e) { tx.rollback(); jsonObject.appendElement("result", "false"); }finally{ if(tx!=null){ tx.commit(); } } return JSONEncoder.encode(jsonObject); } /** * 导入租金表 本金表 * @param fileName * @param sourceFile * @param sourceMap * @return * @throws Exception */ public String importRentOrCorpusTable(String fileName, InputStream sourceFile,MapsourceMap) throws Exception{ TabCalBean tcb=TbBeanTools.getTabInfo(sourceMap.get("calType")); String suffix = fileName.substring(fileName.lastIndexOf(".")+1); ExcelVersionEnum type; if(suffix.equalsIgnoreCase("xlsx")){ type = ExcelVersionEnum.VERSION2007; }else{ type = ExcelVersionEnum.VERSION2003; } List> result = ExcelReader.readExcelDatas(sourceFile,type); List tableBeans = new ArrayList(); for(int i = 0 ; i < result.size() ; i++ ){ MaptableBean = result.get(i); for(Map.Entry entry:tableBean.entrySet()){ if(entry.getKey().equals("plandate")){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日"); Date date=sdf.parse(tableBean.get(entry.getKey())); tableBean.put(entry.getKey(), DateUtil.getSystemTimeByFormat(date, "yyyy/MM/dd")); } } Map map = new HashMap(); map.putAll(tableBean); KnowingTableBean table = ObjectConvertUtils.convertMapToBean(KnowingTableBean.class, map); KnowingTableBean.checkKnowingTableBean(table, i); tableBeans.add(table); } //先校验本金之和是否等于融资额 BigDecimal moneyTotal = BigDecimal.ZERO; Date upperDate=null; for(KnowingTableBean tablePlan : tableBeans){ moneyTotal = moneyTotal.add(new BigDecimal(tablePlan.getPlanMoney())); if(upperDate!=null&&DateUtil.getIntervalDays(DateUtil.getTimeByFormat(tablePlan.getPlandate(), "yyyy/MM/dd"), upperDate)>0){ throw new BusinessException("上传Excel中第"+tablePlan.getPalnList()+"期 日期小于上一期,请检查!"); }else{ upperDate=DateUtil.getTimeByFormat(tablePlan.getPlandate(), "yyyy/MM/dd"); } } String cleanLeaseMoney=sourceMap.get("CLEAN_LEASE_MONEY"); String rentOrRate=sourceMap.get("RENT_OR_RATE"); if(rentOrRate.equals("rent_period")&&moneyTotal.compareTo(new BigDecimal(cleanLeaseMoney))<=0){ throw new BusinessException("上传Excel中租金之和需大于融资额,请核实后再进行上传!"); }else if(rentOrRate.equals("corpus_period")&&moneyTotal.compareTo(new BigDecimal(cleanLeaseMoney).subtract(new BigDecimal(sourceMap.get("EQUIP_END_VALUE"))))!=0){ throw new BusinessException("上传Excel中的本金之和需要等于融资额,请核实后再进行上传!"); } BizObjectManager bm=JBOFactory.getBizObjectManager(tcb.getPeriodTb()); bm.createQuery("delete from O where flowunid=:flowunid and "+sourceMap.get("planCName")+"=:plannumber").setParameter("flowunid", sourceMap.get("flowunid")).setParameter("plannumber", sourceMap.get("plannumber")).executeUpdate(); JSONObject json=JSONObject.createObject(); json.appendElement("firstplan",""); json.appendElement("second",""); for(KnowingTableBean tablePlan : tableBeans){ BizObject bo=bm.newObject(); bo.setAttributeValue("PLAN_LIST", tablePlan.getPalnList()); bo.setAttributeValue("PLAN_DATE", tablePlan.getPlandate()); bo.setAttributeValue("PLAN_MONEY", tablePlan.getPlanMoney()); bo.setAttributeValue("flowunid", sourceMap.get("flowunid")); bo.setAttributeValue(sourceMap.get("planCName"),sourceMap.get("plannumber")); bm.saveObject(bo); if(tablePlan.getPalnList().equals("1")){ json.appendElement("firstplan", tablePlan.getPlandate()); }else if(tablePlan.getPalnList().equals("2")){ json.appendElement("second", tablePlan.getPlandate()); } } json.appendElement("index", tableBeans.size()); return JSONEncoder.encode(json); } /** * 不规则测算 导入租金计划 * */ @Override public int importRentPlan(String fileName, InputStream sourceFile,MapsourceMap) throws Exception { JBOTransaction tx=null; JSONObject jsonObject = JSONObject.createObject(); try{ tx=JBOFactory.createJBOTransaction(); this.flowunid = sourceMap.get("flowunid"); this.plannumber=sourceMap.get("plannumber"); this.calType=sourceMap.get("calType"); TabCalBean bean = TbBeanTools.getTabInfo(calType, flowunid,plannumber,productId); IrregularRentCalExecutor exe = new IrregularRentCalExecutor(tx); List irrPlans = exe.preCreate(fileName, sourceFile, bean); FundRentPlanBean rentPlan = exe.create(bean, 1, irrPlans); bean.getCb().setFirstPlanDate(rentPlan.getPlanDateList().get(0)); if(rentPlan.getPlanDateList().size()>1){//当不规则导入时,租金期次等于1,则不需要设置第二期租金支付日 bean.getCb().setSecondPlanDate(rentPlan.getPlanDateList().get(1)); } this.createFundPlan(rentPlan, bean,tx); this.createCashFlow(bean,tx); jsonObject.appendElement("result", "true"); bean.getCb().setIncomeNumber(rentPlan.getRentList().size()); this.callBack(jsonObject, bean.getCb(), bean,rentPlan,false,tx); // 返回参数上做处理 return irrPlans.size(); }catch(BusinessException e){ tx.rollback(); throw e; }catch(Exception e){ tx.rollback(); return 0; }finally{ if(tx!=null){ tx.commit(); } } } /** * 租金计划变更 更新现金流前先计算增值税 * @param tx * @return * @throws Exception */ public String updateRentTax() throws Exception{ BizObjectManager bm=JBOFactory.getBizObjectManager(LC_RENT_PLAN_TEMP.CLASS_NAME); @SuppressWarnings("unchecked") List rentplans=bm.createQuery("select * from O where flowunid=:flowunid and payment_number=:payment_number order by plan_list") .setParameter("flowunid",this.flowunid).setParameter("payment_number",this.plannumber).getResultList(true); //获取税率 /*BizObject projOrCont=JBOFactory.createBizObjectQuery(LB_CONTRACT_INFO_TEMP.CLASS_NAME,"flowunid=:flowunid").setParameter("flowunid",this.flowunid).getSingleResult(false); String lesae="02";//回租 if(projOrCont!=null&&projOrCont.getAttribute("LEAS_FORM").getString().length()>0){ lesae=projOrCont.getAttribute("LEAS_FORM").getString(); } BizObject flow=JBOFactory.createBizObjectQuery(FLOW_BUSSINESS_OBJECT.CLASS_NAME,"flow_unid=:flowunid").setParameter("flowunid", flowunid).getSingleResult(false); String productId=flow.getAttribute("productId").getString(); Map>> map=ProductParamUtil.getProductComponentDecisionTable(productId, "PRD0340","LeasForm","TaxRate"); BigDecimal rate=BigDecimal.ONE; for(int i=0;i