Commit eb3d0943 by caiyt

周度提交

parent 1d14efba
......@@ -75,10 +75,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
</configuration>
<executions>
<execution>
<goals>
......@@ -87,15 +83,16 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
<excludes>
<exclude>application.yml</exclude>
<exclude>application-druid.yml</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
......
......@@ -18,6 +18,7 @@ import com.soss.system.service.impl.OrderServiceImpl;
import com.soss.system.service.impl.WechatMessageServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
......@@ -50,6 +51,7 @@ public class AppController extends BaseController {
String openId = loginUser.getOpenId();
startPage();
List<Order> myOrder = orderService.getMyOrder(openId);
orderService.wrapperOrder(myOrder, true);
return getDataTable(myOrder);
}
......@@ -94,7 +96,7 @@ public class AppController extends BaseController {
}
@RequestMapping("/getNextOrder")
public AjaxResult getNextOrder(String orderId, String shopId) {
public AjaxResult getNextOrder(Long orderId, Long shopId) {
return AjaxResult.success(orderService.getNextOrder(orderId, shopId));
}
......@@ -148,15 +150,24 @@ public class AppController extends BaseController {
if (loginUser == null) {
throw new ServiceException("请先登录");
}
loginUser.setOpenId("oA0gy4x4bUZcULVYwsLI_EW901mg");
List<CouponVo> couponVos = couponUserService.listCustAvailableCoupon(loginUser.getOpenId(), null);
couponUserService.resovleCouponFitable(couponVos, order);
couponRuleService.translateUseLimit(couponVos);
List<CouponVo> fitableList = couponVos.stream().filter(couponVo -> StringUtils.isEmpty(couponVo.getNotFitableDesc()))
.sorted(Comparator.comparing(CouponVo::getCouponAmount).reversed()).collect(Collectors.toList());
List<CouponVo> notFitableList = couponVos.stream().filter(couponVo -> !StringUtils.isEmpty(couponVo.getNotFitableDesc())).collect(Collectors.toList());
JSONObject result = new JSONObject();
result.put("fitable", fitableList);
List<CouponVo> fitableList = couponVos.stream().filter(couponVo -> StringUtils.isEmpty(couponVo.getNotFitableDesc())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(fitableList)) {
fitableList.sort(Comparator.comparing(CouponVo::getCouponAmount).reversed());
CouponVo couponAmountBigest = fitableList.remove(0);
fitableList.sort(Comparator.comparing(CouponVo::getUseEndTime).thenComparing(CouponVo::getId));
fitableList.add(0, couponAmountBigest);
result.put("fitable", fitableList);
}
List<CouponVo> notFitableList = couponVos.stream().filter(couponVo -> !StringUtils.isEmpty(couponVo.getNotFitableDesc())).
sorted(Comparator.comparing(CouponVo::getUseEndTime).thenComparing(CouponVo::getId)).collect(Collectors.toList());
result.put("notfitable", notFitableList);
return AjaxResult.success(result);
}
......
......@@ -8,7 +8,13 @@ import com.soss.common.utils.uuid.UUID;
import com.soss.system.domain.Machine;
import com.soss.system.domain.Shop;
import com.soss.system.jiguang.impl.JiGuangPushServiceImpl;
import com.soss.system.service.impl.*;
import com.soss.system.service.ICustomerService;
import com.soss.system.service.impl.MachineServiceImpl;
import com.soss.system.service.impl.OrderServiceImpl;
import com.soss.system.service.impl.OrderTakingServiceImpl;
import com.soss.system.service.impl.ShopServiceImpl;
import com.soss.system.utils.DistanceUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
......@@ -24,25 +30,29 @@ public class ApplicationController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
MachineServiceImpl machineService;
MachineServiceImpl machineService;
@Autowired
JiGuangPushServiceImpl jiGuangPushService;
@Autowired
OrderTakingServiceImpl orderTakingService;
OrderTakingServiceImpl orderTakingService;
@Autowired
ShopServiceImpl shopService;
ShopServiceImpl shopService;
@Autowired
OrderServiceImpl orderService;
OrderServiceImpl orderService;
@Autowired
private ICustomerService customerService;
@RequestMapping("/saveData")
public AjaxResult saveApplicationData(@RequestParam("machineCode")String machineCode, @RequestBody String body){
public AjaxResult saveApplicationData(@RequestParam("machineCode") String machineCode, @RequestBody String body) {
String id = UUID.randomUUID().toString();
String key = machineCode;//+"_"+id;
stringRedisTemplate.opsForValue().set(key, body);
stringRedisTemplate.expire(key,60, TimeUnit.SECONDS);
return AjaxResult.success("处理成功",key);
stringRedisTemplate.expire(key, 60, TimeUnit.SECONDS);
return AjaxResult.success("处理成功", key);
}
@RequestMapping("/getData")
public AjaxResult getApplicationData(@RequestBody String body){
public AjaxResult getApplicationData(@RequestBody String body) {
JSONObject jj = JSONObject.parseObject(body);
String key = jj.getString("key");
JSONObject location = jj.getJSONObject("location");
......@@ -50,11 +60,19 @@ public class ApplicationController {
if (StringUtils.isEmpty(s)) {
throw new ServiceException("该二维码已经过期");
}
String openId = jj.getString("openId");
String faceInfoId = jj.getString("faceInfoId");
if (StringUtils.isNotEmpty(openId)) {
Assert.isTrue(StringUtils.isNotEmpty(faceInfoId), "faceInfoId还未传递");
customerService.insertCustFaceInfo(openId, faceInfoId);
}
JSONObject info = JSONObject.parseObject(s);
String machineCode = info.getString("machineCode");
Machine machine = machineService.selectMachineByCode(machineCode);
Shop shop = shopService.selectShopById(machine.getShopId());
shop.setDistance(AppServiceImpl.getDistance(Double.parseDouble(shop.getLng()), Double.parseDouble(shop.getLat()), Double.parseDouble(location.getString("lng")), Double.parseDouble(location.getString("lat"))));
shop.setDistance(DistanceUtil.getDistanceDesc(Double.parseDouble(shop.getLng()), Double.parseDouble(shop.getLat()), Double.parseDouble(location.getString("lng")), Double.parseDouble(location.getString("lat"))));
info.put("shop", shop);
String[] keys = key.split("_");
//推送数据给安卓
......@@ -84,11 +102,12 @@ public class ApplicationController {
}
@RequestMapping("/getOrderInfo")
public AjaxResult getOrderInfo(String machineCode){
public AjaxResult getOrderInfo(String machineCode) {
return AjaxResult.success(orderService.getOrderInfo(machineCode));
}
@RequestMapping("/checkSku")
public AjaxResult checkSku(@RequestParam(required = false) String shopId,String skuId,@RequestParam(required = false) String machineCode){
return shopService.checkSku(shopId,skuId,machineCode);
public AjaxResult checkSku(@RequestParam(required = false) Long shopId, Long skuId, @RequestParam(required = false) String machineCode) {
return shopService.checkSku(shopId, skuId, machineCode);
}
}
......@@ -65,6 +65,16 @@ public class CustomerController extends BaseController {
return AjaxResult.success(customer);
}
@PostMapping("/update/avatar-url")
@ApiOperation("修改用户头像")
public AjaxResult updateAvatarUrl(HttpServletRequest request, @RequestBody Customer customer) {
custPmsCheck(request, customer.getId());
Assert.isTrue(!StringUtils.isEmpty(customer.getAvatarUrl()), "用户头像未传递");
Assert.isNull(customer.getBirthday(), "该方法不支持修改生日");
customerService.updateCustomer(customer);
return AjaxResult.success();
}
@PostMapping("/update/base")
@ApiOperation("修改用户基本信息:昵称和性别")
public AjaxResult updateCust(HttpServletRequest request, @RequestBody Customer customer) {
......@@ -106,7 +116,6 @@ public class CustomerController extends BaseController {
return getDataTable(list);
}
/**
* 获取用户信息详细信息
*/
......
......@@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/v1")
@RequestMapping("/test")
@Slf4j
public class MachineApiController {
@Autowired
......
package com.soss.web.controller.coffee;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.soss.common.annotation.Log;
import com.soss.common.core.controller.BaseController;
import com.soss.common.core.domain.AjaxResult;
import com.soss.common.core.page.TableDataInfo;
import com.soss.common.enums.BusinessType;
import com.soss.system.domain.Machine;
import com.soss.system.service.IMachineService;
import com.soss.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 机器Controller
......
......@@ -14,6 +14,7 @@ import com.soss.system.domain.Order;
import com.soss.system.domain.vo.CouponVo;
import com.soss.system.domain.vo.OrderQuery;
import com.soss.system.service.ICouponUserService;
import com.soss.system.service.IGoodsService;
import com.soss.system.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -45,6 +46,8 @@ public class OrderController extends BaseController {
private WeixinServiceImpl weixinService;
@Autowired
private ICouponUserService couponUserService;
@Autowired
private IGoodsService goodsService;
/**
* 查询订单列表
......@@ -54,6 +57,7 @@ public class OrderController extends BaseController {
public TableDataInfo list(OrderQuery orderQuery) {
startPage();
List<Order> list = orderService.selectOrderList(orderQuery);
orderService.wrapperOrder(list, false);
return getDataTable(list);
}
......@@ -63,7 +67,9 @@ public class OrderController extends BaseController {
*/
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(orderService.selectOrderById(id));
Order order = orderService.selectOrderById(id);
goodsService.resolverGoodsOfOrder(order);
return AjaxResult.success(order);
}
......@@ -156,7 +162,6 @@ public class OrderController extends BaseController {
}
}
/**
* 修改订单
*/
......
......@@ -11,9 +11,7 @@ import com.soss.common.exception.ServiceException;
import com.soss.common.utils.StringUtils;
import com.soss.framework.web.service.TokenService;
import com.soss.framework.web.service.WeixinServiceImpl;
import com.soss.system.domain.Goods;
import com.soss.system.domain.Order;
import com.soss.system.domain.OrderDetail;
import com.soss.system.domain.OrderRefund;
import com.soss.system.domain.vo.OrderQuery;
import com.soss.system.service.IGoodsService;
......@@ -22,13 +20,11 @@ import com.soss.system.service.impl.OrderServiceImpl;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 订单退款Controller
......@@ -80,21 +76,7 @@ public class OrderRefundController extends BaseController
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") String id) {
OrderRefund refund = orderRefundService.selectOrderRefundById(id);
Order order = refund.getOrder();
if (order == null) {
return AjaxResult.success(refund);
}
List<OrderDetail> orderDetails = order.getOrderDetails();
if (CollectionUtils.isEmpty(orderDetails)) {
return AjaxResult.success(refund);
}
List<Long> goodsIds = orderDetails.stream().map(OrderDetail::getGoodsId).collect(Collectors.toList());
List<Goods> goods = goodsService.selectGoodsByIds(goodsIds);
orderDetails.forEach(orderDetail -> goods.forEach(good -> {
if (Objects.equals(orderDetail.getGoodsId(), good.getId())) {
orderDetail.setGoods(good);
}
}));
goodsService.resolverGoodsOfOrder(refund.getOrder());
return AjaxResult.success(refund);
}
......@@ -122,8 +104,14 @@ public class OrderRefundController extends BaseController
int refundAmount = orderRefund1.getRefundAmount().movePointRight(2).intValue();
if (refundAmount > 0) {
int totalFee = orderRefund1.getOrder().getPaidAmount().movePointRight(2).intValue();
weixinService.refund(orderRefund1.getOrderNo(), orderRefund1.getRefundNo(), totalFee, refundAmount);
orderRefund1.setState(RefundState.REFUNDING.getState());
boolean refundSuc;
try {
String refundResult = weixinService.refund(orderRefund1.getOrderNo(), orderRefund1.getRefundNo(), totalFee, refundAmount);
refundSuc = !Objects.equals("退款失败", refundResult);
} catch (Exception e) {
refundSuc = false;
}
orderRefund1.setState(refundSuc ? RefundState.REFUNDING.getState() : RefundState.FAILURE.getState());
} else {
orderRefund1.setState(RefundState.SUCCESS.getState());
}
......
......@@ -32,7 +32,7 @@ public class OrderTakingController {
* @return
*/
@GetMapping(value = "/infoByShop")
public AjaxResult infoByShop(String shopId)
public AjaxResult infoByShop(Long shopId)
{
return AjaxResult.success(orderTakingService.getInfoByShop(shopId));
}
......
......@@ -13,6 +13,7 @@ import com.soss.system.service.ICustomerService;
import com.soss.system.service.impl.AppServiceImpl;
import com.soss.system.service.impl.OrderTakingServiceImpl;
import com.soss.system.utils.SendSmsUtil;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -43,7 +44,6 @@ public class WeixinController {
String code = param.getString("code");
return AjaxResult.success(weixinService.login(code));
}
@PostMapping("/decrypt")
......@@ -54,14 +54,17 @@ public class WeixinController {
String source = param.getString("source");
String openId = param.getString("openId");
String sessionKey = param.getString("session_key");
String faceInfoId = param.getString("faceInfoId");
Assert.isTrue(StringUtils.isNotEmpty(openId), "openId还未传递");
AjaxResult ajax = AjaxResult.success();
Map<String, String> decrypt = weixinService.decrypt(encryptedData, iv, source, openId, sessionKey);
Map<String, String> decrypt = weixinService.decrypt(encryptedData, iv, source, openId, faceInfoId, sessionKey);
ajax.put(Constants.TOKEN, decrypt.get("token"));
ajax.put("phoneNumber", decrypt.get("phoneNumber"));
ajax.put("customerName",decrypt.get("customerName"));
ajax.put("customerName", decrypt.get("customerName"));
return ajax;
}
@PostMapping("/refreshToken")
public AjaxResult getRefreshToken(@RequestBody String body){
JSONObject param = JSONObject.parseObject(body);
......@@ -112,10 +115,8 @@ public class WeixinController {
}
@GetMapping(value = "/infoByShop")
public AjaxResult infoByShop(String shopId)
{
public AjaxResult infoByShop(Long shopId) {
return AjaxResult.success(orderTakingService.getInfoByShop(shopId));
}
......
......@@ -28,6 +28,7 @@ import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
......@@ -77,6 +78,9 @@ public class CouponController extends BaseController {
couponVo.setRuleId(coupon.getRuleId());
couponVo.setRuleName(couponRule.getName());
couponVo.setRuleDesc(couponRule.getDesc());
if (Objects.equals(couponRule.getDaysLimit(), 0)) {
couponVo.setDaysLimit(null);
}
}
return couponVo;
}).collect(Collectors.toList());
......@@ -110,6 +114,9 @@ public class CouponController extends BaseController {
BeanUtils.copyProperties(coupon, couponVo);
CouponRule couponRule = couponRuleService.detail(coupon.getRuleId());
transLimitToArrStyle(couponVo, couponRule);
if (Objects.equals(couponRule.getDaysLimit(), 0)) {
couponVo.setDaysLimit(null);
}
return AjaxResult.success(couponVo);
}
......
......@@ -91,6 +91,7 @@ weixin:
templateId: Fu_CPIXa0cnJ4EDdVKqFQ4T3qTxBqv8vXMU7-sQgerg
pagePath: orderSubPackage/pages/orderInfo/index?orderId=
program: trial
# program: formal
#mqtt:
# url: tcp://iot-06z00dhgql5j8bw.mqtt.iothub.aliyuncs.com:1883
# clientId: h5kgirX6kNQ.XQ_000001A|securemode=2,signmethod=hmacsha256,timestamp=1651746531320|
......
package com.soss.common.enums;
/**
* 商品状态枚举类
*/
public enum GoodsState {
NORMAL(1, "默认"),
PAUSE(2, "暂停销售"),
ONLINE(3, "上架"),
OFFLINE(4, "下架"),
DELETE(5, "已删除");
private Integer state;
private String desc;
GoodsState(Integer state, String desc) {
this.state = state;
this.desc = desc;
}
public Integer getState() {
return state;
}
public static String getDesc(Integer state) {
for (GoodsState goodsState : GoodsState.values()) {
if (goodsState.state.equals(state)) {
return goodsState.desc;
}
}
return null;
}
}
......@@ -163,6 +163,6 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
}
public static LocalDateTime addDaysAndGetEnd(LocalDateTime targetTime, int days) {
return targetTime.plusDays(days).toLocalDate().atTime(23, 59, 59, 999999999);
return targetTime.plusDays(days).toLocalDate().atTime(23, 59, 59);
}
}
......@@ -27,15 +27,13 @@ import com.soss.system.mapper.CustomerMapper;
import com.soss.system.mapper.OrderDetailMapper;
import com.soss.system.mapper.OrderRefundMapper;
import com.soss.system.mapper.ShopMapper;
import com.soss.system.service.IWechatMessageService;
import com.soss.system.service.impl.AppServiceImpl;
import com.soss.system.service.impl.MachineApiServiceImpl;
import com.soss.system.service.impl.OrderOperationLogServiceImpl;
import com.soss.system.service.impl.OrderServiceImpl;
import com.soss.system.utils.DistanceUtil;
import com.soss.system.weixin.entity.OrderInfo;
import com.soss.system.weixin.entity.QueryReturnInfo;
import com.soss.system.weixin.util.RandomStringGenerator;
import com.soss.system.weixin.util.SendMessageUtils;
import com.soss.system.weixin.util.Signature;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.lang3.BooleanUtils;
......@@ -46,6 +44,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;
......@@ -113,19 +112,9 @@ public class WeixinServiceImpl {
private String url;
@Value("${weixin.query-url}")
private String queryUrl;
@Value("${weixin.cert-path}")
private String certPath;
@Value("${weixin.refund-url}")
private String refundUrl;
private String areaData;
@Value("${json.path}")
private String jsonPath;
@Autowired
private IWechatMessageService wechatMessageService;
@Autowired
private SendMessageUtils sendMessageUtils;
public String getSessionKeyOrOpenId(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
......@@ -136,30 +125,19 @@ public class WeixinServiceImpl {
}
@PostConstruct
public void getData() {
public void initAreaData() {
try {
/*File file = new File(jsonPath);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line=bufferedReader.readLine())!=null){
builder.append(line);
}
areaData = builder.toString();*/
ClassPathResource resource = new ClassPathResource("province.json");
byte[] bdata = FileCopyUtils.copyToByteArray(resource.getInputStream());
areaData = new String(bdata, StandardCharsets.UTF_8);
}catch (Exception e){
log.error("",e);
} catch (Exception e) {
log.error("", e);
}
}
public String login(String code) {
String sessionKeyOrOpenId = getSessionKeyOrOpenId(code);
return sessionKeyOrOpenId;
}
private LoginUser transLoginUser(Customer customer){
......@@ -544,18 +522,18 @@ public class WeixinServiceImpl {
String zoneString = "[value='%s'][0].children[value='%s'][0].children[value='%s'][0].label";
Shop shop = new Shop();
if (BooleanUtils.isTrue(testFlag)) {
shop.setStates(Arrays.asList(ShopState.TESTING.getState(), ShopState.OPEN.getState()));
shop.setStates(Arrays.asList(ShopState.TESTING.getState(), ShopState.OPEN.getState(), ShopState.CLOSE.getState()));
} else {
shop.setState(ShopState.OPEN.getState());
shop.setStates(Arrays.asList(ShopState.OPEN.getState(), ShopState.CLOSE.getState()));
}
List<Shop> shops = shopMapper.selectShopList(shop);
List<JSONObject> proviceList = new ArrayList<>();
List<String> proString = new ArrayList<>();
for (Shop shop1 : shops) {
if (StringUtils.isNotEmpty(lng) && StringUtils.isNotEmpty(lat)) {
double realDistance = AppServiceImpl.getRealDistance(Double.parseDouble(lng), Double.parseDouble(lat), Double.parseDouble(shop1.getLng()), Double.parseDouble(shop1.getLat()));
double realDistance = DistanceUtil.getRealDistance(Double.parseDouble(lng), Double.parseDouble(lat), Double.parseDouble(shop1.getLng()), Double.parseDouble(shop1.getLat()));
shop1.setRealDistance(realDistance);
shop1.setDistance(AppServiceImpl.getDistance(realDistance));
shop1.setDistance(DistanceUtil.getDistanceDesc(realDistance));
} else {
shop1.setDistance("-1");
}
......@@ -658,45 +636,50 @@ public class WeixinServiceImpl {
}
public String getPhone(String code, String iv, String encryptedData) {
try{
try {
String sessionKeyOrOpenId = getSessionKeyOrOpenId(code);
String infoString = this.wxDecrypt(encryptedData, sessionKeyOrOpenId, iv);
JSONObject info = JSONObject.parseObject(infoString);
return info.getString("phoneNumber");
}catch (Exception e){
log.error("获取手机号异常",e);
} catch (Exception e) {
log.error("获取手机号异常", e);
throw new ServiceException("获取手机号异常");
}
}
public Map<String,String> decrypt(String encryptedData, String iv, String source, String openId, String sessionKey) {
try{
@Transactional
public Map<String, String> decrypt(String encryptedData, String iv, String source, String openId, String faceInfoId, String sessionKey) {
try {
String cutomerId = openId;
String encData = this.wxDecrypt(encryptedData, sessionKey, iv);
log.info("当前用户的信息为:【{}】",encData);
log.info("当前用户的信息为:【{}】", encData);
Customer customer = customerMapper.selectCustomerById(cutomerId);
JSONObject encDataInf = JSONObject.parseObject(encData);
if(customer ==null){
if (customer == null) {
customer = new Customer();
customer.setId(cutomerId);
customer.setHeadSculpturePath(encDataInf.getString("avatarUrl"));
customer.setUserName("小呼噜"+encDataInf.getString("phoneNumber").substring(encDataInf.getString("phoneNumber").length()-4));
customer.setAvatarUrl(encDataInf.getString("avatarUrl"));
customer.setUserName("小呼噜" + encDataInf.getString("phoneNumber").substring(encDataInf.getString("phoneNumber").length() - 4));
customer.setPhone(encDataInf.getString("phoneNumber"));
customer.setCreateTime(new Date());
if(StringUtils.isNotEmpty(source)){
if (StringUtils.isNotEmpty(source)) {
customer.setSoucre(source);
}
customerMapper.insertCustomer(customer);
}
if (StringUtils.isNotEmpty(faceInfoId)) {
customerMapper.insertCustFaceId(openId, faceInfoId);
}
String token = tokenService.createToken(transLoginUser(customer));
Map map = new HashMap();
map.put("token",token);
map.put("phoneNumber",encDataInf.getString("phoneNumber"));
map.put("customerName",customer.getUserName());
map.put("token", token);
map.put("phoneNumber", encDataInf.getString("phoneNumber"));
map.put("customerName", customer.getUserName());
return map;
}catch (Exception e){
log.error("微信登录发生异常",e);
......
......@@ -42,7 +42,8 @@ public class CouponUser extends BaseEntity {
/**
* 关联订单
*/
private Integer orderId;
private Long orderId;
private String orderNo;
/**
* 关联优惠券
......@@ -99,8 +100,10 @@ public class CouponUser extends BaseEntity {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updatedAt;
public CouponUser(Integer id, Integer state) {
public CouponUser(Integer id, Long orderId, String orderNo, Integer state) {
this.id = id;
this.orderId = orderId;
this.orderNo = orderNo;
this.state = state;
}
}
......@@ -39,7 +39,7 @@ public class Customer extends BaseEntity
* 头像图地址
*/
@Excel(name = "头像图地址")
private String headSculpturePath;
private String avatarUrl;
@ApiModelProperty("性别")
private Boolean sex;
......@@ -83,7 +83,7 @@ public class Customer extends BaseEntity
.append("userName", getUserName())
.append("phone", getPhone())
.append("createTime", getCreateTime())
.append("headSculpturePath", getHeadSculpturePath())
.append("avatarUrl", getAvatarUrl())
.append("soucre", getSoucre())
.toString();
}
......
......@@ -3,6 +3,7 @@ package com.soss.system.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.soss.common.annotation.Excel;
import com.soss.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
......@@ -13,53 +14,75 @@ import java.util.List;
/**
* 商品对象 goods
*
*
* @author zxq
* @date 2022-04-28
*/
@Data
public class Goods extends BaseEntity
{
public class Goods extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 主键 */
/**
* 主键
*/
private long id;
/** 商品名称 */
/**
* 商品名称
*/
@Excel(name = "商品名称")
private String name;
/** 商品分类 */
/**
* 商品分类
*/
@Excel(name = "商品分类")
private String category;
@ApiModelProperty("商品类别id集合,与前端交互使用")
private List<Long> categoryIds;
private String categoryName;
/** 原售价 */
/**
* 原售价
*/
@Excel(name = "原售价")
private BigDecimal price;
/** 折扣价 */
/**
* 折扣价
*/
@Excel(name = "折扣价")
private BigDecimal discount;
/** 制作用时 单位 秒 */
/**
* 制作用时 单位 秒
*/
@Excel(name = "制作用时 单位 秒")
private Long takeTime;
/** 规格信息 形如 [{“spec_name”:”规格1”,”其他属性”:”属性1”,”rules”:[“rule1_name”:”rule1”,”属性1”:”1111”]},{“spec_name”:”规格2”,”其他属性”:”属性2”,”rules”:[“rule1_name”:”rule2”,”属性2”:”2222”]}] */
/**
* 规格信息 形如 [{“spec_name”:”规格1”,”其他属性”:”属性1”,”rules”:[“rule1_name”:”rule1”,”属性1”:”1111”]},{“spec_name”:”规格2”,”其他属性”:”属性2”,”rules”:[“rule1_name”:”rule2”,”属性2”:”2222”]}]
*/
@Excel(name = "规格信息 形如 [{“spec_name”:”规格1”,”其他属性”:”属性1”,”rules”:[“rule1_name”:”rule1”,”属性1”:”1111”]},{“spec_name”:”规格2”,”其他属性”:”属性2”,”rules”:[“rule1_name”:”rule2”,”属性2”:”2222”]}]")
private String spec;
/** 商品图片信息,json字符串形式 如 {“点单屏”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]},“小程序”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]}} */
/**
* 商品图片信息,json字符串形式 如 {“点单屏”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]},“小程序”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]}}
*/
@Excel(name = "商品图片信息,json字符串形式 如 {“点单屏”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]},“小程序”:{“缩略图”:[”地址1”,”地址2”],”介绍图”:[“地址3”,”地址4”]}}")
private String pics;
/** 描述 */
/**
* 描述
*/
@Excel(name = "描述")
private String desc;
/** 备注 */
/**
* 备注
*/
@Excel(name = "备注")
private String remarks;
......
......@@ -127,12 +127,21 @@ public class Order implements Serializable {
@Excel(name = "订单状态 0 未支付取消 1 未支付 2 已支付 3 待制作 4 支付制作中 5 制作完成未取 6 取餐中 7 取餐完成 8 支付后制作前取消 9 制作中取消 10 制作完成取消 11 已退款 12 部分退款 50 其他人工干预状态")
private String state;
/**
* 下单成功通知
*/
@ApiModelProperty("用户授权发送消息1:0-未授权 1-授权")
private Boolean sendMsgFlag1;
/**
* 订单状态变更通知
*/
@ApiModelProperty("用户授权发送消息2:0-未授权 1-授权")
private Boolean sendMsgFlag2;
/**
* 取餐提醒
*/
@ApiModelProperty("用户授权发送消息3:0-未授权 1-授权")
private Boolean sendMsgFlag3;
......
......@@ -7,7 +7,7 @@ import java.io.Serializable;
@Data
public class SkuVo implements Serializable {
private String skuId;
private Long skuId;
private String state;
......
......@@ -86,4 +86,9 @@ public interface CouponUserMapper {
* 用户优惠券到期失效
*/
void expireCouponUser();
/**
* 查询用户领取的优惠券数量
*/
Long getCustCouponCnt(@Param("custId") String custId, @Param("couponId") Integer couponId, @Param("startTime") LocalDateTime startTime);
}
......@@ -3,6 +3,8 @@ package com.soss.system.mapper;
import com.soss.system.domain.Customer;
import com.soss.system.domain.vo.customer.CustomerQueryVo;
import com.soss.system.domain.vo.customer.CustomerResultVo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import java.util.List;
......@@ -61,11 +63,14 @@ public interface CustomerMapper
/**
* 批量删除用户信息
*
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteCustomerByIds(Long[] ids);
List<CustomerResultVo> selectCustomerByQuery(CustomerQueryVo customer);
@Insert("insert into cust_face_info (open_id, face_info_id, created_at) values (#{openId}, #{faceInfoId}, now())")
int insertCustFaceId(@Param("openId") String openId, @Param("faceInfoId") String faceInfoId);
}
package com.soss.system.mapper;
import java.util.List;
import com.soss.system.domain.OrderSnapshot;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 订单快照Mapper接口
*
*
* @author zxq
* @date 2022-05-22
*/
public interface OrderSnapshotMapper
{
public interface OrderSnapshotMapper {
/**
* 查询订单快照
*
*
* @param orderId 订单快照主键
* @return 订单快照
*/
public OrderSnapshot selectOrderSnapshotByOrderId(Long orderId);
List<OrderSnapshot> selectOrderSnapshotByOrderIds(@Param("orderIds") List<Long> orderIds);
/**
* 查询订单快照列表
*
*
* @param orderSnapshot 订单快照
* @return 订单快照集合
*/
......
......@@ -21,8 +21,6 @@ public interface ICouponUserService {
void giveUserCoupon(String custId, Integer couponId);
void receiveCoupon(Long userId, Integer id);
int getCustAvailableCouponCnt(String custId);
List<CouponVo> listCustAvailableCoupon(String custId, Integer couponUserId);
......
......@@ -72,4 +72,6 @@ public interface ICustomerService
public int deleteCustomerById(Long id);
Map<String, Object> getCustSimpleOrderStat(String custId);
int insertCustFaceInfo(String openId, String faceInfoId);
}
......@@ -2,6 +2,7 @@ package com.soss.system.service;
import com.soss.system.domain.Goods;
import com.soss.system.domain.GoodsSku;
import com.soss.system.domain.Order;
import java.util.List;
......@@ -72,4 +73,6 @@ public interface IGoodsService
String deleteGoodsById(Long goodsId, boolean boo);
List<GoodsSku> getGoodsSkus(long goodsId);
void resolverGoodsOfOrder(Order order);
}
......@@ -56,5 +56,7 @@ public interface IOrderService
List<Order> getMyOrder(String openId);
void wrapperOrder(List<Order> orders, boolean snapshotFlag);
int cancel(Long orderId);
}
......@@ -21,6 +21,8 @@ public interface IOrderSnapshotService
*/
public OrderSnapshot selectOrderSnapshotByOrderId(Long orderId);
List<OrderSnapshot> selectOrderSnapshotByOrderIds(List<Long> orderIds);
/**
* 查询订单快照列表
*
......
......@@ -4,12 +4,12 @@ import com.soss.common.enums.ShopState;
import com.soss.common.utils.StringUtils;
import com.soss.system.domain.Shop;
import com.soss.system.mapper.ShopMapper;
import com.soss.system.utils.DistanceUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
......@@ -18,71 +18,39 @@ import java.util.List;
public class AppServiceImpl {
@Autowired
private ShopMapper shopMapper;
private static final double EARTH_RADIUS = 6378137;
/**
* 授权了地理位置的用户都展示距离最近的营业中的店铺;
* 未授权地理位置的用户都展示默认店铺,不管店铺是否营业中;
*/
public Shop getShop(String lng, String lat, Boolean testFlag) {
Shop shop = new Shop();
if (BooleanUtils.isTrue(testFlag)) {
boolean unAuthed = StringUtils.isEmpty(lng) || StringUtils.isEmpty(lat);
if (unAuthed) {
shop.setIsDefault(1L);
} else if (BooleanUtils.isTrue(testFlag)) {
shop.setStates(Arrays.asList(ShopState.TESTING.getState(), ShopState.OPEN.getState()));
} else {
shop.setState(ShopState.OPEN.getState());
}
shop.setIsDefault(1L);
List<Shop> shops = shopMapper.selectShopList(shop);
if (CollectionUtils.isEmpty(shops)) {
return new Shop();
}
if (unAuthed) {
return shops.get(0);
}
shops.forEach(sp -> {
double realDistance;
if (StringUtils.isNotEmpty(lng) && StringUtils.isNotEmpty(lat)) {
realDistance = getRealDistance(Double.parseDouble(lng), Double.parseDouble(lat), Double.parseDouble(sp.getLng()), Double.parseDouble(sp.getLat()));
} else {
realDistance = Double.MAX_VALUE;
}
double realDistance = DistanceUtil.getRealDistance(Double.parseDouble(lng), Double.parseDouble(lat),
Double.parseDouble(sp.getLng()), Double.parseDouble(sp.getLat()));
sp.setRealDistance(realDistance);
sp.setDistance(getDistance(realDistance));
String distanceDesc = DistanceUtil.getDistanceDesc(realDistance);
sp.setDistance(distanceDesc);
});
shops.sort(Comparator.comparing(Shop::getRealDistance).reversed());
shops.sort(Comparator.comparing(Shop::getRealDistance));
return shops.get(0);
}
public static String getDistance(Double realDistance) {
if (realDistance == null) {
return "-1";
}
if (realDistance.equals(Double.MAX_VALUE)) {
return "-1";
}
if (realDistance > 1000 && realDistance < 10000) {
DecimalFormat df = new DecimalFormat("######0.0");
return df.format(realDistance / 1000) + "km";
} else if (realDistance >= 10000) {
Double aDouble = realDistance / 1000;
return aDouble.intValue() + "km";
}
return realDistance.intValue() + "m";
}
/**
* 根据两点间经纬度坐标(double值),计算两点间距离,单位为米
*/
public static String getDistance(double lng1, double lat1, double lng2, double lat2) {
double s = getRealDistance(lng1, lat1, lng2, lat2);
return getDistance(s);
}
public static double getRealDistance(double lng1, double lat1, double lng2, double lat2) {
double radLat1 = Math.toRadians(lat1);
double radLat2 = Math.toRadians(lat2);
double a = radLat1 - radLat2;
double b = Math.toRadians(lng1) - Math.toRadians(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s *= EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
}
}
......@@ -134,6 +134,9 @@ public class CouponServiceImpl implements ICouponService {
}
}
Assert.notNull(couponPo.getUserLimit(), "用户可领取次数限制还未设置");
if (couponPo.getDaysLimit() == null) {
couponPo.setDaysLimit(0);
}
Assert.notNull(couponPo.getUseStartTime(), "优惠券的绝对有效时间还未设置");
Assert.notNull(couponPo.getUseEndTime(), "优惠券的绝对有效时间还未设置");
......
......@@ -3,6 +3,7 @@ package com.soss.system.service.impl;
import com.soss.common.enums.CouponCategoryType;
import com.soss.common.enums.CouponState;
import com.soss.common.enums.CouponUserType;
import com.soss.common.enums.SkuDeleteState;
import com.soss.common.exception.ServiceException;
import com.soss.common.utils.DateUtils;
import com.soss.common.utils.StringUtils;
......@@ -15,7 +16,6 @@ import com.soss.system.utils.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
......@@ -57,17 +57,14 @@ public class CouponUserServiceImpl implements ICouponUserService {
Assert.notNull(cust, "用户不存在[id=" + custId + "]");
Coupon coupon = couponMapper.selectCouponById(couponId);
Assert.isTrue(coupon != null && Objects.equals(coupon.getState(), CouponState.ONLINE.getState()), "优惠券状态不合法");
CouponRule couponRule = couponRuleMapper.selectCouponRuleById(coupon.getRuleId());
Assert.notNull(couponRule, "未查询到匹配的优惠券规则[id=" + coupon.getRuleId() + "]");
LocalDateTime now = LocalDateTime.now();
if (couponRule.getUseStartTime().isAfter(now) || couponRule.getUseEndTime().isBefore(now)) {
throw new ServiceException("优惠券不在有效期内");
}
CouponRule couponRule = this.couponRuleResolve(custId, couponId, coupon);
CouponUser couponUser = new CouponUser();
couponUser.setCustId(custId);
couponUser.setCustName(cust.getUserName());
couponUser.setCustPhone(cust.getPhone());
couponUser.setCouponId(couponId);
LocalDateTime now = LocalDateTime.now();
couponUser.setExpiredTime(this.getCouponExpiredTime(couponRule, now));
couponUser.setReceiveTime(now);
couponUser.setSource("赠送");
......@@ -77,27 +74,36 @@ public class CouponUserServiceImpl implements ICouponUserService {
couponUserMapper.insertCouponUser(couponUser);
}
@Override
@Transactional
public void receiveCoupon(Long userId, Integer id) {
CouponUser couponUser = couponUserMapper.getUserCouponById(id);
Assert.notNull(couponUser, "未查询到匹配记录[id=" + id + "]");
Assert.isTrue(couponUser.getCustId().equals(userId), "该券与当前用户信息不符");
private CouponRule couponRuleResolve(String custId, Integer couponId, Coupon coupon) {
LocalDateTime now = LocalDateTime.now();
Coupon coupon = couponMapper.selectCouponById(couponUser.getCouponId());
Assert.notNull(coupon, "未查询到匹配的优惠券信息[id=" + couponUser.getCouponId() + "]");
CouponRule couponRule = couponRuleMapper.selectCouponRuleById(coupon.getRuleId());
Assert.notNull(couponRule, "未查询到匹配的优惠券规则信息[id=" + coupon.getRuleId() + "]");
if (couponRule.getReceivableTime() != null && couponRule.getReceivableTime().isAfter(now)) {
throw new ServiceException("该券还未到可领取的时间:" + DateUtils.dateTimeNow());
}
Assert.notNull(couponRule, "未查询到匹配的优惠券规则[id=" + coupon.getRuleId() + "]");
if (couponRule.getUseEndTime().isBefore(now)) {
throw new ServiceException("券已失效");
throw new ServiceException("优惠券已失效");
}
couponUser.setExpiredTime(this.getCouponExpiredTime(couponRule, now));
couponUser.setReceiveTime(now);
couponUser.setUpdatedAt(now);
couponUserMapper.updateCouponUser(couponUser);
// 可领取次数的校验
if (couponRule.getUserLimit() == null || couponRule.getUserLimit() == 0) {
return couponRule;
}
CouponUser couponUser = new CouponUser();
couponUser.setCustId(custId);
LocalDateTime startTime = null;
if (couponRule.getDaysLimit() != null && couponRule.getDaysLimit() > 0) {
startTime = DateUtils.addDaysAndGetBegin(now, 1 - couponRule.getDaysLimit());
}
Long custCouponCnt = couponUserMapper.getCustCouponCnt(custId, couponId, startTime);
if (custCouponCnt >= couponRule.getUserLimit()) {
String errMsg = "该优惠券只可";
if (couponRule.getDaysLimit() != null && couponRule.getDaysLimit() > 0) {
errMsg += "每" + couponRule.getDaysLimit() + "天";
}
errMsg += "领取" + couponRule.getUserLimit() + "次";
throw new ServiceException(errMsg);
}
return couponRule;
}
private LocalDateTime getCouponExpiredTime(CouponRule couponRule, LocalDateTime now) {
......@@ -240,6 +246,9 @@ public class CouponUserServiceImpl implements ICouponUserService {
// 订单明细设置
orderDetails.forEach(orderDetail -> {
GoodsSku sku = skuMap.get(orderDetail.getSkuId());
if (!Objects.equals(sku.getIsDeleted(), SkuDeleteState.NORMAL.getState())) {
throw new ServiceException("规格已下架");
}
BigDecimal skuNum = new BigDecimal(orderDetail.getNum());
orderDetail.setOriAmount(skuNum.multiply(sku.getPrice()));
orderDetail.setUnitPrice(sku.getDiscount());
......@@ -254,7 +263,7 @@ public class CouponUserServiceImpl implements ICouponUserService {
OrderDetail orderDetail = fitOrderDetails.stream().max(Comparator.comparing(OrderDetail::getUnitPrice)).get();
BigDecimal discountAmount = orderDetail.getUnitPrice();
if (couponVo.getType().equals(CouponCategoryType.DISCOUNT.getType())) { // 折扣
discountAmount = this.getDiscountAmount(discountAmount, couponVo.getPriceDiscount());
discountAmount = this.getDiscountAmount(discountAmount, couponVo.getPriceDiscount()).min(BigDecimal.valueOf(50));
}
couponVo.setCouponAmount(discountAmount);
couponAmountMap.put(orderDetail.getSkuId(), couponVo.getCouponAmount());
......@@ -305,7 +314,8 @@ public class CouponUserServiceImpl implements ICouponUserService {
return;
}
/** 可用时段的判断 */
if (!ArrayUtil.isAllAvailable(couponVo.getWeekLimit()) && !ArrayUtil.contains(couponVo.getWeekLimit(), dayOfWeek)) {
if ((!ArrayUtil.isAllAvailable(couponVo.getWeekLimit()) && !ArrayUtil.contains(couponVo.getWeekLimit(), dayOfWeek)) ||
couponVo.getUseStartTime().isAfter(LocalDateTime.now())) {
couponVo.setNotFitableDesc("限定时段使用");
}
});
......
......@@ -53,7 +53,6 @@ public class CustomerServiceImpl implements ICustomerService
{
Order order = new Order();
order.setUserId(id);
List<Order> orders = null;
List<String> statusList;
if("1".equals(status)){
statusList = Arrays.asList(OrderStatusConstant.PaidCancel, OrderStatusConstant.Unpaid, OrderStatusConstant.Paid, OrderStatusConstant.production, OrderStatusConstant.productionCompleted, OrderStatusConstant.Taking, OrderStatusConstant.completed);
......@@ -62,7 +61,7 @@ public class CustomerServiceImpl implements ICustomerService
}else{
statusList = Arrays.asList(OrderStatusConstant.refunding, OrderStatusConstant.refundFailed, OrderStatusConstant.PartialRefund, OrderStatusConstant.refund);
}
orders = orderMapper.selectOrderByUserId(id, statusList);
List<Order> orders = orderMapper.selectOrderByUserId(id, statusList);
for (Order order1 : orders) {
order1.setShop(shopMapper.selectShopById(order1.getShopId()));
}
......@@ -155,4 +154,9 @@ public class CustomerServiceImpl implements ICustomerService
public Map<String, Object> getCustSimpleOrderStat(String custId) {
return orderMapper.getCustOrderSimpleStat(custId);
}
@Override
public int insertCustFaceInfo(String openId, String faceInfoId){
return customerMapper.insertCustFaceId(openId, faceInfoId);
}
}
......@@ -56,7 +56,6 @@ public class GoodsServiceImpl implements IGoodsService
@Autowired
private JiGuangPushServiceImpl jiGuangPushService;
/**
* 查询商品
*
......@@ -107,11 +106,14 @@ public class GoodsServiceImpl implements IGoodsService
List<Long> categoryIds = new ArrayList<>(16);
goodsList.forEach(good -> {
String[] categoryIdArr = good.getCategory().split(StringPool.COMMA);
List<Long> goodCategoryIds = new ArrayList<>();
for (String categoryId : categoryIdArr) {
if (!StringUtils.isEmpty(categoryId)) {
categoryIds.add(Long.parseLong(categoryId));
goodCategoryIds.add(Long.parseLong(categoryId));
}
}
good.setCategoryIds(goodCategoryIds);
categoryIds.addAll(goodCategoryIds);
});
List<GoodsCategory> categories = goodsCategoryMapper.selectGoodsCategoryByIds(categoryIds);
Map<Long, String> categoryMap = categories.stream().collect(Collectors.toMap(GoodsCategory::getId, GoodsCategory::getName));
......@@ -131,11 +133,12 @@ public class GoodsServiceImpl implements IGoodsService
*/
@Override
@Transactional
public int insertGoods(Goods goods)
{
if(goods.getDiscount().compareTo(goods.getPrice())>0){
throw new ServiceException("折扣价不能大于原价");
public int insertGoods(Goods goods) {
if (goods.getDiscount().compareTo(goods.getPrice()) > 0) {
throw new ServiceException("折扣价不能大于原价");
}
Assert.notEmpty(goods.getCategoryIds(), "商品分类还未传递");
goods.setCategory(transferCategoryId(goods.getCategoryIds()));
goods.setCode(GenerateCode.getCode("G"));
goods.setCreatedAt(new Date());
goods.setUpdatedAt(new Date());
......@@ -146,28 +149,33 @@ public class GoodsServiceImpl implements IGoodsService
return 1;
}
private String transferCategoryId(List<Long> categoryIds) {
String categoryIdStr = categoryIds.stream().map(String::valueOf).collect(Collectors.joining(","));
return StringPool.COMMA + categoryIdStr + StringPool.COMMA;
}
private void insertgoodsExt(Goods goods) {
String specString = goods.getSpec();
long goodsId = goods.getId();
if(StringUtils.isNotEmpty(specString)){
if (StringUtils.isNotEmpty(specString)) {
List<Spec> specs = JSONArray.parseArray(specString, Spec.class);
List<RuleNode> ruleNodes = new ArrayList<>();
List<RuleNode> ruleNodeList = new ArrayList<>();
for(int i =0;i<specs.size();i++){
for (int i = 0; i < specs.size(); i++) {
Spec spec = specs.get(i);
List<SpecRule> specRules = spec.getSpecRules();
if(specRules!=null &&!specRules.isEmpty()){
if(ruleNodes.isEmpty()){
if (specRules != null && !specRules.isEmpty()) {
if (ruleNodes.isEmpty()) {
for (SpecRule specRule : specRules) {
RuleNode<SpecRule> ruleNode = new RuleNode<>();
ruleNode.setRuleNode(specRule);
ruleNodes.add(ruleNode);
ruleNodeList.add(ruleNode);
}
}else{
} else {
ruleNodeList.clear();
for (RuleNode<SpecRule> ruleNode : ruleNodes) {
putRuleNodeChild(ruleNode,specRules,ruleNodeList);
putRuleNodeChild(ruleNode, specRules, ruleNodeList);
}
}
}
......@@ -255,6 +263,9 @@ public class GoodsServiceImpl implements IGoodsService
*/
@Override
public int updateGoods(Goods goods) {
if (!CollectionUtils.isEmpty(goods.getCategoryIds())) {
goods.setCategory(this.transferCategoryId(goods.getCategoryIds()));
}
Goods goodsOri = goodsMapper.selectGoodsById(goods.getId());
int i = goodsMapper.updateGoods(goods);
if (StringUtils.isEmpty(goods.getSpec()) || Objects.equals(goodsOri.getSpec(), goods.getSpec())) {
......@@ -395,9 +406,27 @@ public class GoodsServiceImpl implements IGoodsService
}
@Data
class RuleNode<T>{
class RuleNode<T> {
private RuleNode parentRuleNode;
private T ruleNode;
private List<RuleNode> childNode;
}
@Override
public void resolverGoodsOfOrder(Order order) {
if (order == null) {
return;
}
List<OrderDetail> orderDetails = order.getOrderDetails();
if (CollectionUtils.isEmpty(orderDetails)) {
return;
}
List<Long> goodsIds = orderDetails.stream().map(OrderDetail::getGoodsId).collect(Collectors.toList());
List<Goods> goods = this.selectGoodsByIds(goodsIds);
orderDetails.forEach(orderDetail -> goods.forEach(good -> {
if (Objects.equals(orderDetail.getGoodsId(), good.getId())) {
orderDetail.setGoods(good);
}
}));
}
}
......@@ -144,12 +144,10 @@ public class MachineApiServiceImpl {
order1.setUpdatedAt(new Date());
if(OrderStatusConstant.completed.equals(status)){
order1.setFinishTime(new Date());
}
int i = orderService.updateOrder(order1);
return i+"";
}
public void testOrder(Long orderId) {
......@@ -276,13 +274,11 @@ public class MachineApiServiceImpl {
}
public void updateOrder(Order order) {
JSONObject param = new JSONObject();
JSONObject data = new JSONObject();
data.put("state",Integer.parseInt(order.getState()));
if("2".equals(order.getState())){
data.put("payTime",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",order.getPayTime()));
if (Objects.equals(OrderStatusConstant.Paid, order.getState())) {
data.put("payTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", order.getPayTime()));
}
param.put("data",data.toJSONString());
param.put("orderId",order.getId());
......
package com.soss.system.service.impl;
import com.soss.common.enums.MachineState;
import com.soss.common.enums.ShopState;
import com.soss.common.exception.ServiceException;
import com.soss.system.domain.Machine;
......@@ -116,6 +117,7 @@ public class MachineServiceImpl implements IMachineService {
}
machine1.setShopId(shopId);
Date curTime = new Date();
machine1.setState(MachineState.TO_BE_TEST.getState());
machine1.setBindTime(curTime);
machine1.setUpdatedAt(curTime);
machineMapper.updateMachine(machine1);
......
......@@ -10,8 +10,8 @@ import com.soss.system.domain.Order;
import com.soss.system.domain.OrderDetail;
import com.soss.system.domain.OrderRefund;
import com.soss.system.domain.vo.OrderQuery;
import com.soss.system.mapper.GoodsMapper;
import com.soss.system.mapper.OrderDetailMapper;
import com.soss.system.mapper.OrderMapper;
import com.soss.system.mapper.OrderRefundMapper;
import com.soss.system.service.IOrderRefundService;
import io.jsonwebtoken.lang.Assert;
......@@ -44,7 +44,7 @@ public class OrderRefundServiceImpl implements IOrderRefundService {
@Autowired
private OrderDetailMapper orderDetailMapper;
@Autowired
private GoodsMapper goodsMapper;
private OrderMapper orderMapper;
/**
* 查询订单退款
......@@ -169,13 +169,19 @@ public class OrderRefundServiceImpl implements IOrderRefundService {
/**
* 修改订单退款
*
*
* @param orderRefund 订单退款
* @return 结果
*/
@Override
public int updateOrderRefund(OrderRefund orderRefund)
{
@Transactional
public int updateOrderRefund(OrderRefund orderRefund) {
if (Objects.equals(orderRefund.getState(), RefundState.FAILURE.getState())) {
Order order = new Order();
order.setId(orderRefund.getOrderId());
order.setState(OrderStatusConstant.refundFailed);
orderMapper.updateOrder(order);
}
return orderRefundMapper.updateOrderRefund(orderRefund);
}
......
......@@ -19,6 +19,7 @@ import com.soss.system.domain.vo.orderTaking.SkuVo;
import com.soss.system.jiguang.impl.JiGuangPushServiceImpl;
import com.soss.system.mapper.*;
import com.soss.system.service.IOrderService;
import com.soss.system.utils.DistanceUtil;
import com.soss.system.utils.SendSmsUtil;
import com.soss.system.weixin.util.SendMessageUtils;
import org.apache.commons.lang3.BooleanUtils;
......@@ -32,6 +33,7 @@ import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
......@@ -71,8 +73,6 @@ public class OrderServiceImpl implements IOrderService {
@Autowired
private OrderTakingServiceImpl orderTakingService;
@Autowired
private CustomerMapper customerMapper;
@Autowired
private SysConfigServiceImpl sysConfigService;
@Autowired
......@@ -111,11 +111,7 @@ public class OrderServiceImpl implements IOrderService {
*/
@Override
public List<Order> selectOrderList(OrderQuery order) {
List<Order> orders = orderMapper.selectOrderByQuery(order);
for (Order order1 : orders) {
order1.setShop(shopMapper.selectShopById(order1.getShopId()));
}
return orders;
return orderMapper.selectOrderByQuery(order);
}
public List<Order> selectOrderList(Order order) {
......@@ -135,11 +131,6 @@ public class OrderServiceImpl implements IOrderService {
@Override
@Transactional
public AjaxResult insertOrder(LoginUser loginUser, Order order, Integer couponUserId) {
if (couponUserId != null) {
CouponUser couponUser = new CouponUser(couponUserId, CouponUserState.USED.getState());
couponUserMapper.updateCouponUser(couponUser);
}
if (order.getPaidAmount().compareTo(BigDecimal.ZERO) == 0) {
order.setState(OrderStatusConstant.Paid);
} else {
......@@ -169,32 +160,28 @@ public class OrderServiceImpl implements IOrderService {
}
}
orderMapper.insertOrder(order);
List<OrderDetail> orderDetails = order.getOrderDetails();
if (orderDetails != null && !orderDetails.isEmpty()) {
// BigDecimal bigDecimal = new BigDecimal(0);
// for (OrderDetail orderDetail : orderDetails) {
// bigDecimal = bigDecimal.add(orderDetail.getRealAmount().multiply( new BigDecimal(orderDetail.getNum())));
// }
// if(order.getAmount().compareTo(bigDecimal)!=0){
// throw new ServiceException("价格计算出现了问题,请重新计算"+ bigDecimal.stripTrailingZeros().toString() );
// }
// order.setAmount(bigDecimal);
int i = orderMapper.insertOrder(order);
for (OrderDetail orderDetail : orderDetails) {
orderDetail.setOrderId(order.getId());
orderDetail.setCreatedAt(new Date());
orderDetail.setUpdatedAt(new Date());
orderDetail.setMachineId(machineId);
orderDetailMapper.insertOrderDetail(orderDetail);
}
for (OrderDetail orderDetail : orderDetails) {
orderDetail.setOrderId(order.getId());
orderDetail.setCreatedAt(new Date());
orderDetail.setUpdatedAt(new Date());
orderDetail.setMachineId(machineId);
orderDetailMapper.insertOrderDetail(orderDetail);
}
//发送数据给机器
// 更新用户的优惠券状态
if (couponUserId != null) {
CouponUser couponUser = new CouponUser(couponUserId, order.getId(), order.getOrderNo(), CouponUserState.USED.getState());
couponUserMapper.updateCouponUser(couponUser);
}
// }
//发送数据给机器
machineApiService.createOrder(order);
orderOperationLogService.insertOrderOperationLog(order);
orderSnapshotService.saveOrderSnapshot(order);
return AjaxResult.success(order.getOrderNo());
}
@Override
......@@ -215,7 +202,7 @@ public class OrderServiceImpl implements IOrderService {
throw new ServiceException("当前时间本店休息中,暂停点单~");
}
if (shop.getDistanceLimit() != null && shop.getDistanceLimit() > 0) {
double distance = AppServiceImpl.getRealDistance(order.getLng().doubleValue(), order.getLat().doubleValue(), Double.parseDouble(shop.getLng()), Double.parseDouble(shop.getLat()));
double distance = DistanceUtil.getRealDistance(order.getLng().doubleValue(), order.getLat().doubleValue(), Double.parseDouble(shop.getLng()), Double.parseDouble(shop.getLat()));
if (distance > shop.getDistanceLimit() * 1000) {
throw new ServiceException("超过店铺下单的距离范围");
}
......@@ -266,6 +253,9 @@ public class OrderServiceImpl implements IOrderService {
private void timeoutState(Order order) {
jiGuangPushService.pushOrderState(order);
if (BooleanUtils.isTrue(order.getSendMsgFlag2())) {
sendMessageUtils.sendWxMsg(order);
}
}
/**
......@@ -423,13 +413,30 @@ public class OrderServiceImpl implements IOrderService {
@Override
public List<Order> getMyOrder(String openId) {
List<Order> orders = orderMapper.selectByUserId(openId);
return orderMapper.selectByUserId(openId);
}
@Override
public void wrapperOrder(List<Order> orders, boolean snapshotFlag) {
if (CollectionUtils.isEmpty(orders)) {
return;
}
List<Long> shopIds = orders.stream().map(Order::getShopId).distinct().collect(Collectors.toList());
List<Shop> shops = shopMapper.selectShopByIds(shopIds);
Map<Long, Shop> shopMap = shops.stream().collect(Collectors.toMap(Shop::getId, Function.identity()));
Map<Long, String> snapshotMap = null;
if (snapshotFlag) {
List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
List<OrderSnapshot> snapshots = orderSnapshotService.selectOrderSnapshotByOrderIds(orderIds);
snapshotMap = snapshots.stream().collect(Collectors.toMap(OrderSnapshot::getOrderId, OrderSnapshot::getSnapshot));
}
for (Order order : orders) {
order.setShop(shopMapper.selectShopById(order.getShopId()));
OrderSnapshot orderSnapshot = orderSnapshotService.selectOrderSnapshotByOrderId(order.getId());
order.setOrderDetails(JSONArray.parseArray(orderSnapshot.getSnapshot(), OrderDetail.class));
order.setShop(shopMap.get(order.getShopId()));
if (snapshotFlag) {
order.setOrderDetails(JSONArray.parseArray(snapshotMap.get(order.getId()), OrderDetail.class));
}
}
return orders;
}
@Override
......@@ -627,9 +634,9 @@ public class OrderServiceImpl implements IOrderService {
}
public List<GoodsVo> getNextOrder(String orderId, String shopId) {
public List<GoodsVo> getNextOrder(Long orderId, Long shopId) {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setOrderId(Long.parseLong(orderId));
orderDetail.setOrderId(orderId);
List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailList(orderDetail);
List<Long> skuIds = orderDetails.stream().map(OrderDetail::getSkuId).collect(Collectors.toList());
OrderTakingVo infoByShop = orderTakingService.getInfoByShop(shopId);
......@@ -650,7 +657,7 @@ public class OrderServiceImpl implements IOrderService {
continue;
}
for (SkuVo skus : good.getSkus()) {
if (skuIds.contains(Long.parseLong(skus.getSkuId()))) {
if (skuIds.contains(skus.getSkuId())) {
skuVoList.add(skus);
}
}
......
package com.soss.system.service.impl;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.soss.system.domain.Order;
import com.soss.system.domain.OrderDetail;
import com.soss.system.domain.OrderSnapshot;
import com.soss.system.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.soss.system.mapper.OrderSnapshotMapper;
import com.soss.system.domain.OrderSnapshot;
import com.soss.system.service.IOrderSnapshotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 订单快照Service业务层处理
......@@ -28,25 +28,28 @@ public class OrderSnapshotServiceImpl implements IOrderSnapshotService
/**
* 查询订单快照
*
*
* @param orderId 订单快照主键
* @return 订单快照
*/
@Override
public OrderSnapshot selectOrderSnapshotByOrderId(Long orderId)
{
public OrderSnapshot selectOrderSnapshotByOrderId(Long orderId) {
return orderSnapshotMapper.selectOrderSnapshotByOrderId(orderId);
}
@Override
public List<OrderSnapshot> selectOrderSnapshotByOrderIds(List<Long> orderIds) {
return orderSnapshotMapper.selectOrderSnapshotByOrderIds(orderIds);
}
/**
* 查询订单快照列表
*
*
* @param orderSnapshot 订单快照
* @return 订单快照
*/
@Override
public List<OrderSnapshot> selectOrderSnapshotList(OrderSnapshot orderSnapshot)
{
public List<OrderSnapshot> selectOrderSnapshotList(OrderSnapshot orderSnapshot) {
return orderSnapshotMapper.selectOrderSnapshotList(orderSnapshot);
}
......
......@@ -45,8 +45,8 @@ public class OrderTakingServiceImpl {
*/
public OrderTakingVo getMachineInfo(String machineCode) {
Machine machine = machineMapper.selectMachineByCode(machineCode);
if(machine==null || machine.getShopId() ==null){
Machine machine = machineMapper.selectMachineByCode(machineCode);
if (machine == null || machine.getShopId() == null) {
throw new ServiceException("该机器没有绑定店铺");
}
return this.getOrderTakingInfo(machine.getShopId());
......@@ -54,12 +54,12 @@ public class OrderTakingServiceImpl {
}
public OrderTakingVo getInfoByShop(String shopId) {
return this.getOrderTakingInfo(Long.parseLong(shopId));
public OrderTakingVo getInfoByShop(Long shopId) {
return this.getOrderTakingInfo(shopId);
}
public OrderTakingVo getOrderTakingInfo(Long shopId){
public OrderTakingVo getOrderTakingInfo(Long shopId) {
OrderTakingVo orderTakingVo = new OrderTakingVo();
Shop shop = shopMapper.selectShopById(shopId);
if (shop == null) {
......@@ -139,6 +139,7 @@ public class OrderTakingServiceImpl {
if (CollectionUtils.isEmpty(categoryIdStrList)) {
return orderTakingVo;
}
List<Long> categoryIds = new ArrayList<>(16);
categoryIdStrList.forEach(categoryIdStr -> {
List<Long> categoryIdsUnit = Arrays.stream(categoryIdStr.split(StringPool.COMMA)).filter(StringUtils::isNotEmpty).map(Long::parseLong).collect(Collectors.toList());
......
......@@ -70,7 +70,11 @@ public class ShopServiceImpl implements IShopService
@Override
public Shop selectShopById(Long id)
{
return shopMapper.selectShopById(id);
Shop shop = shopMapper.selectShopById(id);
if (shop.getDistanceLimit() != null && shop.getDistanceLimit().equals(0.0)) {
shop.setDistanceLimit(null);
}
return shop;
}
/**
......@@ -89,7 +93,9 @@ public class ShopServiceImpl implements IShopService
shop1.setMachineCount(machineMapper.selectMachineList(machine).size());
shop1.setSalesAmount(orderMapper.selectSalesAmount(shop1.getId()));
shop1.setSalesVolume(orderMapper.selectSalesVolume(shop1.getId(), null));
if (shop1.getDistanceLimit() != null && shop1.getDistanceLimit().equals(0.0)) {
shop1.setDistanceLimit(null);
}
//shop1.setMachieStatus(machineMapper.selectMachineList(machine).get(0).getState());
}
......@@ -120,6 +126,10 @@ public class ShopServiceImpl implements IShopService
}
Shop shop = new Shop(shopId, ShopState.CLOSE.getState());
shopMapper.updateShop(shop);
machines.forEach(machine -> {
machine.setState(MachineState.RUNNING.getState());
machineMapper.updateMachine(machine);
});
}
@Override
......@@ -150,16 +160,18 @@ public class ShopServiceImpl implements IShopService
/**
* 修改店铺
*
*
* @param shop 店铺
* @return 结果
*/
@Override
public int updateShop(Shop shop)
{
public int updateShop(Shop shop) {
shop.setUpdatedAt(new Date());
if(1 == shop.getIsDefault()){
/*if(1 == shop.getIsDefault()){
shopMapper.updateNoDefault();
}*/
if (shop.getDistanceLimit() == null) {
shop.setDistanceLimit(0.0);
}
return shopMapper.updateShop(shop);
}
......@@ -259,6 +271,7 @@ public class ShopServiceImpl implements IShopService
for (ShopGoodsSku goodsSkus : shopGoodsSkus) {
if ("2".equals(goodsSkus.getState())) {
boo = false;
break;
}
}
if (!boo) {
......@@ -401,43 +414,40 @@ public class ShopServiceImpl implements IShopService
}
public AjaxResult checkSku(String shopId, String skuId, String machineCode) {
public AjaxResult checkSku(Long shopId, Long skuId, String machineCode) {
ShopGoodsSku shopGoodsSku = new ShopGoodsSku();
shopGoodsSku.setSkuId(Long.parseLong(skuId));
if(StringUtils.isNotEmpty(shopId)){
shopGoodsSku.setShopId(Long.parseLong(shopId));
shopGoodsSku.setSkuId(skuId);
if (shopId != null) {
shopGoodsSku.setShopId(shopId);
}
if(StringUtils.isNotEmpty(machineCode)){
if (StringUtils.isNotEmpty(machineCode)) {
Machine machine = new Machine();
machine.setCode(machineCode);
List<Machine> machines = machineMapper.selectMachineList(machine);
if(machines ==null){
if (machines == null) {
return AjaxResult.error("机器不存在");
}
Machine machine1 = machines.get(0);
if(machine1.getShopId() ==null){
if (machine1.getShopId() == null) {
return AjaxResult.error("该机器暂未绑定店铺");
}
shopGoodsSku.setShopId(machine1.getShopId());
}
shopGoodsSku.setIsDeleted("0");
List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuMapper.selectShopGoodsSkuList(shopGoodsSku);
if(shopGoodsSkus ==null ||shopGoodsSkus.isEmpty()){
if (shopGoodsSkus == null || shopGoodsSkus.isEmpty()) {
return AjaxResult.error("该产品已经不存在");
}else{
ShopGoodsSku shopGoodsSku1 = shopGoodsSkus.get(0);
JSONObject jsonObject = new JSONObject();
jsonObject.put("state",shopGoodsSku1.getState());
Goods goods = goodsMapper.selectGoodsById(shopGoodsSku1.getGoodsId());
jsonObject.put("goods",getGoodsVo(goods,shopGoodsSku1.getShopId()));
return AjaxResult.success(jsonObject);
}
ShopGoodsSku shopGoodsSku1 = shopGoodsSkus.get(0);
JSONObject jsonObject = new JSONObject();
jsonObject.put("state", shopGoodsSku1.getState());
Goods goods = goodsMapper.selectGoodsById(shopGoodsSku1.getGoodsId());
jsonObject.put("goods", getGoodsVo(goods, shopGoodsSku1.getShopId(), skuId));
return AjaxResult.success(jsonObject);
}
public GoodsVo getGoodsVo(Goods good,Long shopId){
GoodsVo goodsVo =new GoodsVo();
public GoodsVo getGoodsVo(Goods good, Long shopId, Long skuId) {
GoodsVo goodsVo = new GoodsVo();
goodsVo.setGoodsId(String.valueOf(good.getId()));
goodsVo.setName(good.getName());
goodsVo.setDesc(good.getDesc());
......@@ -456,7 +466,7 @@ public class ShopServiceImpl implements IShopService
goodsVo.setTags(tags);
//获取产品信息
List<SkuVo> skuVos = shopGoodsSkuMapper.selectSkuByGoodAndShop(shopId, goodsVo.getGoodsId());
buildSkuRules(skuVos);
buildSkuRules(skuVos, skuId);
goodsVo.setSkus(skuVos);
return goodsVo;
}
......@@ -485,14 +495,18 @@ public class ShopServiceImpl implements IShopService
return JSONArray.parseArray(JSONObject.toJSONString(specVos));
}
private void buildSkuRules(List<SkuVo> skuVos) {
if(CollectionUtils.isEmpty(skuVos)){
private void buildSkuRules(List<SkuVo> skuVos, Long skuId) {
if (CollectionUtils.isEmpty(skuVos)) {
return;
}
for (SkuVo skuVo : skuVos) {
if (Objects.equals(skuId, skuVo.getSkuId()) && !Objects.equals(skuVo.getIsDelete(), SkuDeleteState.NORMAL.getState())) {
throw new ServiceException("规格已下架");
}
String rules = skuVo.getRulesString();
List<SpecRule> specRuleList = JSONObject.parseArray(rules, SpecRule.class);
boolean boo =true;
boolean boo = true;
List<SkuRuleVo> skuRuleVos = new ArrayList<>();
for (SpecRule specRule : specRuleList) {
SkuRuleVo skuRuleVo = new SkuRuleVo();
......@@ -501,8 +515,8 @@ public class ShopServiceImpl implements IShopService
skuRuleVo.setRuleId(String.valueOf(specRule.getId()));
skuRuleVo.setSpecId(String.valueOf(specRule.getSpecId()));
skuRuleVo.setRuleName(specRule.getName());
if(0L == specRule.getIsDefault()){
boo =false;
if (0L == specRule.getIsDefault()) {
boo = false;
}
}
skuVo.setIsDefault("0");
......
package com.soss.system.utils;
import java.text.DecimalFormat;
/**
* 经纬度计算距离工具类
*/
public class DistanceUtil {
private static final double EARTH_RADIUS = 6378137;
public static String getDistanceDesc(Double realDistance) {
if (realDistance == null) {
return "-1";
}
if (realDistance.equals(Double.MAX_VALUE)) {
return "-1";
}
if (realDistance > 1000 && realDistance < 10000) {
DecimalFormat df = new DecimalFormat("######0.0");
return df.format(realDistance / 1000) + "km";
} else if (realDistance >= 10000) {
Double aDouble = realDistance / 1000;
return aDouble.intValue() + "km";
}
return realDistance.intValue() + "m";
}
public static String getDistanceDesc(double lng1, double lat1, double lng2, double lat2) {
double s = getRealDistance(lng1, lat1, lng2, lat2);
return getDistanceDesc(s);
}
/**
* 根据两点间经纬度坐标(double值),计算两点间距离,单位为米
*/
public static double getRealDistance(double lng1, double lat1, double lng2, double lat2) {
double radLat1 = Math.toRadians(lat1);
double radLat2 = Math.toRadians(lat2);
double a = radLat1 - radLat2;
double b = Math.toRadians(lng1) - Math.toRadians(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s *= EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
}
}
......@@ -2,7 +2,6 @@ package com.soss.system.weixin.util;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.soss.common.utils.DateUtils;
......@@ -11,12 +10,11 @@ import com.soss.system.domain.Shop;
import com.soss.system.mapper.ShopMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.aspectj.weaver.ast.Or;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -27,8 +25,6 @@ import java.util.Map;
public class SendMessageUtils {
@Autowired
private WxMaService wxMaService;
@Value("${weixin.templateId}")
private String templateId;
@Value("${weixin.pagePath}")
private String pagePath;
@Value("${weixin.program}")
......@@ -36,140 +32,107 @@ public class SendMessageUtils {
@Autowired
private ShopMapper shopMapper;
private String templateInfo="[{" +
"\"status\": \"2\"," +
"\"templateId\": \"1uErx-15S-3vuopXSvvsxCeM_Jd-1iZC-nXzd2yW3QU\"," +
"\"param\": {" +
"\"character_string1\": \"$.orderNum\"," +
"\"thing2\": \"$.shop.name\"," +
"\"thing12\": \"$.shop.address\"," +
"\"time7\": \"now\"," +
"\"thing6\": \"您的订单已经下单成功了~\"" +
"}" +
"}, {" +
"\"status\": \"3\"," +
"\"templateId\": \"Q4HDwBEvpTXpwtZktqWm4SZOTEuQK1x48xjqjD2GqyM\"," +
"\"param\": {" +
"\"thing1\": \"$.shop.name\"," +
"\"date6\": \"now\"," +
"\"thing5\": \"订单已经开始制作,即将可以享用美食!\"" +
"}" +
"}, {" +
"\"status\": \"4\"," +
"\"templateId\": \"Fu_CPIXa0cnJ4EDdVKqFQ3qqKJccMqt2oorI5mfNq74\"," +
"\"param\": {" +
"\"character_string4\": \"$.orderNum\"," +
"\"thing2\": \"$.shop.name\"," +
"\"thing7\": \"$.shop.address\"," +
"\"time6\": \"now\"," +
"\"thing11\": \"您的订单制作完成了,现在可以去取餐啦!\"" +
"}" +
"},{" +
"\"status\": \"6\"," +
"\"templateId\": \"Oq_zfRWRXijvXenRmfD2PARgpvdYlbkjR4laxKmBqb0\"," +
"\"param\": {" +
"\"character_string10.DATA\": \"$.orderNum\"," +
"\"thing1.DATA\": \"$.shop.name\"," +
"\"date7.DATA\": \"now\"," +
"\"thing11\": \"您的订单制作完成了,现在可以去取餐啦!\"" +
"}" +
"}]";
/**
* 设置会议订阅消息
*
* @param
* @return 订阅会议消息
*/
private List<WxMaSubscribeMessage.MsgData> setMeetingMsg (Order order) {
Shop shop = shopMapper.selectShopById(order.getShopId());
List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
//这里要完全按照订阅消息模板详情去设置,thing1 ,thing2...不能变
WxMaSubscribeMessage.MsgData data1 = new WxMaSubscribeMessage.MsgData();
data1.setName("character_string1");
data1.setValue(order.getOrderNo());
dataList.add(data1);
WxMaSubscribeMessage.MsgData data2 = new WxMaSubscribeMessage.MsgData();
data2.setName("thing2");
data2.setValue(shop.getName());
dataList.add(data2);
WxMaSubscribeMessage.MsgData data3 = new WxMaSubscribeMessage.MsgData();
data3.setName("character_string4");
data3.setValue(order.getOrderNum());
dataList.add(data3);
WxMaSubscribeMessage.MsgData data4 = new WxMaSubscribeMessage.MsgData();
data4.setName("thing7");
data4.setValue(shop.getAddress());
dataList.add(data4);
return dataList;
}
private Map<Integer, JSONObject> templateMap;
/**
* 根据模板id发送消息
*
*/
public void sendWxMsg(Order order) {
@PostConstruct
public void init() {
templateMap = new HashMap<>();
JSONObject ordSuc = new JSONObject();
ordSuc.put("templateId", "1uErx-15S-3vuopXSvvsxCeM_Jd-1iZC-nXzd2yW3QU");
JSONObject ordSucParam = new JSONObject();
ordSucParam.put("character_string1", "$.orderNum");
ordSucParam.put("thing2", "$.shop.name");
ordSucParam.put("thing12", "$.shop.address");
ordSucParam.put("time7", "now");
ordSucParam.put("thing6", "您的订单已经下单成功了~");
ordSuc.put("param", ordSucParam);
templateMap.put(2, ordSuc);
//骚操作在这里
try {
Map<String, Object> tempalte = getTempalte(order);
if(tempalte ==null){
return;
}
JSONObject making = new JSONObject();
making.put("templateId", "Q4HDwBEvpTXpwtZktqWm4SZOTEuQK1x48xjqjD2GqyM");
JSONObject makingParam = new JSONObject();
makingParam.put("thing1", "$.shop.name");
makingParam.put("date6", "now");
makingParam.put("thing5", "订单已经开始制作,即将可以享用美食!");
making.put("param", makingParam);
templateMap.put(3, making);
WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder();
//发送人openid
builder.toUser(order.getUserId());
//发送的模板id
builder.templateId((String)tempalte.get("tempalte"));
//消息主体
builder.data((List<WxMaSubscribeMessage.MsgData>) tempalte.get("dataList"));
//点击订阅消息的跳转链接(默认是正式发布的小程序页面,当然也可以通过参数进行控制)
builder.page(pagePath+order.getId());
builder.miniprogramState(program);
WxMaSubscribeMessage msg = builder.build();
wxMaService.getMsgService().sendSubscribeMsg(msg);
} catch (WxErrorException e) {
log.error("会议通知发送失败,用户openId:{}, 错误码:{},错误信息:{}",
order.getUserId(), e.getError().getErrorCode(), e.getError().getErrorMsg());
//发送失败就发送短信
JSONObject untake = new JSONObject();
untake.put("templateId", "Fu_CPIXa0cnJ4EDdVKqFQ3qqKJccMqt2oorI5mfNq74");
JSONObject untakeParam = new JSONObject();
untakeParam.put("character_string4", "$.orderNum");
untakeParam.put("thing2", "$.shop.name");
untakeParam.put("thing7", "$.shop.address");
untakeParam.put("time6", "now");
untakeParam.put("thing11", "您的订单制作完成了,现在可以去取餐啦!");
untake.put("param", untakeParam);
templateMap.put(4, untake);
}
JSONObject complete = new JSONObject();
complete.put("templateId", "Oq_zfRWRXijvXenRmfD2PARgpvdYlbkjR4laxKmBqb0");
JSONObject completeParam = new JSONObject();
completeParam.put("character_string10.DATA", "$.orderNum");
completeParam.put("thing1.DATA", "$.shop.name");
completeParam.put("date7.DATA", "now");
completeParam.put("thing11", "您的订单制作完成了,现在可以去取餐啦!");
complete.put("param", completeParam);
templateMap.put(6, complete);
JSONObject timeout = new JSONObject();
timeout.put("templateId", "Q4HDwBEvpTXpwtZktqWm4SZOTEuQK1x48xjqjD2GqyM");
JSONObject timeoutParam = new JSONObject();
timeoutParam.put("thing1", "$.shop.name");
timeoutParam.put("date6", "now");
timeoutParam.put("thing5", "取餐超时,已将出品废弃,请联系客服重做~");
timeout.put("param", timeoutParam);
templateMap.put(7, timeout);
}
public Map<String,Object> getTempalte(Order order){
JSONArray jsonArray = JSONArray.parseArray(templateInfo);
/**
* 根据模板id发送消息
*/
public void sendWxMsg(Order order) {
Integer orderState = Integer.parseInt(order.getState());
JSONObject orderTemplate = templateMap.get(orderState);
if (orderTemplate == null) {
return;
}
Shop shop = shopMapper.selectShopById(order.getShopId());
order.setShop(shop);
String orderState = order.getState();
Map<String,Object> result = null;
for(int i =0 ;i<jsonArray.size();i++){
JSONObject tempalte = jsonArray.getJSONObject(i);
if(orderState.equals(tempalte.getString("status"))){
List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
result = new HashMap();
result.put("tempalte",tempalte.getString("templateId"));
result.put("dataList",dataList);
JSONObject params = tempalte.getJSONObject("param");
params.forEach((key,value)->{
WxMaSubscribeMessage.MsgData data = new WxMaSubscribeMessage.MsgData();
dataList.add(data);
String valueString = (String) value;
data.setName(key);
if("now".equals(valueString)){
valueString = DateUtils.getTime();
}else if(valueString.startsWith("$")){
valueString = (String) JSONPath.eval(order,valueString);
}
data.setValue(valueString);
});
JSONObject params = orderTemplate.getJSONObject("param");
List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
params.forEach((key, value) -> {
WxMaSubscribeMessage.MsgData data = new WxMaSubscribeMessage.MsgData();
dataList.add(data);
String valueString = (String) value;
data.setName(key);
if ("now".equals(valueString)) {
valueString = DateUtils.getTime();
} else if (valueString.startsWith("$")) {
valueString = (String) JSONPath.eval(order, valueString);
}
data.setValue(valueString);
});
WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder();
//发送人openid
builder.toUser(order.getUserId());
//发送的模板id
builder.templateId(orderTemplate.getString("templateId"));
//消息主体
builder.data(dataList);
//点击订阅消息的跳转链接(默认是正式发布的小程序页面,当然也可以通过参数进行控制)
builder.page(pagePath + order.getId());
builder.miniprogramState(program);
WxMaSubscribeMessage msg = builder.build();
try {
wxMaService.getMsgService().sendSubscribeMsg(msg);
} catch (WxErrorException e) {
log.error("订阅消息发送失败,用户openId:{}, 错误码:{},错误信息:{}",
order.getUserId(), e.getError().getErrorCode(), e.getError().getErrorMsg());
//发送失败就发送短信
}
return result;
}
}
......@@ -84,8 +84,9 @@
select c.id, c.name
from coupon_rule cr
left join coupon c on c.rule_id = cr.id
where cr.use_start_time &lt; now() and cr.use_end_time > now()
where cr.use_end_time > now()
and c.state = ${@com.soss.common.enums.CouponState @ONLINE.getState}
and (cr.receivable_time is null or cr.receivable_time &lt; now())
</select>
<update id="expireCoupon">
......
......@@ -102,12 +102,12 @@
<trim prefix="set" suffixOverrides=",">
<if test="name != null and name != ''">name = #{name},</if>
<if test="desc != null and desc != ''">`desc` = #{desc},</if>
<if test="categoryIds != null and categoryIds != ''">category_ids = #{categoryIds},</if>
<if test="goodsIds != null and goodsIds != ''">goods_ids = #{goodsIds},</if>
<if test="province != null and province != ''">province = #{province},</if>
<if test="city != null and city != ''">city = #{city},</if>
<if test="area != null and area != ''">area = #{area},</if>
<if test="shopIds != null and shopIds != ''">shop_ids = #{shopIds},</if>
<if test="categoryIds != null">category_ids = #{categoryIds},</if>
<if test="goodsIds != null">goods_ids = #{goodsIds},</if>
<if test="province != null">province = #{province},</if>
<if test="city != null">city = #{city},</if>
<if test="area != null">area = #{area},</if>
<if test="shopIds != null">shop_ids = #{shopIds},</if>
<if test="receivableTime != null">receivable_time = #{receivableTime},</if>
<if test="useStartTime != null">use_start_time = #{useStartTime},</if>
<if test="useEndTime != null">use_end_time = #{useEndTime},</if>
......
......@@ -8,6 +8,7 @@
<result column="cust_name" property="custName"/>
<result column="cust_phone" property="custPhone"/>
<result column="order_id" property="orderId"/>
<result column="order_no" property="orderNo"/>
<result column="coupon_id" property="couponId"/>
<result column="receive_time" property="receiveTime"/>
<result column="active_time" property="activeTime"/>
......@@ -41,10 +42,12 @@
<choose>
<when test="effectiveFlag != null and effectiveFlag">
and cu.state = ${@com.soss.common.enums.CouponUserState @EFFECTIVE.getState}
order by cu.expired_time
</when>
<otherwise>
and cu.state in (${@com.soss.common.enums.CouponUserState @USED.getState},
${@com.soss.common.enums.CouponUserState @EXPIRED.getState})
order by cu.updated_at desc, cu.receive_time
</otherwise>
</choose>
</select>
......@@ -67,7 +70,7 @@
left join coupon c on cu.coupon_id = c.id
left join coupon_category cc on c.category_id = cc.id
left join coupon_rule cr on c.rule_id = cr.id
where cu.cust_id = #{custId} and cr.use_start_time &lt; #{nowTime} and cu.expired_time > #{nowTime}
where cu.cust_id = #{custId} and cu.expired_time > #{nowTime}
and cu.state = ${@com.soss.common.enums.CouponUserState @EFFECTIVE.getState}
<if test="couponUserId != null">
and cu.id = #{couponUserId}
......@@ -107,6 +110,7 @@
<if test="custName != null and custName != ''">cust_name,</if>
<if test="custPhone != null and custPhone != ''">cust_phone,</if>
<if test="orderId != null">order_id,</if>
<if test="orderNo != null">order_no,</if>
<if test="couponId != null">coupon_id,</if>
<if test="receiveTime != null">receive_time,</if>
<if test="activeTime != null">active_time,</if>
......@@ -123,6 +127,7 @@
<if test="custName != null and custName != ''">#{custName},</if>
<if test="custPhone != null and custPhone != ''">#{custPhone},</if>
<if test="orderId != null">#{orderId},</if>
<if test="orderNo != null">#{orderNo},</if>
<if test="couponId != null">#{couponId},</if>
<if test="receiveTime != null">#{receiveTime},</if>
<if test="activeTime != null">#{activeTime},</if>
......@@ -143,6 +148,7 @@
<if test="custName != null and custName != ''">cust_name = #{custName},</if>
<if test="custPhone != null and custPhone != ''">cust_phone = #{custPhone},</if>
<if test="orderId != null">order_id = #{orderId},</if>
<if test="orderNo != null">order_no = #{orderNo},</if>
<if test="couponId != null">coupon_id = #{couponId},</if>
<if test="receiveTime != null">receive_time = #{receiveTime},</if>
<if test="activeTime != null">active_time = #{activeTime},</if>
......@@ -161,4 +167,11 @@
set state = ${@com.soss.common.enums.CouponUserState @EXPIRED.getState}
where expired_time &lt; now() and state = ${@com.soss.common.enums.CouponUserState @EFFECTIVE.getState}
</update>
<select id="getCustCouponCnt" resultType="java.lang.Long">
SELECT COUNT(*) from coupon_user where cust_id = #{custId} and coupon_id = #{couponId}
<if test="startTime != null">
and created_at >= #{startTime}
</if>
</select>
</mapper>
......@@ -9,7 +9,7 @@
<result property="userName" column="user_name"/>
<result property="phone" column="phone"/>
<result property="createTime" column="create_time"/>
<result property="headSculpturePath" column="head_sculpture_path"/>
<result property="avatarUrl" column="avatar_url"/>
<result property="sex" column="sex"/>
<result property="birthday" column="birthday"/>
<result property="soucre" column="soucre"/>
......@@ -29,7 +29,7 @@
<where>
<if test="userName != null and userName != ''"> and user_name like concat('%', #{userName}, '%')</if>
<if test="phone != null and phone != ''"> and phone = #{phone}</if>
<if test="headSculpturePath != null and headSculpturePath != ''"> and head_sculpture_path = #{headSculpturePath}</if>
<if test="avatarUrl != null and avatarUrl != ''"> and avatar_url = #{avatarUrl}</if>
<if test="soucre != null and soucre != ''"> and soucre = #{soucre}</if>
</where>
</select>
......@@ -46,7 +46,7 @@
<if test="userName != null">user_name,</if>
<if test="phone != null">phone,</if>
<if test="createTime != null">create_time,</if>
<if test="headSculpturePath != null">head_sculpture_path,</if>
<if test="avatarUrl != null">avatar_url,</if>
<if test="sex != null">sex,</if>
<if test="birthday != null">birthday,</if>
<if test="soucre != null">soucre,</if>
......@@ -61,7 +61,7 @@
<if test="userName != null">#{userName},</if>
<if test="phone != null">#{phone},</if>
<if test="createTime != null">#{createTime},</if>
<if test="headSculpturePath != null">#{headSculpturePath},</if>
<if test="avatarUrl != null">#{avatar_url},</if>
<if test="sex != null">#{sex},</if>
<if test="birthday != null">#{birthday},</if>
<if test="soucre != null">#{soucre},</if>
......@@ -78,11 +78,10 @@
<trim prefix="SET" suffixOverrides=",">
<if test="userName != null">user_name = #{userName},</if>
<if test="phone != null">phone = #{phone},</if>
<if test="headSculpturePath != null">head_sculpture_path = #{headSculpturePath},</if>
<if test="avatarUrl != null">avatar_url = #{avatarUrl},</if>
<if test="sex != null">sex = #{sex},</if>
<if test="birthday != null">birthday = #{birthday},</if>
<if test="soucre != null">soucre = #{soucre},</if>
<!--<if test="allow != null">allow = #{soucre},</if>-->
<if test="sendMsgFlag1 != null">send_msg_flag1 = #{sendMsgFlag1},</if>
<if test="sendMsgFlag2 != null">send_msg_flag2 = #{sendMsgFlag2},</if>
<if test="sendMsgFlag3 != null">send_msg_flag3 = #{sendMsgFlag3},</if>
......
......@@ -37,7 +37,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="selectGoodsCategoryByIds" resultMap="GoodsCategoryResult">
select id, name from goods_category where id in
select id, name, icon from goods_category where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach>
</select>
......@@ -101,10 +101,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectCategoryIdByShopId" resultType="java.lang.String">
select g.category
from
goods g ,
goods g,
shop_goods sg
where
g.id = sg.goods_id
g.id = sg.goods_id and g.is_deleted = 0
and g.state = ${@com.soss.common.enums.GoodsState @ONLINE.getState}
and sg.shop_id = #{shopId}
</select>
......
......@@ -131,7 +131,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</foreach>
</delete>
<select id="selectCount" resultType="integer">
select count(*) from goods where category=#{id}
select count(*) from goods where category like concat('%,', #{id}, ',%')
</select>
<select id="selectSpec" resultMap="GoodsResult">
<include refid="selectGoodsVo"/>
......
......@@ -20,7 +20,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</sql>
<select id="selectSkuListForOrder" resultMap="GoodsSkuResult">
select id, goods_id, price, discount from goods_sku where id in
select id, goods_id, price, discount, is_deleted from goods_sku where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach>
</select>
......
......@@ -15,22 +15,28 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectOrderSnapshotList" parameterType="OrderSnapshot" resultMap="OrderSnapshotResult">
<include refid="selectOrderSnapshotVo"/>
<where>
<if test="snapshot != null and snapshot != ''"> and snapshot = #{snapshot}</if>
<where>
<if test="snapshot != null and snapshot != ''">and snapshot = #{snapshot}</if>
</where>
</select>
<select id="selectOrderSnapshotByOrderId" resultMap="OrderSnapshotResult">
<select id="selectOrderSnapshotByOrderId" resultMap="OrderSnapshotResult">
<include refid="selectOrderSnapshotVo"/>
where order_id = #{orderId}
</select>
<select id="selectOrderSnapshotByOrderIds" resultMap="OrderSnapshotResult">
<include refid="selectOrderSnapshotVo"/>
where order_id in
<foreach collection="orderIds" item="orderId" separator="," open="(" close=")">#{orderId}</foreach>
</select>
<insert id="insertOrderSnapshot" parameterType="OrderSnapshot">
insert into order_snapshot
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="orderId != null">order_id,</if>
<if test="snapshot != null">snapshot,</if>
</trim>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="orderId != null">#{orderId},</if>
<if test="snapshot != null">#{snapshot},</if>
......
......@@ -25,7 +25,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectShopVo">
select id, name, code, lng, lat, remarks, start_time, end_time, address, province, city, zone, distance_limit, state, created_at, updated_at, is_default from shop
select * from shop
</sql>
<select id="selectAllShop" resultMap="ShopResult">
......@@ -64,7 +64,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="selectShopByIds" resultMap="ShopResult">
select id, name, zone from shop where id in
select * from shop where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">#{id}</foreach>
</select>
......
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