Order.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. namespace app\api\controller\invitation;
  3. use app\common\controller\Frontend;
  4. use app\common\service\CommissionService;
  5. use think\facade\Db;
  6. class Order extends Frontend
  7. {
  8. protected array $noNeedPermission = ['purchaseRecordsSimple','orderDetail'];
  9. protected $commissionService;
  10. public function initialize(): void
  11. {
  12. parent::initialize();
  13. $this->commissionService = new CommissionService();
  14. }
  15. /**
  16. * 获取用户购买记录(简化版)
  17. */
  18. public function purchaseRecordsSimple(): void
  19. {
  20. // 确保用户已登录
  21. if (!$this->auth->isLogin()) {
  22. $this->error('请先登录');
  23. }
  24. $userId = $this->auth->id;
  25. if (!$userId) {
  26. $this->error('用户ID获取失败');
  27. }
  28. // try {
  29. // 获取查询参数
  30. $page = $this->request->get('page', 1);
  31. $pageSize = $this->request->get('pageSize', 10);
  32. $status = $this->request->get('status', 'all'); // all, paid, unpaid
  33. // 构建查询条件
  34. $query = Db::table('ba_order')
  35. ->where('user_id', $userId);
  36. // 根据状态筛选
  37. if ($status === 'paid') {
  38. $query->where('pay_status', 1); // 已支付
  39. } elseif ($status === 'unpaid') {
  40. $query->where('pay_status', 0); // 未支付
  41. }
  42. // 获取订单总数
  43. $total = $query->count();
  44. // 获取订单列表(只取必要字段)
  45. $orders = $query->field('order_no, pay_amount, pay_method, pay_status, order_time, pay_time')
  46. ->order('order_time', 'desc')
  47. ->page($page, $pageSize)
  48. ->select()
  49. ->toArray();
  50. // 处理每个订单的商品信息
  51. $orderNos = array_column($orders, 'order_no');
  52. if (!empty($orderNos)) {
  53. // 批量查询订单商品
  54. $orderItems = \think\facade\Db::table('ba_order_item')
  55. ->where('order_id', 'IN', Db::table('ba_order')
  56. ->where('order_no', 'IN', $orderNos)
  57. ->column('id'))
  58. ->field('order_id, item_name, quantity, unit_price, total_price')
  59. ->select()
  60. ->toArray();
  61. // 按order_id分组商品
  62. $itemsByOrderId = [];
  63. foreach ($orderItems as $item) {
  64. $itemsByOrderId[$item['order_id']][] = $item;
  65. }
  66. // 获取订单ID映射
  67. $orderIdMap = \think\facade\Db::table('ba_order')
  68. ->where('order_no', 'IN', $orderNos)
  69. ->column('id', 'order_no');
  70. // 合并商品信息到订单
  71. foreach ($orders as &$order) {
  72. // 注意:现在 $orderIdMap 的键是 order_no,值是对应的 id
  73. $orderId = $orderIdMap[$order['order_no']] ?? 0;
  74. // 取第一个商品作为主商品信息(根据您的截图,一单一个商品)
  75. $mainItem = $itemsByOrderId[$orderId][0] ?? [];
  76. // 商品名称(如果有多个商品,显示第一个)
  77. $order['product_name'] = $mainItem['item_name'] ?? '商品';
  78. // 数量
  79. $order['quantity'] = $mainItem['quantity'] ?? 1;
  80. // 格式化显示字段
  81. $order['amount'] = '¥' . number_format($order['pay_amount'], 2);
  82. $order['pay_method_text'] = $this->getSimplePayMethodText($order['pay_method']);
  83. $order['pay_status_text'] = $order['pay_status'] == 1 ? '已支付' : '未支付';
  84. $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
  85. $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
  86. // 移除不需要的原始字段
  87. unset($order['pay_amount'], $order['pay_method'], $order['pay_status'],
  88. $order['order_time'], $order['pay_time']);
  89. }
  90. }
  91. // 获取简单的统计信息
  92. $stats = [
  93. 'total_orders' => $total,
  94. 'paid_orders' =>Db::table('ba_order')
  95. ->where('user_id', $userId)
  96. ->where('pay_status', 1)
  97. ->count(),
  98. 'unpaid_orders' =>Db::table('ba_order')
  99. ->where('user_id', $userId)
  100. ->where('pay_status', 0)
  101. ->count(),
  102. ];
  103. // } catch (\Throwable $e) {
  104. // \think\facade\Log::error('获取购买记录失败: ' . $e->getMessage());
  105. // $this->error('获取购买记录失败');
  106. // }
  107. $this->success('', [
  108. 'list' => $orders,
  109. 'total' => $total,
  110. 'page' => $page,
  111. 'page_size' => $pageSize,
  112. 'stats' => $stats
  113. ]);
  114. }
  115. /**
  116. * 简化支付方式文本
  117. */
  118. private function getSimplePayMethodText(string $method): string
  119. {
  120. $methodMap = [
  121. 'wechat' => '微信',
  122. 'alipay' => '支付宝',
  123. 'bank' => '银行卡'
  124. ];
  125. return $methodMap[$method] ?? '其他';
  126. }
  127. /**
  128. * 获取购买统计信息
  129. */
  130. private function getPurchaseStats(int $userId, string $status = 'all', string $startDate = '', string $endDate = ''): array
  131. {
  132. try {
  133. // 全部订单统计
  134. $totalQuery = \think\facade\Db::table('ba_order')
  135. ->where('user_id', $userId);
  136. // 已支付订单统计
  137. $paidQuery = \think\facade\Db::table('ba_order')
  138. ->where('user_id', $userId)
  139. ->where('pay_status', 1);
  140. // 时间范围筛选
  141. if (!empty($startDate)) {
  142. $totalQuery->where('order_time', '>=', $startDate);
  143. $paidQuery->where('order_time', '>=', $startDate);
  144. }
  145. if (!empty($endDate)) {
  146. $totalQuery->where('order_time', '<=', $endDate . ' 23:59:59');
  147. $paidQuery->where('order_time', '<=', $endDate . ' 23:59:59');
  148. }
  149. $totalCount = $totalQuery->count();
  150. $paidCount = $paidQuery->count();
  151. $unpaidCount = $totalCount - $paidCount;
  152. // 支付总金额
  153. $totalAmount = $paidQuery->sum('pay_amount');
  154. $totalAmount = $totalAmount ?: 0;
  155. // 本月统计
  156. $monthStart = date('Y-m-01');
  157. $monthPaidAmount = \think\facade\Db::table('ba_order')
  158. ->where('user_id', $userId)
  159. ->where('pay_status', 1)
  160. ->where('order_time', '>=', $monthStart)
  161. ->sum('pay_amount');
  162. $monthPaidAmount = $monthPaidAmount ?: 0;
  163. return [
  164. 'total_orders' => $totalCount,
  165. 'paid_orders' => $paidCount,
  166. 'unpaid_orders' => $unpaidCount,
  167. 'total_amount' => $totalAmount,
  168. 'month_amount' => $monthPaidAmount
  169. ];
  170. } catch (\Throwable $e) {
  171. \think\facade\Log::error('获取购买统计失败: ' . $e->getMessage());
  172. return [
  173. 'total_orders' => 0,
  174. 'paid_orders' => 0,
  175. 'unpaid_orders' => 0,
  176. 'total_amount' => 0,
  177. 'month_amount' => 0
  178. ];
  179. }
  180. }
  181. /**
  182. * 获取支付状态文本
  183. */
  184. private function getPayStatusText(int $status): string
  185. {
  186. $statusMap = [
  187. 0 => '待支付',
  188. 1 => '已支付',
  189. 2 => '支付失败'
  190. ];
  191. return $statusMap[$status] ?? '未知状态';
  192. }
  193. /**
  194. * 获取订单状态文本
  195. */
  196. private function getOrderStatusText(int $status): string
  197. {
  198. $statusMap = [
  199. 0 => '待处理',
  200. 1 => '已确认',
  201. 2 => '已发货',
  202. 3 => '已完成',
  203. 4 => '已取消'
  204. ];
  205. return $statusMap[$status] ?? '未知状态';
  206. }
  207. /**
  208. * 获取支付方式文本
  209. */
  210. private function getPayMethodText(string $method): string
  211. {
  212. $methodMap = [
  213. 'wechat' => '微信支付',
  214. 'alipay' => '支付宝',
  215. 'bank' => '银行卡',
  216. 'balance' => '余额支付'
  217. ];
  218. return $methodMap[$method] ?? '其他支付';
  219. }
  220. /**
  221. * 获取订单详情(单个订单)
  222. */
  223. public function orderDetail(): void
  224. {
  225. if (!$this->auth->isLogin()) {
  226. $this->error('请先登录');
  227. }
  228. $userId = $this->auth->id;
  229. $orderId = $this->request->get('order_id', 0);
  230. $orderNo = $this->request->get('order_no', '');
  231. if (empty($orderId) && empty($orderNo)) {
  232. $this->error('参数错误');
  233. }
  234. try {
  235. // 查询订单
  236. if ($orderId) {
  237. $order = \think\facade\Db::table('ba_order')
  238. ->where('id', $orderId)
  239. ->where('user_id', $userId) // 只能查看自己的订单
  240. ->find();
  241. } else {
  242. $order = \think\facade\Db::table('ba_order')
  243. ->where('order_no', $orderNo)
  244. ->where('user_id', $userId) // 只能查看自己的订单
  245. ->find();
  246. }
  247. if (!$order) {
  248. $this->error('订单不存在或无权查看');
  249. }
  250. // 获取订单商品项
  251. $orderItems = \think\facade\Db::table('ba_order_item')
  252. ->where('order_id', $order['id'])
  253. ->select()
  254. ->toArray();
  255. // 格式化显示数据
  256. $order['pay_status_text'] = $this->getPayStatusText($order['pay_status']);
  257. $order['order_status_text'] = $this->getOrderStatusText($order['order_status']);
  258. $order['pay_method_text'] = $this->getPayMethodText($order['pay_method']);
  259. // 格式化时间
  260. $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
  261. $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
  262. $order['complete_time_formatted'] = $order['complete_time'] ? date('Y-m-d H:i:s', strtotime($order['complete_time'])) : '';
  263. $order['create_time_formatted'] = $order['create_time'] ? date('Y-m-d H:i:s', strtotime($order['create_time'])) : '';
  264. } catch (\Throwable $e) {
  265. \think\facade\Log::error('获取订单详情失败: ' . $e->getMessage());
  266. $this->error('获取订单详情失败');
  267. }
  268. $this->success('', [
  269. 'order' => $order,
  270. 'items' => $orderItems
  271. ]);
  272. }
  273. /**
  274. * 订单支付成功回调(处理佣金)
  275. */
  276. public function paymentCallback(): void
  277. {
  278. if (!$this->request->isPost()) {
  279. $this->error('非法请求');
  280. }
  281. $orderId = $this->request->post('order_id', 0);
  282. $orderNo = $this->request->post('order_no', '');
  283. if (empty($orderId) && empty($orderNo)) {
  284. $this->error('参数错误');
  285. }
  286. try {
  287. // 查找订单
  288. if (!empty($orderId)) {
  289. $order = \think\facade\Db::table('ba_order')
  290. ->where('id', $orderId)
  291. ->find();
  292. } else {
  293. $order = \think\facade\Db::table('ba_order')
  294. ->where('order_no', $orderNo)
  295. ->find();
  296. }
  297. if (!$order) {
  298. $this->error('订单不存在');
  299. }
  300. // 处理订单佣金
  301. $result = $this->commissionService->processOrderCommission($order['id']);
  302. if ($result) {
  303. $this->success('佣金处理成功');
  304. } else {
  305. $this->error('佣金处理失败');
  306. }
  307. } catch (\Throwable $e) {
  308. $this->error('处理失败:' . $e->getMessage());
  309. }
  310. }
  311. /**
  312. * 手动触发订单佣金处理(管理用)
  313. */
  314. public function processCommission(): void
  315. {
  316. if (!$this->auth->isLogin() || !$this->auth->isAdmin()) {
  317. $this->error('权限不足');
  318. }
  319. $orderId = $this->request->post('order_id', 0);
  320. if ($orderId <= 0) {
  321. $this->error('订单ID错误');
  322. }
  323. $result = $this->commissionService->processOrderCommission($orderId);
  324. if ($result) {
  325. $this->success('处理成功');
  326. } else {
  327. $this->error('处理失败');
  328. }
  329. }
  330. }