前台传过来的数据用orderForm类包装:
@Data
public class OrderForm {
@NotEmpty
//买家姓名
private String name;
@NotEmpty
//买家电话
private String phone;
@NotEmpty
//买家地址
private String address;
@NotEmpty
//买家微信
private String openid;
@NotEmpty
//购物车
private String items;
}
注意:表单验证用到@Valid注解
转换器:orderForm转换成orderDto
public class OrderForm2OrderDto {
public static OrderDto convert(OrderForm orderForm) {
Gson gson = new Gson();
OrderDto orderDto = new OrderDto();
orderDto.setBuyerName(orderForm.getName());
orderDto.setBuyerPhone(orderForm.getPhone());
orderDto.setBuyerAddress(orderForm.getAddress());
orderDto.setBuyerOpenid(orderForm.getOpenid());
List<OrderDetail> orderDetailList = new ArrayList<>();
try {
//json数据转换成list
orderDetailList = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>() {
}.getType());
} catch (Exception e) {
throw new SellException(ResultEnum.PARAM_ERROR);
}
orderDto.setOrderDetailList(orderDetailList);
return orderDto;
}
}
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {
@Autowired
private OrderService orderService;
//创建订单
@PostMapping("/create")
public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
log.error("【新建订单】参数错误");
throw new SellException(ResultEnum.PARAM_ERROR);
}
//orderform转成orderdto
OrderDto orderDto = OrderForm2OrderDto.convert(orderForm);
OrderDto createResult = orderService.creat(orderDto);
Map<String, String> map = new HashMap<>();
map.put("orderId", createResult.getOrderId());
return ResultVOUtil.success(map);
}
//订单列表
@GetMapping("/list")
public ResultVO<List<OrderDto>> list(@RequestParam("openid") String openid,
@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size) {
if (org.apache.commons.lang3.StringUtils.isEmpty(openid)) {
log.error("【订单列表】 微信名不能为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
PageRequest pageRequest = new PageRequest(page, size);
Page<OrderDto> orderDtoPage = orderService.findList(openid, pageRequest);
return ResultVOUtil.success(orderDtoPage.getContent());
}
//订单详情
@GetMapping("/detail")
public ResultVO<OrderDto> detail(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId) {
OrderDto orderDto = orderService.findOne(orderId);
return ResultVOUtil.success(orderDto);
}
//取消订单
@PostMapping("/cancle")
public ResultVO cancle(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId) {
OrderDto orderDto = orderService.findOne(orderId);
orderService.cancel(orderDto);
return ResultVOUtil.success();
}
}