CardController.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\coupon\CouponService;
  4. use app\admin\service\member\MemberService;
  5. use app\admin\service\order\OrderService;
  6. use app\admin\service\order\OrderSheetService;
  7. use app\admin\service\order\PayDetailService;
  8. use app\admin\validate\order\OrderValidate;
  9. use app\controller\Curd;
  10. use app\model\Appointment;
  11. use app\model\ClientConfig;
  12. use app\model\Coupon;
  13. use app\model\Goods;
  14. use app\model\GoodsComponent;
  15. use app\model\GoodsRunning;
  16. use app\model\GoodsSku;
  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\Supplier;
  27. use app\model\SysDept;
  28. use app\model\SysUser;
  29. use support\Db;
  30. use support\exception\BusinessException;
  31. use support\Redis;
  32. use support\Request;
  33. use support\Response;
  34. use Tinywan\Jwt\JwtToken;
  35. use Webman\Event\Event;
  36. use Yansongda\Pay\Pay;
  37. class CardController extends Curd
  38. {
  39. public function __construct()
  40. {
  41. $this->model = new Order();
  42. $this->validate = true;
  43. $this->validateClass = new OrderValidate();
  44. }
  45. /**
  46. * @Desc 列表
  47. * @Author Gorden
  48. * @Date 2024/3/28 15:01
  49. *
  50. * @param Request $request
  51. * @return Response
  52. * @throws \support\exception\BusinessException
  53. */
  54. public function select(Request $request): Response
  55. {
  56. $timeType = $request->get('time_type', 'add');
  57. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  58. $where['order_classify'] = 'CARD';
  59. if (!empty($where['order_addtimes']) && $timeType == 'add') {
  60. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  61. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  62. }
  63. $order = $request->get('order', 'desc');
  64. $orderId = $request->get('orderId');
  65. $field = $field ?? 'order_addtimes';
  66. $orderIds = [];
  67. if (!empty($orderId)) {
  68. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  69. ->where('order_classify', 'CARD')
  70. ->pluck('order_id')
  71. ->toArray();
  72. }
  73. $goodsName = trim($request->get('goods_name', ''));
  74. if (!empty($goodsName)) {
  75. $goodsIds = Goods::where('goods_classify', 'CARD')
  76. ->where('goods_name', 'like', '%' . $goodsName . '%')
  77. ->pluck('goods_id')
  78. ->toArray();
  79. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  80. if (!empty($where['order_id'])) {
  81. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  82. } else {
  83. $orderIds = $goodsOrderIds;
  84. }
  85. }
  86. // 付款时间
  87. $payOrderIds = [];
  88. if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
  89. $payTimeStart = strtotime($where['order_addtimes'][0]);
  90. $payTimeEnd = strtotime($where['order_addtimes'][1]);
  91. unset($where['order_addtimes']);
  92. $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['CARD']);
  93. }
  94. if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
  95. $orderIds = array_intersect($orderIds, $payOrderIds);
  96. $where['order_id'] = ['in', implode(',', $orderIds)];
  97. } elseif (!empty($orderId) || !empty($goodsName)) {
  98. $where['order_id'] = ['in', implode(',', $orderIds)];
  99. } elseif ($timeType == 'pay') {
  100. $where['order_id'] = ['in', implode(',', $payOrderIds)];
  101. }
  102. $query = $this->doSelect($where, $field, $order);
  103. return $this->doFormat($query, $format, $limit);
  104. }
  105. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  106. {
  107. $model = $this->model->with([
  108. 'sheets' => function ($query) {
  109. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  110. },
  111. 'member' => function ($query) {
  112. $query->select('member_id', 'member_mobile', 'join_invite_member_id');
  113. },
  114. 'cert' => function ($query) {
  115. $query->select('join_cert_member_id', 'member_cert_name');
  116. },
  117. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  118. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  119. foreach ($where as $column => $value) {
  120. if (is_array($value)) {
  121. if ($value[0] === 'like' || $value[0] === 'not like') {
  122. $model = $model->where($column, $value[0], "%$value[1]%");
  123. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  124. $model = $model->where($column, $value[0], $value[1]);
  125. } elseif ($value[0] == 'in' && !empty($value[1])) {
  126. $valArr = $value[1];
  127. if (is_string($value[1])) {
  128. $valArr = explode(",", trim($value[1]));
  129. }
  130. $model = $model->whereIn($column, $valArr);
  131. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  132. $valArr = $value[1];
  133. if (is_string($value[1])) {
  134. $valArr = explode(",", trim($value[1]));
  135. }
  136. $model = $model->whereNotIn($column, $valArr);
  137. } elseif ($value[0] == 'null') {
  138. $model = $model->whereNull($column);
  139. } elseif ($value[0] == 'not null') {
  140. $model = $model->whereNotNull($column);
  141. } elseif ($value[0] !== '' || $value[1] !== '') {
  142. $model = $model->whereBetween($column, $value);
  143. }
  144. } else {
  145. $model = $model->where($column, $value);
  146. }
  147. }
  148. if ($field) {
  149. $model = $model->orderBy($field, $order);
  150. }
  151. $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
  152. return $model;
  153. }
  154. public function afterQuery($items)
  155. {
  156. foreach ($items as &$item) {
  157. $sheetDeng = '';
  158. $item['sheet'] = $item['sheets'][0] ?? [];
  159. if (!empty($item['sheet'])) {
  160. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  161. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  162. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  163. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  164. }
  165. unset($item['sheets']);
  166. if (isset($item['orders_return_id'])) {
  167. $item['return'] = [
  168. 'orders_return_id' => $item['orders_return_id'],
  169. 'join_return_order_id' => $item['join_return_order_id'],
  170. 'order_return_status' => $item['order_return_status'],
  171. 'order_return_apply_json' => $item['order_return_apply_json'],
  172. 'order_return_remark' => $item['order_return_remark']
  173. ];
  174. }
  175. if (isset($item['join_express_order_id'])) {
  176. $item['express'] = [
  177. 'join_express_order_id' => $item['join_express_order_id'],
  178. 'order_express_type' => $item['order_express_type']
  179. ];
  180. unset($item['join_express_order_id'], $item['order_express_type']);
  181. }
  182. if (!empty($item['member']['join_invite_member_id'])) {
  183. $inviteMember = Member::with([
  184. 'cert' => function ($query) {
  185. $query->select('join_cert_member_id', 'member_cert_name');
  186. }
  187. ])->where('member_id', $item['member']['join_invite_member_id'])
  188. ->first();
  189. $inviteMobile = $inviteMember['member_mobile'] ?? '';
  190. $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
  191. $item['invite_name'] = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
  192. }
  193. $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
  194. }
  195. return $items;
  196. }
  197. /**
  198. * @Desc 下单+支付
  199. * @Author Gorden
  200. * @Date 2024/9/5 13:13
  201. *
  202. * @param Request $request
  203. * @return Response
  204. */
  205. public function insert(Request $request): Response
  206. {
  207. $params = $request->post();
  208. // 判断餐品是否连带着服务或实体
  209. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  210. $params['goods_classify'] = $goodsClassifys[0];
  211. $orderExtendJson = [];
  212. Db::beginTransaction();
  213. try {
  214. // 验证线下付款密码
  215. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  216. $password = $params['offline_password'];
  217. if ($password != '666888') {
  218. throw new BusinessException('密码错误,请重新输入');
  219. }
  220. }
  221. if (!empty($params['dept_id'])) {
  222. $dept = SysDept::where('dept_id', $params['dept_id'])->first();
  223. if (!$dept) {
  224. throw new BusinessException("购买场所不存在");
  225. }
  226. $params['dept_name'] = $dept->dept_name;
  227. $orderExtendJson = ['dept_id' => $params['dept_id'], 'dept_name' => $params['dept_name']];
  228. }
  229. // 下单账户
  230. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  231. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  232. throw new BusinessException('会员已存在');
  233. }
  234. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  235. // 创建会员
  236. MemberService::createMember($params);
  237. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  238. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  239. }
  240. if (empty($params['join_order_member_id'])) {
  241. throw new BusinessException('检查下单账户');
  242. }
  243. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  244. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  245. $systemStatus = 'PAYING';
  246. // 立即结算
  247. if ($params['settlement_now'] == 'Y') {
  248. if ($params['goods_classify'] == 'CARD') {
  249. $params['order_is_complete'] = 'Y';
  250. $systemStatus = 'DONE';
  251. }
  252. }
  253. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  254. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  255. $params['pay_category'] = $params['pay_category_sub'];
  256. }
  257. $params['order_status_system'] = $systemStatus;
  258. $params['order_status_payment'] = 'SUCCESS';
  259. }
  260. if ($params['pay_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  261. $result = OrderService::qrcodePay($params);
  262. $result = json_encode($result);
  263. $params['pay_json_response'] = $result;
  264. $result = json_decode($result, true);
  265. $prefix = substr($params['qrcode_nbr'], 0, 2);
  266. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  267. $params['pay_category'] = 'WXPAY';
  268. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  269. $params['order_status_system'] = 'PAYING';
  270. $params['order_status_payment'] = 'PENDING';
  271. $params['order_is_complete'] = 'N';
  272. } else {
  273. $params['order_status_system'] = $systemStatus;
  274. $params['order_status_payment'] = 'SUCCESS';
  275. }
  276. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  277. $params['pay_category'] = 'ALIPAY';
  278. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  279. $params['order_status_system'] = 'PAYING';
  280. $params['order_status_payment'] = 'PENDING';
  281. $params['order_is_complete'] = 'N';
  282. } else {
  283. $params['order_status_system'] = $systemStatus;
  284. $params['order_status_payment'] = 'SUCCESS';
  285. }
  286. } else {
  287. throw new BusinessException('付款码无效');
  288. }
  289. }
  290. if (empty($paidOrder)) {
  291. $params['order_extend_json'] = $orderExtendJson;
  292. // 写入主订单
  293. $this->insertMain($params);
  294. // 订单详情
  295. $this->insertSheet($params);
  296. } else {
  297. $params['orderGroupId'] = $paidOrder->order_groupby;
  298. if ($params['order_status_payment'] == 'SUCCESS') {
  299. $params['order_amount_paid'] = $paidOrder->order_amount_paid;
  300. $paidOrder->order_amount_paid = $paidOrder->order_amount_paid + $params['order_amount_pay'];
  301. $paidOrder->order_amount_pay = $paidOrder->order_amount_paid;
  302. if (floatval($paidOrder->order_amount_paid) >= $paidOrder->order_amount_total) {
  303. $paidOrder->order_is_complete = 'Y';
  304. $paidOrder->order_status_system = 'DONE';
  305. $paidOrder->order_status_payment = 'SUCCESS';
  306. // 更新sheet
  307. OrderSheet::where('join_sheet_order_id', $paidOrder->order_id)->update(['order_sheet_status' => 'DONE']);
  308. }
  309. }
  310. $paidOrder->save();
  311. // 清除此订单的未支付记录
  312. PayDetail::whereJsonContains('join_pay_object_json->order_id', $paidOrder->order_id)->where('pay_status', 'WAITING')->delete();
  313. }
  314. // 支付记录
  315. $this->insertPayDetail($params);
  316. Db::commit();
  317. if ($params['order_status_payment'] == 'SUCCESS') {
  318. // 入收支明细表
  319. $params['inout_category'] = '购买储值卡';
  320. Event::dispatch('statistics.inout.in', $params);
  321. }
  322. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  323. _syslog("订单", "支付异常,检查是否有轮询");
  324. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  325. }
  326. _syslog("订单", "创建订单成功");
  327. return json_success('创建订单成功');
  328. } catch (BusinessException $e) {
  329. Db::rollBack();
  330. dump($e->getMessage());
  331. dump($e->getTrace());
  332. _syslog("订单", $e->getMessage());
  333. return json_fail($e->getMessage());
  334. } catch (\Exception $e) {
  335. Db::rollBack();
  336. dump($e->getMessage());
  337. dump($e->getTrace());
  338. _syslog("订单", "创建订单失败");
  339. return json_fail('创建订单失败');
  340. }
  341. }
  342. /**
  343. * @Desc 支付
  344. * @Author Gorden
  345. * @Date 2024/9/5 13:12
  346. *
  347. * @param Request $request
  348. * @return Response
  349. */
  350. public function pay(Request $request)
  351. {
  352. $params = $request->post();
  353. // 验证线下付款密码
  354. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  355. $password = $params['offline_password'];
  356. if ($password != '666888') {
  357. return json_fail("密码错误,请重新输入");
  358. }
  359. }
  360. $order = Order::where('order_id', $params['order_id'])->first();
  361. if (!$order) {
  362. return json_fail('订单异常');
  363. }
  364. if ($order->order_status_system != 'PAYING') {
  365. return json_fail('订单不是可支付状态');
  366. }
  367. $params['orderId'] = $params['order_id'];
  368. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  369. $order->order_groupby = $params['orderGroupId'];
  370. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  371. ->select('goods_id', 'goods_name', 'goods_classify')
  372. ->first();
  373. if (!$goods) {
  374. return json_fail('产品数据异常');
  375. }
  376. $goods = $goods->toArray();
  377. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  378. // 购买场所
  379. if (!empty($params['dept_id'])) {
  380. $orderExtendJson = [];
  381. if (!empty($order->order_extend_json)) {
  382. $orderExtendJson = json_decode($order->order_extend_json, true);
  383. }
  384. $dept = SysDept::where('dept_id', $params['dept_id'])->first();
  385. if (!$dept) {
  386. throw new BusinessException("购买场所不存在");
  387. }
  388. $params['dept_name'] = $dept->dept_name;
  389. $orderExtendJson['dept_id'] = $params['dept_id'];
  390. $orderExtendJson['dept_name'] = $params['dept_name'];
  391. $order->order_extend_json = json_encode($orderExtendJson);
  392. }
  393. // 立即结算
  394. if ($params['goods_classify'] == 'CARD') {
  395. $order->order_is_complete = 'Y';
  396. $systemStatus = 'DONE';
  397. }
  398. $paymentStatus = 'PENDING';
  399. Db::beginTransaction();
  400. try {
  401. // 组合支付时,付款码应收金额
  402. $qrcodePayAmount = 0;
  403. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  404. $order->order_status_system = $systemStatus;
  405. $order->order_status_payment = 'SUCCESS';
  406. $paymentStatus = 'SUCCESS';
  407. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  408. $params['pay_category'] = $params['pay_category_sub'];
  409. }
  410. }
  411. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  412. // 提交过来的支付分类
  413. $submitPayCategory = $params['pay_category'];
  414. // 账户支付的金额
  415. $accountAmount = $params['order_amount_pay'];
  416. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  417. // 组合支付,改成需要付款码需要支付的金额
  418. $params['order_amount_pay'] = $qrcodePayAmount;
  419. }
  420. // 去支付
  421. $result = OrderService::qrcodePay($params);
  422. $result = json_encode($result);
  423. $params['pay_json_response'] = $result;
  424. $result = json_decode($result, true);
  425. $prefix = substr($params['qrcode_nbr'], 0, 2);
  426. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  427. $params['pay_category'] = 'WXPAY';
  428. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  429. $order->order_status_system = 'PAYING';
  430. $order->order_status_payment = 'PENDING';
  431. $order->order_is_complete = 'N';
  432. // Db::rollBack();
  433. // return json_fail('支付失败');
  434. } else {
  435. $order->order_status_system = $systemStatus;
  436. $order->order_status_payment = 'SUCCESS';
  437. $paymentStatus = 'SUCCESS';
  438. }
  439. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  440. $params['pay_category'] = 'ALIPAY';
  441. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  442. $order->order_status_system = 'PAYING';
  443. $order->order_status_payment = 'PENDING';
  444. $order->order_is_complete = 'N';
  445. // Db::rollBack();
  446. // return json_fail('支付失败');
  447. } else {
  448. $order->order_status_system = $systemStatus;
  449. $order->order_status_payment = 'SUCCESS';
  450. $paymentStatus = 'SUCCESS';
  451. }
  452. } else {
  453. throw new BusinessException('付款码无效');
  454. }
  455. // 账户支付的金额
  456. $params['order_amount_pay'] = $accountAmount;
  457. }
  458. if ($order->order_status_payment == 'SUCCESS') {
  459. $order->order_amount_paid = $order->order_amount_paid + $params['order_amount_pay'];
  460. $order->order_amount_pay = $order->order_amount_paid;
  461. }
  462. // 分期,支付完就结束了
  463. if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'CARD' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
  464. $order->order_is_complete = 'Y';
  465. }
  466. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  467. $order->order_status_system = 'PAYING';
  468. $order->order_status_payment = 'PENDING';
  469. $order->order_is_complete = 'N';
  470. }
  471. // 主订单
  472. $order->save();
  473. // sheet
  474. if ($order->order_status_payment == 'SUCCESS') {
  475. $data = [
  476. 'order_sheet_status' => $systemStatus
  477. ];
  478. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  479. $data['order_sheet_status'] = 'BEING';
  480. }
  481. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data);
  482. }
  483. // payDetail
  484. $payData = [
  485. 'pay_amount' => $params['order_amount_pay']
  486. ];
  487. if ($paymentStatus == 'SUCCESS') {
  488. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  489. $payData['pay_status'] = 'SUCCESS';
  490. }
  491. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  492. $payData['pay_prepayid'] = $params['pay_category'];
  493. $payData['pay_json_response'] = $params['pay_json_response'];
  494. } else if ($params['pay_category'] == 'CASH') {
  495. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  496. } else if ($params['pay_category'] == 'WELFARE') {
  497. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  498. } else if ($params['pay_category'] == 'CARD') {
  499. $payData['pay_prepayid'] = $params['card_nbr'];
  500. } else if ($params['pay_category'] == 'OFFLINE') {
  501. $payData['pay_prepayid'] = 'OFFLINE';
  502. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  503. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  504. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  505. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  506. } else if ($params['pay_category'] == 'MONEY') {
  507. $payData['pay_prepayid'] = 'MONEY';
  508. }
  509. // 清除此订单的未支付记录
  510. PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete();
  511. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  512. $payData['join_pay_order_id'] = $order->order_groupby;
  513. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  514. $payData['pay_category'] = $params['goods_classify'] ?? '';
  515. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  516. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  517. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? json_encode([
  518. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  519. ]) : '[]';
  520. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  521. $payData['pay_addtimes'] = time();
  522. PayDetail::insert($payData);
  523. Db::commit();
  524. if ($order->order_status_payment == 'SUCCESS') {
  525. // 加销售量
  526. OrderSheetService::addGoodsSales($params['orderId']);
  527. }
  528. if ($order->order_status_payment == 'SUCCESS') {
  529. // 入收支明细表
  530. $params['inout_category'] = '购买储值卡';
  531. Event::dispatch('statistics.inout.in', $params);
  532. }
  533. if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') {
  534. _syslog("订单", "支付异常,检查是否有轮询");
  535. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  536. }
  537. _syslog("订单", "订单支付成功");
  538. return json_success('支付成功');
  539. } catch (BusinessException $e) {
  540. dump($e->getMessage());
  541. Db::rollBack();
  542. _syslog("订单", "订单支付失败:" . $e->getMessage());
  543. return json_fail("支付失败:" . $e->getMessage());
  544. } catch (\Exception $e) {
  545. dump($e->getMessage());
  546. Db::rollBack();
  547. _syslog("订单", "订单支付失败");
  548. return json_fail('支付失败');
  549. }
  550. }
  551. /**
  552. * @Desc
  553. * @Author Gorden
  554. * @Date 2024/6/7 10:30
  555. *
  556. * @param $params
  557. * @return void
  558. * @throws BusinessException
  559. */
  560. public function insertMain($params)
  561. {
  562. try {
  563. $orderCategory = 'NORMAL';
  564. if (!empty($params['order_category'])) {
  565. $orderCategory = $params['order_category'];
  566. } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  567. $orderCategory = 'DISHES';
  568. } else if (isset($params['goods_classify'])) {
  569. $orderCategory = $params['goods_classify'];
  570. }
  571. if (empty($params['order_extend_json'])) {
  572. $params['order_extend_json'] = [];
  573. } else {
  574. if (is_json($params['order_extend_json'])) {
  575. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  576. }
  577. }
  578. // 推荐人
  579. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  580. $data = [
  581. 'order_id' => $params['orderId'],
  582. 'order_groupby' => $params['orderGroupId'],
  583. 'join_order_member_id' => $params['join_order_member_id'],
  584. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  585. 'order_amount_total' => $params['order_amount_total'],
  586. 'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  587. 'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  588. 'order_category' => $orderCategory,
  589. 'order_classify' => $orderCategory,
  590. 'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N',
  591. 'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  592. 'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING',
  593. 'order_status_storage' => $params['order_status_storage'],
  594. 'order_platform' => $params['order_platform'],
  595. 'order_remark' => $params['order_remark'] ?? '',
  596. 'order_discount_json' => $params['order_discount_json'] ?? '[]',
  597. 'order_config_json' => $params['order_config_json'] ?? '[]',
  598. 'order_express_json' => $params['order_express_json'] ?? '[]',
  599. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  600. 'order_addtimes' => time(),
  601. 'order_add_user_id'=>JwtToken::getCurrentId()
  602. ];
  603. Order::insert($data);
  604. } catch (\Exception $e) {
  605. dump($e->getMessage());
  606. throw new BusinessException('订单创建信息失败');
  607. }
  608. }
  609. /**
  610. * @Desc
  611. * @Author Gorden
  612. * @Date 2024/6/7 10:25
  613. *
  614. * @param $params
  615. * @return void
  616. * @throws BusinessException
  617. */
  618. public function insertSheet($params)
  619. {
  620. try {
  621. $orderSheetIds = [];
  622. foreach ($params['goodsContentList'] as $goods) {
  623. //{"unit": "份", "table": null, "premises": "15"}
  624. $price = floatval($goods['goods_sales_price']);
  625. $extendJson['unit'] = $goods['sku_name'];
  626. if (isset($params['submit_premises_id'])) {
  627. $extendJson['premises'] = $params['submit_premises_id'];
  628. }
  629. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  630. $extendJson['table'] = null;
  631. }
  632. $orderSheetStatus = 'PAYING';
  633. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  634. if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
  635. $orderSheetStatus = 'DONE';
  636. } else {
  637. $orderSheetStatus = 'BEING';
  638. }
  639. }
  640. $data = [
  641. 'join_sheet_member_id' => $params['join_order_member_id'],
  642. 'join_sheet_order_id' => $params['orderId'],
  643. 'join_sheet_goods_id' => $goods['goods_id'],
  644. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  645. 'order_sheet_status' => $orderSheetStatus,
  646. 'order_sheet_category' => 'CARD',
  647. 'order_sheet_num' => $goods['nbr'],
  648. 'order_sheet_price' => $goods['goods_sales_price'],
  649. 'order_sheet_price_pay' => $goods['goods_sales_price'],
  650. 'order_sheet_amount' => $price * $goods['nbr'],
  651. 'order_sheet_pay' => $price * $goods['nbr'],
  652. 'order_sheet_task_status' => 'NONE',
  653. 'order_sheet_remark' => $params['order_remark'] ?? '',
  654. 'order_sheet_addtimes' => time(),
  655. 'order_sheet_extend_json' => json_encode($extendJson)
  656. ];
  657. $orderSheetId = OrderSheet::insertGetId($data);
  658. $orderSheetIds[] = $orderSheetId;
  659. // 减库存,规格和总库存
  660. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  661. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  662. if ($goodsRunning->goods_running_storage < 0) {
  663. throw new BusinessException('库存不足');
  664. }
  665. if ($params['order_status_payment'] == 'SUCCESS') {
  666. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  667. }
  668. $goodsRunning->save();
  669. }
  670. return $orderSheetIds;
  671. } catch (\support\exception\BusinessException $e) {
  672. dump($e->getMessage() . '||' . $e->getLine());
  673. throw new BusinessException($e->getMessage());
  674. } catch (\Exception $e) {
  675. dump($e->getMessage() . '||' . $e->getLine());
  676. throw new BusinessException('订单创建失败');
  677. }
  678. }
  679. /**
  680. * @Desc
  681. * @Author Gorden
  682. * @Date 2024/6/7 10:35
  683. *
  684. * @param $params
  685. * @return void
  686. * @throws BusinessException
  687. */
  688. public function insertPayDetail($params)
  689. {
  690. try {
  691. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  692. $payPrepayid = $params['pay_category'];
  693. } else if ($params['pay_category'] == 'OFFLINE') {
  694. $payPrepayid = 'OFFLINE';
  695. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  696. $payPrepayid = 'OFFLINE_ALIPAY';
  697. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  698. $payPrepayid = 'OFFLINE_WXPAY';
  699. } else if ($params['pay_category'] == 'MONEY') {
  700. $payPrepayid = 'MONEY';
  701. } else {
  702. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  703. }
  704. $data = [
  705. 'join_pay_member_id' => $params['join_order_member_id'],
  706. 'join_pay_order_id' => $params['orderGroupId'],
  707. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  708. 'pay_category' => $params['goods_classify'],
  709. 'pay_amount' => $params['order_amount_pay'],
  710. 'pay_prepayid' => $payPrepayid,
  711. 'pay_paytimes' => date('Y-m-d H:i:s'),
  712. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  713. 'pay_json_request' => json_encode($params),
  714. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  715. 'pay_remark' => $params['order_remark'] ?? '',
  716. 'pay_addtimes' => time(),
  717. ];
  718. PayDetail::insert($data);
  719. } catch (\Exception $e) {
  720. dump($e->getMessage());
  721. throw new BusinessException('创建支付记录失败');
  722. }
  723. }
  724. /**
  725. * @Desc 订单商品详情
  726. * @Author Gorden
  727. * @Date 2024/3/29 8:50
  728. *
  729. * @param Request $request
  730. * @return Response
  731. */
  732. public function sheet(Request $request)
  733. {
  734. try {
  735. $orderId = $request->get('order_id');
  736. $orderSheet = OrderSheet::with([
  737. 'member' => function ($query) {
  738. $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'join_invite_member_id', 'member_is_franchisee');
  739. },
  740. 'goods' => function ($query) {
  741. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  742. },
  743. 'memberInfo',
  744. 'cert',
  745. 'sku' => function ($query) {
  746. $query->where('goods_sku_status', 'ON')
  747. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  748. },
  749. 'skus',
  750. 'refund' => function ($query) {
  751. $query->select('join_return_order_id', 'order_return_status');
  752. }
  753. ])->where('join_sheet_order_id', $orderId)
  754. ->orderBy('order_sheet_id', 'DESC')
  755. ->get()
  756. ->toArray();
  757. $order = Order::where('order_id', $orderId)->first();
  758. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  759. $sheetAmount = 0;
  760. foreach ($orderSheet as &$item) {
  761. $sheetAmount += $item['order_sheet_amount'];
  762. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  763. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  764. $components = GoodsComponent::with('goods')
  765. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  766. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  767. 'goods_component_price', 'goods_component_json')
  768. ->get()
  769. ->toArray();
  770. $goodsArr = [];
  771. foreach ($components as $component) {
  772. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  773. if (!empty($component['goods'])) {
  774. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  775. $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  776. ->where('join_benefit_goods_id', $component['goods']['goods_id'])
  777. ->where('join_benefit_order_id', $orderId)
  778. ->first();
  779. $goodsArr[] = [
  780. 'goods_name' => $component['goods']['goods_name'],
  781. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  782. 'supplier_name' => $supplierName,
  783. 'nbr' => $configJson['nbr'] ?? 0,
  784. 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
  785. ];
  786. }
  787. }
  788. $item['goods']['components'] = $goodsArr;
  789. }
  790. if (!empty($item['sku'])) {
  791. if (!empty($item['sku']['goods_sku_specs_json'])) {
  792. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  793. $skuName = '';
  794. foreach ($specsJson as $specsKey => $skuSpecs) {
  795. if (is_array($skuSpecs)) {
  796. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  797. } else {
  798. $skuName = $skuName . ' ' . $skuSpecs . ';';
  799. }
  800. }
  801. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  802. }
  803. }
  804. if (!empty($item['skus'])) {
  805. foreach ($item['skus'] as $key => $skus) {
  806. if (!empty($skus['goods_sku_specs_json'])) {
  807. $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
  808. $skuName = '';
  809. foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
  810. $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
  811. if (is_array($skuSpecs)) {
  812. $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
  813. } else {
  814. $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
  815. }
  816. }
  817. $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
  818. }
  819. }
  820. } else {
  821. $item['skus'] = [];
  822. }
  823. if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
  824. $item['appontment'] = [];
  825. $appontments = Appointment::where('join_appointment_order_id', $orderId)
  826. ->where('appointment_status', 'DONE')
  827. ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
  828. ->get()
  829. ->toArray();
  830. foreach ($appontments as $appontment) {
  831. $doneJson = [];
  832. $username = '';
  833. if (!empty($appontment['appointment_done_json'])) {
  834. $doneJson = json_decode($appontment['appointment_done_json'], true);
  835. if (isset($doneJson['charge'])) {
  836. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  837. }
  838. }
  839. $person = 1;
  840. if (!empty($appontment->appointment_apply_json)) {
  841. $applyJson = json_decode($appontment->appointment_apply_json, true);
  842. if (isset($applyJson['person'])) {
  843. $person = $applyJson['person'];
  844. }
  845. }
  846. $item['appontment'][] = [
  847. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  848. 'goods_name' => $item['goods']['goods_name'],
  849. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  850. 'username' => $username,
  851. 'nbr' => $person,
  852. 'done_time' => $appontment['appointment_done_datetime'],
  853. 'appointment_status' => $appontment['appointment_status'],
  854. ];
  855. }
  856. }
  857. if (!empty($item['order_sheet_extend_json']) && !$express) {
  858. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  859. if (isset($extendJson['address_id'])) {
  860. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  861. if (!empty($address)) {
  862. $valJson = json_decode($address->client_config_val_json, true);
  863. $express = [
  864. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  865. 'order_express_city' => $valJson['city'],
  866. 'order_express_mobile' => $valJson['mobile'],
  867. 'order_express_person' => $valJson['person']
  868. ];
  869. }
  870. }
  871. }
  872. $item['member']['level'] = '普通会员';
  873. if (!empty($item['member']['join_member_role_id'])) {
  874. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  875. }
  876. $item['member_info']['member_info_nickname'] = MemberService::getNickname(!empty($item['member_info']) ? $item['member_info']['member_info_nickname'] : '', (!empty($item['member']) ? $item['member']['member_mobile'] : ''));
  877. $item['member_info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($item['member_info']) && !empty($item['member_info']['member_info_headimg']) ? $item['member_info']['member_info_headimg'] : '');
  878. // 推荐人
  879. if (!empty($item['member']['join_invite_member_id'])) {
  880. $inviteMember = Member::with([
  881. 'cert' => function ($query) {
  882. $query->select('join_cert_member_id', 'member_cert_name');
  883. }
  884. ])->where('member_id', $item['member']['join_invite_member_id'])
  885. ->first();
  886. $inviteMobile = $inviteMember['member_mobile'] ?? '';
  887. $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
  888. $order->invite_name = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
  889. }
  890. }
  891. $order->sheet_amount = number_format($sheetAmount, 2);
  892. $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)
  893. ->where('pay_category', 'CARD')
  894. ->where('pay_status', 'SUCCESS')
  895. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  896. ->orderBy('pay_addtimes', 'DESC')
  897. ->get();
  898. $order->pay_amount_total = 0;
  899. foreach ($payDetails as &$payDetail) {
  900. $categoryArray = explode('-', $payDetail->pay_prepayid);
  901. if (isset($categoryArray[1])) {
  902. $payDetail->pay_category = $categoryArray[1];
  903. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  904. $payDetail->pay_category = $categoryArray[0];
  905. }
  906. if (!empty($payDetail->pay_extend_json)) {
  907. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  908. $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
  909. if (isset($payExtendJson['ticket'])) {
  910. $payDetail->ticket = str_replace('/thumb', '', getenv("STORAGE_DOMAIN") . $payExtendJson['ticket']);
  911. }
  912. }
  913. $order->pay_amount_total += $payDetail->pay_amount;
  914. }
  915. $refund = OrderReturn::where('join_return_order_id', $orderId)
  916. ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
  917. ->first();
  918. if (!empty($refund->order_return_refund_json)) {
  919. $returnRefundJson = json_decode($refund->order_return_refund_json, true);
  920. if (isset($returnRefundJson['user_id'])) {
  921. $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  922. $returnRefundJson['person'] = $userName;
  923. unset($returnRefundJson['user_id']);
  924. }
  925. $refund->order_return_refund_json = json_encode($returnRefundJson);
  926. }
  927. if (!empty($order->order_config_json)) {
  928. $orderConfigJson = json_decode($order->order_config_json, true);
  929. if (isset($orderConfigJson['reach'])) {
  930. $order->reach = $orderConfigJson['reach'];
  931. }
  932. if (isset($orderConfigJson['table'])) {
  933. $order->table = $orderConfigJson['table'];
  934. }
  935. if (isset($orderConfigJson['eat'])) {
  936. $order->eat = $orderConfigJson['eat'];
  937. }
  938. if (isset($orderConfigJson['express'])) {
  939. $order->express = $orderConfigJson['express'];
  940. }
  941. if (isset($orderConfigJson['premises'])) {
  942. $order->premises = $orderConfigJson['premises'];
  943. }
  944. if (isset($orderConfigJson['tableid'])) {
  945. $order->dept_table_id = $orderConfigJson['tableid'];
  946. }
  947. }
  948. if (!empty($order->order_extend_json)) {
  949. $orderExtendJson = json_decode($order->order_extend_json, true);
  950. $order->referee = $orderExtendJson['referee'] ?? '';
  951. if (isset($orderExtendJson['cancel_times'])) {
  952. $order->cancel_times = $orderExtendJson['cancel_times'];
  953. }
  954. if (isset($orderExtendJson['free_remark'])) {
  955. $order->free_remark = $orderExtendJson['free_remark'];
  956. }
  957. if (isset($orderExtendJson['dept_id'])) {
  958. $order->dept_id = $orderExtendJson['dept_id'];
  959. }
  960. if (isset($orderExtendJson['dept_name'])) {
  961. $order->premises = $orderExtendJson['dept_name'];
  962. }
  963. if (isset($orderExtendJson['referee'])) {
  964. $order->invite_name = $orderExtendJson['referee'];
  965. }
  966. }
  967. $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
  968. if (!empty($order->order_discount_json)) {
  969. $orderDiscountJson = json_decode($order->order_discount_json, true);
  970. foreach ($orderDiscountJson as $discountItem) {
  971. if (!empty($discountItem['coupon_id'])) {
  972. $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
  973. ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
  974. ->first();
  975. if (!$coupon) {
  976. continue;
  977. }
  978. $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
  979. $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  980. }
  981. if ($discountItem['coupon_classify'] == '退款') {
  982. continue;
  983. }
  984. if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
  985. if (!empty($discountItem['coupon_detail_id'])) {
  986. $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  987. } else {
  988. $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  989. }
  990. }
  991. if (!empty($discountItem['coupon_value'])) {
  992. $discount['value'] += $discountItem['coupon_value'];
  993. }
  994. }
  995. if (!empty($discount['coupon_name'])) {
  996. $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
  997. }
  998. if (!empty($discount['classify'])) {
  999. $discount['classify'] = rtrim($discount['classify'], ', ');
  1000. }
  1001. }
  1002. $discount['value'] = sprintf("%.2f", $discount['value']);
  1003. $order->discount = $discount;
  1004. $order->premises = $order->premises ?? '';
  1005. $data = [
  1006. 'order' => $order,
  1007. 'refund' => json_decode(json_encode($refund)),
  1008. 'sheet' => json_decode(json_encode($orderSheet)),
  1009. 'express' => json_decode(json_encode($express)),
  1010. 'payDetails' => json_decode(json_encode($payDetails))
  1011. ];
  1012. return json_success('', $data);
  1013. } catch (\Exception $e) {
  1014. dump($e->getMessage());
  1015. }
  1016. }
  1017. /**
  1018. * @Desc 获取分期的订单
  1019. * @Author Gorden
  1020. * @Date 2024/9/10 15:14
  1021. *
  1022. * @param Request $request
  1023. * @return Response
  1024. */
  1025. public function getPaidOrder(Request $request)
  1026. {
  1027. $memberId = $request->get('member_id');
  1028. if (!$memberId) {
  1029. return json_fail('参数异常');
  1030. }
  1031. $order = Order::where('join_order_member_id', $memberId)
  1032. ->where('order_category', 'CARD')
  1033. ->where('order_status_system', 'PAYING')
  1034. ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
  1035. ->first();
  1036. return json_success('', $order);
  1037. }
  1038. /**
  1039. * @Desc 上传支付凭证
  1040. * @Author Gorden
  1041. * @Date 2024/9/12 10:14
  1042. *
  1043. * @param Request $request
  1044. * @return Response
  1045. */
  1046. public function uploadTicket(Request $request)
  1047. {
  1048. $payId = $request->post('pay_id');
  1049. $url = $request->post('url');
  1050. if (!$payId || !$url) {
  1051. return json_fail("参数异常");
  1052. }
  1053. $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
  1054. try {
  1055. $payDetail = PayDetail::where('pay_id', $payId)->first();
  1056. if (!$payDetail) {
  1057. return json_fail('数据异常');
  1058. }
  1059. $extendJson = [];
  1060. if (!empty($payDetail->pay_extend_json)) {
  1061. $extendJson = json_decode($payDetail->pay_extend_json, true);
  1062. }
  1063. $extendJson['ticket'] = $url;
  1064. $payDetail->pay_extend_json = json_encode($extendJson);
  1065. dump($payDetail->save());
  1066. return json_success('success');
  1067. } catch (\Exception $e) {
  1068. return json_fail("上传附件失败");
  1069. }
  1070. }
  1071. /**
  1072. * @Desc 查询订单状态
  1073. * @Author Gorden
  1074. * @Date 2024/8/19 11:55
  1075. *
  1076. * @param Request $request
  1077. * @return Response|void
  1078. */
  1079. public function getOrderPayStatus(Request $request)
  1080. {
  1081. $groupId = $request->get('group_id');
  1082. if (!$groupId) {
  1083. return json_fail('参数异常');
  1084. }
  1085. $order = Order::where('order_groupby', $groupId)->first();
  1086. if (empty($order)) {
  1087. return json_fail('订单不存在');
  1088. }
  1089. $order = $order->toArray();
  1090. $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
  1091. ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
  1092. ->first();
  1093. $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
  1094. try {
  1095. Db::beginTransaction();
  1096. $payStatus = 'N';
  1097. $payAmount = 0;
  1098. if (in_array('WXPAY', $payDetailType)) {
  1099. $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
  1100. $result = json_decode(json_encode($result), true);
  1101. // $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"50","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
  1102. // $result = json_decode($result, true);
  1103. if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
  1104. $payStatus = 'Y';
  1105. $payAmount = ($result['total_fee'] / 100);
  1106. $orderUpdateData['order_status_payment'] = 'PENDING';
  1107. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1108. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1109. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1110. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1111. $orderUpdateData['order_status_system'] = 'DONE';
  1112. $orderUpdateData['order_is_complete'] = 'Y';
  1113. }
  1114. // 主订单
  1115. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1116. // Sheet
  1117. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1118. // 支付记录
  1119. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
  1120. 'pay_status' => 'SUCCESS',
  1121. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1122. 'pay_json_response' => json_encode($result)
  1123. ]);
  1124. }
  1125. } else if (in_array('ALIPAY', $payDetailType)) {
  1126. $result = Pay::alipay(config('payment.alipay'))->find($groupId);
  1127. $result = json_decode(json_encode($result), true);
  1128. // $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"0.01","send_pay_date":"2024-09-25 15:50:22","total_amount":"0.01","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}';
  1129. // $result = json_decode($result, true);
  1130. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  1131. $payStatus = 'Y';
  1132. $payAmount = $result['total_amount'];
  1133. $orderUpdateData['order_status_payment'] = 'PENDING';
  1134. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1135. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1136. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1137. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1138. $orderUpdateData['order_status_system'] = 'DONE';
  1139. $orderUpdateData['order_is_complete'] = 'Y';
  1140. }
  1141. // 主订单
  1142. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1143. // Sheet
  1144. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1145. // 支付记录
  1146. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
  1147. 'pay_status' => 'SUCCESS',
  1148. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1149. 'pay_json_response' => json_encode($result)
  1150. ]);
  1151. }
  1152. }
  1153. if ($payStatus == 'Y') {
  1154. Db::commit();
  1155. // 入收支明细表
  1156. $params['orderId'] = $order['order_id'];
  1157. $params['inout_category'] = '购买储值卡';
  1158. Event::dispatch('statistics.inout.in', $params);
  1159. return json_success('success');
  1160. }
  1161. Db::rollBack();
  1162. return json_fail('没有查询到记录');
  1163. } catch (BusinessException $e) {
  1164. Db::rollBack();
  1165. _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
  1166. return json_fail($e->getMessage());
  1167. } catch (\Exception $e) {
  1168. dump($e->getMessage());
  1169. Db::rollBack();
  1170. return json_fail('查询失败');
  1171. }
  1172. }
  1173. }