CardController.php 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\coupon\CouponDetailService;
  4. use app\admin\service\coupon\CouponService;
  5. use app\admin\service\member\MemberService;
  6. use app\admin\service\order\OrderService;
  7. use app\admin\service\order\OrderSheetService;
  8. use app\admin\service\order\PayDetailService;
  9. use app\admin\validate\order\OrderValidate;
  10. use app\controller\Curd;
  11. use app\model\Appointment;
  12. use app\model\Card;
  13. use app\model\ClientConfig;
  14. use app\model\Coupon;
  15. use app\model\CouponDetail;
  16. use app\model\Goods;
  17. use app\model\GoodsComponent;
  18. use app\model\GoodsRunning;
  19. use app\model\GoodsSku;
  20. use app\model\Member;
  21. use app\model\MemberAccount;
  22. use app\model\MemberBenefit;
  23. use app\model\MemberRole;
  24. use app\model\Order;
  25. use app\model\OrderExpress;
  26. use app\model\OrderReturn;
  27. use app\model\OrderSheet;
  28. use app\model\PayDetail;
  29. use app\model\Supplier;
  30. use app\model\SysDept;
  31. use app\model\SysUser;
  32. use support\Db;
  33. use support\exception\BusinessException;
  34. use support\Log;
  35. use support\Redis;
  36. use support\Request;
  37. use support\Response;
  38. use Tinywan\Jwt\JwtToken;
  39. use Webman\Event\Event;
  40. use Yansongda\Pay\Pay;
  41. class CardController extends Curd
  42. {
  43. public function __construct()
  44. {
  45. $this->model = new Order();
  46. $this->validate = true;
  47. $this->validateClass = new OrderValidate();
  48. }
  49. /**
  50. * @Desc 列表
  51. * @Author Gorden
  52. * @Date 2024/3/28 15:01
  53. *
  54. * @param Request $request
  55. * @return Response
  56. * @throws \support\exception\BusinessException
  57. */
  58. public function select(Request $request): Response
  59. {
  60. $timeType = $request->get('time_type', 'add');
  61. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  62. $where['order_classify'] = 'CARD';
  63. if (!empty($where['order_addtimes']) && $timeType == 'add') {
  64. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  65. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  66. }
  67. $order = $request->get('order', 'desc');
  68. $orderId = $request->get('orderId');
  69. $field = $field ?? 'order_addtimes';
  70. $orderIds = [];
  71. if (!empty($orderId)) {
  72. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  73. ->where('order_classify', 'CARD')
  74. ->pluck('order_id')
  75. ->toArray();
  76. }
  77. $goodsName = trim($request->get('goods_name', ''));
  78. if (!empty($goodsName)) {
  79. $goodsIds = Goods::where('goods_classify', 'CARD')
  80. ->where('goods_name', 'like', '%' . $goodsName . '%')
  81. ->pluck('goods_id')
  82. ->toArray();
  83. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  84. if (!empty($where['order_id'])) {
  85. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  86. } else {
  87. $orderIds = $goodsOrderIds;
  88. }
  89. }
  90. // 付款时间
  91. $payOrderIds = [];
  92. if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
  93. $payTimeStart = strtotime($where['order_addtimes'][0]);
  94. $payTimeEnd = strtotime($where['order_addtimes'][1]);
  95. unset($where['order_addtimes']);
  96. $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['CARD']);
  97. }
  98. if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
  99. $orderIds = array_intersect($orderIds, $payOrderIds);
  100. $where['order_id'] = ['in', implode(',', $orderIds)];
  101. } elseif (!empty($orderId) || !empty($goodsName)) {
  102. $where['order_id'] = ['in', implode(',', $orderIds)];
  103. } elseif ($timeType == 'pay') {
  104. $where['order_id'] = ['in', implode(',', $payOrderIds)];
  105. }
  106. $query = $this->doSelect($where, $field, $order);
  107. return $this->doFormat($query, $format, $limit);
  108. }
  109. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  110. {
  111. $model = $this->model->with([
  112. 'sheets' => function ($query) {
  113. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  114. },
  115. 'member' => function ($query) {
  116. $query->select('member_id', 'member_mobile', 'join_invite_member_id');
  117. },
  118. 'cert' => function ($query) {
  119. $query->select('join_cert_member_id', 'member_cert_name');
  120. },
  121. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  122. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  123. foreach ($where as $column => $value) {
  124. if (is_array($value)) {
  125. if ($value[0] === 'like' || $value[0] === 'not like') {
  126. $model = $model->where($column, $value[0], "%$value[1]%");
  127. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  128. $model = $model->where($column, $value[0], $value[1]);
  129. } elseif ($value[0] == 'in' && !empty($value[1])) {
  130. $valArr = $value[1];
  131. if (is_string($value[1])) {
  132. $valArr = explode(",", trim($value[1]));
  133. }
  134. $model = $model->whereIn($column, $valArr);
  135. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  136. $valArr = $value[1];
  137. if (is_string($value[1])) {
  138. $valArr = explode(",", trim($value[1]));
  139. }
  140. $model = $model->whereNotIn($column, $valArr);
  141. } elseif ($value[0] == 'null') {
  142. $model = $model->whereNull($column);
  143. } elseif ($value[0] == 'not null') {
  144. $model = $model->whereNotNull($column);
  145. } elseif ($value[0] !== '' || $value[1] !== '') {
  146. $model = $model->whereBetween($column, $value);
  147. }
  148. } else {
  149. $model = $model->where($column, $value);
  150. }
  151. }
  152. if ($field) {
  153. $model = $model->orderBy($field, $order);
  154. }
  155. $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');
  156. return $model;
  157. }
  158. public function afterQuery($items)
  159. {
  160. foreach ($items as &$item) {
  161. $sheetDeng = '';
  162. $item['sheet'] = $item['sheets'][0] ?? [];
  163. if (!empty($item['sheet'])) {
  164. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  165. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  166. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  167. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  168. }
  169. unset($item['sheets']);
  170. if (isset($item['orders_return_id'])) {
  171. $item['return'] = [
  172. 'orders_return_id' => $item['orders_return_id'],
  173. 'join_return_order_id' => $item['join_return_order_id'],
  174. 'order_return_status' => $item['order_return_status'],
  175. 'order_return_apply_json' => $item['order_return_apply_json'],
  176. 'order_return_remark' => $item['order_return_remark']
  177. ];
  178. }
  179. if (isset($item['join_express_order_id'])) {
  180. $item['express'] = [
  181. 'join_express_order_id' => $item['join_express_order_id'],
  182. 'order_express_type' => $item['order_express_type']
  183. ];
  184. unset($item['join_express_order_id'], $item['order_express_type']);
  185. }
  186. if (!empty($item['member']['join_invite_member_id'])) {
  187. $inviteMember = Member::with([
  188. 'cert' => function ($query) {
  189. $query->select('join_cert_member_id', 'member_cert_name');
  190. }
  191. ])->where('member_id', $item['member']['join_invite_member_id'])
  192. ->first();
  193. $inviteMobile = $inviteMember['member_mobile'] ?? '';
  194. $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
  195. $item['invite_name'] = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
  196. }
  197. $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
  198. }
  199. return $items;
  200. }
  201. /**
  202. * @Desc 获取卡列表
  203. * @Author Gorden
  204. * @Date 2024/11/22 15:33
  205. *
  206. * @param Request $request
  207. * @return Response
  208. */
  209. public function getCardList(Request $request)
  210. {
  211. $orderId = $request->get('order_id');
  212. $goodsId = OrderSheet::where('join_sheet_order_id', $orderId)->value('join_sheet_goods_id');
  213. $goods = Goods::where('goods_id', $goodsId)->select('goods_attribute_json')->first();
  214. $cards = [];
  215. if (!empty($goods->goods_attribute_json)) {
  216. $goodsAttributeJson = json_decode($goods->goods_attribute_json, true);
  217. if (!empty($goodsAttributeJson['card_main_id'])) {
  218. $cards = Card::where('join_card_main_id', $goodsAttributeJson['card_main_id'])
  219. ->where('card_status', 'WAITING')
  220. ->where('is_issue', 'Y')
  221. ->pluck('card_id')
  222. ->toArray();
  223. }
  224. }
  225. return json_success('success', $cards);
  226. }
  227. /**
  228. * @Desc 下单+支付
  229. * @Author Gorden
  230. * @Date 2024/9/23 16:15
  231. *
  232. * @param Request $request
  233. * @return Response
  234. */
  235. public function insert(Request $request): Response
  236. {
  237. $params = $request->post();
  238. // 判断餐品是否连带着服务或实体
  239. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  240. $premises = [];
  241. if (!empty($params['dept_premises_id'])) {
  242. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  243. }
  244. try {
  245. // 下单账户
  246. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  247. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  248. throw new BusinessException('会员已存在');
  249. }
  250. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  251. // 创建会员
  252. MemberService::createMember($params);
  253. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  254. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  255. }
  256. if (empty($params['join_order_member_id'])) {
  257. throw new BusinessException('检查下单账户');
  258. }
  259. // 带着优惠券,要发券
  260. if (!empty($params['custom_member_id'])) {
  261. // 把券从000000加到真实账户
  262. CouponDetailService::transCoupon('000000', $params['join_order_member_id']);
  263. }
  264. } catch (BusinessException $e) {
  265. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  266. _syslog("订单", $e->getMessage());
  267. return json_fail($e->getMessage());
  268. } catch (\Exception $e) {
  269. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  270. _syslog("订单", "创建订单失败");
  271. return json_fail('创建订单失败');
  272. }
  273. $params['goods_classify'] = $goodsClassifys[0];
  274. Db::beginTransaction();
  275. try {
  276. // 使用优惠券
  277. $couponUseJson = [];
  278. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  279. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  280. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  281. throw new BusinessException("计算优惠后,实付金额错误!");
  282. }
  283. // 组装优惠券使用数据,存主表优惠里
  284. if (!empty($couponResult['use_coupon_json'])) {
  285. $couponUseJson = $couponResult['use_coupon_json'];
  286. }
  287. }
  288. // 存储优惠信息
  289. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  290. // 验证库存
  291. foreach ($params['goodsContentList'] as $goods) {
  292. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  293. dump($goodsRunning);
  294. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  295. if ($goodsRunning->goods_running_storage < 0) {
  296. throw new BusinessException('库存不足');
  297. }
  298. }
  299. // 验证线下付款密码
  300. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  301. $password = $params['offline_password'];
  302. if ($password != '666888') {
  303. throw new BusinessException('密码错误,请重新输入');
  304. }
  305. }
  306. $qrcodePayAmount = 0;
  307. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  308. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  309. $systemStatus = 'SENDING'; // 待发货
  310. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  311. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  312. $params['pay_category'] = $params['pay_category_sub'];
  313. }
  314. $params['order_status_system'] = $systemStatus;
  315. $params['order_status_payment'] = 'SUCCESS';
  316. }
  317. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  318. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  319. $params['order_status_system'] = $systemStatus;
  320. $params['order_status_payment'] = 'SUCCESS';
  321. }
  322. // 不组合或者组合后需要付款码的金额>0
  323. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  324. $result = OrderService::qrcodePay($params);
  325. $result = json_encode($result);
  326. $params['pay_json_response'] = $result;
  327. $result = json_decode($result, true);
  328. $prefix = substr($params['qrcode_nbr'], 0, 2);
  329. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  330. $params['pay_category'] = 'WXPAY';
  331. 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')) {
  332. $params['order_status_system'] = 'PAYING';
  333. $params['order_status_payment'] = 'PENDING';
  334. $params['order_is_complete'] = 'N';
  335. } else {
  336. $params['order_status_system'] = $systemStatus;
  337. $params['order_status_payment'] = 'SUCCESS';
  338. }
  339. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  340. $params['pay_category'] = 'ALIPAY';
  341. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  342. $params['order_status_system'] = 'PAYING';
  343. $params['order_status_payment'] = 'PENDING';
  344. $params['order_is_complete'] = 'N';
  345. } else {
  346. $params['order_status_system'] = $systemStatus;
  347. $params['order_status_payment'] = 'SUCCESS';
  348. }
  349. } else {
  350. throw new BusinessException('付款码无效');
  351. }
  352. }
  353. }
  354. $orderConfigJson = [];
  355. // 优惠
  356. if (!empty($params['preferential'])) {
  357. $orderConfigJson['preferential'] = $params['preferential'];
  358. }
  359. // 配送方式
  360. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  361. $orderConfigJson['premises'] = $params['dept_premises_id'];
  362. }
  363. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  364. $params['submit_premises_id'] = $premises->dept_id;
  365. }
  366. $params['order_config_json'] = json_encode($orderConfigJson);
  367. // 写入订单
  368. $this->insertMain($params);
  369. Db::commit();
  370. // 触发事件
  371. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  372. Event::dispatch('order.complete', $params);
  373. }
  374. // 触发事件
  375. if ($params['order_status_payment'] == 'SUCCESS') {
  376. // 上级提成
  377. OrderService::splitOrderCommission($params);
  378. // 入收支明细表
  379. $params['inout_category'] = '购买储值卡';
  380. Event::dispatch('statistics.inout.in', $params);
  381. }
  382. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  383. _syslog("订单", "支付异常,检查是否有轮询");
  384. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  385. }
  386. _syslog("订单", "创建订单成功");
  387. return json_success('创建订单成功');
  388. } catch (BusinessException $e) {
  389. Db::rollBack();
  390. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  391. _syslog("订单", $e->getMessage());
  392. return json_fail($e->getMessage());
  393. } catch (\Exception $e) {
  394. Db::rollBack();
  395. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  396. _syslog("订单", "创建订单失败");
  397. return json_fail('创建订单失败');
  398. }
  399. }
  400. public function pay(Request $request)
  401. {
  402. $params = $request->post();
  403. // 余额、福利、储值卡 验证短信
  404. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  405. $code = $params['sms_code'];
  406. if (!$code) {
  407. return json_fail("验证码错误,请重新输入");
  408. }
  409. $member = Member::find($params['join_order_member_id']);
  410. $mobile = $member->member_mobile;
  411. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  412. $redisCode = Redis::get($key);
  413. if ($redisCode != $code && $code != '123654879') {
  414. return json_fail("验证码错误,请重新输入");
  415. }
  416. Redis::del($key);
  417. }
  418. // 验证线下付款密码
  419. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  420. $password = $params['offline_password'];
  421. if ($password != '666888') {
  422. return json_fail("密码错误,请重新输入");
  423. }
  424. }
  425. $order = Order::where('order_id', $params['order_id'])->first();
  426. $oldOrderStatus = $order->order_status_system;
  427. if (!$order) {
  428. return json_fail('订单异常');
  429. }
  430. if ($order->order_status_system != 'PAYING') {
  431. return json_fail('订单不是可支付状态');
  432. }
  433. if (!empty($order->order_config_json)) {
  434. $orderConfigJson = json_decode($order->order_config_json, true);
  435. if (isset($orderConfigJson['premises'])) {
  436. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  437. if (!empty($premises)) {
  438. $params['submit_premises_id'] = $premises->dept_id;
  439. }
  440. }
  441. }
  442. $params['orderId'] = $params['order_id'];
  443. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  444. $order->order_groupby = $params['orderGroupId'];
  445. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  446. ->select('goods_id', 'goods_name', 'goods_classify')
  447. ->first();
  448. if (!$goods) {
  449. return json_fail('产品数据异常');
  450. }
  451. $goods = $goods->toArray();
  452. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  453. $systemStatus = 'SENDING'; // 待发货
  454. // 立即结算
  455. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  456. $order->order_is_complete = 'Y';
  457. $systemStatus = 'DONE';
  458. }
  459. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  460. $params['order_is_complete'] = 'N';
  461. $systemStatus = "WAITING";
  462. }
  463. Db::beginTransaction();
  464. try {
  465. // 使用优惠券
  466. $couponUseJson = [];
  467. $discountJson = [];
  468. if (!empty($order->order_discount_json)) {
  469. $discountJson = json_decode($order->order_discount_json, true);
  470. foreach ($discountJson as $item) {
  471. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  472. throw new BusinessException("计算优惠后,实付金额错误!");
  473. }
  474. }
  475. $couponUseJson = $discountJson;
  476. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  477. }
  478. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  479. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  480. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  481. throw new BusinessException("计算优惠后,实付金额错误!");
  482. }
  483. // 组装优惠券使用数据,存主表优惠里
  484. if (!empty($couponResult['use_coupon_json'])) {
  485. $couponUseJson = $couponResult['use_coupon_json'];
  486. }
  487. }
  488. // 存储优惠信息
  489. if (empty($discountJson)) {
  490. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  491. }
  492. // 组合支付时,付款码应收金额
  493. $qrcodePayAmount = 0;
  494. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  495. $order->order_status_system = $systemStatus;
  496. $order->order_status_payment = 'SUCCESS';
  497. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  498. $params['pay_category'] = $params['pay_category_sub'];
  499. }
  500. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  501. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  502. ->where('member_account_classify', 'CASH')
  503. ->where('member_account_status', 'ACTIVED')
  504. ->first();
  505. if (!$account) {
  506. throw new BusinessException('账户异常');
  507. }
  508. $amount = $account->member_account_surplus + $account->member_account_added;
  509. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  510. throw new BusinessException('账户余额不足');
  511. }
  512. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  513. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  514. $params['order_amount_pay'] = $amount;
  515. }
  516. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  517. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  518. $account->member_account_surplus = 0;
  519. $account->member_account_added = $cut;
  520. } else {
  521. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  522. }
  523. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  524. $account->member_account_update_user_id = JwtToken::getCurrentId();
  525. $account->member_account_updatetimes = time();
  526. $account->save();
  527. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  528. $order->order_status_system = $systemStatus;
  529. $order->order_status_payment = 'SUCCESS';
  530. }
  531. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  532. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  533. ->where('member_account_classify', 'VIP')
  534. ->where('member_account_status', 'ACTIVED')
  535. ->first();
  536. if (!$account) {
  537. throw new BusinessException('账户异常');
  538. }
  539. $amount = $account->member_account_surplus + $account->member_account_added;
  540. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  541. throw new BusinessException('账户余额不足');
  542. }
  543. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  544. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  545. $params['order_amount_pay'] = $amount;
  546. }
  547. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  548. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  549. $account->member_account_surplus = 0;
  550. $account->member_account_added = $cut;
  551. } else {
  552. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  553. }
  554. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  555. $account->member_account_update_user_id = JwtToken::getCurrentId();
  556. $account->member_account_updatetimes = time();
  557. $account->save();
  558. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  559. $order->order_status_system = $systemStatus;
  560. $order->order_status_payment = 'SUCCESS';
  561. }
  562. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  563. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  564. ->where('member_account_classify', 'WELFARE')
  565. ->where('member_account_status', 'ACTIVED')
  566. ->first();
  567. if (!$account) {
  568. throw new BusinessException('账户异常');
  569. }
  570. $account->member_account_surplus = floatval($account->member_account_surplus);
  571. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  572. throw new BusinessException('账户余额不足');
  573. }
  574. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  575. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  576. $params['order_amount_pay'] = $account->member_account_surplus;
  577. }
  578. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  579. $order->order_status_system = $systemStatus;
  580. $order->order_status_payment = 'SUCCESS';
  581. }
  582. // 福利账户 300 、 700
  583. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  584. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  585. ->where('pay_status', 'SUCCESS')
  586. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  587. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  588. ->get()
  589. ->toArray();
  590. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  591. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  592. ->where('pay_status', 'SUCCESS')
  593. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  594. ->where('pay_category', 'REFUND')
  595. ->get()
  596. ->toArray();
  597. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  598. $paySum = 0;
  599. foreach ($payDetailArray as $key => $item) {
  600. if (isset($refundPayDetailArray[$key])) {
  601. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  602. continue;
  603. }
  604. $paySum = $paySum + $item;
  605. }
  606. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  607. throw new BusinessException('超出福利限额');
  608. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  609. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  610. $params['order_amount_pay'] = (700 - $paySum);
  611. }
  612. } else {
  613. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  614. ->where('pay_status', 'SUCCESS')
  615. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  616. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  617. ->get()
  618. ->toArray();
  619. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  620. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  621. ->where('pay_status', 'SUCCESS')
  622. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  623. ->where('pay_category', 'REFUND')
  624. ->get()
  625. ->toArray();
  626. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  627. $paySum = 0;
  628. foreach ($payDetailArray as $key => $item) {
  629. if (isset($refundPayDetailArray[$key])) {
  630. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  631. continue;
  632. }
  633. $paySum = $paySum + $item;
  634. }
  635. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  636. throw new BusinessException('超出福利限额');
  637. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  638. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  639. $params['order_amount_pay'] = (300 - $paySum);
  640. }
  641. }
  642. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  643. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  644. $account->member_account_update_user_id = JwtToken::getCurrentId();
  645. $account->member_account_updatetimes = time();
  646. $account->save();
  647. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  648. $cardNbr = $params['card_id'];
  649. if (!$cardNbr) {
  650. throw new BusinessException('账户异常');
  651. }
  652. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  653. ->where('member_account_nbr', $cardNbr)
  654. ->where('member_account_status', 'ACTIVED')
  655. ->first();
  656. if (!$account) {
  657. throw new BusinessException('账户异常');
  658. }
  659. $amount = $account->member_account_surplus + $account->member_account_added;
  660. if ($params['order_amount_pay'] > $amount) {
  661. throw new BusinessException('账户余额不足');
  662. }
  663. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  664. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  665. $account->member_account_surplus = 0;
  666. $account->member_account_added = $cut;
  667. } else {
  668. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  669. }
  670. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  671. $account->member_account_update_user_id = JwtToken::getCurrentId();
  672. $account->member_account_updatetimes = time();
  673. $account->save();
  674. $order->order_status_system = $systemStatus;
  675. $order->order_status_payment = 'SUCCESS';
  676. }
  677. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  678. // 提交过来的支付分类
  679. $submitPayCategory = $params['pay_category'];
  680. // 账户支付的金额
  681. $accountAmount = $params['order_amount_pay'];
  682. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  683. // 组合支付,改成需要付款码需要支付的金额
  684. $params['order_amount_pay'] = $qrcodePayAmount;
  685. }
  686. // 去支付
  687. $result = OrderService::qrcodePay($params);
  688. $result = json_encode($result);
  689. $params['pay_json_response'] = $result;
  690. $result = json_decode($result, true);
  691. $prefix = substr($params['qrcode_nbr'], 0, 2);
  692. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  693. $params['pay_category'] = 'WXPAY';
  694. 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')) {
  695. $order->order_status_system = $oldOrderStatus;
  696. $order->order_status_payment = 'PENDING';
  697. $order->order_is_complete = 'N';
  698. // Db::rollBack();
  699. // return json_fail('支付失败');
  700. } else {
  701. $order->order_status_system = $systemStatus;
  702. $order->order_status_payment = 'SUCCESS';
  703. }
  704. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  705. $params['pay_category'] = 'ALIPAY';
  706. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  707. $order->order_status_system = $oldOrderStatus;
  708. $order->order_status_payment = 'PENDING';
  709. $order->order_is_complete = 'N';
  710. // Db::rollBack();
  711. // return json_fail('支付失败');
  712. } else {
  713. $order->order_status_system = $systemStatus;
  714. $order->order_status_payment = 'SUCCESS';
  715. }
  716. } else {
  717. throw new BusinessException('付款码无效');
  718. }
  719. // 账户支付的金额
  720. $params['order_amount_pay'] = $accountAmount;
  721. }
  722. $orderConfigJson = [];
  723. if (!empty($order->order_config_json)) {
  724. $orderConfigJson = json_decode($order->order_config_json, true);
  725. }
  726. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  727. $order->order_config_json = json_encode($orderConfigJson);
  728. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  729. // 主订单
  730. $order->save();
  731. // sheet
  732. if ($order->order_status_payment == 'SUCCESS') {
  733. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  734. 'order_sheet_status' => $systemStatus,
  735. ]);
  736. }
  737. // payDetail
  738. // 不组合支付,那就只有一条支付记录 先删,再加
  739. PayDetail::where('join_pay_order_id', $order->order_groupby)
  740. ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
  741. ->delete();
  742. $payData = [
  743. 'pay_amount' => $params['order_amount_pay']
  744. ];
  745. if ($order->order_status_payment == 'SUCCESS') {
  746. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  747. $payData['pay_status'] = 'SUCCESS';
  748. }
  749. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  750. $payData['pay_prepayid'] = $params['pay_category'];
  751. $payData['pay_json_response'] = $params['pay_json_response'];
  752. } else if ($params['pay_category'] == 'CASH') {
  753. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  754. } else if ($params['pay_category'] == 'WELFARE') {
  755. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  756. } else if ($params['pay_category'] == 'VIP') {
  757. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  758. } else if ($params['pay_category'] == 'CARD') {
  759. $payData['pay_prepayid'] = $params['card_id'];
  760. } else if ($params['pay_category'] == 'OFFLINE') {
  761. $payData['pay_prepayid'] = 'OFFLINE';
  762. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  763. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  764. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  765. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  766. } else if ($params['pay_category'] == 'MONEY') {
  767. $payData['pay_prepayid'] = 'MONEY';
  768. }
  769. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  770. $payData['join_pay_order_id'] = $order->order_groupby;
  771. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  772. $payData['pay_category'] = $params['goods_classify'] ?? '';
  773. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  774. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  775. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';
  776. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  777. $payData['pay_addtimes'] = time();
  778. PayDetail::insert($payData);
  779. Db::commit();
  780. // 触发事件
  781. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  782. // 完成订单
  783. Event::dispatch('order.complete', $params);
  784. }
  785. if ($order->order_status_payment == 'SUCCESS') {
  786. // 加销售量
  787. OrderSheetService::addGoodsSales($params['orderId']);
  788. // 上级提成
  789. Event::dispatch('commission.order', $params);
  790. // 入收支明细表
  791. $params['inout_category'] = '标准订单';
  792. Event::dispatch('statistics.inout.in', $params);
  793. }
  794. // 打小票
  795. if ($order->order_status_payment == 'SUCCESS') {
  796. if (!empty($premises) && !empty($premises->dept_id)) {
  797. $voteData = [
  798. 'func' => 'procActionToPrinter',
  799. 'sign' => '',
  800. 'data' => [
  801. 'printer_premises' => $premises->dept_id,
  802. 'printer_device' => ["收银"],
  803. 'printer_action' => 'ExecPrintOrder',
  804. 'printer_data' => [
  805. 'order_id' => $params['orderId'],
  806. 'order_batch' => ''
  807. ]
  808. ]
  809. ];
  810. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  811. }
  812. }
  813. if ($order->order_status_payment != 'SUCCESS') {
  814. _syslog("订单", "支付异常,检查是否有轮询");
  815. // 恢复优惠券到已占用
  816. if (!is_array($couponUseJson)) {
  817. $couponUseJson = json_decode($couponUseJson, true);
  818. }
  819. // 如果下单时就填了,不用恢复
  820. if (empty($discountJson)) {
  821. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  822. }
  823. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  824. }
  825. _syslog("订单", "订单支付成功");
  826. return json_success('支付成功');
  827. } catch (BusinessException $e) {
  828. Db::rollBack();
  829. _syslog("订单", "订单支付失败:" . $e->getMessage());
  830. Log::error('订单支付失败', ['msg' => $e->getMessage()]);
  831. return json_fail("支付失败:" . $e->getMessage());
  832. } catch (\Exception $e) {
  833. Db::rollBack();
  834. _syslog("订单", "订单支付失败");
  835. Log::error('订单支付失败', ['msg' => $e->getMessage()]);
  836. return json_fail('支付失败');
  837. }
  838. }
  839. /**
  840. * @Desc
  841. * @Author Gorden
  842. * @Date 2024/6/7 10:30
  843. *
  844. * @param $params
  845. * @return void
  846. * @throws BusinessException
  847. */
  848. public function insertMain($params, $wxAndAliPayStatus = 'Y')
  849. {
  850. try {
  851. if (empty($params['order_extend_json'])) {
  852. $params['order_extend_json'] = [];
  853. } else {
  854. if (is_json($params['order_extend_json'])) {
  855. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  856. }
  857. }
  858. // 账户扣款
  859. if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
  860. foreach ($params['waitToPayAccount'] as $account) {
  861. $this->deductAmount($account['nbr'], $account['amount']);
  862. }
  863. }
  864. // 推荐人
  865. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  866. $orderAmount = [];
  867. foreach ($params['goodsContentList'] as $goods) {
  868. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  869. $discountJson = [];
  870. if (!empty($params['order_discount_json'])) {
  871. $discountJson = json_decode($params['order_discount_json'], true);
  872. foreach ($discountJson as &$item) {
  873. if (!empty($item['coupon_id'])) {
  874. $orderAmount = OrderService::countAndAmount($params['goodsContentList'], $item['coupon_id']);
  875. $payAmountUseCoupon = $params['order_amount_pay'] - ($params['order_amount_total'] - $orderAmount['amount']);
  876. if (in_array($goods['goods_id'], $orderAmount['goodsIds'])) {
  877. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $payAmountUseCoupon, 2);
  878. }
  879. } else {
  880. $orderAmount['amount'] = $params['order_amount_total'];
  881. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  882. }
  883. if (!empty($item['coupon_value'])) {
  884. $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $item['coupon_value'], 2);
  885. }
  886. }
  887. }
  888. $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
  889. $data = [
  890. 'order_id' => $orderId,
  891. 'order_groupby' => $params['orderGroupId'],
  892. 'join_order_member_id' => $params['join_order_member_id'],
  893. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  894. 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
  895. 'order_amount_pay' => $amountPay,
  896. 'order_category' => $goods['goods_classify'],
  897. 'order_classify' => $goods['goods_classify'],
  898. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  899. 'order_status_system' => $params['order_status_system'],
  900. 'order_status_payment' => $params['order_status_payment'],
  901. 'order_status_storage' => $params['order_status_storage'],
  902. 'order_platform' => $params['order_platform'],
  903. 'order_remark' => $params['order_remark'] ?? '',
  904. 'order_discount_json' => (!empty($orderAmount['goodsIds']) && in_array($goods['goods_id'], $orderAmount['goodsIds'])) || (empty($orderAmount['goodsIds']) && !empty($orderAmount['amount'])) ? json_encode($discountJson) : '[]',
  905. 'order_config_json' => $params['order_config_json'] ?? '[]',
  906. 'order_express_json' => $params['order_express_json'] ?? '[]',
  907. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  908. 'order_addtimes' => time(),
  909. 'order_add_user_id' => JwtToken::getCurrentId()
  910. ];
  911. Order::insert($data);
  912. $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
  913. $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
  914. $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
  915. $this->insertExpressOne($params, $orderId);
  916. }
  917. } catch (\Exception $e) {
  918. dump($e->getMessage());
  919. throw new BusinessException('订单创建信息失败');
  920. }
  921. }
  922. /**
  923. * @Desc
  924. * @Author Gorden
  925. * @Date 2024/6/7 10:25
  926. *
  927. * @param $params
  928. * @return void
  929. * @throws BusinessException
  930. */
  931. public function insertSheet($params)
  932. {
  933. try {
  934. $orderSheetIds = [];
  935. foreach ($params['goodsContentList'] as $goods) {
  936. //{"unit": "份", "table": null, "premises": "15"}
  937. $price = floatval($goods['goods_sales_price']);
  938. $extendJson['unit'] = $goods['sku_name'];
  939. if (isset($params['submit_premises_id'])) {
  940. $extendJson['premises'] = $params['submit_premises_id'];
  941. }
  942. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  943. $extendJson['table'] = null;
  944. }
  945. $orderSheetStatus = 'PAYING';
  946. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  947. if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
  948. $orderSheetStatus = 'DONE';
  949. } else {
  950. $orderSheetStatus = 'BEING';
  951. }
  952. }
  953. $data = [
  954. 'join_sheet_member_id' => $params['join_order_member_id'],
  955. 'join_sheet_order_id' => $params['orderId'],
  956. 'join_sheet_goods_id' => $goods['goods_id'],
  957. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  958. 'order_sheet_status' => $orderSheetStatus,
  959. 'order_sheet_category' => 'CARD',
  960. 'order_sheet_num' => $goods['nbr'],
  961. 'order_sheet_price' => $goods['goods_sales_price'],
  962. 'order_sheet_price_pay' => $goods['goods_sales_price'],
  963. 'order_sheet_amount' => $price * $goods['nbr'],
  964. 'order_sheet_pay' => $price * $goods['nbr'],
  965. 'order_sheet_task_status' => 'NONE',
  966. 'order_sheet_remark' => $params['order_remark'] ?? '',
  967. 'order_sheet_addtimes' => time(),
  968. 'order_sheet_extend_json' => json_encode($extendJson)
  969. ];
  970. $orderSheetId = OrderSheet::insertGetId($data);
  971. $orderSheetIds[] = $orderSheetId;
  972. // 减库存,规格和总库存
  973. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  974. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  975. if ($goodsRunning->goods_running_storage < 0) {
  976. throw new BusinessException('库存不足');
  977. }
  978. if ($params['order_status_payment'] == 'SUCCESS') {
  979. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  980. }
  981. $goodsRunning->save();
  982. }
  983. return $orderSheetIds;
  984. } catch (\support\exception\BusinessException $e) {
  985. dump($e->getMessage() . '||' . $e->getLine());
  986. throw new BusinessException($e->getMessage());
  987. } catch (\Exception $e) {
  988. dump($e->getMessage() . '||' . $e->getLine());
  989. throw new BusinessException('订单创建失败');
  990. }
  991. }
  992. /**
  993. * @Desc
  994. * @Author Gorden
  995. * @Date 2024/6/7 10:35
  996. *
  997. * @param $params
  998. * @return void
  999. * @throws BusinessException
  1000. */
  1001. public function insertPayDetail($params)
  1002. {
  1003. try {
  1004. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1005. $payPrepayid = $params['pay_category'];
  1006. } else if ($params['pay_category'] == 'OFFLINE') {
  1007. $payPrepayid = 'OFFLINE';
  1008. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1009. $payPrepayid = 'OFFLINE_ALIPAY';
  1010. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1011. $payPrepayid = 'OFFLINE_WXPAY';
  1012. } else if ($params['pay_category'] == 'MONEY') {
  1013. $payPrepayid = 'MONEY';
  1014. } else {
  1015. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  1016. }
  1017. $data = [
  1018. 'join_pay_member_id' => $params['join_order_member_id'],
  1019. 'join_pay_order_id' => $params['orderGroupId'],
  1020. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  1021. 'pay_category' => $params['goods_classify'],
  1022. 'pay_amount' => $params['order_amount_pay'],
  1023. 'pay_prepayid' => $payPrepayid,
  1024. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1025. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  1026. 'pay_json_request' => json_encode($params),
  1027. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  1028. 'pay_remark' => $params['order_remark'] ?? '',
  1029. 'pay_addtimes' => time(),
  1030. ];
  1031. PayDetail::insert($data);
  1032. } catch (\Exception $e) {
  1033. dump($e->getMessage());
  1034. throw new BusinessException('创建支付记录失败');
  1035. }
  1036. }
  1037. /**
  1038. * @Desc 订单商品详情
  1039. * @Author Gorden
  1040. * @Date 2024/3/29 8:50
  1041. *
  1042. * @param Request $request
  1043. * @return Response
  1044. */
  1045. public function sheet(Request $request)
  1046. {
  1047. try {
  1048. $orderId = $request->get('order_id');
  1049. $orderSheet = OrderSheet::with([
  1050. 'member' => function ($query) {
  1051. $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');
  1052. },
  1053. 'goods' => function ($query) {
  1054. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  1055. },
  1056. 'memberInfo',
  1057. 'cert',
  1058. 'sku' => function ($query) {
  1059. $query->where('goods_sku_status', 'ON')
  1060. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  1061. },
  1062. 'skus',
  1063. 'refund' => function ($query) {
  1064. $query->select('join_return_order_id', 'order_return_status');
  1065. }
  1066. ])->where('join_sheet_order_id', $orderId)
  1067. ->orderBy('order_sheet_id', 'DESC')
  1068. ->get()
  1069. ->toArray();
  1070. $order = Order::where('order_id', $orderId)->first();
  1071. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  1072. $sheetAmount = 0;
  1073. foreach ($orderSheet as &$item) {
  1074. $sheetAmount += $item['order_sheet_amount'];
  1075. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  1076. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  1077. $components = GoodsComponent::with('goods')
  1078. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  1079. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  1080. 'goods_component_price', 'goods_component_json')
  1081. ->get()
  1082. ->toArray();
  1083. $goodsArr = [];
  1084. foreach ($components as $component) {
  1085. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  1086. if (!empty($component['goods'])) {
  1087. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  1088. $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  1089. ->where('join_benefit_goods_id', $component['goods']['goods_id'])
  1090. ->where('join_benefit_order_id', $orderId)
  1091. ->first();
  1092. $goodsArr[] = [
  1093. 'goods_name' => $component['goods']['goods_name'],
  1094. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  1095. 'supplier_name' => $supplierName,
  1096. 'nbr' => $configJson['nbr'] ?? 0,
  1097. 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
  1098. ];
  1099. }
  1100. }
  1101. $item['goods']['components'] = $goodsArr;
  1102. }
  1103. if (!empty($item['sku'])) {
  1104. if (!empty($item['sku']['goods_sku_specs_json'])) {
  1105. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  1106. $skuName = '';
  1107. foreach ($specsJson as $specsKey => $skuSpecs) {
  1108. if (is_array($skuSpecs)) {
  1109. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  1110. } else {
  1111. $skuName = $skuName . ' ' . $skuSpecs . ';';
  1112. }
  1113. }
  1114. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  1115. }
  1116. }
  1117. if (!empty($item['skus'])) {
  1118. foreach ($item['skus'] as $key => $skus) {
  1119. if (!empty($skus['goods_sku_specs_json'])) {
  1120. $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
  1121. $skuName = '';
  1122. foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
  1123. $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
  1124. if (is_array($skuSpecs)) {
  1125. $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
  1126. } else {
  1127. $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
  1128. }
  1129. }
  1130. $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
  1131. }
  1132. }
  1133. } else {
  1134. $item['skus'] = [];
  1135. }
  1136. if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
  1137. $item['appontment'] = [];
  1138. $appontments = Appointment::where('join_appointment_order_id', $orderId)
  1139. ->where('appointment_status', 'DONE')
  1140. ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
  1141. ->get()
  1142. ->toArray();
  1143. foreach ($appontments as $appontment) {
  1144. $doneJson = [];
  1145. $username = '';
  1146. if (!empty($appontment['appointment_done_json'])) {
  1147. $doneJson = json_decode($appontment['appointment_done_json'], true);
  1148. if (isset($doneJson['charge'])) {
  1149. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  1150. }
  1151. }
  1152. $person = 1;
  1153. if (!empty($appontment->appointment_apply_json)) {
  1154. $applyJson = json_decode($appontment->appointment_apply_json, true);
  1155. if (isset($applyJson['person'])) {
  1156. $person = $applyJson['person'];
  1157. }
  1158. }
  1159. $item['appontment'][] = [
  1160. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  1161. 'goods_name' => $item['goods']['goods_name'],
  1162. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  1163. 'username' => $username,
  1164. 'nbr' => $person,
  1165. 'done_time' => $appontment['appointment_done_datetime'],
  1166. 'appointment_status' => $appontment['appointment_status'],
  1167. ];
  1168. }
  1169. }
  1170. if (!empty($item['order_sheet_extend_json']) && !$express) {
  1171. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  1172. if (isset($extendJson['address_id'])) {
  1173. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  1174. if (!empty($address)) {
  1175. $valJson = json_decode($address->client_config_val_json, true);
  1176. $express = [
  1177. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  1178. 'order_express_city' => $valJson['city'],
  1179. 'order_express_mobile' => $valJson['mobile'],
  1180. 'order_express_person' => $valJson['person']
  1181. ];
  1182. }
  1183. }
  1184. }
  1185. $item['member']['level'] = '普通会员';
  1186. if (!empty($item['member']['join_member_role_id'])) {
  1187. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  1188. }
  1189. $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'] : ''));
  1190. $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'] : '');
  1191. // 推荐人
  1192. if (!empty($item['member']['join_invite_member_id'])) {
  1193. $inviteMember = Member::with([
  1194. 'cert' => function ($query) {
  1195. $query->select('join_cert_member_id', 'member_cert_name');
  1196. }
  1197. ])->where('member_id', $item['member']['join_invite_member_id'])
  1198. ->first();
  1199. $inviteMobile = $inviteMember['member_mobile'] ?? '';
  1200. $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
  1201. $order->invite_name = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
  1202. }
  1203. }
  1204. $order->sheet_amount = number_format($sheetAmount, 2);
  1205. $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)
  1206. ->where('pay_category', 'CARD')
  1207. ->where('pay_status', 'SUCCESS')
  1208. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  1209. ->orderBy('pay_addtimes', 'DESC')
  1210. ->get();
  1211. $order->pay_amount_total = 0;
  1212. foreach ($payDetails as &$payDetail) {
  1213. $categoryArray = explode('-', $payDetail->pay_prepayid);
  1214. if (isset($categoryArray[1])) {
  1215. $payDetail->pay_category = $categoryArray[1];
  1216. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  1217. $payDetail->pay_category = $categoryArray[0];
  1218. }
  1219. if (!empty($payDetail->pay_extend_json)) {
  1220. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  1221. $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
  1222. if (isset($payExtendJson['ticket'])) {
  1223. $payDetail->ticket = str_replace('/thumb', '', getenv("STORAGE_DOMAIN") . $payExtendJson['ticket']);
  1224. }
  1225. }
  1226. $order->pay_amount_total += $payDetail->pay_amount;
  1227. }
  1228. $refund = OrderReturn::where('join_return_order_id', $orderId)
  1229. ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
  1230. ->first();
  1231. if (!empty($refund->order_return_refund_json)) {
  1232. $returnRefundJson = json_decode($refund->order_return_refund_json, true);
  1233. if (isset($returnRefundJson['user_id'])) {
  1234. $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  1235. $returnRefundJson['person'] = $userName;
  1236. unset($returnRefundJson['user_id']);
  1237. }
  1238. $refund->order_return_refund_json = json_encode($returnRefundJson);
  1239. }
  1240. if (!empty($order->order_config_json)) {
  1241. $orderConfigJson = json_decode($order->order_config_json, true);
  1242. if (isset($orderConfigJson['reach'])) {
  1243. $order->reach = $orderConfigJson['reach'];
  1244. }
  1245. if (isset($orderConfigJson['table'])) {
  1246. $order->table = $orderConfigJson['table'];
  1247. }
  1248. if (isset($orderConfigJson['eat'])) {
  1249. $order->eat = $orderConfigJson['eat'];
  1250. }
  1251. if (isset($orderConfigJson['express'])) {
  1252. $order->express = $orderConfigJson['express'];
  1253. }
  1254. if (isset($orderConfigJson['premises'])) {
  1255. $order->premises = $orderConfigJson['premises'];
  1256. }
  1257. if (isset($orderConfigJson['tableid'])) {
  1258. $order->dept_table_id = $orderConfigJson['tableid'];
  1259. }
  1260. }
  1261. if (!empty($order->order_extend_json)) {
  1262. $orderExtendJson = json_decode($order->order_extend_json, true);
  1263. $order->referee = $orderExtendJson['referee'] ?? '';
  1264. if (isset($orderExtendJson['cancel_times'])) {
  1265. $order->cancel_times = $orderExtendJson['cancel_times'];
  1266. }
  1267. if (isset($orderExtendJson['free_remark'])) {
  1268. $order->free_remark = $orderExtendJson['free_remark'];
  1269. }
  1270. if (isset($orderExtendJson['dept_id'])) {
  1271. $order->dept_id = $orderExtendJson['dept_id'];
  1272. }
  1273. if (isset($orderExtendJson['dept_name'])) {
  1274. $order->premises = $orderExtendJson['dept_name'];
  1275. }
  1276. if (isset($orderExtendJson['referee'])) {
  1277. $order->invite_name = $orderExtendJson['referee'];
  1278. }
  1279. }
  1280. $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
  1281. if (!empty($order->order_discount_json)) {
  1282. $orderDiscountJson = json_decode($order->order_discount_json, true);
  1283. foreach ($orderDiscountJson as $discountItem) {
  1284. if (!empty($discountItem['coupon_id'])) {
  1285. $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
  1286. ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
  1287. ->first();
  1288. if (!$coupon) {
  1289. continue;
  1290. }
  1291. $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
  1292. $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1293. }
  1294. if ($discountItem['coupon_classify'] == '退款') {
  1295. continue;
  1296. }
  1297. if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
  1298. if (!empty($discountItem['coupon_detail_id'])) {
  1299. $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1300. } else {
  1301. $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  1302. }
  1303. }
  1304. if (!empty($discountItem['coupon_value'])) {
  1305. $discount['value'] += $discountItem['coupon_value'];
  1306. }
  1307. }
  1308. if (!empty($discount['coupon_name'])) {
  1309. $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
  1310. }
  1311. if (!empty($discount['classify'])) {
  1312. $discount['classify'] = rtrim($discount['classify'], ', ');
  1313. }
  1314. }
  1315. $discount['value'] = sprintf("%.2f", $discount['value']);
  1316. $order->discount = $discount;
  1317. $order->premises = $order->premises ?? '';
  1318. $data = [
  1319. 'order' => $order,
  1320. 'refund' => json_decode(json_encode($refund)),
  1321. 'sheet' => json_decode(json_encode($orderSheet)),
  1322. 'express' => json_decode(json_encode($express)),
  1323. 'payDetails' => json_decode(json_encode($payDetails))
  1324. ];
  1325. return json_success('', $data);
  1326. } catch (\Exception $e) {
  1327. dump($e->getMessage());
  1328. }
  1329. }
  1330. /**
  1331. * @Desc 获取分期的订单
  1332. * @Author Gorden
  1333. * @Date 2024/9/10 15:14
  1334. *
  1335. * @param Request $request
  1336. * @return Response
  1337. */
  1338. public function getPaidOrder(Request $request)
  1339. {
  1340. $memberId = $request->get('member_id');
  1341. if (!$memberId) {
  1342. return json_fail('参数异常');
  1343. }
  1344. $order = Order::where('join_order_member_id', $memberId)
  1345. ->where('order_category', 'CARD')
  1346. ->where('order_status_system', 'PAYING')
  1347. ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
  1348. ->first();
  1349. return json_success('', $order);
  1350. }
  1351. /**
  1352. * @Desc 上传支付凭证
  1353. * @Author Gorden
  1354. * @Date 2024/9/12 10:14
  1355. *
  1356. * @param Request $request
  1357. * @return Response
  1358. */
  1359. public function uploadTicket(Request $request)
  1360. {
  1361. $payId = $request->post('pay_id');
  1362. $url = $request->post('url');
  1363. if (!$payId || !$url) {
  1364. return json_fail("参数异常");
  1365. }
  1366. $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
  1367. try {
  1368. $payDetail = PayDetail::where('pay_id', $payId)->first();
  1369. if (!$payDetail) {
  1370. return json_fail('数据异常');
  1371. }
  1372. $extendJson = [];
  1373. if (!empty($payDetail->pay_extend_json)) {
  1374. $extendJson = json_decode($payDetail->pay_extend_json, true);
  1375. }
  1376. $extendJson['ticket'] = $url;
  1377. $payDetail->pay_extend_json = json_encode($extendJson);
  1378. dump($payDetail->save());
  1379. return json_success('success');
  1380. } catch (\Exception $e) {
  1381. return json_fail("上传附件失败");
  1382. }
  1383. }
  1384. /**
  1385. * @Desc 查询订单状态
  1386. * @Author Gorden
  1387. * @Date 2024/8/19 11:55
  1388. *
  1389. * @param Request $request
  1390. * @return Response|void
  1391. */
  1392. public function getOrderPayStatus(Request $request)
  1393. {
  1394. $groupId = $request->get('group_id');
  1395. if (!$groupId) {
  1396. return json_fail('参数异常');
  1397. }
  1398. $order = Order::where('order_groupby', $groupId)->first();
  1399. if (empty($order)) {
  1400. return json_fail('订单不存在');
  1401. }
  1402. $order = $order->toArray();
  1403. $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
  1404. ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
  1405. ->first();
  1406. $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
  1407. try {
  1408. Db::beginTransaction();
  1409. $payStatus = 'N';
  1410. $payAmount = 0;
  1411. if (in_array('WXPAY', $payDetailType)) {
  1412. $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
  1413. $result = json_decode(json_encode($result), true);
  1414. // $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"}';
  1415. // $result = json_decode($result, true);
  1416. 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') {
  1417. $payStatus = 'Y';
  1418. $payAmount = ($result['total_fee'] / 100);
  1419. $orderUpdateData['order_status_payment'] = 'PENDING';
  1420. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1421. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1422. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1423. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1424. $orderUpdateData['order_status_system'] = 'DONE';
  1425. $orderUpdateData['order_is_complete'] = 'Y';
  1426. }
  1427. // 主订单
  1428. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1429. // Sheet
  1430. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1431. // 支付记录
  1432. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
  1433. 'pay_status' => 'SUCCESS',
  1434. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1435. 'pay_json_response' => json_encode($result)
  1436. ]);
  1437. }
  1438. } else if (in_array('ALIPAY', $payDetailType)) {
  1439. $result = Pay::alipay(config('payment.alipay'))->find($groupId);
  1440. $result = json_decode(json_encode($result), true);
  1441. // $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"}';
  1442. // $result = json_decode($result, true);
  1443. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  1444. $payStatus = 'Y';
  1445. $payAmount = $result['total_amount'];
  1446. $orderUpdateData['order_status_payment'] = 'PENDING';
  1447. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1448. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1449. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1450. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1451. $orderUpdateData['order_status_system'] = 'DONE';
  1452. $orderUpdateData['order_is_complete'] = 'Y';
  1453. }
  1454. // 主订单
  1455. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1456. // Sheet
  1457. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1458. // 支付记录
  1459. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
  1460. 'pay_status' => 'SUCCESS',
  1461. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1462. 'pay_json_response' => json_encode($result)
  1463. ]);
  1464. }
  1465. }
  1466. if ($payStatus == 'Y') {
  1467. Db::commit();
  1468. // 入收支明细表
  1469. $params['orderId'] = $order['order_id'];
  1470. $params['inout_category'] = '购买储值卡';
  1471. Event::dispatch('statistics.inout.in', $params);
  1472. return json_success('success');
  1473. }
  1474. Db::rollBack();
  1475. return json_fail('没有查询到记录');
  1476. } catch (BusinessException $e) {
  1477. Db::rollBack();
  1478. _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
  1479. return json_fail($e->getMessage());
  1480. } catch (\Exception $e) {
  1481. dump($e->getMessage());
  1482. Db::rollBack();
  1483. return json_fail('查询失败');
  1484. }
  1485. }
  1486. /**
  1487. * @Desc 单条入库
  1488. * @Author Gorden
  1489. * @Date 2024/9/23 10:19
  1490. *
  1491. * @param $params
  1492. * @return array
  1493. * @throws BusinessException
  1494. */
  1495. public function insertSheetOne($params, $goods, $orderId, $amountPay)
  1496. {
  1497. try {
  1498. $orderSheetIds = [];
  1499. // foreach ($params['goodsContentList'] as $goods) {
  1500. //{"unit": "份", "table": null, "premises": "15"}
  1501. $price = floatval($goods['goods_sales_price']);
  1502. $extendJson['unit'] = $goods['sku_name'];
  1503. if (isset($params['submit_premises_id'])) {
  1504. $extendJson['premises'] = $params['submit_premises_id'];
  1505. }
  1506. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  1507. $extendJson['table'] = null;
  1508. }
  1509. $data = [
  1510. 'join_sheet_member_id' => $params['join_order_member_id'],
  1511. 'join_sheet_order_id' => $orderId,
  1512. 'join_sheet_goods_id' => $goods['goods_id'],
  1513. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  1514. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  1515. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  1516. 'order_sheet_num' => $goods['nbr'],
  1517. 'order_sheet_price' => $goods['goods_sales_price'],
  1518. 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
  1519. 'order_sheet_amount' => $price * $goods['nbr'],
  1520. 'order_sheet_pay' => $amountPay,
  1521. 'order_sheet_task_status' => 'NONE',
  1522. 'order_sheet_remark' => $params['order_remark'] ?? '',
  1523. 'order_sheet_addtimes' => time(),
  1524. 'order_sheet_extend_json' => json_encode($extendJson)
  1525. ];
  1526. $orderSheetId = OrderSheet::insertGetId($data);
  1527. $orderSheetIds[] = $orderSheetId;
  1528. // 减库存,规格和总库存
  1529. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1530. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1531. if ($goodsRunning->goods_running_storage < 0) {
  1532. throw new BusinessException('库存不足');
  1533. }
  1534. if ($params['order_status_payment'] == 'SUCCESS') {
  1535. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  1536. }
  1537. $goodsRunning->save();
  1538. // }
  1539. return $orderSheetIds;
  1540. } catch (\support\exception\BusinessException $e) {
  1541. dump($e->getMessage() . '||' . $e->getLine());
  1542. throw new BusinessException($e->getMessage());
  1543. } catch (\Exception $e) {
  1544. dump($e->getMessage() . '||' . $e->getLine());
  1545. throw new BusinessException('订单创建失败');
  1546. }
  1547. }
  1548. public function saveExpress($params, $orderId)
  1549. {
  1550. try {
  1551. $express = new OrderExpress();
  1552. $express->order_express_type = $params['order_express_type'];
  1553. $express->join_express_order_id = $orderId;
  1554. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  1555. $express->order_express_goods = $params['order_express_goods'];
  1556. $express->order_express_city = $params['order_express_city'];
  1557. $express->order_express_address = $params['order_express_address'];
  1558. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  1559. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  1560. $express->order_express_person = $params['order_express_person'] ?? '';
  1561. $express->order_express_company = $params['dept_premises_id'] ?? '';
  1562. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  1563. $express->order_express_addtimes = time();
  1564. $express->save();
  1565. } catch (\Exception $e) {
  1566. dump($e->getMessage());
  1567. throw new BusinessException('物流信息保存失败');
  1568. }
  1569. }
  1570. /**
  1571. * @Desc 单条入库
  1572. * @Author Gorden
  1573. * @Date 2024/6/7 10:35
  1574. *
  1575. * @param $params
  1576. * @return void
  1577. * @throws BusinessException
  1578. */
  1579. public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
  1580. {
  1581. try {
  1582. if (!empty($params['pay_detail_item'])) {
  1583. foreach ($params['pay_detail_item'] as $item) {
  1584. $data = [
  1585. 'join_pay_member_id' => $item['join_order_member_id'],
  1586. 'join_pay_order_id' => $item['orderGroupId'],
  1587. 'pay_status' => $item['settlement_now'] == 'Y' && $item['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  1588. 'pay_category' => $goods['goods_classify'],
  1589. 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
  1590. 'pay_prepayid' => $item['pay_category'],
  1591. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1592. 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  1593. 'pay_json_request' => json_encode($item),
  1594. 'pay_json_response' => $item['pay_json_response'] ?? '[]',
  1595. 'pay_remark' => $item['order_remark'] ?? '',
  1596. 'pay_addtimes' => time(),
  1597. ];
  1598. PayDetail::insert($data);
  1599. }
  1600. } else {
  1601. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1602. $payPrepayid = $params['pay_category'];
  1603. } else if ($params['pay_category'] == 'OFFLINE') {
  1604. $payPrepayid = 'OFFLINE';
  1605. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1606. $payPrepayid = 'OFFLINE_ALIPAY';
  1607. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1608. $payPrepayid = 'OFFLINE_WXPAY';
  1609. } else if ($params['pay_category'] == 'MONEY') {
  1610. $payPrepayid = 'MONEY';
  1611. } else if ($params['pay_category'] == 'CARD') {
  1612. $payPrepayid = $params['card_id'];
  1613. } else {
  1614. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  1615. }
  1616. $data = [
  1617. 'join_pay_member_id' => $params['join_order_member_id'],
  1618. 'join_pay_order_id' => $params['orderGroupId'],
  1619. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  1620. 'pay_category' => $goods['goods_classify'],
  1621. 'pay_amount' => $amountPay,
  1622. 'pay_prepayid' => $payPrepayid,
  1623. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1624. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  1625. 'pay_json_request' => json_encode($params),
  1626. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  1627. 'pay_remark' => $params['order_remark'] ?? '',
  1628. 'pay_addtimes' => time(),
  1629. ];
  1630. PayDetail::insert($data);
  1631. }
  1632. } catch (\Exception $e) {
  1633. dump($e->getMessage());
  1634. throw new BusinessException('创建支付记录失败');
  1635. }
  1636. }
  1637. /**
  1638. * @Desc 入配送记录
  1639. * @Author Gorden
  1640. * @Date 2024/9/23 10:45
  1641. *
  1642. * @param $params
  1643. * @return void
  1644. * @throws BusinessException
  1645. */
  1646. public function insertExpressOne($params, $orderId)
  1647. {
  1648. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  1649. $params['order_express_type'] = '配送';
  1650. // 入配送
  1651. $this->saveExpress($params, $orderId);
  1652. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  1653. $params['order_express_type'] = '自提';
  1654. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  1655. if (!$premises) {
  1656. throw new BusinessException('自提门店不存在');
  1657. }
  1658. $params['order_express_city'] = $premises->dept_city;
  1659. $params['order_express_address'] = $premises->dept_address;
  1660. $params['order_express_telephone'] = $premises->dept_telephone;
  1661. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  1662. $this->saveExpress($params, $orderId);
  1663. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  1664. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  1665. $params['order_express_type'] = '到店';
  1666. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  1667. $params['order_express_type'] = '堂食';
  1668. }
  1669. if (!$premises) {
  1670. throw new BusinessException('门店不存在');
  1671. }
  1672. $params['order_express_city'] = $premises->dept_city;
  1673. $params['order_express_address'] = $premises->dept_address;
  1674. $params['order_express_telephone'] = $premises->dept_telephone;
  1675. $this->saveExpress($params, $orderId);
  1676. }
  1677. }
  1678. private function discountRecord($orderDiscountJson, $params)
  1679. {
  1680. $json = [];
  1681. if (!empty($orderDiscountJson)) {
  1682. $json = json_decode($orderDiscountJson, true);
  1683. }
  1684. try {
  1685. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  1686. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  1687. throw new BusinessException("抹零后实际支付金额错误");
  1688. }
  1689. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1690. $couponClassifyDesc = $couponClassify = '抹零';
  1691. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  1692. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  1693. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  1694. }
  1695. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  1696. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  1697. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  1698. throw new BusinessException("折扣后实际支付金额错误");
  1699. }
  1700. $couponClassify = '折扣';
  1701. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  1702. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1703. } else {
  1704. return $json;
  1705. }
  1706. $json[date('Y-m-d H:i:s')] = [
  1707. 'coupon_id' => $params['coupon_id'] ?? null,
  1708. 'coupon_value' => $params['order_discount_amount'] ?? '',
  1709. 'coupon_classify' => $couponClassify,
  1710. 'coupon_detail_id' => [$couponClassifyDesc],
  1711. 'coupon_classify_en' => $params['preferential']
  1712. ];
  1713. return $json;
  1714. } catch (BusinessException $e) {
  1715. throw new BusinessException($e->getMessage());
  1716. } catch (\Exception $e) {
  1717. dump($e->getMessage());
  1718. throw new BusinessException("优惠数据错误");
  1719. }
  1720. }
  1721. /**
  1722. * @Desc 修改优惠券状态
  1723. * @Author Gorden
  1724. * @Date 2024/9/19 9:03
  1725. *
  1726. * @param $coupon
  1727. * @param $status
  1728. * @return void
  1729. */
  1730. private function changeOrderCouponStatus($coupon, $status)
  1731. {
  1732. if (!empty($coupon) && is_array($coupon)) {
  1733. $updateData['coupon_detail_status'] = $status;
  1734. if ($status == 'ACTIVED' || $status == 'WAITING') {
  1735. $updateData['coupon_detail_used_datetime'] = '';
  1736. } elseif ($status == 'USED') {
  1737. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  1738. }
  1739. foreach ($coupon as $item) {
  1740. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  1741. foreach ($item['coupon_detail_id'] as $detailId) {
  1742. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  1743. ->where('coupon_detail_id', $detailId)->update($updateData);
  1744. }
  1745. }
  1746. }
  1747. }
  1748. }
  1749. }