WholeController.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\order\OrderService;
  4. use app\admin\validate\coupon\CouponValidate;
  5. use app\admin\validate\device\DeviceValidate;
  6. use app\admin\validate\order\OrderExpressValidate;
  7. use app\admin\validate\order\OrderValidate;
  8. use app\common\payment\AppUtil;
  9. use app\common\payment\Tlpay;
  10. use app\controller\Curd;
  11. use app\model\Appointment;
  12. use app\model\ClientConfig;
  13. use app\model\Coupon;
  14. use app\model\Device;
  15. use app\model\Goods;
  16. use app\model\GoodsComponent;
  17. use app\model\Member;
  18. use app\model\MemberAccount;
  19. use app\model\MemberBenefit;
  20. use app\model\MemberRole;
  21. use app\model\Order;
  22. use app\model\OrderExpress;
  23. use app\model\OrderReturn;
  24. use app\model\OrderSheet;
  25. use app\model\PayDetail;
  26. use app\model\Premises;
  27. use app\model\Supplier;
  28. use app\model\SysDept;
  29. use app\model\SysSerial;
  30. use app\model\SysUser;
  31. use Payment\Common\PayException;
  32. use support\Db;
  33. use support\exception\BusinessException;
  34. use support\Redis;
  35. use support\Request;
  36. use support\Response;
  37. use function Qiniu\Http\Middleware\compose;
  38. class WholeController extends Curd
  39. {
  40. public function __construct()
  41. {
  42. $this->model = new Order();
  43. $this->validate = true;
  44. $this->validateClass = new OrderValidate();
  45. }
  46. /**
  47. * @Desc 列表
  48. * @Author Gorden
  49. * @Date 2024/3/28 15:01
  50. *
  51. * @param Request $request
  52. * @return Response
  53. * @throws \support\exception\BusinessException
  54. */
  55. public function select(Request $request): Response
  56. {
  57. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  58. if (!empty($where['order_addtimes'])) {
  59. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  60. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  61. }
  62. $order = $request->get('order', 'desc');
  63. $field = $field ?? 'order_addtimes';
  64. if (!empty($where['order_status_system']) && in_array($where['order_status_system'],['PENDING','WAITING','SENDING','RECVING','SIGNED','CONFIRM'])){
  65. $where['order_is_complete'] = 'N';
  66. }
  67. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
  68. unset($where['order_status_system']);
  69. unset($where['order_is_complete']);
  70. $where['order_category'] = 'RETURN';
  71. }
  72. $query = $this->doSelect($where, $field, $order);
  73. return $this->doFormat($query, $format, $limit);
  74. }
  75. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  76. {
  77. $model = $this->model->with([
  78. 'sheet' => function ($query) {
  79. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id');
  80. },
  81. 'member' => function ($query) {
  82. $query->select('member_id', 'member_mobile');
  83. },
  84. 'cert' => function ($query) {
  85. $query->select('join_cert_member_id', 'member_cert_name');
  86. },
  87. 'return' => function($query){
  88. $query->select('orders_return_id','join_return_order_id', 'order_return_status');
  89. },
  90. 'express' => function($query){
  91. $query->select('join_express_order_id','order_express_type');
  92. }
  93. ]);
  94. foreach ($where as $column => $value) {
  95. if (is_array($value)) {
  96. if ($value[0] === 'like' || $value[0] === 'not like') {
  97. $model = $model->where($column, $value[0], "%$value[1]%");
  98. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  99. $model = $model->where($column, $value[0], $value[1]);
  100. } elseif ($value[0] == 'in' && !empty($value[1])) {
  101. $valArr = $value[1];
  102. if (is_string($value[1])) {
  103. $valArr = explode(",", trim($value[1]));
  104. }
  105. $model = $model->whereIn($column, $valArr);
  106. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  107. $valArr = $value[1];
  108. if (is_string($value[1])) {
  109. $valArr = explode(",", trim($value[1]));
  110. }
  111. $model = $model->whereNotIn($column, $valArr);
  112. } elseif ($value[0] == 'null') {
  113. $model = $model->whereNull($column);
  114. } elseif ($value[0] == 'not null') {
  115. $model = $model->whereNotNull($column);
  116. } elseif ($value[0] !== '' || $value[1] !== '') {
  117. $model = $model->whereBetween($column, $value);
  118. }
  119. } else {
  120. $model = $model->where($column, $value);
  121. }
  122. }
  123. if ($field) {
  124. $model = $model->orderBy($field, $order);
  125. }
  126. return $model;
  127. }
  128. public function afterQuery($items)
  129. {
  130. foreach ($items as &$item) {
  131. if (!empty($item['sheet'])) {
  132. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  133. $item['sheet']['goods_name'] = $goods->goods_name ?? '';
  134. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  135. }
  136. }
  137. return $items;
  138. }
  139. /**
  140. * @Desc 订单商品详情
  141. * @Author Gorden
  142. * @Date 2024/3/29 8:50
  143. *
  144. * @param Request $request
  145. * @return Response
  146. */
  147. public function sheet(Request $request)
  148. {
  149. $orderId = $request->get('order_id');
  150. $orderSheet = OrderSheet::with([
  151. 'member' => function ($query) {
  152. $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id');
  153. },
  154. 'goods' => function ($query) {
  155. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  156. },
  157. 'memberInfo',
  158. 'cert',
  159. 'skus' => function ($query) {
  160. $query->where('goods_sku_status', 'ON')
  161. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  162. },
  163. 'refund'=>function($query){
  164. $query->select('join_return_order_id','order_return_status');
  165. }
  166. ])->where('join_sheet_order_id', $orderId)
  167. ->get()
  168. ->toArray();
  169. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  170. $premises = '';
  171. if($express && $express->order_express_type == '自提'){
  172. $premises = $express->order_express_company;
  173. }
  174. // if (!empty($express->order_express_code)){
  175. // $expressCode = explode(':',$express->order_express_code);
  176. // if(count($expressCode) == 2){
  177. // $express->order_express_company = $expressCode[0];
  178. // $express->order_express_code = $expressCode[1];
  179. // }
  180. // }
  181. foreach ($orderSheet as &$item) {
  182. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  183. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  184. $components = GoodsComponent::with('goods')
  185. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  186. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  187. 'goods_component_price', 'goods_component_json')
  188. ->get()
  189. ->toArray();
  190. $goodsArr = [];
  191. foreach ($components as $component) {
  192. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  193. if (!empty($component['goods'])) {
  194. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  195. $goodsArr[] = [
  196. 'goods_name' => $component['goods']['goods_name'],
  197. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  198. 'supplier_name' => $supplierName,
  199. 'nbr' => $configJson['nbr'] ?? 0,
  200. ];
  201. }
  202. }
  203. $item['goods']['components'] = $goodsArr;
  204. }
  205. if (!empty($item['skus'])) {
  206. foreach ($item['skus'] as $k => $sku) {
  207. if (!empty($sku['goods_sku_specs_json'])) {
  208. $specsJson = json_decode($sku['goods_sku_specs_json'], true);
  209. $skuName = '';
  210. foreach ($specsJson as $specsKey => $skuSpecs) {
  211. if (is_array($skuSpecs)) {
  212. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  213. } else {
  214. $skuName = $skuName . ' ' . $skuSpecs . ';';
  215. }
  216. }
  217. $item['skus'][$k]['goods_sku_title'] = rtrim($skuName, ';');
  218. }
  219. }
  220. }
  221. if ($item['goods']['goods_classify'] == 'SERVICE') {
  222. $benifit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  223. ->where('join_benefit_order_id', $orderId)
  224. ->first();
  225. if(!empty($benifit)){
  226. $item['benefit'] = [
  227. 'total' => intval($benifit->member_benefit_limit_count),
  228. 'used' => intval($benifit->member_benefit_used_count),
  229. 'cut' => $benifit->member_benefit_limit_count - $benifit->member_benefit_used_count,
  230. ];
  231. $appontments = Appointment::where('join_appointment_member_benefit_id', $benifit->member_benefit_id)
  232. ->where('appointment_status', 'DONE')
  233. ->select('appointment_id', 'appointment_done_datetime', 'appointment_done_json')
  234. ->get()
  235. ->toArray();
  236. $item['appontment'] = [];
  237. foreach ($appontments as $appontment) {
  238. $doneJson = [];
  239. $username = '';
  240. if (!empty($appontment['appointment_done_json'])) {
  241. $doneJson = json_decode($appontment['appointment_done_json'], true);
  242. if (isset($doneJson['charge'])) {
  243. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  244. }
  245. }
  246. $item['appontment'][] = [
  247. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  248. 'goods_name' => $item['goods']['goods_name'],
  249. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  250. 'username' => $username,
  251. 'nbr' => 1,
  252. 'done_time' => $appontment['appointment_done_datetime']
  253. ];
  254. }
  255. }
  256. }
  257. if (!empty($item['order_sheet_extend_json']) && !$express) {
  258. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  259. if (isset($extendJson['address_id'])) {
  260. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  261. if (!empty($address)) {
  262. $valJson = json_decode($address->client_config_val_json, true);
  263. $express = [
  264. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  265. 'order_express_city' => $valJson['city'],
  266. 'order_express_mobile' => $valJson['mobile'],
  267. 'order_express_person' => $valJson['person']
  268. ];
  269. }
  270. }
  271. }
  272. $item['member']['level'] = '普通用户';
  273. if (!empty($item['member']['join_member_role_id'])) {
  274. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  275. }
  276. }
  277. $order = Order::where('order_id', $orderId)->first();
  278. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
  279. ->select('pay_id', 'pay_category', 'pay_prepayid','pay_paytimes','pay_status')
  280. ->first();
  281. if(!empty($payDetail->pay_prepayid)){
  282. $categoryArray = explode('-',$payDetail->pay_prepayid);
  283. if (isset($categoryArray[1])){
  284. $payDetail->pay_category = $categoryArray[1];
  285. }else if(in_array($categoryArray[0],['A01','W06'])){
  286. $payDetail->pay_category = $categoryArray[0];
  287. }else{
  288. if (MemberAccount::where('member_account_nbr',$categoryArray[0])->where('member_account_classify','CARD')->exists()){
  289. $payDetail->pay_category = 'CARD';
  290. }else{
  291. $payDetail->pay_category = 'CASH';
  292. }
  293. }
  294. }else if(!empty($payDetail)){
  295. $payDetail->pay_category = 'CASH';
  296. }
  297. if (!empty($order->order_config_json)){
  298. $orderConfigJson = json_decode($order->order_config_json,true);
  299. if(isset($orderConfigJson['reach'])){
  300. $order->reach = $orderConfigJson['reach'];
  301. }
  302. if(isset($orderConfigJson['table'])){
  303. $order->table = $orderConfigJson['table'];
  304. }
  305. // if(isset($orderConfigJson['express'])){
  306. // $order->express = $orderConfigJson['express'];
  307. // }
  308. // if(isset($orderConfigJson['premises'])){
  309. // $order->premises = $orderConfigJson['premises'];
  310. // }
  311. }
  312. $order->premises = $premises;
  313. $data = [
  314. 'order' => $order,
  315. 'sheet' => $orderSheet,
  316. 'express' => $express,
  317. 'payDetail' => $payDetail
  318. ];
  319. return json_success('', $data);
  320. }
  321. public function update(Request $request): Response
  322. {
  323. $params = $request->post();
  324. try {
  325. Db::beginTransaction();
  326. // 修改主订单
  327. // $this->updateMain($params);
  328. // 修改物流
  329. $this->updateExpress($params);
  330. Db::commit();
  331. return json_success('修改订单成功');
  332. } catch (\Exception $e) {
  333. Db::rollBack();
  334. return json_fail('修改订单失败');
  335. }
  336. }
  337. public function updateExpress($params){
  338. $express = OrderExpress::where('join_express_order_id',$params['order_id'])->first();
  339. if(!$express){
  340. throw new BusinessException('物流信息异常');
  341. }
  342. if($params['delivery'] == 'PICKUP'){
  343. $premises = SysDept::where('dept_category','营业场所')->where('dept_name',$params['dept_premises_id'])->first();
  344. $express->order_express_type = '自提';
  345. $express->order_express_city = str_replace(',',' ',$premises->dept_city);
  346. $express->order_express_address = $premises->dept_address;
  347. $express->order_express_mobile = '';
  348. $express->order_express_person = '';
  349. $express->order_express_telephone = $premises->dept_telephone ?? '';
  350. $express->order_express_company = $params['dept_premises_id'];
  351. }else if($params['delivery'] == 'LOGISTICS'){
  352. $express->order_express_type = '配送';
  353. $express->order_express_city = $params['order_express_city'] ?? '';
  354. $express->order_express_address = $params['order_express_address'] ?? '';
  355. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  356. $express->order_express_person = $params['order_express_person'] ?? '';
  357. $express->order_express_telephone = '';
  358. $express->order_express_company = '';
  359. }
  360. try{
  361. if(($params['delivery'] == 'PICKUP') || ($params['delivery'] == 'LOGISTICS')){
  362. $express->save();
  363. }
  364. }catch(\Exception $e){
  365. dump($e->getTrace());
  366. throw new BusinessException('修改配送方式失败');
  367. }
  368. }
  369. public function delete(Request $request): Response
  370. {
  371. $params = $request->post();
  372. try {
  373. Db::beginTransaction();
  374. $order = Order::where('order_id', $params['order_id'])
  375. ->where('order_status_system','CANCEL')
  376. ->orWhere(function($query){
  377. $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM');
  378. })
  379. ->first();
  380. if (!$order) {
  381. return json_fail('此订单不允许删除');
  382. }
  383. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  384. if ($payDetail->pay_category == 'CASH') {
  385. $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
  386. ->where('member_account_classify', 'CASH')
  387. ->first();
  388. $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
  389. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
  390. $memberAccount->save();
  391. }
  392. // 删支付记录
  393. $payDetail->delete();
  394. // 删收货信息
  395. OrderExpress::where('join_express_order_id', $params['order_id'])->delete();
  396. // 删订单详情
  397. OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete();
  398. // 删主订单
  399. $order->delete();
  400. Db::commit();
  401. return json_success('删除订单成功');
  402. } catch (\Exception $e) {
  403. dump($e->getMessage());
  404. Db::rollBack();
  405. return json_fail('删除订单失败');
  406. }
  407. }
  408. public function insert(Request $request): Response
  409. {
  410. $params = $request->post();
  411. try {
  412. Db::beginTransaction();
  413. // 余额支付
  414. if ($params['pay_category'] == 'CASH') {
  415. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  416. ->where('member_account_classify', 'CASH')
  417. ->where('member_account_status', 'ACTIVED')
  418. ->first();
  419. if (!$account) {
  420. return json_fail('账户异常');
  421. }
  422. $amount = $account->member_account_surplus + $account->member_account_added;
  423. if (!$account || $params['order_sheet_pay'] > $amount) {
  424. return json_fail('账户余额不足');
  425. }
  426. if ($params['order_sheet_pay'] > $account->member_account_surplus) {
  427. $cut = $account->member_account_added - ($params['order_sheet_pay'] - $account->member_account_surplus);
  428. $account->member_account_surplus = 0;
  429. $account->member_account_added = $cut;
  430. } else {
  431. $account->member_account_surplus = $account->member_account_surplus - $params['order_sheet_pay'];
  432. }
  433. $account->member_account_expend = $account->member_account_expend + $params['order_sheet_pay'];
  434. $account->save();
  435. }
  436. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  437. ->select('goods_id', 'goods_name', 'goods_classify')
  438. ->first();
  439. if (!$goods) {
  440. return json_fail('产品数据异常');
  441. }
  442. $goods = $goods->toArray();
  443. $params['goods_classify'] = $goods['goods_classify'];
  444. $writeOffDate = [];
  445. // 服务已完成,生成核销数据
  446. if ($params['order_status_system'] == 'DONE' && in_array($goods['goods_classify'], ['SERVICE', 'PACKAGE'])) {
  447. $writeOffDate = OrderService::generateWriteOffData($params);
  448. }
  449. $params['orderId'] = 'OD' . date('YmdHis') . random_string(6, 'up');
  450. $params['orderGroupId'] = 'OD' . date('YmdHis') . random_string(6, 'up');
  451. $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up');
  452. // 配送方式
  453. // if ($params['delivery'] == 'PICKUP') { // 自提
  454. // // $params['order_config_json'] = json_encode([
  455. // // // 'express' => 'S',
  456. // // 'premises' => $params['dept_premises_id']
  457. // // ]);
  458. // } else if ($params['delivery'] == 'LOGISTICS') {
  459. // // $params['order_express_json'] = json_encode([
  460. // // 'express' => 'Y',
  461. // // ]);
  462. // }
  463. // 写入主订单
  464. $this->insertMain($params);
  465. // 订单详情
  466. $sheetId = $this->insertSheet($params);
  467. // 支付记录
  468. $this->insertPayDetail($params);
  469. $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]);
  470. if ($params['delivery'] == 'LOGISTICS') {
  471. $params['order_express_type'] = '配送';
  472. // 入配送
  473. $this->saveExpress($params);
  474. }else if($params['delivery'] == 'PICKUP'){
  475. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  476. $params['order_express_type'] = '自提';
  477. if(!$premises){
  478. throw new BusinessException('自提门店不存在');
  479. }
  480. $params['order_express_city'] = $premises->dept_city;
  481. $params['order_express_address'] = $premises->dept_address;
  482. $params['order_express_telephone'] = $premises->dept_telephone;
  483. $this->saveExpress($params);
  484. }
  485. // 买的单个服务
  486. if ($goods['goods_classify'] == 'SERVICE') {
  487. // 预约表
  488. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  489. $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(6, 'up');
  490. // 入预约记录
  491. $this->insertAppointment($params, $writeOffDate);
  492. }
  493. $goods['skuId'] = $params['join_sheet_goods_sku_id'];
  494. $goods['category'] = 'SERVICE';
  495. // 权益表
  496. $this->insertMemberBenefit($params, $goods);
  497. } elseif ($goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  498. $params['packageId'] = $params['join_sheet_goods_id'];
  499. $components = GoodsComponent::with([
  500. 'goods' => function ($query) {
  501. $query->select('goods_id', 'goods_name', 'goods_classify');
  502. }
  503. ])->where('join_component_master_goods_id', $params['join_sheet_goods_id'])
  504. ->get()
  505. ->toArray();
  506. $orderSheetNum = $params['order_sheet_num'];
  507. foreach ($components as $component) {
  508. $params['order_sheet_num'] = $orderSheetNum;
  509. $componentJson = json_decode($component['goods_component_json'], true);
  510. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  511. $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
  512. $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up');
  513. $params['order_sheet_num'] = $params['order_sheet_num'] * $componentJson['nbr'];
  514. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  515. $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(8, 'up');
  516. // 入预约记录
  517. $this->insertAppointment($params, $writeOffDate);
  518. }
  519. $goods['goods_id'] = $component['join_component_goods_id'];
  520. $goods['goods_name'] = $component['goods']['goods_name'];
  521. $goods['goods_classify'] = $component['goods']['goods_classify'];
  522. $goods['skuId'] = $params['join_sheet_goods_sku_id'];
  523. $goods['category'] = 'SERVICE';
  524. // 权益表
  525. $this->insertMemberBenefit($params, $goods);
  526. }
  527. }
  528. Db::commit();
  529. return json_success('创建订单成功');
  530. } catch (\Exception $e) {
  531. Db::rollBack();
  532. dump($e->getMessage());
  533. return json_fail('创建订单失败');
  534. }
  535. }
  536. /**
  537. * @Desc
  538. * @Author Gorden
  539. * @Date 2024/6/7 10:30
  540. *
  541. * @param $params
  542. * @return void
  543. * @throws BusinessException
  544. */
  545. public function insertMain($params)
  546. {
  547. try {
  548. $data = [
  549. 'order_id' => $params['orderId'],
  550. 'order_groupby' => $params['orderGroupId'],
  551. 'join_order_member_id' => $params['join_order_member_id'],
  552. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  553. 'order_amount_total' => $params['order_sheet_amount'],
  554. 'order_amount_pay' => $params['order_sheet_pay'],
  555. 'order_category' => 'SYSTEM',
  556. 'order_is_complete' => 'N',
  557. 'order_status_system' => $params['order_status_system'],
  558. 'order_status_payment' => $params['order_status_payment'],
  559. 'order_status_storage' => $params['order_status_storage'],
  560. 'order_remark' => $params['order_remark'] ?? '',
  561. 'order_config_json' =>$params['order_config_json'] ?? '[]',
  562. 'order_express_json' => $params['order_express_json'] ?? '[]',
  563. 'order_addtimes' => time()
  564. ];
  565. Order::insert($data);
  566. } catch (\Exception $e) {
  567. dump($e->getMessage());
  568. throw new BusinessException('订单创建信息失败');
  569. }
  570. }
  571. /**
  572. * @Desc
  573. * @Author Gorden
  574. * @Date 2024/6/7 10:25
  575. *
  576. * @param $params
  577. * @return void
  578. * @throws BusinessException
  579. */
  580. public function insertSheet($params)
  581. {
  582. try {
  583. $data = [
  584. 'join_sheet_member_id' => $params['join_order_member_id'],
  585. 'join_sheet_order_id' => $params['orderId'],
  586. 'join_sheet_goods_id' => $params['join_sheet_goods_id'],
  587. 'join_sheet_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  588. 'order_sheet_status' => 'DONE',
  589. 'order_sheet_category' => 'NORMAL',
  590. 'order_sheet_num' => $params['order_sheet_num'],
  591. 'order_sheet_price' => $params['order_sheet_price'],
  592. 'order_sheet_amount' => $params['order_sheet_amount'],
  593. 'order_sheet_pay' => $params['order_sheet_pay'],
  594. 'order_sheet_remark' => $params['order_remark'] ?? '',
  595. 'order_sheet_addtimes' => time()
  596. ];
  597. return OrderSheet::insertGetId($data);
  598. } catch (\Exception $e) {
  599. throw new BusinessException('订单创建失败');
  600. }
  601. }
  602. /**
  603. * @Desc
  604. * @Author Gorden
  605. * @Date 2024/6/7 10:35
  606. *
  607. * @param $params
  608. * @return void
  609. * @throws BusinessException
  610. */
  611. public function insertPayDetail($params)
  612. {
  613. try {
  614. $data = [
  615. 'join_pay_member_id' => $params['join_order_member_id'],
  616. 'join_pay_order_id' => $params['orderGroupId'],
  617. 'pay_status' => 'SUCCESS',
  618. 'pay_category' => $params['pay_category'],
  619. 'pay_amount' => $params['order_sheet_pay'],
  620. 'pay_prepayid' => $params['join_order_member_id'].'-'.$params['pay_category'],
  621. 'pay_paytimes' => date('Y-m-d H:i:s'),
  622. 'pay_remark' => $params['order_remark'] ?? '',
  623. 'pay_addtimes' => time()
  624. ];
  625. PayDetail::insert($data);
  626. } catch (\Exception $e) {
  627. dump(111);
  628. dump($e->getMessage());
  629. throw new BusinessException('创建支付记录失败');
  630. }
  631. }
  632. /**
  633. * @Desc
  634. * @Author Gorden
  635. * @Date 2024/6/7 10:50
  636. *
  637. * @param $params
  638. * @return void
  639. * @throws BusinessException
  640. */
  641. public function insertAppointment($params, $writeOffDate)
  642. {
  643. try {
  644. $data = [
  645. 'appointment_id' => $params['appointmentId'],
  646. 'join_appointment_member_id' => $params['join_order_member_id'],
  647. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  648. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  649. 'join_appointment_order_id' => $params['orderId'],
  650. 'join_appointment_member_benefit_id' => $params['benefitId'],
  651. 'appointment_classify' => $params['goods_classify'],
  652. 'appointment_status' => $params['order_status_system'] == 'DONE' ? 'DONE' : 'INIT',
  653. 'appointment_category' => 'NORMAL',
  654. 'appointment_addtimes' => time(),
  655. 'appointment_done_datetime' => $params['order_status_system'] == 'DONE' ? date('Y-m-d H:i:s') : '',
  656. 'appointment_remark' => $params['order_remark'] ?? '',
  657. 'appointment_done_json' => $params['order_status_system'] == 'DONE' && $writeOffDate ? json_encode($writeOffDate) : '[]'
  658. ];
  659. Appointment::insert($data);
  660. } catch (\Exception $e) {
  661. dump($e->getMessage());
  662. throw new BusinessException("创建权益记录失败");
  663. }
  664. }
  665. /**
  666. * @Desc
  667. * @Author Gorden
  668. * @Date 2024/6/7 11:05
  669. *
  670. * @param $params
  671. * @param $goods
  672. * @return void
  673. * @throws BusinessException
  674. */
  675. public function insertMemberBenefit($params, $goods)
  676. {
  677. try {
  678. $data = [
  679. 'member_benefit_id' => $params['benefitId'],
  680. 'join_benefit_member_id' => $params['join_order_member_id'],
  681. 'join_benefit_package_id' => $params['packageId'] ?? '',
  682. 'join_benefit_goods_id' => $goods['goods_id'],
  683. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  684. 'join_benefit_order_id' => $params['orderId'],
  685. 'member_benefit_status' => 'ACTIVED',
  686. 'member_benefit_category' => $goods['category'],
  687. 'member_benefit_name' => $goods['goods_name'],
  688. 'member_benefit_limit_count' => $params['order_sheet_num'],
  689. 'member_benefit_used_count' => $params['order_status_system'] == 'DONE' ? $params['order_sheet_num'] : 0,
  690. 'member_benefit_remark' => $params['order_remark'] ?? '',
  691. 'member_benefit_addtimes' => time()
  692. ];
  693. MemberBenefit::insert($data);
  694. } catch (\Exception $e) {
  695. dump($e->getMessage());
  696. throw new BusinessException('创建会员权益失败');
  697. }
  698. }
  699. /**
  700. * 修改主订单
  701. */
  702. public function updateMain($params)
  703. {
  704. $params['order_express_goods'] = json_encode(['sheet' => [$params['sheet_id']]]);
  705. if ($params['delivery'] == 'PICKUP') { // 自提
  706. $params['order_config_json'] = json_encode([
  707. // 'express' => 'S',
  708. // 'premises' => $params['dept_premises_id']
  709. ]);
  710. } else if ($params['delivery'] == 'LOGISTICS') {
  711. // $params['order_express_json'] = json_encode([
  712. // 'express' => 'Y',
  713. // ]);
  714. $params['orderId'] = $params['order_id'];
  715. $this->saveExpress($params);
  716. }
  717. try {
  718. Order::where('order_id', $params['order_id'])->update(['order_config_json' => $params['order_config_json'] ?? '[]']);
  719. } catch (\Exception $e) {
  720. throw new BusinessException('修改订单失败');
  721. }
  722. }
  723. public function delivery(Request $request)
  724. {
  725. if (!Order::where('order_id', $request->post('order_id'))->where('order_status_system', 'SENDING')->exists()) {
  726. return json_fail('订单状态异常');
  727. }
  728. // 验证
  729. $validate = new OrderExpressValidate();
  730. if (!$validate->scene('delivery')->check($request->post())) {
  731. return json_fail($validate->getError());
  732. }
  733. $params = $request->post();
  734. try {
  735. Db::beginTransaction();
  736. if ($params['express_type'] == '自提') {
  737. $premises = SysDept::where('dept_name', $params['order_express_premises'])->first();
  738. if (!$premises) {
  739. return json_fail("门店不存在,请重新填写");
  740. }
  741. $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city);
  742. $params['order_express_address'] = $premises->dept_address;
  743. $params['order_express_code'] = '';
  744. $params['order_express_addtimes'] = strtotime($params['order_express_addtimes']);
  745. $orderData = [
  746. 'order_status_system' => 'CONFIRM',
  747. 'order_status_storage' => 'EXPRESSING'
  748. ];
  749. // 7天后自动完成
  750. $redis = Redis::connection();
  751. $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
  752. $redis->sadd($key, $params['order_id']);
  753. $model = new OrderExpress();
  754. } else {
  755. $orderData = [
  756. 'order_status_system' => 'RECVING',
  757. 'order_status_storage' => 'EXPRESSING'
  758. ];
  759. // 15天后自动确认收货
  760. $redis = Redis::connection();
  761. $key = Order::AUTOMATIC_RECEIPT_PREFIX . date('Ymd', strtotime("+15 days"));
  762. $redis->sadd($key, $params['order_id']);
  763. $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  764. if (!$model) {
  765. $model = new OrderExpress();
  766. // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id'))
  767. // ->select('join_sheet_goods_id')
  768. // ->first();
  769. // if(!empty($sheet->order_sheet_extend_json)){
  770. // $extendJson = json_decode($sheet->order_sheet_extend_json,true);
  771. // $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first();
  772. // $params['']
  773. // }
  774. }
  775. }
  776. // 该订单状态
  777. Order::where('order_id', $request->post('order_id'))->update($orderData);
  778. // 入配送记录表
  779. $model->join_express_order_id = $params['order_id'];
  780. if (isset($params['order_express_goods'])) {
  781. $model->order_express_goods = $params['order_express_goods'];
  782. }
  783. if (isset($params['order_express_company'])) {
  784. $model->order_express_company = $params['order_express_company'];
  785. }
  786. if (isset($params['order_express_code'])) {
  787. $model->order_express_code = $params['order_express_code'];
  788. }
  789. if (isset($params['order_express_city'])) {
  790. $model->order_express_city = $params['order_express_city'];
  791. }
  792. if (isset($params['order_express_address'])) {
  793. $model->order_express_address = $params['order_express_address'];
  794. }
  795. if (isset($params['order_express_mobile'])) {
  796. $model->order_express_mobile = $params['order_express_mobile'];
  797. }
  798. if (isset($params['order_express_telephone'])) {
  799. $model->order_express_telephone = $params['order_express_telephone'];
  800. }
  801. if (isset($params['order_express_person'])) {
  802. $model->order_express_person = $params['order_express_person'];
  803. }
  804. $model->order_express_remark = $params['order_express_remark'] ?? null;
  805. $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
  806. $model->save();
  807. Db::commit();
  808. return json_success('发货成功');
  809. } catch (\Exception $e) {
  810. Db::rollBack();
  811. dump($e->getMessage());
  812. return json_fail('发货失败');
  813. }
  814. }
  815. public function writeOff(Request $request)
  816. {
  817. $memberId = $request->post('member_id', '');
  818. $benefitId = $request->post('benefit_id', '');
  819. $nbr = $request->post('nbr');
  820. $times = $request->post('times', '');
  821. $code = $request->post('sms_code', '');
  822. if (!$memberId || !$benefitId) {
  823. return json_fail('参数异常');
  824. }
  825. $member = Member::find($memberId);
  826. $mobile = $member->member_mobile;
  827. $key = "SMS:CODE:QUOTA:" . $mobile;
  828. $redisCode = Redis::get($key);
  829. if ($redisCode != $code) {
  830. return json_fail("验证码错误,请重新输入");
  831. }
  832. Redis::del($key);
  833. $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
  834. ->where('join_benefit_member_id', $memberId)
  835. ->first();
  836. if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
  837. return json_fail('可核销数量不足');
  838. }
  839. if (!$times) {
  840. $times = date('Y-m-d H:i:s');
  841. } else {
  842. $times = date('Y-m-d H:i:s', strtotime($times));
  843. }
  844. try {
  845. Db::beginTransaction();
  846. // 减额度
  847. $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
  848. // 用完了
  849. if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
  850. $benefit->member_benefit_status = 'DONE';
  851. if (!empty($benefit->join_benefit_order_id)) {
  852. Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']);
  853. }
  854. }
  855. $benefit->save();
  856. // 记录核销
  857. $params = [
  858. 'dept_premises_id' => $request->post('dept_premises_id'),
  859. 'order_remark' => $request->post('remark'),
  860. 'write_off_member_id' => $request->post('write_off_member_id'),
  861. 'join_order_member_id' => $memberId
  862. ];
  863. $writeOffData = OrderService::generateWriteOffData($params);
  864. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
  865. ->where('appointment_status', 'INIT')
  866. ->limit($nbr)
  867. ->get();
  868. foreach ($appointments as $appointment) {
  869. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  870. 'appointment_status' => 'DONE',
  871. 'appointment_datetime' => $times,
  872. 'appointment_apply_datetime' => $times,
  873. 'appointment_doing_datetime' => $times,
  874. 'appointment_done_datetime' => $times,
  875. 'appointment_done_json' => json_encode($writeOffData)
  876. ]);
  877. }
  878. Db::commit();
  879. return json_success('核销成功');
  880. } catch (\Exception $e) {
  881. dump($e->getMessage());
  882. Db::rollBack();
  883. return json_fail('核销失败');
  884. }
  885. }
  886. public function writeOffDishes(Request $request)
  887. {
  888. $orderId = $request->post('order_id','');
  889. $memberId = $request->post('member_id', '');
  890. $times = $request->post('times', '');
  891. $code = $request->post('sms_code', '');
  892. if (!$memberId || !$orderId) {
  893. return json_fail('参数异常');
  894. }
  895. if (!$times) {
  896. $times = date('Y-m-d H:i:s');
  897. } else {
  898. $times = date('Y-m-d H:i:s', strtotime($times));
  899. }
  900. try {
  901. Db::beginTransaction();
  902. // 记录核销
  903. $params = [
  904. 'dept_premises_id' => $request->post('dept_premises_id'),
  905. 'order_remark' => $request->post('remark'),
  906. 'write_off_member_id' => $request->post('write_off_member_id'),
  907. 'join_order_member_id' => $memberId
  908. ];
  909. $writeOffData['charge'] = OrderService::generateWriteOffData($params);
  910. $writeOffData['charge']['order_id'] = $orderId;
  911. $writeOffData['charge']['member_id'] = $memberId;
  912. $writeOffData['charge']['order_code'] = random_string(10,'number');
  913. $writeOffData['express'] = 'N';
  914. Order::where('order_id',$orderId)->update([
  915. 'order_express_json'=>json_encode($writeOffData),
  916. 'order_is_complete'=>'Y',
  917. 'order_status_system'=>'DONE'
  918. ]);
  919. Db::commit();
  920. return json_success('核销成功');
  921. } catch (\Exception $e) {
  922. dump($e->getMessage());
  923. Db::rollBack();
  924. return json_fail('核销失败');
  925. }
  926. }
  927. public function myOrder(Request $request)
  928. {
  929. $memberId = $request->get('member_id', '');
  930. if (!$memberId) {
  931. return json_fail('查询错误');
  932. }
  933. $sheet = OrderSheet::with([
  934. 'goods' => function ($query) {
  935. $query->select('goods_id', 'goods_name', 'goods_cover');
  936. },
  937. 'order' => function ($query) {
  938. $query->select('order_id', 'order_status_system', 'order_status_payment', 'order_status_storage');
  939. },
  940. 'refund' => function ($query) {
  941. $query->select('join_return_order_id', 'orders_return_id', 'order_return_status');
  942. },
  943. ])->where('join_sheet_member_id', $memberId)
  944. ->orderBy('order_sheet_addtimes', 'desc')
  945. ->get()
  946. ->toArray();
  947. foreach ($sheet as &$item) {
  948. if (!empty($item->goods->goods_cover)) {
  949. $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover;
  950. }
  951. }
  952. // 预约单
  953. $appointments = Db::table('appointment')
  954. // ->leftJoin('member', 'member.member_id', '=', 'appointment.join_appointment_member_id')
  955. // ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'appointment.join_appointment_member_id')
  956. // ->leftJoin('member_info', 'member_info.join_info_member_id', '=', 'appointment.join_appointment_member_id')
  957. ->leftJoin('goods', 'goods.goods_id', '=', 'appointment.join_appointment_goods_id')
  958. // ->leftJoin('order', 'order.order_id', '=', 'appointment.join_appointment_order_id')
  959. ->leftJoin('member_benefit', 'member_benefit.member_benefit_id', '=', 'appointment.join_appointment_member_benefit_id')
  960. // ->leftJoin('goods_sku', 'goods_sku.goods_sku_id', '=', 'appointment.join_appointment_goods_sku_id')
  961. ->where('join_appointment_member_id', $memberId)
  962. ->whereIn('appointment_status',['WAITING','PENDING','DOING','DONE','CANCEL','REVOKE'])
  963. ->select('appointment.*',
  964. // 'member.member_mobile',
  965. // 'member_cert.member_cert_name',
  966. // 'member_info.member_info_nickname',
  967. 'goods.goods_name', 'goods.goods_sales_price',
  968. // 'order.order_name', 'goods_sku.goods_sku_specs_json', 'order.order_amount_total', 'order.order_amount_pay',
  969. // 'order.order_category', 'order.order_status_system', 'order.order_status_payment', 'order.order_status_storage',
  970. // 'order.order_addtimes',
  971. 'member_benefit.member_benefit_name'
  972. )
  973. ->orderBy('appointment.appointment_addtimes', 'desc')
  974. ->get();
  975. foreach ($appointments as &$row) {
  976. if ($row->appointment_category == 'NOFEE') {
  977. $row->member_benefit_name = "后付费预约";
  978. }
  979. $row->appointment_addtimes = date('Y-m-d H:i:s', $row->appointment_addtimes);
  980. }
  981. return json_success('', ['order' => $sheet, 'appointment' => $appointments]);
  982. }
  983. public function saveExpress($params)
  984. {
  985. try {
  986. $express = new OrderExpress();
  987. $express->order_express_type = $params['order_express_type'];
  988. $express->join_express_order_id = $params['orderId'];
  989. $express->order_express_goods = $params['order_express_goods'];
  990. $express->order_express_city = $params['order_express_city'];
  991. $express->order_express_address = $params['order_express_address'];
  992. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  993. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  994. $express->order_express_person = $params['order_express_person'] ?? '';
  995. $express->order_express_company = $params['dept_premises_id'] ?? '';
  996. $express->order_express_addtimes = time();
  997. $express->save();
  998. } catch (\Exception $e) {
  999. dump($e->getMessage());
  1000. throw new BusinessException('物流信息保存失败');
  1001. }
  1002. }
  1003. // TODO 确认收货(完成订单)
  1004. public function confirm($id)
  1005. {
  1006. $order = Order::where('order_id', $id)->first();
  1007. if (empty($order)) {
  1008. return json_fail("暂无数据");
  1009. }
  1010. Db::beginTransaction();
  1011. try {
  1012. // 主订单
  1013. Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']);
  1014. } catch (\Exception $e) {
  1015. }
  1016. }
  1017. public function doRefund(Request $request)
  1018. {
  1019. $orderId = $request->post('order_id', '');
  1020. // $returnId = $request->post('return_id', '');
  1021. $amount = $request->post('refund_amount', 0);
  1022. $password = $request->post('refund_password', '');
  1023. if (!$orderId || !$amount || !$password) {
  1024. return json_fail('参数异常');
  1025. }
  1026. if ($password != '123456'){
  1027. return json_fail('支付密码错误');
  1028. }
  1029. $return = OrderReturn::where('join_return_order_id', $orderId)
  1030. ->first();
  1031. if (!$return) {
  1032. return json_fail("退款订单异常");
  1033. }
  1034. $order = Order::where('order_id', $return->join_return_order_id)->first();
  1035. if (!$order) {
  1036. return json_fail("订单异常");
  1037. }
  1038. if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') {
  1039. return json_fail('订单已完成,无法退款');
  1040. }
  1041. if ($amount > $order->order_amount_pay) {
  1042. return json_fail('退款金额不能超过订单金额');
  1043. }
  1044. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first();
  1045. if (!$payDetail) {
  1046. return json_fail("支付信息异常异常");
  1047. }
  1048. $res = '[]';
  1049. $data = '[]';
  1050. try {
  1051. Db::beginTransaction();
  1052. // 订单主表
  1053. Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']);
  1054. // return 表
  1055. $return->order_return_status = 'DONE';
  1056. $return->order_return_refund_json = json_encode(['amount'=>$amount]);
  1057. $return->save();
  1058. // 区分账户余额支付和通联支付
  1059. if (in_array($payDetail->pay_prepayid, ['W06', 'A01'])) {
  1060. $responseJson = [];
  1061. if (!empty($payDetail->pay_json_response)) {
  1062. $responseJson = json_decode($payDetail->pay_json_response, true);
  1063. if (!isset($responseJson['trxid'])) {
  1064. throw new PayException("支付信息异常");
  1065. }
  1066. }
  1067. $data = [
  1068. 'randomstr' => random_string(32),
  1069. 'reqsn' => $return->join_return_order_id,
  1070. 'oldtrxid' => $responseJson['trxid'],
  1071. 'trxamt' => $amount * 100,
  1072. ];
  1073. $tlpay = new Tlpay();
  1074. $res = $tlpay->refund($data);
  1075. $resArray = json_decode($res, true);
  1076. if (AppUtil::validSign($resArray)) {
  1077. if ($resArray['retcode'] != 'SUCCESS' || $resArray['trxstatus'] != '0000') {
  1078. throw new PayException('退款失败,原因:' . $resArray['errmsg']);
  1079. }
  1080. }
  1081. }
  1082. $payType = explode('-', $payDetail->pay_prepayid);
  1083. // 余额支付
  1084. if (isset($payType[1]) && $payType[1] == 'CASH') {
  1085. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  1086. ->where('member_account_classify', 'CASH')
  1087. ->first();
  1088. $account->member_account_expend = $account->member_account_expend - $amount;
  1089. $account->member_account_surplus = $account->member_account_surplus + $amount;
  1090. $account->save();
  1091. $data = [
  1092. 'type' => 'REFUND',
  1093. 'member_id' => $order->join_order_member_id,
  1094. 'order_id' => $return->join_return_order_id,
  1095. 'return_id' => $return->orders_return_id
  1096. ];
  1097. $res = json_encode([
  1098. 'status' => 'SUCCESS'
  1099. ]);
  1100. }
  1101. // 卡支付
  1102. if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) {
  1103. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  1104. ->where('member_account_nbr', $payType[0])
  1105. ->where('member_account_classify', 'CARD')
  1106. ->first();
  1107. $account->member_account_expend = $account->member_account_expend - $amount;
  1108. $account->member_account_surplus = $account->member_account_surplus + $amount;
  1109. $account->save();
  1110. $data = [
  1111. 'type' => 'REFUND',
  1112. 'nbr' => $account->member_account_nbr,
  1113. 'member_id' => $order->join_order_member_id,
  1114. 'order_id' => $return->join_return_order_id,
  1115. 'return_id' => $return->orders_return_id
  1116. ];
  1117. $res = json_encode([
  1118. 'status' => 'SUCCESS'
  1119. ]);
  1120. }
  1121. // 生成payDetail
  1122. $payDetailData = [
  1123. 'join_pay_member_id' => $order->join_order_member_id,
  1124. 'join_pay_order_id' => $order->order_groupby,
  1125. 'pay_status' => 'SUCCESS',
  1126. 'pay_category' => 'REFUND',
  1127. 'pay_amount' => $amount,
  1128. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1129. 'pay_json_request' => json_encode($data),
  1130. 'pay_json_response' => $res,
  1131. 'pay_prepayid' => $payType[0].(!empty($payType[1]) ? '-'.$payType[1] : ''),
  1132. 'pay_addtimes' => time()
  1133. ];
  1134. PayDetail::insert($payDetailData);
  1135. Db::commit();
  1136. _syslog("退款", "发起退款", json_decode($res), $data);
  1137. return json_success("退款成功");
  1138. } catch (PayException $e) {
  1139. Db::rollBack();
  1140. _syslog("退款", "发起退款", $e->getMessage(), $data);
  1141. return json_fail($e->getMessage());
  1142. } catch (\Exception $e) {
  1143. Db::rollBack();
  1144. dump($e->getTrace());
  1145. _syslog("退款", "发起退款", $e->getMessage(), $data);
  1146. return json_fail("数据更新失败");
  1147. }
  1148. }
  1149. }