前端 + 后端:创建订单,接入价格计算

This commit is contained in:
YunaiV 2019-04-20 19:59:08 +08:00
parent ff69f324d5
commit 5785827748
14 changed files with 119 additions and 175 deletions

View File

@ -59,13 +59,14 @@ export function getOrderInfo(orderId) {
// Cart
export function createOrderFromCart(userAddressId, remark) {
export function createOrderFromCart(userAddressId, couponCardId, remark) {
return request({
url: '/order-api/users/order/create_order_from_cart',
method: 'post',
params: {
userAddressId,
remark,
couponCardId,
}
});
}

View File

@ -161,12 +161,14 @@
}
const remark = '';
const couponCardId = this.chosenCoupon >= 0 ? this.coupons[this.chosenCoupon].id : undefined;
if (this.from === 'direct_order') {
const { skuId, quantity } = this.$route.query;
const orderItems = [{
skuId,
quantity,
couponCardId,
}];
createOrder({
orderItems,
@ -184,7 +186,7 @@
}
});
} else if (this.from === 'cart') {
createOrderFromCart(userAddressId, remark).then(result => {
createOrderFromCart(userAddressId, couponCardId, remark).then(result => {
if (result) {
// const { orderNo } = result;
this.$router.push({ //

View File

@ -67,6 +67,7 @@ public class UsersOrderController {
@PostMapping("create_order_from_cart")
@ApiOperation("创建订单购物车")
public CommonResult<OrderCreateBO> createOrderFromCart(@RequestParam("userAddressId") Integer userAddressId,
@RequestParam(value = "couponCardId", required = false) Integer couponCardId,
@RequestParam(value = "remark", required = false) String remark,
HttpServletRequest request) {
Integer userId = UserSecurityContextHolder.getContext().getUserId();
@ -78,7 +79,7 @@ public class UsersOrderController {
// 创建 OrderCreateDTO 对象
OrderCreateDTO orderCreateDTO = OrderConvertAPP.INSTANCE.createOrderCreateDTO(userId, userAddressId,
remark, HttpUtil.getIp(request),
cartItems);
cartItems, couponCardId);
// 创建订单
CommonResult<OrderCreateBO> createResult= orderService.createOrder(orderCreateDTO);
if (createResult.isError()) {

View File

@ -40,15 +40,15 @@ public interface OrderConvertAPP {
@Mappings({})
List<OrderCreateItemDTO> convert(List<CartItemBO> cartItems);
default OrderCreateDTO createOrderCreateDTO(Integer userId, Integer userAddressId,
String remark, String ip,
List<CartItemBO> cartItems) {
default OrderCreateDTO createOrderCreateDTO(Integer userId, Integer userAddressId, String remark, String ip,
List<CartItemBO> cartItems, Integer couponCardId) {
return new OrderCreateDTO()
.setUserId(userId)
.setUserAddressId(userAddressId)
.setRemark(remark)
.setIp(ip)
.setOrderItems(this.convert(cartItems));
.setOrderItems(this.convert(cartItems))
.setCouponCardId(couponCardId);
}
}

View File

@ -24,6 +24,10 @@ public class OrderCreatePO implements Serializable {
*/
@NotNull(message = "用户地址id不能为空!")
private Integer userAddressId;
/**
* 优惠劵编号
*/
private Integer couponCardId;
/**
* 备注
*/

View File

@ -142,7 +142,7 @@ public class CalcOrderPriceBO {
*/
private Integer discountTotal;
/**
* 邮费
* 邮费 TODO 芋艿 postage 改成 logistics
*/
private Integer postageTotal;
/**

View File

@ -24,6 +24,10 @@ public class OrderCreateDTO implements Serializable {
* 用户地址
*/
private Integer userAddressId;
/**
* 优惠劵编号
*/
private Integer couponCardId;
/**
* 备注
*/
@ -37,4 +41,5 @@ public class OrderCreateDTO implements Serializable {
/// order item
private List<OrderCreateItemDTO> orderItems;
}

View File

@ -1,39 +0,0 @@
package cn.iocoder.mall.order.biz;
import cn.iocoder.mall.order.biz.dataobject.OrderItemDO;
import java.util.List;
/**
* 订单常用
*
* @author Sin
* @time 2019-03-23 11:51
*/
public interface OrderCommon {
/**
* 计算总价格
*
* @param items
* @return
*/
Integer calculatedPrice(List<OrderItemDO> items);
/**
* 计算订单实付金额
*
* @param items
* @return
*/
Integer calculatedAmount(List<OrderItemDO> items);
/**
* 计算物流金额
*
* @param items
* @return
*/
Integer calculatedLogisticsPrice(List<OrderItemDO> items);
}

View File

@ -1,54 +0,0 @@
package cn.iocoder.mall.order.biz;
import cn.iocoder.mall.order.biz.dataobject.OrderItemDO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 订单常用
*
* @author Sin
* @time 2019-03-23 11:53
*/
@Component
public class OrderCommonImpl implements OrderCommon {
@Override
public Integer calculatedPrice(List<OrderItemDO> items) {
if (CollectionUtils.isEmpty(items)) {
return 0;
}
AtomicInteger totalPrice = new AtomicInteger(0);
items.forEach(orderItemDO -> {
totalPrice.addAndGet(orderItemDO.getPrice() * orderItemDO.getQuantity());
});
return totalPrice.get();
}
@Override
public Integer calculatedAmount(List<OrderItemDO> items) {
if (CollectionUtils.isEmpty(items)) {
return 0;
}
AtomicInteger totalAmount = new AtomicInteger(0);
items.forEach(orderItemDO -> {
totalAmount.addAndGet(orderItemDO.getPayAmount() * orderItemDO.getQuantity());
});
return totalAmount.get();
}
@Override
public Integer calculatedLogisticsPrice(List<OrderItemDO> items) {
if (CollectionUtils.isEmpty(items)) {
return 0;
}
AtomicInteger totalAmount = new AtomicInteger(0);
items.forEach(orderItemDO -> {
totalAmount.addAndGet(orderItemDO.getLogisticsPrice());
});
return totalAmount.get();
}
}

View File

@ -29,15 +29,27 @@ public class OrderDO extends DeletableDO {
*/
private String orderNo;
/**
* 价格()
* 购买商品总金额单位
*/
private Integer price;
private Integer buyPrice;
/**
* 优惠总金额单位
*/
private Integer discountPrice;
/**
* 物流金额 ()
*/
private Integer logisticsPrice;
/**
* 交易金额
* 最终金额单位
*
* buyPrice + logisticsPrice - discountPrice = presentPrice
*/
private Integer presentPrice;
/**
* 实际已支付金额单位
*
* 初始时金额为 0 等到支付成功后会进行更新
*/
private Integer payAmount;

View File

@ -48,22 +48,6 @@ public class OrderItemDO extends DeletableDO {
* 数量
*/
private Integer quantity;
/**
* 商品成交单价()
*/
@Deprecated
private Integer price;
/**
* 支付金额实付金额
*/
@Deprecated
private Integer payAmount;
/**
* 物流金额 ()
*/
@Deprecated
private Integer logisticsPrice;
/**
* 原始单价单位
*/

View File

@ -9,7 +9,6 @@ import cn.iocoder.mall.order.api.constant.OrderErrorCodeEnum;
import cn.iocoder.mall.order.api.constant.OrderHasReturnExchangeEnum;
import cn.iocoder.mall.order.api.constant.OrderStatusEnum;
import cn.iocoder.mall.order.api.dto.*;
import cn.iocoder.mall.order.biz.OrderCommon;
import cn.iocoder.mall.order.biz.constants.OrderDeliveryTypeEnum;
import cn.iocoder.mall.order.biz.constants.OrderRecipientTypeEnum;
import cn.iocoder.mall.order.biz.convert.*;
@ -25,6 +24,7 @@ import com.google.common.collect.Lists;
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;
import java.util.*;
@ -57,11 +57,11 @@ public class OrderServiceImpl implements OrderService {
private OrderRecipientMapper orderRecipientMapper;
@Autowired
private OrderCancelMapper orderCancelMapper;
@Autowired
private OrderCommon orderCommon;
@Reference
private ProductSpuService productSpuService;
@Autowired
private CartServiceImpl cartService;
@Reference
private UserAddressService userAddressService;
@Reference
@ -196,61 +196,70 @@ public class OrderServiceImpl implements OrderService {
// 获取商品信息
Set<Integer> skuIds = orderItemDOList.stream()
.map(orderItemDO -> orderItemDO.getSkuId()).collect(Collectors.toSet());
CommonResult<List<ProductSkuDetailBO>> productResult = productSpuService.getProductSkuDetailList(skuIds);
// 校验商品信息
if (productResult.isError()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_GET_SKU_FAIL.getCode());
}
if (productResult.getData() == null) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_GET_SKU_NOT_EXISTENT.getCode());
}
if (orderItemDTOList.size() != productResult.getData().size()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_GET_GOODS_INFO_INCORRECT.getCode());
}
//
// 价格计算
CommonResult<CalcOrderPriceBO> calcOrderPriceResult = calcOrderPrice(productResult.getData(), orderCreateDTO);
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
CalcOrderPriceBO calcOrderPrice = calcOrderPriceResult.getData();
// 设置 orderItem
Map<Integer, ProductSkuDetailBO> productSpuBOMap = productResult.getData()
.stream().collect(Collectors.toMap(o -> o.getId(), o -> o));
.stream().collect(Collectors.toMap(ProductSkuDetailBO::getId, o -> o)); // 商品 SKU 信息的集合
Map<Integer, CalcOrderPriceBO.Item> priceItemMap = new HashMap<>();
calcOrderPrice.getItemGroups().forEach(itemGroup ->
itemGroup.getItems().forEach(item -> priceItemMap.put(item.getId(), item)));
for (OrderItemDO orderItemDO : orderItemDOList) {
ProductSkuDetailBO productSkuDetailBO = productSpuBOMap.get(orderItemDO.getSkuId());
if (productSkuDetailBO.getQuantity() <= 0) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_INSUFFICIENT_INVENTORY.getCode());
}
if (productSkuDetailBO.getPrice() <= 0) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_GOODS_AMOUNT_INCORRECT.getCode());
}
// 设置 SKU 信息
orderItemDO.setSkuImage(Optional.ofNullable(productSkuDetailBO.getSpu().getPicUrls().get(0)).get());
orderItemDO.setSkuName(productSkuDetailBO.getSpu().getName());
orderItemDO.setPrice(productSkuDetailBO.getPrice());
orderItemDO.setLogisticsPrice(0);
int payAmount = orderItemDO.getQuantity() * orderItemDO.getPrice();
orderItemDO.setPayAmount(payAmount);
// 设置价格信息
CalcOrderPriceBO.Item priceItem = priceItemMap.get(orderItemDO.getSkuId());
Assert.notNull(priceItem, "商品计算价格为空");
orderItemDO.setOriginPrice(priceItem.getOriginPrice())
.setBuyPrice(priceItem.getBuyPrice())
.setPresentPrice(priceItem.getPresentPrice())
.setBuyTotal(priceItem.getBuyTotal())
.setDiscountTotal(priceItem.getDiscountTotal())
.setPresentTotal(priceItem.getPresentTotal());
}
// order
// TODO: 2019-04-11 Sin 订单号需要生成规则
String orderNo = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
Integer totalAmount = orderCommon.calculatedAmount(orderItemDOList);
Integer totalPrice = orderCommon.calculatedPrice(orderItemDOList);
Integer totalLogisticsPrice = orderCommon.calculatedLogisticsPrice(orderItemDOList);
// Integer totalAmount = orderCommon.calculatedAmount(orderItemDOList);
// Integer totalPrice = orderCommon.calculatedPrice(orderItemDOList);
// Integer totalLogisticsPrice = orderCommon.calculatedLogisticsPrice(orderItemDOList);
OrderDO orderDO = new OrderDO()
.setUserId(userId)
.setOrderNo(orderNo)
.setPrice(totalPrice)
.setPayAmount(totalAmount)
.setLogisticsPrice(totalLogisticsPrice)
.setBuyPrice(calcOrderPrice.getFee().getBuyTotal())
.setDiscountPrice(calcOrderPrice.getFee().getDiscountTotal())
.setLogisticsPrice(calcOrderPrice.getFee().getPostageTotal())
.setPresentPrice(calcOrderPrice.getFee().getPresentTotal())
.setPayAmount(0)
.setClosingTime(null)
.setDeliveryTime(null)
.setPaymentTime(null)
@ -330,6 +339,19 @@ public class OrderServiceImpl implements OrderService {
);
}
private CommonResult<CalcOrderPriceBO> calcOrderPrice(List<ProductSkuDetailBO> skus, OrderCreateDTO orderCreateDTO) {
// 创建计算的 DTO
CalcOrderPriceDTO calcOrderPriceDTO = new CalcOrderPriceDTO()
.setUserId(orderCreateDTO.getUserId())
.setItems(new ArrayList<>(skus.size()))
.setCouponCardId(orderCreateDTO.getCouponCardId());
for (ProductSkuDetailBO item : skus) {
calcOrderPriceDTO.getItems().add(new CalcOrderPriceDTO.Item(item.getId(), item.getQuantity(), true));
}
// 执行计算
return cartService.calcOrderPrice(calcOrderPriceDTO);
}
@Override
public CommonResult updateOrderItem(OrderItemUpdateDTO orderUpdateDTO) {
OrderItemDO orderItemDO = OrderItemConvert.INSTANCE.convert(orderUpdateDTO);
@ -352,17 +374,21 @@ public class OrderServiceImpl implements OrderService {
}
// 先更新金额
orderItemMapper.updateById(new OrderItemDO().setId(orderItemId).setPayAmount(payAmount));
orderItemMapper.updateById(new OrderItemDO().setId(orderItemId)
// .setPayAmount(payAmount) TODO 芋艿这里要修改
);
// 再重新计算订单金额
List<OrderItemDO> orderItemDOList = orderItemMapper
.selectByDeletedAndOrderId(orderId, DeletedStatusEnum.DELETED_NO.getValue());
Integer price = orderCommon.calculatedPrice(orderItemDOList);
Integer amount = orderCommon.calculatedAmount(orderItemDOList);
// Integer price = orderCommon.calculatedPrice(orderItemDOList);
// Integer amount = orderCommon.calculatedAmount(orderItemDOList);
Integer price = -1; // TODO 芋艿这里要修改价格
Integer amount = -1;
orderMapper.updateById(
new OrderDO()
.setId(orderId)
.setPrice(price)
// .setPrice(price) TODO 芋艿这里要修改
.setPayAmount(amount)
);
return CommonResult.success(null);
@ -495,7 +521,8 @@ public class OrderServiceImpl implements OrderService {
);
// 更新订单 amount
Integer totalAmount = orderCommon.calculatedAmount(effectiveOrderItems);
// Integer totalAmount = orderCommon.calculatedAmount(effectiveOrderItems);
Integer totalAmount = -1; // TODO 芋艿需要修改下价格相关
orderMapper.updateById(
new OrderDO()
.setId(orderId)

View File

@ -4,7 +4,7 @@
<sql id="FIELDS">
id, order_id, order_no, sku_id, sku_name, sku_image, order_logistics_id,
quantity, price, pay_amount,
quantity, origin_price, buy_price, present_price, buy_total, discount_total, present_total,
payment_time, delivery_time, receiver_time, closing_time,
has_return_exchange, delivery_type, status,
create_time, update_time, deleted
@ -13,20 +13,20 @@
<!--
插入数据
-->
<insert id="insert" parameterType="OrderItemDO" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
<insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
INSERT INTO `order_item` (
order_id, order_no, sku_id, sku_name, sku_image, order_logistics_id,
quantity, price, pay_amount,
quantity, origin_price, buy_price, present_price, buy_total, discount_total, present_total,
payment_time, delivery_time, receiver_time, closing_time,
has_return_exchange, delivery_type, status,
create_time, update_time, deleted
) VALUES
<foreach collection="list" item="item" separator="," open="(" close=")">
#{item.orderId}, #{item.orderNo}, #{item.skuId}, #{item.skuName}, #{item.skuImage}, #{item.orderLogisticsId},
#{item.quantity}, #{item.price}, #{item.payAmount},
<foreach collection="list" item="item" separator=",">
(#{item.orderId}, #{item.orderNo}, #{item.skuId}, #{item.skuName}, #{item.skuImage}, #{item.orderLogisticsId},
#{item.quantity}, #{item.originPrice}, #{item.buyPrice}, #{item.presentPrice}, #{item.buyTotal}, #{item.discountTotal}, #{item.presentTotal},
#{item.paymentTime}, #{item.deliveryTime}, #{item.receiverTime}, #{item.closingTime},
#{item.hasReturnExchange}, #{item.deliveryType}, #{item.status},
#{item.createTime}, #{item.updateTime}, #{item.deleted}
#{item.createTime}, #{item.updateTime}, #{item.deleted})
</foreach>
</insert>
@ -56,12 +56,13 @@
<if test="orderItemDO.quantity != null">
, quantity = #{orderItemDO.quantity}
</if>
<if test="orderItemDO.price != null">
, price = #{orderItemDO.price}
</if>
<if test="orderItemDO.payAmount != null">
, pay_amount = #{orderItemDO.payAmount}
</if>
<!-- TODO 芋艿 需要改 -->
<!-- <if test="orderItemDO.price != null">-->
<!-- , price = #{orderItemDO.price}-->
<!-- </if>-->
<!-- <if test="orderItemDO.payAmount != null">-->
<!-- , pay_amount = #{orderItemDO.payAmount}-->
<!-- </if>-->
<if test="orderItemDO.paymentTime != null">
, payment_time = #{orderItemDO.paymentTime}

View File

@ -3,7 +3,7 @@
<mapper namespace="cn.iocoder.mall.order.biz.dao.OrderMapper">
<sql id="FIELDS">
id, user_id, order_no, price, pay_amount, logistics_price,
id, user_id, order_no, buy_price, discount_price, logistics_price, present_price, pay_amount,
payment_time, delivery_time, receiver_time, closing_time,
has_return_exchange,
status, remark, create_time, update_time, `deleted`
@ -14,12 +14,12 @@
-->
<insert id="insert" parameterType="OrderDO" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
INSERT INTO `order` (
user_id, order_no, price, pay_amount, logistics_price,
user_id, order_no, buy_price, discount_price, logistics_price, present_price, pay_amount,
payment_time, delivery_time, receiver_time, closing_time,
has_return_exchange,
status, remark, create_time, update_time, `deleted`
) VALUES (
#{userId}, #{orderNo}, #{price}, #{payAmount}, #{logisticsPrice},
#{userId}, #{orderNo}, #{buyPrice}, #{discountPrice}, #{logisticsPrice}, #{presentPrice}, #{payAmount},
#{paymentTime}, #{deliveryTime}, #{receiverTime}, #{closingTime},
#{hasReturnExchange},
#{status}, #{remark}, #{createTime}, #{updateTime}, #{deleted}
@ -34,15 +34,15 @@
<if test="orderNo != null">
, order_no = #{orderNo}
</if>
<if test="price != null">
, price = #{price}
</if>
<if test="payAmount != null">
, pay_amount = #{payAmount}
</if>
<if test="logisticsPrice != null">
, logistics_price = #{logisticsPrice}
</if>
<!-- <if test="price != null">--> <!-- TODO 后面要改下 -->
<!-- , price = #{price}-->
<!-- </if>-->
<!-- <if test="payAmount != null">-->
<!-- , pay_amount = #{payAmount}-->
<!-- </if>-->
<!-- <if test="logisticsPrice != null">-->
<!-- , logistics_price = #{logisticsPrice}-->
<!-- </if>-->
<if test="paymentTime != null">
, payment_time = #{paymentTime}
@ -129,7 +129,7 @@
SELECT
COUNT(*)
FROM `order`
WHERE 1 = 1
WHERE 1 = 1 <!-- TODO 芋艿 不要 1=1 ,会有问题,使用 where 标签 -->
<include refid="selectWhere" />
</select>
@ -140,10 +140,10 @@
SELECT
<include refid="FIELDS" />
FROM `order`
WHERE 1 = 1
WHERE 1 = 1 <!-- TODO 芋艿 不要 1=1 ,会有问题,使用 where 标签 -->
<include refid="selectWhere" />
LIMIT ${pageNo * pageSize}, ${pageSize}
</select>
</mapper>
</mapper>