You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
940 lines
34 KiB
940 lines
34 KiB
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Commons\Log;
|
|
use App\Constants\LogLabel;
|
|
use App\Model\Coupon;
|
|
use App\Model\CouponRec;
|
|
use App\Model\CouponUserUse;
|
|
use App\Model\Goods;
|
|
use App\Model\Market;
|
|
use App\Model\Order;
|
|
use App\Model\OrderGoods;
|
|
use App\Model\OrderMain;
|
|
use App\Model\OrderSalesStatistic;
|
|
use App\Model\SpecCombination;
|
|
use App\Model\Store;
|
|
use Exception;
|
|
use Hyperf\DbConnection\Db;
|
|
use Hyperf\Snowflake\IdGeneratorInterface;
|
|
use Hyperf\Utils\ApplicationContext;
|
|
use Hyperf\Di\Annotation\Inject;
|
|
use App\Service\WxRefundServiceInterface;
|
|
use App\Service\UserServiceInterface;
|
|
use App\Model\Users;
|
|
use App\Constants\SsdbKeysPrefix;
|
|
|
|
class OrderService implements OrderServiceInterface
|
|
{
|
|
/**
|
|
* @Inject
|
|
* @var Log
|
|
*/
|
|
protected $log;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var CouponServiceInterface
|
|
*/
|
|
protected $couponService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var WxRefundServiceInterface
|
|
*/
|
|
protected $wxRefundService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var UserServiceInterface
|
|
*/
|
|
protected $userService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var PurchaseLimitServiceInterface
|
|
*/
|
|
protected $purchaseLimitService;
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function addOnlineOrder($data)
|
|
{
|
|
|
|
bcscale(6);
|
|
$dataMain = $data;
|
|
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
// TODO 这个字段后续可能不用了,之前由达达订单号从前端传上来
|
|
$dataMain['order_num'] = 'o'.date('YmdHis').mt_rand(1000,9999);
|
|
|
|
// 计算当前订单可用红包优惠金额
|
|
$couponMoney = 0;
|
|
$receiveCouponIds = [];
|
|
if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) {
|
|
$receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids']));
|
|
$couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']);
|
|
}
|
|
$dataMain['yhq_money2'] = $couponMoney;
|
|
|
|
// 获取分布式全局ID
|
|
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
|
|
$dataMain['global_order_id'] = $generator->generate();
|
|
|
|
// 店铺IDs
|
|
$dataMain['store_ids'] = '';
|
|
$storeList = json_decode(html_entity_decode($data['store_list']), true);
|
|
if (!is_array($storeList)||empty($storeList)) {
|
|
Db::rollBack();
|
|
return '订单中商品不存在或已失效';
|
|
}
|
|
|
|
// 获取商户IDs
|
|
foreach ($storeList as &$item) {
|
|
$dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id'];
|
|
}
|
|
|
|
// 主订单插入数据
|
|
$currentTime = time();
|
|
$dataMain['time'] = date('Y-m-d H:i:s', $currentTime);
|
|
$dataMain['time_add'] = $currentTime;
|
|
$dataMain['pay_time'] = '';
|
|
$dataMain['state'] = OrderMain::ORDER_STATE_UNPAY;
|
|
$dataMain['code'] = $dataMain['global_order_id'];
|
|
$dataMain['jj_note'] = '';
|
|
|
|
// 主订单模型保存
|
|
$orderMain = OrderMain::create($dataMain);
|
|
$orderMainId = $orderMain->id;
|
|
|
|
// 统计订单中所有店铺当日订单数,做店铺订单序号
|
|
$countsArr = Order::query()
|
|
->selectRaw('store_id, COUNT(*) AS count')
|
|
->whereIn('store_id', explode(',', $dataMain['store_ids']))
|
|
->where(['type' => OrderMain::ORDER_TYPE_ONLINE])
|
|
->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
|
|
->groupBy('store_id')
|
|
->get()
|
|
->toArray();
|
|
|
|
$storeOrderCounts = [];
|
|
foreach ($countsArr as $key => &$row) {
|
|
$storeOrderCounts[$row['store_id']] = $row['count'];
|
|
}
|
|
|
|
// 循环处理订单总额、子订单总额、商品、商户订单等信息
|
|
$orderAmountTotal = 0; # 总订单金额
|
|
$orderGoods = [];
|
|
foreach ($storeList as $key => &$item) {
|
|
|
|
// 子订单数据处理
|
|
$dataChild = [
|
|
'uniacid' => $data['uniacid'],
|
|
'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
|
|
'user_id' => $orderMain->user_id,
|
|
'store_id' => $item['store_id'],
|
|
'order_main_id' => $orderMainId,
|
|
'state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'tel' => $orderMain->tel,
|
|
'name' => $orderMain->name,
|
|
'address' => $orderMain->address,
|
|
'area' => $orderMain->area,
|
|
'time' => date("Y-m-d H:i:s"),
|
|
'note' => $item['note'] ?? '',
|
|
'delivery_time' => $orderMain->delivery_time,
|
|
'type' => $orderMain->type,
|
|
'lat' => $orderMain->lat,
|
|
'lng' => $orderMain->lng,
|
|
'pay_type' => $orderMain->pay_type,
|
|
'order_type' => $orderMain->order_type,
|
|
'money' => floatval($item['subtotal']),
|
|
'box_money' => floatval($item['box_money']),
|
|
'mj_money' => floatval($item['mj_money']),
|
|
'yhq_money' => floatval($item['yhq_money']),
|
|
'yhq_money2' => floatval($item['yhq_money2']),
|
|
'zk_money' => floatval($item['zk_money']),
|
|
'coupon_id' => $item['coupon_id'],
|
|
'coupon_id2' => $item['coupon_id2'],
|
|
'xyh_money' => floatval($item['xyh_money']),
|
|
'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
|
|
'time_add' => date("Y-m-d H:i:s"),
|
|
'jj_note' => '',
|
|
'form_id' => '',
|
|
'form_id2' => '',
|
|
'code' => '',
|
|
];
|
|
|
|
$orderChildId = Order::query()->insertGetId($dataChild);
|
|
|
|
// 子订单内商品处理
|
|
$goodsAmountTotal = 0;
|
|
|
|
if (!is_array($item['good_list'])||empty($item['good_list'])) {
|
|
Db::rollBack();
|
|
return '订单商品异常';
|
|
}
|
|
foreach ($item['good_list'] as &$goods) {
|
|
$goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money']));
|
|
$goodsAmount = bcmul($goodsAmount, $goods['num']);
|
|
$goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount);
|
|
|
|
$orderGoods[$goods['id']] = $goods;
|
|
$orderGoods[$goods['id']]['uniacid'] = $data['uniacid'];
|
|
$orderGoods[$goods['id']]['order_id'] = $orderChildId;
|
|
$orderGoods[$goods['id']]['user_id'] = $dataMain['user_id'];
|
|
$orderGoods[$goods['id']]['store_id'] = $item['store_id'];
|
|
}
|
|
|
|
// 子订单优惠总额
|
|
$discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']);
|
|
|
|
$goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2);
|
|
$orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2);
|
|
|
|
// 校验子订单金额
|
|
if ($goodsAmountTotal != $dataChild['money']) {
|
|
Db::rollBack();
|
|
return '店铺订单总金额错误';
|
|
}
|
|
|
|
}
|
|
|
|
// 校验库存
|
|
foreach ($orderGoods as $Key => &$goodsItem) {
|
|
|
|
$goodsItem['combination_id'] = intval($goodsItem['combination_id']);
|
|
|
|
// 存在规格,则去规格处查库存
|
|
$goods = [];
|
|
if ($goodsItem['combination_id'] > 0) {
|
|
|
|
$combination = SpecCombination::query()
|
|
->select(['good_id AS id', 'number AS inventory'])
|
|
->where(['id' => $goodsItem['combination_id']])
|
|
->first()
|
|
->toArray();
|
|
|
|
$goods = Goods::query()
|
|
->select(['id', 'name', 'is_max'])
|
|
->where(['id' => $combination['id']])
|
|
->first()
|
|
->toArray();
|
|
$goods['inventory'] = $combination['inventory'];
|
|
|
|
} else {
|
|
|
|
$goods = Goods::query()
|
|
->select(['id', 'name', 'is_max', 'inventory'])
|
|
->where(['id' => $goodsItem['good_id']])
|
|
->first()
|
|
->toArray();
|
|
|
|
}
|
|
|
|
if (!$goods) {
|
|
Db::rollBack();
|
|
return '缺少商品';
|
|
}
|
|
|
|
if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){
|
|
Db::rollBack();
|
|
return '商品 '.$goods->name.' 库存不足!';
|
|
}
|
|
|
|
}
|
|
|
|
// 校验总订单金额
|
|
$deliveryAmount = 0; # 配送费用
|
|
if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){
|
|
$deliveryAmount = $dataMain['dada_fee'];
|
|
}
|
|
|
|
$orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount);
|
|
# 总订单优惠总额
|
|
$discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']);
|
|
$orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2);
|
|
|
|
if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) {
|
|
Db::rollBack();
|
|
return '订单总金额错误';
|
|
}
|
|
|
|
// 添加订单商品
|
|
$tempGoods = $orderGoods;
|
|
$orderGoods = [];
|
|
foreach ($tempGoods as $key => &$value) {
|
|
$goodsTemp['good_id'] = $value['good_id'];
|
|
$goodsTemp['img'] = $value['logo'];
|
|
$goodsTemp['number'] = $value['num'];
|
|
$goodsTemp['order_id'] = $value['order_id'];
|
|
$goodsTemp['name'] = $value['name'];
|
|
$goodsTemp['money'] = $value['money'];
|
|
$goodsTemp['dishes_id'] = $value['dishes_id'];
|
|
$goodsTemp['spec'] = $value['spec'];
|
|
$goodsTemp['is_qg'] = $value['is_qg'];
|
|
$goodsTemp['good_unit'] = $value['good_unit'];
|
|
$goodsTemp['uniacid'] = $value['uniacid'];
|
|
$goodsTemp['combination_id'] = $value['combination_id'];
|
|
$orderGoods[] = $goodsTemp;
|
|
}
|
|
|
|
$addOrderGoods = OrderGoods::query()->insert($orderGoods);
|
|
if (!$addOrderGoods) {
|
|
Db::rollBack();
|
|
return '订单商品异常';
|
|
}
|
|
|
|
//判断是否有购买特价商品
|
|
$this->purchaseLimitService->ssdbPurchaseRecord($orderGoods,$data['user_id'],$dataMain['global_order_id']);
|
|
|
|
// 修改总订单金额,金额是计算来的
|
|
// TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
|
|
$updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
|
|
if (!$updateOrderMain) {
|
|
Db::rollBack();
|
|
return '订单总金额记录失败';
|
|
}
|
|
|
|
// 处理红包的使用
|
|
$canUseCoupons = CouponRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id'])
|
|
->whereIn('id', $receiveCouponIds)
|
|
->get()->toArray();
|
|
if (is_array($canUseCoupons)&&!empty($canUseCoupons)) {
|
|
# 使用记录、更新当前优惠券
|
|
foreach ($canUseCoupons as $key => &$coupon) {
|
|
|
|
$couponUse = [
|
|
'user_id' => $coupon['user_id'],
|
|
'user_receive_id' => $coupon['id'],
|
|
'system_coupon_id' => $coupon['system_coupon_user_id'],
|
|
'order_main_id' => $orderMainId,
|
|
'use_time' => $currentTime,
|
|
'return_time' => 0,
|
|
'number' => 1,
|
|
'status' => 1,
|
|
'update_time' => 0,
|
|
];
|
|
var_dump('$couponUse',$couponUse);
|
|
|
|
$insertRes = CouponUserUse::query()->insert($couponUse);
|
|
|
|
if ($insertRes) {
|
|
$numberRemain = $coupon['number_remain'] - 1;
|
|
if ($numberRemain == 0) {
|
|
$status = 2;
|
|
} elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
|
|
$status = 1;
|
|
} elseif ($numberRemain == $coupon['number']) {
|
|
$status = 0;
|
|
}
|
|
|
|
$upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
|
|
|
|
if (!$upRes) {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
// 缓存使用记录
|
|
$usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
|
|
if (!$usedRes) {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
} else {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
Db::commit();
|
|
return $orderMainId;
|
|
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(
|
|
LogLabel::ORDER_LOG,
|
|
['message' => $e->getMessage()]
|
|
);
|
|
|
|
Db::rollBack();
|
|
return $e->getMessage();
|
|
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function addOfflineOrder($data)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
// 主订单数据
|
|
$dataMain = [];
|
|
|
|
// 获取分布式全局ID
|
|
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
|
|
$globalRrderId = $generator->generate();
|
|
|
|
// 主订单插入数据
|
|
$currentTime = time();
|
|
$dataMain = [
|
|
'delivery_no' => '',
|
|
'dada_fee' => 0,
|
|
'market_id' => 0,
|
|
'box_money' => 0,
|
|
'ps_money' => 0,
|
|
'mj_money' => 0,
|
|
'xyh_money' => 0,
|
|
'yhq_money' => 0,
|
|
'yhq_money2' => 0,
|
|
'zk_money' => 0,
|
|
'tel' => '',
|
|
'name' => '',
|
|
'address' => '',
|
|
'area' => '',
|
|
'lat' => '',
|
|
'lng' => '',
|
|
'note' => '',
|
|
'form_id' => '',
|
|
'form_id2' => '',
|
|
'delivery_time' => '',
|
|
'order_type' => 0,
|
|
'coupon_id' => 0,
|
|
'coupon_id2' => 0,
|
|
'store_list' => '',
|
|
'receive_coupon_ids' => '',
|
|
'type' => OrderMain::ORDER_TYPE_OFFLINE,
|
|
'time' => date('Y-m-d H:i:s', $currentTime),
|
|
'time_add' => $currentTime,
|
|
'pay_time' => '',
|
|
'pay_type' => OrderMain::ORDER_PAY_WX,
|
|
'state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'dm_state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'code' => $globalRrderId,
|
|
'jj_note' => '',
|
|
'uniacid' => 2,
|
|
'order_num' => 'dm'.date('YmdHis') . mt_rand(1000, 9999),
|
|
'money' => $data['money'],
|
|
'user_id' => $data['user_id'],
|
|
'store_ids' => $data['store_id'],
|
|
'global_order_id' => $globalRrderId,
|
|
];
|
|
|
|
// 主订单模型保存
|
|
$orderMain = OrderMain::create($dataMain);
|
|
$orderMainId = $orderMain->id;
|
|
|
|
// 子订单模型保存
|
|
$dataChild = [
|
|
'uniacid' => 1,
|
|
'order_num' => 's'.date('YmdHis') . mt_rand(1000, 9999),
|
|
'user_id' => $orderMain->user_id,
|
|
'store_id' => $data['store_id'],
|
|
'order_main_id' => $orderMainId,
|
|
'state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'dm_state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'tel' => $orderMain->tel,
|
|
'name' => $orderMain->name,
|
|
'address' => $orderMain->address,
|
|
'area' => $orderMain->area,
|
|
'time' => date("Y-m-d H:i:s"),
|
|
'note' => '',
|
|
'delivery_time' => $orderMain->delivery_time,
|
|
'type' => $orderMain->type,
|
|
'lat' => $orderMain->lat,
|
|
'lng' => $orderMain->lng,
|
|
'pay_type' => $orderMain->pay_type,
|
|
'order_type' => $orderMain->order_type,
|
|
'money' => $data['money'],
|
|
'box_money' => 0,
|
|
'mj_money' => 0,
|
|
'yhq_money' => 0,
|
|
'yhq_money2' => 0,
|
|
'zk_money' => 0,
|
|
'coupon_id' => 0,
|
|
'coupon_id2' => 0,
|
|
'xyh_money' => 0,
|
|
'time_add' => date("Y-m-d H:i:s"),
|
|
'jj_note' => '',
|
|
'form_id' => '',
|
|
'form_id2' => '',
|
|
'code' => '',
|
|
];
|
|
|
|
$orderChildId = Order::query()->insertGetId($dataChild);
|
|
|
|
Db::commit();
|
|
return $orderMainId;
|
|
} catch (Exception $e) {
|
|
$this->log->event(
|
|
LogLabel::ORDER_LOG,
|
|
['message' => $e->getMessage()]
|
|
);
|
|
Db::rollBack();
|
|
return '购买失败';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 计算和校验当前订单可用红包及金额
|
|
* @param $couponIds
|
|
* @param $orderAmount
|
|
* @param $userId
|
|
* @param $marketId
|
|
* @return int|string
|
|
* @throws Exception
|
|
*/
|
|
protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
|
|
{
|
|
|
|
// 用户当前订单可用优惠券
|
|
$couponsCanUse = $this->couponService->getOrderCanUseCoupons(
|
|
$orderAmount,
|
|
$marketId,
|
|
$userId,
|
|
[
|
|
'receive.id',
|
|
'receive.user_id',
|
|
'receive.number',
|
|
'receive.number_remain',
|
|
'receive.system_coupon_user_id',
|
|
'coupon.discounts',
|
|
'coupon.discount_type',
|
|
]
|
|
);
|
|
|
|
$couponCanUseIds = array_column($couponsCanUse, 'id');
|
|
$couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
|
|
$couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
|
|
|
|
if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
|
|
throw new Exception('您的订单中有优惠券已经失效');
|
|
}
|
|
|
|
// 计算红包折扣金额
|
|
$couponMoney = 0;
|
|
foreach ($couponsCanUse as $key => $coupon) {
|
|
|
|
if (!in_array($coupon->id, $couponIds)) {
|
|
continue;
|
|
}
|
|
|
|
if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
|
|
$couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
|
|
} elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
|
|
$discountRate = bcdiv($coupon->discounts,10);
|
|
$discountRate = bcsub(1,$discountRate);
|
|
$discountMoney = bcmul($orderAmount, $discountRate);
|
|
$couponMoney = bcadd($couponMoney, $discountMoney, 2);
|
|
}
|
|
}
|
|
|
|
return $couponMoney;
|
|
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function existsByGlobalOrderId($global_order_id)
|
|
{
|
|
return OrderMain::query()->where(['order_num' => $global_order_id])->value('id');
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function onlineCompleted($global_order_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
// 主订单状态更新
|
|
$orderMain = OrderMain::query()
|
|
->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_DELIVERY])
|
|
->first();
|
|
|
|
if (empty($orderMain)) {
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
$orderMain->state = OrderMain::ORDER_STATE_COMPLETE;
|
|
$orderMain->save();
|
|
|
|
// 子订单状态更新
|
|
$upChild = Order::query()
|
|
->where(['order_main_id' => $orderMain->id])
|
|
->update(['state' => OrderMain::ORDER_STATE_COMPLETE]);
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ONLINE_COMPLETE_LOG, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function onlinePaid($global_order_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
// 查询订单
|
|
$orderMain = OrderMain::query()
|
|
->where([
|
|
'global_order_id' => $global_order_id,
|
|
'type' => OrderMain::ORDER_TYPE_ONLINE
|
|
])
|
|
->first();
|
|
|
|
// 修改订单、子订单状态
|
|
$currentTime = time();
|
|
$orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
|
|
$orderMain->time_pay = $currentTime;
|
|
$orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
|
|
$orderMain->save();
|
|
|
|
$upOrder = Order::query()
|
|
->where(['order_main_id' => $orderMain->id])
|
|
->update(['state' => OrderMain::ORDER_STATE_UNTAKE, 'pay_time' => $orderMain->pay_time]);
|
|
|
|
// 更新商户销量
|
|
$upStoreScore = Store::query()
|
|
->whereIn('id', explode(',', $orderMain->store_ids))
|
|
->update(['score' => Db::raw('score+1')]);
|
|
|
|
// 更新商品库存和销量
|
|
$orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time'])
|
|
->where(['order_main_id' => $orderMain->id])
|
|
->get()
|
|
->toArray();
|
|
$orderGoods = OrderGoods::query()->select(['good_id AS id', 'number', 'combination_id'])
|
|
->whereIn('order_id', array_values(array_column($orders, 'id')))
|
|
->get()
|
|
->toArray();
|
|
foreach ($orderGoods as $key => &$goodsItem) {
|
|
|
|
$goods = Goods::find($goodsItem['id']);
|
|
|
|
// 库存处理,有规格
|
|
if ($goodsItem['combination_id']) {
|
|
$combination = SpecCombination::find($goodsItem['combination_id']);
|
|
$combination->number = $combination->number - $goodsItem['number'];
|
|
$combination->save();
|
|
} else {
|
|
$goods->inventory = $goods->inventory - $goodsItem['number'];
|
|
}
|
|
|
|
$goods->sales = $goods->sales - $goodsItem['number'];
|
|
$goods->save();
|
|
|
|
}
|
|
|
|
// 月销流水
|
|
$statistics = [];
|
|
foreach ($orders as $key => &$order) {
|
|
$statistics[] = [
|
|
'money' => $order['money'],
|
|
'user_id' => $order['user_id'],
|
|
'store_id' => $order['store_id'],
|
|
'market_id' => $orderMain->market_id,
|
|
'order_id' => $order['id'],
|
|
'createtime' => strtotime($order['pay_time']),
|
|
];
|
|
}
|
|
|
|
if (is_array($statistics) && !empty($statistics)) {
|
|
$inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
|
|
}
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function offlinePaid($global_order_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
// 主订单状态更新
|
|
$orderMain = OrderMain::query()
|
|
->where(['global_order_id' => $global_order_id, 'type' => OrderMain::ORDER_TYPE_OFFLINE])
|
|
->first();
|
|
|
|
if (empty($orderMain)) {
|
|
|
|
$this->log->event(
|
|
LogLabel::PAY_NOTIFY_WXMINI,
|
|
['order_not_found' => $global_order_id]
|
|
);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
$currentTime = time();
|
|
$orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
|
|
$orderMain->dm_state = OrderMain::ORDER_STATE_UNTAKE;
|
|
$orderMain->time_pay = $currentTime;
|
|
$orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
|
|
$orderMain->save();
|
|
|
|
// 子订单状态更新
|
|
$upOrder = Order::query()
|
|
->where(['order_main_id' => $orderMain->id])
|
|
->update([
|
|
'state' => OrderMain::ORDER_STATE_UNTAKE,
|
|
'dm_state' => OrderMain::ORDER_STATE_UNTAKE,
|
|
'pay_time' => date('Y-m-d H:i:s', $currentTime)
|
|
]);
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::OFFLINE_PAID_LOG, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function onlineCancel($global_order_id){
|
|
OrderMain::where('global_order_id',$global_order_id)
|
|
->update(['state' => OrderMain::ORDER_STATE_CANCEL]);
|
|
//撤销redis 用券记录
|
|
$res = $this->couponService->refundOrderCoupons($global_order_id);
|
|
//撤销特价商品购买记录
|
|
$res = $this->purchaseLimitService->delSsdbPurchaseRecord($global_order_id);
|
|
return $res;
|
|
}
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function onlineRefund($global_order_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
$time = time();
|
|
// 主订单状态更新
|
|
$orderMain = OrderMain::query()
|
|
->select('id','global_order_id','state','pay_type','user_id','money')
|
|
->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDING])
|
|
->first();
|
|
|
|
if (empty($orderMain)) {
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
$orderMain->state = OrderMain::ORDER_STATE_REFUNDED;
|
|
if(!$orderMain->save()){
|
|
Db::rollBack();
|
|
return false;
|
|
};
|
|
|
|
// 子订单状态更新
|
|
$upChild = Order::query()
|
|
->where('order_main_id' , $orderMain->id)
|
|
->where('state',OrderMain::ORDER_STATE_REFUNDING)
|
|
->update(['state' => OrderMain::ORDER_STATE_REFUNDED]);
|
|
if(empty($upChild)){
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
if($orderMain->pay_type == OrderMain::ORDER_PAY_WX){
|
|
// 微信支付 微信退款
|
|
if(!$this->wxRefundService->wxPayRefund($global_order_id)){
|
|
Db::rollBack();
|
|
return false;
|
|
};
|
|
}else if($orderMain->pay_type == OrderMain::ORDER_PAY_BALANCE){
|
|
// 余额支付 退款到用户余额
|
|
// if($this->userService->userWallet($orderMain->user_id,$orderMain->money,Users::WALLET_TYPE_INC)){
|
|
// Db::rollBack();
|
|
// return false;
|
|
// };
|
|
|
|
// 返还优惠券
|
|
// $this->couponService->orderRefundCoupon($global_order_id);
|
|
// 删除特价商品缓存
|
|
// $this->orderService->clearTodayGoodPurchase($orderMain->user_id,1);
|
|
// 添加用户流水
|
|
// $this->financialService->userByOLOrderRefund($orderMain->user_id, $orderMain->global_order_id, $orderMain->money);
|
|
}
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款','exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 订单退款失败
|
|
* 回退订单状态
|
|
*/
|
|
public function onlineRefundFail($global_order_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
$time = time();
|
|
// 主订单状态更新
|
|
$orderMain = OrderMain::query()
|
|
->select('id','global_order_id','state','pay_type')
|
|
->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDED])
|
|
->first();
|
|
|
|
if (empty($orderMain)) {
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
$orderMain->state = OrderMain::ORDER_STATE_REFUNDING;
|
|
$upOrderMain = $orderMain->save();
|
|
|
|
// 子订单状态更新
|
|
$upChild = Order::query()
|
|
->where('order_main_id' , $orderMain->id)
|
|
->where('state',OrderMain::ORDER_STATE_REFUNDED)
|
|
->update(['state' => OrderMain::ORDER_STATE_REFUNDING]);
|
|
if(empty($upChild)){
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款失败时处理状态9->8 ','exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 删除特价商品缓存
|
|
*/
|
|
public function clearTodayGoodPurchase($userId, $goodId)
|
|
{
|
|
$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
|
|
return $ssdb->exec('del', SsdbKeysPrefix::PURCHASE_RECORD. date('Ymd') .'_'.$userId, $goodId);
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function onlineAutoCancelByUserId($user_id)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
$orders = OrderMain::query()
|
|
->select(['id', 'global_order_id'])
|
|
->where([
|
|
'user_id' => $user_id,
|
|
'state' => OrderMain::ORDER_STATE_UNPAY
|
|
])
|
|
->where('time_add', '<', (time()-900))
|
|
->get()->toArray();
|
|
|
|
foreach ($orders as $key => &$item) {
|
|
$order = OrderMain::query()->find($item['id']);
|
|
$order->state = OrderMain::ORDER_STATE_CANCEL;
|
|
$order->save();
|
|
|
|
$this->couponService->orderRefundCoupons($item['global_order_id']);
|
|
}
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::AUTO_CANCEL_USER_ORDER, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function userOnlineOrders($user_id, $state, $page=1, $pagesize=10)
|
|
{
|
|
$builder = OrderMain::query()
|
|
->where(['user_id' => $user_id, 'del' => OrderMain::ORDER_DEL_NO, 'type' => OrderMain::ORDER_TYPE_ONLINE]);
|
|
if ($state != 0) {
|
|
$state = explode(',', $state);
|
|
$builder = $builder->whereIn('state', $state);
|
|
}
|
|
$orders = $builder->get()->forPage($page, $pagesize)->toArray();
|
|
|
|
foreach ($orders as $key => &$order) {
|
|
// 市场名称
|
|
$order['market_name'] = Market::query()->where(['id' => $order['market_id']])->value('name');
|
|
|
|
// 商品数量和第一个商品名、图
|
|
$orderChildIds = Order::query()->select(['id'])->where(['order_main_id' => $order['id']])->get()->toArray();
|
|
$orderChildIds = array_values(array_column($orderChildIds, 'id'));
|
|
$order['g_num'] = OrderGoods::query()->whereIn('order_id', $orderChildIds)->count();
|
|
$goods = OrderGoods::query()->whereIn('order_id', $orderChildIds)->select(['name', 'img'])->first();
|
|
$order['good_name'] = $goods->name;
|
|
// TODO 临时写死oss压缩类型
|
|
$order['img'] = $this->switchImgToAliOss($goods->img);
|
|
}
|
|
|
|
return $orders;
|
|
}
|
|
|
|
public function switchImgToAliOss($path, $bucket = 'thumbnail_q50')
|
|
{
|
|
if (strpos($path, 'http') === false || strpos($path, 'https') === false) {
|
|
$path = 'https://img.lanzulive.com/' . $path;
|
|
} else {
|
|
$temp = explode('//', $path);
|
|
$temp = explode('/', $temp[1]);
|
|
unset($temp[0]);
|
|
$path = 'https://img.lanzulive.com/' . implode('/', $temp);
|
|
}
|
|
return $path . '!' . $bucket;
|
|
}
|
|
}
|