FranchiseeController.php 65 KB

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