package cn.com.lzt.contractsaleinvoice.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.Validator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jeecgframework.core.beanvalidator.BeanValidators; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.exception.BusinessException; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.DateUtils; import org.jeecgframework.core.util.ExceptionUtil; import org.jeecgframework.core.util.MyBeanUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.tag.vo.datatable.SortDirection; import org.jeecgframework.web.system.pojo.base.DictEntity; import org.jeecgframework.web.system.pojo.base.TSUser; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.UriComponentsBuilder; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.xcgl.utils.XcglDateUtils; import cn.com.lzt.contractsale.entity.ContractSaleEntity; import cn.com.lzt.contractsaleinvoice.entity.ContractSaleInvoiceEntity; import cn.com.lzt.contractsaleinvoice.service.ContractSaleInvoiceServiceI; import cn.com.lzt.goodsinfo.entity.TBGoodsInfoEntity; import cn.com.lzt.priceinfo.entity.TBPriceInfoEntity; import cn.com.lzt.tools.DecimalUtils; /** * @Title: Controller * @Description: 销售开票 * @author onlineGenerator * @date 2019-05-12 11:45:01 * @version V1.0 * */ @Controller @RequestMapping("/contractSaleInvoiceController") public class ContractSaleInvoiceController extends BaseController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(ContractSaleInvoiceController.class); @Autowired private ContractSaleInvoiceServiceI contractSaleInvoiceService; @Autowired private SystemService systemService; @Autowired private Validator validator; /** * 销售开票列表 页面跳转 * * @return */ @RequestMapping(params = "list") public ModelAndView list(HttpServletRequest request) { return new ModelAndView("cn/com/lzt/contractsaleinvoice/contractSaleInvoiceList"); } /** * 销售开票列表 页面跳转 * * @return */ @RequestMapping(params = "listByContractid") public ModelAndView listByContractid(String contractid,HttpServletRequest request) { if(StringUtils.isEmpty(contractid)) contractid = "1"; request.setAttribute("contractid", contractid); return new ModelAndView("cn/com/lzt/contractsaleinvoice/contractSaleInvoiceListReadonly"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(ContractSaleInvoiceEntity contractSaleInvoice,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(ContractSaleInvoiceEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, contractSaleInvoice, request.getParameterMap()); try{ //自定义追加查询条件 }catch (Exception e) { throw new BusinessException(e.getMessage()); } cq.add(); this.contractSaleInvoiceService.getDataGridReturn(cq, true); if (StringUtils.isNotEmpty(contractSaleInvoice.getContractid())) { List resualtlist = dataGrid.getResults(); Double sum = 0.0; if (resualtlist.size() != 0) { for (ContractSaleInvoiceEntity aa : resualtlist) { sum = sum + Double.valueOf(aa.getInvoiceamount()); } } // 格式化为小数点2位数 DecimalFormat df = new DecimalFormat("#.00"); String total_salary = df.format(sum); dataGrid.setFooter("invoiceamount:累计开票:,periodBegin:"+total_salary); } TagUtil.datagrid(response, dataGrid); } /** * 删除销售开票 * * @return */ @RequestMapping(params = "doDel") @ResponseBody public AjaxJson doDel(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); contractSaleInvoice = systemService.getEntity(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); message = "销售开票删除成功"; try{ contractSaleInvoiceService.delete(contractSaleInvoice); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "销售开票删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 批量删除销售开票 * * @return */ @RequestMapping(params = "doBatchDel") @ResponseBody public AjaxJson doBatchDel(String ids,HttpServletRequest request){ String message = null; AjaxJson j = new AjaxJson(); message = "销售开票删除成功"; try{ for(String id:ids.split(",")){ ContractSaleInvoiceEntity contractSaleInvoice = systemService.getEntity(ContractSaleInvoiceEntity.class, id ); contractSaleInvoiceService.delete(contractSaleInvoice); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "销售开票删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加销售开票 * * @param ids * @return */ @RequestMapping(params = "doAdd") @ResponseBody public AjaxJson doAdd(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "销售开票添加成功"; try{ String sql = " FROM ContractSaleInvoiceEntity where invoiceno = ?"; List hisIncoiceList = systemService.findHql(sql, contractSaleInvoice.getInvoiceno()); if(hisIncoiceList.size() > 0) { j.setSuccess(false); j.setMsg("发票号已经存在,请重新填写"); return j; } //设置初始状态 contractSaleInvoice.setBusstatus(Globals.CONTRACT_STATUS_INVOICE); contractSaleInvoice.setIncomeamount(DecimalUtils.ZERO); TSUser user = ResourceUtil.getSessionUser(); contractSaleInvoice.setInvoiceopt(user.getId()); contractSaleInvoice.setInvoiceoptname(user.getRealName()); setFinancialData(contractSaleInvoice); contractSaleInvoiceService.save(contractSaleInvoice); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); //回写合同开票合计 updateContractSaleTotalInvoice(contractSaleInvoice.getContractid(), contractSaleInvoice.getInvoiceamount()); }catch(Exception e){ e.printStackTrace(); message = "销售开票添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 更新销售开票 * * @param ids * @return */ @RequestMapping(params = "doUpdate") @ResponseBody public AjaxJson doUpdate(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "销售开票更新成功"; String msg = checkEntity(contractSaleInvoice); if(StringUtils.isNotEmpty(msg)) { j.setSuccess(false); j.setMsg(msg); return j; } ContractSaleInvoiceEntity t = contractSaleInvoiceService.get(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); try { Double changeAmount = DecimalUtils.ZERO; if(StringUtils.isEmpty(t.getContractid())) { changeAmount = contractSaleInvoice.getInvoiceamount(); }else { changeAmount = contractSaleInvoice.getInvoiceamount() - t.getInvoiceamount(); } MyBeanUtils.copyBeanNotNull2Bean(contractSaleInvoice, t); setFinancialData(t); contractSaleInvoiceService.saveOrUpdate(t); updateContractSaleTotalInvoice(t.getContractid(), changeAmount); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "销售开票更新失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 销售开票新增页面跳转 * * @return */ @RequestMapping(params = "goAdd") public ModelAndView goAdd(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest req) { if (StringUtil.isNotEmpty(contractSaleInvoice.getId())) { contractSaleInvoice = contractSaleInvoiceService.getEntity(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); }else{ ContractSaleEntity contractSale = systemService.getEntity(ContractSaleEntity.class, contractSaleInvoice.getContractid()); contractSaleInvoice.setContractname(contractSale.getName()); contractSaleInvoice.setProjectid(contractSale.getProjectid()); contractSaleInvoice.setProjectname(contractSale.getProjectname()); contractSaleInvoice.setCustomerid(contractSale.getCustomerid()); contractSaleInvoice.setCustomername(contractSale.getCustomername()); contractSaleInvoice.setFeetype("wuyefee"); contractSaleInvoice.setInvoicetype("special"); contractSaleInvoice.setInvoicedate(new Date()); } req.setAttribute("contractSaleInvoicePage", contractSaleInvoice); return new ModelAndView("cn/com/lzt/contractsaleinvoice/contractSaleInvoice-add"); } /** * 销售开票编辑页面跳转 * * @return */ @RequestMapping(params = "goUpdate") public ModelAndView goUpdate(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest req) { if (StringUtil.isNotEmpty(contractSaleInvoice.getId())) { contractSaleInvoice = contractSaleInvoiceService.getEntity(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); req.setAttribute("contractSaleInvoicePage", contractSaleInvoice); } return new ModelAndView("cn/com/lzt/contractsaleinvoice/contractSaleInvoice-update"); } /** * 导入功能跳转 * * @return */ @RequestMapping(params = "upload") public ModelAndView upload(HttpServletRequest req) { req.setAttribute("controller_name","contractSaleInvoiceController"); return new ModelAndView("common/upload/pub_excel_upload"); } /** * 导出excel * * @param request * @param response */ @RequestMapping(params = "exportXls") public String exportXls(ContractSaleInvoiceEntity contractSaleInvoice,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { CriteriaQuery cq = new CriteriaQuery(ContractSaleInvoiceEntity.class, dataGrid); cq.addOrder("createDate", SortDirection.desc); cq.add(); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, contractSaleInvoice, request.getParameterMap()); List contractSaleInvoices = this.contractSaleInvoiceService.getListByCriteriaQuery(cq,false); modelMap.put(NormalExcelConstants.FILE_NAME,"销售合同开票收款"+DateUtils.yyyymmddhhmmss.format(new Date())); modelMap.put(NormalExcelConstants.CLASS,ContractSaleInvoiceEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("销售合同开票收款列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,contractSaleInvoices); return NormalExcelConstants.JEECG_EXCEL_VIEW; } /** * 导出excel 使模板 * * @param request * @param response */ @RequestMapping(params = "exportXlsByT") public String exportXlsByT(ContractSaleInvoiceEntity contractSaleInvoice,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { modelMap.put(NormalExcelConstants.FILE_NAME,"销售开票"); modelMap.put(NormalExcelConstants.CLASS,ContractSaleInvoiceEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("销售开票列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList()); return NormalExcelConstants.JEECG_EXCEL_VIEW; } @SuppressWarnings("unchecked") @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map fileMap = multipartRequest.getFileMap(); for (Map.Entry entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List listContractSaleInvoiceEntitys = ExcelImportUtil.importExcel(file.getInputStream(),ContractSaleInvoiceEntity.class,params); for (ContractSaleInvoiceEntity contractSaleInvoice : listContractSaleInvoiceEntitys) { contractSaleInvoiceService.save(contractSaleInvoice); } j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return j; } @RequestMapping(method = RequestMethod.GET) @ResponseBody public List list() { List listContractSaleInvoices=contractSaleInvoiceService.getList(ContractSaleInvoiceEntity.class); return listContractSaleInvoices; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public ResponseEntity get(@PathVariable("id") String id) { ContractSaleInvoiceEntity task = contractSaleInvoiceService.get(ContractSaleInvoiceEntity.class, id); if (task == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(task, HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity create(@RequestBody ContractSaleInvoiceEntity contractSaleInvoice, UriComponentsBuilder uriBuilder) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set> failures = validator.validate(contractSaleInvoice); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ contractSaleInvoiceService.save(contractSaleInvoice); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象. String id = contractSaleInvoice.getId(); URI uri = uriBuilder.path("/rest/contractSaleInvoiceController/" + id).build().toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uri); return new ResponseEntity(headers, HttpStatus.CREATED); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity update(@RequestBody ContractSaleInvoiceEntity contractSaleInvoice) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set> failures = validator.validate(contractSaleInvoice); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ setFinancialData(contractSaleInvoice); contractSaleInvoiceService.saveOrUpdate(contractSaleInvoice); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按Restful约定,返回204状态码, 无内容. 也可以返回200状态码. return new ResponseEntity(HttpStatus.NO_CONTENT); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable("id") String id) { contractSaleInvoiceService.deleteEntityById(ContractSaleInvoiceEntity.class, id); } /** * 作废开票 * * @return */ @RequestMapping(params = "doCancel") @ResponseBody public AjaxJson doCancel(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); contractSaleInvoice = systemService.getEntity(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); Double invoiceamount = contractSaleInvoice.getInvoiceamount(); message = "作废发票成功"; try{ contractSaleInvoice.setInvoiceamount(DecimalUtils.ZERO); contractSaleInvoice.setInvoicedate(null); contractSaleInvoice.setInvoiceopt(null); contractSaleInvoice.setInvoiceoptname(null); contractSaleInvoice.setInvoiceno(null); contractSaleInvoice.setBusstatus(Globals.CONTRACT_STATUS_CANCELINVOICE); contractSaleInvoiceService.save(contractSaleInvoice); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); //回写合同开票合计 updateContractSaleTotalInvoice(contractSaleInvoice.getContractid(), 0-invoiceamount); }catch(Exception e){ e.printStackTrace(); message = "作废发票失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 收款 * * @return */ @RequestMapping(params = "doIncome") @ResponseBody public AjaxJson doIncome(ContractSaleInvoiceEntity contractSaleInvoice, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); contractSaleInvoice = systemService.getEntity(ContractSaleInvoiceEntity.class, contractSaleInvoice.getId()); message = "收款成功"; try{ contractSaleInvoice.setIncomeamount(contractSaleInvoice.getInvoiceamount()); contractSaleInvoice.setIncomedate(new Date()); contractSaleInvoice.setBusstatus(Globals.CONTRACT_STATUS_INCOME); TSUser user = ResourceUtil.getSessionUser(); contractSaleInvoice.setIncomeopt(user.getId()); contractSaleInvoice.setIncomeoptname(user.getRealName()); contractSaleInvoiceService.save(contractSaleInvoice); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "收款失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } private void updateContractSaleTotalInvoice(String cid,Double invoiceamount) { if(StringUtils.isNotEmpty(cid)){ String updateSql = "update t_b_contract_sale c set c.totalinvoice = c.totalinvoice+? where c.id =? "; systemService.executeSql(updateSql,invoiceamount,cid); } } /** * 文件上传通用跳转 * * @param req * @return */ @RequestMapping(params = "commonUpload") public ModelAndView commonUpload(HttpServletRequest req) { String extend = req.getParameter("extend"); req.setAttribute("extend", "xml"); req.setAttribute("uploader", "contractSaleInvoiceController.do?ajaxSaveFile"); return new ModelAndView("cn/com/lzt/publicpage/uploadView"); } @RequestMapping(params = "ajaxSaveFile") @ResponseBody public AjaxJson ajaxSaveFile(MultipartHttpServletRequest request) { AjaxJson ajaxJson = new AjaxJson(); Map attributes = new HashMap(); try { Map fileMap = request.getFileMap(); String uploadbasepath = ResourceUtil.getConfigByName("uploadpath"); // 文件数据库保存路径 String path = uploadbasepath + "/";// 文件保存在硬盘的相对路径 String realPath = request.getSession().getServletContext().getRealPath("/") + "/" + path;// 文件的硬盘真实路径 realPath += DateUtils.getDataString(DateUtils.yyyyMMdd) + "/"; path += DateUtils.getDataString(DateUtils.yyyyMMdd) + "/"; File file = new File(realPath); if (!file.exists()) { file.mkdirs();// 创建文件时间子目录 } if(fileMap != null && !fileMap.isEmpty()){ for (Map.Entry entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(mf.getInputStream()); NodeList data = document.getChildNodes(); //检查文件有效性,文件data info=“YIKAIFAPIAO” if(data.getLength() == 1 && data.item(0).getAttributes().getLength() == 1 && data.item(0).getAttributes().item(0).getNodeValue().equals("YIKAIFAPIAO")) { //缓存客户档案 List> curstomerList = systemService.findForJdbc(" select id,name from t_b_partner"); HashMap custMap = new HashMap(); for(Map map:curstomerList) { custMap.put(map.get("name").toString(), map.get("id").toString()); } NodeList rows = data.item(0).getChildNodes().item(0).getChildNodes(); ContractSaleInvoiceEntity newInvoice; for (int i = 0; i < rows.getLength(); i++) { Node row = rows.item(i); //作废发票不处理,非物业管理费不处理 if((!row.getAttributes().getNamedItem("作废日期").getNodeValue().equals("")) || row.getAttributes().getNamedItem("主要商品名称").getNodeValue().indexOf("物业管理费") == -1) continue; newInvoice = new ContractSaleInvoiceEntity(); newInvoice.setInvoicedate( DateUtils.parseDate(row.getAttributes().getNamedItem("开票日期").getNodeValue(),"yyyy-MM-dd")); newInvoice.setInvoicetype(row.getAttributes().getNamedItem("发票类型").getNodeValue().equals("增值税普票") ? Globals.INVOICE_TYPE_ordinary:Globals.INVOICE_TYPE_special); newInvoice.setInvoiceno(row.getAttributes().getNamedItem("发票号码").getNodeValue()); if(custMap.containsKey(row.getAttributes().getNamedItem("客户名称").getNodeValue())) { newInvoice.setCustomername(row.getAttributes().getNamedItem("客户名称").getNodeValue()); newInvoice.setCustomerid(custMap.get(row.getAttributes().getNamedItem("客户名称").getNodeValue())); } newInvoice.setRemark("发票内容:"+row.getAttributes().getNamedItem("主要商品名称").getNodeValue() +"\n开票人:"+row.getAttributes().getNamedItem("开票人").getNodeValue()); newInvoice.setTaxamount(new Double(row.getAttributes().getNamedItem("税额").getNodeValue())); newInvoice.setSaleamount(new Double(row.getAttributes().getNamedItem("合计金额").getNodeValue())); newInvoice.setInvoiceamount(new Double(row.getAttributes().getNamedItem("价税合计").getNodeValue())); newInvoice.setFeetype("wuyefee"); doAdd(newInvoice, request); } } // String fileName = mf.getOriginalFilename();// 获取文件名 // String swfName = PinyinUtil.getPinYinHeadChar(oConvertUtils.replaceBlank(FileUtils.getFilePrefix(fileName)));// 取文件名首字母作为SWF文件名 // String extend = FileUtils.getExtend(fileName);// 获取文件扩展名 // String noextfilename=DateUtils.getDataString(DateUtils.yyyymmddhhmmss)+StringUtil.random(8);//自定义文件名称 // String myfilename=noextfilename+"."+extend;//自定义文件名称 // String savePath = realPath + myfilename;// 文件保存全路径 // write2Disk(mf, extend, savePath); // TSAttachment attachment = new TSAttachment(); // attachment.setId(UUID.randomUUID().toString().replace("-", "")); // attachment.setAttachmenttitle(fileName); // attachment.setCreatedate(new Timestamp(new Date().getTime())); // attachment.setExtend(extend); // attachment.setRealpath(path + myfilename); // attachment.setSwfpath(swfName); // systemService.save(attachment); // attributes.put("url", path + myfilename); // attributes.put("name", fileName); ajaxJson.setMsg("上传发票xml完成"); systemService.addLog("上传发票xml完成", Globals.Log_Leavel_INFO, Globals.Log_Type_OTHER); } } // ajaxJson.setAttributes(attributes); } catch (Exception e) { ajaxJson.setSuccess(false); ajaxJson.setMsg(e.getMessage()); } return ajaxJson; } /** * 保存文件的具体操作 * @param mf * @param extend * @param savePath * @throws IOException * @throws UnsupportedEncodingException * @throws FileNotFoundException */ private void write2Disk(MultipartFile mf, String extend, String savePath) throws IOException, UnsupportedEncodingException, FileNotFoundException { File savefile = new File(savePath); if("txt".equals(extend)){ //利用utf-8字符集的固定首行隐藏编码原理 //Unicode:FF FE UTF-8:EF BB byte[] allbytes = mf.getBytes(); try{ String head1 = toHexString(allbytes[0]); String head2 = toHexString(allbytes[1]); if("ef".equals(head1) && "bb".equals(head2)){ //UTF-8 String contents = new String(mf.getBytes(),"UTF-8"); if(StringUtils.isNotBlank(contents)){ OutputStream out = new FileOutputStream(savePath); out.write(contents.getBytes()); out.close(); } } else { //GBK String contents = new String(mf.getBytes(),"GBK"); OutputStream out = new FileOutputStream(savePath); out.write(contents.getBytes()); out.close(); } } catch(Exception e){ String contents = new String(mf.getBytes(),"UTF-8"); if(StringUtils.isNotBlank(contents)){ OutputStream out = new FileOutputStream(savePath); out.write(contents.getBytes()); out.close(); } } } else { FileCopyUtils.copy(mf.getBytes(), savefile); } } private String toHexString(int index){ String hexString = Integer.toHexString(index); // 1个byte变成16进制的,只需要2位就可以表示了,取后面两位,去掉前面的符号填充 hexString = hexString.substring(hexString.length() -2); return hexString; } /** * 设置开上年、开下年、开本年金额 * @throws ParseException * */ private ContractSaleInvoiceEntity setFinancialData(ContractSaleInvoiceEntity invoice) throws ParseException { if(StringUtil.isEmpty(invoice.getPeriodBegin())) return invoice; if(invoice.getPeriodBegin().substring(0,4).equals(invoice.getPeriodEnd().substring(0,4))) { //不跨年 invoice.setC2cinvoice(invoice.getInvoiceamount()); invoice.setC2ninvoice(DecimalUtils.ZERO); invoice.setC2linvoice(DecimalUtils.ZERO); }else { //跨年时,需要计算开上一年或开下一年金额 Date begin = DateUtils.datetimeFormat.parse(invoice.getPeriodBegin()+" 00:00:00"); Date end = DateUtils.datetimeFormat.parse(invoice.getPeriodEnd()+" 00:00:00"); //属于上一年的天数 int firstHalf = XcglDateUtils.differentDays2YearEnd(begin)+1; //属于下一年的天数 int secondHalf = XcglDateUtils.differentDays2YearStart(end)+1; double firstAmount = DecimalUtils.formatToDouble((invoice.getInvoiceamount()*firstHalf)/(firstHalf+secondHalf)); double secondAmount = DecimalUtils.formatToDouble(invoice.getInvoiceamount()-firstAmount); //如果开票日期属于上半个阶段 if(invoice.getPeriodBegin().substring(0,4).equals( DateUtils.date_sdf.format(invoice.getInvoicedate()).substring(0,4))) { invoice.setC2cinvoice(firstAmount);//开本年 invoice.setC2ninvoice(secondAmount);//开下年 invoice.setC2linvoice(DecimalUtils.ZERO);//开上年 }else { //开票日期属于下半个阶段 invoice.setC2cinvoice(firstAmount);//开本年 invoice.setC2ninvoice(DecimalUtils.ZERO);//开下年 invoice.setC2linvoice(secondAmount);//开上年 } } return invoice; } private String checkEntity(ContractSaleInvoiceEntity invoice) { String msg = ""; if(StringUtils.isEmpty(invoice.getContractid()) || StringUtils.isEmpty(invoice.getContractname())){ msg = "合同不能为空"; } if(StringUtils.isEmpty(invoice.getCustomerid()) || StringUtils.isEmpty(invoice.getCustomername())){ msg = "抬头不能为空"; } if(StringUtils.isEmpty(invoice.getProjectid()) || StringUtils.isEmpty(invoice.getProjectname())){ msg = "项目不能为空"; } return msg; } @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(params = "getProjectInfo", method = RequestMethod.POST) @ResponseBody public Object getProjectInfo(String goodsCode,String contractid){ Map reJson = new HashMap(); TBGoodsInfoEntity goodInfo = null; List> resList = new ArrayList>(); if(StringUtils.isNotBlank(contractid) ){ try { String sql = "select id as projectid,name as projectname from t_b_project where id in (select projectid from t_b_contract_sale where id = ?)"; resList = systemService.findForJdbc(sql, contractid); if(resList.size() == 0) throw new BusinessException("查询不到项目"); }catch (Exception e) { reJson.put("status", "fail"); logger.info(e.getMessage()); return reJson; } reJson.put("status", "success"); reJson.put("projectinfo", resList.get(0)); }else{ reJson.put("status", "success"); reJson.put("projectinfo", null); } return reJson; } }