HaniBlindBox/server/php/app/api/controller/FFOrdersController.php
2026-01-01 20:46:07 +08:00

708 lines
25 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace app\api\controller;
use app\api\controller\Base;
use app\common\model\FFProducts;
use app\common\model\UserAddress;
use app\common\model\CouponReceive;
use app\common\server\platform\PlatformFactory;
class FFOrdersController extends Base
{
public function createOrder()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
$product_id = $this->request->param('product_id', 0);
$address_id = $this->request->param('address_id', 0);
$coupon_id = $this->request->param('coupon_id', 0);
// $total_price = $this->request->param('total_price', 0);
if (empty($product_id) || empty($address_id)) {
return $this->renderError('缺少必要参数');
}
$product = FFProducts::where('id', $product_id)->find();
if (!$product) {
return $this->renderError('商品不存在');
}
$address = UserAddress::where('id', $address_id)->find();
if (!$address) {
return $this->renderError('地址不存在');
}
$coupon = null;
if ($coupon_id > 0) {
$coupon = CouponReceive::where('id', $coupon_id)->find();
if (!$coupon) {
return $this->renderError('优惠券不存在');
}
}
//$user, $price, $title, $attach, $pre = "MH_", $pay_type = 1, $client = null
$total_price = $product['price'];
if ($coupon) {
$total_price = $total_price - $coupon['price'];
}
$user = $this->getUser();
$payRes = PlatformFactory::createPay($user, $total_price, $product['product_name'], 'order_product', 'YS_', 1);
if ($payRes['status'] !== 1) {
return $this->renderError("购买失败,请稍后再试");
}
//使用优惠卷
if ($coupon) {
$coupon['status'] = 1;
$coupon->save();
}
# 订单号
$order_num = $payRes['data']['order_no'];
$receiver_name = $address['receiver_name'];
$receiver_phone = $address['receiver_phone'];
$receiver_address = $address['detailed_address'];
# 保存到ff_orders 表
$orderData = [
'order_no' => $order_num,
'user_id' => $user_id,
'product_id' => $product_id,
'total_amount' => $product['price'],
'payment_amount' => $total_price,
'discount_amount' => $coupon ? $coupon['price'] : 0,
'payment_type' => 1, // 假设这里是微信支付
'order_status' => 0, // 待支付
'pay_status' => 0, // 未支付
'shipping_status' => 0, // 未发货
'receiver_name' => $receiver_name,
'receiver_phone' => $receiver_phone,
'receiver_address' => $receiver_address,
'source' => 2, // APP来源
'create_time' => date('Y-m-d H:i:s')
];
// 将该用户的所有未支付订单状态变成已取消
\app\common\model\FFOrders::where([
'user_id' => $user_id,
'order_status' => 0, // 待支付
'pay_status' => 0 // 未支付
])->update([
'order_status' => 5, // 已取消
'cancel_time' => date('Y-m-d H:i:s') // 取消时间
]);
// 创建订单
$order = new \app\common\model\FFOrders();
$result = $order->save($orderData);
if (!$result) {
return $this->renderError('订单创建失败');
}
return $this->renderSuccess('订单创建成功', [
'order_no' => $order_num,
'user_info' => ['is_test' => $user['istest']],
'payment_data' => $payRes['data']['res']
]);
}
public function orderPaySuccess()
{
$order_no = $this->request->param('order_no', '');
if (empty($order_no)) {
return $this->renderError('订单号不能为空');
}
// 根据订单号查询订单
$order = \app\common\model\FFOrders::where('order_no', $order_no)->find();
if (!$order) {
return $this->renderError('订单不存在');
}
// 判断订单状态,避免重复处理
if ($order['pay_status'] == 2) {
return $this->renderSuccess('订单已支付', ['order_no' => $order_no]);
}
// 查询订单对应的商品信息
$product_id = $order['product_id'];
$product = FFProducts::where('id', $product_id)->find();
if (!$product) {
return $this->renderError('商品不存在');
}
// 开启事务
\think\facade\Db::startTrans();
try {
// 扣减库存
if ($product['stock'] > 0) {
$product->sales = $product['sales'] - 1; // 增加销量
$product->save();
} else {
throw new \Exception('商品库存不足');
}
// 更新订单状态
$order->order_status = 2; // 已支付待发货
$order->pay_status = 2; // 已支付
$order->shipping_status = 1; // 未发货
$order->shipping_company = '京东快递'; // 快递公司
$order->shipping_no = "TEST_" . time();//TEST_开头
$order->shipping_time = date('Y-m-d H:i:s'); // 发货时间
$order->payment_time = date('Y-m-d H:i:s'); // 支付时间
$order->payment_no = $this->request->param('payment_no', ''); // 支付流水号
// 保存订单
if (!$order->save()) {
throw new \Exception('订单状态更新失败');
}
// 提交事务
\think\facade\Db::commit();
return $this->renderSuccess('购买成功', [
'order_no' => $order_no,
'order_status' => $order->order_status,
'pay_status' => $order->pay_status
]);
} catch (\Exception $e) {
// 回滚事务
\think\facade\Db::rollback();
return $this->renderError('支付处理失败:' . $e->getMessage());
}
}
/**
* 获取订单列表
* @return \think\Response
*/
public function getOrderList()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收参数
$status = $this->request->param('status', 0); // 订单状态0表示全部
$keyword = $this->request->param('keyword', ''); // 商品标题搜索关键词
$page = (int) $this->request->param('page', 1);
$limit = (int) $this->request->param('limit', 10);
// 构建查询条件
$where = [
'user_id' => $user_id,
'delete_status' => 0
];
// 初始化查询对象
$query = \app\common\model\FFOrders::alias('o');
// 根据状态筛选
if ($status > 0) {
if ($status == 4) {
// 当status为4时查询状态为6和7的订单申请售后和退款售后成功
$query = $query->where($where)
->where('o.order_status', 'in', [6, 7]);
} else {
// 其他状态正常查询
$query = $query->where($where)
->where('o.order_status', $status);
}
} else {
// status为0时查询所有订单
$query = $query->where($where);
}
// 如果有搜索关键词,则需要联表查询
if (!empty($keyword)) {
// 通过product_id关联FFProducts表
$query = $query->join('ff_products p', 'o.product_id = p.id')
->where('p.product_name', 'like', "%{$keyword}%");
}
// 排序方式 - 最新订单在前
$query = $query->order('o.create_time desc');
// 分页查询
$count = $query->count();
$list = $query->page($page, $limit)->select();
// 处理结果
$result = [];
foreach ($list as $order) {
// 获取商品信息
$product = \app\common\model\FFProducts::where('id', $order['product_id'])->find();
$item = [
'order_id' => $order['order_id'],
'order_no' => $order['order_no'],
'product_id' => $product ? $product['id'] : '', //
'product_cover' => $product ? $product['cover_image'] : '', // 商品封面图
'product_title' => $product ? $product['product_name'] : '', // 商品标题
'payment_amount' => $order['payment_amount'], // 支付金额
'payment_time' => $order['payment_time'] ?: '', // 支付时间
'order_status' => $order['order_status'], // 订单状态
'order_status_text' => $this->getOrderStatusText($order['order_status']), // 订单状态文本
'create_time' => $order['create_time'], // 创建时间
'receive_time' => $order['receive_time'] ?: '', // 收货时间
'is_invoice' => $order['invoice_title'] == '' ? 0 : 1, // 是否开票
];
$result[] = $item;
}
return $this->renderSuccess('获取成功', [
'total' => $count,
'page' => $page,
'limit' => $limit,
'list' => $result
]);
}
/**
* 获取订单状态文本
* @param int $status 订单状态
* @return string 状态文本
*/
private function getOrderStatusText($status)
{
$statusArr = [
0 => '待支付',
1 => '已支付待发货',
2 => '已发货',
3 => '已完成',
4 => '已关闭',
5 => '已取消',
6 => '申请售后',
7 => '售后结束'
];
return isset($statusArr[$status]) ? $statusArr[$status] : '未知状态';
}
/**
* 订单收货接口
* @return \think\Response
*/
public function orderReceive()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收订单编号参数
$order_no = $this->request->param('order_no', '');
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 判断订单状态是否为已发货
if ($order['order_status'] != 2) {
return $this->renderError('只有已发货的订单才能确认收货');
}
// 更新订单状态和收货时间
$order->order_status = 3; // 已完成
$order->receive_time = date('Y-m-d H:i:s'); // 收货时间
// 保存订单
if ($order->save()) {
return $this->renderSuccess('确认收货成功', [
'order_no' => $order_no,
'order_status' => $order->order_status,
'order_status_text' => $this->getOrderStatusText($order->order_status),
'receive_time' => $order->receive_time
]);
} else {
return $this->renderError('确认收货失败');
}
}
/**
* 申请售后接口
* @return \think\Response
*/
public function applyRefund()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收参数
$order_no = $this->request->param('order_no', '');
$extend_info = $this->request->param('extend_info', '');
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 判断订单状态是否可申请售后
if ($order['order_status'] == 0 || $order['order_status'] == 4 || $order['order_status'] == 5 || $order['order_status'] == 6 || $order['order_status'] == 7) {
return $this->renderError('当前订单状态不可申请售后');
}
try {
// 将当前订单状态保存到扩展信息中
$extendData = json_decode($extend_info, true) ?: [];
$extendData['original_status'] = $order['order_status'];
// 更新订单状态和扩展信息
$order->order_status = 6; // 申请退款
$order->extend_info = json_encode($extendData);
// 保存订单
if ($order->save()) {
return $this->renderSuccess('申请售后成功', [
'order_no' => $order_no,
'order_status' => $order->order_status,
'order_status_text' => $this->getOrderStatusText($order->order_status)
]);
} else {
return $this->renderError('申请售后失败');
}
} catch (\Exception $e) {
return $this->renderError('申请售后失败:' . $e->getMessage());
}
}
/**
* 取消售后接口
* @return \think\Response
*/
public function cancelRefund()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收参数
$order_no = $this->request->param('order_no', '');
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 判断订单状态是否为申请退款
if ($order['order_status'] != 6) {
return $this->renderError('只有申请退款状态的订单才能取消售后');
}
try {
// 从扩展信息中读取原始状态
$extendInfo = $order['extend_info'] ? json_decode($order['extend_info'], true) : [];
$originalStatus = isset($extendInfo['original_status']) ? $extendInfo['original_status'] : 3; // 默认为已完成
// 移除原始状态信息
if (isset($extendInfo['original_status'])) {
unset($extendInfo['original_status']);
}
// 更新订单状态和扩展信息
$order->order_status = $originalStatus;
$order->extend_info = !empty($extendInfo) ? json_encode($extendInfo) : '';
// 保存订单
if ($order->save()) {
return $this->renderSuccess('取消售后成功', [
'order_no' => $order_no,
'order_status' => $order->order_status,
'order_status_text' => $this->getOrderStatusText($order->order_status)
]);
} else {
return $this->renderError('取消售后失败');
}
} catch (\Exception $e) {
return $this->renderError('取消售后失败:' . $e->getMessage());
}
}
/**
* 删除订单接口
* @return \think\Response
*/
public function deleteOrder()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收订单编号参数
$order_no = $this->request->param('order_no', '');
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id,
'delete_status' => 0 // 未删除的订单
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 判断订单状态是否可删除
// 通常只有已完成(3)、已关闭(4)、已取消(5)、退款成功(7)的订单可以删除
$allowDeleteStatus = [3, 4, 5, 7];
if (!in_array($order['order_status'], $allowDeleteStatus)) {
return $this->renderError('当前订单状态不允许删除');
}
try {
// 更新订单删除状态
$order->delete_status = 1; // 标记为已删除
// 保存订单
if ($order->save()) {
return $this->renderSuccess('订单删除成功');
} else {
return $this->renderError('订单删除失败');
}
} catch (\Exception $e) {
return $this->renderError('订单删除失败:' . $e->getMessage());
}
}
/**
* 获取订单详情接口
* @return \think\Response
*/
public function getOrderDetail()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收订单编号参数
$order_no = $this->request->param('order_no', '');
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id,
'delete_status' => 0 // 未删除的订单
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 查询关联商品
$product = \app\common\model\FFProducts::where('id', $order['product_id'])->find();
// 组装订单详情数据
$orderDetail = [
// 商品信息
'product_id' => $product ? $product['id'] : '',
'product_cover' => $product ? $product['cover_image'] : '',
'product_title' => $product ? $product['product_name'] : '',
'product_price' => $product ? $product['price'] : 0.00,
// 订单信息
'order_id' => $order['order_id'],
'order_no' => $order['order_no'],
'total_amount' => $order['total_amount'], // 订单总金额
'payment_amount' => $order['payment_amount'], // 实际支付金额
'discount_amount' => $order['discount_amount'], // 优惠金额
'shipping_fee' => $order['shipping_fee'], // 运费
'order_status' => $order['order_status'],
'order_status_text' => $this->getOrderStatusText($order['order_status']),
'pay_status' => $order['pay_status'],
'payment_type' => $order['payment_type'], // 支付方式
// 物流信息
'shipping_company' => $order['shipping_company'] ?: '',
'shipping_no' => $order['shipping_no'] ?: '',
'create_time' => $order['create_time'], // 下单时间
'shipping_time' => $order['shipping_time'] ?: '', // 发货时间
'receive_time' => $order['receive_time'] ?: '', // 收货时间
'payment_time' => $order['payment_time'] ?: '', // 支付时间
// 收货人信息
'receiver_name' => $order['receiver_name'],
'receiver_phone' => $order['receiver_phone'],
'receiver_address' => $order['receiver_address'],
// 发票信息
'invoice_title' => $order['invoice_title'] ?: '',
'invoice_content' => $order['invoice_content'] ?: '',
'invoice_type' => $order['invoice_type'],
'invoice_type_text' => $order['invoice_type'] == 1 ? '个人' : ($order['invoice_type'] == 2 ? '企业' : ''),
// 扩展信息
'extend_info' => $order['extend_info'] ? json_decode($order['extend_info'], true) : []
];
return $this->renderSuccess('获取成功', $orderDetail);
}
/**
* 申请发票接口
* @return \think\Response
*/
public function applyInvoice()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
// 接收参数
$order_no = $this->request->param('order_no', '');
$invoice_title = $this->request->param('invoice_title', '');
$invoice_content = $this->request->param('invoice_content', '');
$invoice_type = (int) $this->request->param('invoice_type', 1); // 默认个人
$user_email = $this->request->param('user_email', ''); // 用户邮箱,不存储
// 参数验证
if (empty($order_no)) {
return $this->renderError('订单编号不能为空');
}
if (empty($invoice_title)) {
return $this->renderError('发票抬头不能为空');
}
if (empty($invoice_content)) {
return $this->renderError('发票内容不能为空');
}
if (!in_array($invoice_type, [1, 2])) {
return $this->renderError('发票类型不正确');
}
if (empty($user_email)) {
return $this->renderError('用户邮箱不能为空');
}
// 邮箱格式验证
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
return $this->renderError('邮箱格式不正确');
}
// 查询订单
$order = \app\common\model\FFOrders::where([
'order_no' => $order_no,
'user_id' => $user_id,
'delete_status' => 0 // 未删除的订单
])->find();
if (!$order) {
return $this->renderError('订单不存在或不属于当前用户');
}
// 验证订单状态,通常只有已支付的订单才能申请发票
if ($order['pay_status'] != 2) { // 2表示已支付
return $this->renderError('只有已支付的订单才能申请发票');
}
try {
// 更新订单发票信息
$order->invoice_title = $invoice_title;
$order->invoice_content = $invoice_content;
$order->invoice_type = $invoice_type;
// 保存订单
if ($order->save()) {
return $this->renderSuccess('发票申请成功', true);
} else {
return $this->renderError('发票申请失败');
}
} catch (\Exception $e) {
return $this->renderError('发票申请失败:' . $e->getMessage());
}
}
/**
* 获取用户订单统计数据
* @return \think\Response
*/
public function getOrderStatistics()
{
$user_id = $this->getUserId();
if (!$user_id) {
return $this->renderError('请先登录');
}
try {
// 查询条件 - 用户ID和未删除
$where = [
'user_id' => $user_id,
'delete_status' => 0
];
// 查询待发货订单数量 - 订单状态为1已支付待发货
$waitingShipCount = \app\common\model\FFOrders::where($where)
->where('order_status', 1)
->count();
// 查询待收货订单数量 - 订单状态为2已发货
$waitingReceiveCount = \app\common\model\FFOrders::where($where)
->where('order_status', 2)
->count();
// 查询已收货订单数量 - 订单状态为3已完成
$receivedCount = \app\common\model\FFOrders::where($where)
->where('order_status', 3)
->count();
// 查询申请售后订单数量 - 订单状态为6申请售后和7售后结束
$afterSalesCount = \app\common\model\FFOrders::where($where)
->where('order_status', 'in', [6])
->count();
// 返回统计结果
return $this->renderSuccess('获取成功', [
'waiting_ship_count' => $waitingShipCount, // 待发货数量
'waiting_receive_count' => $waitingReceiveCount, // 待收货数量
'received_count' => $receivedCount, // 已收货数量
'after_sales_count' => $afterSalesCount // 申请售后数量
]);
} catch (\Exception $e) {
return $this->renderError('获取订单统计数据失败:' . $e->getMessage());
}
}
}