Authored by mali

Merge branch 'master' of http://git.yoho.cn/ufo/yohoufo-fore

Showing 23 changed files with 535 additions and 151 deletions
... ... @@ -14,19 +14,19 @@ public class AddressUtil {
* @param str
* @return
*/
public static String getDecryptStr(String str){
public static int getDecryptStr(String str){
String decryptStr = str;
try{
str = str.replace(' ','+');
decryptStr = AES.decrypt(DynamicPropertyFactory.getInstance().getStringProperty("password.aes.key", "yoho9646yoho9646").get(), str);
return Integer.parseInt(decryptStr);
}catch (Exception e){
logger.error("getDecryptStr failed. str is {}, e is {}", str, e);
}
logger.info("getDecryptStr, str is {}, decryptStr is {}", str, decryptStr);
return decryptStr;
return -1;
}
}
... ...
... ... @@ -11,7 +11,7 @@ import java.util.Objects;
* Created by chunhua.zhang@yoho.cn on 2015/12/15.
*/
public class BigDecimalHelper {
public static final String FORMAT_TWOBITAFTERPOINT = "###.00";
public static final String FORMAT_TWOBITAFTERPOINT = "##0.00";
private static Map<String,DecimalFormat> DecimalFormatCache = new HashMap<>();
... ...
... ... @@ -13,7 +13,7 @@ public interface BuyerOrderMapper {
BuyerOrder selectByPrimaryKey(Integer id);
BuyerOrder selectByOrderCode(@Param("orderCode") Long orderCode);
BuyerOrder selectByOrderCode(@Param("orderCode") Long orderCode, @Param("uid") int uid);
int updateByPrimaryKeySelective(BuyerOrder record);
... ...
... ... @@ -12,7 +12,7 @@ public interface SellerOrderMapper {
SellerOrder selectByPrimaryKey(Integer id);
SellerOrder selectByOrderCode(@Param("orderCode") long orderCode);
SellerOrder selectByOrderCode(@Param("orderCode") long orderCode, @Param("uid") int uid);
SellerOrder selectBySkup(@Param("skup") Integer skup);
... ...
... ... @@ -32,11 +32,12 @@
</select>
<select id="selectByOrderCode" parameterType="java.lang.Long" resultMap="BaseResultMap">
<select id="selectByOrderCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from buyer_order
where order_code = #{orderCode,jdbcType=BIGINT}
and uid = #{uid,jdbcType=INTEGER}
limit 1
</select>
... ...
... ... @@ -27,11 +27,12 @@
</select>
<select id="selectByOrderCode" parameterType="java.lang.Long" resultMap="BaseResultMap">
<select id="selectByOrderCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from seller_order
where order_code = #{orderCode,jdbcType=BIGINT}
and uid = #{uid,jdbcType=INTEGER}
limit 1
</select>
... ...
... ... @@ -8,5 +8,11 @@ public interface MetaKey {
String BACK_2_SELLER_DELIVERY_ADDRESS = "back_delivery_address";
/**
* 买家收货地址
*/
String BUYER_DELIVERY_ADDRESS = "delivery_address";
String SELLER_FEE = "fee";
}
... ...
... ... @@ -39,5 +39,7 @@ public interface OrderConstant {
*/
String ORDER_CODE_PRE = "3194";
String EMPTY_ADDRESS_CODE = "000000";
}
... ...
... ... @@ -5,17 +5,17 @@ import com.yohoufo.common.ApiResponse;
import com.yohoufo.order.request.ShoppingRequest;
import com.yohoufo.order.response.OrderSubmitResponse;
import com.yohoufo.order.response.ShoppingPaymentResponse;
import com.yohoufo.order.service.IShoppingService;
import com.yohoufo.order.service.IBuyerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/shopping")
public class ShoppingController {
public class BuyerOrderController {
@Autowired
IShoppingService shoppingService;
IBuyerOrderService buyerOrderService;
/**
... ... @@ -26,7 +26,7 @@ public class ShoppingController {
public ApiResponse payment(@RequestParam(name = "uid") int uid,
@RequestParam(name = "skup") int skup){
ShoppingPaymentResponse paymentResponse = shoppingService.payment(ShoppingRequest.builder().uid(uid).skup(skup).build());
ShoppingPaymentResponse paymentResponse = buyerOrderService.payment(ShoppingRequest.builder().uid(uid).skup(skup).build());
return new ApiResponse.ApiResponseBuilder().code(200).data(paymentResponse).message("结算成功").build();
}
... ... @@ -43,7 +43,7 @@ public class ShoppingController {
@RequestParam(name = "clientType") String clientType){
ShoppingRequest request = ShoppingRequest.builder().uid(uid).skup(skup).channelNo(channelNo).clientType(clientType).addressId(addressId).build();
OrderSubmitResponse paymentResponse = shoppingService.submit(request);
OrderSubmitResponse paymentResponse = buyerOrderService.submit(request);
return new ApiResponse.ApiResponseBuilder().code(200).data(paymentResponse).message("提交订单SUCCESS").build();
}
... ...
... ... @@ -12,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by chenchao on 2018/9/13.
... ... @@ -34,6 +35,7 @@ public class SellerOrderController {
* @throws GatewayException
*/
@RequestMapping(params = "method=ufo.sellerOrder.computePublishPrd")
@ResponseBody
public ApiResponse computePublishPrd(@RequestParam(name = "uid", required = true)int uid,
@RequestParam(name = "storage_id", required = true)int storage_id,
@RequestParam(name="price", required = true)String price) throws GatewayException {
... ... @@ -58,6 +60,7 @@ public class SellerOrderController {
* @throws GatewayException
*/
@RequestMapping(params = "method=ufo.sellerOrder.publishPrd")
@ResponseBody
public ApiResponse publishPrd(@RequestParam(name = "uid", required = true)int uid,
@RequestParam(name = "storage_id", required = true)int storage_id,
@RequestParam(name="price", required = true)String price,
... ...
package com.yohoufo.order.model.dto;
import com.yoho.service.model.response.UserAddressRspBO;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Builder;
... ... @@ -30,4 +31,11 @@ public class OrderBuilder {
* 运费
*/
BigDecimal shipFee;
/**
* 用户地址
*/
UserAddressRspBO addressInfo;
}
... ...
... ... @@ -5,7 +5,7 @@ import com.yohoufo.order.request.ShoppingRequest;
import com.yohoufo.order.response.OrderSubmitResponse;
import com.yohoufo.order.response.ShoppingPaymentResponse;
public interface IShoppingService {
public interface IBuyerOrderService {
/**
* 结算页数据
... ...
... ... @@ -256,10 +256,6 @@ public class SellerOrderService {
private String formatFee(BigDecimal fee){
return PriceFormater.addCnCurrencySymbol(BigDecimalHelper.formatNumber(fee, BigDecimalHelper.FORMAT_TWOBITAFTERPOINT));
}
... ...
package com.yohoufo.order.service.impl;
import com.yoho.core.rest.client.ServiceCaller;
import com.yoho.error.ServiceError;
import com.yoho.error.exception.ServiceException;
import com.yoho.service.model.request.UserAddressReqBO;
import com.yoho.service.model.response.UserAddressRspBO;
import com.yohoufo.common.utils.AddressUtil;
import com.yohoufo.dal.order.SellerOrderGoodsMapper;
import com.yohoufo.dal.order.model.SellerOrderGoods;
import com.yohoufo.order.common.OrderCodeType;
... ... @@ -11,20 +15,22 @@ import com.yohoufo.order.model.dto.OrderBuilder;
import com.yohoufo.order.request.ShoppingRequest;
import com.yohoufo.order.response.OrderSubmitResponse;
import com.yohoufo.order.response.ShoppingPaymentResponse;
import com.yohoufo.order.service.IBuyerOrderService;
import com.yohoufo.order.service.IOrdeCreationService;
import com.yohoufo.order.service.IShoppingService;
import com.yohoufo.order.service.support.ShoppingSupport;
import com.yohoufo.order.service.support.codegenerator.OrderCodeGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Arrays;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class ShoppingServiceImpl implements IShoppingService{
public class BuyerOrderServiceImpl implements IBuyerOrderService {
private final Logger logger = LoggerFactory.getLogger(getClass());
... ... @@ -40,9 +46,12 @@ public class ShoppingServiceImpl implements IShoppingService{
@Autowired
IOrdeCreationService ordeCreationService;
@Autowired
ServiceCaller serviceCaller;
/**
* 结算页数据
* @param shoppingRequest
* @param request
* @return
*/
public ShoppingPaymentResponse payment(ShoppingRequest request){
... ... @@ -53,20 +62,8 @@ public class ShoppingServiceImpl implements IShoppingService{
throw new ServiceException(ServiceError.ORDER_REQUEST_PARM_IS_EMPTY);
}
// skup是否是可售状态
SellerOrderGoods skupGood = sellerOrderGoodsMapper.selectByPrimaryKey(request.getSkup());
if (skupGood == null){
logger.warn("payment skup not exist, skup is {}", request.getSkup());
// TODO
throw new ServiceException(ServiceError.ORDER_REQUEST_ERROR);
}
// 不可售
if (skupGood.getStatus()!=null
&& skupGood.getStatus().intValue() != SkupStatus.CAN_SELL.getCode()){
logger.warn("payment skup status, skup is {}", request.getSkup());
throw new ServiceException(ServiceError.ORDER_REQUEST_ERROR);
}
// 检查 商品sku是否可售
SellerOrderGoods skupGood = checkSkupSellOrNot(request.getSkup());
ShoppingPaymentResponse response = new ShoppingPaymentResponse();
response.setPaymentWay(shoppingSupport.getPaymentWay());
... ... @@ -75,11 +72,28 @@ public class ShoppingServiceImpl implements IShoppingService{
response.setPromotionFormulaList(shoppingSupport.getPromotionFormula(skupGood));
// TODO 赔偿金计算
response.setDamagesDesc(shoppingSupport.getDamagesDesc(null));
// response.setDamagesDesc(shoppingSupport.getDamagesDesc(null));
return response;
}
private SellerOrderGoods checkSkupSellOrNot(int skup) {
// skup是否是可售状态
SellerOrderGoods skupGood = sellerOrderGoodsMapper.selectByPrimaryKey(skup);
if (skupGood == null){
logger.warn("payment skup not exist, skup is {}", skup);
throw new ServiceException(ServiceError.ORDER_SKUP_CANNOT_SELL);
}
// 不可售
if (skupGood.getStatus() == null
|| skupGood.getStatus().intValue() == SkupStatus.CAN_NOT_SELL.getCode()){
logger.warn("payment skup status, skup is {}", skup);
throw new ServiceException(ServiceError.ORDER_SKUP_CANNOT_SELL);
}
return skupGood;
}
/**
* 提交订单
... ... @@ -93,29 +107,25 @@ public class ShoppingServiceImpl implements IShoppingService{
|| shoppingRequest.getUid() < 0
|| StringUtils.isEmpty(shoppingRequest.getAddressId())){
logger.warn("submit param is null");
// TODO
throw new ServiceException(ServiceError.ORDER_REQUEST_ERROR);
throw new ServiceException(ServiceError.ORDER_REQUEST_PARM_IS_EMPTY);
}
// 创建订单
// 校验 skup是否是可售
SellerOrderGoods skup = sellerOrderGoodsMapper.selectByPrimaryKey(shoppingRequest.getSkup());
if (skup == null){
logger.warn("payment skup not exist, skup is {}", shoppingRequest.getSkup());
// TODO
throw new ServiceException(ServiceError.ORDER_REQUEST_ERROR);
// 检查地址是否合法
int addressId = AddressUtil.getDecryptStr(shoppingRequest.getAddressId());
if (addressId < 0){
logger.warn("submit addressId invalidate, uid is {}, skup is {}, addressId is {}", shoppingRequest.getUid(),
shoppingRequest.getSkup(), shoppingRequest.getAddressId());
throw new ServiceException(ServiceError.ORDER_ADDRESSID_INVALIDATE);
}
// 不可售
if (skup.getStatus()!=null
&& skup.getStatus().intValue() != SkupStatus.CAN_SELL.getCode()){
logger.warn("payment skup status, skup is {}", shoppingRequest.getSkup());
throw new ServiceException(ServiceError.ORDER_REQUEST_ERROR);
}
// 检查skup是否可售
SellerOrderGoods skup = checkSkupSellOrNot(shoppingRequest.getSkup());
// 生成订单号 TODO
// 生成订单号
long orderCode = orderCodeGenerator.generate(OrderCodeType.BUYER_TYPE);
UserAddressRspBO addressInfo = getAddressInfo(shoppingRequest, addressId);
// 减库存,skup更新成不可售,入库
BigDecimal shipFee = new BigDecimal(OrderConstant.DELIVERY_WAY_SF_COST);
OrderBuilder orderBuilder = OrderBuilder.builder()
... ... @@ -128,10 +138,9 @@ public class ShoppingServiceImpl implements IShoppingService{
.channelNo(shoppingRequest.getChannelNo())
.amount(skup.getGoodsPrice().add(shipFee))
.shipFee(shipFee)
.addressInfo(addressInfo)
.build();
// 收货地址信息, 入口参数:uid, address_id TODO
ordeCreationService.create(orderBuilder);
... ... @@ -140,7 +149,27 @@ public class ShoppingServiceImpl implements IShoppingService{
}
/**
* 获取用户信息
* @param shoppingRequest
* @param addressId
* @return
*/
private UserAddressRspBO getAddressInfo(ShoppingRequest shoppingRequest, int addressId) {
// 收货地址信息, 入口参数:uid, address_id
UserAddressReqBO userAddressReqBO = new UserAddressReqBO();
userAddressReqBO.setUid(shoppingRequest.getUid());
userAddressReqBO.setId(addressId);
//超时,使用默认地址,后续需要手动补充地址
UserAddressRspBO defaultResponse = new UserAddressRspBO();
defaultResponse.setAreaCode(OrderConstant.EMPTY_ADDRESS_CODE);
defaultResponse.setId(String.valueOf(addressId));
UserAddressRspBO userAddressBO = serviceCaller.asyncCall("users.getAddress", userAddressReqBO,
UserAddressRspBO.class, defaultResponse).get(500, TimeUnit.MILLISECONDS);
return userAddressBO;
}
}
... ...
package com.yohoufo.order.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.yoho.core.common.utils.DateUtil;
import com.yoho.error.ServiceError;
import com.yoho.error.exception.ServiceException;
import com.yohoufo.common.ApiResponse;
import com.yohoufo.common.caller.UfoServiceCaller;
import com.yohoufo.dal.order.*;
import com.yohoufo.dal.order.model.BuyerOrder;
import com.yohoufo.dal.order.model.BuyerOrderGoods;
import com.yohoufo.dal.order.model.SellerOrder;
import com.yohoufo.dal.order.model.SellerOrderGoods;
import com.yohoufo.dal.order.model.*;
import com.yohoufo.order.common.OrderStatus;
import com.yohoufo.order.common.SellerOrderStatus;
import com.yohoufo.order.common.SkupStatus;
import com.yohoufo.order.constants.MetaKey;
import com.yohoufo.order.model.dto.OrderBuilder;
import com.yohoufo.order.service.IOrdeCreationService;
import com.yohoufo.product.controller.ProductController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
... ... @@ -21,6 +24,8 @@ import org.springframework.transaction.annotation.Transactional;
@Service
public class OrdeCreationServiceImpl implements IOrdeCreationService {
private final Logger logger = LoggerFactory.getLogger(ProductController.class);
@Autowired
SellerOrderGoodsMapper sellerOrderGoodsMapper;
... ... @@ -36,7 +41,6 @@ public class OrdeCreationServiceImpl implements IOrdeCreationService {
@Autowired
BuyerOrderMetaMapper buyerOrderMetaMapper;
@Autowired
private UfoServiceCaller serviceCaller;
... ... @@ -48,47 +52,59 @@ public class OrdeCreationServiceImpl implements IOrdeCreationService {
@Transactional
public void create(OrderBuilder orderBuilder){
boolean increaseNeed = false;
try{
// 扣减库存,入口参数:skup, product_id TODO
// 1.skup不可售
// 2.卖家订单,skup已经售出
SellerOrderGoods sellerOrderGoods = new SellerOrderGoods();
sellerOrderGoods.setId(orderBuilder.getSkup());
sellerOrderGoods.setStatus(SkupStatus.CAN_NOT_SELL.getCode());
sellerOrderGoodsMapper.updateByPrimaryKeySelective(sellerOrderGoods);
// 根据skup 查询卖家订单 ==> 卖家uid
SellerOrder sellerOrder = sellerOrderMapper.selectBySkup(orderBuilder.getSkup());
sellerOrder.setUpdateTime(DateUtil.getCurrentTimeSecond());
sellerOrder.setStatus(SellerOrderStatus.HAS_SELLED.getCode());
sellerOrderMapper.updateByPrimaryKeySelective(sellerOrder);
// 订单入口
BuyerOrder buyerOrder = new BuyerOrder();
buyerOrder.setUid(orderBuilder.getUid());
buyerOrder.setOrderCode(orderBuilder.getOrderCode());
buyerOrder.setSellerUid(sellerOrder.getUid());
buyerOrder.setPaymentType((byte) orderBuilder.getPaymentType());
buyerOrder.setAmount(orderBuilder.getAmount());
buyerOrder.setShipFee(orderBuilder.getShipFee());
buyerOrder.setChannelNo(orderBuilder.getChannelNo());
int now = DateUtil.getCurrentTimeSecond();
buyerOrder.setCreateTime(now);
buyerOrder.setUpdateTime(now);
buyerOrder.setStatus((byte)OrderStatus.WAITING_PAY.getCode());
buyerOrderMapper.insert(buyerOrder);
BuyerOrderGoods buyerOrderGoods = new BuyerOrderGoods();
buyerOrderGoods.setSkup(orderBuilder.getSkup());
buyerOrderGoods.setOrderCode(orderBuilder.getOrderCode());
buyerOrderGoods.setGoodsPrice(sellerOrderGoods.getGoodsPrice());
buyerOrderGoods.setGoodsAmount(sellerOrderGoods.getGoodsPrice());
buyerOrderGoodsMapper.insertSelective(buyerOrderGoods);
// 扣减库存
// 入口参数:skup, product_id
ApiResponse apiResponse = serviceCaller.call("ufo.product.saleSkup",
ApiResponse.class, orderBuilder.getProductId(), orderBuilder.getSkup());
// 减库存失败
if (apiResponse.getCode() != 200){
logger.warn("submit create order, decrease storage faile, orderCode is {}, uid is {}, skup is {}, productId is {}",
orderBuilder.getOrderCode(), orderBuilder.getUid(), orderBuilder.getSkup(), orderBuilder.getProductId());
throw new ServiceException(ServiceError.ORDER_SKUP_CANNOT_SELL);
}
// product处减库存失败
increaseNeed = true;
/**
* 1.更新 表seller_order_goods skup的状态为不可售
* 2.更新 表seller_order 状态为已经售出
* 3.插入订单 表buyer_order
* 4.插入订单商品 buyer_order_goods
* 5.插入收货地址 buyer_order_meta
*/
// 1.表seller_order_goods ==> 不可售
SellerOrderGoods sellerOrderGoods = updSellerOrderGoods(orderBuilder);
// 2.更新 表seller_order 状态 ==> 已售出
SellerOrder sellerOrder = updSellerOrder(orderBuilder);
// 3.插入订单 表buyer_order
insertOrder(orderBuilder, sellerOrder.getUid());
// 4.插入订单商品 buyer_order_goods
insertOrderGoods(orderBuilder, sellerOrderGoods);
// 5.插入收货地址 buyer_order_meta 买家收货地址
insertOrderMeta(orderBuilder);
}catch (Exception ex){
if (increaseNeed){
// order处 更新状态失败,需要补库存
ApiResponse apiResponse = serviceCaller.call("ufo.product.cancelSaleSkup",ApiResponse.class, orderBuilder.getSkup());
// 补库存失败,需要报警手动补库存 TODO
if (apiResponse.getCode() != 200){
}
}
if (!(ex instanceof ServiceException)) {
//上报告警事件
// EventBusPublisher.publishEvent(new SmsAlarmEvent(OrderHanders.submit, "submit", "订单(" + order.getOrderCode() + ")创建失败"));
... ... @@ -98,4 +114,54 @@ public class OrdeCreationServiceImpl implements IOrdeCreationService {
}
}
private void insertOrderMeta(OrderBuilder orderBuilder) {
BuyerOrderMeta buyerOrderMeta = new BuyerOrderMeta();
buyerOrderMeta.setUid(orderBuilder.getUid());
buyerOrderMeta.setOrderCode(orderBuilder.getOrderCode());
buyerOrderMeta.setMetaKey(MetaKey.BUYER_DELIVERY_ADDRESS);
buyerOrderMeta.setMetaValue(JSONObject.toJSONString(orderBuilder.getAddressInfo()));
buyerOrderMetaMapper.insert(buyerOrderMeta);
}
private void insertOrderGoods(OrderBuilder orderBuilder, SellerOrderGoods sellerOrderGoods) {
BuyerOrderGoods buyerOrderGoods = new BuyerOrderGoods();
buyerOrderGoods.setSkup(orderBuilder.getSkup());
buyerOrderGoods.setOrderCode(orderBuilder.getOrderCode());
buyerOrderGoods.setGoodsPrice(sellerOrderGoods.getGoodsPrice());
buyerOrderGoods.setGoodsAmount(sellerOrderGoods.getGoodsPrice());
buyerOrderGoodsMapper.insertSelective(buyerOrderGoods);
}
private void insertOrder(OrderBuilder orderBuilder, int sellerUid) {
BuyerOrder buyerOrder = new BuyerOrder();
buyerOrder.setUid(orderBuilder.getUid());
buyerOrder.setOrderCode(orderBuilder.getOrderCode());
buyerOrder.setSellerUid(sellerUid);
buyerOrder.setPaymentType((byte) orderBuilder.getPaymentType());
buyerOrder.setAmount(orderBuilder.getAmount());
buyerOrder.setShipFee(orderBuilder.getShipFee());
buyerOrder.setChannelNo(orderBuilder.getChannelNo());
int now = DateUtil.getCurrentTimeSecond();
buyerOrder.setCreateTime(now);
buyerOrder.setUpdateTime(now);
buyerOrder.setStatus((byte) OrderStatus.WAITING_PAY.getCode());
buyerOrderMapper.insert(buyerOrder);
}
private SellerOrder updSellerOrder(OrderBuilder orderBuilder) {
SellerOrder sellerOrder = sellerOrderMapper.selectBySkup(orderBuilder.getSkup());
sellerOrder.setUpdateTime(DateUtil.getCurrentTimeSecond());
sellerOrder.setStatus(SellerOrderStatus.HAS_SELLED.getCode());
sellerOrderMapper.updateByPrimaryKeySelective(sellerOrder);
return sellerOrder;
}
private SellerOrderGoods updSellerOrderGoods(OrderBuilder orderBuilder) {
SellerOrderGoods sellerOrderGoods = new SellerOrderGoods();
sellerOrderGoods.setId(orderBuilder.getSkup());
sellerOrderGoods.setStatus(SkupStatus.CAN_NOT_SELL.getCode());
sellerOrderGoodsMapper.updateByPrimaryKeySelective(sellerOrderGoods);
return sellerOrderGoods;
}
}
... ...
... ... @@ -154,7 +154,7 @@ public class PaymentServiceImpl implements IPaymentService {
logger.info("payment orderCode is {} ,uid is {}, type is {}",request.getOrderCode(), request.getUid(), codeMeta.getType());
// 家订单号
// 家订单号
if (codeMeta.getType() == OrderCodeType.BUYER_TYPE.getType()){
return checkUpdBuyerOrderCode(request);
}else{
... ... @@ -165,7 +165,7 @@ public class PaymentServiceImpl implements IPaymentService {
private BigDecimal checkUpdSellerOrderCode(PaymentRequest request) {
// 订单状态
SellerOrder sellerOrder = sellerOrderMapper.selectByOrderCode(request.getOrderCode());
SellerOrder sellerOrder = sellerOrderMapper.selectByOrderCode(request.getOrderCode(), request.getUid());
if (sellerOrder == null){
logger.warn("payment orderCode not exist, orderCode is {}", request.getOrderCode(), request.getUid());
throw new ServiceException(ServiceError.ORDER_NULL);
... ... @@ -178,7 +178,7 @@ public class PaymentServiceImpl implements IPaymentService {
}
// 检查实付金额
if (sellerOrder.getEarnestMoney() == null){
if (sellerOrder.getEarnestMoney() == null || sellerOrder.getEarnestMoney().compareTo(new BigDecimal(0)) <=0 ){
logger.warn("payment amount null, orderCode is {}", request.getOrderCode());
throw new ServiceException(ServiceError.ORDER_NULL);
}
... ... @@ -197,7 +197,7 @@ public class PaymentServiceImpl implements IPaymentService {
*/
private BigDecimal checkUpdBuyerOrderCode(PaymentRequest request) {
// 订单状态
BuyerOrder buyerOrder = buyerOrderMapper.selectByOrderCode(request.getOrderCode());
BuyerOrder buyerOrder = buyerOrderMapper.selectByOrderCode(request.getOrderCode(), request.getUid());
if (buyerOrder == null){
logger.warn("payment orderCode not exist, orderCode is {}", request.getOrderCode(), request.getUid());
throw new ServiceException(ServiceError.ORDER_NULL);
... ... @@ -210,7 +210,7 @@ public class PaymentServiceImpl implements IPaymentService {
}
// 检查实付金额
if (buyerOrder.getAmount() == null){
if (buyerOrder.getAmount() == null || buyerOrder.getAmount().compareTo(new BigDecimal(0)) <= 0){
logger.warn("payment amount null, orderCode is {}", request.getOrderCode());
throw new ServiceException(ServiceError.ORDER_NULL);
}
... ...
... ... @@ -84,15 +84,15 @@ public class ProductController {
@ApiOperation(name = "ufo.product.storage.leastprice", desc="sku的最低价")
@RequestMapping(params = "method=ufo.product.storage.leastprice")
//@Cachable(expire=600)
public ApiResponse queryStorageLeastprice(
public StorageLeastPriceResp queryStorageLeastprice(
@RequestParam(value = "storage_id", required = true) Integer storageId) {
if (storageId == null) {
return new ApiResponse(500, "storageId Is Null", null);
return null;
}
StorageLeastPriceResp resp = productService.queryStorageLeastPrice(storageId);
return new ApiResponse.ApiResponseBuilder().data(queryStorageLeastprice()).code(200).message("storage.leastprice").build();
return queryStorageLeastprice();
}
... ... @@ -105,16 +105,16 @@ public class ProductController {
@ApiOperation(name = "ufo.product.storage.data", desc="sku信息")
@RequestMapping(params = "method=ufo.product.storage.data")
//@Cachable(expire=600)
public ApiResponse queryStorageInfo(
public StorageDataResp queryStorageInfo(
@RequestParam(value = "storage_id", required = true) Integer storageId) {
if (storageId == null) {
return new ApiResponse(500, "storageId Is Null", null);
return null;
}
StorageDataResp resp = productService.queryStorageInfo(storageId);
return new ApiResponse.ApiResponseBuilder().data(queryStorageData()).code(200).message("storage.data").build();
return queryStorageData();
}
... ...
... ... @@ -18,13 +18,6 @@
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.yohoufo.fore</groupId>
<artifactId>yohoufo-fore-dal</artifactId>
... ...
... ... @@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
... ... @@ -41,4 +42,19 @@ public class ResourcesController {
return new ApiResponse.ApiResponseBuilder().data(data).code(200).message("resources data").build();
}
@RequestMapping(params = "method=ufo.resource.get")
public ApiResponse payment(@RequestParam(name = "contentCode") String contentCode,
@RequestParam(name = "clientType") String clientType) {
ResourcesRequestBody request = new ResourcesRequestBody();
request.setClientType(clientType);
request.setContentCode(contentCode);
logger.info("Get resources by content code[{}] and client type [{}].", request.getContentCode(),
request.getClientType());
List<Object> data = resourcesService.get(request);
logger.info("Get resources by content code[{}] and client type [{}] success.", request.getContentCode(),
request.getClientType());
return new ApiResponse.ApiResponseBuilder().data(data).code(200).message("resources data").build();
}
}
... ...
package com.yohoufo.resource.service.impl.cache;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.IntegerCodec;
import com.yoho.core.cache.LocalCache;
import com.yoho.core.cache.LocalCacheCallback;
import com.yoho.core.rest.client.ServiceCaller;
import com.yoho.core.rest.client.hystrix.AsyncFuture;
import com.yoho.product.model.ShopsBo;
import com.yoho.product.request.BatchBaseRequest;
import com.yoho.service.model.resource.request.RecommendReqVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by oneway.wang on 2017/7/14.
*/
@Component
public class FocusCacheService {
private static final Logger LOGGER = LoggerFactory.getLogger(FocusCacheService.class);
private LocalCache localCache = new LocalCache();
@Autowired
private ServiceCaller serviceCaller;
private static final String REC_POS = "100047";
//存储JSON格式,存在转义问题,修改为String
@PostConstruct
private void init() {
localCache.init("focus Cache", ExpireTime.RESOURCES_LOCAL_CACHE, TimeUnit.HOURS, new LocalCacheCallback() {
@Override
public Object load(String key, Object oldValue) throws Exception {
RecommendReqVO recommendReqVO = new RecommendReqVO();
recommendReqVO.setUid(0);
recommendReqVO.setChannelId(Integer.parseInt(key));
recommendReqVO.setRec_pos(REC_POS);
JSONObject result = null;
result = serviceCaller.call("bigdata.getFocusShop", recommendReqVO, JSONObject.class);
if (result != null && result.getIntValue("code") == 200) {
return result;
}
return null;
}
});
}
public JSONObject getData(int cid){
JSONObject result = (JSONObject) localCache.get(String.valueOf(cid));
return result;
}
}
... ...
package com.yohoufo.resource.service.impl.resource;
import java.io.Serializable;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoho.core.common.utils.URIBuilder;
import com.yoho.core.rest.client.ServiceCaller;
import com.yoho.product.model.ShopActivityInfoBo;
import com.yoho.product.request.ShopsFocusRequest;
import com.yoho.service.model.resource.request.RecommendReqVO;
import com.yoho.service.model.resource.resource.FocusParsedResource;
import com.yohoufo.common.redis.NoSyncGracefulRedisTemplate;
import com.yohoufo.resource.helper.MakeUrlService;
import com.yohoufo.resource.service.IResourceParse;
import com.yohoufo.resource.service.Resource;
import com.yohoufo.resource.service.impl.cache.ExpireTime;
import com.yohoufo.resource.service.impl.cache.FocusCacheService;
import com.yohoufo.resource.util.JSONConvert;
import com.yohoufo.resource.util.ResourcesKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.yohoufo.resource.helper.MakeUrlService;
import com.yohoufo.resource.service.IResourceParse;
import com.yohoufo.resource.service.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by wangwei on 2016/11/8.
* 处理焦点图数据
*/
@Service
public class FocusResourceParse implements IResourceParse{
public class FocusResourceParse implements IResourceParse {
@javax.annotation.Resource
private MakeUrlService makeUrlService;
private static final Logger logger = LoggerFactory.getLogger(FocusResourceParse.class);
private static final String REC_POS = "100047";
public static final String TEMPLATE_NAME="focus";
@javax.annotation.Resource(name="NoSyncGracefulRedisTemplate")
private NoSyncGracefulRedisTemplate resourcesRedisCache;
@Autowired
private MakeUrlService makeUrlService;
private ServiceCaller serviceCaller;
@Autowired
private FocusCacheService focusCacheService;
Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Serializable parse(Resource resource) {
try {
return parseData(resource);
} catch (Exception e) {
logger.warn("Parse focus resource fail, resource code [{}] exception: {}", resource.getCode(), e);
return resource.getData();
public FocusParsedResource parse(Resource resource) {
int uid = resource.getUid()==null?0:resource.getUid();
String udid = resource.getUdid();
String clientType = resource.getClientType();
int channel;
if(resource.getGender()==null||resource.getGender().equals("1,3")){
channel = 1;
}else {
channel = 2;
}
FocusParsedResource parsedResource = new FocusParsedResource();
if(getRecommendSize(resource.getData().getJSONObject("data"))>0){
parsedResource.setOriginalTemplateId(resource.getOriginalId());
}
parsedResource.setTemplateId(resource.getId().toString());
parsedResource.setFocusType(resource.getData().getString("focus_type"));
parsedResource.setTemplateIntro(resource.getData().getString("template_intro"));
parsedResource.setData(parseData(resource.getData().getJSONObject("data"), resource.getClientType(),channel,uid,udid,clientType));
String isNewFocus = StringUtils.isEmpty(resource.getData().getString("isNewFocus"))?"":resource.getData().getString("isNewFocus");
parsedResource.setTemplateName(isNewFocus.equals("1")?"newFocus":"focus");
return parsedResource;
}
private List<FocusParsedResource.Data> parseData(JSONObject data, String clientTpe,int channel,int uid,String udid,String clientType) {
if (data == null) {
return Collections.emptyList();
}
List<FocusParsedResource.Data> parsedResourceDataList = new ArrayList<>();
JSONArray dataArray = JSONConvert.transform2JSONArray(data);
int recommendSize = getRecommendSize(data);
if(recommendSize>0) {
JSONArray shopArray = buildShopInfo(getRecommendShopIds(channel, uid, udid),channel);
for (Object obj : dataArray) {
if (obj instanceof JSONObject) {
JSONObject val = (JSONObject) obj;
FocusParsedResource.Data tmp = new FocusParsedResource.Data();
if (val.getInteger("isFocusRec") != null && val.getIntValue("isFocusRec") == 1 && shopArray.size() > 0) {
JSONObject shopInfo = (JSONObject) shopArray.get(0);
String src = shopInfo.getString("focusUrl");
String url;
//如果不能获取链接,参数拼接
if(StringUtils.isEmpty(shopInfo.getString("url"))){
url = makeShopUrl(shopInfo.getInteger("shopsId"), clientType, shopInfo.getString("shopName"), shopInfo.getString("shopTemplateType"), shopInfo.getString("isRedShop"));
}else{
url = shopInfo.getString("url");
}
private JSONObject parseData(Resource resource) {
if(StringUtils.isEmpty(src)||StringUtils.isEmpty(url)){
tmp.setSrc(val.getString("src"));
tmp.setUrl(makeUrlService.makeUrl(val.getJSONObject("url"), clientTpe));
tmp.setTitle(val.getString("alt"));
if (val.containsKey("bgColor")) {
tmp.setBgColor(val.getString("bgColor"));
}
}else{
//推荐店铺增加标识用于大数据统计
tmp.setIsFocusRec("1");
tmp.setSrc(src + "?imageView2/{mode}/w/{width}/h/{height}");
tmp.setUrl(url);
}
JSONObject returnJSON=new JSONObject();
//加入最基础的东西
returnJSON.put("template_id",resource.getId().toString());
returnJSON.put("template_name",this.TEMPLATE_NAME);
returnJSON.put("template_intro",resource.getData().getString("template_intro"));
logger.info("shopInfo:url={},src={}", url, shopInfo.getString("focusUrl"));
shopArray.remove(shopInfo);
} else {
tmp.setSrc(val.getString("src"));
tmp.setUrl(makeUrlService.makeUrl(val.getJSONObject("url"), clientTpe));
tmp.setTitle(val.getString("alt"));
if (val.containsKey("bgColor")) {
tmp.setBgColor(val.getString("bgColor"));
}
}
parsedResourceDataList.add(tmp);
}
}
}else{
for(Object obj : dataArray){
if (obj instanceof JSONObject) {
JSONObject val = (JSONObject) obj;
FocusParsedResource.Data tmp = new FocusParsedResource.Data();
tmp.setSrc(val.getString("src"));
tmp.setUrl(makeUrlService.makeUrl(val.getJSONObject("url"), clientTpe));
// 处理 data(充分利用原数据库中数据转成的JSONObject,只是遍历之后把URLObject替换成解析之后的数据)
JSONObject data = resource.getData().getJSONObject("data");
for (String index: data.keySet()) {
makeUrl(data.getJSONObject(index), resource.getClientType());
tmp.setTitle(val.getString("alt"));
if (val.containsKey("bgColor")) {
tmp.setBgColor(val.getString("bgColor"));
}
parsedResourceDataList.add(tmp);
}
}
}
returnJSON.put("data",data);
return returnJSON;
return parsedResourceDataList;
}
private void makeUrl(JSONObject jsonElement, String clientType) {
JSONObject jsonUrl = jsonElement.getJSONObject("url");
String strUrl = makeUrlService.makeUrl(jsonUrl, clientType);
jsonElement.put("url", strUrl);
private int getRecommendSize(JSONObject data) {
JSONArray dataArray = JSONConvert.transform2JSONArray(data);
int recommendSize = 0;
for(Object obj : dataArray){
if (obj instanceof JSONObject) {
JSONObject val = (JSONObject) obj;
//FocusParsedResource.Data tmp = new FocusParsedResource.Data();
if(val.getInteger("isFocusRec")!=null&&val.getIntValue("isFocusRec")==1){
recommendSize++;
}
}
}
return recommendSize;
}
private List<Integer> getRecommendShopIds(int cId,Integer uid,String udid){
if(uid==null){
uid = 0;
}
RecommendReqVO recommendReqVO = new RecommendReqVO();
recommendReqVO.setUid(uid);
recommendReqVO.setChannelId(cId);
recommendReqVO.setRec_pos(REC_POS);
recommendReqVO.setUdid(udid);
JSONObject result = null;
try{
logger.info("getFromBigData,uid={},cId={}",uid,cId);
//查询缓存
result = resourcesRedisCache.get(ResourcesKeyBuilder.generateFocusRecKey(REC_POS,uid,cId,udid),JSONObject.class);
if(result==null){
result = serviceCaller.call("bigdata.getFocusShop", recommendReqVO, JSONObject.class);
if (result == null || result.getIntValue("code") == 505) {
//大数据调用失败
result = getBackupCache(cId);
}else if (result != null && result.getIntValue("code") == 200) {
// 大数据调用成功,刷新一、二级缓存
resourcesRedisCache.setEx(ResourcesKeyBuilder.generateFocusRecKey(REC_POS,uid,cId,udid),result, ExpireTime.FOCUS_CACHE);
getBackupCache(cId);
}
}
}catch(Exception e){
//查询二级缓存
result = getBackupCache(cId);
}
return getArrayFromJSON(result);
}
//二级缓存
private JSONObject getBackupCache(int cid){
JSONObject result = focusCacheService.getData(cid);
logger.info("invoke backupCache,cid={},result={}",cid,result);
return result;
}
private List<Integer> getArrayFromJSON(JSONObject result){
List<Integer> shopRecommendArray = new ArrayList<>();
JSONArray jsonArray = new JSONArray();
jsonArray = JSON.parseArray(result.getString("data"));
//组织返回
shopRecommendArray = JSON.parseObject(jsonArray.toString(), List.class);
return shopRecommendArray;
}
//根据店铺id获取店铺url
private String makeShopUrl(Integer shopId,String clientType,String shopName,String shopTemplateType,String isRedShop){
URIBuilder uriBuilder = new URIBuilder("https://m.yohobuy.com");
JSONObject jsonUrl = new JSONObject();
// http://m.yohobuy.com?openby:yohobuy=
// {\"action\":\"go.shop\",\"params\":{\"shop_id\":\"%zd\", \"shop_template_type\":\"%@\", \"shop_name\":\"%@\", \"is_red_shop\":\"%zd\"}
uriBuilder.addParameter("shop_id",String.valueOf(shopId));
uriBuilder.addParameter("shop_name",shopName);
uriBuilder.addParameter("shop_template_type",shopTemplateType);
uriBuilder.addParameter("is_red_shop",isRedShop);
jsonUrl.put("action",makeUrlService.SHOP_ACTION);
String url = uriBuilder.build();
jsonUrl.put("url",url);
return makeUrlService.makeUrl(jsonUrl, clientType,"");
}
//查询店铺信息
private JSONArray buildShopInfo( List<Integer> shopIdList,int channel) {
JSONArray shopArray = resourcesRedisCache.get(ResourcesKeyBuilder.generateFocusShopInfoKey(shopIdList),JSONArray.class);
if(shopArray==null||shopArray.size()==0){
Integer appType = 0;//默认yoho app
ShopsFocusRequest shopRequest = new ShopsFocusRequest();
shopRequest.setShopIdList(shopIdList);
shopRequest.setChannel(channel);
shopRequest.setAppType(appType);//默认yoho app
ShopActivityInfoBo[] shopList = serviceCaller.asyncCall("product.queryShopFocusIntroList", shopRequest, ShopActivityInfoBo[].class).get(3);
shopArray = new JSONArray();
for(ShopActivityInfoBo shopsBo:shopList){
JSONObject jsonObject = new JSONObject();
jsonObject.put("isRedShop",shopsBo.getIsRedShop());
jsonObject.put("shopTemplateType",shopsBo.getShopTemplateType());
jsonObject.put("shopsId",shopsBo.getShopsId());
jsonObject.put("shopName",shopsBo.getShopName());
jsonObject.put("focusUrl",shopsBo.getFocusUrl());
//6.5添加的链接地址
jsonObject.put("url",shopsBo.getUrl());
shopArray.add(jsonObject);
}
resourcesRedisCache.setEx(ResourcesKeyBuilder.generateFocusShopInfoKey(shopIdList),shopArray,ExpireTime.FOCUS_CACHE);
}
return shopArray;
}
}
... ...
... ... @@ -44,6 +44,9 @@ public class HotSeriesResourceParse implements IResourceParse{
returnJSON.put("template_name",this.TEMPLATE_NAME);
returnJSON.put("template_intro",resource.getData().getString("template_intro"));
JSONObject moreUrl = resource.getData().getJSONObject("more_url");
returnJSON.put("more_url", makeMoreUrl(moreUrl,resource.getClientType()));
// 处理 data(充分利用原数据库中数据转成的JSONObject,只是遍历之后把URLObject替换成解析之后的数据)
JSONObject data = resource.getData().getJSONObject("data");
for (String index: data.keySet()) {
... ... @@ -58,4 +61,9 @@ public class HotSeriesResourceParse implements IResourceParse{
String strUrl = makeUrlService.makeUrl(jsonUrl, clientType);
jsonElement.put("url", strUrl);
}
private String makeMoreUrl(JSONObject jsonUrl, String clientType) {
String strUrl = makeUrlService.makeUrl(jsonUrl, clientType,"");
return strUrl;
}
}
... ...
... ... @@ -48,7 +48,7 @@ uic.service.url=http://192.168.103.73:8096/uic
#signature encrypt key salt
gateway.signature.key.salt=mQyMTMwZjlmZTZmYjY4UjkNmYwZGM0OTk0Y
trace.enabled=true
trace.enabled=false
# yoho api docs
yoho.api.docs.switch=off
... ... @@ -74,3 +74,10 @@ unionpay.pay.mid=898310148160568
unionpay.pay.tid=00000001
unionPay.pay.signKey=fcAmtnx7MwismjWNhNKdHC44mNXtnEQeJkRrhKJwyrW2ysRR
redis.readonly.proxy.address=192.168.102.45
redis.readonly.proxy.auth=redis9646
redis.readonly.proxy.port=6379
redis.proxy.address=192.168.102.45
redis.proxy.auth=redis9646
redis.proxy.port=6379
\ No newline at end of file
... ...