12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337 |
- <?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)
- ->order(['id'=>'desc'])
- ->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;
- }
- }
- }
- }
|