| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412 |
- package com.xcgl.weixin;
- import cn.com.lzt.car.alarm.CarAlarmEntity;
- import cn.com.lzt.common.entity.TSysFileEntity;
- import cn.com.lzt.common.service.TSysFileServiceI;
- import cn.com.lzt.common.util.CustomerConstant;
- import cn.com.lzt.common.util.DictUtil;
- import cn.com.lzt.common.util.UserUtil;
- import cn.com.lzt.contract.entity.ContractEntity;
- import cn.com.lzt.maintainbill.entity.MaintainBillEntity;
- import cn.com.lzt.maintainplan.entity.MaintainPlanEntity;
- import cn.com.lzt.message.personal.entity.MPersonalMessageEntity;
- import cn.com.lzt.message.personal.service.MPersonalMessageServiceI;
- import cn.com.lzt.message.reply.entity.MMessageReplyEntity;
- import cn.com.lzt.message.reply.service.MMessageReplyServiceI;
- import cn.com.lzt.message.send.entity.MMessageEntity;
- import cn.com.lzt.message.send.service.MMessageServiceI;
- import com.aliyun.oss.OSSClient;
- import com.aliyun.oss.model.ObjectMetadata;
- import com.aliyuncs.DefaultAcsClient;
- import com.aliyuncs.IAcsClient;
- import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
- import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
- import com.aliyuncs.exceptions.ClientException;
- import com.aliyuncs.exceptions.ServerException;
- import com.aliyuncs.http.MethodType;
- import com.aliyuncs.profile.DefaultProfile;
- import com.aliyuncs.profile.IClientProfile;
- import com.xcgl.dataview.service.DataviewServiceI;
- import com.xcgl.projecttask.entity.ProjecttaskEntity;
- import com.xcgl.reports.dao.XcglRptDao;
- import com.xcgl.taskresult.entity.TaskResultEntity;
- import com.xcgl.utils.UUID;
- import com.xcgl.utils.XcglConstant;
- import com.xcgl.utils.XcglDateUtils;
- import com.xcgl.weeklyMeeting.entity.WeeklyMeetingEntity;
- import com.xcgl.weixin.base.ApiException;
- import com.xcgl.weixin.dao.WXDao;
- import com.xcgl.weixin.entity.*;
- import com.xcgl.weixin.service.WXServiceI;
- import com.xcgl.weixin.service.WxTokenService;
- import com.xcgl.weixin.utils.WXUtils;
- import org.activiti.engine.HistoryService;
- import org.activiti.engine.RepositoryService;
- import org.activiti.engine.RuntimeService;
- import org.activiti.engine.TaskService;
- import org.activiti.engine.history.HistoricProcessInstance;
- import org.activiti.engine.history.HistoricProcessInstanceQuery;
- import org.activiti.engine.impl.persistence.entity.TaskEntity;
- import org.activiti.engine.repository.ProcessDefinition;
- import org.activiti.engine.runtime.ProcessInstance;
- import org.activiti.engine.task.NativeTaskQuery;
- import org.activiti.engine.task.Task;
- import org.activiti.engine.task.TaskQuery;
- import org.apache.commons.lang.xwork.StringUtils;
- import org.apache.commons.lang3.time.DateFormatUtils;
- import org.apache.log4j.Logger;
- import org.hibernate.Query;
- import org.jeecgframework.core.common.exception.BusinessException;
- import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
- import org.jeecgframework.core.common.model.json.DataGrid;
- import org.jeecgframework.core.common.model.json.DataGridReturn;
- import org.jeecgframework.core.util.*;
- import org.jeecgframework.minidao.pojo.MiniDaoPage;
- import org.jeecgframework.minidao.util.MiniDaoUtil;
- import org.jeecgframework.tag.vo.datatable.SortDirection;
- import org.jeecgframework.web.system.pojo.base.TSBaseUser;
- import org.jeecgframework.web.system.pojo.base.TSDepart;
- import org.jeecgframework.web.system.pojo.base.TSType;
- import org.jeecgframework.web.system.pojo.base.TSUser;
- import org.jeecgframework.web.system.service.SystemService;
- import org.jeecgframework.workflow.common.WorkFlowGlobals;
- import org.jeecgframework.workflow.dao.IActivitiCommonDao;
- import org.jeecgframework.workflow.pojo.activiti.ActHiTaskinst;
- import org.jeecgframework.workflow.pojo.activiti.ActHiVarinst;
- import org.jeecgframework.workflow.pojo.base.TPProcess;
- import org.jeecgframework.workflow.service.ActivitiService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import org.springframework.web.multipart.MultipartFile;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.SocketTimeoutException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.Map.Entry;
- @Controller
- @RequestMapping(value = "/api/wxdispatch")
- public class WXController {
- private static final Logger logger = Logger.getLogger(WXController.class);
- @Autowired
- SystemService systemService;
- @Autowired
- WXDao wxdao;
- @Autowired
- private DataviewServiceI dvservice;
- @Autowired
- private TSysFileServiceI tSysFileService;
- @Autowired
- private ActivitiService activitiService;
- @Autowired
- private HistoryService historyService;
- @Autowired
- protected RepositoryService repositoryService;
- @Autowired
- private WxTokenService wxTokenService;
- @Autowired
- private XcglRptDao rptDao;
- @Autowired
- private RuntimeService runtimeService;
- @Autowired
- private IActivitiCommonDao activitiCommonDao;
- @Autowired
- protected TaskService taskService;
- @Autowired
- private MMessageServiceI mMessageService;
- @Autowired
- private MPersonalMessageServiceI mPersonalMessageService;
- @Autowired
- private MMessageReplyServiceI mMessageReplyService;
- /**
- * 访问地址:http://localhost:8080/xcgl/api/wx
- *
- * @return
- */
- @RequestMapping(method = RequestMethod.GET)
- @ResponseBody
- public WXAjaxJson checkNet() {
- WXAjaxJson json = new WXAjaxJson();
- // String key = "userAccessory/03fbd2d1-5d97-4aed-9a33-91a7849b8d62.jpg";
- // HashMap<String, String> mediaurl = new HashMap<String, String>();
- // try {
- // URL url = getAliyunImgByurl(key);
- // mediaurl.put("url", url.toString());
- // } catch (Exception e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- // json.setData(mediaurl);
- return json;
- }
- @RequestMapping(value = "user/get_user_info")
- @ResponseBody
- public WXAjaxJson getUserInfo(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = request.getParameter("openid");
- if (!StringUtils.isNotBlank(openid)) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- UserDto data = wxdao.getUser(openid);
- if (data == null) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- // 设置组织机构
- String orgId = data.getProjectid();
- String[] project = getParentProject(orgId);
- data.setProjectid(project[0]);
- data.setProjectname(project[1]);
- if (StringUtils.isNotEmpty(data.getJgprojectids())) {
- ArrayList<String> ids = new ArrayList<String>();
- ArrayList<String> names = new ArrayList<String>();
- String[] jzproject = data.getJgprojectids().split(",");
- for (String pid : jzproject) {
- String[] jzpro = getParentProject(pid);
- ids.add(jzpro[0]);
- names.add(jzpro[1]);
- }
- data.setJgprojectids(StringUtils.join(ids, ","));
- data.setJgprojectnames(StringUtils.join(names, ","));
- }
- //设置项目未完成工作数量
- // Map projectcount = getUserProjectNotFinashTaskCount(data.getUserid());
- // data.setProjectTaskCount(projectcount);
- //是否项目人员
- boolean isProjectUser = UserUtil.isProjectUser(data.getUserid());
- json.setData(data);
- ;
- return json;
- }
- private String[] getParentProject(String projectid) {
- String[] temp = new String[2];
- if (!StringUtils.isNotEmpty(projectid)) {
- return temp;
- }
- StringBuffer hql = new StringBuffer("from TSDepart where id = :pid");
- List<TSDepart> tsList = systemService.getSession().createQuery(hql.toString()).setParameter("pid", projectid).list();
- if (!tsList.isEmpty()) {
- TSDepart tsDepart = tsList.get(0);
- //直属项目、区域项目、公司类型
- if ("3".equals(tsDepart.getOrgType()) || "5".equals(tsDepart.getOrgType()) || "1".equals(tsDepart.getOrgType())
- || ("2".equals(tsDepart.getOrgType()) && ("1".equals(tsDepart.getTSPDepart().getOrgType())))) {
- temp[0] = tsDepart.getId();
- temp[1] = tsDepart.getDescription();
- } else if ("2".equals(tsDepart.getOrgType()) && ("1".equals(tsDepart.getTSPDepart().getOrgType())
- || "3".equals(tsDepart.getTSPDepart().getOrgType()) || "5".equals(tsDepart.getTSPDepart().getOrgType()))) {
- temp[0] = tsDepart.getTSPDepart().getId();
- temp[1] = tsDepart.getTSPDepart().getDescription();
- }
- }
- return temp;
- }
- @RequestMapping(value = "user/getProjectList4Mine")
- @ResponseBody
- public WXAjaxJson getProjectList4Mine(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = request.getParameter("openid");
- if (!StringUtils.isNotBlank(openid)) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- UserDto userdata = wxdao.getUser(openid);
- if (userdata == null) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- // 设置组织机构
- Map<String, String> projectAndNameMap = new HashMap<String, String>();
- String orgId = userdata.getProjectid();
- String[] project = getParentProject(orgId);
- projectAndNameMap.put(project[0], project[1]);
- if (StringUtils.isNotEmpty(userdata.getJgprojectids())) {
- String[] jzproject = userdata.getJgprojectids().split(",");
- for (String pid : jzproject) {
- String[] jzpro = getParentProject(pid);
- projectAndNameMap.put(jzpro[0], jzpro[1]);
- }
- }
- //设置项目未完成工作数量
- List<Map<String, Object>> projectcount = getUserProjectNotFinashTaskCount(userdata.getUserid());
- for (Map<String, Object> pcountMap : projectcount) {
- if (projectAndNameMap.containsKey(pcountMap.get("id"))) {
- projectAndNameMap.remove(pcountMap.get("id"));
- }
- }
- for (Entry<String, String> projectIDName : projectAndNameMap.entrySet()) {
- Map<String, Object> oneProjectMap = new HashMap<String, Object>();
- oneProjectMap.put("id", projectIDName.getKey());
- oneProjectMap.put("name", projectIDName.getValue());
- oneProjectMap.put("count", "0");
- projectcount.add(oneProjectMap);
- }
- json.setData(projectcount);
- ;
- return json;
- }
- private List<Map<String, Object>> getUserProjectNotFinashTaskCount(String userid) {
- String taskCountSql = "select cast(count(1) as char) count , task.projectid id,project.description name from p_projecttask task \n" +
- "left join t_s_depart project on task.projectid = project.id\n" +
- "where owner =? and taskstatus in ('0','1') and left(task.planendtime,10)<=? group by task.projectid";
- List<Map<String, Object>> lsCount = systemService.findForJdbc(taskCountSql, userid, DateUtils.date_sdf.format(new Date()));
- return lsCount;
- }
- @RequestMapping(value = "user/getProjectList")
- @ResponseBody
- public WXAjaxJson getProjectList(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = request.getParameter("openid");
- if (!StringUtils.isNotBlank(openid)) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- UserDto userdata = wxdao.getUser(openid);
- if (userdata == null) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- // 设置组织机构
- Map<String, String> projectAndNameMap = new HashMap<String, String>();
- String orgId = userdata.getProjectid();
- String[] project = getParentProject(orgId);
- projectAndNameMap.put(project[0], project[1]);
- if (StringUtils.isNotEmpty(userdata.getJgprojectids())) {
- String[] jzproject = userdata.getJgprojectids().split(",");
- for (String pid : jzproject) {
- String[] jzpro = getParentProject(pid);
- projectAndNameMap.put(jzpro[0], jzpro[1]);
- }
- }
- //设置项目未完成工作数量
- List<Map<String, Object>> projectcount = getProjectNotFinashTaskCount("'" + StringUtils.join(projectAndNameMap.keySet(), "','") + "'");
- for (Map<String, Object> pcountMap : projectcount) {
- if (projectAndNameMap.containsKey(pcountMap.get("id"))) {
- projectAndNameMap.remove(pcountMap.get("id"));
- }
- }
- for (Entry<String, String> projectIDName : projectAndNameMap.entrySet()) {
- Map<String, Object> oneProjectMap = new HashMap<String, Object>();
- oneProjectMap.put("id", projectIDName.getKey());
- oneProjectMap.put("name", projectIDName.getValue());
- oneProjectMap.put("count", "0");
- projectcount.add(oneProjectMap);
- }
- json.setData(projectcount);
- ;
- return json;
- }
- private List<Map<String, Object>> getProjectNotFinashTaskCount(String projectids) {
- String taskCountSql = "select cast(count(1) as char) count , task.projectid id,project.description name from p_projecttask task \n" +
- "left join t_s_depart project on task.projectid = project.id\n" +
- "where task.projectid in (" + projectids + ") and taskstatus in ('0','1') group by task.projectid";
- List<Map<String, Object>> lsCount = systemService.findForJdbc(taskCountSql);
- return lsCount;
- }
- /**
- * 微信绑定手机号
- */
- @RequestMapping(value = "user/bindTel")
- @ResponseBody
- public WXAjaxJson bindTel(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = request.getParameter("openid");
- String phonenum = request.getParameter("phonenum");
- String timestamp = request.getParameter("timestamp");
- if (!StringUtils.isNotBlank(openid)) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- } else if (!StringUtils.isNotBlank(phonenum)) {
- json.setCode(XcglConstant.RETCODE_PHONE_NOTFOUND);
- json.setMsg(XcglConstant.RETMSG_PHONE_NOTFOUND);
- return json;
- } else if (!StringUtils.isNotBlank(timestamp)) {
- json.setCode(XcglConstant.RETCODE_TIMEOUT);
- json.setMsg(XcglConstant.RETMSG_TIMEOUT);
- return json;
- }
- //只有【已入职】、【已转正】状态的员工才可以注册
- String uptOpenidSql = " update t_s_user set openid =? where mobilePhone =? and "
- + "id in (select userid from t_bus_user_personnel where position_status in ('1','2'))";
- Integer count = systemService.executeSql(uptOpenidSql, openid, phonenum);
- if (count == 0) {
- json.setCode(XcglConstant.RETCODE_PHONE_NOTFOUND);
- json.setMsg(XcglConstant.RETMSG_PHONE_NOTFOUND);
- }
- return json;
- }
- /**
- * 下载图片
- */
- @RequestMapping(value = "user/download_wx_media")
- @ResponseBody
- public WXAjaxJson downloadWXMedia(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- Map map = new HashMap<String, String>();
- json.setAttributes(map);
- return json;
- }
- /**
- * 上传附件
- */
- @RequestMapping(value = "user/uploadAttachment")
- @ResponseBody
- public WXAjaxJson uploadAttachment(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String userid = oConvertUtils.getString(request.getParameter("userid"));
- String upFlag = oConvertUtils.getString(request.getParameter("isup"));
- String delFlag = oConvertUtils.getString(request.getParameter("isdel"));
- String mediaid = oConvertUtils.getString(request.getParameter("picture0id")) +
- oConvertUtils.getString(request.getParameter("picture1id")) +
- oConvertUtils.getString(request.getParameter("picture2id")) +
- oConvertUtils.getString(request.getParameter("picture3id")) +
- oConvertUtils.getString(request.getParameter("picture4id")) +
- oConvertUtils.getString(request.getParameter("picture5id")) +
- oConvertUtils.getString(request.getParameter("picture6id"));
- // String token = oConvertUtils.getString(request.getParameter("accessToken"));
- String token = wxTokenService.getSkey();
- try {
- //如果是上传操作
- if ("1".equals(upFlag)) {
- HashMap<String, String> mediaurl = new HashMap<String, String>();
- String busiId = com.xcgl.utils.UUID.randomUUID().toString();
- String fileName = null;
- TSBaseUser baseUser = systemService.get(TSBaseUser.class, userid);
- //附件类型名,例如:*户口本本人页
- String accessoryName = null;
- //附件类型枚举 例如:hukoubenbenrenye4
- String accessoryType = null;
- String bizType = "userAccessory";//request.getParameter("bizType");//上传业务名称
- if (oConvertUtils.getString(request.getParameter("picture0id")).length() > 0) {
- accessoryName = "*身份证复印件";
- accessoryType = "shenfenzhengfuyinjian2";
- } else if (oConvertUtils.getString(request.getParameter("picture1id")).length() > 0) {
- accessoryName = "*政审材料第一页";
- accessoryType = "zhengshencailiao5";
- } else if (oConvertUtils.getString(request.getParameter("picture2id")).length() > 0) {
- accessoryName = "*政审材料第二页";
- accessoryType = "zhengshencailiao6";
- } else if (oConvertUtils.getString(request.getParameter("picture3id")).length() > 0) {
- accessoryName = "*体检表第一页";
- accessoryType = "tijianbiao1";
- } else if (oConvertUtils.getString(request.getParameter("picture4id")).length() > 0) {
- accessoryName = "*体检表第二页";
- accessoryType = "tijianbiao7";
- } else if (oConvertUtils.getString(request.getParameter("picture5id")).length() > 0) {
- accessoryName = "*户口本首页";
- accessoryType = "hukoubenshouye3";
- } else if (oConvertUtils.getString(request.getParameter("picture6id")).length() > 0) {
- accessoryName = "*户口本本人页";
- accessoryType = "hukoubenbenrenye4";
- } else if (oConvertUtils.getString(request.getParameter("picture7id")).length() > 0) {
- accessoryName = "*离职报告";
- accessoryType = "lizhibaogao8";
- }
- String extName = "jpg";//FileUtils.getExtend(fileName);
- fileName = baseUser.getRealName() + accessoryName.substring(1) + "." + extName;
- List<String> keyAndUrl = getWXfileToOSS(extName, bizType, token, mediaid);
- // List<String> keyAndUrl = getWXfileToOSSTest(extName, "test", token, mediaid, request);
- if (keyAndUrl.size() == 2) {
- mediaurl.put("url", keyAndUrl.get(1));
- String busiTable = "t_bus_accessory";// request.getParameter("busiTable");
- TSysFileEntity tSysFileEntity = new TSysFileEntity();
- tSysFileEntity.setBusiId(busiId);// 业务id
- tSysFileEntity.setFileUrl(keyAndUrl.get(0));// 文件访问路径
- tSysFileEntity.setFileName(fileName);// 文件名称
- tSysFileEntity.setTagetType(bizType);// 文件类型
- tSysFileEntity.setBusiTable(oConvertUtils.getString(busiTable));
- tSysFileService.save(tSysFileEntity);
- // 保存业务表
- String accessorySql = "INSERT INTO t_bus_accessory(id, accessory_name, userid, isfixed, gatet_type, delete_flag) "
- + "VALUES (?, ?, ?, '1', ?, '0')";
- systemService.executeSql(accessorySql, busiId, accessoryName, userid, accessoryType);
- // }
- json.setData(mediaurl);
- }
- } else if ("1".equals(delFlag)) {//如果是删除操作
- // TODO 删除业务表数据,再删除oss,t_sys_file数据
- Map<String, String[]> params = request.getParameterMap();
- String ossKey = deleteAccSysfile(params, userid);
- if (!deleteOssfile(ossKey)) {
- String msg = MutiLangUtil.getMutiLangInstance().getLang("file.warn.filelost");
- // 不存在前台也给他删除
- json.setMsg(msg);
- }
- } else {
- throw new BusinessException("没有传参指定上传还是删除操作!");
- }
- } catch (IOException e) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(e.getMessage());
- logger.error(e.getMessage());
- } catch (BusinessException b) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(b.getMessage());
- logger.error(b.getMessage());
- } catch (Exception e) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(e.getMessage());
- logger.error(e.getMessage());
- }
- return json;
- }
- /**
- * 从微信获取临时素材,存入到oss中
- */
- private List<String> getWXfileToOSSTest(String extName, String bizType, String wxtoken, String mediaid, HttpServletRequest request) throws IOException {
- List<String> keyAndUrl = new ArrayList<String>();
- InputStream input = null;
- int fileLength = 0;
- String realpath = request.getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/") + "/images/";
- String getURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + wxtoken + "&media_id=" + mediaid;
- FileInputStream is = null;
- FileOutputStream fileOutputStream = null;
- OSSClient ossClient = null;
- HttpURLConnection conn = null;
- try {
- URL url = new URL(getURL);
- logger.error("start: get image from weixin " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setRequestMethod("GET");
- conn.connect();
- logger.error("end: get image from weixin " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- fileLength = conn.getContentLength();
- input = conn.getInputStream();
- logger.error("get inputSteam from weixin connection,over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- String uuid = com.xcgl.utils.UUID.randomUUID().toString();
- fileOutputStream = new FileOutputStream(realpath + uuid + ".jpg");
- int len = 0;
- byte[] data = new byte[1024];
- while ((len = input.read(data)) != -1) {
- fileOutputStream.write(data, 0, len);
- }
- fileOutputStream.close();
- logger.error("image save local over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- is = new FileInputStream(realpath + uuid + ".jpg");
- int i = is.available(); // 得到文件大小
- byte dataUp[] = new byte[i];
- is.read(dataUp);
- logger.error("image read over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- // 创建上传Object的Metadata
- ObjectMetadata meta = new ObjectMetadata();
- // 设置contenttype否则上传图片在oss上预览时不显示图片
- meta.setContentType("image/jpeg");
- // 必须设置ContentLength
- meta.setContentLength(fileLength);
- // 创建OSSClient实例
- logger.error("start : OSS " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- logger.error("new OSS client over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- String key = String.format(bizType + "/%s", uuid + "." + extName);
- ossClient.putObject(CustomerConstant.BUCKETNAME, key, new ByteArrayInputStream(dataUp), meta);
- logger.error("pus object to OSS over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
- logger.error("get OSS object URL over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- logger.error("end OSS work: " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- keyAndUrl.add(key);
- keyAndUrl.add(fileUrl.toString());
- // 关闭client
- // ossClient.shutdown();
- // conn.disconnect();
- } catch (SocketTimeoutException e) {
- logger.error("获取微信图片请求出错: " + e);
- } catch (Exception ex) {
- ex.printStackTrace();
- logger.error("获取微信图片请求出错: " + ex);
- } finally {
- if (ossClient != null)
- ossClient.shutdown();
- if (conn != null)
- conn.disconnect();
- if (is != null)
- is.close();
- }
- return keyAndUrl;
- }
- /**
- * 从微信获取临时素材,存入到oss中
- */
- private List<String> getWXfileToOSS(String extName, String bizType, String wxtoken, String mediaid) throws IOException {
- List<String> keyAndUrl = new ArrayList<String>();
- try {
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- keyAndUrl = savefileToOSS(ossClient, extName, bizType, wxtoken, mediaid);
- // 关闭client
- ossClient.shutdown();
- } catch (SocketTimeoutException e) {
- logger.error("获取微信图片请求出错: " + e);
- } catch (Exception ex) {
- ex.printStackTrace();
- logger.error("获取微信图片请求出错: " + ex);
- }
- return keyAndUrl;
- }
- /**
- * 从微信获取临时素材,存入到oss中
- */
- private List<String> savefileToOSS(OSSClient ossClient, String extName, String bizType, String wxtoken, String mediaid) throws IOException {
- logger.error("********** toOSS start **********");
- logger.error("accessToken:" + wxtoken);
- logger.error("mediaid:" + mediaid);
- logger.error("*********** toOSS end *********");
- List<String> keyAndUrl = new ArrayList<String>();
- InputStream input = null;
- int fileLength = 0;
- String getURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + wxtoken + "&media_id=" + mediaid;
- try {
- URL url = new URL(getURL);
- logger.error("start: get image from weixin " + getURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setRequestMethod("GET");
- conn.connect();
- logger.error("end: get image from weixin ");
- fileLength = conn.getContentLength();
- input = conn.getInputStream();
- String uuid = com.xcgl.utils.UUID.randomUUID().toString();
- // 创建上传Object的Metadata
- ObjectMetadata meta = new ObjectMetadata();
- // 设置contenttype否则上传图片在oss上预览时不显示图片
- meta.setContentType("image/jpeg");
- // 必须设置ContentLength
- meta.setContentLength(fileLength);
- // 创建OSSClient实例
- String date = DateUtils.formatDate(new Date(), "yyyyMM");
- logger.error("start : OSS " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- logger.error("new OSS client over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- String key = String.format(bizType + "/%s/%s", date, uuid + "." + extName);
- ossClient.putObject(CustomerConstant.BUCKETNAME, key, input, meta);
- logger.error("pus object to OSS over");
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
- logger.error("get OSS object URL over");
- logger.error("end OSS work: " + fileUrl);
- keyAndUrl.add(key);
- keyAndUrl.add(fileUrl.toString());
- conn.disconnect();
- } catch (SocketTimeoutException e) {
- logger.error("获取微信图片请求出错: " + e);
- } catch (Exception ex) {
- ex.printStackTrace();
- logger.error("获取微信图片请求出错: " + ex);
- }
- return keyAndUrl;
- }
- private List<String> saveVideoToOSS(OSSClient ossClient, MultipartFile video, String bizType) {
- List<String> keyAndUrl = new ArrayList<String>();
- try {
- ObjectMetadata meta = new ObjectMetadata();
- // 设置contenttype否则上传图片在oss上预览时不显示图片
- meta.setContentType(video.getContentType());
- // 必须设置ContentLength
- meta.setContentLength(video.getSize());
- String fileName = video.getOriginalFilename();
- String uuid = UUID.randomUUID().toString();
- String key = String.format(bizType + "/video/%s", uuid + "." + FileUtils.getExtend(fileName));
- ossClient.putObject(CustomerConstant.BUCKETNAME, key, video.getInputStream(), meta);
- logger.error("pus object to OSS over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
- logger.error("get OSS object URL over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
- logger.error("end OSS work: " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS") + fileUrl.toString());
- keyAndUrl.add(key);
- keyAndUrl.add(fileUrl.toString());
- } catch (Exception ex) {
- ex.printStackTrace();
- logger.error("请求出错: " + ex);
- }
- return keyAndUrl;
- }
- private String saveToOSS(String extName, String bizType, InputStream fileStream, int fileLength, URL fileUrl) throws IOException {
- String uuid = com.xcgl.utils.UUID.randomUUID().toString();
- // 创建上传Object的Metadata
- ObjectMetadata meta = new ObjectMetadata();
- // 设置contenttype否则上传图片在oss上预览时不显示图片
- meta.setContentType("image/jpeg");
- // 必须设置ContentLength
- meta.setContentLength(fileLength);
- // 创建OSSClient实例
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- String key = String.format(bizType + "/%s", uuid + "." + extName);
- ossClient.putObject(CustomerConstant.BUCKETNAME, key, fileStream, meta);
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
- // 关闭client
- ossClient.shutdown();
- return key;
- }
- private boolean deleteOssfile(String path) {
- // 创建OSSClient实例
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- // Object是否存在
- boolean found = ossClient.doesObjectExist(CustomerConstant.BUCKETNAME, path);
- if (found) {
- ossClient.deleteObject(CustomerConstant.BUCKETNAME, path);
- ossClient.shutdown();
- return true;
- }
- return false;
- }
- /**
- * 1、删除系统数据库中记录的文件信息
- *
- * @return ossKey
- */
- private String deleteAccSysfile(Map<String, String[]> params, String userid) {
- String accessoryType = "";
- if (params.containsKey("picture0id")) {
- accessoryType = "shenfenzhengfuyinjian2";
- } else if (params.containsKey("picture1id")) {
- accessoryType = "zhengshencailiao5";
- } else if (params.containsKey("picture2id")) {
- accessoryType = "zhengshencailiao6";
- } else if (params.containsKey("picture3id")) {
- accessoryType = "tijianbiao1";
- } else if (params.containsKey("picture4id")) {
- accessoryType = "tijianbiao7";
- } else if (params.containsKey("picture5id")) {
- accessoryType = "hukoubenshouye3";
- } else if (params.containsKey("picture6id")) {
- accessoryType = "hukoubenbenrenye4";
- }
- if (accessoryType.length() == 0)
- return "";
- String qrySysFileSql = "select file_url from t_sys_file where busi_table = 't_bus_accessory' " +
- "and busi_id in (select id from t_bus_accessory where userid =? and gatet_type = ? ) ";
- List<Map<String, Object>> ret = systemService.findForJdbc(qrySysFileSql, userid, accessoryType);
- if (ret.size() == 0)
- return "";
- String ossKey = ret.get(0).get("file_url").toString();
- //删除系统文件库数据
- String delSysFileSql = "delete from t_sys_file where busi_table = 't_bus_accessory' " +
- "and busi_id in (select id from t_bus_accessory where userid =? and gatet_type = ? ) ";
- systemService.executeSql(delSysFileSql, userid, accessoryType);
- return ossKey;
- }
- /**
- * 从服务器获取用户功能权限
- */
- @RequestMapping(value = "user/qryAuth")
- @ResponseBody
- public WXAjaxJson qryAuth(HttpServletRequest request) {
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- WXAjaxJson json = new WXAjaxJson();
- List<AuthorityDto> data = wxdao.getAuthByOpenid(openid);
- for (AuthorityDto auth : data) {
- auth.setAlert("0");
- //查询设备是否有异常,如果有异常,则前台界面小红点提示
- if (auth.getOptName().equals("设备监测")) {
- String alertSql = "select count(*) total from p_sensor_abnormal abn\n" +
- "left join p_sensor_monitor_point point on abn.monitor_point_id = point.id\n" +
- "where left(abn.create_date,10) = '2018-09-09'\n" +
- "and point.projectid in (select org_id from t_s_user_org uorg "
- + "left join t_s_user user on user.id = uorg.user_id where ifpluralism = '0' and openid = ?)";
- List<Map<String, Object>> ret = systemService.findForJdbc(alertSql, openid);
- if (ret.size() > 0 && Integer.parseInt(ret.get(0).get("total").toString()) > 0) {
- auth.setAlert("1");
- }
- }
- if (!auth.getEnable().equals("0"))
- auth.setEnable("1");
- }
- json.setData(data);
- return json;
- }
- /**
- * 变更工作状态
- */
- @RequestMapping(value = "task/changeWorkStatus")
- @ResponseBody
- public WXAjaxJson changeWorkStatus(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String userid = oConvertUtils.getString(request.getParameter("userid"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- String oldStatus = oConvertUtils.getString(request.getParameter("oldStatus"));
- String newStatus = oConvertUtils.getString(request.getParameter("newStatus"));
- String closeReason = oConvertUtils.getString(request.getParameter("closeReason"));
- ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
- if (task == null || !task.getTaskstatus().equals(oldStatus)) {
- json.setCode(XcglConstant.RETCODE_TASK_ERROR);
- json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
- return json;
- }
- String changeSql = "";
- switch (newStatus) {
- case XcglConstant.TASKSTATUS_EXEING:
- changeSql = "update p_projecttask set taskstatus =? ,executer = ? ,exestarttime=? where id = ? ";
- systemService.executeSql(changeSql, newStatus, userid, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
- break;
- case XcglConstant.TASKSTATUS_CLOSED:
- changeSql = "update p_projecttask set taskstatus =? ,executer = ? ,closemsg=? where id = ? ";
- systemService.executeSql(changeSql, newStatus, userid, closeReason, taskid);
- break;
- case XcglConstant.TASKSTATUS_DONE:
- changeSql = "update p_projecttask set taskstatus =? ,exeendtime =? where id = ? ";
- systemService.executeSql(changeSql, newStatus, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
- break;
- }
- return json;
- }
- /**
- * 提交工作执行结果
- */
- @RequestMapping(value = "task/sendWorkResult")
- @ResponseBody
- public WXAjaxJson sendWorkResult(
- @RequestParam(value = "video", required = false) MultipartFile video, HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- int progress = oConvertUtils.getInt(request.getParameter("progress"), 100);
- String pictureids = oConvertUtils.getString(request.getParameter("pictureids"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- String texts = oConvertUtils.getString(request.getParameter("texts"));
- // String token = oConvertUtils.getString(request.getParameter("accessToken"));
- String token = wxTokenService.getSkey();
- int isTemp = oConvertUtils.getInt(request.getParameter("isTemp"), 0);
- ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
- Map<String, String[]> params = request.getParameterMap();
- // logger.error("********** params start **********");
- // for(Entry<String, String[]> entity : params.entrySet()) {
- // logger.error(entity.getKey());
- // logger.error(entity.getValue().length>0?entity.getValue()[0]:"");
- // }
- // logger.error("*********** params end *********");
- // logger.error("accessToken:"+token);
- // logger.error(openid);
- // logger.error(pictureids);
- // logger.error(taskid);
- // logger.error(texts);
- if (task == null) {
- json.setCode(XcglConstant.RETCODE_TASK_ERROR);
- json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
- return json;
- }
- TaskResultEntity resultEntity = null;
- List<TaskResultEntity> list = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
- if(list != null && list.size() > 0) {
- resultEntity = list.get(0);
- } else {
- resultEntity = new TaskResultEntity();
- }
- resultEntity.setTaskid(taskid);
- resultEntity.setMemo(texts);
- Integer qualityScore = oConvertUtils.getInt(request.getParameter("qualityScore"));//服务质量
- Integer efficiencyScore = oConvertUtils.getInt(request.getParameter("efficiencyScore"));//服务时效
- Integer attitudeScore = oConvertUtils.getInt(request.getParameter("attitudeScore"));//服务态度
- Integer skillsScore = oConvertUtils.getInt(request.getParameter("skillsScore"));//技术能力
- Integer taskObjectScore = oConvertUtils.getInt(request.getParameter("taskObjectScore"));//总分
- resultEntity.setEfficiencyScore(efficiencyScore);
- resultEntity.setQualityScore(qualityScore);
- resultEntity.setSkillsScore(skillsScore);
- resultEntity.setReviewScore(0);
- resultEntity.setTaskObjectScore(taskObjectScore);
- resultEntity.setAttitudeScore(attitudeScore);
- resultEntity.setCreateDate(new Date());
- resultEntity.setCreateBy("system");
- //最多10个图片
- String[] keys = new String[10];
- OSSClient ossClient = null;
- try {
- if (pictureids.length() > 0 || (video != null && !video.isEmpty())) {
- ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- }
- if (pictureids.length() > 0) {
- String[] picList = pictureids.split(",");
- //存储到oss
- String extName = "jpg";//FileUtils.getExtend(fileName);
- int index = 0;
- for (String mediaid : picList) {
- String bizType = "projecttask";
- if(mediaid.startsWith(bizType)) {
- keys[index] = mediaid;
- } else {
- List<String> keyAndUrl = savefileToOSS(ossClient, extName, bizType, token, mediaid);
- if (keyAndUrl.size() == 2) {
- keys[index] = keyAndUrl.get(0);
- }
- }
- index++;
- }
- }
- if (video != null && !video.isEmpty()) {
- List<String> keyAndUrl = saveVideoToOSS(ossClient, video, "project");
- resultEntity.setVideo(keyAndUrl.get(0));
- }
- if(ossClient != null) {
- ossClient.shutdown();
- }
- } catch (Exception e) {
- json.setCode(XcglConstant.RETCODE_PICTURE_ERROR);
- json.setMsg(XcglConstant.RETMSG_PICTURE_ERROR);
- return json;
- } finally {
- if (ossClient != null)
- ossClient.shutdown();
- }
- // String workRsultSql = " INSERT INTO p_taskresult(id, taskid, picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9, picture10, memo) "
- // + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
- resultEntity.setProgress(progress);
- resultEntity.setPicture1(keys[0]);
- resultEntity.setPicture2(keys[1]);
- resultEntity.setPicture3(keys[2]);
- resultEntity.setPicture4(keys[3]);
- resultEntity.setPicture5(keys[4]);
- resultEntity.setPicture6(keys[5]);
- resultEntity.setPicture7(keys[6]);
- resultEntity.setPicture8(keys[7]);
- resultEntity.setPicture9(keys[8]);
- resultEntity.setPicture10(keys[9]);
- systemService.save(resultEntity);
- // systemService.executeSql(workRsultSql, UUID.randomUUID().toString(),taskid,keys[0],keys[1],keys[2],keys[3],keys[4],keys[5],keys[6],keys[7],keys[8],keys[9],texts);
- if(isTemp != 1 && progress == 100) {
- String changeSql = "update p_projecttask set taskstatus =? ,exeendtime =? where id = ? ";
- systemService.executeSql(changeSql, XcglConstant.TASKSTATUS_DONE, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
- if(org.apache.commons.lang3.StringUtils.equals(task.getSourcetype(), "caralarm")){
- CarAlarmEntity entity = systemService.get(CarAlarmEntity.class, task.getSourceid());
- entity.setExecuteDesc(resultEntity.getMemo());
- entity.setStatus(1);
- systemService.save(entity);
- }
- }
- if(isTemp!=1){
- task.setTemp(0);
- }
- task.setCompletePer(String.valueOf(progress));
- systemService.updateEntitie(task);
- json.setData(keys);
- return json;
- }
- @RequestMapping(value = "task/qryWorkResult")
- @ResponseBody
- public WXAjaxJson qryWorkResult(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- List<TaskResultEntity> entitys = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
- Map<String, Object> retMap = new HashMap<String, Object>();
- List<String> picURL = new ArrayList<String>();
- if (entitys != null && entitys.size() > 0) {
- TaskResultEntity entity = entitys.get(0);
- picURL = setTaskPicURL(entity);
- List<String> taskPictures = getTaskPictures(entity);
- String videoURL = setTaskVideoURL(entity);
- if (org.jeecgframework.p3.core.utils.common.StringUtils.isEmpty(entity.getMemo())
- && picURL.size() == 0) {
- retMap.put("taskid", entity.getId());
- retMap.put("text", "");
- retMap.put("pictures", picURL);
- } else {
- List<Map<String, Object>> pictures = new ArrayList<>();
- for (int i=0; i < taskPictures.size(); i++) {
- Map<String, Object> picItem = new HashMap<String, Object>();
- picItem.put("src", picURL.get(i));
- picItem.put("mediaid", taskPictures.get(i));
- pictures.add(picItem);
- }
- retMap.put("taskid", entity.getId());
- retMap.put("text", entity.getMemo());
- retMap.put("pictures", pictures);
- }
- retMap.put("video", videoURL);
- retMap.put("progress", entity.getProgress());
- json.setData(retMap);
- return json;
- } else {
- retMap.put("taskid", taskid);
- retMap.put("text", "");
- retMap.put("pictures", picURL);
- retMap.put("video", null);
- json.setData(retMap);
- }
- return json;
- }
- /**
- * 上报或分配工作
- */
- @RequestMapping(value = "task/dispatchWork")
- @ResponseBody
- public WXAjaxJson dispatchWork(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- //指派类型: '0':上报 '1':分配下级
- String dispatchType = oConvertUtils.getString(request.getParameter("dispatchType"));
- String newOwner = oConvertUtils.getString(request.getParameter("newOwner"));
- ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
- if (task == null) {
- json.setCode(XcglConstant.RETCODE_TASK_ERROR);
- json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
- logger.error("找不到项目信息");
- return json;
- }
- if (dispatchType.equals("0")) {//上报
- //查询项目负责人
- String projectManager = "";
- String qryManagerSql = "select distinct suser.id manager from t_s_user_org userorg\n" +
- "left join t_s_user suser on suser.id = userorg.user_id\n" +
- "left join t_s_role_user ruser on suser.id = ruser.userid\n" +
- "left join t_s_role role on ruser.roleid = role.id\n" +
- "where role.rolecode = 'P_XMJL' and userorg.org_id = ?";
- List<Map<String, Object>> ret = systemService.findForJdbc(qryManagerSql, task.getProjectid());
- if (ret.size() == 0) {
- json.setCode(XcglConstant.RETCODE_TASK_ERROR);
- json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
- logger.error("task/dispatchWork,找不到项目负责人");
- return json;
- }
- projectManager = ret.get(0).get("manager").toString();
- String updTaskSql = "update p_projecttask set submittime = ? ,owner=? where id = ? ";
- systemService.executeSql(updTaskSql, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"), projectManager, taskid);
- } else if (dispatchType.equals("1")) {//分配下级
- String updTaskSql = "update p_projecttask set dispatchtime = ? ,owner=? where id = ? ";
- systemService.executeSql(updTaskSql, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"), newOwner, taskid);
- }
- return json;
- }
- /**
- * 查询用户工作
- * | openid | true | string | 用户openid |
- * | qrydate | false | string | 查询条件:日期,dateformater: yyyy-MM-dd hh:mm:ss ,参数中有taskid时,此参数可空|
- * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
- */
- @RequestMapping(value = "task/qryUserTasks")
- @ResponseBody
- public WXAjaxJson qryUserTasks(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- String qrydate = oConvertUtils.getString(request.getParameter("qrydate"));
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- if (StringUtils.isNotEmpty(taskid)) {
- openid = null;
- }
- //默认为今天
- qrydate = taskid.length() > 0 ? null : (qrydate.length() == 0 ? DateUtils.formatDate(new Date(), "yyyy-MM-dd") : qrydate);
- String status = oConvertUtils.getString(request.getParameter("status"));
- List<ProjecttaskEntity> data = null;
- switch (status) {
- case ""://全部
- data = wxdao.getTaskListAll(openid, qrydate, projectid, taskid);
- break;
- case "0"://未完成
- data = wxdao.getTaskListNotDone(openid, qrydate, projectid, taskid, null);
- break;
- case "20"://已完成
- data = wxdao.getTaskListDone(openid, qrydate, projectid, taskid);
- break;
- case "30"://逾期
- data = wxdao.getTaskListNotDone(openid, qrydate, projectid, taskid, "1");
- break;
- }
- Map<String, Object> retdata = new HashMap<String, Object>();
- retdata.put("list", data);
- retdata.put("hasmore", 0);
- if(data!=null&&!data.isEmpty()){
- ProjecttaskEntity projecttaskEntity = data.get(0);
- if(StringUtils.equals(projecttaskEntity.getId(),taskid)){
- String sourceType = projecttaskEntity.getSourcetype();
- if(StringUtils.equals(projecttaskEntity.getSourcetype(),"maintainbill")){
- String hql = "from MaintainBillEntity where taskId=? ";
- List<MaintainBillEntity> billList = systemService.findHql(hql,taskid);
- if(!billList.isEmpty()){
- MaintainBillEntity billEntity = billList.get(0);
- Map<String,Object> maintainBill = new HashMap<>();
- maintainBill.put("projectName", billEntity.getProjectname());//项目名称
- maintainBill.put("name", billEntity.getName());//计划名称
- String serviceType = DictUtil.formatToTypeName(billEntity.getServicetypedetail(),"servicetypedetail");
- maintainBill.put("serviceType", serviceType);//服务类型
- maintainBill.put("pojectServiceName", billEntity.getProjectservicename());//服务明细
- maintainBill.put("planDateStart", billEntity.getPlandatestart());//开始时间
- maintainBill.put("planDateEnd", billEntity.getPlandateend());//结束时间
- maintainBill.put("contractName", billEntity.getContractname());//合同名称
- maintainBill.put("relatedUnitName", billEntity.getRelatedunitname());//供应商名称
- String planId = billEntity.getMaintainPlanId();
- MaintainPlanEntity planEntity = systemService.get(MaintainPlanEntity.class,planId);
- maintainBill.put("remark", planEntity.getRemark());//备注
- String contractId = billEntity.getContractid();
- ContractEntity contractEntity = systemService.get(ContractEntity.class,contractId);
- maintainBill.put("contractStartDate", contractEntity.getStartdate());//合同开始时间
- maintainBill.put("contractEndDate", contractEntity.getEnddate());//合同结束时间
- retdata.put("maintainBill",maintainBill);
- }else if(StringUtils.equals(sourceType,"weeklymeeting")){
- hql = "from WeeklyMeetingEntity where projectTaskId=? ";
- List<WeeklyMeetingEntity> list = systemService.findHql(hql,taskid);
- if(!list.isEmpty()){
- WeeklyMeetingEntity entity = list.get(0);
- retdata.put("weeklymeeting",entity);
- }
- }
- }
- }
- }
- json.setData(retdata);
- return json;
- }
- /**
- * 查询用户工作
- * | openid | true | string | 用户openid |
- * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
- */
- @RequestMapping(value = "task/qryTaskResult")
- @ResponseBody
- public WXAjaxJson qryTaskResult(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- List<TaskResultEntity> entitys = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
- Map<String, Object> retMap = new HashMap<String, Object>();
- List<String> picURL = new ArrayList<String>();
- if (entitys != null && entitys.size() > 0) {
- TaskResultEntity entity = entitys.get(0);
- picURL = setTaskPicURL(entity);
- String videoURL = setTaskVideoURL(entity);
- if (org.jeecgframework.p3.core.utils.common.StringUtils.isEmpty(entity.getMemo())
- && picURL.size() == 0) {
- retMap.put("taskid", entity.getId());
- retMap.put("text", "工作已完成(描述:无,图片:无)");
- retMap.put("pictures", picURL);
- } else {
- retMap.put("taskid", entity.getId());
- retMap.put("text", entity.getMemo());
- retMap.put("pictures", picURL);
- }
- retMap.put("video", videoURL);
- retMap.put("progress", entity.getProgress());
- json.setData(retMap);
- return json;
- } else {
- retMap.put("taskid", taskid);
- retMap.put("text", "工作已完成(描述:无,图片:无)");
- retMap.put("pictures", picURL);
- retMap.put("video", null);
- json.setData(retMap);
- }
- return json;
- }
- private String setTaskVideoURL(TaskResultEntity taskResult) {
- if(StringUtil.isEmpty(taskResult.getVideo())) return null;
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- String url = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getVideo(), expiration).toString();
- ossClient.shutdown();
- return url;
- }
- private List<String> getTaskPictures(TaskResultEntity taskResult) {
- List<String> picURL = new ArrayList<String>();
- if (taskResult.getPicture1() != null && taskResult.getPicture1().trim().length() > 0) {
- picURL.add(taskResult.getPicture1());
- }
- if (taskResult.getPicture2() != null && taskResult.getPicture2().trim().length() > 0) {
- picURL.add(taskResult.getPicture2());
- }
- if (taskResult.getPicture3() != null && taskResult.getPicture3().trim().length() > 0) {
- picURL.add(taskResult.getPicture3());
- }
- if (taskResult.getPicture4() != null && taskResult.getPicture4().trim().length() > 0) {
- picURL.add(taskResult.getPicture4());
- }
- if (taskResult.getPicture5() != null && taskResult.getPicture5().trim().length() > 0) {
- picURL.add(taskResult.getPicture5());
- }
- if (taskResult.getPicture6() != null && taskResult.getPicture6().trim().length() > 0) {
- picURL.add(taskResult.getPicture6());
- }
- if (taskResult.getPicture7() != null && taskResult.getPicture7().trim().length() > 0) {
- picURL.add(taskResult.getPicture7());
- }
- if (taskResult.getPicture8() != null && taskResult.getPicture8().trim().length() > 0) {
- picURL.add(taskResult.getPicture8());
- }
- if (taskResult.getPicture9() != null && taskResult.getPicture9().trim().length() > 0) {
- picURL.add(taskResult.getPicture9());
- }
- if (taskResult.getPicture10() != null && taskResult.getPicture10().trim().length() > 0) {
- picURL.add(taskResult.getPicture10());
- }
- return picURL;
- }
- private List<String> setTaskPicURL(TaskResultEntity taskResult) {
- List<String> picURL = new ArrayList<String>();
- // 创建OSSClient实例
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- if (taskResult.getPicture1() != null && taskResult.getPicture1().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture1(), expiration).toString());
- }
- if (taskResult.getPicture2() != null && taskResult.getPicture2().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture2(), expiration).toString());
- }
- if (taskResult.getPicture3() != null && taskResult.getPicture3().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture3(), expiration).toString());
- }
- if (taskResult.getPicture4() != null && taskResult.getPicture4().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture4(), expiration).toString());
- }
- if (taskResult.getPicture5() != null && taskResult.getPicture5().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture5(), expiration).toString());
- }
- if (taskResult.getPicture6() != null && taskResult.getPicture6().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture6(), expiration).toString());
- }
- if (taskResult.getPicture7() != null && taskResult.getPicture7().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture7(), expiration).toString());
- }
- if (taskResult.getPicture8() != null && taskResult.getPicture8().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture8(), expiration).toString());
- }
- if (taskResult.getPicture9() != null && taskResult.getPicture9().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture9(), expiration).toString());
- }
- if (taskResult.getPicture10() != null && taskResult.getPicture10().trim().length() > 0) {
- picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture10(), expiration).toString());
- }
- // 关闭client
- ossClient.shutdown();
- return picURL;
- }
- /**
- * 查询项目工作
- * | projectid | true | string | 项目id |
- * | openid | true | string | 用户openid |
- * | qrydate | true | string | 查询条件:日期,dateformater: yyyy-MM-dd hh:mm:ss |
- * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
- */
- @RequestMapping(value = "task/qryProjectTasks")
- @ResponseBody
- public WXAjaxJson qryProjectTasks(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String taskid = oConvertUtils.getString(request.getParameter("taskid"));
- String qrydate = oConvertUtils.getString(request.getParameter("qrydate"));
- //默认为今天
- qrydate = taskid.length() > 0 ? null : (qrydate.length() == 0 ? DateUtils.formatDate(new Date(), "yyyy-MM-dd") : qrydate);
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- String status = oConvertUtils.getString(request.getParameter("status"));
- List<ProjecttaskEntity> data = null;
- switch (status) {
- case ""://全部
- data = wxdao.getTaskListAll(null, qrydate, projectid, taskid);
- break;
- case "0"://未完成
- data = wxdao.getTaskListNotDone(null, qrydate, projectid, taskid, null);
- break;
- case "20"://已完成
- data = wxdao.getTaskListDone(null, qrydate, projectid, taskid);
- break;
- case "30"://逾期
- data = wxdao.getTaskListNotDone(null, qrydate, projectid, taskid, "1");
- break;
- }
- Map<String, Object> retdata = new HashMap<String, Object>();
- retdata.put("list", data);
- retdata.put("hasmore", 0);
- json.setData(retdata);
- return json;
- }
- /**
- * 查询项目本日工作完成率
- * | projectid | true | string | 项目id |
- */
- @RequestMapping(value = "task/qryTodayWorkStati")
- @ResponseBody
- public WXAjaxJson qryTodayWorkStati(HttpServletRequest request) {
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- WXAjaxJson json = new WXAjaxJson();
- List<Map<String, Object>> list = null;
- try {
- SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
- String date = dateformat.format(new Date());
- list = wxdao.getTodayWorkStati(projectid, date);
- } catch (Exception e) {
- logger.error(e.getMessage());
- }
- // if(list == null || list.isEmpty()) {
- // return null;
- // }
- // Option option = new Option();
- //
- // List<Object> seriesdata = new ArrayList<Object>();
- // List<Axis> xaxisList = new ArrayList<Axis>();
- // List<Object> xaxisdata = new ArrayList<Object>();
- //
- // CategoryAxis axis = new CategoryAxis();
- //
- // xaxisList.add(axis);
- // for(Map<String,Object> oneRec : list) {
- // seriesdata.add(oneRec.get("rate"));
- // xaxisdata.add(oneRec.get("name"));
- // }
- // axis.setData(xaxisdata);
- // Bar bar = new Bar();
- // bar.setData(seriesdata);
- // option.xAxis(xaxisList);
- // option.series(bar);
- json.setData(list);
- return json;
- }
- /**
- * 查询项目七日内工作完成率
- * | projectid | true | string | 项目id |
- */
- @RequestMapping(value = "task/qryWeekWorkStati")
- @ResponseBody
- public WXAjaxJson qryWeekWorkStati(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
- String today = dateformat.format(new Date());
- String lastWeekDay = XcglDateUtils.addDateDay(today, -7, dateformat);
- List<Map<String, Object>> list = null;
- try {
- list = wxdao.getWeekWorkStati(projectid, today, lastWeekDay);
- } catch (Exception e) {
- logger.error(e.getMessage());
- }
- // if(list == null || list.isEmpty()) {
- // return null;
- // }
- // Option option = new Option();
- //
- // List<Object> seriesdata = new ArrayList<Object>();
- // List<Axis> xaxisList = new ArrayList<Axis>();
- // List<Object> xaxisdata = new ArrayList<Object>();
- //
- // CategoryAxis axis = new CategoryAxis();
- //
- // xaxisList.add(axis);
- // for(Map<String,Object> oneRec : list) {
- // if(oneRec.get("date").toString().length() == 10) {
- // seriesdata.add(oneRec.get("rate"));
- // xaxisdata.add(oneRec.get("date").toString().substring(5));
- // }
- // }
- // axis.setData(xaxisdata);
- // Bar bar = new Bar();
- // bar.setData(seriesdata);
- // option.xAxis(xaxisList);
- // option.series(bar);
- json.setData(list);
- return json;
- }
- /**
- * 查询项目设备状态统计
- * | projectid | true | string | 项目id |
- */
- @RequestMapping(value = "device/qryDeviceStatusSumData")
- @ResponseBody
- public WXAjaxJson qryDeviceStatusSumData(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- if (!StringUtils.isNotBlank(projectid)) {
- return json;
- }
- SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
- String today = dateformat.format(new Date());
- List<Map<String, Object>> list = null;
- try {
- list = wxdao.getDeviceStatusSumData(projectid, today);
- } catch (Exception e) {
- logger.error(e.getMessage());
- }
- json.setData(list);
- return json;
- }
- /**
- * 查询项目设备监测数据
- * | projectid | true | string | 项目id |
- * | openid | true | string | 用户openid |
- */
- @RequestMapping(value = "device/qryProjectDevicesData")
- @ResponseBody
- public WXAjaxJson qryProjectDevicesData(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String qrydate = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- List<SensorLiveDto> data = wxdao.getSensorLiveData(qrydate, projectid);
- json.setData(data);
- return json;
- }
- /**
- * 查询项目设备本日能耗
- */
- @RequestMapping(value = "device/getNenghao")
- @ResponseBody
- public WXAjaxJson getNenghao(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- Map map = dvservice.getNenghaoSumDataByProject(false, projectid);
- json.setData(map);
- return json;
- }
- /**
- * 查询项目人员信息
- * | projectid | true | string | 项目id |
- * | openid | true | string | 用户openid |
- */
- @RequestMapping(value = "employee/qryProjectEmployee")
- @ResponseBody
- public WXAjaxJson qryProjectEmployee(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- if (!StringUtils.isNotEmpty(projectid)) {
- json.setCode(XcglConstant.RETCODE_SERVICE_ERROR);
- json.setMsg(XcglConstant.RETMSG_SERVICEERROR);
- return json;
- }
- List<UserDto> data = wxdao.getProjectUsers(projectid);
- // 设置组织机构
- for (UserDto user : data) {
- user.setProjectid(null);
- user.setProjectname(null);
- user.setProjectTaskCount(null);
- user.setJgprojectids(null);
- user.setJgprojectnames(null);
- /*
- String orgId = user.getProjectid();
- String[] project = getParentProject(orgId);
- user.setProjectid(project[0]);
- user.setProjectname(project[1]);
- if(StringUtils.isNotEmpty(user.getJgprojectids())) {
- ArrayList<String> ids = new ArrayList<String>();
- ArrayList<String> names = new ArrayList<String>();
- String[] jzproject = user.getJgprojectids().split(",");
- for(String pid : jzproject) {
- String[] jzpro = getParentProject(pid);
- ids.add(jzpro[0]);
- names.add(jzpro[1]);
- }
- user.setJgprojectids(StringUtils.join(ids,","));
- user.setJgprojectnames(StringUtils.join(names,","));
- }
- */
- }
- json.setData(data);
- return json;
- }
- /**
- * 查询员工附件信息
- * | openid | true | String | openid |
- * | userid | true | String | 员工id |
- */
- @RequestMapping(value = "employee/qryEmployeeAttc")
- @ResponseBody
- public WXAjaxJson qryEmployeeAttc(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String userid = oConvertUtils.getString(request.getParameter("userid"));
- List<UserAccessoryDto> dtolist = wxdao.getUserAccessory(userid);
- if (dtolist.size() == 0) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- json.setData(setURL(dtolist.get(0)));
- return json;
- }
- private UserAccessoryDto setURL(UserAccessoryDto userAcc) {
- // 创建OSSClient实例
- OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
- // 设置URL过期时间为1小时
- Date expiration = new Date(new Date().getTime() + 3600 * 1000);
- if (userAcc.getPicture0id() != null && userAcc.getPicture0id().trim().length() > 0) {
- userAcc.setPicture0id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture0id(), expiration).toString());
- }
- if (userAcc.getPicture1id() != null && userAcc.getPicture1id().trim().length() > 0) {
- userAcc.setPicture1id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture1id(), expiration).toString());
- }
- if (userAcc.getPicture2id() != null && userAcc.getPicture2id().trim().length() > 0) {
- userAcc.setPicture2id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture2id(), expiration).toString());
- }
- if (userAcc.getPicture3id() != null && userAcc.getPicture3id().trim().length() > 0) {
- userAcc.setPicture3id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture3id(), expiration).toString());
- }
- if (userAcc.getPicture4id() != null && userAcc.getPicture4id().trim().length() > 0) {
- userAcc.setPicture4id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture5id(), expiration).toString());
- }
- if (userAcc.getPicture5id() != null && userAcc.getPicture5id().trim().length() > 0) {
- userAcc.setPicture5id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture5id(), expiration).toString());
- }
- if (userAcc.getPicture6id() != null && userAcc.getPicture6id().trim().length() > 0) {
- userAcc.setPicture6id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture6id(), expiration).toString());
- }
- // 关闭client
- ossClient.shutdown();
- return userAcc;
- }
- /**
- * 发送验证码
- * | phoneno | true | String | 手机号
- * | openid | true | String | openid
- *
- * @throws ClientException
- * @throws ServerException
- */
- @RequestMapping(value = "employee/sendSms")
- @ResponseBody
- public WXAjaxJson sendSms(HttpServletRequest req) throws ServerException, ClientException {
- WXAjaxJson json = new WXAjaxJson();
- String phoneno = req.getParameter("phoneno");
- if (!StringUtils.isNotBlank(phoneno)) {
- json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
- json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
- return json;
- }
- //设置超时时间-可自行调整
- System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
- System.setProperty("sun.net.client.defaultReadTimeout", "10000");
- //初始化ascClient需要的几个参数
- final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
- final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
- //替换成你的AK
- final String accessKeyId = "LTAImsMOGNQTqWvX";//你的accessKeyId,参考本文档步骤2
- final String accessKeySecret = "zdf5cux8RzTl531tQQ1rIlESTBBiBe";//你的accessKeySecret,参考本文档步骤2
- //初始化ascClient,暂时不支持多region(请勿修改)
- IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
- accessKeySecret);
- DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
- IAcsClient acsClient = new DefaultAcsClient(profile);
- //组装请求对象
- SendSmsRequest request = new SendSmsRequest();
- //使用post提交
- request.setMethod(MethodType.POST);
- //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
- request.setPhoneNumbers(phoneno);
- //必填:短信签名-可在短信控制台中找到
- request.setSignName("美都环卫物业");
- //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
- request.setTemplateCode("SMS_144450234");
- //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
- //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
- String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
- request.setTemplateParam("{\"code\":\"" + code + "\"}");
- //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
- //request.setSmsUpExtendCode("90997");
- //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
- // request.setOutId("yourOutId");
- //请求失败这里会抛ClientException异常
- SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
- if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
- //请求成功
- String logSql = "INSERT INTO p_usersms(`id`, `phoneno`, `sendtime`, `validtime`, `code`) "
- + "VALUES (?, ?, ?, ?, ?)";
- systemService.executeSql(logSql, com.xcgl.utils.UUID.randomUUID().toString(), phoneno, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
- XcglDateUtils.addDateMinut(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), 5), code);
- }
- json.setData(code);
- return json;
- }
- @RequestMapping(value = "task/qryTaskStati")
- @ResponseBody
- public WXAjaxJson qryTaskStati(HttpServletRequest request) throws ServerException, ClientException {
- WXAjaxJson json = new WXAjaxJson();
- Map<String, String> retMap = new HashMap<String, String>();
- retMap.put("today", "0/0");
- retMap.put("week", "0/0");
- retMap.put("month", "0/0");
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String projectid = oConvertUtils.getString(request.getParameter("projectid"));
- String weekStart = DateUtils.date_sdf.format(XcglDateUtils.getTimesWeekmorning());
- String weekend = DateUtils.date_sdf.format(XcglDateUtils.getTimesWeeknight());
- String monthStart = DateUtils.date_sdf.format(XcglDateUtils.getTimesMonthmorning());
- String monthend = DateUtils.date_sdf.format(XcglDateUtils.getTimesMonthnight());
- String today = DateUtils.date_sdf.format(new Date());
- List<Map<String, String>> retList = wxdao.getTaskStati(openid, projectid, today, weekStart, weekend, monthStart, monthend);
- if (retList.size() > 0) {
- retMap = retList.get(0);
- }
- json.setData(retMap);
- return json;
- }
- // public void weixinLogin(HttpServletRequest request,HttpServletResponse response) throws Exception {
- // Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
- // String[] codes = params.get("code");//拿到的code的值
- // String code = codes[0];//code
- // String APPID = "";
- // String AppSecret = "";
- // /*
- // * 拼写微信api请求地址并通过微信的appId和微信公众号的AppSecret
- // * 以及授权回调的code获取用户的openid和access_token
- // */
- // String requestUrl = " https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID"
- // + "&redirect_uri=APPSECRET&response_type=code&scope=snsapi_userinfo&state=STATE"
- // .replace("APPID",APPID).replace("APPSECRET", AppSecret).replace("CODE", code);
- // String requestResult = doGet(requestUrl);
- // com.alibaba.fastjson.JSONObject jsons = com.alibaba.fastjson.JSON.parseObject(requestResult);//结果转换成JSON对象
- // if(jsons == null || jsons.getInteger("errcode") != null || jsons.getString("openid") == null) {
- // throw new NoResultException();//自定义异常类
- // }
- // String openid = jsons.getString("openid");
- // //注意:公众号通用的access_token和登录用户的access_token是有区别的
- // //微信公众号的通用access_token每天只能取2000次 每次token有效期是7200S
- // requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
- // + "?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"
- // .replace("APPID", APPID).replace("APPSECRET", AppSecret);
- // requestResult = doGet(requestUrl);
- // JSONObject weixinToken = JSON.parseObject(requestResult);
- // if(weixinToken == null){
- // throw new NoResultException();//自定义异常类,获取我们公众号token失败
- // }
- // String wxgzhToken = weixinToken.getString("access_token");
- // requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN"
- // + "&openid=OPENID&lang=zh_CN".replace("ACCESS_TOKEN", wxgzhToken).replace("OPENID", openid);
- // requestResult = doGet(requestUrl);
- // JSONObject user = JSON.parseObject(requestResult);
- // if(user == null || user.getInteger("errcode") != null ) {
- // throw new NoResultException();//自定义异常类
- // }
- // //把这些信息存在我们的数据库中然后跳转到我们前台页面
- // }
- // /**
- // * get方式
- // * @param url
- // * @author blog.yoodb.com
- // * @return
- // */
- // public static String doGet(String url) {
- // String responseMsg = "";
- // HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
- // GetMethod getMethod = new GetMethod(url);
- // getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER
- // ,new DefaultHttpMethodRetryHandler());
- // try {
- // httpClient.executeMethod(getMethod);
- // ByteArrayOutputStream out = new ByteArrayOutputStream();
- // InputStream in = getMethod.getResponseBodyAsStream();
- // int len = 0;
- // byte[] buf = new byte[1024];
- // while((len=in.read(buf))!=-1){
- // out.write(buf, 0, len);
- // }
- // responseMsg = out.toString("UTF-8");
- // } catch (org.apache.commons.httpclient.HttpException e) {
- // e.printStackTrace();
- // } catch (IOException e) {
- // e.printStackTrace();
- // } finally {
- // //释放连接
- // getMethod.releaseConnection();
- // }
- // return responseMsg;
- // }
- /**
- * 按照微信消息模板keyword要求,组织消息,然后调用美都环卫微信平台服务发送消息
- */
- @RequestMapping(value = "test/msg")
- @ResponseBody
- public WXAjaxJson testMsg(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- WXServiceI service = ApplicationContextUtil.getContext().getBean(WXServiceI.class);
- try {
- service.sendMsgToWXInMorning();
- } catch (Exception e) {
- json.setMsg(e.getMessage());
- e.printStackTrace();
- }
- return json;
- }
- @RequestMapping(value = "interaction/textaction")
- @ResponseBody
- public WXAjaxJson textAction(HttpServletRequest request) throws ServerException, ClientException {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- String text = "";
- try {
- text = new String(request.getParameter("text").getBytes("iso-8859-1"), "utf-8");
- } catch (UnsupportedEncodingException e) {
- logger.error(e);
- e.printStackTrace();
- }
- //查询是否为总经理微信
- List<Map<String, Object>> ret = systemService.findForJdbc("select * from t_s_user where openid =? and usernum = '0001'", openid);
- if (ret == null || ret.size() == 0)
- json.setData("<a href=\"http://hgl.shenqin.work/hgl\" target=\"_blank\">美都环卫物业</a>:勤思、勤学、勤劳、勤勉");
- if (text.indexOf("下周") > -1)
- json.setData("<a href=\"http://hgl.shenqin.work/hgl\" target=\"_blank\">点击</a>查看下周工作计划\r\n \r\n★温馨提示:智能工作助理正在设计、开发中,敬请期待后续功能");
- else
- json.setData("美都环卫物业:勤思、勤学、勤劳、勤勉");
- return json;
- }
- /**
- * 新版首页数据 ,以后可能会拆分
- * 2019年12月7日
- *
- * @param request
- * @return
- */
- @RequestMapping(value = "/indexData")
- @ResponseBody
- public WXAjaxJson indexData(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- if (StringUtils.isBlank(openid)) {
- return json;
- }
- // 待我审批数量
- List<TSUser> userList = systemService.findByProperty(TSUser.class, "openid", openid);
- if (userList.size() == 0) {
- return json;
- }
- TSUser user = userList.get(0);
- String userName = user.getUserName();
- Map<String, Object> data = new HashMap<String, Object>();
- Long activitiToDoSize = this.activitiService.countPriTodaoTask(userName, request);
- data.put("activitiToDoSize", activitiToDoSize);
- //我发起的未审批完成的数量
- Long activitiStartSize = historyService.createHistoricProcessInstanceQuery().startedBy(userName).unfinished().count();
- data.put("activitiStartSize", activitiStartSize);
- //部门签报未完成
- List<Map<String, Object>> activitiStatsOrgUnFinishedData = rptDao.activitiStatsOrgUnFinishedData(5);
- data.put("activitiStatsOrgUnFinishedData", activitiStatsOrgUnFinishedData);
- //人员签报未完成
- List<?> activitiStatsUserUnFinishedData = rptDao.activitiStatsUserUnFinishedData(5);
- data.put("activitiStatsUserUnFinishedData", activitiStatsUserUnFinishedData);
- //部门工作
- List<?> taskStatsOrgUnFinishedData = rptDao.taskStatsOrgUnFinishedData(5);
- data.put("taskStatsOrgUnFinishedData", taskStatsOrgUnFinishedData);
- //人员工作未完成
- List<?> taskStatsOrgUserUnFinishedData = rptDao.taskStatsOrgUserUnFinishedData(5);
- data.put("taskStatsOrgUserUnFinishedData", taskStatsOrgUserUnFinishedData);
- json.setData(data);
- return json;
- }
- /**
- * 上传附件
- */
- @RequestMapping(value = "user/uploadPersonalImage")
- @ResponseBody
- public WXAjaxJson uploadPersonalImage(HttpServletRequest request) {
- WXAjaxJson json = new WXAjaxJson();
- String userid = oConvertUtils.getString(request.getParameter("userid"));
- String upFlag = oConvertUtils.getString(request.getParameter("isup"));
- String delFlag = oConvertUtils.getString(request.getParameter("isdel"));
- String mediaid = oConvertUtils.getString(request.getParameter("pictureid"));
- // String token = oConvertUtils.getString(request.getParameter("accessToken"));
- String token = wxTokenService.getSkey();
- try {
- //如果是上传操作
- if ("1".equals(upFlag)) {
- HashMap<String, String> mediaurl = new HashMap<String, String>();
- String busiId = com.xcgl.utils.UUID.randomUUID().toString();
- String fileName = null;
- //附件类型名,例如:*户口本本人页
- String accessoryName = null;
- //附件类型枚举 例如:hukoubenbenrenye4
- String accessoryType = null;
- // String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
- String now = DateUtils.yyyymmddhhmmss.format(new Date());
- String bizType = "personalImage/" + userid;//request.getParameter("bizType");//上传业务名称
- if (oConvertUtils.getString(request.getParameter("pictureid")).length() > 0) {
- accessoryName = "wxupload-" + now;
- accessoryType = "personalImage";
- }
- String extName = "jpg";//FileUtils.getExtend(fileName);
- fileName = accessoryName + "." + extName;
- List<String> keyAndUrl = getWXfileToOSS(extName, bizType, token, mediaid);
- // List<String> keyAndUrl = getWXfileToOSSTest(extName, "test", token, mediaid, request);
- if (keyAndUrl.size() == 2) {
- mediaurl.put("url", keyAndUrl.get(1));
- String busiTable = "t_b_personalImage";// request.getParameter("busiTable");
- TSysFileEntity tSysFileEntity = new TSysFileEntity();
- tSysFileEntity.setBusiId(busiId);// 业务id
- tSysFileEntity.setFileUrl(keyAndUrl.get(0));// 文件访问路径
- tSysFileEntity.setFileName(fileName);// 文件名称
- tSysFileEntity.setTagetType(bizType);// 文件类型
- tSysFileEntity.setBusiTable(oConvertUtils.getString(busiTable));
- tSysFileService.save(tSysFileEntity);
- // 保存业务表
- String accessorySql = "INSERT INTO t_b_personalImage(id, accessory_name, userid, isfixed, gatet_type, delete_flag,createtime,accUrl,ossKey) "
- + "VALUES (?, ?, ?, '1', ?, '0',?,?,?)";
- systemService.executeSql(accessorySql, busiId, accessoryName, userid, accessoryType, now, "", keyAndUrl.get(0));
- // }
- json.setData(mediaurl);
- }
- } else if ("1".equals(delFlag)) {//如果是删除操作
- // TODO 删除业务表数据,再删除oss,t_sys_file数据
- Map<String, String[]> params = request.getParameterMap();
- String ossKey = deleteAccSysfile(params, userid);
- if (!deleteOssfile(ossKey)) {
- String msg = MutiLangUtil.getMutiLangInstance().getLang("file.warn.filelost");
- // 不存在前台也给他删除
- json.setMsg(msg);
- }
- } else {
- throw new BusinessException("没有传参指定上传还是删除操作!");
- }
- } catch (IOException e) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(e.getMessage());
- logger.error(e.getMessage());
- } catch (BusinessException b) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(b.getMessage());
- logger.error(b.getMessage());
- } catch (Exception e) {
- json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
- json.setMsg(e.getMessage());
- logger.error(e.getMessage());
- }
- return json;
- }
- /**
- * 校验用户授权
- *
- * @param forceLogin 是否强制用户登录
- * @return
- */
- protected TSUser verifyUser(boolean forceLogin) {
- try {
- HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
- .getRequestAttributes())
- .getRequest();
- String openid = oConvertUtils.getString(request.getParameter("openid"));
- if (StringUtils.isBlank(openid)) {
- throw new ApiException(300, "openid required");
- }
- List<TSUser> userList = systemService.findByProperty(TSUser.class, "openid", openid);
- if (userList.size() == 0) {
- throw new ApiException(301, "用户未找到");
- }
- TSUser user = userList.get(0);
- return user;
- } catch (ApiException e) {
- if (forceLogin) throw e;
- }
- return null;
- }
- /**
- * 待我审批
- *
- * @param request
- * @return
- */
- @RequestMapping(value = "/workflow/taskList")
- @ResponseBody
- public WXAjaxJson workflow_taskList(HttpServletRequest request) {
- TSUser user = verifyUser(true);
- int rows = Integer.parseInt(request.getParameter("rows"));
- WXAjaxJson json = new WXAjaxJson();
- String userName = user.getUserName();
- Map<String, Object> data = new HashMap<String, Object>();
- List taskList = this.findBaseTodoTasks(true,user.getUserName(), request);
- String fields = "id,bpmBizTitle,Process_processDefinition_id,Process_processDefinition_name," +
- "Process_task_processInstanceId,userRealName,assigneeName," +
- "Process_task_createTime,Process_task_dueTime,TSPrjstatus_description," +
- "Process_task_name,Process_task_id,Process_task_taskDefinitionKey";
- List<Map> datalist = WXUtils.copyRecordListFields(taskList, fields);
- data.put("list", datalist);
- data.put("hasmore", datalist.size() >= rows ? 1 : 0);
- json.setData(data);
- return json;
- }
- /*
- * 从activitiService中移植过来的,为了改变部分查询过程
- * 1、与activitiService比,改变了排序为正序,即最先产生的任务排在上面
- * */
- private List findBaseTodoTasks(boolean isPri, String id, HttpServletRequest request) {
- List results = new ArrayList();
- List<Task> tasks = new ArrayList();
- Integer page = Integer.parseInt(request.getParameter("page"));
- Integer rows = Integer.parseInt(request.getParameter("rows"));
- Integer start = (page - 1) * rows;
- Integer end = page * rows - 1;
- String typeid;
- String inUserNameStr;
- try {
- List<Task> tempList = new ArrayList();
- if (!isPri) {
- } else {
- String userName = request.getParameter("userName");
- typeid = oConvertUtils.getString(request.getParameter("typeid"));
- StringBuilder userNamesb = new StringBuilder("");
- if (StringUtils.isNotEmpty(userName)) {
- List<ProcessInstance> processInstanceList = this.runtimeService.createProcessInstanceQuery()
- .variableValueEquals("applyUserId", userName).list();
- if (processInstanceList != null && processInstanceList.size() > 0) {
- for (int i = 0; i < processInstanceList.size(); ++i) {
- if (i == 0) {
- userNamesb.append("'"
- + ((ProcessInstance) processInstanceList.get(i)).getProcessInstanceId() + "'");
- } else {
- userNamesb.append(",'"
- + ((ProcessInstance) processInstanceList.get(i)).getProcessInstanceId() + "'");
- }
- }
- }
- }
- inUserNameStr = userNamesb.toString();
- String procDefId = request.getParameter("Process.processDefinition.id");
- StringBuilder sb = new StringBuilder("");
- sb.append("select * ").append("from (");
- sb.append("(select distinct RES.* ");
- sb.append(" from ACT_RU_TASK RES inner join ACT_RU_IDENTITYLINK I on I.TASK_ID_ = RES.ID_ ");
- sb.append(" \tLEFT JOIN t_p_process tpp on tpp.processkey = LEFT(RES.PROC_DEF_ID_ ,20) ");
- sb.append("WHERE RES.ASSIGNEE_ is null and I.TYPE_ = 'candidate' ");
- if (oConvertUtils.isNotEmpty(typeid)) {
- sb.append(" and tpp.typeid = #{typeid}");
- }
- sb.append(
- "\tand ( I.USER_ID_ = #{userid} or I.GROUP_ID_ IN ( select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{userid} ) ");
- sb.append(" ) ").append(" and RES.SUSPENSION_STATE_ = 1 ");
- if (StringUtils.isNotEmpty(procDefId)) {
- sb.append(" AND RES.PROC_DEF_ID_ LIKE #{procDefId} ");
- }
- if (StringUtils.isNotEmpty(userName)) {
- if (StringUtils.isNotEmpty(inUserNameStr)) {
- sb.append(" AND RES.PROC_INST_ID_ in (" + inUserNameStr + ") ");
- } else {
- sb.append(" AND RES.PROC_INST_ID_ in ('-1') ");
- }
- }
- sb.append(") union ");
- sb.append("(select distinct RES.* ");
- sb.append(" from ACT_RU_TASK RES ");
- sb.append("WHERE RES.ASSIGNEE_ = #{userid} ");
- if (StringUtils.isNotEmpty(procDefId)) {
- sb.append(" AND RES.PROC_DEF_ID_ LIKE #{procDefId} ");
- }
- if (StringUtils.isNotEmpty(userName)) {
- if (StringUtils.isNotEmpty(inUserNameStr)) {
- sb.append(" AND RES.PROC_INST_ID_ in (" + inUserNameStr + ") ");
- } else {
- sb.append(" AND RES.PROC_INST_ID_ in ('-1') ");
- }
- }
- sb.append(" )) v ");
- sb.append(" order by v.CREATE_TIME_ asc, v.PRIORITY_ desc ");
- String dbType = DBTypeUtil.getDBType();
- String sql = MiniDaoUtil.createPageSql(dbType, sb.toString(), page, rows);
- NativeTaskQuery query = (NativeTaskQuery) ((NativeTaskQuery) this.taskService.createNativeTaskQuery()
- .sql(sql)).parameter("userid", id);
- if (StringUtils.isNotEmpty(typeid)) {
- query.parameter("typeid", typeid);
- }
- if (StringUtils.isNotEmpty(procDefId)) {
- query.parameter("procDefId", "%" + procDefId + "%");
- }
- List<Task> pretasks = query.list();
- tempList.addAll(pretasks);
- TaskQuery tq = (TaskQuery) ((TaskQuery) this.taskService.createTaskQuery()
- .taskCandidateGroupIn(Arrays.asList(id.split(","))).orderByTaskCreateTime().desc())
- .orderByTaskPriority().desc();
- tq = this.installQueryParam(tq, request);
- List<Task> unsignedTasks = tq.listPage(start, end);
- tempList.addAll(unsignedTasks);
- }
- tasks.addAll(tempList);
- } catch (Exception var32) {
- var32.printStackTrace();
- }
- Iterator var35 = tasks.iterator();
- while (var35.hasNext()) {
- Task task = (Task) var35.next();
- typeid = task.getProcessInstanceId();
- ProcessInstance processInstance = (ProcessInstance) this.runtimeService.createProcessInstanceQuery()
- .processInstanceId(typeid).singleResult();
- inUserNameStr = this.getBusinessKeyByTask(task);
- Class entityClass = MyClassLoader.getClassByScn("org.jeecgframework.workflow.pojo.base.TSBaseBusQuery");
- Object entityObj = systemService.getEntity(entityClass, inUserNameStr);
- Object obj = null;
- try {
- obj = entityClass.newInstance();
- MyBeanUtils.copyBeanNotNull2Bean(entityObj, obj);
- } catch (Exception var31) {
- ;
- }
- if (obj != null) {
- ReflectHelper reflectHelper = new ReflectHelper(obj);
- org.jeecgframework.workflow.model.activiti.Process process = new org.jeecgframework.workflow.model.activiti.Process();
- process.setTask(task);
- process.setProcessInstance(processInstance);
- process.setProcessDefinition(this.getProcessDefinition(processInstance.getProcessDefinitionId()));
- reflectHelper.setMethodValue("Process", process);
- String userid = (String) reflectHelper.getMethodValue("userid");
- if (userid != null) {
- TSBaseUser baseUser = (TSBaseUser) this.activitiCommonDao.findUniqueByProperty(TSBaseUser.class,
- "userName", userid);
- if (baseUser != null) {
- reflectHelper.setMethodValue("userRealName", baseUser.getRealName());
- }
- }
- String assigneeUserId = task.getAssignee();
- if (assigneeUserId != null) {
- TSBaseUser baseUser = (TSBaseUser) this.activitiCommonDao.findUniqueByProperty(TSBaseUser.class,
- "userName", assigneeUserId);
- if (baseUser != null) {
- reflectHelper.setMethodValue("assigneeName", baseUser.getRealName());
- }
- }
- String bpmBizTitle = (String) this.taskService.getVariable(task.getId(), WorkFlowGlobals.BPM_BIZ_TITLE);
- if (bpmBizTitle != null) {
- reflectHelper.setMethodValue("bpmBizTitle", bpmBizTitle);
- }
- String processnodecode = task.getTaskDefinitionKey();
- String processDefinitionId = task.getProcessDefinitionId();
- String sql = "select node.NODE_TIMEOUT from T_P_PROCESSNODE node where node.PROCESSID = (select tpp.ID from T_P_PROCESS tpp where tpp.PROCESSKEY = ";
- sql = sql + "(select arp.KEY_ from ACT_RE_PROCDEF arp where arp.ID_ = ?)) and node.PROCESSNODECODE = ?";
- List<Map<String, Object>> list = this.systemService.findForJdbc(sql,
- new Object[] { processDefinitionId, processnodecode });
- if (list != null && list.size() > 0) {
- Map<String, Object> map = (Map) list.get(0);
- Integer nodeTimeout = (Integer) map.get("NODE_TIMEOUT");
- if (this.checkTimeOut(task.getCreateTime(), nodeTimeout)) {
- reflectHelper.setMethodValue("timeoutRemaid", true);
- } else {
- reflectHelper.setMethodValue("timeoutRemaid", false);
- }
- }
- if (oConvertUtils.getString(processDefinitionId).length() > 20) {
- String processDefinkey = processDefinitionId.substring(0, 20);
- TPProcess tpProcess = (TPProcess) systemService.findUniqueByProperty(TPProcess.class, "processkey",
- processDefinkey);
- if (tpProcess != null) {
- reflectHelper.setMethodValue("typeid", tpProcess.getTypeid());
- }
- }
- results.add(obj);
- }
- }
- return results;
- }
- private TaskQuery installQueryParam(TaskQuery tq, HttpServletRequest request) {
- String procDefId = request.getParameter("Process.processDefinition.id");
- String procName = request.getParameter("Process.processDefinition.name");
- if (StringUtils.isNotEmpty(procDefId)) {
- tq = tq.processDefinitionId(procDefId);
- }
- if (StringUtils.isNotEmpty(procName)) {
- tq = tq.processDefinitionName(procName);
- }
- return tq;
- }
- private boolean checkTimeOut(Date startTime, Integer timeout) {
- boolean flag = false;
- try {
- if (timeout == null || startTime == null) {
- return flag;
- }
- Calendar calSrc = Calendar.getInstance();
- Calendar calDes = Calendar.getInstance();
- calDes.setTime(startTime);
- int diff = DateUtils.dateDiff('h', calSrc, calDes);
- if (diff >= timeout) {
- flag = true;
- }
- } catch (Exception var7) {
- ;
- }
- return flag;
- }
-
- private ProcessDefinition getProcessDefinition(String processDefinitionId) {
- return (ProcessDefinition) this.repositoryService.createProcessDefinitionQuery()
- .processDefinitionId(processDefinitionId).singleResult();
- }
- private String getBusinessKeyByTask(Task task) {
- String businessKey = "";
- TaskEntity taskEntity = (TaskEntity) this.taskService.createTaskQuery().taskId(task.getId()).singleResult();
- HistoricProcessInstance hiproins = (HistoricProcessInstance) this.historyService
- .createHistoricProcessInstanceQuery().processInstanceId(taskEntity.getProcessInstanceId())
- .singleResult();
- if (hiproins != null) {
- if (hiproins.getSuperProcessInstanceId() != null && hiproins.getBusinessKey() == null) {
- hiproins = (HistoricProcessInstance) this.historyService.createHistoricProcessInstanceQuery()
- .processInstanceId(hiproins.getSuperProcessInstanceId()).singleResult();
- businessKey = hiproins.getBusinessKey();
- } else {
- businessKey = hiproins.getBusinessKey();
- }
- }
- return businessKey;
- }
-
- //审批历史
- @RequestMapping(value = "/workflow/myAuditHistoryList")
- @ResponseBody
- public WXAjaxJson workflow_myAuditHistoryList(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- int rows = Integer.parseInt(request.getParameter("rows"));
- List taskList = findHistoryTasks(user.getUserName(), request);
- Long taskSize = this.activitiService.countHistoryTasks(user.getUserName(), request);
- Map<String, Object> data = new HashMap<>();
- String fields = "id,bpmBizTitle,prodef_name,proInsl_procInstId,name,proInsl_startUserId,assignee,startTime,endTime,durationStr";
- List<Map> datalist = WXUtils.copyRecordListFields(taskList, fields);
- data.put("list", datalist);
- data.put("hasmore", datalist.size() >= rows ? 1 : 0);
- json.setData(data);
- return json;
- }
- private List findHistoryTasks(String userName, HttpServletRequest request) {
- Integer page = Integer.parseInt(request.getParameter("page"));
- Integer rows = Integer.parseInt(request.getParameter("rows"));
- Integer start = (page - 1) * rows;
- Query query = systemService.getSession().createQuery(this
- .installQueryParamH("from ActHiTaskinst o where o.duration>0 and o.assignee =? and o.deleteReason <>? ", request));
- query.setFirstResult(start);
- query.setMaxResults(rows);
- query.setString(0, userName);
- query.setString(1,"发起人流程追回");
- this.installQueryParamHV(query, request, 1);
- List result = query.list();
- for (int i = 0; i < result.size(); ++i) {
- ActHiTaskinst hi = (ActHiTaskinst) result.get(i);
- hi.setBpmBizTitle(this.getHiVariable(hi.getProcInstId(), WorkFlowGlobals.BPM_BIZ_TITLE));
- }
- return result;
- }
-
- private String installQueryParamH(String sql, HttpServletRequest request) {
- String procDefId = request.getParameter("procDefId");
- String procName = request.getParameter("prodef.name");
- StringBuilder s = new StringBuilder(sql);
- if (StringUtils.isNotEmpty(procDefId)) {
- s.append(" and o.procDefId =? ");
- }
- if (StringUtils.isNotEmpty(procName)) {
- s.append(" and o.prodef.name like CONCAT('%',CONCAT(?,'%')) ");
- }
- s.append(" order by o.endTime desc ");
- return s.toString();
- }
- private void installQueryParamHV(Query query, HttpServletRequest request, int index) {
- String procDefId = request.getParameter("procDefId");
- String procName = request.getParameter("prodef.name");
- if (StringUtils.isNotEmpty(procDefId)) {
- query.setParameter(index, procDefId);
- ++index;
- }
- if (StringUtils.isNotEmpty(procName)) {
- query.setParameter(index, procName);
- }
- }
- private String getHiVariable(String taskId, String variableName) {
- StringBuilder sb = new StringBuilder("");
- sb.append("from ActHiVarinst VAR where VAR.procInstId =? and VAR.name = ?");
- Query query = this.activitiService.getSession().createQuery(sb.toString());
- query.setString(0, taskId);
- query.setString(1, variableName);
- ActHiVarinst obj = (ActHiVarinst) query.uniqueResult();
- return obj == null ? "" : obj.getText();
- }
- //我发起的
- @RequestMapping(value = "/workflow/myLaunchTaskList")
- @ResponseBody
- public WXAjaxJson workflow_myLaunchTaskList(HttpServletRequest request, HttpServletResponse response) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- Map<String, Object> data = new HashMap<>();
- String currentUserName = user.getUserName();
- String realName = user.getRealName();
- int page = Integer.parseInt(request.getParameter("page"));
- int rows = Integer.parseInt(request.getParameter("rows"));
- HistoricProcessInstanceQuery historicProcessInstanceQuery = this.historyService
- .createHistoricProcessInstanceQuery().startedBy(currentUserName);
- List<HistoricProcessInstance> list = ((HistoricProcessInstanceQuery) historicProcessInstanceQuery
- .orderByProcessInstanceStartTime().desc()).listPage((page - 1) * rows, rows);
- Iterator var9 = list.iterator();
- List<Map> datalist = new ArrayList<>();
- while (var9.hasNext()) {
- HistoricProcessInstance hi = (HistoricProcessInstance) var9.next();
- String starttime = DateFormatUtils.format(hi.getStartTime(), "yyyy-MM-dd HH:mm:ss");
- String endtime = hi.getEndTime() == null ? "" : DateFormatUtils.format(hi.getEndTime(), "yyyy-MM-dd HH:mm:ss");
- long totalTimes = hi.getEndTime() == null
- ? Calendar.getInstance().getTimeInMillis() - hi.getStartTime().getTime()
- : hi.getEndTime().getTime() - hi.getStartTime().getTime();
- long dayCount = totalTimes / 86400000L;
- long restTimes = totalTimes % 86400000L;
- long hourCount = restTimes / 3600000L;
- restTimes %= 3600000L;
- long minuteCount = restTimes / 60000L;
- String spendTimes = dayCount + "天" + hourCount + "小时" + minuteCount + "分";
- ProcessDefinition processDefinition = (ProcessDefinition) this.repositoryService
- .createProcessDefinitionQuery()
- .processDefinitionId(hi.getProcessDefinitionId())
- .singleResult();
- String bpmBizTitle = this.getHiVariable(hi.getId(), WorkFlowGlobals.BPM_BIZ_TITLE);
- Map<String, Object> item = new HashMap<>();
- item.put("id", hi.getId());
- item.put("prcocessDefinitionName", StringUtils.trimToEmpty(processDefinition.getName()));
- item.put("startUserId", hi.getStartUserId());
- item.put("startUserName", realName);
- item.put("starttime", starttime);
- item.put("endtime", endtime);
- item.put("spendTimes", spendTimes);
- item.put("processDefinitionId", hi.getProcessDefinitionId());
- item.put("processInstanceId", hi.getId());
- item.put("bpmBizTitle", bpmBizTitle);
- datalist.add(item);
- }
- data.put("list", datalist);
- data.put("hasmore", datalist.size() >= rows ? 1 : 0);
- json.setData(data);
- return json;
- }
- /**
- * 我的消息列表
- * @param request
- * @param response
- * @param noticeType 通知类型
- * @param isRead 是否已读 0未读 1已读
- * @return
- */
- @RequestMapping(value = "/message/myList")
- @ResponseBody
- public WXAjaxJson messeg_myList(
- @RequestParam(value = "noticeType",required = false) String noticeType
- ,@RequestParam(value = "isRead",required = false) Integer isRead
- ,@RequestParam(value = "page",required = false,defaultValue = "1") Integer page
- ,@RequestParam(value = "rows",required = false,defaultValue = "10") Integer rows
- ,HttpServletRequest request, HttpServletResponse response) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- Map<String, Object> data = new HashMap<>();
- MiniDaoPage<MPersonalMessageEntity> pageList = mPersonalMessageService.getUserMessage(user.getId(),noticeType,isRead,page,rows);
- List<TSType> types = systemService.getTypesByGroupcodeFromCache("message_notice_type");
- List<Map<String,String>> noticeTypeList = new ArrayList<>(types.size());
- for(TSType type:types){
- Map<String,String> map = new HashMap<>();
- map.put("code",type.getTypecode());
- map.put("name",type.getTypename());
- noticeTypeList.add(map);
- }
- data.put("list",pageList.getResults());
- data.put("noticeTypeList",noticeTypeList);
- data.put("hasmore", pageList.getPages() > page ? 1 : 0);
- json.setData(data);
- return json;
- }
- /**
- * 消息详情
- * @param messageId 消息id
- * @param request
- * @param response
- * @return
- */
- @RequestMapping(value = "/message/detail")
- @ResponseBody
- public WXAjaxJson messeg_detail(
- @RequestParam(value = "messageId") String messageId
- ,HttpServletRequest request
- , HttpServletResponse response) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- Map<String, Object> data = new HashMap<>();
- MMessageEntity entity = mMessageService.userPreview(user.getId(),messageId);
- Map<String,Object> obj = new HashMap<>();
- obj.put("title",entity.getTitle());
- obj.put("text",entity.getSendText());
- obj.put("id",messageId);
- data.put("entity",obj);
- //消息附件
- CriteriaQuery cq = new CriteriaQuery(TSysFileEntity.class);
- try{
- cq.eq("busiTable","m_message");
- cq.eq("tagetType","mmessage");
- cq.addOrder("createDate",SortDirection.asc);
- cq.eq("busiId",messageId);
- }catch (Exception e) {
- throw new BusinessException(e.getMessage());
- }
- cq.add();
- cq.setDataGrid(new DataGrid());
- DataGridReturn dataGridReturn = systemService.getDataGridReturn(cq, false);
- String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
- List<TSysFileEntity> fileEntityList = dataGridReturn.getRows();
- List<Map<String,String>> fileList = new ArrayList<>();
- for(TSysFileEntity fileEntity:fileEntityList){
- Map<String,String> map = new HashMap<>();
- map.put("fileName",fileEntity.getFileName());
- try {
- map.put("fileUrl",showAndDownUrl+fileEntity.getFileUrl()+"&down=1&userName="+URLEncoder.encode(user.getUserName(),"UTF-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- fileList.add(map);
- }
- data.put("fileList",fileList);
- json.setData(data);
- return json;
- }
- /**
- * 我的回复列表
- * @param messageId 消息id
- * @return
- */
- @RequestMapping(value = "/message/myreply")
- @ResponseBody
- public WXAjaxJson messeg_myreply(@RequestParam(value = "messageId") String messageId
- , HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- Map<String, Object> data = new HashMap<>();
- CriteriaQuery cq = new CriteriaQuery(MMessageReplyEntity.class, dataGrid);
- //查询条件组装器
- try{
- cq.eq("userId",user.getId());
- cq.eq("messageId",messageId);
- //自定义追加查询条件
- }catch (Exception e) {
- throw new BusinessException(e.getMessage());
- }
- cq.add();
- systemService.getDataGridReturn(cq, true);
- data.put("list",dataGrid.getResults());
- json.setData(data);
- return json;
- }
- /**
- * 回复消息
- * @param messageId 消息id
- * @param reply 回复内容
- * @return
- */
- @RequestMapping(value = "/message/doreply")
- @ResponseBody
- public WXAjaxJson messeg_doreply(@RequestParam(value = "messageId") String messageId
- , @RequestParam(value = "reply") String reply
- , HttpServletRequest request, HttpServletResponse response) {
- TSUser user = verifyUser(true);
- WXAjaxJson json = new WXAjaxJson();
- Map<String, Object> data = new HashMap<>();
- mMessageReplyService.reply(user.getId(),messageId,reply);
- data.put("success",true);
- json.setData(data);
- return json;
- }
- }
|