PartnerController.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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 PartnerController 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'] = 'PARTNER';
  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', 'PARTNER')
  70. ->pluck('order_id')
  71. ->toArray();
  72. }
  73. $goodsName = trim($request->get('goods_name', ''));
  74. if (!empty($goodsName)) {
  75. $goodsIds = Goods::where('goods_classify', 'PARTNER')
  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, ['PARTNER']);
  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. // 查询是否有未完全支付订单
  246. $paidOrder = Order::where('join_order_member_id', $params['join_order_member_id'])
  247. ->where('order_category', 'PARTNER')
  248. ->where('order_status_system', 'PAYING')
  249. ->first();
  250. if (!empty($paidOrder)) {
  251. $paidOrder->order_groupby = $params['orderGroupId'];
  252. $params['orderId'] = $paidOrder->order_id;
  253. }
  254. $systemStatus = 'PAYING';
  255. // 立即结算
  256. if ($params['settlement_now'] == 'Y') {
  257. if ($params['goods_classify'] == 'PARTNER') {
  258. $params['order_is_complete'] = 'Y';
  259. $systemStatus = 'DONE';
  260. }
  261. }
  262. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  263. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  264. $params['pay_category'] = $params['pay_category_sub'];
  265. }
  266. $params['order_status_system'] = $systemStatus;
  267. $params['order_status_payment'] = 'SUCCESS';
  268. }
  269. if ($params['pay_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  270. $result = OrderService::qrcodePay($params);
  271. $result = json_encode($result);
  272. $params['pay_json_response'] = $result;
  273. $result = json_decode($result, true);
  274. $prefix = substr($params['qrcode_nbr'], 0, 2);
  275. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  276. $params['pay_category'] = 'WXPAY';
  277. 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')) {
  278. $params['order_status_system'] = 'PAYING';
  279. $params['order_status_payment'] = 'PENDING';
  280. $params['order_is_complete'] = 'N';
  281. } else {
  282. $params['order_status_system'] = $systemStatus;
  283. $params['order_status_payment'] = 'SUCCESS';
  284. }
  285. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  286. $params['pay_category'] = 'ALIPAY';
  287. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  288. $params['order_status_system'] = 'PAYING';
  289. $params['order_status_payment'] = 'PENDING';
  290. $params['order_is_complete'] = 'N';
  291. } else {
  292. $params['order_status_system'] = $systemStatus;
  293. $params['order_status_payment'] = 'SUCCESS';
  294. }
  295. } else {
  296. throw new BusinessException('付款码无效');
  297. }
  298. }
  299. if (empty($paidOrder)) {
  300. $params['order_extend_json'] = $orderExtendJson;
  301. // 写入主订单
  302. $this->insertMain($params);
  303. // 订单详情
  304. $this->insertSheet($params);
  305. } else {
  306. $params['orderGroupId'] = $paidOrder->order_groupby;
  307. if ($params['order_status_payment'] == 'SUCCESS') {
  308. $params['order_amount_paid'] = $paidOrder->order_amount_paid;
  309. $paidOrder->order_amount_paid = $paidOrder->order_amount_paid + $params['order_amount_pay'];
  310. $paidOrder->order_amount_pay = $paidOrder->order_amount_paid;
  311. if (floatval($paidOrder->order_amount_paid) >= $paidOrder->order_amount_total) {
  312. $paidOrder->order_is_complete = 'Y';
  313. $paidOrder->order_status_system = 'DONE';
  314. $paidOrder->order_status_payment = 'SUCCESS';
  315. // 更新sheet
  316. OrderSheet::where('join_sheet_order_id', $paidOrder->order_id)->update(['order_sheet_status' => 'DONE']);
  317. }
  318. }
  319. $paidOrder->save();
  320. // 清除此订单的未支付记录
  321. PayDetail::whereJsonContains('join_pay_object_json->order_id', $paidOrder->order_id)->where('pay_status', 'WAITING')->delete();
  322. }
  323. // 支付记录
  324. $this->insertPayDetail($params);
  325. Db::commit();
  326. // 分期付完
  327. $full = '';
  328. if ($params['goods_classify'] == 'PARTNER' && $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'])) {
  329. $full = '-满额';
  330. $params['member_id'] = $params['join_order_member_id'];
  331. Event::dispatch('order.partner.grant', $params);
  332. }
  333. if ($params['order_status_payment'] == 'SUCCESS') {
  334. // 入收支明细表
  335. $params['inout_category'] = '购买会员合伙人' . $full;
  336. Event::dispatch('statistics.inout.in', $params);
  337. }
  338. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  339. _syslog("订单", "支付异常,检查是否有轮询");
  340. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  341. }
  342. _syslog("订单", "创建订单成功");
  343. return json_success('创建订单成功');
  344. } catch (BusinessException $e) {
  345. Db::rollBack();
  346. dump($e->getMessage());
  347. dump($e->getTrace());
  348. _syslog("订单", $e->getMessage());
  349. return json_fail($e->getMessage());
  350. } catch (\Exception $e) {
  351. Db::rollBack();
  352. dump($e->getMessage());
  353. dump($e->getTrace());
  354. _syslog("订单", "创建订单失败");
  355. return json_fail('创建订单失败');
  356. }
  357. }
  358. /**
  359. * @Desc 支付
  360. * @Author Gorden
  361. * @Date 2024/9/5 13:12
  362. *
  363. * @param Request $request
  364. * @return Response
  365. */
  366. public function pay(Request $request)
  367. {
  368. $params = $request->post();
  369. // 验证线下付款密码
  370. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  371. $password = $params['offline_password'];
  372. if ($password != '666888') {
  373. return json_fail("密码错误,请重新输入");
  374. }
  375. }
  376. $order = Order::where('order_id', $params['order_id'])->first();
  377. if (!$order) {
  378. return json_fail('订单异常');
  379. }
  380. if ($order->order_status_system != 'PAYING') {
  381. return json_fail('订单不是可支付状态');
  382. }
  383. $params['orderId'] = $params['order_id'];
  384. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  385. $order->order_groupby = $params['orderGroupId'];
  386. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  387. ->select('goods_id', 'goods_name', 'goods_classify')
  388. ->first();
  389. if (!$goods) {
  390. return json_fail('产品数据异常');
  391. }
  392. $goods = $goods->toArray();
  393. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  394. // 入伙场所
  395. if (!empty($params['dept_id'])) {
  396. $orderExtendJson = [];
  397. if (!empty($order->order_extend_json)) {
  398. $orderExtendJson = json_decode($order->order_extend_json, true);
  399. }
  400. $dept = SysDept::where('dept_id', $params['dept_id'])->first();
  401. if (!$dept) {
  402. throw new BusinessException("入伙场所不存在");
  403. }
  404. $params['dept_name'] = $dept->dept_name;
  405. $orderExtendJson['dept_id'] = $params['dept_id'];
  406. $orderExtendJson['dept_name'] = $params['dept_name'];
  407. $order->order_extend_json = json_encode($orderExtendJson);
  408. }
  409. // 立即结算
  410. if ($params['goods_classify'] == 'PARTNER') {
  411. $order->order_is_complete = 'Y';
  412. $systemStatus = 'DONE';
  413. }
  414. $paymentStatus = 'PENDING';
  415. Db::beginTransaction();
  416. try {
  417. // 组合支付时,付款码应收金额
  418. $qrcodePayAmount = 0;
  419. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  420. $order->order_status_system = $systemStatus;
  421. $order->order_status_payment = 'SUCCESS';
  422. $paymentStatus = 'SUCCESS';
  423. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  424. $params['pay_category'] = $params['pay_category_sub'];
  425. }
  426. }
  427. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  428. // 提交过来的支付分类
  429. $submitPayCategory = $params['pay_category'];
  430. // 账户支付的金额
  431. $accountAmount = $params['order_amount_pay'];
  432. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  433. // 组合支付,改成需要付款码需要支付的金额
  434. $params['order_amount_pay'] = $qrcodePayAmount;
  435. }
  436. // 去支付
  437. $result = OrderService::qrcodePay($params);
  438. $result = json_encode($result);
  439. $params['pay_json_response'] = $result;
  440. $result = json_decode($result, true);
  441. $prefix = substr($params['qrcode_nbr'], 0, 2);
  442. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  443. $params['pay_category'] = 'WXPAY';
  444. 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')) {
  445. $order->order_status_system = 'PAYING';
  446. $order->order_status_payment = 'PENDING';
  447. $order->order_is_complete = 'N';
  448. // Db::rollBack();
  449. // return json_fail('支付失败');
  450. } else {
  451. $order->order_status_system = $systemStatus;
  452. $order->order_status_payment = 'SUCCESS';
  453. $paymentStatus = 'SUCCESS';
  454. }
  455. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  456. $params['pay_category'] = 'ALIPAY';
  457. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  458. $order->order_status_system = 'PAYING';
  459. $order->order_status_payment = 'PENDING';
  460. $order->order_is_complete = 'N';
  461. // Db::rollBack();
  462. // return json_fail('支付失败');
  463. } else {
  464. $order->order_status_system = $systemStatus;
  465. $order->order_status_payment = 'SUCCESS';
  466. $paymentStatus = 'SUCCESS';
  467. }
  468. } else {
  469. throw new BusinessException('付款码无效');
  470. }
  471. // 账户支付的金额
  472. $params['order_amount_pay'] = $accountAmount;
  473. }
  474. if ($order->order_status_payment == 'SUCCESS') {
  475. $order->order_amount_paid = $order->order_amount_paid + $params['order_amount_pay'];
  476. $order->order_amount_pay = $order->order_amount_paid;
  477. }
  478. // 分期,支付完就结束了
  479. if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'PARTNER' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
  480. $order->order_is_complete = 'Y';
  481. }
  482. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  483. $order->order_status_system = 'PAYING';
  484. $order->order_status_payment = 'PENDING';
  485. $order->order_is_complete = 'N';
  486. }
  487. // 主订单
  488. $order->save();
  489. // sheet
  490. if ($order->order_status_payment == 'SUCCESS') {
  491. $data = [
  492. 'order_sheet_status' => $systemStatus
  493. ];
  494. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  495. $data['order_sheet_status'] = 'BEING';
  496. }
  497. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data);
  498. }
  499. // payDetail
  500. $payData = [
  501. 'pay_amount' => $params['order_amount_pay']
  502. ];
  503. if ($paymentStatus == 'SUCCESS') {
  504. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  505. $payData['pay_status'] = 'SUCCESS';
  506. }
  507. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  508. $payData['pay_prepayid'] = $params['pay_category'];
  509. $payData['pay_json_response'] = $params['pay_json_response'];
  510. } else if ($params['pay_category'] == 'CASH') {
  511. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  512. } else if ($params['pay_category'] == 'WELFARE') {
  513. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  514. } else if ($params['pay_category'] == 'CARD') {
  515. $payData['pay_prepayid'] = $params['card_nbr'];
  516. } else if ($params['pay_category'] == 'OFFLINE') {
  517. $payData['pay_prepayid'] = 'OFFLINE';
  518. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  519. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  520. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  521. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  522. } else if ($params['pay_category'] == 'MONEY') {
  523. $payData['pay_prepayid'] = 'MONEY';
  524. }
  525. // 清除此订单的未支付记录
  526. PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete();
  527. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  528. $payData['join_pay_order_id'] = $order->order_groupby;
  529. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  530. $payData['pay_category'] = $params['goods_classify'] ?? '';
  531. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  532. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  533. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? json_encode([
  534. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  535. ]) : '[]';
  536. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  537. $payData['pay_addtimes'] = time();
  538. PayDetail::insert($payData);
  539. Db::commit();
  540. // 分期付款完成
  541. $full = '';
  542. if ($params['goods_classify'] == 'PARTNER' && $order->order_status_payment == 'SUCCESS' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
  543. $full = '-满额';
  544. $params['member_id'] = $params['join_order_member_id'];
  545. Event::dispatch('order.complete', $params);
  546. Event::dispatch('order.partner.grant', $params);
  547. // 加销售量
  548. OrderSheetService::addGoodsSales($params['orderId']);
  549. }
  550. if ($order->order_status_payment == 'SUCCESS') {
  551. // 入收支明细表
  552. $params['inout_category'] = '购买会员合伙人' . $full;
  553. Event::dispatch('statistics.inout.in', $params);
  554. }
  555. if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') {
  556. _syslog("订单", "支付异常,检查是否有轮询");
  557. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  558. }
  559. _syslog("订单", "订单支付成功");
  560. return json_success('支付成功');
  561. } catch (BusinessException $e) {
  562. dump($e->getMessage());
  563. Db::rollBack();
  564. _syslog("订单", "订单支付失败:" . $e->getMessage());
  565. return json_fail("支付失败:" . $e->getMessage());
  566. } catch (\Exception $e) {
  567. dump($e->getMessage());
  568. Db::rollBack();
  569. _syslog("订单", "订单支付失败");
  570. return json_fail('支付失败');
  571. }
  572. }
  573. /**
  574. * @Desc
  575. * @Author Gorden
  576. * @Date 2024/6/7 10:30
  577. *
  578. * @param $params
  579. * @return void
  580. * @throws BusinessException
  581. */
  582. public function insertMain($params)
  583. {
  584. try {
  585. $orderCategory = 'NORMAL';
  586. if (!empty($params['order_category'])) {
  587. $orderCategory = $params['order_category'];
  588. } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  589. $orderCategory = 'DISHES';
  590. } else if (isset($params['goods_classify'])) {
  591. $orderCategory = $params['goods_classify'];
  592. }
  593. if (empty($params['order_extend_json'])) {
  594. $params['order_extend_json'] = [];
  595. } else {
  596. if (is_json($params['order_extend_json'])) {
  597. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  598. }
  599. }
  600. // 推荐人
  601. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  602. $data = [
  603. 'order_id' => $params['orderId'],
  604. 'order_groupby' => $params['orderGroupId'],
  605. 'join_order_member_id' => $params['join_order_member_id'],
  606. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  607. 'order_amount_total' => $params['order_amount_total'],
  608. 'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  609. 'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  610. 'order_category' => $orderCategory,
  611. 'order_classify' => $orderCategory,
  612. 'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N',
  613. 'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  614. 'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING',
  615. 'order_status_storage' => $params['order_status_storage'],
  616. 'order_platform' => $params['order_platform'],
  617. 'order_remark' => $params['order_remark'] ?? '',
  618. 'order_discount_json' => $params['order_discount_json'] ?? '[]',
  619. 'order_config_json' => $params['order_config_json'] ?? '[]',
  620. 'order_express_json' => $params['order_express_json'] ?? '[]',
  621. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  622. 'order_addtimes' => time(),
  623. 'order_add_user_id'=>JwtToken::getCurrentId()
  624. ];
  625. Order::insert($data);
  626. } catch (\Exception $e) {
  627. dump($e->getMessage());
  628. throw new BusinessException('订单创建信息失败');
  629. }
  630. }
  631. /**
  632. * @Desc
  633. * @Author Gorden
  634. * @Date 2024/6/7 10:25
  635. *
  636. * @param $params
  637. * @return void
  638. * @throws BusinessException
  639. */
  640. public function insertSheet($params)
  641. {
  642. try {
  643. $orderSheetIds = [];
  644. foreach ($params['goodsContentList'] as $goods) {
  645. //{"unit": "份", "table": null, "premises": "15"}
  646. $price = floatval($goods['goods_sales_price']);
  647. $extendJson['unit'] = $goods['sku_name'];
  648. if (isset($params['submit_premises_id'])) {
  649. $extendJson['premises'] = $params['submit_premises_id'];
  650. }
  651. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  652. $extendJson['table'] = null;
  653. }
  654. $orderSheetStatus = 'PAYING';
  655. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  656. if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
  657. $orderSheetStatus = 'DONE';
  658. } else {
  659. $orderSheetStatus = 'BEING';
  660. }
  661. }
  662. $data = [
  663. 'join_sheet_member_id' => $params['join_order_member_id'],
  664. 'join_sheet_order_id' => $params['orderId'],
  665. 'join_sheet_goods_id' => $goods['goods_id'],
  666. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  667. 'order_sheet_status' => $orderSheetStatus,
  668. 'order_sheet_category' => 'PARTNER',
  669. 'order_sheet_num' => $goods['nbr'],
  670. 'order_sheet_price' => $goods['goods_sales_price'],
  671. 'order_sheet_price_pay' => $goods['goods_sales_price'],
  672. 'order_sheet_amount' => $price * $goods['nbr'],
  673. 'order_sheet_pay' => $price * $goods['nbr'],
  674. 'order_sheet_task_status' => 'NONE',
  675. 'order_sheet_remark' => $params['order_remark'] ?? '',
  676. 'order_sheet_addtimes' => time(),
  677. 'order_sheet_extend_json' => json_encode($extendJson)
  678. ];
  679. $orderSheetId = OrderSheet::insertGetId($data);
  680. $orderSheetIds[] = $orderSheetId;
  681. // 减库存,规格和总库存
  682. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  683. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  684. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  685. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  686. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  687. }
  688. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  689. throw new BusinessException('库存不足');
  690. }
  691. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  692. $goodsSku->save();
  693. }
  694. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  695. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  696. if ($goodsRunning->goods_running_storage < 0) {
  697. throw new BusinessException('库存不足');
  698. }
  699. if ($params['order_status_payment'] == 'SUCCESS') {
  700. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  701. }
  702. $goodsRunning->save();
  703. }
  704. return $orderSheetIds;
  705. } catch (\support\exception\BusinessException $e) {
  706. dump($e->getMessage() . '||' . $e->getLine());
  707. throw new BusinessException($e->getMessage());
  708. } catch (\Exception $e) {
  709. dump($e->getMessage() . '||' . $e->getLine());
  710. throw new BusinessException('订单创建失败');
  711. }
  712. }
  713. /**
  714. * @Desc
  715. * @Author Gorden
  716. * @Date 2024/6/7 10:35
  717. *
  718. * @param $params
  719. * @return void
  720. * @throws BusinessException
  721. */
  722. public function insertPayDetail($params)
  723. {
  724. try {
  725. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  726. $payPrepayid = $params['pay_category'];
  727. } else if ($params['pay_category'] == 'OFFLINE') {
  728. $payPrepayid = 'OFFLINE';
  729. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  730. $payPrepayid = 'OFFLINE_ALIPAY';
  731. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  732. $payPrepayid = 'OFFLINE_WXPAY';
  733. } else if ($params['pay_category'] == 'MONEY') {
  734. $payPrepayid = 'MONEY';
  735. } else {
  736. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  737. }
  738. $data = [
  739. 'join_pay_member_id' => $params['join_order_member_id'],
  740. 'join_pay_order_id' => $params['orderGroupId'],
  741. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  742. 'pay_category' => $params['goods_classify'],
  743. 'pay_amount' => $params['order_amount_pay'],
  744. 'pay_prepayid' => $payPrepayid,
  745. 'pay_paytimes' => date('Y-m-d H:i:s'),
  746. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  747. 'pay_json_request' => json_encode($params),
  748. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  749. 'pay_remark' => $params['order_remark'] ?? '',
  750. 'pay_addtimes' => time(),
  751. ];
  752. PayDetail::insert($data);
  753. } catch (\Exception $e) {
  754. dump($e->getMessage());
  755. throw new BusinessException('创建支付记录失败');
  756. }
  757. }
  758. /**
  759. * @Desc 订单商品详情
  760. * @Author Gorden
  761. * @Date 2024/3/29 8:50
  762. *
  763. * @param Request $request
  764. * @return Response
  765. */
  766. public function sheet(Request $request)
  767. {
  768. try {
  769. $orderId = $request->get('order_id');
  770. $orderSheet = OrderSheet::with([
  771. 'member' => function ($query) {
  772. $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');
  773. },
  774. 'goods' => function ($query) {
  775. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  776. },
  777. 'memberInfo',
  778. 'cert',
  779. 'sku' => function ($query) {
  780. $query->where('goods_sku_status', 'ON')
  781. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  782. },
  783. 'skus',
  784. 'refund' => function ($query) {
  785. $query->select('join_return_order_id', 'order_return_status');
  786. }
  787. ])->where('join_sheet_order_id', $orderId)
  788. ->orderBy('order_sheet_id', 'DESC')
  789. ->get()
  790. ->toArray();
  791. $order = Order::where('order_id', $orderId)->first();
  792. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  793. $sheetAmount = 0;
  794. foreach ($orderSheet as &$item) {
  795. $sheetAmount += $item['order_sheet_amount'];
  796. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  797. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  798. $components = GoodsComponent::with('goods')
  799. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  800. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  801. 'goods_component_price', 'goods_component_json')
  802. ->get()
  803. ->toArray();
  804. $goodsArr = [];
  805. foreach ($components as $component) {
  806. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  807. if (!empty($component['goods'])) {
  808. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  809. $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  810. ->where('join_benefit_goods_id', $component['goods']['goods_id'])
  811. ->where('join_benefit_order_id', $orderId)
  812. ->first();
  813. $goodsArr[] = [
  814. 'goods_name' => $component['goods']['goods_name'],
  815. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  816. 'supplier_name' => $supplierName,
  817. 'nbr' => $configJson['nbr'] ?? 0,
  818. 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
  819. ];
  820. }
  821. }
  822. $item['goods']['components'] = $goodsArr;
  823. }
  824. if (!empty($item['sku'])) {
  825. if (!empty($item['sku']['goods_sku_specs_json'])) {
  826. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  827. $skuName = '';
  828. foreach ($specsJson as $specsKey => $skuSpecs) {
  829. if (is_array($skuSpecs)) {
  830. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  831. } else {
  832. $skuName = $skuName . ' ' . $skuSpecs . ';';
  833. }
  834. }
  835. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  836. }
  837. }
  838. if (!empty($item['skus'])) {
  839. foreach ($item['skus'] as $key => $skus) {
  840. if (!empty($skus['goods_sku_specs_json'])) {
  841. $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
  842. $skuName = '';
  843. foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
  844. $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
  845. if (is_array($skuSpecs)) {
  846. $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
  847. } else {
  848. $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
  849. }
  850. }
  851. $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
  852. }
  853. }
  854. } else {
  855. $item['skus'] = [];
  856. }
  857. if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
  858. $item['appontment'] = [];
  859. $appontments = Appointment::where('join_appointment_order_id', $orderId)
  860. ->where('appointment_status', 'DONE')
  861. ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
  862. ->get()
  863. ->toArray();
  864. foreach ($appontments as $appontment) {
  865. $doneJson = [];
  866. $username = '';
  867. if (!empty($appontment['appointment_done_json'])) {
  868. $doneJson = json_decode($appontment['appointment_done_json'], true);
  869. if (isset($doneJson['charge'])) {
  870. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  871. }
  872. }
  873. $person = 1;
  874. if (!empty($appontment->appointment_apply_json)) {
  875. $applyJson = json_decode($appontment->appointment_apply_json, true);
  876. if (isset($applyJson['person'])) {
  877. $person = $applyJson['person'];
  878. }
  879. }
  880. $item['appontment'][] = [
  881. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  882. 'goods_name' => $item['goods']['goods_name'],
  883. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  884. 'username' => $username,
  885. 'nbr' => $person,
  886. 'done_time' => $appontment['appointment_done_datetime'],
  887. 'appointment_status' => $appontment['appointment_status'],
  888. ];
  889. }
  890. }
  891. if (!empty($item['order_sheet_extend_json']) && !$express) {
  892. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  893. if (isset($extendJson['address_id'])) {
  894. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  895. if (!empty($address)) {
  896. $valJson = json_decode($address->client_config_val_json, true);
  897. $express = [
  898. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  899. 'order_express_city' => $valJson['city'],
  900. 'order_express_mobile' => $valJson['mobile'],
  901. 'order_express_person' => $valJson['person']
  902. ];
  903. }
  904. }
  905. }
  906. $item['member']['level'] = '普通会员';
  907. if (!empty($item['member']['join_member_role_id'])) {
  908. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  909. }
  910. $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'] : ''));
  911. $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'] : '');
  912. // 推荐人
  913. if (!empty($item['member']['join_invite_member_id'])) {
  914. $inviteMember = Member::with([
  915. 'cert' => function ($query) {
  916. $query->select('join_cert_member_id', 'member_cert_name');
  917. }
  918. ])->where('member_id', $item['member']['join_invite_member_id'])
  919. ->first();
  920. $inviteMobile = $inviteMember['member_mobile'] ?? '';
  921. $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
  922. $order->invite_name = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
  923. }
  924. }
  925. $order->sheet_amount = number_format($sheetAmount, 2);
  926. $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)
  927. ->where('pay_category', 'PARTNER')
  928. ->where('pay_status', 'SUCCESS')
  929. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  930. ->orderBy('pay_addtimes', 'DESC')
  931. ->get();
  932. $order->pay_amount_total = 0;
  933. foreach ($payDetails as &$payDetail) {
  934. $categoryArray = explode('-', $payDetail->pay_prepayid);
  935. if (isset($categoryArray[1])) {
  936. $payDetail->pay_category = $categoryArray[1];
  937. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  938. $payDetail->pay_category = $categoryArray[0];
  939. }
  940. if (!empty($payDetail->pay_extend_json)) {
  941. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  942. $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
  943. if (isset($payExtendJson['ticket'])) {
  944. $payDetail->ticket = str_replace('/thumb', '', getenv("STORAGE_DOMAIN") . $payExtendJson['ticket']);
  945. }
  946. }
  947. $order->pay_amount_total += $payDetail->pay_amount;
  948. }
  949. $refund = OrderReturn::where('join_return_order_id', $orderId)
  950. ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
  951. ->first();
  952. if (!empty($refund->order_return_refund_json)) {
  953. $returnRefundJson = json_decode($refund->order_return_refund_json, true);
  954. if (isset($returnRefundJson['user_id'])) {
  955. $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  956. $returnRefundJson['person'] = $userName;
  957. unset($returnRefundJson['user_id']);
  958. }
  959. $refund->order_return_refund_json = json_encode($returnRefundJson);
  960. }
  961. if (!empty($order->order_config_json)) {
  962. $orderConfigJson = json_decode($order->order_config_json, true);
  963. if (isset($orderConfigJson['reach'])) {
  964. $order->reach = $orderConfigJson['reach'];
  965. }
  966. if (isset($orderConfigJson['table'])) {
  967. $order->table = $orderConfigJson['table'];
  968. }
  969. if (isset($orderConfigJson['eat'])) {
  970. $order->eat = $orderConfigJson['eat'];
  971. }
  972. if (isset($orderConfigJson['express'])) {
  973. $order->express = $orderConfigJson['express'];
  974. }
  975. if (isset($orderConfigJson['premises'])) {
  976. $order->premises = $orderConfigJson['premises'];
  977. }
  978. if (isset($orderConfigJson['tableid'])) {
  979. $order->dept_table_id = $orderConfigJson['tableid'];
  980. }
  981. }
  982. if (!empty($order->order_extend_json)) {
  983. $orderExtendJson = json_decode($order->order_extend_json, true);
  984. $order->referee = $orderExtendJson['referee'] ?? '';
  985. if (isset($orderExtendJson['cancel_times'])) {
  986. $order->cancel_times = $orderExtendJson['cancel_times'];
  987. }
  988. if (isset($orderExtendJson['free_remark'])) {
  989. $order->free_remark = $orderExtendJson['free_remark'];
  990. }
  991. if (isset($orderExtendJson['dept_id'])) {
  992. $order->dept_id = $orderExtendJson['dept_id'];
  993. }
  994. if (isset($orderExtendJson['dept_name'])) {
  995. $order->premises = $orderExtendJson['dept_name'];
  996. }
  997. if (isset($orderExtendJson['referee'])) {
  998. $order->invite_name = $orderExtendJson['referee'];
  999. }
  1000. }
  1001. $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
  1002. if (!empty($order->order_discount_json)) {
  1003. $orderDiscountJson = json_decode($order->order_discount_json, true);
  1004. foreach ($orderDiscountJson as $discountItem) {
  1005. if (!empty($discountItem['coupon_id'])) {
  1006. $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
  1007. ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
  1008. ->first();
  1009. if (!$coupon) {
  1010. continue;
  1011. }
  1012. $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
  1013. $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1014. }
  1015. if ($discountItem['coupon_classify'] == '退款') {
  1016. continue;
  1017. }
  1018. if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
  1019. if (!empty($discountItem['coupon_detail_id'])) {
  1020. $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1021. } else {
  1022. $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1023. }
  1024. }
  1025. if (!empty($discountItem['coupon_value'])) {
  1026. $discount['value'] += $discountItem['coupon_value'];
  1027. }
  1028. }
  1029. if (!empty($discount['coupon_name'])) {
  1030. $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
  1031. }
  1032. if (!empty($discount['classify'])) {
  1033. $discount['classify'] = rtrim($discount['classify'], ', ');
  1034. }
  1035. }
  1036. $discount['value'] = sprintf("%.2f", $discount['value']);
  1037. $order->discount = $discount;
  1038. $order->premises = $order->premises ?? '';
  1039. $data = [
  1040. 'order' => $order,
  1041. 'refund' => json_decode(json_encode($refund)),
  1042. 'sheet' => json_decode(json_encode($orderSheet)),
  1043. 'express' => json_decode(json_encode($express)),
  1044. 'payDetails' => json_decode(json_encode($payDetails))
  1045. ];
  1046. return json_success('', $data);
  1047. } catch (\Exception $e) {
  1048. dump($e->getMessage());
  1049. }
  1050. }
  1051. /**
  1052. * @Desc 获取分期的订单
  1053. * @Author Gorden
  1054. * @Date 2024/9/10 15:14
  1055. *
  1056. * @param Request $request
  1057. * @return Response
  1058. */
  1059. public function getPaidOrder(Request $request)
  1060. {
  1061. $memberId = $request->get('member_id');
  1062. if (!$memberId) {
  1063. return json_fail('参数异常');
  1064. }
  1065. $order = Order::where('join_order_member_id', $memberId)
  1066. ->where('order_category', 'PARTNER')
  1067. ->where('order_status_system', 'PAYING')
  1068. ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
  1069. ->first();
  1070. return json_success('', $order);
  1071. }
  1072. /**
  1073. * @Desc 上传支付凭证
  1074. * @Author Gorden
  1075. * @Date 2024/9/12 10:14
  1076. *
  1077. * @param Request $request
  1078. * @return Response
  1079. */
  1080. public function uploadTicket(Request $request)
  1081. {
  1082. $payId = $request->post('pay_id');
  1083. $url = $request->post('url');
  1084. if (!$payId || !$url) {
  1085. return json_fail("参数异常");
  1086. }
  1087. $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
  1088. try {
  1089. $payDetail = PayDetail::where('pay_id', $payId)->first();
  1090. if (!$payDetail) {
  1091. return json_fail('数据异常');
  1092. }
  1093. $extendJson = [];
  1094. if (!empty($payDetail->pay_extend_json)) {
  1095. $extendJson = json_decode($payDetail->pay_extend_json, true);
  1096. }
  1097. $extendJson['ticket'] = $url;
  1098. $payDetail->pay_extend_json = json_encode($extendJson);
  1099. dump($payDetail->save());
  1100. return json_success('success');
  1101. } catch (\Exception $e) {
  1102. return json_fail("上传附件失败");
  1103. }
  1104. }
  1105. /**
  1106. * @Desc 查询订单状态
  1107. * @Author Gorden
  1108. * @Date 2024/8/19 11:55
  1109. *
  1110. * @param Request $request
  1111. * @return Response|void
  1112. */
  1113. public function getOrderPayStatus(Request $request)
  1114. {
  1115. $groupId = $request->get('group_id');
  1116. if (!$groupId) {
  1117. return json_fail('参数异常');
  1118. }
  1119. $order = Order::where('order_groupby', $groupId)->first();
  1120. if (empty($order)) {
  1121. return json_fail('订单不存在');
  1122. }
  1123. $order = $order->toArray();
  1124. $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
  1125. ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
  1126. ->first();
  1127. $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
  1128. try {
  1129. Db::beginTransaction();
  1130. $payStatus = 'N';
  1131. $payAmount = 0;
  1132. if (in_array('WXPAY', $payDetailType)) {
  1133. $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
  1134. $result = json_decode(json_encode($result), true);
  1135. // $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"}';
  1136. // $result = json_decode($result, true);
  1137. 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') {
  1138. $payStatus = 'Y';
  1139. $payAmount = ($result['total_fee'] / 100);
  1140. $orderUpdateData['order_status_payment'] = 'PENDING';
  1141. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1142. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1143. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1144. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1145. $orderUpdateData['order_status_system'] = 'DONE';
  1146. $orderUpdateData['order_is_complete'] = 'Y';
  1147. }
  1148. // 主订单
  1149. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1150. // Sheet
  1151. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1152. // 支付记录
  1153. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
  1154. 'pay_status' => 'SUCCESS',
  1155. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1156. 'pay_json_response' => json_encode($result)
  1157. ]);
  1158. }
  1159. } else if (in_array('ALIPAY', $payDetailType)) {
  1160. $result = Pay::alipay(config('payment.alipay'))->find($groupId);
  1161. $result = json_decode(json_encode($result), true);
  1162. // $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"}';
  1163. // $result = json_decode($result, true);
  1164. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  1165. $payStatus = 'Y';
  1166. $payAmount = $result['total_amount'];
  1167. $orderUpdateData['order_status_payment'] = 'PENDING';
  1168. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1169. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1170. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1171. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1172. $orderUpdateData['order_status_system'] = 'DONE';
  1173. $orderUpdateData['order_is_complete'] = 'Y';
  1174. }
  1175. // 主订单
  1176. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1177. // Sheet
  1178. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1179. // 支付记录
  1180. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
  1181. 'pay_status' => 'SUCCESS',
  1182. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1183. 'pay_json_response' => json_encode($result)
  1184. ]);
  1185. }
  1186. }
  1187. $full = '';
  1188. if ($payStatus == 'Y') {
  1189. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1190. $full = '-满额';
  1191. $params['member_id'] = $order['join_order_member_id'];
  1192. $params['orderId'] = $order['order_id'];
  1193. $params['order_amount_pay'] = $payAmount;
  1194. $params['order_amount_total'] = $order['order_amount_total'];
  1195. $params['join_sheet_goods_id'] = $sheet->join_sheet_goods_id;
  1196. if (!empty($order['order_extend_json'])) {
  1197. $orderExtendJson = json_decode($order['order_extend_json'], true);
  1198. $params['dept_id'] = $orderExtendJson['dept_id'] ?? '';
  1199. $params['dept_name'] = $orderExtendJson['dept_name'] ?? '';
  1200. }
  1201. Event::dispatch('order.partner.grant', $params);
  1202. }
  1203. Db::commit();
  1204. // 入收支明细表
  1205. $params['orderId'] = $order['order_id'];
  1206. $params['inout_category'] = '购买会员合伙人' . $full;
  1207. Event::dispatch('statistics.inout.in', $params);
  1208. return json_success('success');
  1209. }
  1210. Db::rollBack();
  1211. return json_fail('没有查询到记录');
  1212. } catch (BusinessException $e) {
  1213. Db::rollBack();
  1214. _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
  1215. return json_fail($e->getMessage());
  1216. } catch (\Exception $e) {
  1217. dump($e->getMessage());
  1218. Db::rollBack();
  1219. return json_fail('查询失败');
  1220. }
  1221. }
  1222. }