1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336 |
- <?php
- namespace app\common\model;
- use app\common\util\AppMsg;
- use app\hander\HelpHander;
- use think\Db;
- use think\Exception;
- use think\Log;
- use tools\Hwsms;
- class PhOrders extends Base
- {
- protected $table = 'ph_orders';
- public $status = [ //0=待分配 1=进行中 2=已完成 3=已作废 4=已结算
- 0=>'待分配',
- 1=>'进行中',
- 2=>'已完成',
- 3=>'已作废',
- 4=>'已结算',
- ];
- // 前端预约单
- public function bookOrder(){
- $data = [
- 'user_id' => input('userId/d',0),
- 'org_id' => input('orgId/d',0),
- 'contact' => input('contact','','trim'),
- 'phone' => input('phone','','trim'),
- 'name' => input('name','','trim'),
- 'gender' => input('gender/d',1),
- 'age' => input('age/d',0),
- 'bed' => input('bed','','trim'),
- 'ill' => input('ill','','trim'),
- 'start' => input('start',null,'trim'),
- 'remark' => input('remark','','trim'),
- 'dep_id' => input('depId/d',0),
- 'sn' => get_unique_id(),
- 'form' => 1,
- ];
- $validate = new \app\common\validate\PhOrders();
- $result = $validate->scene('book')->check($data,[]);
- if(true !== $result){
- $this->error = $validate->getError();
- return false;
- }
- Db::startTrans();
- try{
- $data['status'] = 0;
- $data['create_time'] = date('Y-m-d H:i:s');
- $orderId = Db::name('ph_orders')->insertGetId($data);
- if(!$orderId){
- \exception('创建订单失败');
- }
- Db::commit();
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- $this->sendSmsDispatch($data['name'],$data['phone'],$data['org_id'],$orderId);
- return true;
- }
- // 给调度短信发消息
- private function sendSmsDispatch($contact,$phone,$orgId,$fromId=0){
- $users = (new User())->get_ph_dispatch_user($orgId);
- foreach ($users as $k=>$v){
- if($v['mobile']){
- // 添加短信队列
- $content = AppMsg::getSmsMsg(AppMsg::SMS_PH_DISPATCH,[
- 'name' => $v['real_name'],
- 'contact' => $contact,
- 'phone' => $phone
- ]);
- $json = [
- 'orgId' => $orgId,
- 'mobiles' => [$v['mobile']],
- 'msg' => $content,
- 'fromId' => $fromId,
- 'type' => 2
- ];
- queue_push(json_encode($json),1);
- }
- // 添加推送队列 例:{"users":[1,2,3],"type":1,"msg":"有新订单需要你的处理","extra"=>[]}
- $json = [
- 'users' => [$v['id']],
- 'msg' => $content,
- 'extra' => [],
- 'type' => AppMsg::PUSH_PH_DISPATCH
- ];
- queue_push(json_encode($json),0);
- }
- }
- // 添加订单
- public function addSave($userId,$orgId,$type=0){ // type 1=调度端发单 0=后台发单
- $data = request()->post();
- $cate = isset($data['cateId'])?$data['cateId']:0;
- unset($data['cateId']);
- $data['dep_id'] =isset($data['depId'])?$data['depId']:0;
- $data['cate_id'] = $cate;
- $data['pre_money'] =isset($data['preMoney'])?$data['preMoney']:0;
- $data['org_id'] = $orgId;
- $data['user_id'] = $userId;
- $data['sn'] = get_unique_id();
- if(isset($data['userId'])){
- unset($data['userId'],$data['token'],$data['orgId']);
- }
- unset($data['depId'],$data['preMoney']);
- $validate = new \app\common\validate\PhOrders();
- $scene = 'add';
- if($type == 1){
- $scene = 'qadd';
- }
- $result = $validate->scene($scene)->check($data,[]);
- if(true !== $result){
- $this->error = $validate->getError();
- return false;
- }
- $data['start'] = $data['start']?$data['start']:null;
- $uids = $data['uids']?explode(',',$data['uids']):[];
- unset($data['uids']);
- if($uids && !$data['start']){
- $this->error = '未选择开始时间';
- return false;
- }
- Db::startTrans();
- try{
- $data['status'] = 0;
- $data['create_time'] = date('Y-m-d H:i:s');
- if($uids){
- $data['status'] = 1;
- }
- $ret = $this->insertGetId($data);
- if(!$ret){
- \exception('创建订单失败');
- }
- $orderId = $ret;
- if($uids){ // 创建工单
- $ph_todos = [];
- foreach ($uids as $k=>$v){
- $ph_todos[] = [
- 'org_id' => $data['org_id'],
- 'order_id' => $orderId,
- 'user_id' => $userId,
- 'worker_id' => $v,
- 'start' => $data['start'],
- 'create_time' => date('Y-m-d H:i:s'),
- 'status' => 1
- ];
- }
- $ret = Db::name('ph_todo')->insertAll($ph_todos);
- if($ret != count($ph_todos)){
- \exception('创建订单失败');
- }
- }
- Db::commit();
- return true;
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- }
- public function editSave($userId,$orgId){
- $data = request()->post();
- $validate = new \app\common\validate\PhOrders();
- $result = $validate->scene('edit')->check($data,[]);
- if(true !== $result){
- $this->error = $validate->getError();
- return false;
- }
- $data['start'] = $data['start']?$data['start']:null;
- $data['end'] = $data['end']?$data['end']:null;
- $old = Db::name('ph_orders')
- ->where('id',$data['id'])->find();
- if(!$old){
- $this->error = '订单不存在';
- return false;
- }
- if($old['status'] == 4){
- $this->error = '已结算的订单不能修改';
- return false;
- }
- Db::startTrans();
- try{
- $data['update_time'] = date('Y-m-d H:i:s');
- $orderId = Db::name('ph_orders')
- ->where('id',$data['id'])->update($data);
- if(!$orderId){
- \exception('创建订单失败');
- }
- Db::commit();
- $this->saveLog($userId,$orgId,$data['id'],1,$old);// 订单修改日志
- return true;
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- }
- // 派单
- public function sendSave($userId,$orgId){
- $data = [
- 'id' => input('id/d',0),
- // 'cate_id' => input('cate_id/d',0),
- // 'price' => input('price/f',0),
- 'uids' => input('uids','','trim'),
- 'start' => input('start',null,'trim'),
- 'remark' => input('remark','','trim'),
- ];
- // $cateId = input('cateId');
- //
- // $data['cate_id'] = $cateId?$cateId:$data['cate_id'];
- $uids = $data['uids']?explode(',',$data['uids']):[];
- if(!$uids){
- $this->error ='请选择执行护工';
- return false;
- }
- unset($data['uids']);
- if(!$data['start']){
- $this->error = '未选择开始时间';
- return false;
- }
- if($uids){
- $ph_todo = Db::name('ph_todo')
- ->where('order_id',$data['id'])
- ->where('status',1)
- ->where('user_id','in',$uids)
- ->find();
- if($ph_todo){
- $this->error = '此订单正在服务中';
- return false;
- }
- }
- $info = Db::name('ph_orders')
- ->where('id',$data['id'])->find();
- if(!$info){
- $this->error = '订单不存在';
- return false;
- }
- if(!in_array($info['status'],[0,1])){
- $this->error = '订单该状态无法派单';
- return false;
- }
- if($data['start'] && $info['start'] && $data['start'] < $info['start']){
- $this->error = '开始时间不能小于订单的开始时间';
- return false;
- }
- Db::startTrans();
- try{
- if($uids){
- foreach ($uids as $k=>$v){
- $todoList = Db::name('ph_todo')->where('order_id',$data['id'])->where('worker_id',$v)->whereIn('status',[1,2])->select();
- if(count($todoList) >= 1){
- $arr = $this->compareDate($todoList,$data['start']);
- if(!$arr){
- $this->error = '该护工在此时间段工单未完成,不能派单';
- return false;
- }
- }
- }
- }
- $sdata['update_time'] = date('Y-m-d H:i:s');
- $sdata['status'] = 1;
- // $sdata['cate_id'] = $data['cate_id'];
- // $sdata['price'] = $data['price'];
- if($info['status'] == 0){
- $orderId = Db::name('ph_orders')
- ->where('id',$data['id'])->update($sdata);
- if(!$orderId){
- \exception('订单修改失败');
- }
- }
- if($uids){ // 创建工单
- $todos = [];
- foreach ($uids as $k=>$v){
- $todos[] = [
- 'org_id' => $orgId,
- 'order_id' => $data['id'],
- 'user_id' => $userId,
- 'worker_id' => $v,
- 'start' => $data['start'],
- 'remark' => $data['remark'],
- 'create_time' => date('Y-m-d H:i:s'),
- 'status' => 1
- ];
- }
- $ret = Db::name('ph_todo')->insertAll($todos);
- if($ret != count($todos)){
- \exception('创建订单失败');
- }
- }
- Db::commit();
- return true;
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- }
- // 完成订单
- public function finishSave($userId,$orgId){
- $data = [
- 'id' => input('id/d',0),
- 'end' => input('end',null,'trim'),
- 'amount' => input('amount/f',0)
- ];
- if($data['amount'] <= 0){
- $this->error = '收费金额不能小于0';
- return false;
- }
- if(!$data['end']){
- $this->error = '未选择服务结束日期';
- return false;
- }
- $info = Db::name('ph_orders')->where('id',$data['id'])->find();
- if(!$info){
- $this->error = '订单不存在';
- return false;
- }
- if($info['status'] != 1){
- $this->error = '订单该状态无法完成';
- return false;
- }
- if($data['end'] && $info['start'] && $data['end'] < $info['start']){
- $this->error = '结束时间不能小于订单的开始时间';
- return false;
- }
- if($data['amount'] != $info['pre_money']){
- $this->error = '收费金额与预收金不一致,不能完成';
- return false;
- }
- Db::startTrans();
- try{
- $sdata['update_time'] = date('Y-m-d H:i:s');
- $sdata['status'] = 2;
- $sdata['amount'] = $data['amount'];
- $sdata['end'] = $data['end'];
- $orderId = Db::name('ph_orders')->where('id',$data['id'])->update($sdata);
- if(!$orderId){
- \exception('订单修改失败');
- }
- $ph_todos = Db::name('ph_todo')
- ->where('order_id',$data['id'])
- ->where('status',1)->select();
- foreach ($ph_todos as $k=>$v){
- Db::name('ph_todo')->where('id',$v['id'])->update([
- 'update_time' => date('Y-m-d H:i:s'),
- 'status' => 2,
- 'end' => $data['end'],
- 'day' => $this->getWorkerDay($v['start'],$data['end'])
- ]);
- }
- Db::commit();
- return true;
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- }
- // 修改工单
- public function edit_todo($userId,$orgId){
- $data = [
- 'id' => input('id/d',0),
- 'start' => input('start',null,'trim'),
- 'end' => input('end',null,'trim'),
- 'remark' => input('remark','','trim'),
- 'status' => input('status/d',0),
- 'day' => input('day/f',0)
- ];
- $ph_todo = Db::name('ph_todo')->where('id',$data['id'])->find();
- if(!$ph_todo){
- $this->error = '工单不存在';
- return false;
- }
- $info = Db::name('ph_orders')->where('id',$ph_todo['order_id'])->find();
- if(!$info){
- $this->error = '订单不存在';
- return false;
- }
- if($info['status'] == 3||$info['status'] == 4){
- $this->error = '订单该状态无法修改工单';
- return false;
- }
- if(!$data['start'] || !$data['end']){
- $this->error = '未选择开始时间或结束时间';
- return false;
- }
- if($data['end'] && $info['start'] && $data['end'] < $info['start']){
- $this->error = '结束时间不能小于订单的开始时间';
- return false;
- }
- $todoList = Db::name('ph_todo')
- ->where('order_id',$info['id'])
- ->group('user_id')
- ->select();
- foreach ($todoList as $k=>$v){
- $todos = Db::name('ph_todo')
- ->where('order_id',$v['order_id'])
- ->where('user_id',$v['user_id'])
- ->where('id','<>',$data['id'])
- ->select();
- if(count($todos) >=1){
- foreach ($todos as $kk=>$vv){
- $ret = $this->is_time_cross($data['start'],$data['end'],$vv['start'],$vv['end']);
- if($ret){
- $this->error = '该时间段有未完成的工单,不能修改';
- return false;
- }
- }
- }
- }
- Db::startTrans();
- try{
- $data['update_time'] = date('Y-m-d H:i:s');
- if($data['day'] <= 0){
- $data['day'] = $this->getWorkerDay($data['start'],$data['end']);
- }
- $ret = Db::name('ph_todo')->where('id',$data['id'])->update($data);
- if(!$ret){
- \exception('工单修改失败');
- }
- Db::commit();
- $this->saveLog($userId,$orgId,$data['id'],2,$ph_todo);// 工单修改日志
- return true;
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = $e->getMessage();
- return false;
- }
- }
- // 计算工期
- public function getWorkerDay($start,$end){
- if($end <= $start||!$start||!$end){
- return 0;
- }
- $day1 = date('Y-m-d',strtotime($start));
- $day2 = date('Y-m-d',strtotime($end));
- $day = 0;
- if($day1 == $day2){ // 当天
- if($start < $day1.' 12:00:00' && $end < $day1.' 12:00:00'){
- $day = 0.5;
- }else if($start < $day1.' 12:00:00' && $end < $day1.' 12:00:00'){
- $day = 0.5;
- }else {
- $day = 1;
- }
- }else{ // 跨天
- if($start < $day1.' 12:00:00'){
- $day = 1;
- }else{
- $day = 0.5;
- }
- $i = 1;
- while (true){
- $dd = date('Y-m-d',strtotime($start) + $i*24*60*60);
- if($dd == $day2){
- if($end != $day2.' 00:00:00'){
- if($end > $day2.' 00:00:00'&&$end <= $day2.' 12:00:00'){
- $day += 0.5;
- }else{
- $day += 1;
- }
- }
- break;
- }else{
- $day += 1;
- $i++;
- }
- }
- }
- return $day;
- }
- public function saveLog($userId,$orgId,$id,$type,$old){
- if($type == 1){ // 修改订单
- $new = Db::name('ph_orders')
- ->where('id',$id)->find();
- }else{
- $new = Db::name('ph_todo')->where('id',$id)->find();
- }
- $data = [
- 'org_id' => $orgId,
- 'user_id' => $userId,
- 'type' => $type,
- 'bus_id' => $id,
- 'old_data' => json_encode($old,JSON_UNESCAPED_UNICODE),
- 'new_data' => json_encode($new,JSON_UNESCAPED_UNICODE),
- 'create_time' => date('Y-m-d H:i:s')
- ];
- Db::name('ph_orders_log')->insert($data);
- }
- public function getInfo($id){
- $info = $this->where('id',$id)->find()->toArray();
- $off = model('Config')->getConfig('ph_order_cancel_time',cur_org_id());
- $info['is_zf'] = 0;
- if($off){
- $start = strtotime($info['create_time']) + $off*60*60;
- $end = strtotime(date('Y-m-d H:i:s'));
- if($start < $end){
- $info['is_zf'] = 1;
- }
- }
- $info['end'] = $info['end']? $info['end']:'';
- $info['cancel_time'] = $info['cancel_time']? $info['cancel_time']:'';
- $info['update_time'] = $info['update_time']? $info['update_time']:'';
- $info['settlementUseId'] = $info['settlement_use_id']? $info['settlement_use_id']:0;
- $info['settlement_time'] = $info['settlement_time']? $info['settlement_time']:"";
- if($info){
- $info['cate_name'] = '';
- if($info['cate_id'] > 0){
- $info['cate_name'] = Db::name('cate')
- ->where('id',$info['cate_id'])
- ->value('title');
- }
- $info['dep_name'] = '';
- if($info['dep_id'] > 0){
- $info['dep_name'] = Db::name('dep')
- ->where('id',$info['dep_id'])
- ->value('title');
- }
- $info['user_name'] = '';
- if($info['user_id'] > 0){
- $info['user_name'] = Db::name('user')
- ->where('id',$info['user_id'])
- ->value('real_name');
- if(empty($info['user_name'])){
- $info['user_name'] = Db::name('wxuser')
- ->where('id',$info['user_id'])
- ->value('nickname');
- }
- }
- $info['cancel_user_name'] = '';
- if($info['cancel_user_id'] > 0){
- $info['cancel_user_name'] = Db::name('user')
- ->where('id',$info['cancel_user_id'])
- ->value('real_name');
- }
- $info['settlement_use_name'] = '';
- if($info['settlement_use_id'] > 0){
- $info['settlement_use_name'] = Db::name('user')
- ->where('id',$info['settlement_use_id'])
- ->value('real_name');
- }
- $todos = Db::name('ph_todo')
- ->where('order_id',$id)->select();
- foreach ($todos as $k=>$v){
- $todos[$k]['user_name'] = Db::name('user')
- ->where('id',$v['user_id'])
- ->value('real_name');
- $user_id = Db::name('worker')
- ->where('id',$v['worker_id'])
- ->value('user_id');
- $todos[$k]['worker_name'] = Db::name('user')
- ->where('id',$user_id)
- ->value('real_name');
- $todos[$k]['end'] = $v['end']? $info['end']:"";
- }
- $info['todo'] = $todos;
- // 获取缴费记录
- $pays = Db::name('ph_order_pay')->where('status',1)->where('order_id',$id)->select();
- $pays = $pays?$pays:[];
- $info['pays'] = $pays;
- // 获取退款记录
- $refunds = Db::name('ph_order_refund')->where('order_id',$id)->select();
- $refunds = $refunds?$refunds:[];
- $info['refunds'] = $refunds;
- }
- return $info;
- }
- public function orderTotal($start,$end,$price){
- $day = diffBetweenTwoDays($start,$end);
- $day = $day > 0?$day:1;
- return $day*$price;
- }
- //验证用户是否有待支付追加金额的订单
- public function checkAddAmount($userId){
- $ret = $this
- ->where('user_id',$userId)
- ->where('status',2)
- ->where('completion',0)
- ->where('end','<',date('Y-m-d'))
- ->where('add_amount','>',0)
- ->find();
- return $ret?false:true;
- }
- //订单详情
- public function orderDetail($id,$type=0){
- $map = [];
- if($type==0){
- $map[] = ['user_del','=',0];
- }elseif ($type==1){
- $map[] = ['worker_del','=',0];
- }
- $info = $this->where('id',$id)->where($map)
- ->find()->toArray();
- if(empty($info)) HelpHander::error('订单信息不存在');
- $info['start'] = date('Y/m/d',strtotime($info['start']));
- $info['end'] = date('Y/m/d',strtotime($info['end']));
- $info['orgName'] = Db::name('org')
- ->where('id',$info['org_id'])->value('title');
- $info['addrTitle'] = (new Worker())->getAddressName($info['addr_id']);
- $info['userInfo'] = (new User())->getUserInfo($info['user_id']);
- $info['workerInfo'] = (new Worker())->workerDetail($info['worker_id'],$info['org_id'],$info['user_id']);
- $info['cateInfo'] = (new Cate())->info($info['cate_id']);
- $info['selfcareInfo'] = Db::name('options')->where('id',$info['selfcare'])
- ->where('type',1)->value('title');
- $info['refundInfo'] = [];
- if($info['refund_status']==1){//退款明细
- $info['refundInfo'] = (new OrderRefund())->info($info['id']);
- $info['statusName'] =(new OrderRefund())->status[$info['refundInfo']['status']];
- }else{
- $info['statusName'] = $this->status[$info['status']];
- }
- $cancelName = '';
- $cancelType = '';
- if($info['status']==5){
- if($info['cancel_type']==3){
- $cancelName =$cancelType= '系统取消';
- }
- if($info['cancel_type']==2){
- $cancelName = Db::name('user')->
- where('id',$info['cancel_user_id'])
- ->value('nickname');
- $cancelType = '用户取消';
- }
- if($info['cancel_type']==1){
- $cancelName = Db::name('worker')->
- where('id',$info['cancel_user_id'])
- ->value('name');
- $cancelType = '护工取消';
- }
- }
- $info['cancelName'] = $cancelName;
- $info['cancelType'] = $cancelType;
- $info['cancelTypeId'] = $info['cancel_type'];
- // 添加订单评价信息
- $info['comment'] = null;
- if($info['status'] == 5){
- $comment = Db::name('comment')->where('order_id',$id)->find();
- $info['comment'] = $comment;
- }
- $info['addOrderInfo'] = [];
- if($info['add_amount']>0){//追加金额明细
- $addOrder = Db::name('order_add')
- ->alias('a')
- ->join('options b','a.options_id=b.id')
- ->where('a.order_id',$info['id'])
- ->field('a.*,b.title')
- ->select()
- ->toArray();
- $info['addOrderInfo'] = $addOrder;
- }
- return $info;
- }
- //订单列表
- public function orderList($orgId,$status,$page,$size,$userId=0){
- $start = ($page - 1) * $size;
- if($status >= 0){
- if($userId >0){
- if($status==2){
- $map[] = ['status','in',[2,4]];
- }else{
- $map[] = ['status','=',$status];
- }
- }
- }
- if($userId > 0){
- $map[] = ['user_id','=',$userId];
- $map[] = ['form','=',1];
- }
- $map[] = ['org_id', '=', $orgId];
- $list = $this->where($map)
- ->limit($start,$size)
- ->order('id','desc')
- ->select();
- $list = $list?$list->toArray():[];
- foreach ($list as $k=>$v){
- }
- return $list;
- }
- //调度订单列表
- public function orderList1($orgId,$status,$page,$size){
- $start = ($page - 1) * $size;
- if($status >= 0){
- if($status==2){
- $map[] = ['status','in',[2,4]];
- }else{
- $map[] = ['status','=',$status];
- }
- }
- $map[] = ['org_id', '=', $orgId];
- $list = $this->where($map)
- ->limit($start,$size)
- ->field('id,sn,contact,phone,start,create_time')
- ->order('id','desc')
- ->select();
- $list = $list?$list->toArray():[];
- foreach ($list as $k=>$v){
- }
- return $list;
- }
- //订单列表
- public function workerOrderList($orgId,$status,$page,$size,$userId=0){
- $start = ($page - 1) * $size;
- if($status >= 0){
- $map[] = ['status','=',$status];
- }else{
- $map[] = ['status','>',0];
- }
- $worker = Db::name('worker')
- ->where('user_id',$userId)
- ->find();
- if(empty($worker)){
- return [];
- }
- $map[] = ['org_id', '=', $orgId];
- $map[] = ['worker_id', '=', $worker['id']];
- $todo = Db::name('ph_todo')
- ->where($map)
- ->field('id,start,day,status,create_time')
- ->limit($start,$size)
- ->select();
- return $todo;
- }
- //取消订单
- public function cancelOrder($id,$note,$userId){
- if(!$note){
- $this->error = '未填写作废原因';
- return false;
- }
- $info = Db::name('ph_orders')
- ->where('id',$id)->find();
- if(!$info){
- $this->error = '订单不存在';
- return false;
- }
- if($info['status'] == 3||$info['status'] == 4){
- $this->error = '订单已作废或已结算';
- return false;
- }
- $off = model('Config')->getConfig('ph_order_cancel_time',cur_org_id());
- if($off){
- $info = Db::name('ph_orders')->where('id',$id)->find();
- $start = strtotime($info['create_time']) + $off*60*60;
- $end = strtotime(date('Y-m-d H:i:s'));
- if($start < $end){
- $this->error = '该订单已超过作废时间';
- return false;
- }
- }
- Db::startTrans();
- try{
- $res =Db::name('ph_orders')
- ->where('id',$id)
- ->update([
- 'status'=>3,
- 'cancel_reason'=>$note,
- 'cancel_time'=>getTime(),
- 'cancel_user_id'=>$userId
- ]);
- if(!$res){
- \exception('操作失败');
- }
- Db::name('ph_todo')->where('order_id',$id)->update(['status' => 0]);
- Db::commit();
- }catch (Exception $e){
- Db::rollback();
- \think\facade\Log::write($e->getMessage(), 'info');
- $this->error = '操作失败';
- return false;
- }
- return true;
- }
- //用户护工删除订单
- public function delOrder($id,$userId,$type=0){
- $info = $this->getOrderDetail($id,$userId,$type);
- if(!in_array($info['status'],[3,4,5])) HelpHander::error('当前订单状态不能删除');
- if($type==0){
- $params = ['user_del'=>1,'user_del_time'=>getTime()];
- }else{
- $params = ['worker_del'=>1,'worker_del_time'=>getTime()];
- }
- $res = $this->where('id',$id)
- ->update($params);
- return $res;
- }
- //用户发起退款
- public function orderRefund($id,$amount,$reason,$desc,$userId){
- $info = $this->getOrderDetail($id,$userId);
- if($info['amount'] < $amount) HelpHander::error('退款金额不能大于订单金额');
- if($info['refund_status']==1) HelpHander::error('当前订单已申请过退款');
- if(!in_array($info['status'],[1,2])) HelpHander::error('当前订单状态不能退款');
- $refundModel = new OrderRefund();
- Db::startTrans();
- try{
- $params = [
- 'sn'=>get_unique_id(),
- 'order_id'=>$id,
- 'user_id'=>$userId,
- 'amount'=>$amount,
- 'reason'=>$reason,
- 'desc'=>$desc,
- 'is_cx'=>0,
- 'create_time'=>getTime(),
- ];
- if($refundModel->info($id)){
- if(!$refundModel->where('order_id',$id)->save($params)) exception('保存退款单失败');
- }else{
- if(!$refundModel->save($params)) exception('保存退款单失败');
- }
- if(!$this->where('id',$id)->update(['refund_status'=>1])){
- exception('更新订单失败');
- }
- $om = new \app\model\OrderMessage();
- $om->saveMassage($userId,'发起退款申请');
- Db::commit();
- return true;
- }catch (Exception $e){
- HelpHander::error($e->getMessage());
- Db::rollback();
- }
- }
- public function getOrderDetail($id,$userId,$type=0){
- if($type==0){
- $map[] = ['user_id','=',$userId];
- $map[] = ['user_del','=',0];
- }else{
- $map[] = ['worker_id','=',$userId];
- $map[] = ['worker_del','=',0];
- }
- $info = $this
- ->where('id',$id)
- ->where($map)
- ->find();
- if(empty($info)) HelpHander::error('订单信息不存在');
- return $info;
- }
- //护工领取订单
- public function orderReceive($workerId,$id){
- $info = $this->getOrderDetail($id,$workerId,1);
- if($info['status']!=1) HelpHander::error('当前订单已领取');
- $ret = $this->where('id',$id)
- ->save(['status'=>2,'receive_time'=>getTime()]);
- return $ret;
- }
- //撤销退款
- public function cxOrder($id){
- $info = (new OrderRefund())->info($id);
- if($info['status']!=0) HelpHander::error('当前订单不能撤销');
- Db::startTrans();
- try{
- $ret = $this->where('id',$id)
- ->save(['refund_status'=>0,'refund_amount'=>0]);
- if(!$ret) exception('更新订单失败');
- $ret = (new OrderRefund())->where('order_id',$id)
- ->save(['is_cx'=>1,'cx_time'=>getTime()]);
- if(!$ret) exception('退款单更新失败');
- Db::commit();
- return true;
- }catch (Exception $e){
- HelpHander::error($e->getMessage());
- Db::rollback();
- }
- return $ret;
- }
- // 用户正在进行的最新的陪护单
- public function latestOrder($userId){
- $map[] = ['user_id','=',$userId];
- $map[] = ['user_del','=','0'];
- $map[] = ['refund_status','=','0'];
- $map[] = ['status','=','2'];
- $info = Db::name('ph_orders')->where($map)->order('id desc')->find();
- if($info){
- $worker = Db::name('worker')->where('id',$info['worker_id'])->value('name');
- $info['worker_name'] = $worker?$worker:'';
- }
- return $info?$info:null;
- }
- //获取护工已预订日期
- public function bookDateList($workerId){
- $curday = date('Y-m-d');
- $lists = Db::name('ph_orders')
- ->where('end','>=',$curday)
- ->where('worker_id',$workerId)
- ->where('status','in',[1,2])
- ->where('refund_status',0)
- ->order('id asc')
- ->field('id,start,end,cate_id')
- ->select();
- foreach ($lists as $k=>$v){
- $lists[$k]['cate_name'] = Db::name('cate')->where('id',$v['cate_id'])->value('title');
- }
- return $lists?$lists:[];
- }
- //支付
- public function pay($orderId){
- $params = $this->where('id',$orderId)
- ->find();
- $workerModel = new Worker();
- $cateInfo = (new Cate())->info($params['cate_id']);
- if(!$workerModel->checkServiceNum($params['worker_id'],$cateInfo['nums'],$params['start'],$params['end'],$params['addr_id'],$msg)){
- HelpHander::error($msg);
- }
- $openid = Db::name('user_oauth')->where('user_id',$params['user_id'])->value('openid');
- $config = config('app.wx_config');
- $app = \EasyWeChat\Factory::payment($config);
- $result = $app->order->unify([
- 'body' => '订单-'.$params['sn'],
- 'out_trade_no' => $params['sn'],
- 'total_fee' => $params['amount']*100,
- 'spbill_create_ip' => request()->ip(), // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
- 'notify_url' => (string)url('api/Notify/wxorder',[],false,true), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
- 'openid' => $openid,
- ]);
- tplog($result);
- if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS'){
- HelpHander::error('下单失败1');
- }
- $jssdk = $app->jssdk;
- $json = $jssdk->bridgeConfig($result['prepay_id'],false);
- $json['order_id'] = $orderId;
- return $json;
- }
- //结算订单
- public function js($orderId=[],$web_bl,$web_deduct,$org){
- $succ = [];
- $error = [];
- foreach ($orderId as $k=>$v){
- Db::startTrans();
- try{
- $info = $this->where('id',$v)->find()->toArray();
- $total = $info['amount'];
- $money1 = ($total-$web_deduct)*$web_bl;
- if($money1 > 0){
- $ph_todo = Db::name('ph_todo')
- ->where('order_id',$v)
- ->where('status','<>',0)
- ->select();
- $days = Db::name('ph_todo')
- ->where('order_id',$v)
- ->where('status','<>',0)
- ->sum('day');
- if($days >0){
- $avgPrice = round($money1/$days,2);
- if(!empty($ph_todo)){
- foreach ($ph_todo as $k1=>$v1){
- $workerMoney = Db::name('worker')
- ->where('id',$v1['worker_id'])->value('balance');
- $money = $avgPrice*$v1['day'];
- if($money >0){
- $newMoney = $workerMoney+$money;
- $res = Db::name('worker')
- ->where('id',$v1['worker_id'])
- ->update(['balance'=>$newMoney]);
- if(!$res) \exception('订单id:'.$v.'余额更新失败');
- $res = Db::name('worker')
- ->where('id',$v1['worker_id'])
- ->inc('cumulative_money',$money);
- if(!$res) \exception('订单id:'.$v.'累计收入更新失败');
- $res = Db::name('worker_balance')->insert([
- 'worker_id'=>$v1['worker_id'],
- 'org_id'=>$org,
- 'user_id'=>is_login(),
- 'money'=>$money,
- 'from_id'=>$v,
- 'type'=>1,
- 'remark'=>'id:'.$v.'订单结算('.$info['sn'].')',
- 'create_time'=>date('Y-m-d H:i:s')
- ]);
- if(!$res) \exception('订单id:'.$v.' 结算记录添加失败');
- $cc = [
- 'settlement_money'=>$money
- ];
- $res= Db::name('ph_todo')
- ->where('id',$v1['id'])
- ->update($cc);
- if(!$res) \exception('订单id:'.$v.' 更新ph_todo 失败');
- }
- }
- }
- }
- }
- $res = $this->where('id',$v)
- ->update([
- 'status'=>4,
- 'settlement_money'=>$money1 >0?$money1:0,
- 'settlement_use_id'=>is_login(),
- 'settlement_time'=>date('Y-m-d H:i:s'),
- ]);
- if(!$res) \exception('订单id:'.$v.'更新失败');
- Db::commit();
- $succ[] = $v;
- }catch (Exception $e){
- $error[] = $e->getMessage();;
- Db::rollback();
- }
- }
- $msg = '';
- if(count($error) > 0){
- $msg = '结算成功:'.count($succ).',失败:'.count($error).',失败订单:'.implode(',',$error);
- $a = ['code'=>0,'msg'=>$msg];
- }else{
- $msg = '结算成功:'.count($succ).',失败:'.count($error);
- $a = ['code'=>1,'msg'=>$msg];
- }
- return $a;
- }
- //用户完成
- public function finish($orderId){
- $params = $this->where('id',$orderId)->find();
- if(!$params){
- HelpHander::error('订单不存在');
- }
- if($params['refund_status'] == 1){
- HelpHander::error('退款中不能完成');
- }
- if($params['status'] != 2){
- HelpHander::error('该状态不能完成');
- }
- if($params['add_amount'] > 0){ // 追加大于0,支付
- $openid = Db::name('user_oauth')->where('user_id',$params['user_id'])->value('openid');
- $config = config('app.wx_config');
- $app = \EasyWeChat\Factory::payment($config);
- $result = $app->order->unify([
- 'body' => '订单-'.$params['sn'],
- 'out_trade_no' => $params['sn'].mt_rand(100,999),
- 'total_fee' => $params['add_amount']*100,
- 'spbill_create_ip' => request()->ip(), // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
- 'notify_url' => (string)url('api/Notify/wxaddorder',[],false,true), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
- 'openid' => $openid,
- 'attach' => $orderId
- ]);
- tplog($result);
- if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS'){
- HelpHander::error('操作失败');
- }
- $jssdk = $app->jssdk;
- $json = $jssdk->bridgeConfig($result['prepay_id'],false);
- $json['type'] = 1;
- return $json;
- }else{ //直接完成
- $sdata = [
- 'status' => 3,
- 'finish_time' => date('Y-m-d H:i:s'),
- ];
- if($params['completion'] == 0){
- $sdata['completion'] = 1;
- $sdata['completion_time'] = date('Y-m-d H:i:s');
- }
- $ret = Db::name('ph_orders')->where('id',$orderId)->update($sdata);
- if(!$ret){
- HelpHander::error('操作失败');
- }
- return ['type' => 0];
- }
- }
- //护工追加金额
- public function orderAdd($data,$orderId){
- $total = 0;
- $arr = [];
- foreach ($data as $k=>$v){
- $total+=floatval($v);
- if(!empty($v) && $v > 0){
- $arr[] = [
- 'order_id'=>$orderId,
- 'amount'=>$v,
- 'options_id'=>$k,
- ];
- }
- }
- if($total==0){
- $this->error = '追加项目必选选择一个';
- return false;
- }
- Db::startTrans();
- try {
- Db::name('order_add')
- ->where('order_id',$orderId)
- ->delete();
- $ret = Db::name('order_add')
- ->insertAll($arr);
- if(!$ret) \exception('追加项目添加失败');
- $ret = $this->where('id',$orderId)
- ->save(['add_amount'=>$total,'update_time'=>getTime()]);
- if(!$ret) \exception('订单更新失败');
- Db::commit();
- return true;
- }catch (Exception $e){
- $this->error = $e->getMessage();
- Db::rollback();
- return false;
- }
- }
- //护工操作完工
- public function completion($orderId){
- $info = $this->where('id',$orderId)
- ->find();
- if($info['completion'] !=0){
- $this->error = '当前订单已完工';
- return false;
- }
- $ret = $this->where('id',$orderId)
- ->save([
- "completion"=>1,
- "completion_time"=>getTime(),
- ]);
- if(!$ret){
- $this->error = '订单更新失败';
- return false;
- }
- return $ret;
- }
- public function makeAccount($ids,$title,$remark){
- $this->startTrans();
- try{
- $amount = $this->where('id','in',$ids)
- ->sum('amount');
- $addAmount = $this->where('id','in',$ids)
- ->sum('add_amount');
- $refund_amount = $this->where('id','in',$ids)
- ->sum('refund_amount');
- $settlement_money = $this->where('id','in',$ids)
- ->sum('settlement_money');
- $data = [
- 'title'=>$title,
- 'remark'=>$remark,
- 'amount'=>$amount+$addAmount-$refund_amount,
- 'settlement_money'=>$settlement_money,
- 'income_money'=>$amount+$addAmount-$refund_amount-$settlement_money,
- 'create_time'=>getTime()
- ];
- $ret = Db::name('make_account')
- ->insertGetId($data);
- if(!$ret) {
- \exception('保存做账记录失败');
- }
- $ret = $this->where('id','in',$ids)
- ->update([
- 'is_make_account'=>1,
- 'make_account_id'=>$ret,
- ]);
- if(!$ret) {
- \exception('更新订单失败');
- }
- $this->commit();
- return true;
- }catch (Exception $e){
- $this->error = $e->getMessage();
- $this->rollback();
- return false;
- }
- }
- //护工工单详情
- public function todoDetail($id){
- $todo = Db::name('ph_todo')
- ->where('id',$id)
- ->find();
- $todo['end'] = $todo['end']?$todo['end']:'';
- $todo['user_name'] = Db::name('user')
- ->where('id',$todo['user_id'])
- ->value('real_name');
- $user_id = Db::name('worker')
- ->where('id',$todo['worker_id'])
- ->value('user_id');
- $todo['worker_name'] = Db::name('user')
- ->where('id',$user_id)
- ->value('real_name');
- $orderInfo = $this->getInfo($todo['order_id']);
- unset($orderInfo['todo']);
- $orderInfo['todo'][] = $todo;
- return $orderInfo;
- }
- function compareDate($arr,$start){
- array_multisort(array_column($arr, 'start'), SORT_ASC, $arr);
- foreach ($arr as $k => $v){
- if($v['end'] && $start > $v['start'] && $start < $v['end']){
- return false;
- }
- }
- return true;
- }
- /**
- * PHP计算两个时间段是否有交集(边界重叠不算)
- *
- * @param string $beginTime1 开始时间1
- * @param string $endTime1 结束时间1
- * @param string $beginTime2 开始时间2
- * @param string $endTime2 结束时间2
- * @return bool
- */
- function is_time_cross($beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = '') {
- $status = strtotime($beginTime2) - strtotime($beginTime1);
- if($beginTime1 == $beginTime2 && $endTime1 == $endTime2){
- return false;
- }
- if(!$endTime2){
- return false;
- }
- if ($status > 0) {
- $status2 = strtotime($beginTime2) - strtotime($endTime1);
- if ($status2 >= 0) {
- return false;
- } else {
- return true;
- }
- } else {
- $status2 = strtotime($endTime2) - strtotime($beginTime1);
- if ($status2 > 0) {
- return true;
- } else {
- return false;
- }
- }
- }
- }
|