NewCustomerController.php 61 KB

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