Files
oil/server-tp6/app/store/model/Order.php
T
2026-09-01 22:15:50 +08:00

836 lines
28 KiB
PHP

<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\store\model;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\service\goods\source\Factory as StockFactory;
use app\store\controller\Controller;
use app\store\model\store\User;
use think\facade\Db;
use think\facade\Request;
use app\common\model\Goods as GoodsModel;
use app\common\model\Order as OrderModel;
use app\common\service\Order as OrderService;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\enum\order\OrderStatus as OrderStatusEnum;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\DeliveryType as DeliveryTypeEnum;
use app\common\enum\order\ReceiptStatus as ReceiptStatusEnum;
use app\common\enum\order\DeliveryStatus as DeliveryStatusEnum;
use app\common\library\helper;
/**
* 订单管理
* Class Order
* @package app\store\model
*/
class Order extends OrderModel
{
// 全部订单
const LIST_TYPE_ALL = 'all';
// 待发货订单
const LIST_TYPE_DELIVERY = 'delivery';
// 待收货订单
const LIST_TYPE_RECEIPT = 'receipt';
// 待付款订单
const LIST_TYPE_PAY = 'pay';
// 已完成订单
const LIST_TYPE_COMPLETE = 'complete';
// 已取消
const LIST_TYPE_CANCEL = 'cancel';
// 油券
const LIST_TYPE_OIL = 'oil';
// 优惠券
const LIST_TYPE_COUPON = 'coupon';
/**
* 订单详情页数据
* @param int $orderId
* @return Order|array|false|null
*/
public function getDetail(int $orderId)
{
return static::detail($orderId, [
'user',
'address',
'goods' => ['image'],
'express',
]) ?: false;
}
/**
* 订单列表
* @param string $dataType 订单类型
* @param array $param
* @param array $user
* @return mixed
*/
public function getList(string $dataType = self::LIST_TYPE_ALL, array $param = [], $user = [])
{
if(!isset($param['merchantId']) && isset($user['is_super']) && $user['is_super'] == 0){
$param['merchantId'] = $user['merchant_id'];
}
// 检索查询条件
$filter = $this->getQueryFilter($param);
// 设置订单类型条件
$dataTypeFilter = $this->getFilterDataType($dataType);
$keyword = $param['goods_no'] ?? '';
// 先查询总金额
$totalPayPrice = $this->alias('order')
->leftJoin('user', 'user.user_id = order.user_id')
->leftJoin('order_address address', 'address.order_id = order.order_id')
->leftJoin('order_goods og', 'og.order_id = order.order_id')
->where($dataTypeFilter)
->where($filter)
->where('order.is_delete', '=', 0)
->when(!empty($keyword), function ($query) use ($keyword) {
$query->whereLike('og.goods_no', "%{$keyword}%");
})
->sum('order.pay_price');
// 再查分页列表
$list = $this->with(['goods.image', 'user.avatar', 'spreadOne', 'spreadTwo'])
->alias('order')
->field('order.*')
->leftJoin('user', 'user.user_id = order.user_id')
->leftJoin('order_address address', 'address.order_id = order.order_id')
->leftJoin('order_goods og', 'og.order_id = order.order_id')
->where($dataTypeFilter)
->where($filter)
->where('order.is_delete', '=', 0)
->when(!empty($keyword), function ($query) use ($keyword) {
$query->whereLike('og.goods_no', "%{$keyword}%");
})
->order(['order.create_time' => 'desc'])
->paginate(10);
// 获取数据列表
return [
'list' => $list,
'total_money' => $totalPayPrice,
];
}
/**
* 订单列表(全部)
* @param string $dataType 订单类型
* @param array $query
* @return mixed
*/
public function getListAll(string $dataType = self::LIST_TYPE_ALL, array $query = [])
{
// 检索查询条件
$queryFilter = $this->getQueryFilter($query);
// 设置订单类型条件
$dataTypeFilter = $this->getFilterDataType($dataType);
// 获取数据列表
return $this->with(['goods.image', 'address', 'user.avatar', 'express'])
->alias('order')
->field('order.*')
->join('user', 'user.user_id = order.user_id')
->where($dataTypeFilter)
->where($queryFilter)
->where('order.is_delete', '=', 0)
->order(['order.create_time' => 'desc'])
->select();
}
/**
* 设置检索查询条件
* @param array $param
* @return array
*/
private function getQueryFilter(array $param): array
{
// 默认参数
$params = $this->setQueryDefaultValue($param, [
'searchType' => '', // 关键词类型 (10订单号 20会员昵称 30会员ID 40收货人姓名 50收货人电话)
'searchValue' => '', // 关键词内容
'goods_no' => '', // 商品编码
'oilCardNo' => '', // 油卡编号
'shareNo' => '', // 分油记录编号
'orderSource' => -1, // 订单来源
'payType' => -1, // 支付方式
'spread_uid' => -1, // 一级代理商
'pay_status' => -1, // 支付状态
'oil_status' => -1, // 分油状态
'use_status' => -1, // 使用状态
'deliveryType' => -1, // 配送方式
'betweenTime' => [], // 起止时间
'userId' => 0, // 会员ID
'merchantId' => 0, // 代理商
]);
// 检索查询条件
$filter = [];
// 关键词
if (!empty($params['searchValue'])) {
$searchWhere = [
10 => ['order.order_no', 'like', "%{$params['searchValue']}%"],
20 => ['user.nick_name', 'like', "%{$params['searchValue']}%"],
30 => ['order.user_id', '=', (int)$params['searchValue']],
40 => ['address.name', 'like', "%{$params['searchValue']}%"],
50 => ['address.phone', 'like', "%{$params['searchValue']}%"],
];
array_key_exists($params['searchType'], $searchWhere) && $filter[] = $searchWhere[$params['searchType']];
}
// 起止时间
if (!empty($params['betweenTime'])) {
$times = between_time($params['betweenTime']);
$filter[] = ['order.create_time', '>=', strtotime(date('Y-m-d',$times['start_time']))];
$filter[] = ['order.create_time', '<', strtotime(date('Y-m-d',$times['end_time'])) + 86400];
}
// 订单来源
$params['orderSource'] > -1 && $filter[] = ['order_source', '=', (int)$params['orderSource']];
// 支付方式
$params['payType'] > -1 && $filter[] = ['pay_type', '=', (int)$params['payType']];
// 一级代理商
$params['spread_uid'] > -1 && $filter[] = ['spread_uid', '=', (int)$params['spread_uid']];
// 支付状态
$params['pay_status'] > -1 && $filter[] = ['pay_status', '=', (int)$params['pay_status']];
// 分油状态
if($params['oil_status'] > -1){
$subQuery = Db::name('order_goods')
->where('oil_status', (int)$params['oil_status'])
->column('order_id'); // 获取所有符合条件的 order_id 数组
$filter[] = ['order.order_id', 'in', $subQuery];
}
// 使用状态
if($params['use_status'] > -1){
$subQuery = Db::name('order_goods')
->where('use_status', (int)$params['use_status'])
->column('order_id'); // 获取所有符合条件的 order_id 数组
$filter[] = ['order.order_id', 'in', $subQuery];
}
// 油卡编号
if($params['oilCardNo']){
$subQuery = Db::name('order_goods')
->where('oilCardNo', 'like', "%{$params['oilCardNo']}%")
->column('order_id'); // 获取所有符合条件的 order_id 数组
$filter[] = ['order.order_id', 'in', $subQuery];
}
// 分油记录编号
if($params['shareNo']){
$subQuery = Db::name('order_goods')
->where('shareNo', 'like', "%{$params['shareNo']}%")
->column('order_id'); // 获取所有符合条件的 order_id 数组
$filter[] = ['order.order_id', 'in', $subQuery];
}
// 配送方式
$params['deliveryType'] > -1 && $filter[] = ['delivery_type', '=', (int)$params['deliveryType']];
// 用户id
$params['userId'] > 0 && $filter[] = ['order.user_id', '=', (int)$params['userId']];
// 推广人ID
if($params['merchantId'] > 0) {
$filter[] = function ($query) use ($params) {
$query->where('order.spread_uid', '=', $params['merchantId'])
->whereOr('order.spread_two_uid', '=', $params['merchantId']);
};
}
return $filter;
}
/**
* 设置检索查询条件
* @param $query
*/
private function setWhere($query): array
{
$filter = [];
// $query['start_time'] = isset($query['start_time'])?$query['start_time']:strtotime(date("Y-m-d"));
// $query['end_time'] = isset($query['end_time'])?$query['end_time']:strtotime(date("Y-m-d"));
if (isset($query['start_time'])) {
!empty($query['start_time']) && $filter[] = ['create_time', '>=', $query['start_time']];
}
if (isset($query['end_time'])) {
!empty($query['end_time']) && $filter[] = ['create_time', '<', $query['end_time']+86400];
}
if (isset($query['order_status'])) {
!empty($query['order_status']) && $query['order_status'] != -1 && $filter[] = ['order_status', '=', $query['order_status']];
}
if (isset($query['merchant_id']) && !empty($query['merchant_id']) && $query['merchant_id'] != -1) {
$merchantId = $query['merchant_id'];
$filter[] = function ($query) use ($merchantId) {
$query->where('spread_uid', '=', $merchantId)
->whereOr('spread_two_uid', '=', $merchantId);
};
}
if (isset($query['oilCardType'])) {
!empty($query['oilCardType']) && $query['oilCardType'] != -1 && $filter[] = ['oilCardType', '=', $query['oilCardType']];
}
if (isset($query['saleOrderNo'])) {
!empty($query['saleOrderNo']) && $filter[] = ['saleOrderNo', 'like', '%' . trim($query['saleOrderNo']) . '%'];
}
if (isset($query['goodsNo'])) {
!empty($query['goodsNo']) && $filter[] = ['goodsNo', 'like', '%' . trim($query['goodsNo']) . '%'];
}
if (isset($query['userNo'])) {
!empty($query['userNo']) && $filter[] = ['userNo', 'like', '%' . trim($query['userNo']) . '%'];
}
if (isset($query['mobile'])) {
!empty($query['mobile']) && $filter[] = ['mobile', 'like', '%' . trim($query['mobile']) . '%'];
}
if (isset($query['oilCardNo'])) {
!empty($query['oilCardNo']) && $filter[] = ['oilCardNo', 'like', '%' . trim($query['oilCardNo']) . '%'];
}
if (isset($query['shareNo'])) {
!empty($query['shareNo']) && $filter[] = ['shareNo', 'like', '%' . trim($query['shareNo']) . '%'];
}
return $filter;
}
/**
* 设置订单类型条件
* @param string $dataType
* @return array
*/
private function getFilterDataType(string $dataType = self::LIST_TYPE_ALL): array
{
// 数据类型
$filter = [];
switch ($dataType) {
case self::LIST_TYPE_ALL:
$filter = [];
break;
case self::LIST_TYPE_DELIVERY:
$filter = [
['pay_status', '=', PayStatusEnum::SUCCESS],
['delivery_status', '=', DeliveryStatusEnum::NOT_DELIVERED],
['order_status', 'in', [OrderStatusEnum::NORMAL]]
];
break;
case self::LIST_TYPE_RECEIPT:
$filter = [
['pay_status', '=', PayStatusEnum::SUCCESS],
['delivery_status', '=', DeliveryStatusEnum::DELIVERED],
['receipt_status', '=', ReceiptStatusEnum::NOT_RECEIVED]
];
break;
case self::LIST_TYPE_PAY:
$filter[] = ['pay_status', '=', PayStatusEnum::PENDING];
$filter[] = ['order_status', '=', OrderStatusEnum::NORMAL];
break;
case self::LIST_TYPE_COMPLETE:
$filter[] = ['order_status', '=', OrderStatusEnum::COMPLETED];
break;
case self::LIST_TYPE_CANCEL:
$filter[] = ['order_status', '=', OrderStatusEnum::CANCELLED];
break;
case self::LIST_TYPE_OIL:
$filter[] = ['order_type', '=', 'zsy_ticket'];
break;
case self::LIST_TYPE_COUPON:
$filter[] = ['order_type', '=', 'coupon'];
break;
}
return $filter;
}
/**
* 确认发货(单独订单)
* @param $data
* @return bool|false
* @throws \Exception
*/
public function delivery($data): bool
{
// 转义为订单列表
$orderList = [$this];
// 验证订单是否满足发货条件
if (!$this->verifyDelivery($orderList)) {
return false;
}
// 整理更新的数据
$updateList = [[
'order_id' => $this['order_id'],
'express_id' => $data['express_id'],
'express_no' => $data['express_no']
]];
// 更新订单发货状态
$this->updateToDelivery($updateList);
// 获取已发货的订单
$completed = self::detail($this['order_id'], ['user', 'address', 'goods', 'express']);
// 发送消息通知
$this->sendDeliveryMessage([$completed]);
return true;
}
/**
* 确认发货后发送消息通知
* @param $orderList
* @return bool
*/
private function sendDeliveryMessage($orderList): bool
{
// 发送消息通知
foreach ($orderList as $item) {
MessageService::send('order.delivery', ['order' => $item], self::$storeId);
}
return true;
}
/**
* 更新订单发货状态(批量)
* @param $orderList
* @return bool
*/
private function updateToDelivery($orderList): bool
{
// 整理更新的数据
$data = [];
foreach ($orderList as $item) {
$data[] = [
'data' => [
'express_no' => $item['express_no'],
'express_id' => $item['express_id'],
'delivery_status' => 20,
'delivery_time' => time(),
],
'where' => ['order_id' => $item['order_id']]
];
}
// 批量更新
$this->updateAll($data);
return true;
}
/**
* 验证订单是否满足发货条件
* @param $orderList
* @return bool
*/
private function verifyDelivery($orderList): bool
{
foreach ($orderList as $order) {
if (
$order['pay_status'] != PayStatusEnum::SUCCESS
|| $order['delivery_type'] != DeliveryTypeEnum::EXPRESS
|| $order['delivery_status'] != DeliveryStatusEnum::NOT_DELIVERED
) {
$this->error = "订单号[{$order['order_no']}] 不满足发货条件!";
return false;
}
}
return true;
}
/**
* 修改订单价格
* @param array $data
* @return bool
*/
public function updatePrice(array $data): bool
{
if ($this['pay_status'] != PayStatusEnum::PENDING) {
$this->error = '该订单不合法';
return false;
}
// 实际付款金额
$payPrice = helper::bcadd($data['order_price'], $data['express_price']);
if ($payPrice <= 0) {
$this->error = '订单实付款价格不能为0.00元';
return false;
}
// 改价的金额差价
$updatePrice = helper::bcsub($data['order_price'], $this['order_price']);
// 更新订单记录
return $this->save([
'order_no' => $this->orderNo(), // 修改订单号, 否则微信支付提示重复
'pay_price' => $payPrice,
'update_price' => $updatePrice,
'express_price' => $data['express_price']
]) !== false;
}
/**
* 撤销分油,回收
* @param array $data
* @return bool
*/
public function cancelShare(array $data): bool
{
// 更新订单记录
return $this->save([
'order_status' => OrderStatusEnum::RECOVER
]) !== false;
}
/**
* 审核:用户取消订单
* @param array $data
* @return bool|mixed
*/
public function confirmCancel(array $data)
{
// 判断订单是否有效
if (
$this['pay_status'] != PayStatusEnum::SUCCESS
) {
$this->error = '该订单不合法';
return false;
}
// 订单取消事件
return $this->transaction(function () use ($data) {
if ($data['status']) {
// 执行退款操作
(new RefundService)->execute($this);
// 订单取消事件
OrderService::cancelEvent($this);
}
// 更新订单状态
return $this->save(['order_status' => $data['status'] ? OrderStatusEnum::CANCELLED : OrderStatusEnum::NORMAL]);
});
}
/**
* 将订单记录设置为已删除
* @return bool
*/
public function setDelete(): bool
{
return $this->save(['is_delete' => 1]) !== false;
}
/**
* 获取已付款订单总数 (可指定某天)
* @param null $startDate
* @param null $endDate
* @param array $user
* @return int
*/
public function getPayOrderTotal($startDate = null, $endDate = null, $user = []): int
{
$filter = [];
$filter[] = ['pay_status', '=', 20];
if (!is_null($startDate) && !is_null($endDate)) {
$filter[] = ['create_time', '>=', strtotime($startDate)];
$filter[] = ['create_time', '<', strtotime($endDate) + 86400];
}
if(!empty($user)) {
if(isset($user['is_super']) && $user['is_super'] == 0){
$filter[] = function ($query) use ($user) {
$query->where('spread_uid', '=', $user['merchant_id'])
->whereOr('spread_two_uid', '=', $user['merchant_id']);
};
}
}
return $this->getOrderTotal($filter);
}
/**
* 获取未发货订单数量
* @return int
*/
public function getNotDeliveredOrderTotal(): int
{
$filter = [
['pay_status', '=', PayStatusEnum::SUCCESS],
['delivery_status', '=', DeliveryStatusEnum::NOT_DELIVERED],
['order_status', 'in', [OrderStatusEnum::NORMAL]]
];
return $this->getOrderTotal($filter);
}
/**
* 获取未付款订单数量
* @return int
*/
public function getNotPayOrderTotal(): int
{
$filter = [
['pay_status', '=', PayStatusEnum::PENDING],
['order_status', '=', OrderStatusEnum::NORMAL]
];
return $this->getOrderTotal($filter);
}
/**
* 获取订单总数
* @param array $filter
* @return int
*/
public function getOrderTotal(array $filter = [], $query = []): int
{
// 获取订单总数量
// 检索查询
$search = $this->setWhere($query);
return $this->where(array_merge($filter,$search))
->count();
}
/**
* 获取总金额
* @param array $filter
* @param array $query
* @return float|int
*/
public function getOrderTotalMoney($filter=[], $query = [])
{
// 检索查询
$search = $this->setWhere($query);
return $this->where(array_merge($filter,$search))
->sum('pay_price');
}
/**
* 获取某天的总销售额
* @param null $startDate
* @param null $endDate
* @param array $user
* @return float
*/
public function getOrderTotalPrice($startDate = null, $endDate = null,$user=[]): float
{
// 查询对象
$query = $this->getNewQuery();
$filter = [];
// 设置查询条件
if (!is_null($startDate) && !is_null($endDate)) {
$filter[] = ['create_time', '>=', strtotime($startDate)];
$filter[] = ['create_time', '<', strtotime($endDate) + 86400];
}
if(!empty($user)) {
if(isset($user['is_super']) && $user['is_super'] == 0){
$filter[] = function ($query) use ($user) {
$query->where('spread_uid', '=', $user['merchant_id'])
->whereOr('spread_two_uid', '=', $user['merchant_id']);
};
}
}
// 总销售额
return $query->where('pay_status', '=', 20)
->where($filter)
->sum('pay_price');
}
/**
* 获取某天的下单用户数
* @param string $day
* @return float|int
*/
public function getPayOrderUserTotal(string $day)
{
$startTime = strtotime($day);
return $this->field('user_id')
->where('pay_time', '>=', $startTime)
->where('pay_time', '<', $startTime + 86400)
->where('pay_status', '=', PayStatusEnum::SUCCESS)
->where('is_delete', '=', '0')
->group('user_id')
->count();
}
/**
* 修改订单状态
* @param $data
* @return bool
*/
public function updateStatus($data)
{
if ($this['order_status'] == $data['status']) {
$this->error = '状态未做改变';
return false;
}
$field = [
'order_status' => $data['status'],
'buyer_remark' => $data['buyer_remark']
];
if($data['status'] == 20){
$field['pay_status'] = 20;
$field['pay_time'] = time();
}
return $this->save($field) !== false;
}
/**
* 订单超时修改
* @param $where
* @return bool
* @throws \app\common\exception\BaseException
* @throws \think\exception\DbException
*/
public function overtimeUpdate($where)
{
if (empty($where) || !is_array($where)) {
$this->error = '条件不合法';
return false;
}
return $this->where($where)->update(['order_status' => 30]) !== false;
}
/**
* 创建新订单
* @param array $order 订单信息
* @return bool
*/
public function addOil(array $order): bool
{
// 创建新的订单
$status = $this->transaction(function () use ($order) {
// 创建订单事件
return $this->createOrderEvent($order);
});
return $status;
}
/**
* 创建订单事件
* @param $order
* @return bool
* @throws BaseException
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
private function createOrderEvent($order): bool
{
// 新增订单记录
$status = $this->add($order);
// 保存订单商品信息
$this->saveOrderGoods($order);
return true;
}
/**
* 更新商品库存 (针对下单减库存的商品)
* @param $orderSource
* @param $goodsList
* @return void
*/
private function updateGoodsStockNum($orderSource, $goodsList): void
{
StockFactory::getFactory($orderSource)->updateGoodsStock($goodsList);
}
/**
* 新增订单记录
* @param $order
* @return bool|false
*/
private function add($order): bool
{
// 订单数据
$data = [
'user_id' => $order['user_id'],
'order_no' => $order['saleOrderNo'],
'total_price' => $order['amount'],
'order_price' => $order['amount'],
'coupon_id' => '',
'coupon_money' => '',
'points_money' => 0.00,
'points_num' => 0,
'pay_price' => $order['amount'],
'delivery_type' => 10,
'pay_type' => $order['payType'],
'buyer_remark' => $order['buyer_remark'],
'order_source' => 10,
'order_source_id' => '',
'points_bonus' => '',
'order_status' => OrderStatusEnum::NORMAL,
'platform' => '后台',
'store_id' => $order['store_id'],
'pay_status' => PayStatusEnum::SUCCESS,
'pay_time' => time()
];
// 保存订单记录
return $this->save($data);
}
/**
* 保存订单商品信息
* @param $order
* @return void
*/
private function saveOrderGoods($order): void
{
// 查找一个未被调用的用户
$goods = Db::name('goods')
->alias('goods')
->field('goods.*,yoshop_goods_image.image_id')
->where('goods.goods_id', '=', $order['goods_id'])
->join('yoshop_goods_image', 'goods.goods_id = yoshop_goods_image.goods_id')
->limit(1)
->find();
// 订单商品列表
$list[] = [
'province' => $order['province'],
'user_id' => $order['user_id'],
'account_id' => $order['account_id'],
'userNo' => $order['userNo'],
'mobile' => $order['mobile'],
'store_id' => $order['store_id'],
'goods_id' => $goods['goods_id'],
'goods_name' => $goods['goods_name'],
'oilCardType' => $order['oilCardType'],
'company_id' => $order['company_id'],
'oilCardNo' => $order['oilCardNo'],
'shareNo' => $order['shareNo'],
'goods_no' => $order['goodsNo'],
'image_id' => $goods['image_id'],
'deduct_stock_type' => 10,
'spec_type' => 10,
'goods_sku_id' => '',
'goods_props' => '',
'content' => '',
'goods_sku_no' => '',
'goods_price' => $order['amount'],
'line_price' => 0,
'goods_weight' => 0,
'is_user_grade' => 0,
'grade_ratio' => 0,
'grade_goods_price' => 0,
'grade_total_money' => 0,
'coupon_money' => 0,
'points_money' => 0.00,
'points_num' => 0,
'points_bonus' => 0,
'total_num' => 1,
'total_price' => $order['amount'],
'total_pay_price' => $order['amount']
];
$this->goods()->saveAll($list) !== false;
// 更新商品库存 (针对下单减库存的商品)
$this->updateGoodsStockNum(10, $list);
}
/**
* 修改订单状态
* @param $where
* @param $field
* @return false|int
*/
public static function orderUpdate($where, $field)
{
return (new static())->where($where)->update($field) !== false;
}
/**
* 获取一条记录
* @param array $filter
* @return array|null
*/
public static function getSingle(array $filter): ?array
{
$model = new static;
$data = $model->where($filter)->order(['order_id' => 'asc'])->find();
return $data ? $data->toArray() : null;
}
}