Beispiel #1
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // 转发处理
    StringBuffer json = new StringBuffer();
    String methodCall = req.getParameter("methodCall");
    if (methodCall.equals("getResultDetailByBatchNo")) { // 通过原来的批量退款批次号获取退款详情
      if (req.getParameter("batchNo") == null) {
        json.append("{success:false,msg:'参数[原批量退款批次号]不能为空'}");
      } else {
        Map resultDetails =
            refundFastpayService.getResultDetailByBatchNo(req.getParameter("batchNo"));
        if (CollectionUtils.isEmpty(resultDetails)) {
          json.append(
              "{success:false,msg:'原批量退款批次号为:" + req.getParameter("batchNo") + "的批量退款信息不存在'}");
        } else {
          json.append("{success:true,data:{");
          json.append("batchNo:'" + resultDetails.get("batchNo") + "',");
          json.append("batchNum:'" + resultDetails.get("batchNum") + "',");
          json.append("batchData:'" + resultDetails.get("batchData") + "',");
          json.append(
              "refundDate:'"
                  + DateUtil.formatDate(
                      (Date) resultDetails.get("refundDate"), "yyyy-MM-dd HH:mm:ss")
                  + "',");
          json.append("isSuccess:'" + resultDetails.get("isSuccess") + "',");
          json.append(
              "successNum:'"
                  + (resultDetails.get("successNum") != null ? resultDetails.get("successNum") : "")
                  + "',");
          json.append(
              "resultDetails:'"
                  + (resultDetails.get("resultDetails") != null
                      ? resultDetails.get("resultDetails")
                      : "")
                  + "',");
          json.append(
              "relation:'"
                  + (resultDetails.get("relation") != null ? resultDetails.get("relation") : "")
                  + "',");
          json.append(
              "totalRefund:'"
                  + (resultDetails.get("totalRefund") != null
                      ? resultDetails.get("totalRefund")
                      : "")
                  + "'");
          json.append("},msg:'获取原批量退款批次号为:" + req.getParameter("batchNo") + "的批量退款信息成功!'}");
        }
      }
      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write(json.toString());
      resp.getWriter().close();
      return;
    } else if (methodCall.equals("batchRefundImport")) { // 批量退款导入
      // 解析文件

      String realPath = null;
      String filePath = null;
      Result result = null;
      try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        boolean isMutipart = ServletFileUpload.isMultipartContent(req);
        if (isMutipart) {
          ServletFileUpload upload = new ServletFileUpload(factory);
          List fileItems = upload.parseRequest(req);
          Iterator iterator = fileItems.iterator();
          while (iterator.hasNext()) {
            FileItem fi = (FileItem) iterator.next();
            if (!fi.isFormField()) {
              String fileName = fi.getName();
              if (fileName == null || "".equals(fileName)) break;
              String suffix = fileName.substring(fileName.lastIndexOf("."));
              String systemFileName = "upload-" + System.currentTimeMillis() + suffix;

              filePath =
                  PropertiesUtil.getProperties("fileUploadPath", "D:/data/upload/")
                      + systemFileName;
              // realPath = req.getSession().getServletContext().getRealPath("/") + filePath;
              realPath = filePath;
              try {
                File uploadedFile = new File(realPath);
                fi.write(uploadedFile);
                result = processRefundFastpayExcel(realPath);

                if (!result.isSuccess()) { // 失败
                  RequestDispatcher rd = req.getRequestDispatcher("/refund/result.jsp");
                  req.setAttribute("result", result);
                  rd.forward(req, resp);
                } else { // 成功
                  req.getSession(true).setAttribute("result", result);
                  resp.sendRedirect(req.getContextPath() + "/refund/success.jsp");
                }

              } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          }
        }
      } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else if (methodCall.equals("batchRefundApply")) { // 批量退款申请
      // 解析文件

      String realPath = null;
      String filePath = null;
      Result result = null;
      String applyUser = null;
      String applyRemark = null;
      try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        boolean isMutipart = ServletFileUpload.isMultipartContent(req);
        if (isMutipart) {
          ServletFileUpload upload = new ServletFileUpload(factory);
          List fileItems = upload.parseRequest(req);
          Iterator iterator = fileItems.iterator();
          while (iterator.hasNext()) {
            FileItem fi = (FileItem) iterator.next();
            if (!fi.isFormField()) {
              String fileName = fi.getName();
              if (fileName == null || "".equals(fileName)) break;
              String suffix = fileName.substring(fileName.lastIndexOf("."));
              String systemFileName = "upload-" + System.currentTimeMillis() + suffix;

              filePath =
                  PropertiesUtil.getProperties("fileUploadPath", "D:/data/upload/")
                      + systemFileName;
              // realPath = req.getSession().getServletContext().getRealPath("/") + filePath;
              realPath = filePath;
              File uploadedFile = new File(realPath);
              fi.write(uploadedFile);
            } else {
              String name = fi.getFieldName();
              String value = fi.getString();
              // 在enctype="multipart/form-data") 情况下,form表单的数据通过流传递,且在Tomcat服务器下,默认使用ISO-8859-1编码
              value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
              if (name.equals("applyUser")) {
                applyUser = value;
              }
              if (name.equals("applyRemark")) {
                applyRemark = value;
              }
            }
          }
          try {
            // 简单校验,提交申请applyId为null
            result = processRefundFastpayApplyExcel(realPath, true, null, applyUser, applyRemark);
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      } catch (FileUploadException e) {
        result.setMsg("附件上传失败导致申请失败!");
      } catch (Exception e) {
        result.setMsg("服务器端异常导致申请失败!");
      }
      if (!result.isSuccess()) { // 失败
        RequestDispatcher rd = req.getRequestDispatcher("/refund/result.jsp");
        req.setAttribute("result", result);
        rd.forward(req, resp);
      } else { // 成功
        req.getSession(true).setAttribute("result", result);
        resp.sendRedirect(req.getContextPath() + "/refund/success.jsp");
      }
    } else if (methodCall.equals("searchRefundFastpayApplyList")) { // 查询申请列表
      int currentPage = Integer.valueOf(req.getParameter("currentPage").toString());
      int startRecord =
          currentPage == 1
              ? 0
              : ((currentPage - 1) * Integer.valueOf(req.getParameter("pageSize").toString()));
      int totalPage = 0;
      if (req.getParameter("flag").toString().equals("0")) {
        startRecord = 0;
      }
      Map resultDetails =
          refundFastpayService.searchRefundFastpayApplyList(
              req.getParameter("startDate").toString(),
              req.getParameter("endDate").toString(),
              Integer.valueOf(req.getParameter("applyStatus").toString()),
              req.getParameter("applyUser").toString(),
              Boolean.valueOf(req.getParameter("isSignUser")),
              startRecord,
              Integer.valueOf(req.getParameter("pageSize").toString()));

      for (Map map : ((List<Map>) resultDetails.get("data"))) {
        json.append("{'id':'");
        json.append(map.get("id")).append("','applyNo':'");
        json.append(map.get("applyNo")).append("','batchNo':'");
        json.append(map.get("batchNo")).append("','filepath':'");
        json.append(map.get("filepath")).append("','applyStatus':'");
        json.append(map.get("applyStatus")).append("','applyUser':'******','applyTime':'");
        json.append(map.get("applyTime")).append("','applyRemark':'");
        json.append(map.get("applyRemark")).append("','auditUser':'******','auditTime':'");
        json.append(map.get("auditTime")).append("','auditRemark':'");
        json.append(map.get("auditRemark")).append("','importUser':'******','importTime':'");
        json.append(map.get("importTime")).append("','importRemark':'");
        json.append(map.get("importRemark")).append("'");
        json.append("},");
      }

      if (json.toString().endsWith(",")) {
        json = new StringBuffer(json.substring(0, json.length() - 1));
      }

      totalPage =
          (Integer.valueOf(resultDetails.get("rowCount").toString()) == 0
              ? 1
              : (Integer.valueOf(resultDetails.get("rowCount").toString())
                      + Integer.valueOf(req.getParameter("pageSize").toString())
                      - 1)
                  / Integer.valueOf(req.getParameter("pageSize").toString()));

      json =
          new StringBuffer(
              "{success: true,rowCount:'"
                  + resultDetails.get("rowCount")
                  + "',data:["
                  + json
                  + "],currentPage:'"
                  + currentPage
                  + "',totalPage:'"
                  + totalPage
                  + "'}");

      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write(json.toString());
      resp.getWriter().close();
      return;

    } else if (methodCall.equals("auditRefundFastpayApply")) { // 审批
      Result result = null;
      result =
          refundFastpayService.auditRefundFastpay(
              req.getParameter("applyId"),
              req.getParameter("auditUser"),
              // new String(req.getParameter("auditRemark").getBytes("iso-8859-1"), "UTF-8"),
              // req.getParameter("auditRemark"),
              HttpUtil.ConverUnicode(req.getParameter("auditRemark")), // reuncode
              Integer.valueOf(req.getParameter("applyStatus").toLowerCase()));
      if (result.isSuccess()) {
        json.append("{success:true}");
      } else {
        json.append("{success:false, msg:'" + result.getMsg() + "'}");
      }

      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write(json.toString());
      resp.getWriter().close();
      return;
    } else if (methodCall.equals("importRefundFastpayApply")) { // 导入
      Result result = null; // 简单校验,提交申请applyId为null
      result =
          processRefundFastpayApplyExcel(
              null,
              false,
              req.getParameter("applyId"),
              req.getParameter("importUser"),
              // req.getParameter("importRemark")
              HttpUtil.ConverUnicode(req.getParameter("importRemark")));
      if (result.isSuccess()) {
        json.append("{success:true}");
      } else {
        json.append("{success:false, msg:'" + result.getMsg() + "'}");
      }

      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write(json.toString());
      resp.getWriter().close();
      return;
    } else if (methodCall.equals("downloadFile")) { // 下载

      Map map = refundFastpayService.getApplyDetailByBatchNo(req.getParameter("applyId"));
      String filePath = map.get("filepath").toString();

      File dbFile = new File(filePath);
      FileInputStream fileIn = null;

      fileIn = new FileInputStream(dbFile);
      String contentType;
      contentType = "application/x-xls";
      resp.setContentType(contentType);
      resp.setHeader(
          "Content-Disposition", "filename=" + filePath.substring(filePath.indexOf("upload-")));

      byte[] buffer = new byte[1024 * 512];
      while (true) {
        int bytes = fileIn.read(buffer);
        if (bytes == -1) {
          break;
        }
        resp.getOutputStream().write(buffer, 0, bytes);
      }
      resp.getOutputStream().flush();
      resp.getOutputStream().close();
      fileIn.close();
      return;
    }
    /*else if(methodCall.equals("test")){
    	test();
    }*/

  }
Beispiel #2
0
  private Result processRefundFastpayExcel(String realPath) {
    // TODO Auto-generated method stub
    Set<String> repetFilter = new HashSet(); // 过滤重复
    Workbook book = null;
    StringBuffer msg = new StringBuffer();
    Result result = new Result();
    // 2011112421847473^0.01^NOT_THIS_PARTNERS_TRAD
    int batchNum = 0;
    StringBuffer batchData = new StringBuffer();
    StringBuffer relation = new StringBuffer();
    BigDecimal totalRefund = new BigDecimal(0); // 退款总金额
    boolean hasError = false;
    try {
      try {
        book = Workbook.getWorkbook(new File(realPath));
      } catch (BiffException e) {
        e.printStackTrace();
        result.setMsg("导入文件读取失败,请重新导入或者联系开发人员!<br>");
        return result;
      } catch (IOException e) {
        e.printStackTrace();
        result.setMsg("导入文件读取失败,请重新导入或者联系开发人员!<br>");
        return result;
      }
      Sheet sheet = book.getSheet(0);
      int count = sheet.getRows();
      // 生成批量退款笔数及退款数据集
      if (count <= 2) { // 没有数据
        result.setMsg("没有数据!");
        return result;
      } else if (count
          >= (Integer.valueOf(PropertiesUtil.getProperties("alipay.batchNumLimit", "1000"))
                  .intValue()
              + 2)) { // 超出最大笔数
        result.setMsg(
            "支付宝即时到账批量退款,最大支持"
                + PropertiesUtil.getProperties("alipay.batchNumLimit", "1000")
                + "笔!");
        return result;
      } else { // 校验合法性
        for (int i = 1; i < count - 1; i++) { // 最后一行是合计				
          Cell[] cells = sheet.getRow(i);
          String outTradeNo =
              cells[Integer.valueOf(PropertiesUtil.getProperties("outTradeNOIndex", "0"))]
                  .getContents()
                  .trim();
          if (!repetFilter.contains(outTradeNo)) {
            repetFilter.add(outTradeNo);
          } else {
            msg.append(
                "EXCEL第"
                    + i
                    + "行(不包含表头部分)数据-单品订单号["
                    + outTradeNo
                    + "]在导入文件的前面部分已经出现请合并为一条退款记录!<br/>");
            hasError = true;
          }

          // 校验money
          String totalFee =
              cells[Integer.valueOf(PropertiesUtil.getProperties("totalFeeIndex", "0"))]
                  .getContents()
                  .trim();
          totalRefund = totalRefund.add(new BigDecimal(totalFee));
          String tradeNo = getTradeNoByOutTradeNo(outTradeNo, new BigDecimal(totalFee));

          // 校验tradeNo逻辑
          if (tradeNo == null) {
            msg.append("EXCEL第" + i + "行(不包含表头部分)数据-单品订单号[" + outTradeNo + "]获取支付宝交易号失败!<br/>");
            hasError = true;
          } else if (tradeNo.indexOf(
                  PropertiesUtil.getProperties(
                      "alipay.interface.returncode.outoftotalfee", "OUTOFTOTALFEE"))
              == 0) {
            msg.append("EXCEL第" + i + "行(不包含表头部分)数据-单品订单号[" + outTradeNo + "]退款总金额大于当前可退款金额!<br/>");
            hasError = true;
          } else {
            // 拼接relation (商家订单号1^支付宝交易号1#商家订单号2^支付宝交易号2)
            relation.append(outTradeNo).append("^").append(tradeNo);
            if (i < count - 2) {
              relation.append("#");
            }
          }

          String remark = PropertiesUtil.getProperties("refundRemark", "上品折扣支付宝退款");
          // 处理逻辑
          batchNum++;
          batchData.append(tradeNo + "^" + totalFee + "^" + remark);
          if (i < count - 2) {
            batchData.append("#");
          }
        }
      }

      if (hasError) {
        result.setMsg(msg.toString());
        return result;
      }

      result =
          refundFastpayService.processRefundFastpayExcel(
              batchNum, batchData.toString(), realPath, relation.toString(), totalRefund);

    } catch (RuntimeException e) {
      e.printStackTrace();
      result.setMsg("服务端异常,导致导入文件读取失败,请联系开发人员!<br>" + e.getMessage());
    } finally {
      book.close();
    }
    return result;
  }