Commit abf45d7b authored by libin's avatar libin

Merge branch 'master' into master_member_level_feature

parents 624d5772 5b931e2a
package com.github.wxiaoqi.security.common.util;
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
/**
* 关键字: 微信浏览器
*/
public static final String KEY_WEIXIN_BROWSER = "micromessenger";
/**
* 判断是否微信浏览器
*
* @param user_agent
* @return
*/
public static boolean isWexinBrowser(HttpServletRequest request) {
// 可能会出现npe
String user_agent = "";
user_agent = request.getHeader("user-agent");
// 修改如下
return user_agent != null && user_agent.toLowerCase().indexOf(KEY_WEIXIN_BROWSER) > 0;
}
}
package com.github.wxiaoqi.security.admin.rest;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.biz.*;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
......@@ -40,6 +41,10 @@ public class PublicController {
@Autowired
private AppUserDetailBiz detailBiz;
@Autowired
private AppUserLoginBiz appUserLoginBiz;
@Autowired
private BaseUserMemberBiz userMemberBiz;
......@@ -85,6 +90,23 @@ public class PublicController {
return ObjectRestResponse.succ(getAppUserInfoById(id));
}
@RequestMapping(value = "/app/userinfo-by-username", method = RequestMethod.GET)
public @ResponseBody
ObjectRestResponse<AppUserDTO> userDetailByUsername(String name) throws Exception {
AppUserLogin appUserLogin;
if (StrUtil.isBlank(name)) {
throw new BaseException(ResultCode.NOTEXIST_CODE
, new HashSet<String>() {{add("用户名不存在!");}});
}else {
appUserLogin = appUserLoginBiz.selectOne(new AppUserLogin(){{setUsername(name);}});
if(null == appUserLogin) {
throw new BaseException(ResultCode.NOTEXIST_CODE
, new HashSet<String>() {{add("用户名不存在!");}});
}
}
return ObjectRestResponse.succ(getAppUserInfoById(appUserLogin.getId()));
}
private AppUserDTO getAppUserInfoById(Integer userid) throws IllegalAccessException, InvocationTargetException {
AppUserDTO userDTO=new AppUserDTO();
//获取用户基础信息
......
......@@ -239,7 +239,7 @@ public class AppPermissionService {
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public JSONObject register(String username, String password, String headimgurl,
String nickname, String mobilecode, String openId, String unionid, Integer type,String code) {
log.info("register------code====="+code);
log.info("register------code====="+code+"----开始进入方法---time===="+System.currentTimeMillis()/1000L);
String activityCode = null;
// 判断参数和验证码
if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(mobilecode)) {
......@@ -247,7 +247,7 @@ public class AppPermissionService {
}
String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
log.error("注册接口,获取redis中的验证码:" + mobilecodeRedis);
log.info("注册接口,获取redis中的验证码:" + mobilecodeRedis+"---time===="+System.currentTimeMillis()/1000L);
// 获取到缓存的验证码后要先清空缓存对应键的值
userRedisTemplate.delete(redisLockKey);
if (StringUtils.isBlank(mobilecodeRedis)) {
......@@ -282,7 +282,7 @@ public class AppPermissionService {
appUserLogin.setUpdatetime(now);
appUserLoginBiz.insertSelective(appUserLogin);
Integer userid = appUserLogin.getId();
log.error("注册:新增登陆用户信息: " + userid);
log.info("注册:新增登陆用户信息: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 新增用户详情
AppUserDetail rsUserDetail = new AppUserDetail();
rsUserDetail.setUserid(userid);
......@@ -292,7 +292,9 @@ public class AppPermissionService {
rsUserDetail.setUpdatetime(now);
rsUserDetail.setIsdel(0);
rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail);
//setCreateIPInfo(rsUserDetail);
log.info("注册:解析地址后: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//邀请人id关系绑定
Integer parentId=0;
if (StringUtils.isNotBlank(code)){
......@@ -314,21 +316,27 @@ public class AppPermissionService {
//生成邀请码 长度改为8 不然重复率太高
rsUserDetail.setCode(ReferralCodeUtil.encode(userid));
appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid);
log.info("注册:新增用户详情: " + userid+"---time===="+System.currentTimeMillis()/1000L);
/* //绑定上下线关系
if(parentId!=null&&parentId>0){
relationBiz.bindRelation(userid,parentId,1);
}*/
//临时会员绑定
insertUserMemberByUserIdAndPhone(userid, username);
log.info("注册:临时会员绑定: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//参加新人活动
jionActivity(userid);
log.info("注册:参加新人活动: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//创建钱包
walletBiz.createWalletByUserId(appUserLogin.getId());
log.info("注册:创建钱包: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 登录结果要做做统一处理
JSONObject data = autoLogin(userid, username, headimgurl, nickname,code,activityCode,1);
log.info("注册:登录结果要做做统一处理: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 到im注册,获取返回结果
Map<String, Object> map = registerIm(username, appUserLogin.getPassword(), nickname);
log.info("注册:到im注册: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (map != null) {
Integer imUserId = Integer.parseInt(map.get("userId").toString());
//String access_token=map.get("access_token").toString();
......@@ -345,6 +353,7 @@ public class AppPermissionService {
//data.put("imToken",access_token);
data.put("imUserId", imUserId);
}
log.info("注册:处理im账号: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (data != null) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userid);
......@@ -352,6 +361,7 @@ public class AppPermissionService {
log.info("注册成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
mqSenderFeign.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
sendQueue(username, password, headimgurl, nickname, mobilecode, openId, unionid, type, code, activityCode, userid,RegisterQueueDTO.SIGN_NEW);
log.info("注册:发消息队列: " + userid+"---time===="+System.currentTimeMillis()/1000L);
return JsonResultUtil.createSuccessResultWithObj(data);
} else {
return JsonResultUtil.createDefaultFail();
......@@ -535,7 +545,7 @@ public class AppPermissionService {
userDetail.setUpdatetime(now);
userDetail.setIsdel(0);
userDetail.setCrtHost(getIp());
setCreateIPInfo(userDetail);
//setCreateIPInfo(userDetail);
appUserDetailBiz.insertSelective(userDetail);
} /*else {
......@@ -949,7 +959,7 @@ public class AppPermissionService {
//设置来源
rsUserDetail.setChannel(UserSourceEnum.APPLET.getCode());
rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail);
//setCreateIPInfo(rsUserDetail);
rsUserDetail.setState(1);
appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid);
......@@ -1083,7 +1093,7 @@ public class AppPermissionService {
public void setCreateIPInfo(AppUserDetail appUserDetail) {
String crtHost = appUserDetail.getCrtHost();
if (log.isDebugEnabled()) {
log.debug("解析的地址:【{}】", crtHost);
log.debug("解析的地址:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
}
try {
analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL2, crtHost, appUserDetail);
......@@ -1100,10 +1110,12 @@ public class AppPermissionService {
private void analyticalIPByWebSiteAndIPAddress(String url, String crtHost, AppUserDetail appUserDetail) {
String ipAddress = restTemplate.getForObject(String.format("%s%s", url, crtHost), String.class);
log.debug("解析的调用网站后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA);
JSONObject ipJsonObject = JSONObject.parseObject(data);
String cityName = ipJsonObject.getString(IPAddress.CITY_NAME);
RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName);
log.debug("解析的调用服务后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
if (null != regionDTO) {
appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId())));
appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId())));
......
package com.xxfc.platform.order.entity.inter;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderItem;
......@@ -28,4 +29,8 @@ public interface OrderDetail extends OrderItemInter {
void setTickerNo(List<String> tickerNo);
public AppUserDTO getAppUserDTO();
public void setAppUserDTO(AppUserDTO appUserDTO);
}
......@@ -3,6 +3,7 @@ package com.xxfc.platform.order.feign;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.GoodDataVO;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.entity.*;
import com.xxfc.platform.vehicle.pojo.*;
......@@ -21,4 +22,7 @@ import java.util.Set;
public interface OrderFeign {
@GetMapping("/baseOrder/count")
public ObjectRestResponse<Integer> baseOrderCount(@RequestParam("hasMemberRight") Integer hasMemberRight, @RequestParam("multiStatus") String multiStatus, @RequestParam("multiTypes") String multiTypes, @RequestParam("userId") Integer userId);
@GetMapping("/count/list")
public ObjectRestResponse<List<OrderPageVO>> getOrderList(@RequestParam("dateTime")Long dateTime, @RequestParam("type")Integer type, @RequestParam("status")Integer status);
}
......@@ -7,4 +7,7 @@ import lombok.Data;
public class CancelOrderDTO {
@ApiModelProperty(value = "取消原因")
private String cancelReason;
@ApiModelProperty(value = "app用户id")
private String appUserId;
}
\ No newline at end of file
......@@ -19,6 +19,7 @@ import java.util.List;
public class MemberBO extends OrderMemberDetail implements OrderDetail {
private BaseOrder order;
private BaseUserMemberLevel baseUserMemberLevel;
AppUserDTO appUserDTO;
/**
* 下单来源,1--app;2--小程序
*/
......
......@@ -42,4 +42,15 @@ public class RentVehicleBO extends OrderRentVehicleDetail implements OrderDetail
@ApiModelProperty(value = "随车物品", hidden = true)
private List<OrderAccompanyDTO> accompanyItems;
/**
* 创建用户 -1+后台用户id 后台系统
*/
String crtUser;
/**
* 用途 1 租车
*/
@ApiModelProperty(hidden = true)
Integer useType = 1;
}
package com.xxfc.platform.order.pojo;
package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.format.DateTimeFormatter;
@Data
......
package com.xxfc.platform.order.pojo;
package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
......@@ -8,7 +8,7 @@ public class AddOrderCommonDTO {
/**
*
*/
@ApiModelProperty(value = "下单来源,1--app;2--小程序")
@ApiModelProperty(value = "下单来源,1--app;2--小程序;3--后台")
private Integer orderOrigin;
......
package com.xxfc.platform.order.pojo;
package com.xxfc.platform.order.pojo.order.add;
import com.xxfc.platform.activity.entity.ActivityPopularizeItem;
import com.xxfc.platform.vehicle.constant.AccompanyingItemType;
import com.xxfc.platform.vehicle.entity.AccompanyingItem;
import com.xxfc.platform.order.pojo.OrderAccompanyDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
......
package com.xxfc.platform.order.pojo;
package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Data
......
package com.xxfc.platform.order.pojo.order.add;
import lombok.Data;
@Data
public class BgAddRentDTO extends AddRentVehicleDTO {
/**
* 用户订单
*/
Integer appUserId;
}
......@@ -632,7 +632,8 @@ public class BaseOrderBiz extends BaseBiz<BaseOrderMapper, BaseOrder> {
public Query initQuery(String no) {
QueryOrderDetailDTO qodd = new QueryOrderDetailDTO();
qodd.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
//qodd.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
qodd.setUserId(Integer.valueOf(BaseContextHandler.getUserID()));
qodd.setNo(no);
qodd.setLimit(1);
qodd.setPage(1);
......
package com.xxfc.platform.order.biz.rpc;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.mapper.BaseOrderMapper;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
@Service
public class OrderListBiz extends BaseBiz<BaseOrderMapper, BaseOrder> {
/**
*
* @param dateTime 筛选的时间
* @param type 筛选的类型, 1,租车,2,旅游
* @return
*/
public ObjectRestResponse<List<OrderPageVO>> getOrderList(Long dateTime, Integer type, Integer status) {
Map<String, Object> map = new HashMap<>();
if (dateTime != null) {
map.put("startTime", getDayStart(dateTime));
map.put("endTime", getDayStart(dateTime) + 3600 * 24 * 1000);
}
map.put("status", status);
if (type == OrderTypeEnum.RENT_VEHICLE.getCode()) { //租车
List<OrderPageVO> list = mapper.selectAllRentVehicleOrder(map);
return ObjectRestResponse.succ(list);
} else if (type == OrderTypeEnum.TOUR.getCode()) {
List<OrderPageVO> list = mapper.selectAllTourOrder(map);
return ObjectRestResponse.succ(list);
} else {
return ObjectRestResponse.succ();
}
}
public static Long getDayStart(Long datetime) {
long current = datetime;
long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
return zero;
}
}
......@@ -28,4 +28,8 @@ public interface BaseOrderMapper extends Mapper<BaseOrder> {
public OrderPageVO getOrderDetail(String no);
public List<OrderPageVO> selectAllRentVehicleOrder(Map<String, Object> paramMap);
public List<OrderPageVO> selectAllTourOrder(Map<String, Object> paramMap);
}
......@@ -37,7 +37,6 @@ import com.xxfc.platform.vehicle.entity.VehicleUserLicense;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.BookVehicleVO;
import com.xxfc.platform.vehicle.pojo.CompanyDetail;
import com.xxfc.platform.vehicle.pojo.QueryMultiDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
......@@ -49,14 +48,13 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;
import static com.xxfc.platform.order.pojo.AddRentVehicleDTO.DEFAULT_DATE_TIME_FORMATTER;
import static com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO.DEFAULT_DATE_TIME_FORMATTER;
@Controller
@RequestMapping("baseOrder")
......
......@@ -149,7 +149,8 @@ public class BaseOrderController extends CommonBaseController implements UserRes
if (StringUtils.isBlank(BaseContextHandler.getUserID())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
}
dto.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
//dto.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
dto.setUserId(Integer.valueOf(BaseContextHandler.getUserID()));
Query query = new Query(dto);
PageDataVO<OrderPageVO> pages = PageDataVO.pageInfo(query, () -> baseOrderBiz.pageByParm(query.getSuper()));
pages.getData().parallelStream().forEach(data -> data.setQrcodeStr(qrcodePrefix));
......@@ -248,16 +249,33 @@ public class BaseOrderController extends CommonBaseController implements UserRes
if (StringUtils.isBlank(BaseContextHandler.getUserID())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
}
cancelCommon(no, cancelOrderDto, BaseContextHandler.getUserID());
return ObjectRestResponse.succ();
}
@RequestMapping(value = "/back-stage/cancel/{no}", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "取消订单")
@IgnoreClientToken
public ObjectRestResponse bgCancel(@PathVariable String no, @RequestBody CancelOrderDTO cancelOrderDto) {
//查询列表数据
if (StringUtils.isBlank(cancelOrderDto.getAppUserId())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
}
cancelCommon(no, cancelOrderDto, cancelOrderDto.getAppUserId());
return ObjectRestResponse.succ();
}
private void cancelCommon(String no, CancelOrderDTO cancelOrderDto, String userId) {
BaseOrder dbBaseOrder = baseOrderBiz.selectOne(new BaseOrder() {{
setNo(no);
}});
if (null == dbBaseOrder || !BaseContextHandler.getUserID().equals(dbBaseOrder.getUserId().toString())) {
if (null == dbBaseOrder || !userId.equals(dbBaseOrder.getUserId().toString())) {
throw new BaseException(ResultCode.NOTEXIST_CODE);
}
dbBaseOrder.setCancelReason(cancelOrderDto.getCancelReason());
orderCancelBiz.cancel(dbBaseOrder);
return ObjectRestResponse.succ();
}
@RequestMapping(value = "/app/unauth/notifyUrl", method = RequestMethod.GET)
......
package com.xxfc.platform.order.rest;
import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.xxfc.platform.order.biz.OrderMemberDetailBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderMemberDetail;
import com.xxfc.platform.order.pojo.AddMemberDTO;
import com.xxfc.platform.order.pojo.AddTourDTO;
import com.xxfc.platform.order.pojo.order.add.AddMemberDTO;
import com.xxfc.platform.order.pojo.order.MemberBO;
import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.service.OrderMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
......@@ -49,6 +46,7 @@ public class OrderMemberController extends BaseController<OrderMemberDetailBiz,O
// bo.setMemberLevelId(bo.getBaseUserMemberLevel().getId());
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
//查询优惠券
orderMemberService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
......
......@@ -13,8 +13,9 @@ import com.xxfc.platform.order.biz.BaseOrderBiz;
import com.xxfc.platform.order.biz.OrderRentVehicleBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.pojo.AddRentVehicleDTO;
import com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO;
import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.add.BgAddRentDTO;
import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO;
import com.xxfc.platform.order.service.OrderRentVehicleService;
import com.xxfc.platform.vehicle.entity.BranchCompany;
......@@ -59,6 +60,26 @@ public class OrderRentVehicleController extends CommonBaseController {
@ResponseBody
@ApiOperation(value = "确认租车订单")
public ObjectRestResponse<BaseOrder> add(@RequestBody AddRentVehicleDTO vo){
RentVehicleBO bo = initRentVehicleBO(vo);
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
orderRentVehicleService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
}
@RequestMapping(value = "back-stage/add",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "后台人员为客户下租车订单")
public ObjectRestResponse<BaseOrder> backStagedd(@RequestBody BgAddRentDTO dto){
RentVehicleBO bo = initRentVehicleBO(dto);
bo.setAppUserDTO(userFeign.userDetailById(dto.getAppUserId()).getData());
bo.setCrtUser("-1"+ BaseContextHandler.getUserID());
bo.setUseType(null);
orderRentVehicleService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
}
private RentVehicleBO initRentVehicleBO(@RequestBody AddRentVehicleDTO vo) {
if(null == vo.getEndCompanyId() || vo.getEndCompanyId().equals(0)) {
if(StrUtil.isBlank(vo.getEndAddr())) {
throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
......@@ -92,12 +113,10 @@ public class OrderRentVehicleController extends CommonBaseController {
setBookStartDate(vo.getBookStartDate());
setBookEndDate(vo.getBookEndDate());
}});
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())?
StrUtil.splitTrim(vo.getTickerNos(), ","):null);
bo.setAccompanyItems(vo.getAccompanyItems());
orderRentVehicleService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
return bo;
}
@RequestMapping(value = "list-by-order/{orderId}",method = RequestMethod.GET)
......
......@@ -7,12 +7,13 @@ import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.xxfc.platform.order.biz.OrderTourDetailBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderTourDetail;
import com.xxfc.platform.order.pojo.AddTourDTO;
import com.xxfc.platform.order.pojo.order.add.AddTourDTO;
import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.pojo.price.TourPriceVO;
import com.xxfc.platform.order.service.OrderTourService;
......@@ -58,6 +59,7 @@ public class OrderTourController extends BaseController<OrderTourDetailBiz,Order
@ApiOperation(value = "确认旅游订单")
public ObjectRestResponse<BaseOrder> add(@RequestBody AddTourDTO vo){
TourBO bo = BeanUtil.toBean(vo, TourBO.class);
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())? Arrays.asList(vo.getTickerNos().split(",")):null);
orderTourService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
......
package com.xxfc.platform.order.rest.background;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.biz.rpc.OrderListBiz;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "/count")
public class OrderListController {
@Autowired
OrderListBiz orderListBiz;
@GetMapping("/list")
public ObjectRestResponse<List<OrderPageVO>> getOrderList(@RequestParam("dateTime")Long dateTime, @RequestParam("type")Integer type, @RequestParam("status")Integer status) {
return orderListBiz.getOrderList(dateTime, type, status);
}
}
package com.xxfc.platform.order.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
......@@ -64,7 +66,7 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
* 创建基础订单
* @return
*/
public BaseOrder createBaseOrder(Integer orderOrigin) {
public BaseOrder createBaseOrder(Integer orderOrigin, AppUserDTO appUserDTO) {
BaseOrder baseOrder = new BaseOrder();
//设置下单来源
......@@ -85,13 +87,14 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
baseOrder.setVersion(VERSION_INITIAL);
//设置用户id
baseOrder.setUserId(Integer.valueOf(BaseContextHandler.getUserID()));
baseOrder.setMemberLevel(getAppUser().getMemberLevel());
baseOrder.setUserId(appUserDTO.getUserid());
baseOrder.setMemberLevel(appUserDTO.getMemberLevel());
return baseOrder;
}
public void initDetail(Detail detail) {
BaseOrder order = createBaseOrder(detail.getOrderOrigin());
// Integer appUserId = (null == detail.getAppUserDTO())? Integer.valueOf(BaseContextHandler.getUserID()): detail.getAppUserDTO().getUserid();
BaseOrder order = createBaseOrder(detail.getOrderOrigin(), detail.getAppUserDTO());
detail.setOrder(order);
}
......@@ -118,10 +121,11 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
detail.setOrderId(detail.getOrder().getId());
detailBiz.insertSelective(detail);
detail.getOrder().setDetailId(detail.getId());
int updateResult =baseOrderBiz.updateSelectiveByIdRe(detail.getOrder());
if(updateResult > 0) {
detail.getOrder().setVersion(detail.getOrder().getVersion() + 1);
}
// int updateResult =baseOrderBiz.updateSelectiveByIdRe(detail.getOrder());
// if(updateResult > 0) {
// detail.getOrder().setVersion(detail.getOrder().getVersion() + 1);
// }
detail.setOrder(baseOrderBiz.updateSelectiveByIdReT(detail.getOrder()));
//插入item
if(null != detail.getItems() && detail.getItems().size() > 0) {
......
......@@ -196,6 +196,11 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl
accompanyItem.setOrderId(bo.getOrder().getId());
orderItemBiz.insertSelective(accompanyItem);
//设置后台系统创建人
if(StrUtil.isNotBlank(bo.getCrtUser())) {
bo.getOrder().setCrtUser(bo.getCrtUser());
}
super.handleDetail(bo);
//发送定时取消订单(数据字典设置--5分钟)
......@@ -454,6 +459,8 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl
rentVehicleBookDTO.setOrderNo(detail.getOrder().getNo());
rentVehicleBookDTO.setNumberPlate(numberPlate);
rentVehicleBookDTO.setStatus(status);
rentVehicleBookDTO.setUseType(detail.getUseType());
if(null != detail.getAccompanyItems()) {
rentVehicleBookDTO.setSelectedAccItem(detail.getAccompanyItems().parallelStream().collect(Collectors.toMap(OrderAccompanyDTO::getId, OrderAccompanyDTO::getNum)));
}
......
......@@ -75,6 +75,9 @@
<if test="crtUser != null">
and crt_user = #{crtUser}
</if>
<if test="userId != null">
and user_id = #{userId}
</if>
<if test="crtCompanyId != null">
and crt_company_id = #{crtCompanyId}
</if>
......@@ -127,9 +130,6 @@
</foreach>
</if>
<if test="userId != null">
and b.user_id = #{userId}
</if>
<if test="status != null">
and b.status = #{status}
</if>
......@@ -208,10 +208,16 @@
and r.end_time between #{startTime} and #{endTime}
</if>
<if test="companyIds != null and companyIds.size > 0">
and r.start_company_id in
and (r.start_company_id in
<foreach collection="companyIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
or
r.end_company_id in
<foreach collection="companyIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
)
</if>
<if test="status == 4">
order by r.start_time
......@@ -251,5 +257,26 @@
where no = #{no}
</select>
<select id="selectAllRentVehicleOrder" parameterType="Map" resultMap="orderPageMap">
select b.*
from base_order b
LEFT JOIN order_rent_vehicle_detail r on r.order_id = b.id
where b.type = 2 and b.status &gt;= 4
<if test="startTime != null and status == 1">
and r.start_time between #{startTime} and #{endTime}
</if>
<if test="startTime != null and status == 2">
and r.start_time between #{startTime} and #{endTime}
</if>
</select>
<select id="selectAllTourOrder" parameterType="Map" resultMap="orderPageMap">
select b.*
from base_order b
LEFT JOIN order_tour_detail r on r.order_id = b.id
where b.type = 2 and b.status &gt;= 4
<if test="startTime != null">
and r.start_time between #{startTime} and #{endTime}
</if>
</select>
</mapper>
\ No newline at end of file
......@@ -7,7 +7,7 @@ public class RedisKey {
/**
* 常量缓存key前缀
*/
public static final String CONSTANT_CACHE_PREFIX ="cache:constant:";
public static final String TOKEN_CACHE_PREFIX ="cache:token:";
/**
* 地区常量缓存key前缀(子读取列表)
......
package com.xxfc.platform.universal.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.github.wxiaoqi.security.common.util.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Author vitoHuang
* @Time 2015年8月14日
* @Mark HTTPS请求工具
*/
@Slf4j
public class HTTPSUtils{
/**
* HTTPS json 请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式 POST/GET
* @param msg json方式的请求参数
* @return 返回相应的字符串 异常会输出null
*/
public static String httpRequest(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequest()httpRequest="+requestUrl);
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
log.error("httpUrlConn="+httpUrlConn);
if (null != msg) {
outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(msg.getBytes("UTF-8"));
}
// 将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
log.error("inputStreamReader="+inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
httpUrlConn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:"+e.getMessage());
}finally{
if(outputStream != null)try{outputStream.close();}catch (Exception e) {}
if(inputStream != null)try{inputStream.close();;}catch (Exception e) {}
}
return null;
}
/**
* HTTPS json 请求
* @param requestUrl
* @param requestMethod
* @param msg
* @return 对字符串进行封装成JSON
*/
public static JSONObject httpRequestToJSON(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequestToJSON-----");
String json = httpRequest(requestUrl, requestMethod, msg);
log.error("json-----"+json);
JSONObject jsonObject = null;
if(StringUtils.isNotBlank(json)) jsonObject = JSON.parseObject(json);
return jsonObject;
}
}
package com.xxfc.platform.universal.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
@Slf4j
public class HttpRequestUtil {
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
package com.xxfc.platform.universal.utils;
import com.github.wxiaoqi.security.common.util.MD5Util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
'微信支付服务器签名支付请求请求类
'============================================================================
'api说明:
'init(app_id, app_secret, partner_key, app_key);
'初始化函数,默认给一些参数赋值,如cmdno,date等。
'setKey(key_)'设置商户密钥
'getLasterrCode(),获取最后错误号
'GetToken();获取Token
'getTokenReal();Token过期后实时获取Token
'createMd5Sign(signParams);生成Md5签名
'genPackage(packageParams);获取package包
'createSHA1Sign(signParams);创建签名SHA1
'sendPrepay(packageParams);提交预支付
'getDebugInfo(),获取debug信息
'============================================================================
'*/
public class RequestHandler {
/** Token获取网关地址地址 */
private String tokenUrl;
/** 预支付网关url地址 */
private String gateUrl;
/** 查询支付通知网关URL */
private String notifyUrl;
/** 商户参数 */
private String appid;
private String appkey;
private String partnerkey;
private String appsecret;
private String key;
/** 请求的参数 */
private SortedMap parameters;
/** Token */
private String Token;
private String charset;
/** debug信息 */
private String debugInfo;
private String last_errcode;
private HttpServletRequest request;
private HttpServletResponse response;
/**
* 初始构造函数。
*
* @return
*/
public RequestHandler(HttpServletRequest request,
HttpServletResponse response) {
this.last_errcode = "0";
this.request = request;
this.response = response;
//this.charset = "GBK";
this.charset = "UTF-8";
this.parameters = new TreeMap();
// 验证notify支付订单网关
notifyUrl = "https://gw.tenpay.com/gateway/simpleverifynotifyid.xml";
}
/**
* 初始化函数。
*/
public void init(String app_id, String app_secret, String partner_key) {
this.last_errcode = "0";
this.Token = "token_";
this.debugInfo = "";
this.appid = app_id;
this.partnerkey = partner_key;
this.appsecret = app_secret;
this.key = partner_key;
}
public void init() {
}
/**
* 获取最后错误号
*/
public String getLasterrCode() {
return last_errcode;
}
/**
*获取入口地址,不包含参数值
*/
public String getGateUrl() {
return gateUrl;
}
/**
* 获取参数值
*
* @param parameter
* 参数名称
* @return String
*/
public String getParameter(String parameter) {
String s = (String) this.parameters.get(parameter);
return (null == s) ? "" : s;
}
//设置密钥
public void setKey(String key) {
this.partnerkey = key;
}
//设置微信密钥
public void setAppKey(String key){
this.appkey = key;
}
// 特殊字符处理
public String UrlEncode(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, this.charset).replace("+", "%20");
}
// 获取package的签名包
public String genPackage(SortedMap<String, String> packageParams)
throws UnsupportedEncodingException {
String sign = createSign(packageParams);
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + UrlEncode(v) + "&");
}
// 去掉最后一个&
String packageValue = sb.append("sign=" + sign).toString();
// System.out.println("UrlEncode后 packageValue=" + packageValue);
return packageValue;
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public String createSign(SortedMap<String, String> packageParams) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
System.out.println("md5 sb:" + sb);
String sign = MD5Util.MD5Encode(sb.toString(), this.charset).toUpperCase();
System.out.println("packge签名:" + sign);
return sign;
}
//输出XML
public String parseXML() {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(null != v && !"".equals(v) && !"appkey".equals(k)) {
sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 设置debug信息
*/
protected void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
public void setPartnerkey(String partnerkey) {
this.partnerkey = partnerkey;
}
public String getDebugInfo() {
return debugInfo;
}
public String getKey() {
return key;
}
}
package com.xxfc.platform.universal.utils;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WeiXinPayUtil{
private final static String WeXinPay_URL ="https://api.mch.weixin.qq.com/pay/unifiedorder";
private final static String WeXinRefund_URL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String getPrepayId(String xml,String method){
return HTTPSUtils.httpRequest(WeXinPay_URL, method, xml);
}
@SuppressWarnings("deprecation")
private static XStream xstream = new XStream(/*new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
}*/
new XppDriver(new
XmlFriendlyReplacer("_-", "_"){
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
})
);
public static String toXml(WxPrepay wxPrepay){
xstream.alias("xml", wxPrepay.getClass());
return xstream.toXML(wxPrepay);
}
/**
* 获取随机字符串
* @return
*/
public static String getNonceStr() {
// 随机数
String currTime = getCurrTime();
// 8位日期
String strTime = currTime.substring(8, currTime.length());
// 四位随机数
String strRandom = buildRandom(4) + "";
// 10位序列号,可以自行调整。
return strTime + strRandom;
}
/**
* 获取当前时间 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 元转换成分
* @param
* @return
*/
public static String getMoney(String amount) {
if(amount==null){
return "";
}
// 金额转化为分为单位
String currency = amount.replaceAll("\\$|\\¥|\\,", ""); //处理包含, ¥ 或者$的金额
int index = currency.indexOf(".");
int length = currency.length();
Long amLong = 0l;
if(index == -1){
amLong = Long.valueOf(currency+"00");
}else if(length - index >= 3){
amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
}else if(length - index == 2){
amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
}else{
amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
}
return amLong.toString();
}
/**
* ArrayToXml
* @param arr
* @return
*/
public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}
public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}
}
package com.xxfc.platform.universal.utils;
public class WxPrepay {
private String appid;
private String mch_id;
private String nonce_str;
private String sign;
private String body;
private String out_trade_no;
private String attach;
private String total_fee;
private String spbill_create_ip;
private String notify_url;
private String trade_type;
private String openid;
private String out_refund_no;
private String refund_fee;
private String op_user_id;
public WxPrepay(){};
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getSpbill_create_ip() {
return spbill_create_ip;
}
public void setSpbill_create_ip(String spbill_create_ip) {
this.spbill_create_ip = spbill_create_ip;
}
public String getNotify_url() {
return notify_url;
}
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getOut_refund_no() {
return out_refund_no;
}
public void setOut_refund_no(String out_refund_no) {
this.out_refund_no = out_refund_no;
}
public String getRefund_fee() {
return refund_fee;
}
public void setRefund_fee(String refund_fee) {
this.refund_fee = refund_fee;
}
public String getOp_user_id() {
return op_user_id;
}
public void setOp_user_id(String op_user_id) {
this.op_user_id = op_user_id;
}
}
package com.xxfc.platform.universal.weixin.api;
import java.util.Map.Entry;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.*;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.MD5Util;
import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.universal.utils.RequestHandler;
import com.xxfc.platform.universal.utils.WeiXinPayUtil;
import com.xxfc.platform.universal.utils.WxPrepay;
import com.xxfc.platform.universal.weixin.util.HTTPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
......@@ -44,9 +41,12 @@ public class WXPay {
* @return
*/
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid){
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String wyAppid){
WXPrepay prePay = new WXPrepay();
prePay.setAppid(SystemConfig.WINXIN_AppID);//pay.getAppId()
if (StringUtils.isBlank(wyAppid)){
wyAppid=SystemConfig.WINXIN_AppID;
}
prePay.setAppid(wyAppid);//pay.getAppId()
prePay.setBody(body);
prePay.setPartnerKey(SystemConfig.WINXIN_PARTNER_KEY);//pay.getPartnerKey()
prePay.setMch_id(SystemConfig.WINXIN_PARTNER);//pay.getPartnerId()
......@@ -65,7 +65,7 @@ public class WXPay {
String jsParam = "";
if (prepayid != null && prepayid.length() > 10) {
// 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式
jsParam = WXPay.createPackageValueWeb(SystemConfig.WINXIN_AppID, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
jsParam = WXPay.createPackageValueWeb(wyAppid, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
}
return jsParam;
......@@ -115,6 +115,7 @@ public class WXPay {
}
}
sb.append("key=" + AppKey);
log.info("-----签名sign==="+sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
......@@ -374,6 +375,92 @@ public class WXPay {
System.out.println(response_body);
}
public static String getPackage(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String appid,String appsecret){
Map<String,String> map = new LinkedHashMap<String,String>();
Random random = new Random();
String randomStr = MD5.GetMD5String(String.valueOf(random.nextInt(10000)));
String noceStr = MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase();
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid",appid);
packageParams.put("mch_id", SystemConfig.WINXIN_PARTNER);
packageParams.put("nonce_str", noceStr);
packageParams.put("body", body);
packageParams.put("attach", "");
packageParams.put("out_trade_no", orderNo);
// 这里写的金额为1 分到时修改
packageParams.put("total_fee",total_fee);
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
String trade_type = "JSAPI";
packageParams.put("trade_type", trade_type);
packageParams.put("openid", openid);
RequestHandler reqHandler = new RequestHandler(null, null);
reqHandler.init(appid, appsecret, SystemConfig.WINXIN_PARTNER_KEY);
String sign = reqHandler.createSign(packageParams);
WxPrepay wxPrepay = new WxPrepay();
wxPrepay.setAppid(appid);
wxPrepay.setMch_id(SystemConfig.WINXIN_PARTNER);
wxPrepay.setNonce_str(noceStr);
wxPrepay.setSign(sign);
wxPrepay.setBody(body);
wxPrepay.setOut_trade_no(orderNo);
wxPrepay.setTotal_fee(total_fee);
wxPrepay.setSpbill_create_ip(spbill_create_ip);
wxPrepay.setNotify_url(notify_url);
wxPrepay.setTrade_type(trade_type);
wxPrepay.setOpenid(openid);
wxPrepay.setAttach("");
String xml = WeiXinPayUtil.toXml(wxPrepay);
log.error("post_prepay_xml: " + xml);
//获取prepay_id
map = StringtoMap(WeiXinPayUtil.getPrepayId(xml,"POST"));
//获取prepay_id后,拼接最后请求支付所需要的package
SortedMap<String, String> finalpackage = new TreeMap<String, String>();
String timestamp = OrderUtil.GetTimestamp();
String packages = "prepay_id="+map.get("prepay_id");
finalpackage.put("appId", appid);
finalpackage.put("timeStamp", timestamp);
finalpackage.put("nonceStr", noceStr);
finalpackage.put("package", packages);
finalpackage.put("signType", "MD5");
//要签名
String finalsign = reqHandler.createSign(finalpackage);
String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\"" + timestamp
+ "\",\"nonceStr\":\"" + noceStr + "\",\"package\":\""
+ packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
+ finalsign + "\"";
return finaPackage;
}
public static Map<String,String> StringtoMap(String str){
log.error("respon_prepay_xml: " + str);
Map<String,String> map = new LinkedHashMap<String,String>();
try {
Document document = DocumentHelper.parseText(str);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for(Element e : elementList){
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
......
......@@ -63,6 +63,11 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}")
String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public JSONObject preparepay(OrderPayVo orderPayVo) {
......@@ -102,13 +107,16 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
String sellerAccount = null;
if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount());
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),null);
} else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID;
jsParam = generateAliPayment(orderPayVo, notifyUrl);
}else if (type == 3 && payWay == 1){
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),wy_appid);
}
log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) {
......
package com.xxfc.platform.universal.biz;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.universal.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Service
@Slf4j
public class WeixinService {
/**
* 网页
*/
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public static final String frontSessionKey = "frontWeixKey";
public JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public String getAuthorize(String redirec_url){
String oauth_api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&state={STATE}#wechat_redirect";
oauth_api = oauth_api.replace("{APPID}", wy_appid)
.replace("{REDIRECT_URI}", redirec_url)
.replace("{SCOPE}", "snsapi_base").replace("{STATE}", "state");
log.info("---oauth_api===="+oauth_api);
return oauth_api;
}
//获取缓存
public String getSession(HttpServletRequest request){
try {
HttpSession session = request.getSession();
String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
log.info("---session获取===="+frontSessionValue1+"---sessionId==="+session.getId());
if (StringUtils.isBlank(frontSessionValue1)) {
return null;
}
String openId = Base64.decodeStr(frontSessionValue1);
return openId;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
......@@ -3,6 +3,7 @@ package com.xxfc.platform.universal.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.xxfc.platform.universal.interceptor.WeChatH5LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
......@@ -29,6 +30,10 @@ public class WebConfiguration implements WebMvcConfigurer {
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/3p/**");
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
/* registry.addInterceptor(getWeChatH5LoginInterceptor()
).addPathPatterns(getWxIncludePathPatterns());*/
}
@Bean
......@@ -41,6 +46,10 @@ public class WebConfiguration implements WebMvcConfigurer {
return new UserAuthRestInterceptor();
}
@Bean
WeChatH5LoginInterceptor getWeChatH5LoginInterceptor() { return new WeChatH5LoginInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
......@@ -53,6 +62,14 @@ public class WebConfiguration implements WebMvcConfigurer {
Collections.addAll(list, urls);
return list;
}
private ArrayList<String> getWxIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/info/**"
};
Collections.addAll(list, urls);
return list;
}
/* @Bean(name = "customTaskExecutor")
TaskExecutor getTaskExecutor(){
......
package com.xxfc.platform.universal.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 用户
*/
@RestController
@RequestMapping("info")
@IgnoreUserToken
@Slf4j
public class UserInfoController {
@Autowired
WeixinService weixinService;
@Value("${wx.sendUrl}")
private String sendUrl;
@RequestMapping(value = "getOpenId", method = RequestMethod.GET) //匹配的是href中的download请求
public ObjectRestResponse getOpenId(HttpServletRequest request) throws Exception {
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
log.info("---进入方法getOpenId----openId===="+openId);
if (StringUtils.isBlank(openId)){
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
return ObjectRestResponse.createFailedResultWithObj(1001,"",json);
}
return ObjectRestResponse.succ(openId);
}
return ObjectRestResponse.succ();
}
}
package com.xxfc.platform.universal.controller;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author Administrator
*/
@Controller
@RequestMapping("/auth")
@Slf4j
public class WeixinController {
public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "callback";
public static final String frontSessionKey = "frontWeixKey";
@Autowired
WeixinService weixinService;
@Value("${wx.url}")
private String url;
@RequestMapping(value ="/app/unauth/wxLogin",method = RequestMethod.GET)
@IgnoreUserToken
public String wxLogin(@RequestParam(value = "redirec_url")String redirec_url){
log.info("-----微信wxLogin---redirec_url=="+redirec_url);
if (StringUtils.isBlank(redirec_url)){
redirec_url="";
}
try {
String encrypt_curr_url = Base64.encode(redirec_url.getBytes("utf-8"));
redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url;
String oauth_api=weixinService.getAuthorize(redirec_url);
return String.format("redirect:"+oauth_api);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
return String.format("网络异常");
}
}
/**
* 微信浏览器获取用户信息
* @param code
* @param callback
* @return
*/
@GetMapping(value = "/app/unauth/userInfo")
public String getUserInformation(String code, String callback, HttpServletRequest request) {
log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback);
try {
authUser(code,request);
callback =new String(Base64.decode(callback), "utf-8");
log.info("callback===" + callback);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
}
return String.format("redirect:"+callback);
}
public void authUser(String code,HttpServletRequest request){
if (StringUtils.isBlank(code)){
log.info("----code为空---");
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
}
String openid = null;
String access_token = null;
try {
JSONObject jsonData = weixinService.getAccessToken(code);
openid = jsonData.getString("openid");
access_token = jsonData.getString("access_token");
String refresh_token = jsonData.getString("refresh_token");
log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
//验证access_token是否失效
JSONObject validateData = weixinService.getValidateData(access_token, openid);
if (!"0".equals(validateData.getString("errcode"))){
//刷新access_token
JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
access_token = refreshData.getString("access_token");
}
String encode = Base64.encode(openid);
HttpSession session = request.getSession();
session.removeAttribute(frontSessionKey);
session.setAttribute(frontSessionKey, encode);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
}
}
}
package com.xxfc.platform.universal.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 微信登陆拦截器
*
* @author
*
*/
@Slf4j
public class WeChatH5LoginInterceptor extends HandlerInterceptorAdapter {
@Value("${wx.sendUrl}")
private String sendUrl;
@Autowired
WeixinService weixinService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String curr_domain = request.getServerName();
log.info("curr_domain:" + curr_domain);
log.info("address:" + request.getRequestURL().toString());
log.info("params:" + request.getQueryString());
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
if (StringUtils.isNotBlank(openId)){
return true;
}
Map<String,Object> result=new HashMap<>();
result.put("status",1001);
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
result.put("data",json);
response.getWriter().write(result.toString());
return false;
}
return true;
}
}
package com.xxfc.platform.vehicle.constant;
import java.util.HashMap;
import java.util.Map;
public enum VehicleCountType {
RENT_VEHICLE(1, "租车用车"),
TOUR(2, "旅游用车"),
INNER(3, "内部用车"),
;
/**
* 编码
*/
private Integer code;
/**
* 类型描述
*/
private String desc;
public static Map<Integer, VehicleCountType> codeAndDesc = new HashMap<Integer, VehicleCountType>();
//Maps.newHashMap();
static{
for(VehicleCountType enumE : VehicleCountType.values()){
codeAndDesc.put(enumE.getCode(), enumE);
}
}
VehicleCountType(Integer code, String desc){
this.code=code;
this.desc=desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static Boolean exists(Integer code){
return codeAndDesc.containsKey(code);
}
public static VehicleCountType get(Integer code) {
for(VehicleCountType enumE : VehicleCountType.values()) {
if (enumE.getCode().equals(code)) {
return enumE;
}
}
return null;
}
}
package com.xxfc.platform.vehicle.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
@Table(name = "vehicle_count_record")
@Data
public class VehicleCountRecord {
@Id
private Integer id;
private Integer type;
/**
* 应出车数量
*/
@Column(name = "departure_num")
private Integer departureNum;
/**
* 实际出车数量
*/
@Column(name = "actual_departure_num")
private Integer actualDepartureNum;
/**
* 延期交车数量
*/
@Column(name = "after_departure_num")
private Integer afterDepartureNum;
/**
* 提前交车数
*/
@Column(name = "before_departure_num")
private Integer beforeDepartureNum;
/**
* 应还车数量
*/
@Column(name = "arrival_num")
private Integer arrivalNum;
/**
* 未提前还车数量
*/
@Column(name = "actual_arrival_num")
private Integer actualArrivalNum;
/**
* 延后还车数量
*/
@Column(name = "after_arrival_num")
private Integer afterArrivalNum;
/**
* 提前还车数量
*/
@Column(name = "before_arrival_num")
private Integer beforeArrivalNum;
/**
* 统计日期 yyyy-MM-dd
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(
pattern = "yyyy-MM-dd"
)
private Date countDate;
@Transient
private String startTime;
@Transient
private String endTime;
}
\ No newline at end of file
package com.xxfc.platform.vehicle.pojo;
import lombok.Data;
import java.util.List;
@Data
public class ExcelParamDto {
List<Object[]> data;
String[] header;
String name;
String path;
}
......@@ -91,6 +91,12 @@ public class RentVehicleBookDTO extends PageParam {
@ApiModelProperty("扩展结束时间")
String endDateExtend;
/**
* 用途 1 租车
*/
@ApiModelProperty(hidden = true)
Integer useType = 1;
public void setBookStartDate(String bookStartDate) {
this.bookStartDate = bookStartDate;
//首次设置
......
......@@ -57,6 +57,12 @@ public class UsableVeicleDTO extends PageParam {
@ApiModelProperty(hidden = true)
Integer withoutRecordWhere = 1;
/**
* 用途 1 租车
*/
@ApiModelProperty(hidden = true)
Integer useType = 1;
public void setStartDateTamp(Long startDateTamp) {
this.startDateTamp = startDateTamp;
this.startDate = DEFAULT_DATE_TIME_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startDateTamp), ZoneOffset.ofHours(8)));
......
......@@ -40,4 +40,7 @@ public class VehicleBookRecordVo extends VehicleBookRecord {
List<VehicleUpkeepItem> vehicleUpkeepItems;
private String userCompanyName;
}
package com.xxfc.platform.vehicle.util.excel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/***
* 将文件内容响应到浏览器
*/
public class DownloadUtil {
// 字符编码格式
private static String charsetCode = "utf-8";
/**
* 文件的内容类型
*/
private static String getFileContentType(String name){
String result = "";
String fileType = name.toLowerCase();
if (fileType.endsWith(".png")) {
result = "image/png";
} else if (fileType.endsWith(".gif")) {
result = "image/gif";
} else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
result = "image/jpeg";
} else if(fileType.endsWith(".svg")){
result = "image/svg+xml";
}else if (fileType.endsWith(".doc")) {
result = "application/msword";
} else if (fileType.endsWith(".xls")) {
result = "application/x-excel";
} else if (fileType.endsWith(".zip")) {
result = "application/zip";
} else if (fileType.endsWith(".pdf")) {
result = "application/pdf";
} else {
result = "application/octet-stream";
}
return result;
}
/**
* 下载文件
* @param path 文件的位置
* @param fileName 自定义下载文件的名称
* @param resp http响应
* @param req http请求
*/
public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){
File file = new File(path);
try {
/**
* 中文乱码解决
*/
String type = req.getHeader("User-Agent").toLowerCase();
if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){
/**
* 谷歌或火狐
*/
fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
}else{
/**
* IE
*/
fileName = URLEncoder.encode(fileName, charsetCode);
}
// 设置响应的头部信息
resp.setHeader("content-disposition", "attachment;filename=" + fileName);
// 设置响应内容的类型
resp.setContentType(getFileContentType(fileName)+"; charset=" + charsetCode);
// 设置响应内容的长度
resp.setContentLength((int) file.length());
// 输出
outStream(new FileInputStream(file), resp.getOutputStream());
} catch (Exception e) {
System.out.println("执行downloadFile发生了异常:" + e.getMessage());
} finally {
if (file.exists()) {
file.delete();
}
}
}
/**
* 基础字节数组输出
*/
private static void outStream(InputStream is, OutputStream os) {
try {
byte[] buffer = new byte[10240];
int length = -1;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
os.flush();
}
} catch (Exception e) {
System.out.println("执行 outStream 发生了异常:" + e.getMessage());
} finally {
try {
os.close();
} catch (IOException e) {
}
try {
is.close();
} catch (IOException e) {
}
}
}
}
\ No newline at end of file
......@@ -29,6 +29,11 @@
<artifactId>xx-universal-api</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.xxfc.platform</groupId>
<artifactId>xx-order-api</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
......
......@@ -311,10 +311,24 @@ public class VehicleBookRecordBiz extends BaseBiz<VehicleBookRecordMapper, Vehic
}
}
}
if (vehicleBookRecordVo.getBookUser() != null) {
UserDTO userDTO = userFeign.userinfoByUid(vehicleBookRecordVo.getBookUser()).getData();
if(userDTO != null) {
BranchCompany branchCompany = branchCompanyBiz.getById(userDTO.getCompanyId());
if (branchCompany != null) {
vehicleBookRecordVo.setUserCompanyName(branchCompany.getName());
}
}
}
}
return vehicleBookRecordVos;
}
public ObjectRestResponse<List<VehicleBookRecordVo>> selectByIds(List<Long> ids) {
Map<String, Object> map = new HashMap<>();
map.put("ids", ids);
return ObjectRestResponse.succ(mapper.selectByIds(map));
}
public RestResponse<Integer> lift(Integer operatorId, String userName, LiftVehicleVo liftVehicleVo) throws Exception {
Map<String, Object> params = PropertyUtils.describe(liftVehicleVo);
......@@ -499,6 +513,13 @@ public class VehicleBookRecordBiz extends BaseBiz<VehicleBookRecordMapper, Vehic
}
public ObjectRestResponse<List<VehicleBookRecordVo>> selectAllBookRecord(Date startTime, Date endTime, Integer status) {
Map<String, Object> map = new HashMap<>();
map.put("startTime", startTime);
map.put("endTime", endTime);
map.put("status", status);
return ObjectRestResponse.succ(mapper.selectAllBookRecord(map));
}
/**
* 获取上月数据,并复制到历史表
......
......@@ -40,4 +40,7 @@ public interface VehicleBookRecordMapper extends Mapper<VehicleBookRecord> {
public List<VehicleBookRecordVo> selectZeroHourRecord(Map<String, Object> param);
public List<VehicleBookRecordVo> selectAllBookRecord(Map<String, Object> param);
public List<VehicleBookRecordVo> selectByIds(Map<String, Object> param);
}
\ No newline at end of file
package com.xxfc.platform.vehicle.mapper;
import com.xxfc.platform.vehicle.entity.VehicleCountRecord;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
import java.util.Map;
public interface VehicleCountRecordMapper extends Mapper<VehicleCountRecord> {
List<VehicleCountRecord> countDepartureVehicle(VehicleCountRecord vehicleCountRecord);
List<VehicleCountRecord> selectByTypeAndTime(Map<String, Object> param);
}
\ No newline at end of file
......@@ -125,6 +125,27 @@ public class RentVehicleController extends BaseController<VehicleBiz> implements
return ObjectRestResponse.succ(vehicleBiz.searchUsableModel(dto));
}
/**
* 后台查询可用车辆(车型)
*
* @param dto
* @return
*/
@ApiOperation("可用车辆查询")
@RequestMapping(value = "/rent/back-stage/usable-vehicle", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse<PageDataVO<UsableVehicleModelVO>> rentBgUsableVehicle(UsableVeicleDTO dto) throws Exception {
//根据时间 获得 可用车辆
//结合车型
if (StringUtils.isNotBlank(dto.getCatasStr())) {
dto.setCatas(vehiclePlatCataBiz.groupCatasByParent(dto.getCatasStr()));
}
//设置显示是否有车
dto.setYearNo4Where(Boolean.TRUE);
dto.setUseType(null);
return ObjectRestResponse.succ(vehicleBiz.searchUsableModel(dto));
}
/**
* 热门车型
*
......
package com.xxfc.platform.vehicle.rest;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.vehicle.biz.VehicleCountRecordBiz;
import com.xxfc.platform.vehicle.entity.VehicleCountRecord;
import com.xxfc.platform.vehicle.pojo.ExcelParamDto;
import com.xxfc.platform.vehicle.util.excel.DownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
@Controller
@RequestMapping(value = "/vehicleCount")
public class VehicleCountRecordController {
@Autowired
VehicleCountRecordBiz vehicleCountRecordBiz;
@GetMapping("/app/unauth/test")
@ResponseBody
public ObjectRestResponse add() {
vehicleCountRecordBiz.addAll();
return ObjectRestResponse.succ();
}
@GetMapping("/app/unauth/get")
@ResponseBody
public ObjectRestResponse getByTypeAndDate(VehicleCountRecord vehicleCountRecord) {
return vehicleCountRecordBiz.countDepartureVehicle(vehicleCountRecord);
}
@PostMapping("/app/unauth/export")
@ResponseBody
public ObjectRestResponse export(@RequestBody ExcelParamDto excelParamDto) {
return vehicleCountRecordBiz.export(excelParamDto);
}
@GetMapping("/app/unauth/download")
public void download(ExcelParamDto excelParamDto, HttpServletRequest request,HttpServletResponse response) {
DownloadUtil.downloadFile(excelParamDto.getPath(), "export.xls", response,request);
}
}
......@@ -15,7 +15,7 @@
</plugin>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://10.5.52.3:3306/vehicle?useUnicode=true&amp;characterEncoding=UTF8"
connectionURL="jdbc:mysql://10.5.52.3:3306/xxfc_vehicle?useUnicode=true&amp;characterEncoding=UTF8"
userId="root"
password="sslcloud123*()">
</jdbcConnection>
......@@ -37,7 +37,7 @@
<!-- </table>-->
<!-- <table tableName="branch_company_stock_info" domainObjectName="BranchCompanyStockInfo"></table>-->
<!-- <table tableName="branch_company_stock_apply_info" domainObjectName="BranchCompanyStockApplyInfo"></table>-->
<table tableName="vehicle_book_hour_info" domainObjectName="VehicleBookHourInfo"></table>
<table tableName="vehicle_count_record" domainObjectName="VehicleCountRecord"></table>
<!-- <table tableName="vehicle_upkeep_log" domainObjectName="VehicleUpkeepLog"></table>-->
</context>
</generatorConfiguration>
\ No newline at end of file
......@@ -516,6 +516,26 @@
order by create_time DESC
</select>
<select id="selectAllBookRecord" resultMap="searchBookRecord" parameterType="Map">
select v1.* from vehicle_book_record v1
where v1.status not in (4,6,7,3)
<if test="startTime != null and status == 1">
and v1.book_start_date between #{startTime} and #{endTime}
</if>
<if test="startTime != null and status == 2">
and v1.book_end_date between #{startTime} and #{endTime}
</if>
</select>
<select id="selectByIds" resultMap="searchBookRecord" parameterType="Map">
select v1.* from vehicle_book_record v1
where v1.status not in (4,6,7,3)
<if test="ids != null and ids.size > 0">
and v1.id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</select>
<insert id="createTbIfNotExists" parameterType="java.lang.String">
CREATE TABLE IF NOT EXISTS ${_parameter} (
......
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxfc.platform.vehicle.mapper.VehicleCountRecordMapper" >
<resultMap id="BaseResultMap" type="com.xxfc.platform.vehicle.entity.VehicleCountRecord" >
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="type" property="type" jdbcType="INTEGER" />
<result column="departure_num" property="departureNum" jdbcType="INTEGER" />
<result column="actual_departure_num" property="actualDepartureNum" jdbcType="INTEGER" />
<result column="after_departure_num" property="afterDepartureNum" jdbcType="INTEGER" />
<result column="before_departure_num" property="beforeDepartureNum" jdbcType="INTEGER" />
<result column="arrival_num" property="arrivalNum" jdbcType="INTEGER" />
<result column="actual_arrival_num" property="actualArrivalNum" jdbcType="INTEGER" />
<result column="after_arrival_num" property="afterArrivalNum" jdbcType="INTEGER" />
<result column="before_arrival_num" property="beforeArrivalNum" jdbcType="INTEGER" />
<result column="count_date" property="countDate" jdbcType="DATE"/>
</resultMap>
<select id = "countDepartureVehicle" parameterType = "com.xxfc.platform.vehicle.entity.VehicleCountRecord" resultMap = "BaseResultMap">
select * from vehicle_count_record where count_date = #{time}
</select>
<select id="selectByTypeAndTime" parameterType = "Map" resultType="com.xxfc.platform.vehicle.entity.VehicleCountRecord">
select * from vehicle_count_record
<where>
<if test="type != null">
and type = #{type}
</if>
<if test="startTime != null">
and count_date = #{startTime}
</if>
</where>
order by id DESC
</select>
</mapper>
\ No newline at end of file
......@@ -682,6 +682,9 @@
</if>
and v.is_del = 0
and v.status != 3
<if test="useType != null">
and v.use_type = #{useType}
</if>
and v.use_type = 1
and bc.is_del = 0
and bc.is_show = 1
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment