Order.php 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
<?php

namespace app\admin\controller\groupon\order;

use addons\groupon\library\Export;
use addons\groupon\model\Config as ModelConfig;
use app\admin\model\groupon\order\OrderExpress;
use think\Db;
use think\Config;
use app\common\controller\Backend;
use app\admin\controller\groupon\Base;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Base
{
    protected $noNeedRight = ['getType', 'getExpress'];

    /**
     * Order模型对象
     * @var \app\admin\model\groupon\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        // 手动加载语言包
        $this->loadlang('groupon/order/order_item');
        $this->loadlang('groupon/goods/goods');

        $this->model = new \app\admin\model\groupon\order\Order;
        $this->storeModel = new \app\admin\model\groupon\store\Store;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("platformList", $this->model->getPlatformList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $nobuildfields = ['status', 'nickname', 'user_phone', 'goods_title'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $total = $this->buildSearchOrder()
                ->where($where)
                ->removeOption('soft_delete')
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearchOrder()
                ->where($where)
                ->with(['user', 'item', 'store'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            $list = collection($list)->toArray();
            $items = [];
            foreach ($list as $key => $od) {
                // 处理 未支付订单 的 订单 item status_code 状态
                $list[$key] = $this->model->setOrderItemStatusByOrder($od);
            }

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }


    public function export()
    {
        $nobuildfields = ['status', 'nickname', 'user_phone', 'goods_title'];
        list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);


        $expCellName = [
            'order_id' => 'Id',
            'order_sn' => '订单号',
            'status_text' => '订单状态',
            'pay_type_text' => '支付类型',
            'paytime_text' => '支付时间',
            'user_nickname' => '用户姓名',
            'user_phone' => '手机号',
            'store_info' => '门店信息',
            'total_amount' => '订单总金额',
            'discount_fee' => '优惠金额',
            'pay_fee' => '实际支付金额',
            'consignee_info' => '收货信息',
            'remark' => '用户备注',
            'activity_type_text' => '营销类型',
            'goods_title' => '商品名称',
            'goods_original_price' => '商品原价',
            'goods_price' => '商品价格',
            'goods_sku_text' => '商品规格',
            'goods_num' => '购买数量',
            'dispatch_status_text' => '发货状态',
            'refund_status' => '退款状态',
            'comment_status_text' => '评价状态',
            'refund_fee' => '退款金额',
            'refund_msg' => '退款原因',
        ];

        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->buildSearchOrder()->where($where)->order($sort, $order)->count();
        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        $newList = [];
        $total_amount = 0;      // 订单总金额
        $discount_fee = 0;      // 优惠总金额
        $pay_fee = 0;      // 实际支付总金额

        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;

            $list = $this->buildSearchOrder()
                ->where($where)
                ->with(['user', 'item', 'store'])
                ->order($sort, $order)
                ->limit(($i * $page_size), $page_size)
                ->select();

            $list = collection($list)->toArray();
            foreach ($list as $key => $od) {
                // 处理 未支付订单 的 订单 item status_code 状态
                $list[$key] = $this->model->setOrderItemStatusByOrder($od);
            }

            $newList = [];
            foreach ($list as $key => $ord) {
                $data = [
                    'order_id' => $ord['id'],
                    'order_sn' => $ord['order_sn'],
                    'status_text' => $ord['status_text'],
                    'pay_type_text' => $ord['pay_type_text'],
                    'paytime_text' => $ord['paytime_text'],
                    'user_nickname' => $ord['user'] ? $ord['user']['nickname'] : '',
                    'user_phone' => $ord['user'] ? $ord['user']['mobile'] . ' ' : '',
                    'store_info' => $ord['store'] ? $ord['store']['name'] : '',
                    'total_amount' => $ord['total_amount'],
                    'discount_fee' => $ord['discount_fee'],
                    'pay_fee' => $ord['pay_fee'],
                    'consignee_info' => ($ord['consignee'] ? ($ord['consignee'] . '-' . $ord['phone']) : ''),
                    'remark' => $ord['remark']
                ];
                foreach ($ord['item'] as $k => $item) {
                    $itemData = [
                        'activity_type_text' => $item['activity_type_text'],
                        'goods_title' => $item['goods_title'],
                        'goods_original_price' => $item['goods_original_price'],
                        'goods_price' => $item['goods_price'],
                        'goods_sku_text' => $item['goods_sku_text'],
                        'goods_num' => $item['goods_num'],
                        'dispatch_status_text' => $item['dispatch_status_text'],
                        'refund_status' => $item['refund_status_text'],
                        'comment_status_text' => $item['comment_status_text'],
                        'refund_fee' => $item['refund_fee'],
                        'refund_msg' => $item['refund_msg'],
                    ];

                    $newList[] = array_merge($data, $itemData);
                }

                $total_amount += $ord['total_amount'];      // 订单总金额
                $discount_fee += $ord['discount_fee'];      // 优惠总金额
                $pay_fee += $ord['pay_fee'];      // 实际支付总金额
            }
        }

        if ($is_last_page) {
            $newList[] = [
                'order_id' => "订单总数:" . $total . ";订单总金额:¥" . $total_amount . ";优惠总金额:¥" . $discount_fee . ";实际支付总金额:¥" . $pay_fee . ";"
            ];
        }

        $current_total += count($newList);     // 当前循环总条数

        $export->exportExcel('订单列表-' . date('Y-m-d H:i:s'), $expCellName, $newList, $spreadsheet, $sheet, [
            'page' => $page,
            'page_size' => $page_size,      // 如果传了 current_total 则 page_size 就不用了
            'current_total' => $current_total,      // page_size 是 order 的,但是 newList 其实是 order_item 的
            'is_last_page' => $is_last_page
        ]);
    }


    // 获取要查询的订单类型
    public function getType()
    {
        $pay_type = $this->model->getPayTypeList();
        $platform = $this->model->getPlatformList();

        $result = [
            'pay_type' => $pay_type,
            'platform' => $platform,
        ];

        $data = [];
        foreach ($result as $key => $list) {
            $data[$key][] = ['name' => '全部', 'type' => 'all'];

            foreach ($list as $k => $v) {
                $data[$key][] = [
                    'name' => $v,
                    'type' => $k
                ];
            }
        }

        return $this->success('操作成功', null, $data);
    }


    public function detail($id)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->withTrashed()->with(['user', 'item', 'store'])->where('id', $id)->find();
            if (!$row) {
                $this->error(__('No Results were found'));
            }
    
            // 处理未支付 item status_code
            $row = $this->model->setOrderItemStatusByOrder($row);

            return $this->success('获取成功', null, [
                'order' => $row,
                'item' => $row['item'],
                'store' => $row['store'],
            ]);
        }

        $this->assignconfig('id', $id);
        return $this->view->fetch();
    }


    /**
     * 同意退款
     */
    public function refund($id = 0, $item_id = 0)
    {
        if ($this->request->isAjax()) {
            $refund_money = round($this->request->post('refund_money', 0), 2);

            if ($refund_money <= 0) {
                $this->error('退款金额必须大于 0');
            }

            $order = $this->model->where('status', 'in', [
                    \app\admin\model\groupon\order\Order::STATUS_PAYED,
                    \app\admin\model\groupon\order\Order::STATUS_FINISH
                ]
            )
            ->with('item')->where('id', $id)->find();

            if (!$order) {
                $this->error('订单不存在或不可退款');
            }

            $items = $order->item;
            $items = array_column($items, null, 'id');

            // 当前订单已退款总金额
            $refunded_money = array_sum(array_column($items, 'refund_fee'));
            // 剩余可退款金额
            $refund_surplus_money = $order->pay_fee - $refunded_money;
            // 如果退款金额大于订单支付总金额
            if ($refund_money > $refund_surplus_money) {
                $this->error('退款总金额不能大于实际支付金额');
            }

            if ($item_id) {
                $item = $items[$item_id];
                if (!$item || in_array($item['refund_status'], [
                    \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_OK,
                    \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_FINISH,
                ])) {
                    $this->error('订单商品已退款,不能重复退款');
                }
            } else {
                $is_refund = false;
                foreach ($items as $key => $it) {
                    if (in_array($it['refund_status'], [
                        \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_OK,
                        \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_FINISH,
                    ])) {
                        // 已退款
                        unset($items[$key]);
                    } else {
                        $is_refund = true;
                    }
                }
                $items = array_values($items);

                if (!$is_refund) {
                    $this->error('订单已退款,不能重复退款');
                }
            }

            Db::transaction(function () use ($order, $items, $item_id, $refund_money, $refund_surplus_money) {
                if ($item_id) {
                    // 单个商品退款
                    $item = $items[$item_id];
                    \app\admin\model\groupon\order\Order::startRefund($order, $item, $refund_money, $this->auth->getUserInfo(), '管理员操作退款');
                } else {
                    // 全部退款
                    // 未退款 item 商品总金额
                    $goods_total_amount = 0;
                    foreach ($items as $ke => $it) {
                        $goods_total_amount += ($it['goods_price'] * $it['goods_num']);
                    }

                    $current_refunded_money = 0;
                    for($i = 0; $i < count($items); $i ++) {
                        if ($i == (count($items) - 1)) {
                            // 最后一条,全部退完
                            $current_refund_money = $refund_money - $current_refunded_money;
                        } else {
                            // 按比例计算当前 item 应退金额
                            $current_refund_money = round($refund_money * (($items[$i]['goods_price'] * $it['goods_num']) / $goods_total_amount), 2);
                        }
                        if (($current_refunded_money + $current_refund_money) > $refund_money) {
                            $current_refund_money = $refund_money - $current_refunded_money;
                        }

                        if ($current_refund_money > 0) {
                            $current_refunded_money += $current_refund_money;

                            \app\admin\model\groupon\order\Order::startRefund($order, $items[$i], $current_refund_money, $this->auth->getUserInfo(), '管理员操作退款');
                        }
                    }
                }
            });

            $item_list = \app\admin\model\groupon\order\OrderItem::where(['order_id' => $id])->select();
            return $this->success('操作成功', null, $item_list);
        }
    }


    // 取消订单
    public function cancel($id)
    {
        if ($this->request->isAjax()) {
            $order = $this->model->where('id', $id)->nopay()->find();
            if (!$order) {
                $this->error('订单不存在或已取消');
            }

            $order = $order->doCancel($order, $this->auth->getUserInfo(), 'admin');

            return $this->success('操作成功', null, $order);
        }
    }


    // 修改收货人信息
    public function editConsignee($id)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post();
            extract($params);

            $row = $this->model->get($id);
            if (!$row) {
                $this->error('订单不存在');
            }

            try {
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }

                $result = $row->save([
                    'consignee' => $consignee,
                    'phone' => $phone,
                ], ['id' => $id]);

            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                $this->error($e->getMessage());
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $order = $this->model->with('user')->where('id', $id)->find();
                $this->success('修改成功', null, $order);
            } else {
                $this->error(__('No rows were updated'));
            }
        }
    }


    // 编辑商家备注
    public function editMemo($id)
    {
        if ($this->request->isAjax()) {
            $memo = $this->request->post('memo');

            $order = $this->model->get($id);
            if (!$order) {
                $this->error('订单不存在');
            }

            $order->memo = $memo;
            $order->save();

            \addons\groupon\model\OrderAction::operAdd($order, null, $this->auth->getUserInfo(), 'admin', "修改备注:" . $memo);

            return $this->success('操作成功', null, $order);
        }
    }


    // 获取订单操作记录
    public function actions($id)
    {
        $actions = \app\admin\model\groupon\order\OrderAction::with('oper')->where('order_id', $id)->select();

        foreach ($actions as $key => $action) {
            $action = $action->toArray();
            if ($action['oper_type'] == 'admin') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => $action['oper'] ? $action['oper']['nickname'] : ''
                ];
            } else if ($action['oper_type'] == 'user') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => '用户'
                ];
            } else if ($action['oper_type'] == 'system') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => '系统'
                ];
            } else {
                $oper = null;
            }

            $action['oper'] = $oper;
            $actions[$key] = $action;
        }

        return $this->success('操作成功', null, $actions);
    }


    // 构建查询条件
    private function buildSearchOrder()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $status = isset($filter['status']) ? $filter['status'] : 'all';
        $nickname = isset($filter['nickname']) ? $filter['nickname'] : '';
        $mobile = isset($filter['user_phone']) ? $filter['user_phone'] : '';
        $goods_title = isset($filter['goods_title']) ? $filter['goods_title'] : '';

        $name = $this->model->getQuery()->getTable();
        $tableName = $name . '.';

        $orders = $this->model->withTrashed();

        if ($nickname || $mobile) {
            $orders = $orders->whereExists(function ($query) use ($nickname, $mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();

                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . 'user_id');

                if ($nickname) {
                    $query = $query->where('nickname', 'like', "%{$nickname}%");
                }

                if ($mobile) {
                    $query = $query->where('mobile', 'like', "%{$mobile}%");
                }

                return $query;
            });
        }
        
        // 快递方式 || 商品类型 (同一个表,写在一起)
        if ($goods_title) {
            $orders = $orders->whereExists(function ($query) use ($goods_title, $tableName) {
                $itemTableName = (new \app\admin\model\groupon\order\OrderItem())->getQuery()->getTable();

                $query = $query->table($itemTableName)->where($itemTableName . '.order_id=' . $tableName . 'id');

                if ($goods_title) {
                    $query = $query->where('goods_title', 'like', "%{$goods_title}%");
                }

                return $query;
            });
        }

        // 订单状态
        if ($status != 'all') {
            if (in_array($status, ['invalid', 'cancel', 'nopay', 'nosend', 'noarrive', 'noget', 'sends', 'nocomment', 'refund', 'payed', 'finish'])) {
                if (in_array($status, ['nosend', 'noarrive', 'noget', 'sends', 'nocomment', 'refund'])) {
                    $orders = $orders->payed();
                }

                $status = $status == 'refund' ? 'refundStatus' : $status;    

                // 所有订单
                $orders = $orders->{$status}();
            }
        }

        return $orders;
    }
}