package com.nationalelectric.greenH5; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.nationalelectirc.Constant.ApplyRoleConstant; import com.nationalelectirc.Constant.Constant; import com.nationalelectirc.utils.RestResult; import com.nationalelectric.greenH5.DTO.GreenMealTicketApplyDTO; import com.nationalelectric.greenH5.bizc.IGreenMealTicketNumBizc; import com.nationalelectric.greenH5.bizc.IGreenOperateLogBizc; import com.sgcc.uap.persistence.IHibernateDao; import com.sgcc.uap.service.validator.ServiceValidatorBaseException; import com.sgcc.uap.service.validator.ServiceValidatorUtil; import java.text.ParseException; import java.text.SimpleDateFormat; import org.springframework.web.bind.annotation.RequestMapping; import java.util.*; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Resource; import com.nationalelectric.greenH5.po.GreenApplyList; import com.nationalelectric.greenH5.po.GreenDepartment; import com.nationalelectric.greenH5.po.GreenMealTicket; import com.nationalelectric.greenH5.po.GreenMealTicketApply; import com.nationalelectric.greenH5.po.GreenMealTicketIssue; import com.nationalelectric.greenH5.po.GreenUserInfo; import com.nationalelectric.greenH5.po.GreenUserRoleRel; import com.nationalelectric.greenH5.utils.DateUtil; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.bind.annotation.RequestBody; /** * 概述
*

* 功能
* * @author bowei */ @Controller @RequestMapping("/greenMealTicketApply") public class GreenMealTicketApplyController extends GreenBaseController{ @Resource private IHibernateDao hibernateDao; @Resource private IGreenMealTicketNumBizc greenMealTicketNumBizc; @Resource private IGreenOperateLogBizc greenOperateLogBizc; private ReentrantLock lock = new ReentrantLock(); /**员工-部门申请*/ @SuppressWarnings("deprecation") @RequestMapping(value = "/apply" , method = RequestMethod.POST) @ResponseBody @Transactional(rollbackFor=Exception.class) public RestResult apply(@RequestBody Object requestBody){ String flag = ""; GreenMealTicketApplyDTO greenMealTicketApplyDTO = new ObjectMapper().convertValue(requestBody, new TypeReference() {}); try { String userId = greenMealTicketApplyDTO.getUserId(); GreenUserInfo info = getUserInfo(userId); if(info==null){ return new RestResult(Constant.FAILED, "非法用户"); } flag = greenMealTicketApplyDTO.getFlag(); String ticketVariety = Constant.AUTO_ISSUE ; ServiceValidatorUtil.validatorJavaBean(greenMealTicketApplyDTO); /** 根据是 员工 还是 部门 来判断 */ /** 如果是员工 即领取 则查询ticket是否 够 */ /** 如果是部门申请则 置为 待审批 插入餐券申请表 还要插入我的申请表 ,审批过了才能插入 ticket num 表 */ if (flag == null && "".equals(flag)) { return new RestResult(Constant.FAILED, "返回异常"); } //实体转换 GreenMealTicketApply greenMealTicketApply = new GreenMealTicketApply(); greenMealTicketApply.setApplyReason(greenMealTicketApplyDTO.getApplyReason()); greenMealTicketApply.setEndDate(greenMealTicketApplyDTO.getEndDate()); greenMealTicketApply.setStartDate(greenMealTicketApplyDTO.getStartDate()); greenMealTicketApply.setMealTicketNum(greenMealTicketApplyDTO.getMealTicketNum()); greenMealTicketApply.setMealTicketVariety(greenMealTicketApplyDTO.getMealTicketVariety()); //greenMealTicketApply.setUserId(greenMealTicketApplyDTO.getId()); greenMealTicketApply.setUserId(greenMealTicketApplyDTO.getUserId()); GreenUserInfo userInfo = getUserInfo(String.valueOf(greenMealTicketApplyDTO.getUserId())); String title = userInfo.getTitle(); Long departmentId = userInfo.getDepartmentId(); greenMealTicketApply.setApplicantName(userInfo.getRealName()); if (title == null && "".equals(title)) { return new RestResult(Constant.FAILED, "不是本公司职员不能使用餐券功能!"); } //判断申请-领取的时间是否在自然月 String startDate2 = greenMealTicketApplyDTO.getStartDate(); String[] split = startDate2.split("-"); String endDate2 = greenMealTicketApplyDTO.getEndDate(); String[] split3 = endDate2.split("-"); if (!(split[0] + split[1]).equals(split3[0] + split3[1])) { return new RestResult(Constant.FAILED, "请不要跨月领取餐券!"); } String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String[] split2 = format.split("-"); if (Integer.valueOf((split[0] + split[1] + split[2])) < Integer.valueOf((split2[0] + split2[1] + split2[2])) || Integer.valueOf((split3[0] + split3[1] + split3[2])) < Integer.valueOf((split2[0] + split2[1] + split2[2]))) { return new RestResult(Constant.FAILED, "时间范围请填写将来时间!"); } //判断 小于20号 则只能领取本月餐券 List list = hibernateDao.queryForListWithSql("SELECT ISSUE_DAY FROM GREEN_MEAL_TICKET_ISSUE WHERE is_deleted = 'N' order by id desc limit 1",new BeanPropertyRowMapper(GreenMealTicketIssue.class)); if (list.size() == 0) { return new RestResult(Constant.FAILED, "每月下发日期未设置,不能判断领取(申请)餐券日期范围!"); } Integer issueDay = Integer.valueOf(list.get(0).getIssueDay()); if (Integer.valueOf(split2[2]) < issueDay && Integer.valueOf(split[1]) > Integer.valueOf(split2[1]) ) { return new RestResult(Constant.FAILED, "当前时间未到" + issueDay + "号,只能领取本月餐券!"); } //判断 下一个月时间 Calendar cal = Calendar.getInstance(); cal.add(cal.MONTH, 1); SimpleDateFormat dft = new SimpleDateFormat("yyyyMM"); String preMonth = dft.format(cal.getTime()); if (Integer.valueOf(split2[2]) >= issueDay && Integer.valueOf(split[0] + split[1]) > Integer.valueOf(preMonth) ) { return new RestResult(Constant.FAILED, "当前时间超过" + issueDay + "号,只能领取本月及下月餐券!"); } // GreenDepartment department = getDepartment(departmentId); // //拿到员工的所属部门的父级部门 // Long parentId = department.getParentId(); // //若父级为总部或银座 则为当前部门id // if (parentId == 1 || parentId == 2 || parentId == 0) { // parentId = department.getId(); // } //申请 员工不能申请 if ("申请".equals(flag)) { // //根据角色名称查询'餐券申请审批'的用户 // String ticketAppSql = "SELECT user_name userName FROM GREEN_USER_ROLE_REL WHERE role_name='餐券申请审批'"; // // List ticketAppList = hibernateDao.queryForListWithSql(ticketAppSql, new Object[] {}, // new BeanPropertyRowMapper(GreenUserRoleRel.class)); List queryForListWithSql = hibernateDao.queryForListWithSql( "Select * from GREEN_MEAL_TICKET_NUM where department_id = ? and is_deleted = 'N' and date_format(t.effective_date, '%Y-%m') =DATE_FORMAT(?, '%Y-%m') limit 1", new Object[] { departmentId }); if (queryForListWithSql.isEmpty()) { return new RestResult(Constant.FAILED, "当前部门未设置餐券下发,请联系下发餐券管理员对您的部门下发餐券!"); } //title-1 部门 2员工 // //判断时间段是否在同一天 申请数叠在一起? // SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); // long startDate = Long.valueOf(greenMealTicketApplyDTO.getStartDate().replaceAll("[-\\s:]","")); // long endDate = Long.valueOf(greenMealTicketApplyDTO.getEndDate().replaceAll("[-\\s:]","")); // Long c = sf.parse(String.valueOf(endDate)).getTime()-sf.parse(String.valueOf(startDate)).getTime(); // long d = c/1000/60/60/24; // // if ( d > 0 ) { // greenMealTicketApply.setMealTicketNum(String.valueOf(Long.valueOf(greenMealTicketApplyDTO.getMealTicketNum()) * d)); // } greenMealTicketApply.setApplyStatus("1"); greenMealTicketApply.setApplicantDepartmentId(departmentId); greenMealTicketApply.setApplyDate(DateUtil.now()); // greenMealTicketApply.setApprovalStatus(Constant.APPROVAL_DOING); hibernateDao.saveObject(greenMealTicketApply); /**插入我的申请表*/ GreenApplyList applyList = new GreenApplyList(); applyList.setDetailId(greenMealTicketApply.getId()); applyList.setUserId(greenMealTicketApply.getUserId()); applyList.setApplyType("01"); applyList.setApplyTypeName("餐券申请"); applyList.setApplyInfo1(greenMealTicketApply.getStartDate() +"-"+greenMealTicketApply.getEndDate()); applyList.setApplyInfo2(greenMealTicketApply.getApplyReason()); applyList.setApplyTime(DateUtil.now()); applyList.setFirstApproval(ApplyRoleConstant.MEAL_TICKET_APPROVE); // applyList.setFirstStatus(Constant.APPROVAL_DOING); //一级审时间 applyList.setFirstApproveTime(new SimpleDateFormat(DateUtil.Y_M_DH_MI_S).format(new Date())); //创建者 applyList.setCreator("admin"); //修改者 applyList.setModifier("admin"); //创建时间 applyList.setGmtCreated(new Date()); //修改时间 applyList.setGmtModified(new Date()); //删除标识 applyList.setIsDeleted("N"); hibernateDao.saveObject(applyList); //addLog(Constant.MEAL_TICKET_A, Constant.T_APPLY, Constant.OPERATE_SUCCESS, "申请餐券", Constant.LOG_OPERATE, greenMealTicketApplyDTO.getUserId()); /* //推送消息给餐券申请审批的用户 String msgname ="审批通知"; String tm = "您有一个【餐券申请】审批"; for (int i = 0; i < ticketAppList.size(); i++) { String userName = ticketAppList.get(i).getUserName(); //System.out.println(userName); PushMessageUtil.pushMessage(msgname,tm, userName); } */ } /** 员工领取 */ if ("领取".equals(flag)) { lock.lock(); // List> list1 = hibernateDao.queryForListWithSql( // "Select * from GREEN_MEAL_TICKET_NUM where department_id = ? and issue_date >= ? and issue_date <= ?", // new Object[] { departmentId, // greenMealTicketApply.getStartDate(), greenMealTicketApply.getEndDate() }); // if (list1.isEmpty()) { // return new RestResult(Constant.FAILED, "领取日期未发放餐券,请重新输入", null); // } //下发的餐券是一个月的 Integer ticketNum =Integer.valueOf(greenMealTicketApply.getMealTicketNum()) ; List> list1 = hibernateDao.queryForListWithSql( "Select * from GREEN_MEAL_TICKET_NUM where department_id = ? and is_deleted = 'N' order by issue_date desc limit 1 ", new Object[] { departmentId }); if (list1.isEmpty()) { return new RestResult(Constant.FAILED, "相关部门未发放餐券!", null); } List betweenDays = getBetweenDays(greenMealTicketApplyDTO.getStartDate(),greenMealTicketApplyDTO.getEndDate()); StringBuffer stringBuffer = new StringBuffer(); for (String string : betweenDays) { stringBuffer.append("'"+string + "',"); } String substring = stringBuffer.substring(0, stringBuffer.length() - 1); //加锁 防止扣负 String sql = " SELECT ANY_value (n.id) AS id,n.department_id,d. NAME AS departmentName, DATE_FORMAT(n.issue_date, '%Y-%m') AS time, if(t.currentNum=NULL,0,t.currentNum) currentNum," + " sum(n.issue_num) AS 'mealNum' FROM GREEN_MEAL_TICKET_NUM n " + " LEFT JOIN GREEN_DEPARTMENT d ON n.department_id = d.id LEFT JOIN ( SELECT b.applicant_department_id AS id, " + " count(IF(a.use_status <> '2', TRUE, NULL)) currentNum FROM GREEN_MEAL_TICKET a " + " LEFT JOIN GREEN_MEAL_TICKET_APPLY b ON a.ticket_apply_id = b.id WHERE " + " a.is_deleted = 'N' AND DATE_FORMAT(a.use_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') GROUP BY " + " b.applicant_department_id, DATE_FORMAT(a.use_date, '%Y-%m') DESC ) t on t.id = n.department_id " + " where n.is_deleted = 'N' AND DATE_FORMAT(n.issue_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')" + " and d.id= ? GROUP BY n.department_id,d. NAME,DATE_FORMAT(n.issue_date, '%Y-%m') "; List> list3 = hibernateDao.queryForListWithSql(sql, new Object[] { departmentId}); if(list3.size()<=0){ return new RestResult(Constant.FAILED, "该部门无餐券可领取!"); } Integer c = 0; Integer mealNum = 0; if(list3.get(0).get("mealNum")!=null && !"".equals(list3.get(0).get("mealNum"))){ mealNum = Integer.valueOf(list3.get(0).get("mealNum")+""); if(list3.get(0).get("currentNum")!=null && !"".equals(list3.get(0).get("currentNum"))){ c = Integer.parseInt(list3.get(0).get("currentNum").toString()); } } int daynum = DateUtil.getDayPass(greenMealTicketApply.getEndDate(), greenMealTicketApply.getStartDate(), new SimpleDateFormat("yyyy-MM-dd")); if((mealNum-c) == 0){ return new RestResult(Constant.FAILED, "餐券已用完", null); } if((mealNum-c)> list2 = hibernateDao.queryForListWithSql( // sqlString, // new Object[] { departmentId,greenMealTicketApply.getStartDate(), ticketNum}); // // if (list2.isEmpty() || betweenDays.size() > list2.size()) { // return new RestResult(Constant.FAILED, "餐券已用完", null); // } // greenMealTicketApply.setUserId(669L); // greenMealTicketApply.setApplicantDepartmentId(332L); //title-1 部门 2员工 greenMealTicketApply.setApplyStatus("2"); greenMealTicketApply.setApplicantDepartmentId(departmentId); greenMealTicketApply.setApplyDate(DateUtil.now()); // greenMealTicketApply.setApprovalStatus(Constant.APPROVAL_YES); hibernateDao.saveObject(greenMealTicketApply); /** 减去 领取的餐券 */ // if (!list2.isEmpty()) { // int num = 0; // // for (Map map : list2) { // // int issue_unused_num = Integer.parseInt(map.get("issue_unused_num").toString()); // int extra_unused_num = Integer.parseInt(map.get("extra_unused_num").toString()); // // if (ticketNum <= issue_unused_num) { // num = issue_unused_num - ticketNum; // hibernateDao.updateWithSql("update GREEN_MEAL_TICKET_NUM set issue_unused_num = ? where id = ? and is_deleted = 'N'", // new Object[] { num,map.get("id") }); // ticketVariety = Constant.AUTO_ISSUE; // }else { // //Integer ticketNum2 =Integer.valueOf(greenMealTicketApply.getMealTicketNum()) ; // if (ticketNum > issue_unused_num) { // num =extra_unused_num - (ticketNum - issue_unused_num); // hibernateDao.updateWithSql("update GREEN_MEAL_TICKET_NUM set issue_unused_num = 0,extra_unused_num = ? where id = ? and is_deleted = 'N'", // new Object[] { num,map.get("id") }); // ticketVariety = Constant.EXTRA_APPLY; // } // } // } // } /**扣券成功,将员工领取的餐券插入餐券表*/ // String ticketNo =""; Integer mealTicketNum = Integer.parseInt(greenMealTicketApply.getMealTicketNum()); // List> queryForListWithSql = hibernateDao.queryForListWithSql("SELECT * FROM GREEN_SEQ WHERE table_name = 'GREEN_MEAL_TICKET'"); // if (queryForListWithSql.isEmpty()) { // throw new Exception("返回异常"); // } // int seqId = Integer.parseInt(String.valueOf(queryForListWithSql.get(0).get("max_id"))); Long id = greenMealTicketApply.getId(); String insertsql = "INSERT INTO GREEN_MEAL_TICKET(ticket_apply_id,use_id,ticket_no,use_date,use_status,ticket_variety,creator,modifier,gmt_created,gmt_modified,is_deleted) VALUES "; StringBuilder builder = new StringBuilder(); builder.append(insertsql); //LinkedList list = new LinkedList(); //List betweenDays = getBetweenDays(greenMealTicketApply.getStartDate(),greenMealTicketApply.getEndDate()); for (String day : betweenDays) { String ticketUseId = "CQ" + greenMealTicketApply.getUserId() + day.replace("-", ""); for (int i = 0; i < mealTicketNum.intValue(); i++) { // ticketNo = GUID.getTicketNo() + String.valueOf(i); // ticket.setTicketNo(ticketNo); // GreenMealTicket ticket = new GreenMealTicket(); // ticket.setTicketApplyId(greenMealTicketApply.getId()); // ticket.setTicketVariety(String.valueOf(ticketVariety)); // ticket.setUseStatus(Constant.TICKET_UNUSE); // ticket.setUseId(ticketUseId); // ticket.setTicketNo(ticketUseId); // ticket.setUseDate(day); builder.append("("+id+ ",'"+ticketUseId+"','"+ticketUseId+"','"+day+"','"+Constant.TICKET_UNUSE+"','"+ticketVariety+"','"+departmentId+"','"+departmentId+"','"+DateUtil.now()+"','"+DateUtil.now()+"','"+"N"+"'" +"),"); // seqId ++; //hibernateDao.saveObject(ticket); //list.add(ticket); } } String substring2 = builder.substring(0, builder.length()-1); //System.out.println(substring2.length()); hibernateDao.updateWithSql(substring2); //hibernateDao.updateWithSql("update GREEN_SEQ set max_id = ? WHERE table_name = 'GREEN_MEAL_TICKET'",new Object[]{ seqId}); /**插入我的申请表*/ GreenApplyList applyList = new GreenApplyList(); applyList.setDetailId(greenMealTicketApply.getId()); applyList.setUserId(greenMealTicketApply.getUserId()); applyList.setApplyType("07"); applyList.setApplyTypeName("餐券领取"); applyList.setApplyInfo1(greenMealTicketApply.getStartDate() +"-"+greenMealTicketApply.getEndDate()); applyList.setApplyInfo2(greenMealTicketApply.getApplyReason()); applyList.setApplyTime(DateUtil.now()); applyList.setFirstApproval(greenMealTicketApply.getId().toString()); // applyList.setFirstStatus(Constant.RECEIVE_SUCCESS); //一级审时间 applyList.setFirstApproveTime(new SimpleDateFormat(DateUtil.Y_M_DH_MI_S).format(new Date())); //创建者 applyList.setCreator("admin"); //修改者 applyList.setModifier("admin"); //创建时间 applyList.setGmtCreated(new Date()); //修改时间 applyList.setGmtModified(new Date()); //删除标识 applyList.setIsDeleted("N"); hibernateDao.saveObject(applyList); } //greenOperateLogBizc.addLog(Constant.MEAL_TICKET_B, Constant.T_TAKE, Constant.OPERATE_SUCCESS, "领取餐券", Constant.LOG_OPERATE, greenMealTicketApplyDTO.getUserId()); return new RestResult(Constant.SUCCESS, "成功",flag+"成功"); }catch (ServiceValidatorBaseException e) { e.printStackTrace(); /*if ("领取".equals(flag)) { greenOperateLogBizc.addLog(Constant.MEAL_TICKET_B, Constant.T_TAKE, Constant.OPERATE_FAIL, "领取餐券", Constant.LOG_ERROR, greenMealTicketApplyDTO.getUserId()); }else { greenOperateLogBizc.addLog(Constant.MEAL_TICKET_A, Constant.T_APPLY, Constant.OPERATE_FAIL, "申请餐券", Constant.LOG_ERROR, greenMealTicketApplyDTO.getUserId()); }*/ return new RestResult(Constant.FAILED,e.getMessage()); } catch (Exception e) { e.printStackTrace(); /* if ("领取".equals(flag)) { greenOperateLogBizc.addLog(Constant.MEAL_TICKET_B, Constant.T_TAKE, Constant.OPERATE_FAIL, "领取餐券", Constant.LOG_ERROR, greenMealTicketApplyDTO.getUserId()); }else { greenOperateLogBizc.addLog(Constant.MEAL_TICKET_A, Constant.T_APPLY, Constant.OPERATE_FAIL, "申请餐券", Constant.LOG_ERROR, greenMealTicketApplyDTO.getUserId()); }*/ //设置手动回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return new RestResult(Constant.FAILED, "返回异常"); }finally { if (lock.isLocked()) { lock.unlock(); } } } /** * 根据id查询餐券申请和餐券领取详情 * @param id * @param applyType * @return */ @SuppressWarnings("unchecked") public List getMealTicketApplyInfo(String id,String applyType) { //返回结果定义 List resultList = new ArrayList(); //查询sql String applyInfoByIdSql = " SELECT mta.*," + " al.detail_id," + " al.apply_type," + " al.apply_type_name," + " al.first_approval," + " al.first_status," + " al.first_approve_time," + " CASE first_status" + " WHEN '0' THEN '待审批'" + " WHEN '1' THEN '已同意'" + " WHEN '2' THEN '已拒绝'" + " WHEN '3' THEN '已取消'" + " WHEN '12' THEN '领取成功'" + " END AS first_status_value" + " FROM GREEN_APPLY_LIST al" + " INNER JOIN GREEN_MEAL_TICKET_APPLY mta" + " ON al.detail_id = mta.id" + " WHERE 1=1 AND mta.id = ?" + " AND al.apply_type = ?"; //sql执行 resultList = hibernateDao.queryForListWithSql(applyInfoByIdSql,new Object[]{id,applyType}); //返回结果 return resultList; } public static List getBetweenDays(String stime,String etime) throws ParseException{ SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Date sdate=df.parse(stime); Date eDate=df.parse(etime); //long betweendays=(long) ((eDate.getTime()-sdate.getTime())/(1000 * 60 * 60 *24)+0.5);//天数间隔 Calendar c = Calendar.getInstance(); List list=new ArrayList(); while (sdate.getTime()<=eDate.getTime()) { list.add(df.format(sdate)); //System.out.println(df.format(sdate)); c.setTime(sdate); c.add(Calendar.DATE, 1); // 日期加1天 sdate = c.getTime(); } return list; } }