ServiceOrderLogic.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. <?php
  2. namespace app\api\logic;
  3. use app\adminapi\logic\master_worker\MasterWorkerLogic;
  4. use app\adminapi\service\DistributeLeafletsService;
  5. use app\common\enum\GoodsEnum;
  6. use app\common\enum\PayEnum;
  7. use app\common\enum\RefundEnum;
  8. use app\common\enum\WorkEnum;
  9. use app\common\enum\YesNoEnum;
  10. use app\common\logic\BaseLogic;
  11. use app\common\logic\PaymentLogic;
  12. use app\common\logic\PayNotifyLogic;
  13. use app\common\logic\RefundLogic;
  14. use app\common\model\coupon\CouponCategory;
  15. use app\common\model\coupon\UserCoupon;
  16. use app\common\model\dict\DictData;
  17. use app\common\model\equity\UserEquity;
  18. use app\common\model\goods\Goods;
  19. use app\common\model\master_commission\MasterWorkerCommissionConfig;
  20. use app\common\model\master_commission\MasterWorkerCommissionNotice;
  21. use app\common\model\master_worker\MasterWorker;
  22. use app\common\model\master_worker\MasterWorkerRule;
  23. use app\common\model\orders\OrderEffectiveLog;
  24. use app\common\model\orders\RechargeOrder;
  25. use app\common\model\property\PropertyActivity;
  26. use app\common\model\recharge\OrderGoods;
  27. use app\common\model\refund\RefundRecord;
  28. use app\common\model\service_area\ServiceArea;
  29. use app\common\model\spare_part\SparePart;
  30. use app\common\model\works\ServiceWork;
  31. use app\common\model\works\ServiceWorkAppointmentLog;
  32. use app\common\model\works\ServiceWorkDeterminedPrice;
  33. use app\common\model\works\ServiceWorkSpare;
  34. use app\workerapi\logic\ServiceWorkLogLogic;
  35. use think\Exception;
  36. use think\facade\Db;
  37. use think\facade\Log;
  38. /**
  39. * 订单逻辑层
  40. * Class ServiceOrderLogic
  41. * @package app\api\logic
  42. */
  43. class ServiceOrderLogic extends BaseLogic
  44. {
  45. /**
  46. * 判断是否在某服务区 返回服务区城市信息
  47. * @param $params
  48. * @return bool
  49. */
  50. public static function isService($params):array
  51. {
  52. // 查询服务区所有的地点
  53. $rules = ServiceArea::field(['id', 'province', 'city','county', 'area_name', 'electronic_fence'])->select()->toArray();
  54. $point=['lng'=> $params['lon'],'lat'=> $params['lat']];
  55. foreach ($rules as $value){
  56. foreach ($value['electronic_fence'] as $polygon) {
  57. if (isPointInPolygon($point, $polygon)) {
  58. return [
  59. 'id'=>$value['id'],
  60. 'city'=>$value['city'],
  61. 'county'=>$value['county'],
  62. 'area_name'=>$value['area_name']
  63. ];
  64. }
  65. }
  66. }
  67. throw new Exception('已超出服务区域!-1001');
  68. }
  69. /**
  70. * 提交订单
  71. * @param array $params
  72. * @return array|false
  73. */
  74. public static function submitOrder($params)
  75. {
  76. Db::startTrans();
  77. try {
  78. // 订单位置是否在服务区内
  79. $areas = self::isService($params);
  80. $goods = Goods::findOrEmpty($params['goods_id']);
  81. if($goods->isEmpty()){
  82. throw new Exception('产品不存在!');
  83. }
  84. if(empty($params['user_info']['mobile'])){
  85. throw new Exception('请先补充您的联系方式后在提交订单');
  86. }
  87. // TODO tmp防抖1m
  88. $isExist = ServiceWork::where(['user_id'=>$params['user_id'],'goods_category_id'=>$goods['goods_category_id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  89. if(!$isExist->isEmpty()){
  90. throw new Exception('请勿重复下单!');
  91. }
  92. //根据服务工单计算当前订单应支付金额
  93. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE){
  94. //一口价订单
  95. $order_total = $goods['service_fee'];
  96. $order_amount = $goods['service_fee'];
  97. }else if ($goods['goods_payment_type'] == GoodsEnum::DEP_GOODS_PAYMENT_TYPE){
  98. $order_total = $goods['service_fee'];
  99. $order_amount = $goods['service_fee'];
  100. }
  101. else{
  102. $order_total = $goods['base_service_fee'];
  103. $order_amount = $goods['service_fee'];
  104. }
  105. //优惠券验证
  106. if(!empty($params['coupon_id'])){
  107. $user_coupon = UserCoupon::where(['id'=>$params['coupon_id'],'user_id'=>$params['user_id'],'voucher_status'=>0])
  108. ->where('voucher_count','>',0)
  109. ->where('expire_time','>=',time())
  110. ->where('begin_use','<',time())
  111. ->findOrEmpty();
  112. if($user_coupon->isEmpty()){
  113. throw new Exception('该优惠券无法使用');
  114. }
  115. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE and $order_amount<$user_coupon['amount_require']){
  116. throw new Exception('该优惠劵不满足满减使用条件');
  117. }
  118. if($goods['goods_payment_type'] != GoodsEnum::ISGOODS_PAYMENT_TYPE){
  119. throw new Exception('请在支付尾款的时候使用该优惠券');
  120. }
  121. //优惠券折扣
  122. if($user_coupon['mold_type'] == 1){
  123. //按比例折扣
  124. if($user_coupon['discount_ratio']>=1){
  125. throw new Exception('优惠券有误,请联系客服');
  126. }
  127. $order_coupon_amount = $order_amount*(1-$user_coupon['discount_ratio']);
  128. }else{
  129. $order_coupon_amount = $user_coupon['amount'];
  130. }
  131. if(!empty($user_coupon['max_deductible_price'])){
  132. $order_amount = ($order_coupon_amount>$user_coupon['max_deductible_price'])?($order_amount-$user_coupon['max_deductible_price']):($order_amount-$order_coupon_amount);
  133. }else{
  134. $order_amount = $order_amount-$order_coupon_amount;
  135. }
  136. $user_coupon->voucher_status = 1;
  137. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  138. $user_coupon->save();
  139. }
  140. //生成服务工单
  141. $work_data = [
  142. 'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
  143. 'real_name' => $params['contact_people'],
  144. 'mobile' => $params['contact_number'],
  145. 'address' => $params['address'],
  146. 'province' => $areas['province']??0,
  147. 'city' => $areas['city']??0,
  148. 'area_name' => $areas['area_name']??'',
  149. 'service_area_id' => $areas['id']??0,
  150. 'title' => $goods->goods_name,
  151. 'category_type' => $goods['category_type'],
  152. 'goods_category_ids' => $goods['goods_category_ids'],
  153. 'goods_category_id' => $goods['goods_category_id'],
  154. 'base_service_fee' => $goods['base_service_fee'],
  155. 'service_fee' => $goods['service_fee'],
  156. 'work_pay_status'=>WorkEnum::UN_PAY_STATUS,
  157. 'appointment_time' => strtotime($params['appointment_time']),
  158. 'user_id'=>$params['user_id'],
  159. 'lon'=>!empty($params['lon'])?$params['lon']:0,
  160. 'lat'=>!empty($params['lat'])?$params['lat']:0,
  161. 'property_activity_id'=>!empty($params['property_activity_id'])?$params['property_activity_id']:0,
  162. 'user_equity_id'=>$params['user_equity_id']??0,
  163. ];
  164. //判断是否是加单
  165. if(!empty($params['worker'])){
  166. $worker_id = MasterWorker::where('worker_number',$params['worker'])->value('id');
  167. $work_data['master_worker_id'] = $worker_id;
  168. $work_data['work_status'] = 4;
  169. $work_data['dispatch_time'] = time();
  170. $work_data['work_type'] = 2;
  171. $work_data['data_type'] = 1;
  172. }
  173. //判断是否是复购单
  174. $is_work = ServiceWork::where(['user_id'=>$params['user_id'],'service_status'=>3])->findOrEmpty();
  175. if(!$is_work->isEmpty()){
  176. $work_data['data_type'] = 1;
  177. }
  178. $service_work = ServiceWork::create($work_data);
  179. //使用权益卡时订单应支付金额=0
  180. if(isset($params['user_equity_id']) && $params['user_equity_id']){
  181. $userEquity = UserEquity::with(['equityConfig'])->where(['user_id'=>$params['user_id'],'id'=>$params['user_equity_id']])->findOrEmpty();
  182. if($userEquity->isEmpty() || (int)$userEquity['equityConfig']['status'] === 2){
  183. throw new Exception('您的权益卡已关闭,请重新选择权益卡!');
  184. }
  185. if(!isset($params['equity_external_source']) && (int)$userEquity['equityConfig']['is_oneself_operate'] === 2){
  186. throw new Exception('该权益卡无需自行下单!');
  187. }
  188. $order_total = 0;
  189. $order_amount = 0;
  190. }
  191. //生成服务订单
  192. $data = [
  193. 'work_id'=> $service_work['id'],
  194. 'sn' => generate_sn(RechargeOrder::class, 'sn'),
  195. 'order_type'=>0,//服务订单
  196. 'order_terminal' => $params['terminal'],
  197. 'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
  198. 'user_id' => $params['user_id'],
  199. 'pay_status' => PayEnum::UNPAID,
  200. 'coupon_id'=>!empty($params['coupon_id'])?$params['coupon_id']:0,
  201. 'coupon_price'=>!empty($order_coupon_amount)?$order_coupon_amount:0,
  202. 'pay_way' => $params['pay_way'],
  203. 'order_total' => $order_total,
  204. 'order_amount' => $order_amount,
  205. ];
  206. $order = RechargeOrder::create($data);
  207. //生成订单服务详情
  208. OrderGoods::create([
  209. 'sn' => $order['sn'],
  210. 'goods_id' => $params['goods_id'],
  211. 'category_type' => $goods['category_type'],
  212. 'goods_category_ids' => $goods['goods_category_ids'],
  213. 'goods_category_id' => $goods['goods_category_id'],
  214. 'goods_name' => $goods['goods_name'],
  215. 'goods_image' => $goods['goods_image'],
  216. 'goods_video' => $goods['goods_video'],
  217. 'goods_number' => $goods['goods_number'],
  218. 'good_unit' => $goods['good_unit'],
  219. 'goods_size' => $goods['goods_size'],
  220. 'goods_type' => $goods['goods_type'],
  221. 'goods_brand' => $goods['goods_brand'],
  222. 'install_guide' => $goods['install_guide'],
  223. 'goods_payment_type'=>$goods['goods_payment_type'],
  224. 'base_service_fee' => $goods['base_service_fee'],
  225. 'service_total' => $goods['service_total'],
  226. 'service_fee' => $goods['service_fee'],
  227. 'service_image' => $goods['service_image'],
  228. 'warranty_period'=>$goods['warranty_period'],
  229. 'fee_schedule' => $goods['fee_schedule'],
  230. 'goods_status' => $goods['goods_status'],
  231. ]);
  232. Db::commit();
  233. } catch (\Exception $e) {
  234. Db::rollback();
  235. self::setError($e->getMessage());
  236. return false;
  237. }
  238. return [
  239. 'order_id' => (int)$order['id'],
  240. 'work_id' => (int)$order['work_id'],
  241. ];
  242. }
  243. /**
  244. * 提交尾款订单
  245. * @param array $params
  246. * @return array|false
  247. */
  248. public static function submitFinalOrder($params)
  249. {
  250. Db::startTrans();
  251. try {
  252. $order = \app\common\model\recharge\RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  253. if ($order->isEmpty()) {
  254. throw new Exception('订单不存在');
  255. }
  256. //判断订单类型.服务订单尾款处理
  257. if($order['order_type'] == 0 and $order['pay_status'] == PayEnum::ISPAID)//服务工单
  258. {
  259. $order = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
  260. if($order->isEmpty()){
  261. throw new Exception('订单已支付');
  262. }
  263. }
  264. if ($order['pay_status'] == PayEnum::ISPAID) {
  265. throw new Exception('订单已支付');
  266. }
  267. $order_goods = OrderGoods::where('sn',$params['sn'])->findOrEmpty();
  268. $goods = Goods::findOrEmpty($order_goods['goods_id']);
  269. //判断是否存在优惠券
  270. if(!empty($params['coupon_id']) && empty($order['coupon_id'])){
  271. $user_coupon = UserCoupon::where(['id'=>$params['coupon_id'],'user_id'=>$params['user_id'],'voucher_status'=>0])
  272. ->where('voucher_count','>',0)
  273. ->where('expire_time','>=',time())
  274. ->where('begin_use','<',time())
  275. ->findOrEmpty();
  276. if($user_coupon->isEmpty()){
  277. throw new Exception('该优惠券不满足使用条件');
  278. }
  279. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE and $order['order_amount']<$user_coupon['amount_require']){
  280. throw new Exception('该优惠劵不满足满减使用条件');
  281. }
  282. //优惠券折扣
  283. if($user_coupon['mold_type'] == 1){
  284. //按比例折扣
  285. if($user_coupon['discount_ratio']>=1){
  286. throw new Exception('优惠券有误,请联系客服');
  287. }
  288. $order_coupon_amount = $order['order_amount']*(1-$user_coupon['discount_ratio']);
  289. }else{
  290. $order_coupon_amount = $user_coupon['amount'];
  291. }
  292. if(!empty($user_coupon['max_deductible_price'])){
  293. $order_amount = ($order_coupon_amount>$user_coupon['max_deductible_price'])?($order['order_amount']-$user_coupon['max_deductible_price']):($order['order_amount']-$order_coupon_amount);
  294. }else{
  295. $order_amount = $order['order_amount']-$order_coupon_amount;
  296. }
  297. $user_coupon->voucher_status = 1;
  298. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  299. $user_coupon->save();
  300. $order->coupon_id = !empty($params['coupon_id'])?$params['coupon_id']:0;
  301. $order->coupon_price = !empty($order_coupon_amount)?$order_coupon_amount:0;
  302. $order->order_amount = !empty($order_amount)?$order_amount:$order->order_amount;
  303. $order->save();
  304. }
  305. Db::commit();
  306. } catch (\Exception $e) {
  307. Db::rollback();
  308. self::setError($e->getMessage());
  309. return false;
  310. }
  311. return [
  312. 'order_id' => (int)$order['id'],
  313. 'work_id' => (int)$order['work_id'],
  314. ];
  315. }
  316. /**
  317. * 重置订单优惠券
  318. * * @param $params
  319. * * * @return array|false
  320. */
  321. public static function cancelOrderCoupon($params)
  322. {
  323. Db::startTrans();
  324. try {
  325. $order = \app\common\model\recharge\RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  326. if ($order->isEmpty()) {
  327. throw new Exception('订单不存在');
  328. }
  329. //判断订单类型.服务订单尾款处理
  330. if($order['order_type'] == 0 and $order['pay_status'] == PayEnum::ISPAID)//服务工单
  331. {
  332. $order = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
  333. if($order->isEmpty()){
  334. throw new Exception('订单已支付');
  335. }
  336. }
  337. if ($order['pay_status'] == PayEnum::ISPAID) {
  338. throw new Exception('订单已支付');
  339. }
  340. if(!empty($order['coupon_id'])){
  341. $user_coupon_ed = UserCoupon::findOrEmpty($order['coupon_id']);
  342. if(!$user_coupon_ed->isEmpty()){
  343. $user_coupon_ed->voucher_count = $user_coupon_ed->voucher_count+1;
  344. $user_coupon_ed->voucher_status = 0;
  345. $user_coupon_ed->save();
  346. $order->order_amount = $order->order_amount+$order->coupon_price;
  347. $order->coupon_id = 0;
  348. $order->coupon_price = 0;
  349. $order->save();
  350. }
  351. }
  352. Db::commit();
  353. } catch (\Exception $e) {
  354. Db::rollback();
  355. self::setError($e->getMessage());
  356. return false;
  357. }
  358. }
  359. /**
  360. * 获取订单工程师信息
  361. * * @param $params
  362. * * @return array|false
  363. */
  364. public static function getMasterWorker($params)
  365. {
  366. try {
  367. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  368. $query->visible(['goods_name','goods_image','goods_number','good_unit']);
  369. },'service_work'=>function ($query) {
  370. $query->visible(['real_name','mobile','address','service_status','appointment_time','master_worker_id','work_images','finished_images','finished_time'])->append(['service_status_text','user_service_status','user_service_status_text']);
  371. }])
  372. ->visible(['id','sn','payment_type','order_total','order_amount','pay_status','create_time','title','work_id'])
  373. ->where([
  374. 'order_type' => 0,
  375. 'user_id' => $params['user_id'],
  376. 'sn'=>$params['sn']
  377. ])->findOrEmpty()->toArray();
  378. $data = [];
  379. //获取工程师参数
  380. if(!empty($order_info['service_work']['master_worker_id'])){
  381. $worker = MasterWorker::find($order_info['service_work']['master_worker_id']);
  382. $data['avatar'] = $worker['avatar'];
  383. $data['real_name'] = $worker['real_name'];
  384. $data['worker_number'] = $worker['worker_number'];
  385. $data['mobile'] = $worker['mobile'];
  386. $maintain_exp_type = !empty($worker->worker_register->maintain_exp_type)?$worker->worker_register->maintain_exp_type:'';
  387. $data['worker_exp'] = DictData::where(['type_value'=>'worker_exp_type','value'=>$maintain_exp_type])->value('name');
  388. $data['appointment_time'] = $order_info['service_work']['appointment_time'];
  389. }
  390. return $data;
  391. }
  392. catch (\Exception $e) {
  393. self::setError($e->getMessage());
  394. return false;
  395. }
  396. }
  397. /**
  398. * 获取订单详情
  399. * @param $params
  400. * @return array|false
  401. */
  402. public static function detail($params)
  403. {
  404. try {
  405. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  406. $query->visible(['goods_id','goods_name','goods_image','goods_number','good_unit']);
  407. },'service_work'=>function ($query) {
  408. $query->visible(['id','work_sn','real_name','mobile','address','service_status','appointment_time','master_worker_id','work_images','explanation','finished_images','finished_time','spare_total','service_work_spare_id','refund_approval','property_activity_id','order_effective_id','external_platform_id'])->append(['service_status_text','user_service_status','user_service_status_text','external_platform_text']);
  409. }])
  410. ->visible(['id','sn','payment_type','order_total','order_amount','paid_amount','pay_status','create_time','title','work_id'])
  411. ->where([
  412. 'order_type' => 0,
  413. 'user_id' => $params['user_id'],
  414. 'sn'=>$params['sn']
  415. ])->findOrEmpty()->toArray();
  416. if(empty($order_info)){
  417. throw new Exception('订单不存在');
  418. }
  419. $order_info['master_worker'] = [
  420. 'avatar' => '',
  421. 'real_name'=>'',
  422. 'worker_number'=>'',
  423. 'mobile'=>'',
  424. 'worker_exp'=>''
  425. ];
  426. //查询总价
  427. $order_info['order_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('order_amount');
  428. $order_info['paid_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('paid_amount');
  429. //退款金额
  430. $order_refund_amount = 0;
  431. //获取工程师参数
  432. if(!empty($order_info['service_work']['master_worker_id'])){
  433. $worker = MasterWorker::find($order_info['service_work']['master_worker_id']);
  434. $order_info['master_worker']['avatar'] = !empty($worker)?$worker['avatar']:'';
  435. $order_info['master_worker']['real_name'] = !empty($worker)?$worker['real_name']:'';
  436. $order_info['master_worker']['worker_number'] = !empty($worker)?$worker['worker_number']:'';
  437. $order_info['master_worker']['mobile'] = !empty($worker)?$worker['mobile']:'';
  438. $maintain_exp_type = !empty($worker->worker_register->maintain_exp_type)?$worker->worker_register->maintain_exp_type:'';
  439. $order_info['master_worker']['worker_exp'] = DictData::where(['type_value'=>'worker_exp_type','value'=>$maintain_exp_type])->value('name');
  440. }
  441. //搜索当前工单下的所有订单记录
  442. $order_info['pay_orders'] = \app\common\model\recharge\RechargeOrder::where(['work_id'=>$order_info['work_id']])->field('id as order_id, pay_status ,refund_status,payment_type,pay_way,pay_time,order_total,order_amount,coupon_price')->order('id asc')->select()->toArray();
  443. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  444. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  445. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  446. $coupon_price = 0;
  447. foreach ($order_info['pay_orders'] as $k=>&$v){
  448. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  449. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  450. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  451. if($v['refund_status']==1){
  452. $order_refund_amount += $v['order_amount'];
  453. $refund_status = RefundRecord::where('order_id',$v['order_id'])->value('refund_status');
  454. }
  455. if($v['payment_type']!=1 and !empty($order_info['service_work']['spare_total'])){
  456. $v['order_amount_total'] = $v['order_amount'];
  457. $v['order_amount'] = $v['order_amount'] - $order_info['service_work']['spare_total'];
  458. }
  459. $coupon_price += $v['coupon_price'];
  460. }
  461. //汇总优惠卷额度
  462. $order_info['coupon_price'] = $coupon_price;
  463. //退款汇总
  464. $order_info['refund_amount'] = $order_refund_amount;
  465. if(isset($refund_status)){
  466. switch ($refund_status){
  467. case 0:
  468. $order_info['refund_status'] = '退款中';
  469. break;
  470. case 1:
  471. $order_info['refund_status'] = '退款成功';
  472. break;
  473. case 2:
  474. $order_info['refund_status'] = '退款失败';
  475. break;
  476. }
  477. }else{
  478. $order_info['refund_status'] = '未退款';
  479. }
  480. // 所有配件
  481. $order_info['spare_total'] = $order_info['service_work']['spare_total']??0;
  482. $order_info['spare_parts'] = [];
  483. if($order_info['service_work']['service_work_spare_id']){
  484. $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$order_info['service_work']['service_work_spare_id'])->value('spare_parts'),true);
  485. $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
  486. ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
  487. ->select()
  488. ->toArray();
  489. $spare_parts = array_column($spare_parts,null,'id');
  490. foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
  491. $spare_parts[$k] = array_merge($spare_parts[$k],$v);
  492. }
  493. $order_info['spare_parts'] = array_values($spare_parts)??[];
  494. }
  495. //获取所有的改约记录
  496. $order_info['appoint_list'] = [];
  497. $appoint_log = ServiceWorkAppointmentLog::where('work_id',$order_info['work_id'])->order('id desc')->select()->toArray();
  498. if(!empty($appoint_log)){
  499. $order_info['appoint_list'][0]['appointment_time'] = date('Y-m-d H:i:s',$appoint_log[0]['this_appointment_time']);
  500. foreach ($appoint_log as $k1=>$v1){
  501. $order_info['appoint_list'][$k1+1]['appointment_time'] = date('Y-m-d H:i:s',$v1['last_appointment_time']);
  502. }
  503. }
  504. //获取是否是活动工单
  505. if(!empty($order_info['service_work']['property_activity_id'])){
  506. $propertyActivity = PropertyActivity::findOrEmpty($order_info['service_work']['property_activity_id']);
  507. $order_info['service_work']['url_page'] = rawurlencode($params['domain'].'/static/wxapp/H5/'.$propertyActivity['url_page'].'/index.html?property_activity_id='.$propertyActivity['id'].'&token='.$params['user_info']['token']);
  508. }
  509. //保修工单时的信息
  510. $order_info['effective_income_amount'] = 0;
  511. if(!empty($order_info['service_work']['order_effective_id'])){
  512. $order_effective = OrderEffectiveLog:: findOrEmpty($order_info['service_work']['order_effective_id']);
  513. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  514. if($serviceWork->master_worker_id != $order_info['service_work']['master_worker_id']){
  515. $order_info['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  516. }
  517. }
  518. // 尾款报价信息
  519. if($order_info['service_work']['id']){
  520. $determinedPrice = ServiceWorkDeterminedPrice::where('work_id',$order_info['service_work']['id'])->findOrEmpty();
  521. if(!$determinedPrice->isEmpty()){
  522. $order_info['price_content'] = $determinedPrice->toArray()['content'];
  523. }
  524. }
  525. return $order_info;
  526. }
  527. catch (\Exception $e) {
  528. self::setError($e->getMessage());
  529. return false;
  530. }
  531. }
  532. public static function getDetailStatus($params)
  533. {
  534. try {
  535. $order_info = \app\common\model\recharge\RechargeOrder::with(['service_work'=>function ($query) {
  536. $query->visible(['work_sn'])->append(['service_status_text','user_service_status','user_service_status_text']);
  537. }])
  538. ->visible(['id','sn'])
  539. ->where([
  540. 'order_type' => 0,
  541. 'user_id' => $params['user_id'],
  542. 'sn'=>$params['sn']
  543. ])->findOrEmpty()->toArray();
  544. if(empty($order_info)){
  545. throw new Exception('订单不存在');
  546. }
  547. return $order_info;
  548. }
  549. catch (\Exception $e) {
  550. self::setError($e->getMessage());
  551. return false;
  552. }
  553. }
  554. /**
  555. * 获取订单支付详情--这个用于尾款支付的时候,自动使用了优惠券,不要随便调用
  556. * @param $params
  557. * @return array|false
  558. */
  559. public static function orderPayInfo($params)
  560. {
  561. Db::startTrans();
  562. try {
  563. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  564. $query->visible(['goods_id','goods_payment_type','goods_category_id']);
  565. },'service_work'=>function ($query) {
  566. $query->visible(['service_fee','spare_total','service_work_spare_id','goods_category_id']);
  567. }])
  568. ->visible(['id','pay_status','sn','work_id','coupon_id','coupon_price'])
  569. ->where([
  570. 'order_type' => 0,
  571. 'user_id' => $params['user_id'],
  572. 'sn'=>$params['sn']
  573. ])->findOrEmpty()->toArray();
  574. if(empty($order_info)){
  575. throw new Exception('订单不存在');
  576. }
  577. //查询总价
  578. $order_info['order_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('order_amount');
  579. $order_info['paid_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('paid_amount');
  580. //搜索当前工单下的所有订单记录
  581. $order_info['pay_orders'] = \app\common\model\recharge\RechargeOrder::where(['work_id'=>$order_info['work_id']])->field('id as order_id, pay_status,refund_status,payment_type,pay_way,pay_time,order_total,order_amount,coupon_id,coupon_price')->order('id asc')->select()->toArray();
  582. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  583. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  584. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  585. $coupon_price = 0;
  586. //退款金额
  587. $order_refund_amount = 0;
  588. $payment_type = 0;
  589. foreach ($order_info['pay_orders'] as $k=>&$v){
  590. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  591. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  592. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  593. if($v['refund_status']==1){
  594. $order_refund_amount += $v['order_amount'];
  595. $refund_status = RefundRecord::where('order_id',$v['order_id'])->value('refund_status');
  596. }
  597. if($v['payment_type']!=1 and !empty($order_info['service_work']['spare_total'])){
  598. $v['order_total'] = $v['order_total'] - $order_info['service_work']['spare_total'];
  599. $v['order_amount'] = $v['order_amount'] - $order_info['service_work']['spare_total'] + $v['coupon_price'];
  600. }
  601. if($v['pay_status']!=0){
  602. $coupon_price += $v['coupon_price'];
  603. }
  604. if($v['pay_status'] == 0){
  605. $order_info['coupon_id'] = $v['coupon_id'];
  606. $order_info['coupon_price'] = $v['coupon_price'];
  607. }
  608. $payment_type = $v['payment_type'];
  609. }
  610. $order_info['payment_type'] = $payment_type;
  611. //汇总优惠卷额度
  612. $order_info['coupon_price'] = $coupon_price;
  613. //退款汇总
  614. $order_info['refund_amount'] = $order_refund_amount;
  615. if(isset($refund_status)){
  616. switch ($refund_status){
  617. case 0:
  618. $order_info['refund_status'] = '退款中';
  619. break;
  620. case 1:
  621. $order_info['refund_status'] = '退款成功';
  622. break;
  623. case 2:
  624. $order_info['refund_status'] = '退款失败';
  625. break;
  626. }
  627. }else{
  628. $order_info['refund_status'] = '未退款';
  629. }
  630. // 所有配件
  631. $order_info['spare_total'] = $order_info['service_work']['spare_total']??0;
  632. $order_info['spare_parts'] = [];
  633. if($order_info['service_work']['service_work_spare_id']){
  634. $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$order_info['service_work']['service_work_spare_id'])->value('spare_parts'),true);
  635. $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
  636. ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
  637. ->select()
  638. ->toArray();
  639. $spare_parts = array_column($spare_parts,null,'id');
  640. foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
  641. $spare_parts[$k] = array_merge($spare_parts[$k],$v);
  642. }
  643. $order_info['spare_parts'] = array_values($spare_parts)??[];
  644. }
  645. //获取是否存在可使用优惠券
  646. if(!empty($order_info['coupon_id'])){
  647. $order_info['order_amount'] = $order_info['order_amount'] + $order_info['coupon_price'];
  648. $order_info['coupon'] = UserCoupon::where('id',$order_info['coupon_id'])->findOrEmpty()->toArray();
  649. $usable_coupon = true;
  650. }else{
  651. if(!empty($order_info['order_goods'][0])){
  652. $usable_coupon = UserCouponLogic::categoryWithAmountLists(['user_id'=>$params['user_id'],'amount'=>$order_info['order_amount'],'goods_category_id'=>$order_info['order_goods'][0]['goods_category_id'],'goods_id'=>$order_info['order_goods'][0]['goods_id']]);
  653. if(!empty($usable_coupon[0]['id'])){
  654. //绑定最新可使用优惠券
  655. $final_order = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id'],'pay_status'=>0])->findOrEmpty();
  656. if(!empty($final_order)){
  657. $user_coupon = UserCoupon::where('id',$usable_coupon[0]['id'])->findOrEmpty();
  658. $user_coupon->voucher_status = 1;
  659. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  660. $user_coupon->save();
  661. $final_order->coupon_id = $usable_coupon[0]['id'];
  662. $final_order->coupon_price = $usable_coupon[0]['amount'];
  663. $final_order->order_amount = $final_order->order_amount - $usable_coupon[0]['amount'];
  664. $final_order->save();
  665. $order_info['coupon'] = $usable_coupon[0];
  666. }
  667. }
  668. }
  669. }
  670. $order_info['usable_coupon'] = !empty($usable_coupon)?true:false;
  671. Db::commit();
  672. return $order_info;
  673. } catch (\Exception $e) {
  674. Db::rollback();
  675. self::setError($e->getMessage());
  676. return false;
  677. }
  678. }
  679. /**
  680. * 取消订单
  681. * @param $params
  682. * @return false|void
  683. */
  684. public static function cancelOrder($params)
  685. {
  686. Db::startTrans();
  687. try {
  688. $work_id = \app\common\model\recharge\RechargeOrder::where([
  689. 'order_type' => 0,
  690. 'user_id' => $params['user_id'],
  691. 'sn'=>$params['sn']
  692. ])->value('work_id');
  693. if(empty($work_id)){
  694. throw new Exception('订单不存在');
  695. }
  696. $payed_order = \app\common\model\recharge\RechargeOrder::where(['user_id'=>$params['user_id'],'work_id'=>$work_id,'pay_status'=>1])->findOrEmpty();
  697. if(!$payed_order->isEmpty()){
  698. throw new Exception('存在已支付订单,不允许取消订单,请联系客服');
  699. }
  700. //软删除订单
  701. $cancel_order = \app\common\model\recharge\RechargeOrder::where(['user_id'=>$params['user_id'],'work_id'=>$work_id])->findOrEmpty();
  702. $cancel_order->pay_status = 2;
  703. $cancel_order->save();
  704. //更新工单状态为已取消
  705. $service_work = ServiceWork::find($work_id);
  706. $service_work->service_status = 4;
  707. $service_work->save();
  708. //判断如果存在优惠券,返还优惠券
  709. if(!empty($payed_order->coupon_id)){
  710. $user_coupon = UserCoupon::where(['user_id'=>$payed_order->user_id,'id'=>$payed_order->coupon_id])->findOrEmpty();
  711. $user_coupon->voucher_status = 0;
  712. $user_coupon->voucher_count = $user_coupon->voucher_count+1;
  713. $user_coupon->save();
  714. }
  715. Db::commit();
  716. if($cancel_order->pay_time){
  717. // 订单取消通知【给用户】
  718. event('Notice', [
  719. 'scene_id' => 122,
  720. 'params' => [
  721. 'user_id' => $params['user_id']
  722. ]
  723. ]);
  724. }
  725. }
  726. catch (\Exception $e) {
  727. Db::rollback();
  728. self::setError($e->getMessage());
  729. return false;
  730. }
  731. }
  732. /**
  733. * 用户确认尾款报价单
  734. * @param $params
  735. * @return false|void
  736. */
  737. public static function confirmOrder($params)
  738. {
  739. Db::startTrans();
  740. try {
  741. $work_id = \app\common\model\recharge\RechargeOrder::where([
  742. 'order_type' => 0,
  743. 'user_id' => $params['user_id'],
  744. 'sn'=>$params['sn']
  745. ])->value('work_id');
  746. if(empty($work_id)){
  747. throw new Exception('订单不存在');
  748. }
  749. //更新工单状态为已取消
  750. $service_work = ServiceWork::find($work_id);
  751. if($service_work->user_confirm_status==2){
  752. throw new Exception('请勿重复操作');
  753. }
  754. $service_work->work_status = 5;
  755. $service_work->user_confirm_status = 2;
  756. $service_work->save();
  757. $work_log = [
  758. 'work_id'=>$work_id,
  759. 'master_worker_id'=>$service_work->master_worker_id,
  760. 'opera_log'=>'用户'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'确认了报价单',
  761. ];
  762. ServiceWorkLogLogic::add($work_log);
  763. Db::commit();
  764. }
  765. catch (\Exception $e) {
  766. Db::rollback();
  767. self::setError($e->getMessage());
  768. return false;
  769. }
  770. }
  771. /**
  772. * 用户确认服务完成
  773. * @param $params
  774. * @return false|void
  775. */
  776. public static function confirmServiceFinish($params)
  777. {
  778. Db::startTrans();
  779. try {
  780. $work_id = \app\common\model\recharge\RechargeOrder::where([
  781. 'order_type' => 0,
  782. 'user_id' => $params['user_id'],
  783. 'sn'=>$params['sn']
  784. ])->value('work_id');
  785. if(empty($work_id)){
  786. throw new Exception('订单不存在');
  787. }
  788. $service_work = ServiceWork::find($work_id);
  789. $orders = RechargeOrder::where(['work_id'=>$work_id,'user_id'=>$params['user_id']])->select()->toArray();
  790. //确认所有订单总金额和结算金额
  791. //若订单是全款已支付订单
  792. if(count($orders)==1 and $orders[0]['payment_type']==0 and $orders[0]['pay_status']==1){
  793. $service_work->work_status = 7;
  794. $service_work->user_confirm_status = 5;
  795. $service_work->service_status = 3;
  796. $service_work->work_pay_status = 1;
  797. }else{
  798. $service_work->work_status = 6;
  799. $service_work->user_confirm_status = 4;
  800. }
  801. if(isset($params['admin_id']) && $service_work->user_confirm_status!=3){
  802. \app\common\model\recharge\RechargeOrder::where([
  803. 'order_type' => 0,
  804. 'user_id' => $params['user_id'],
  805. 'pay_status' => 0,
  806. 'payment_type' => 2,
  807. 'sn'=>$params['sn']
  808. ])->update(['pay_status'=>1]);
  809. $service_work->work_status = 7;
  810. $service_work->user_confirm_status = 5;
  811. $service_work->service_status = 3;
  812. }
  813. $service_work->finished_time = time();
  814. $service_work->save();
  815. //保修工单时,且尾款=0,直接支付无需用户操作支付
  816. if($service_work->order_effective_id >0){
  817. $paid_amount = 0;
  818. $order_id = 0;
  819. foreach ($orders as $order) {
  820. if($order['payment_type'] == 2) $order_id = $order['id'];
  821. $paid_amount += $order['order_amount'];
  822. }
  823. if($paid_amount == 0){
  824. // 直接支付
  825. $order = PaymentLogic::getPayOrderInfo(['order_id'=>$order_id]);
  826. if ($order) {
  827. //支付流程
  828. $result = PaymentLogic::workerPay(1, 'goods', $order, ['terminal'=>0], '');
  829. /*if ($result && ($result['need_pay'] == 0)) {
  830. $service_work->work_status = 7;
  831. $service_work->user_confirm_status = 5;
  832. $service_work->service_status = 3;
  833. $service_work->work_pay_status = 1;
  834. }*/
  835. }
  836. }
  837. }
  838. //更新工程师的进行工单数量
  839. MasterWorker::setWorktotal('dec',$service_work->master_worker_id);
  840. $work_log = [
  841. 'work_id'=>$work_id,
  842. 'master_worker_id'=>$service_work->master_worker_id,
  843. 'opera_log'=>'用户'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'确认服务完成',
  844. ];
  845. ServiceWorkLogLogic::add($work_log);
  846. Db::commit();
  847. }
  848. catch (\Exception $e) {
  849. Db::rollback();
  850. self::setError($e->getMessage());
  851. return false;
  852. }
  853. }
  854. public static function approvalChangePrice($params)
  855. {
  856. Db::startTrans();
  857. try {
  858. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  859. if($order->isEmpty()){
  860. throw new Exception('订单不存在');
  861. }
  862. $work = ServiceWork::findOrEmpty($order->work_id);
  863. if($work->isEmpty()){
  864. throw new Exception('工单不存在');
  865. }
  866. $work->work_status = 4;
  867. $work->user_confirm_status = 0;
  868. $work->price_approval = 1;
  869. $work->save();
  870. Db::commit();
  871. }
  872. catch (\Exception $e) {
  873. Db::rollback();
  874. self::setError($e->getMessage());
  875. return false;
  876. }
  877. }
  878. public static function approvalChangeAppointment($params)
  879. {
  880. Db::startTrans();
  881. try {
  882. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  883. if($order->isEmpty()){
  884. throw new Exception('订单不存在');
  885. }
  886. $work = ServiceWork::findOrEmpty($order->work_id);
  887. if($work->isEmpty()){
  888. throw new Exception('工单不存在');
  889. }
  890. if($work->master_worker_id!=0){
  891. //更新工单未确认上门的状态
  892. $work->work_status = 3;
  893. $work->user_confirm_status = 0;
  894. $work->appoint_approval = 1;
  895. }
  896. ServiceWorkAppointmentLog::create([
  897. 'work_id'=>$work->id,
  898. 'last_appointment_time'=>strtotime($work->appointment_time),
  899. 'this_appointment_time'=>strtotime($params['appointment_time']),
  900. ]);
  901. //修改预计完成时间
  902. if ($work->estimated_finish_time) {
  903. $work->estimated_finish_time = strtotime($params['appointment_time']) + (strtotime($work->estimated_finish_time) - strtotime($work->appointment_time));
  904. }
  905. $work->appointment_time = strtotime($params['appointment_time']);
  906. $work->save();
  907. Db::commit();
  908. if($work->master_worker_id!=0){
  909. $workDetail = ServiceWorkAppointmentLog::where(['work_id'=>$work->id])->order('id desc')->findOrEmpty();
  910. $masterDetail = MasterWorkerLogic::detail(['id'=>$work->master_worker_id]);
  911. // 修改预约时间通知【给用户的通知】
  912. event('Notice', [
  913. 'scene_id' => 117,
  914. 'params' => [
  915. 'user_id' => $work->user_id,
  916. 'date' => $params['appointment_time'],
  917. 'tel' => asteriskString($masterDetail['mobile']),
  918. ]
  919. ]);
  920. // 修改预约时间通知【给工程师的通知,仅限公众号】
  921. event('Notice', [
  922. 'scene_id' => 118,
  923. 'params' => [
  924. 'user_id' => $work->master_worker_id,
  925. 'order_id' => $work->id,
  926. 'thing4' => $work->title,
  927. 'time5' => date('Y-m-d H:i:s',$workDetail['last_appointment_time']),
  928. 'time6' => date('Y-m-d H:i:s',$workDetail['this_appointment_time']),
  929. 'thing11' => addressOmit($work->address),
  930. 'phone_number8' => asteriskString($work->mobile),
  931. ]
  932. ]);
  933. }
  934. }
  935. catch (\Exception $e) {
  936. Db::rollback();
  937. self::setError($e->getMessage());
  938. return false;
  939. }
  940. return $work;
  941. }
  942. public static function approvalRefund($params)
  943. {
  944. Db::startTrans();
  945. try {
  946. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  947. if($order->isEmpty()){
  948. throw new Exception('订单不存在');
  949. }
  950. $work = ServiceWork::findOrEmpty($order->work_id);
  951. if($work->isEmpty()){
  952. throw new Exception('工单不存在');
  953. }
  954. $work->refund_approval = 1;
  955. $work->save();
  956. //判断是否已下单时间过了两小时,并且师傅暂未上门,距离预约时间两小时以上
  957. if(($order['pay_time']+7200)>time() and $work['work_status']<4 and (strtotime($work['appointment_time'])-7200)>time()){
  958. //生成退款订单
  959. \app\common\model\recharge\RechargeOrder::update([
  960. 'id' => $order['id'],
  961. 'refund_status' => YesNoEnum::YES,
  962. ]);
  963. // 生成退款记录
  964. $recordSn = generate_sn(RefundRecord::class, 'sn');
  965. $record = RefundRecord::create([
  966. 'sn' => $recordSn,
  967. 'user_id' => $order['user_id'],
  968. 'order_id' => $order['id'],
  969. 'order_sn' => $order['sn'],
  970. 'order_type' => RefundEnum::ORDER_TYPE_ORDER,
  971. 'order_amount' => $order['order_amount'],
  972. 'refund_amount' => $order['order_amount'],
  973. 'refund_type' => RefundEnum::TYPE_ADMIN,
  974. 'transaction_id' => $order['transaction_id'] ?? '',
  975. 'refund_way' => RefundEnum::getRefundWayByPayWay($order['pay_way']),
  976. ]);
  977. //更新工单状态
  978. ServiceWork::update([
  979. 'id'=>$order['work_id'],
  980. 'service_status'=>5
  981. ]);
  982. // 退款
  983. RefundLogic::refund($order, $record['id'], $order['order_amount'], 1);
  984. }
  985. Db::commit();
  986. }
  987. catch (\Exception $e) {
  988. Db::rollback();
  989. self::setError($e->getMessage());
  990. return false;
  991. }
  992. }
  993. /**
  994. * 订单完成通知【给用户】 - 全款 -通知
  995. * @param $params
  996. * @return bool
  997. */
  998. public static function serviceFinishNotice($params)
  999. {
  1000. try {
  1001. $order = RechargeOrder::where('sn', $params['sn'])
  1002. ->where('payment_type','=',0)
  1003. ->where('pay_status','=',1)
  1004. ->findOrEmpty();
  1005. if(!$order->isEmpty()){
  1006. event('Notice', [
  1007. 'scene_id' => 120,
  1008. 'params' => [
  1009. 'user_id' => $order['user_id']
  1010. ]
  1011. ]);
  1012. }
  1013. return true;
  1014. }catch (\Exception $e) {
  1015. return false;
  1016. }
  1017. }
  1018. /**
  1019. * 工程师完单的时候设置单量规则 - 通知
  1020. * @param $params
  1021. * @return bool
  1022. */
  1023. public static function orderQuantityRule($params)
  1024. {
  1025. try {
  1026. $work_id = \app\common\model\recharge\RechargeOrder::where([
  1027. 'order_type' => 0,
  1028. 'user_id' => $params['user_id'],
  1029. 'sn'=>$params['sn']
  1030. ])->value('work_id');
  1031. if(empty($work_id)){
  1032. throw new Exception('订单不存在');
  1033. }
  1034. $service_work = ServiceWork::find($work_id);
  1035. $commission_config_id = MasterWorkerCommissionConfig::where('voucher_status','=',2)
  1036. ->where('master_worker_id', $service_work['master_worker_id'])
  1037. ->value('id');
  1038. if($commission_config_id){
  1039. // 工程师完单的时候设置该规则关闭,以及短信通知工程师
  1040. $noticeRule = Db::name('master_worker_commission_notice')->alias('n')
  1041. ->leftJoin('service_work sw', 'n.master_worker_id = sw.master_worker_id AND sw.create_time >= n.signing_date AND sw.create_time <= n.signing_date_end')
  1042. ->field([
  1043. 'n.id', 'n.commission_config_id', 'n.master_worker_id', 'n.day_num', 'n.order_num', 'n.signing_date', 'n.signing_date_end','n.is_notice',
  1044. Db::raw("COUNT(sw.id) AS order_count")
  1045. ])
  1046. ->where('n.commission_config_id', $commission_config_id)
  1047. ->group('n.master_worker_id, n.id')
  1048. ->select()->toArray();
  1049. $is_off = true;
  1050. foreach ($noticeRule as $item) {
  1051. if($item['order_num'] <= $item['order_count'] && empty($item['is_notice'])){
  1052. Log::info('orderQuantityRule:'.json_encode($item));
  1053. MasterWorkerCommissionNotice::where('id',$item['id'])->update([
  1054. 'is_notice'=>1
  1055. ]);
  1056. event('Notice', [
  1057. 'scene_id' => 128,
  1058. 'params' => [
  1059. 'user_id' => $service_work['master_worker_id'],
  1060. 'number1' => $item['day_num'],
  1061. 'number' => $item['order_num']
  1062. ]
  1063. ]);
  1064. }
  1065. if($item['order_num'] > $item['order_count']){
  1066. $is_off = false;
  1067. }
  1068. }
  1069. if($is_off){
  1070. MasterWorkerCommissionConfig::where('id',$commission_config_id)->update([
  1071. 'voucher_status'=>1
  1072. ]);
  1073. }
  1074. }
  1075. return true;
  1076. }catch (\Exception $e) {
  1077. Log::info('orderQuantityRule:'.$e->getMessage());
  1078. return false;
  1079. }
  1080. }
  1081. /**
  1082. * 提交订单
  1083. * @param array $params
  1084. * @return array|false
  1085. */
  1086. public static function firmSubmitOrder($params)
  1087. {
  1088. Db::startTrans();
  1089. try {
  1090. // 订单位置是否在服务区内
  1091. $areas = self::isService($params);
  1092. $goods = Goods::findOrEmpty($params['goods_id']);
  1093. if($goods->isEmpty()){
  1094. throw new Exception('产品不存在!');
  1095. }
  1096. if(empty($params['user_info']['mobile'])){
  1097. throw new Exception('请先补充您的联系方式后在提交订单');
  1098. }
  1099. //根据服务工单计算当前订单应支付金额
  1100. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE){
  1101. //一口价订单
  1102. $order_total = $goods['service_fee'];
  1103. $order_amount = $goods['service_fee'];
  1104. }else if ($goods['goods_payment_type'] == GoodsEnum::DEP_GOODS_PAYMENT_TYPE){
  1105. $order_total = $goods['service_fee'];
  1106. $order_amount = $goods['service_fee'];
  1107. }
  1108. else{
  1109. $order_total = $goods['base_service_fee'];
  1110. $order_amount = $goods['service_fee'];
  1111. }
  1112. //生成服务工单
  1113. $work_data = [
  1114. 'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
  1115. 'real_name' => $params['contact_people'],
  1116. 'mobile' => $params['contact_number'],
  1117. 'address' => $params['address'],
  1118. 'title' => $goods->goods_name . '*' . $goods->goods_number.$goods->good_unit,
  1119. 'category_type' => $goods['category_type'],
  1120. 'goods_category_ids' => $goods['goods_category_ids'],
  1121. 'goods_category_id' => $goods['goods_category_id'],
  1122. 'base_service_fee' => $goods['base_service_fee'],
  1123. 'service_fee' => $goods['service_fee'],
  1124. 'work_pay_status'=>WorkEnum::UN_PAY_STATUS,
  1125. 'work_type'=> 1,
  1126. 'appointment_time' => strtotime($params['appointment_time']),
  1127. 'user_id'=>$params['user_id'],
  1128. 'lon'=>!empty($params['lon'])?$params['lon']:0,
  1129. 'lat'=>!empty($params['lat'])?$params['lat']:0,
  1130. 'province' => $areas['province']??0,
  1131. 'city' => $areas['city']??0,
  1132. 'area_name' => $areas['area_name']??'',
  1133. 'service_area_id' => $areas['id']??0,
  1134. ];
  1135. $service_work = ServiceWork::create($work_data);
  1136. //生成服务订单
  1137. $data = [
  1138. 'work_id'=> $service_work['id'],
  1139. 'sn' => generate_sn(RechargeOrder::class, 'sn'),
  1140. 'order_type'=>0,//服务订单
  1141. 'order_terminal' => $params['terminal'],
  1142. 'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
  1143. 'user_id' => $params['user_id'],
  1144. 'pay_status' => PayEnum::UNPAID,
  1145. 'coupon_id'=>!empty($params['coupon_id'])?$params['coupon_id']:0,
  1146. 'coupon_price'=>!empty($order_coupon_amount)?$order_coupon_amount:0,
  1147. 'pay_way' => $params['pay_way'],
  1148. 'order_total' => $order_total,
  1149. 'order_amount' => $order_amount,
  1150. ];
  1151. $order = RechargeOrder::create($data);
  1152. //生成订单服务详情
  1153. OrderGoods::create([
  1154. 'sn' => $order['sn'],
  1155. 'goods_id' => $params['goods_id'],
  1156. 'category_type' => $goods['category_type'],
  1157. 'goods_category_ids' => $goods['goods_category_ids'],
  1158. 'goods_category_id' => $goods['goods_category_id'],
  1159. 'goods_name' => $goods['goods_name'],
  1160. 'goods_image' => $goods['goods_image'],
  1161. 'goods_video' => $goods['goods_video'],
  1162. 'goods_number' => $goods['goods_number'],
  1163. 'good_unit' => $goods['good_unit'],
  1164. 'goods_size' => $goods['goods_size'],
  1165. 'goods_type' => $goods['goods_type'],
  1166. 'goods_brand' => $goods['goods_brand'],
  1167. 'install_guide' => $goods['install_guide'],
  1168. 'goods_payment_type'=>$goods['goods_payment_type'],
  1169. 'base_service_fee' => $goods['base_service_fee'],
  1170. 'service_total' => $goods['service_total'],
  1171. 'service_fee' => $goods['service_fee'],
  1172. 'service_image' => $goods['service_image'],
  1173. 'warranty_period'=>$goods['warranty_period'],
  1174. 'fee_schedule' => $goods['fee_schedule'],
  1175. 'goods_status' => $goods['goods_status'],
  1176. ]);
  1177. Db::commit();
  1178. } catch (\Exception $e) {
  1179. Db::rollback();
  1180. self::setError($e->getMessage());
  1181. return false;
  1182. }
  1183. return [
  1184. 'order_id' => (int)$order['id'],
  1185. 'work_id' => (int)$order['work_id'],
  1186. ];
  1187. }
  1188. /**
  1189. * 绑定工程师-设置为加单
  1190. * * @param array $params
  1191. * * @return array|false
  1192. */
  1193. public static function bindWorkerAndWork(array $params)
  1194. {
  1195. Db::startTrans();
  1196. try {
  1197. $order = RechargeOrder::where(['sn'=>$params['sn'],'user_id'=>$params['user_id']])->findOrEmpty();
  1198. if($order->isEmpty()){
  1199. throw new Exception('订单不存在');
  1200. }
  1201. $work = ServiceWork::where(['id'=>$order['work_id']])->findOrEmpty();
  1202. if($work->isEmpty()){
  1203. throw new Exception('工单不存在');
  1204. }
  1205. /*if($work['work_status']!=WorkEnum::WORK_STATUS_WAIT_SERVICE){
  1206. throw new Exception('工单状态不正确,无法绑定');
  1207. }*/
  1208. // 20250310 未上门状态强转新工程师
  1209. if((int)$work['work_status'] > 3){
  1210. throw new Exception('工单状态不正确,无法绑定');
  1211. }
  1212. $worker = MasterWorker::where('id',$params['worker_id'])->findOrEmpty();
  1213. if($worker->isEmpty()){
  1214. throw new Exception('工程师不存在');
  1215. }
  1216. $work->master_worker_id = $params['worker_id'];
  1217. $work->work_status = WorkEnum::WORK_STATUS_WORKER;
  1218. $work->receive_time = time();
  1219. $work->work_type = 2;//加单状态
  1220. $work->save();
  1221. Db::commit();
  1222. } catch (\Exception $e) {
  1223. Db::rollback();
  1224. self::setError($e->getMessage());
  1225. return false;
  1226. }
  1227. }
  1228. /**
  1229. * 0元支付直接完成支付
  1230. * @param array $params attach out_trade_no
  1231. * @return bool|void
  1232. */
  1233. public static function zeroDirectlyPayment(array $params, $extra = [])
  1234. {
  1235. try {
  1236. $message['out_trade_no'] = mb_substr($params['out_trade_no'], 0, 18);
  1237. $order = RechargeOrder::where(['sn' => $params['out_trade_no']])->findOrEmpty();
  1238. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  1239. return true;
  1240. }
  1241. switch ($params['attach']) {
  1242. case 'recharge':
  1243. PayNotifyLogic::handle('recharge', $params['out_trade_no'], $extra);
  1244. break;
  1245. case 'goods':
  1246. $res = PayNotifyLogic::handle('goods', $params['out_trade_no'], $extra);
  1247. if($res === true){
  1248. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  1249. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  1250. ->where('payment_type','IN',[0,1])
  1251. ->where('pay_status','=',1)
  1252. ->findOrEmpty();
  1253. if(!$order->isEmpty()){
  1254. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  1255. if(!$workDetail->isEmpty()){
  1256. event('Notice', [
  1257. 'scene_id' => 100,
  1258. 'params' => [
  1259. 'user_id' => 0,
  1260. 'order_id' => $workDetail['id'],
  1261. 'thing3' => $workDetail['title'],
  1262. 'time6' => $workDetail['appointment_time'],
  1263. 'phone_number8' => asteriskString($workDetail['mobile']),
  1264. 'thing5' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  1265. ]
  1266. ]);
  1267. }
  1268. }
  1269. // 订单完成通知【给用户】 - 尾款 -通知
  1270. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  1271. ->where('payment_type','=',2)
  1272. ->where('pay_status','=',1)
  1273. ->findOrEmpty();
  1274. if(!$order->isEmpty()){
  1275. event('Notice', [
  1276. 'scene_id' => 120,
  1277. 'params' => [
  1278. 'user_id' => $order['user_id']
  1279. ]
  1280. ]);
  1281. }
  1282. }
  1283. break;
  1284. }
  1285. return true;
  1286. } catch (\Exception $e) {
  1287. self::setError($e->getMessage());
  1288. return false;
  1289. }
  1290. }
  1291. }