allocatr/application/admin/controller/orders/Dispatch.php
2025-07-15 12:42:26 +08:00

349 lines
12 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
namespace app\admin\controller\orders;
use app\admin\model\Order;
use app\admin\model\OrderDispatch;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
/**
* 派单列管理
*
* @icon fa fa-circle-o
*/
class Dispatch extends Backend
{
/**
* OrderDispatch模型对象
* @var \app\admin\model\OrderDispatch
*/
protected $model = null;
protected $searchFields = 'order.order_no,order.tel,order.customer,worker_name,worker_tel';
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\OrderDispatch;
$this->view->assign("typeList", $this->model->getTypeList());
$this->view->assign("statusList", $this->model->getStatusList());
}
/**
* 默认生成的控制器所继承的父类中有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();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['order'])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as &$row) {
$row->btn_edit = (in_array($row->status, $this->model->btnActiveStatusList('btn_edit'))) ? true : false;
$row->btn_cancel = (in_array($row->status, $this->model->btnActiveStatusList('btn_cancel'))) ? true : false;
$row->btn_abnormal = (in_array($row->status, $this->model->btnActiveStatusList('btn_abnormal'))) ? true : false;
// $row->btn_income = (in_array($row->status, $this->model->btnActiveStatusList('btn_income')) && in_array($row->order->status, $orderModel->incomeBtnStatus())) ? true : false;
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*
* @return string
* @throws \think\Exception
*/
public function add()
{
if (false === $this->request->isPost()) {
$id = $this->request->param('order_id');
$order = model('order')->where('id', $id)->find();
if (!$order) {
$this->error(__('No results were found'));
}
$items = Db::name('item')
->where('status', 1)
->field(['id', 'title', 'key_word', 'pid'])
->order('pid', 'asc')
->order('sort', 'desc')
->select();
$tree = $this->buildTree($items);
$formattedTree = $this->formatTree($tree);
$area_name = model('area')->getNameByCode($order->area_id);
// dd($area_name);
$order->area_name = str_replace(',', '/', $area_name);
$this->view->assign('items', $formattedTree);
$this->view->assign('row', $order);
return $this->view->fetch();
}
// dd(1);
$params = $this->request->post('row/a');
// $this->success();
if (empty($params)) {
$params = $this->request->post();
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
}
$params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException()->validate($validate);
}
$order = model('order')->where('id', $params['order_id'])->find();
if (!$order) {
$this->error(__('No results were found'));
}
//判断 是否存在有效派单任务
$existDispatch = OrderDispatch::where('order_id', $params['order_id'])->where('status', '>=',0)->count();
if($existDispatch > 0){
$this->error('该订单已经派单,不可重复操作');
}
$insert = [
'admin_id' => $this->auth->id,
'admin_user' => $this->auth->nickname,
'order_id' => $params['order_id'],
'type' => 1,
'worker_id' => $params['worker_id'],
'plan_time' => $order['plan_time'],
'is_receipt' => $order['receive_type'] == 1
];
$worker = model('worker')->where('id', $params['worker_id'])->find();
$insert ['worker_name'] = $worker->name;
$insert ['worker_tel'] = $worker->tel;
$result = $this->model->allowField(true)->save($insert);
$order->status = Order::STATUS_DISPATCHED;
$order->dispatch_time = date('Y-m-d H:i:s');
$order->dispatch_admin_id = $this->auth->id;
$order->worker_id = $worker->id;
$order->dispatch_admin_user = $this->auth->nickname;
$order->save();
$auth = clone $this->auth;
//order log
$hookparams['order'] = $order;
$hookparams['role'] = 1;
$hookparams['auth'] = $auth;
$hookparams['remark'] = '手动完成派单';
Hook::listen('order_change', $hookparams);
$dispatch = $this->model->get($this->model->id);
$groups = $this->auth->getGroups($this->auth->id);
$groupName = '';
if(!empty($groups)){
$groupNames = array_column($groups,'name');
$groupName = implode(',',$groupNames);
}
$dispatch->admin_user = $groupName."".$this->auth->nickname;
//dispatch log
$hookParams2 = [
'dispatch' => $dispatch,
'remark' => '手动派单给工程师:' . $worker->name .'('.$worker->tel.')',
];
Hook::listen('order_dispatch_change', $hookParams2);
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
sleep(2);
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
}
/**
* 编辑
*
* @param $ids
* @return string
* @throws DbException
* @throws \think\Exception
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if (false === $this->request->isPost()) {
$this->view->assign('row', $row);
return $this->view->fetch();
}
$params = $this->request->post('row/a');
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
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()->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if (false === $result) {
$this->error(__('No rows were updated'));
}
$this->success();
}
/**
* 取消派单
*
* @param $ids
* @return void
* @throws DbException
* @throws DataNotFoundException
* @throws ModelNotFoundException
*/
public function del($ids = null)
{
if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ?: $this->request->post("ids");
if (empty($ids)) {
$this->error(__('Parameter %s can not be empty', 'ids'));
}
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->whereIn('status', $this->model->deleteStatusList())->select();
$remark = $this->request->param('remark', '');
$count = 0;
Db::startTrans();
try {
foreach ($list as $item) {
//$count += $item->delete();
$order = Order::where('id', $item->order_id)->where('status', Order::STATUS_DISPATCHED)->find();
if (!$order) {
$this->error('订单状态已变更,请刷新后操作');
}
//取消
$item->save(['status' => OrderDispatch::STATUS_CANCEL, 'remark' => $remark]);
//回退订单状态
$order->allowField(true)->save(['status' => Order::STATUS_DISPATCHING]);
$params['order'] = $order->ref;
$params['role'] = 1;
$params['auth'] = $this->auth;
$params['remark'] = '派单被取消[ID' . $item->id . '],订单状态回退';
if (!empty($remark)) {
$params['remark'] .= ',操作备注:' . $remark;
}
Hook::listen('order_change', $params);
}
Db::commit();
} catch (PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
/* if ($count) {
$this->success();
}*/
$this->error(__('取消成功'));
}
private function getWorkers($workers)
{
foreach ($workers as $worker) {
$worker->dist = '100m';
}
return $workers;
}
public function map()
{
// 配置信息
$config = get_addon_config('address');
$order_id = request()->get('order_id');
$order = (new Order())->where('id', $order_id)->select();
$order = $order[0] ?? false;
if (!$order) {
abort(404);
}
$center = [
$order->lng, $order->lat
];
$this->view->assign('mapkey', $config);
$this->view->assign('center', $center);
return $this->fetch();
}
}